Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: limit attachment storage per workspace (MUL-9489) (#11044)
Multica Eve0d9e4c24b2f6
diff --git a/apps/mobile/app/(app)/[workspace]/more/settings/profile.tsx b/apps/mobile/app/(app)/[workspace]/more/settings/profile.tsxindex ebc280242d..ff6df01a1a 100644--- a/apps/mobile/app/(app)/[workspace]/more/settings/profile.tsx+++ b/apps/mobile/app/(app)/[workspace]/more/settings/profile.tsx@@ -29,6 +29,7 @@ import { useAuthStore } from "@/data/auth-store";import { api } from "@/data/api";import type { FileAsset } from "@/data/api";import { useT } from "@/lib/i18n";+import { isStorageLimitReached } from "@/lib/upload-error";const MAX_AVATAR_BYTES = 5 * 1024 * 1024; // 5 MB — matches what's reasonable on cellular.@@ -141,6 +142,13 @@ export default function ProfileSettingsScreen() {const updated = await api.updateMe({ avatar_url: attachment.url });setUser(updated);} catch (err) {+ if (isStorageLimitReached(err)) {+ Alert.alert(+ t("editor:upload.storage_full_title"),+ t("editor:upload.storage_full_message"),+ );+ return;+ }Alert.alert(t("avatar.upload_failed"),err instanceof Errordiff --git a/apps/mobile/components/composer/message-composer.tsx b/apps/mobile/components/composer/message-composer.tsxindex 21ee5fe2e9..92433c6982 100644--- a/apps/mobile/components/composer/message-composer.tsx+++ b/apps/mobile/components/composer/message-composer.tsx@@ -70,6 +70,7 @@ import {type MentionChip,} from "@/components/issue/composer-attachment-row";import { useT } from "@/lib/i18n";+import { isStorageLimitReached } from "@/lib/upload-error";export interface MessageComposerReplyTarget {actorName: string;@@ -353,8 +354,11 @@ export function MessageComposer({),);} catch (err) {- const message =- err instanceof Error ? err.message : t("common:states.error");+ const message = isStorageLimitReached(err)+ ? t("editor:upload.storage_full_title")+ : err instanceof Error+ ? err.message+ : t("common:states.error");setAttachments((prev) =>prev.map((it) =>it.localId === localIddiff --git a/apps/mobile/components/editor/use-file-attach.ts b/apps/mobile/components/editor/use-file-attach.tsindex d991e7df3e..740a8ce300 100644--- a/apps/mobile/components/editor/use-file-attach.ts+++ b/apps/mobile/components/editor/use-file-attach.ts@@ -18,6 +18,7 @@*/import { useCallback, useState } from "react";import { Alert } from "react-native";+import { isStorageLimitReached } from "@/lib/upload-error";import * as ImagePicker from "expo-image-picker";import * as DocumentPicker from "expo-document-picker";import { api, MAX_FILE_SIZE, type FileAsset } from "@/data/api";@@ -68,6 +69,10 @@ export function useFileAttach() {filename: attachment.filename,};} catch (err) {+ if (isStorageLimitReached(err)) {+ Alert.alert(t("upload.storage_full_title"), t("upload.storage_full_message"));+ return null;+ }Alert.alert(t("upload.failed"),err instanceof Error ? err.message : t("upload.error"),diff --git a/apps/mobile/lib/upload-error.test.ts b/apps/mobile/lib/upload-error.test.tsnew file mode 100644index 0000000000..332ce789f9--- /dev/null+++ b/apps/mobile/lib/upload-error.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from "vitest";+import { isStorageLimitReached } from "./upload-error";++// The shape of `ApiError` in data/api.ts, which pulls in native modules.+function apiError(status: number, body: unknown) {+ return Object.assign(new Error("refused"), { status, body });+}++describe("isStorageLimitReached", () => {+ it("recognises the storage refusal", () => {+ expect(isStorageLimitReached(apiError(403, { code: "storage_limit_reached", used_bytes: 1 }))).toBe(true);+ });++ it("ignores other failures", () => {+ expect(isStorageLimitReached(apiError(413, { code: "storage_limit_reached" }))).toBe(false);+ expect(isStorageLimitReached(apiError(403, { code: "feature_locked" }))).toBe(false);+ expect(isStorageLimitReached(new Error("storage_limit_reached"))).toBe(false);+ expect(isStorageLimitReached(null)).toBe(false);+ });+});diff --git a/apps/mobile/lib/upload-error.ts b/apps/mobile/lib/upload-error.tsnew file mode 100644index 0000000000..8c9c06419b--- /dev/null+++ b/apps/mobile/lib/upload-error.ts@@ -0,0 +1,19 @@+/**+ * Upload refusals the server reports with a machine-readable code. Mirrors+ * `storageLimitReachedFromError` in `packages/core/billing/storage-limit.ts`+ * (MUL-9489): a full workspace refuses new uploads with+ * `403 storage_limit_reached`. Mobile shows a localized message for it and,+ * unlike web/desktop, offers no upgrade action.+ */+export const STORAGE_LIMIT_REACHED_CODE = "storage_limit_reached";++export function isStorageLimitReached(error: unknown): boolean {+ if (typeof error !== "object" || error === null) return false;+ const { status, body } = error as { status?: unknown; body?: unknown };+ return (+ status === 403 &&+ typeof body === "object" &&+ body !== null &&+ (body as { code?: unknown }).code === STORAGE_LIMIT_REACHED_CODE+ );+}diff --git a/apps/mobile/locales/en/editor.json b/apps/mobile/locales/en/editor.jsonindex 47e7458836..dc9071e266 100644--- a/apps/mobile/locales/en/editor.json+++ b/apps/mobile/locales/en/editor.json@@ -16,6 +16,8 @@"file_too_large_title": "File too large","file_too_large_message": "Files must be smaller than 100 MB.","failed": "Upload failed",- "error": "Unknown error"+ "error": "Unknown error",+ "storage_full_title": "Attachment storage is full",+ "storage_full_message": "This file wasn't uploaded. Existing attachments aren't affected. Ask an admin to upgrade the plan, or delete attachments you no longer need."}}diff --git a/apps/mobile/locales/zh-Hans/editor.json b/apps/mobile/locales/zh-Hans/editor.jsonindex f36973ecd8..0b0a1ed38c 100644--- a/apps/mobile/locales/zh-Hans/editor.json+++ b/apps/mobile/locales/zh-Hans/editor.json@@ -16,7 +16,9 @@"file_too_large_title": "文件过大","file_too_large_message": "文件必须小于 100 MB。","failed": "上传失败",- "error": "未知错误"+ "error": "未知错误",+ "storage_full_title": "附件存储已满",+ "storage_full_message": "这个文件没有上传,已有附件不受影响。请联系管理员升级套餐,或删除不需要的附件。"},"a11y.mention_someone": "提及某人"}diff --git a/apps/mobile/locales/zh-Hant/editor.json b/apps/mobile/locales/zh-Hant/editor.jsonindex d0acdba39a..a0049cc5d5 100644--- a/apps/mobile/locales/zh-Hant/editor.json+++ b/apps/mobile/locales/zh-Hant/editor.json@@ -16,7 +16,9 @@"file_too_large_title": "檔案過大","file_too_large_message": "檔案必須小於 100 MB。","failed": "上傳失敗",- "error": "未知錯誤"+ "error": "未知錯誤",+ "storage_full_title": "附件儲存空間已滿",+ "storage_full_message": "這個檔案沒有上傳,既有附件不受影響。請聯絡管理員升級套餐,或刪除不需要的附件。"},"a11y.mention_someone": "提及某人"}diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 06aa71e2b2..a98934835d 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -2289,6 +2289,32 @@ describe("ApiClient", () => {).rejects.toMatchObject({ name: "AbortError" });});+ it("rejects a refused upload with an ApiError carrying the body's code (MUL-9489)", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ code: "storage_limit_reached",+ error: "This workspace has reached its attachment storage limit.",+ used_bytes: 900,+ limit_bytes: 1000,+ }),+ { status: 403, headers: { "Content-Type": "application/json" } },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const client = new ApiClient("https://api.example.test");+ const file = new File(["hi"], "hi.png", { type: "image/png" });+ const err = await client.uploadFile(file).catch((e: unknown) => e);++ expect(err).toBeInstanceOf(ApiError);+ expect(err).toMatchObject({+ status: 403,+ message: "This workspace has reached its attachment storage limit.",+ body: { code: "storage_limit_reached", used_bytes: 900, limit_bytes: 1000 },+ });+ });+it("sendChatMessage serialises attachment_ids onto the JSON body when present", async () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ message_id: "m1", task_id: "t1", created_at: "2026-08-01T00:00:00Z" }), {diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex c124ffbf59..f83ea1b75d 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -290,6 +290,7 @@ import type {WorkspaceSubscriptionPrices,WorkspaceFeatures,MemberLimit,+ StorageUsage,CreateWorkspaceSubscriptionCheckoutRequest,CreateWorkspaceSubscriptionCheckoutResponse,WorkspaceSubscriptionSeatReconcileResult,@@ -455,6 +456,7 @@ import {WorkspaceSubscriptionPricesSchema,WorkspaceFeaturesSchema,MemberLimitSchema,+ StorageUsageSchema,CreateWorkspaceSubscriptionCheckoutResponseSchema,WorkspaceSubscriptionSeatReconcileResultSchema,WorkspaceSeatPurchasePreviewSchema,@@ -2705,6 +2707,18 @@ export class ApiClient {);}+ // The plan's attachment storage limit (MUL-9489). A response that cannot+ // be read falls back to no limit: the server still checks every upload.+ async getStorageUsage(workspaceId: string): Promise<StorageUsage> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/storage-usage`);+ return parseWithFallback<StorageUsage>(+ raw,+ StorageUsageSchema,+ { action: "off", usedBytes: null, limitBytes: null, reached: null },+ { endpoint: "GET /api/workspaces/:id/storage-usage" },+ );+ }+async getWorkspaceSubscriptionPrices(): Promise<WorkspaceSubscriptionPrices | null> {const raw = await this.fetch<unknown>("/api/cloud-subscriptions/prices");return parseWithFallback<WorkspaceSubscriptionPrices | null>(@@ -4398,9 +4412,11 @@ export class ApiClient {if (!res.ok) {if (res.status === 401) this.handleUnauthorized(credentialUsed);- const message = await this.parseErrorMessage(res, `Upload failed: ${res.status}`);+ // An ApiError, so callers can branch on the body's `code` (for example+ // storage_limit_reached) instead of the message.+ const { message, body } = await this.parseErrorBody(res, `Upload failed: ${res.status}`);this.logger.error(`← ${res.status} /api/upload-file`, { rid, duration: `${Date.now() - start}ms`, error: message });- throw new Error(message);+ throw new ApiError(message, res.status, res.statusText, body);}this.logger.info(`← ${res.status} /api/upload-file`, { rid, duration: `${Date.now() - start}ms` });diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex 27c1c894b1..c12449e4d6 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -1635,6 +1635,32 @@ describe("workspace subscription contract", () => {expect(summary?.trial).toBeNull();});+ it("reads the storage limit when Cloud sends one, and nothing when it is missing or malformed (MUL-9489)", async () => {+ const client = new ApiClient("https://api.example.test");+ const read = async (storage: unknown) => {+ stubFetchJson({+ entitlement: { ...entitlement, limits: { ...entitlement.limits, ...(storage === undefined ? {} : { storage_bytes: storage }) } },+ billing_interval: null,+ human_members: 3,+ seat_capacity: null,+ cancel_at_period_end: false,+ grace_until: null,+ has_stripe_customer: false,+ available_actions: { checkout: true, portal: false, purchase_seats: false, change_plan: false },+ });+ return (await client.getWorkspaceSubscriptionSummary())?.entitlement;+ };++ expect((await read({ mode: "limited", limit: 30_000_000_000 }))?.limits.storageBytes).toEqual({+ mode: "limited",+ limit: 30_000_000_000,+ });+ expect((await read(undefined))?.limits.storageBytes).toBeNull();+ const malformed = await read({ mode: "limited", limit: "lots" });+ expect(malformed?.limits.storageBytes).toBeNull();+ expect(malformed?.plan).toBe("pro");+ });+it("reads a plan change that still holds the subscription", async () => {stubFetchJson({entitlement,diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex b0ce9b6881..d4fe0a9846 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -39,6 +39,7 @@ import type {WorkspaceFeatureState,WorkspaceFeatures,MemberLimit,+ StorageUsage,WorkspaceSubscriptionSummary,WorkspaceSubscriptionPrice,WorkspaceSubscriptionPlanPrices,@@ -3637,6 +3638,9 @@ export const WorkspaceSubscriptionEntitlementsSchema = zlimits: z.object({autopilot_runs: WorkspaceEntitlementLimitSchema,+ // Optional: a Cloud without the storage limit omits it, and a+ // malformed one must not fail the whole snapshot.+ storage_bytes: WorkspaceEntitlementLimitSchema.nullable().optional().catch(null),}).loose(),current_period_end: z.string().nullable().optional(),@@ -3652,6 +3656,7 @@ export const WorkspaceSubscriptionEntitlementsSchema = zseats: value.seats,limits: {autopilotRuns: value.limits.autopilot_runs,+ storageBytes: value.limits.storage_bytes ?? null,},currentPeriodEnd: value.current_period_end ?? null,snapshotExpiresAt: value.snapshot_expires_at ?? null,@@ -3932,6 +3937,30 @@ export const MemberLimitSchema = z},);+// Storage usage that cannot be read, or an action from a newer server, reads+// as off: the server still checks every upload.+export const StorageUsageSchema = z+ .object({+ action: z.enum(["off", "observe", "enforce"]).catch("off"),+ used_bytes: z.number().int().nonnegative().nullable().catch(null).default(null),+ limit_bytes: z.number().int().nonnegative().nullable().catch(null).default(null),+ reached: z.boolean().nullable().catch(null).default(null),+ })+ .loose()+ .transform(+ (value): StorageUsage =>+ value.action === "off" || value.limit_bytes === null+ ? { action: "off", usedBytes: null, limitBytes: null, reached: null }+ : {+ action: value.action,+ // Missing when the server could not read usage in time.+ usedBytes: value.used_bytes,+ limitBytes: value.limit_bytes,+ reached:+ value.action === "enforce" && value.used_bytes !== null ? (value.reached ?? false) : null,+ },+ );+export const CreateWorkspaceSubscriptionCheckoutResponseSchema = z.object({request_id: z.string(),diff --git a/packages/core/billing/index.ts b/packages/core/billing/index.tsindex c554bfde51..6c8dd81639 100644--- a/packages/core/billing/index.ts+++ b/packages/core/billing/index.ts@@ -7,3 +7,4 @@ export * from "./paid-features";export * from "./trial";export * from "./trial-notice-store";export * from "./member-limit";+export * from "./storage-limit";diff --git a/packages/core/billing/storage-limit.test.ts b/packages/core/billing/storage-limit.test.tsnew file mode 100644index 0000000000..5f8d28f4bc--- /dev/null+++ b/packages/core/billing/storage-limit.test.ts@@ -0,0 +1,142 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";++import { ApiError } from "../api";+import { StorageUsageSchema } from "../api/schemas";+import type { StorageUsage } from "../types";+import {+ formatStorageBytes,+ resolveStorageRow,+ storageLimitReachedFromError,+ storageUsageProgress,+} from "./storage-limit";++const OFF: StorageUsage = { action: "off", usedBytes: null, limitBytes: null, reached: null };++describe("StorageUsageSchema", () => {+ it("reads an enforced limit with its figures", () => {+ expect(+ StorageUsageSchema.parse({ action: "enforce", used_bytes: 1_000_000_000, limit_bytes: 1_000_000_000, reached: true }),+ ).toEqual({ action: "enforce", usedBytes: 1_000_000_000, limitBytes: 1_000_000_000, reached: true });+ });++ it("never reports an observed limit as reached", () => {+ expect(StorageUsageSchema.parse({ action: "observe", used_bytes: 5, limit_bytes: 1, reached: true })).toEqual({+ action: "observe",+ usedBytes: 5,+ limitBytes: 1,+ reached: null,+ });+ });++ it("reads off, an unknown action, or a limit without a value as no limit", () => {+ expect(StorageUsageSchema.parse({ action: "off" })).toEqual(OFF);+ expect(StorageUsageSchema.parse({ action: "block", limit_bytes: 5 })).toEqual(OFF);+ expect(StorageUsageSchema.parse({ action: "enforce", limit_bytes: "5" })).toEqual(OFF);+ });++ it("keeps the limit and leaves usage unknown when the server could not read it", () => {+ expect(StorageUsageSchema.parse({ action: "enforce", limit_bytes: 10 })).toEqual({+ action: "enforce",+ usedBytes: null,+ limitBytes: 10,+ reached: null,+ });+ });+});++describe("storageLimitReachedFromError", () => {+ const refusal = (body: unknown, status = 403) => new ApiError("refused", status, "Forbidden", body);++ it("reads the figures of a storage refusal", () => {+ expect(+ storageLimitReachedFromError(refusal({ code: "storage_limit_reached", used_bytes: 900, limit_bytes: 1000 })),+ ).toEqual({ usedBytes: 900, limitBytes: 1000 });+ });++ it("keeps a refusal whose figures are missing or malformed", () => {+ expect(storageLimitReachedFromError(refusal({ code: "storage_limit_reached", used_bytes: "900" }))).toEqual({+ usedBytes: null,+ limitBytes: null,+ });+ });++ it("ignores every other failure", () => {+ expect(storageLimitReachedFromError(refusal({ code: "feature_locked" }))).toBeNull();+ expect(storageLimitReachedFromError(refusal({ code: "storage_limit_reached" }, 413))).toBeNull();+ expect(storageLimitReachedFromError(new Error("storage_limit_reached"))).toBeNull();+ expect(storageLimitReachedFromError(refusal(undefined))).toBeNull();+ });+});++describe("formatStorageBytes", () => {+ it("uses decimal units, as plans are sold", () => {+ expect(formatStorageBytes(1_000_000_000, "en")).toBe("1 GB");+ expect(formatStorageBytes(23_400_000_000, "en")).toBe("23.4 GB");+ expect(formatStorageBytes(120_000_000_000, "en")).toBe("120 GB");+ expect(formatStorageBytes(48_000_000, "en")).toBe("48 MB");+ expect(formatStorageBytes(999, "en")).toBe("999 B");+ expect(formatStorageBytes(2_500_000_000_000, "en")).toBe("2.5 TB");+ // Rounding up to the next unit names that unit.+ expect(formatStorageBytes(999_990_000, "en")).toBe("1 GB");+ expect(formatStorageBytes(999_940_000, "en")).toBe("999.9 MB");+ });+});++describe("storageUsageProgress", () => {+ it("is the share of the limit in use, capped at 100", () => {+ expect(storageUsageProgress(250, 1000)).toBe(25);+ expect(storageUsageProgress(2000, 1000)).toBe(100);+ expect(storageUsageProgress(0, 0)).toBe(100);+ });+});++describe("resolveStorageRow", () => {+ const usage = (over: Partial<StorageUsage>): StorageUsage => ({+ action: "enforce",+ usedBytes: 900,+ limitBytes: 1000,+ reached: false,+ ...over,+ });+ const plan = (limit: number) => ({ mode: "limited", limit });++ it("meters usage against the limit, and only an enforced limit is reached", () => {+ expect(resolveStorageRow(usage({}), false, null)).toEqual({+ kind: "metered",+ usedBytes: 900,+ limitBytes: 1000,+ reached: false,+ });+ expect(resolveStorageRow(usage({ usedBytes: 1000 }), false, null)).toMatchObject({ reached: true });+ expect(resolveStorageRow(usage({ action: "observe", usedBytes: 5000 }), false, null)).toMatchObject({+ reached: false,+ });+ });++ // Right after an upgrade the usage read can still carry the policy cached+ // before it; the entitlement has the new limit.+ it("takes the limit from the plan when the entitlement has one", () => {+ expect(resolveStorageRow(usage({ usedBytes: 1000 }), false, plan(100_000))).toEqual({+ kind: "metered",+ usedBytes: 1000,+ limitBytes: 100_000,+ reached: false,+ });+ });++ it("shows usage the server could not read, or a failed read, as unavailable", () => {+ expect(resolveStorageRow(usage({ usedBytes: null, reached: null }), false, null)).toEqual({+ kind: "unavailable",+ limitBytes: 1000,+ });+ expect(resolveStorageRow(undefined, true, plan(1000))).toEqual({ kind: "unavailable", limitBytes: 1000 });+ });++ it("shows nothing without a limit", () => {+ expect(resolveStorageRow(OFF, false, plan(1000))).toBeNull();+ expect(resolveStorageRow(undefined, false, plan(1000))).toBeNull();+ // A failed read with no plan limit says nothing about whether one applies.+ expect(resolveStorageRow(undefined, true, null)).toBeNull();+ });+});diff --git a/packages/core/billing/storage-limit.ts b/packages/core/billing/storage-limit.tsnew file mode 100644index 0000000000..76f208ddef--- /dev/null+++ b/packages/core/billing/storage-limit.ts@@ -0,0 +1,119 @@+import { queryOptions } from "@tanstack/react-query";+import { api, type ApiError } from "../api";+import type { StorageUsage } from "../types";++/**+ * Attachment storage limit (MUL-9489).+ *+ * A workspace may hold a limited number of attachment bytes, shared by every+ * member. When it is full the server refuses new uploads with+ * `403 storage_limit_reached`; attachments already stored stay readable. This+ * module reads the limit for Billing and turns a refusal into the facts the+ * upload notice shows.+ */+export const STORAGE_LIMIT_REACHED_CODE = "storage_limit_reached";++export const storageUsageKeys = {+ all: (wsId: string) => ["workspace-storage-usage", wsId] as const,+};++/** Refetched on focus: an upgrade happens outside this tab, in Stripe. */+export function storageUsageOptions(wsId: string) {+ return queryOptions({+ queryKey: storageUsageKeys.all(wsId),+ queryFn: () => api.getStorageUsage(wsId),+ enabled: wsId.length > 0,+ staleTime: 30 * 1000,+ refetchOnWindowFocus: true,+ });+}++/** What a refused upload reports: the workspace's bytes and its limit. */+export interface StorageLimitReached {+ usedBytes: number | null;+ limitBytes: number | null;+}++/**+ * The storage facts of a refused upload, or null when error is anything+ * else. The figures are null when an older or unexpected body omits them.+ */+export function storageLimitReachedFromError(error: unknown): StorageLimitReached | null {+ // Read structurally rather than with `instanceof ApiError`: the error can+ // cross module copies (the upload coordinator, test doubles of the API).+ if (typeof error !== "object" || error === null) return null;+ const { status, body } = error as Partial<Pick<ApiError, "status" | "body">>;+ if (status !== 403) return null;+ if (typeof body !== "object" || body === null) return null;+ const value = body as { code?: unknown; used_bytes?: unknown; limit_bytes?: unknown };+ if (value.code !== STORAGE_LIMIT_REACHED_CODE) return null;+ const bytes = (v: unknown) =>+ typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null;+ return { usedBytes: bytes(value.used_bytes), limitBytes: bytes(value.limit_bytes) };+}++const STORAGE_UNITS = ["B", "KB", "MB", "GB", "TB"] as const;++/**+ * Storage in decimal units, as plans are sold: 1 GB is 10^9 bytes. Whole+ * numbers drop the decimal ("1 GB"); others keep one ("23.4 GB").+ */+export function formatStorageBytes(bytes: number, locale?: string): string {+ let value = Math.max(0, bytes);+ let unit = 0;+ while (value >= 1000 && unit < STORAGE_UNITS.length - 1) {+ value /= 1000;+ unit++;+ }+ let rounded = Math.round(value * 10) / 10;+ // 999.99 MB rounds to 1000 MB; show it as 1 GB instead.+ if (rounded >= 1000 && unit < STORAGE_UNITS.length - 1) {+ rounded = Math.round(rounded / 100) / 10;+ unit++;+ }+ const formatted = new Intl.NumberFormat(locale, {+ maximumFractionDigits: Number.isInteger(rounded) ? 0 : 1,+ }).format(rounded);+ return `${formatted} ${STORAGE_UNITS[unit]}`;+}++/** The share of the limit in use, 0–100, for a progress bar. */+export function storageUsageProgress(usedBytes: number, limitBytes: number): number {+ if (limitBytes <= 0) return 100;+ return Math.min(100, (usedBytes / limitBytes) * 100);+}++/** The Billing row for attachment storage. */+export type StorageRow =+ | { kind: "metered"; usedBytes: number; limitBytes: number; reached: boolean }+ | { kind: "unavailable"; limitBytes: number | null };++/**+ * What Billing shows for attachment storage, or null when no limit applies.+ *+ * The limit comes from the entitlement snapshot when it has one: it is the+ * number Cloud just computed for the plan, so a page that has just upgraded+ * or added seats shows the new limit at once, while the usage read can still+ * carry a policy cached before the change. Usage that could not be read (a+ * failed request, or a sum the server gave up on) shows as unavailable.+ */+export function resolveStorageRow(+ usage: StorageUsage | undefined,+ usageFailed: boolean,+ entitlementLimit: { mode: string; limit: number | null } | null | undefined,+): StorageRow | null {+ const planLimit = entitlementLimit?.mode === "limited" ? entitlementLimit.limit : null;+ if (usageFailed || !usage) {+ return usageFailed && planLimit !== null ? { kind: "unavailable", limitBytes: planLimit } : null;+ }+ if (usage.action === "off" || usage.limitBytes === null) return null;+ const limitBytes = planLimit ?? usage.limitBytes;+ if (usage.usedBytes === null) return { kind: "unavailable", limitBytes };+ return {+ kind: "metered",+ usedBytes: usage.usedBytes,+ limitBytes,+ // Only an enforced limit is ever reached; observe never refuses.+ reached: usage.action === "enforce" && usage.usedBytes >= limitBytes,+ };+}diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.tsindex 5e878e891e..37cb8eb3a0 100644--- a/packages/core/types/billing.ts+++ b/packages/core/types/billing.ts@@ -217,6 +217,8 @@ export interface WorkspaceSubscriptionEntitlements {seats: number;limits: {autopilotRuns: WorkspaceEntitlementLimit;+ /** Attachment storage in bytes (MUL-9489); absent from older Cloud. */+ storageBytes?: WorkspaceEntitlementLimit | null;};currentPeriodEnd: string | null;snapshotExpiresAt: string | null;@@ -456,6 +458,20 @@ export interface WorkspaceFeatures {* also every self-hosted workspace; the counts are null then. Members and* pending invitations both take a slot; guests take none.*/+/**+ * The plan's attachment storage limit (MUL-9489). `off` means no limit+ * applies, which is also every self-hosted workspace; the figures are null+ * then. Bytes are counted across every attachment in the workspace.+ */+export interface StorageUsage {+ action: "off" | "observe" | "enforce";+ /** Null also while a limit applies, when the server could not read usage in time. */+ usedBytes: number | null;+ limitBytes: number | null;+ /** Set only under enforce: observe never refuses an upload. */+ reached: boolean | null;+}+export interface MemberLimit {action: "off" | "observe" | "enforce";limit: number | null;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 1aff01dd8a..0701b7e7c8 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -435,6 +435,7 @@ export type {WorkspaceFeatureState,WorkspaceFeatures,MemberLimit,+ StorageUsage,} 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 3608bf2715..069c936dff 100644--- a/packages/views/billing/index.ts+++ b/packages/views/billing/index.ts@@ -2,3 +2,9 @@ export { BillingReturnPage } from "./billing-return-page";export { PaidFeatureNotice, usePaidFeatureErrorMessage } from "./paid-feature-notice";export { TrialStatus } from "./trial-status";export { WorkspaceTrialNotices } from "./trial-notices";+export {+ StorageLimitNotice,+ storageLimitRefusal,+ useStorageLimitToast,+ type StorageLimitRefusal,+} from "./storage-limit-notice";diff --git a/packages/views/billing/storage-limit-notice.test.tsx b/packages/views/billing/storage-limit-notice.test.tsxnew file mode 100644index 0000000000..685c213682--- /dev/null+++ b/packages/views/billing/storage-limit-notice.test.tsx@@ -0,0 +1,190 @@+import { fireEvent, renderHook, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { ApiError } from "@multica/core/api";+import type { ReactNode } from "react";+import { I18nProvider } from "@multica/core/i18n/react";+import { getTestResources, renderWithI18n } from "../test/i18n";+import { StorageLimitNotice, storageLimitRefusal, useStorageLimitToast } from "./storage-limit-notice";++const h = vi.hoisted(() => ({+ workspace: { id: "ws-1", slug: "acme", name: "Acme Labs" } as { id: string; slug: string; name: string } | null,+ role: "owner" as "owner" | "admin" | "member",+ plan: "free" as string | undefined,+ push: vi.fn(),+ toastError: vi.fn(),+}));++vi.mock("@multica/core/paths", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/paths")>("@multica/core/paths");+ return {+ ...actual,+ useCurrentWorkspace: () => h.workspace,+ useWorkspaceSlug: () => h.workspace?.slug ?? null,+ };+});+vi.mock("@multica/core/auth", () => {+ const useAuthStore = (select: (state: { user: { id: string } }) => unknown) => select({ user: { id: "u1" } });+ useAuthStore.getState = () => ({ user: { id: "u1" } });+ return { useAuthStore };+});+vi.mock("@tanstack/react-query", async () => {+ const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query");+ return {+ ...actual,+ useQuery: (options: { queryKey: readonly unknown[]; enabled?: boolean }) => {+ const key = options.queryKey;+ if (options.enabled === false) return { data: undefined };+ if (key[0] === "workspaces" && key[2] === "members") {+ return { data: [{ user_id: "u1", role: h.role }] };+ }+ if (key[0] === "workspace-subscriptions" && key[2] === "summary") {+ return { data: h.plan ? { entitlement: { plan: h.plan } } : undefined };+ }+ return { data: undefined };+ },+ };+});+vi.mock("sonner", () => ({ toast: { error: h.toastError } }));+vi.mock("../navigation", () => ({+ useOptionalNavigation: () => ({ pathname: "/acme/issues", push: h.push }),+}));++const refusal = { filename: "design-v3.fig", usedBytes: 1_000_000_000, limitBytes: 1_000_000_000 };++function storageError() {+ return new ApiError("full", 403, "Forbidden", {+ code: "storage_limit_reached",+ used_bytes: 1_000_000_000,+ limit_bytes: 1_000_000_000,+ });+}++describe("StorageLimitNotice", () => {+ beforeEach(() => {+ h.workspace = { id: "ws-1", slug: "acme", name: "Acme Labs" };+ h.role = "owner";+ h.plan = "free";+ h.push.mockReset();+ h.toastError.mockReset();+ });++ it.each([+ ["free", "Upgrade to Pro", "/acme/settings?tab=billing&upgrade=pro"],+ ["pro", "Upgrade to Business", "/acme/settings?tab=billing&upgrade=business"],+ ["business", "Manage billing", "/acme/settings?tab=billing"],+ ])("offers a %s admin the next step for storage", (plan, label, href) => {+ h.plan = plan;+ renderWithI18n(<StorageLimitNotice refusal={refusal} onDismiss={() => {}} />);++ expect(screen.getByText("design-v3.fig wasn't uploaded")).toBeTruthy();+ expect(+ screen.getByText("Attachment storage is full (1 GB / 1 GB). Existing attachments aren't affected."),+ ).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: label }));+ expect(h.push).toHaveBeenCalledWith(href);+ });++ it("tells a member to ask an admin, with no upgrade button", () => {+ h.role = "member";+ renderWithI18n(<StorageLimitNotice refusal={refusal} onDismiss={() => {}} />);++ expect(+ screen.getByText(+ "Attachment storage is full. Ask an admin to upgrade the plan, or delete attachments you no longer need.",+ ),+ ).toBeTruthy();+ expect(screen.queryByRole("button", { name: /Upgrade|Manage billing|View plans/ })).toBeNull();+ });++ it("names a refused sub-issue copy instead of a file", () => {+ renderWithI18n(<StorageLimitNotice refusal={{ ...refusal, kind: "copy" }} onDismiss={() => {}} />);+ expect(screen.getByText("The sub-issue wasn't created: its source attachments couldn't be copied")).toBeTruthy();+ });++ it("dismisses", () => {+ const onDismiss = vi.fn();+ renderWithI18n(<StorageLimitNotice refusal={refusal} onDismiss={onDismiss} />);+ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));+ expect(onDismiss).toHaveBeenCalledTimes(1);+ });+});++describe("storageLimitRefusal", () => {+ it("is null for any other upload failure", () => {+ expect(storageLimitRefusal(new ApiError("too big", 413, "Too Large", {}), "a.png")).toBeNull();+ expect(storageLimitRefusal(storageError(), "a.png")).toEqual({+ filename: "a.png",+ usedBytes: 1_000_000_000,+ limitBytes: 1_000_000_000,+ });+ });+});++describe("useStorageLimitToast", () => {+ beforeEach(() => {+ h.toastError.mockReset();+ h.role = "owner";+ h.plan = "free";+ h.workspace = { id: "ws-1", slug: "acme", name: "Acme Labs" };+ });++ function seededClient() {+ const client = new QueryClient();+ client.setQueryData(["workspaces", "list"], [h.workspace]);+ client.setQueryData(["workspaces", "ws-1", "members"], [{ user_id: "u1", role: h.role }]);+ client.setQueryData(["workspace-subscriptions", "ws-1", "summary"], { entitlement: { plan: h.plan } });+ return client;+ }++ function wrap(client: QueryClient = new QueryClient()) {+ function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={client}>+ <I18nProvider locale="en" resources={getTestResources("en")}>+ {children}+ </I18nProvider>+ </QueryClientProvider>+ );+ }+ return Wrapper;+ }++ it("toasts a storage refusal with the admin's action and leaves other failures to the caller", async () => {+ const { result } = renderHook(() => useStorageLimitToast(), { wrapper: wrap(seededClient()) });+ expect(result.current(new Error("network"), "a.png")).toBe(false);++ expect(result.current(storageError(), "a.png")).toBe(true);+ await waitFor(() => expect(h.toastError).toHaveBeenCalledTimes(1));+ expect(h.toastError).toHaveBeenCalledWith(+ "a.png wasn't uploaded",+ expect.objectContaining({+ description: "Attachment storage is full (1 GB / 1 GB). Existing attachments aren't affected.",+ action: expect.objectContaining({ label: "Upgrade to Pro" }),+ }),+ );+ });++ it("gives a member the ask-an-admin copy without an action", async () => {+ h.role = "member";+ const { result } = renderHook(() => useStorageLimitToast(), { wrapper: wrap(seededClient()) });+ result.current(storageError(), "a.png");+ await waitFor(() => expect(h.toastError).toHaveBeenCalledTimes(1));+ expect(h.toastError).toHaveBeenCalledWith(+ "a.png wasn't uploaded",+ expect.objectContaining({+ description:+ "Attachment storage is full. Ask an admin to upgrade the plan, or delete attachments you no longer need.",+ action: undefined,+ }),+ );+ });++ it("reports a refusal outside a workspace with the member copy", async () => {+ h.workspace = null;+ const { result } = renderHook(() => useStorageLimitToast(), { wrapper: wrap() });+ expect(result.current(storageError(), "a.png")).toBe(true);+ await waitFor(() => expect(h.toastError).toHaveBeenCalledTimes(1));+ expect(h.toastError).toHaveBeenCalledWith("a.png wasn't uploaded", expect.objectContaining({ action: undefined }));+ });+});diff --git a/packages/views/billing/storage-limit-notice.tsx b/packages/views/billing/storage-limit-notice.tsxnew file mode 100644index 0000000000..3a4acfa182--- /dev/null+++ b/packages/views/billing/storage-limit-notice.tsx@@ -0,0 +1,209 @@+"use client";++import { useCallback } from "react";+import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { Paperclip, X } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import { cn } from "@multica/ui/lib/utils";+import { useAuthStore } from "@multica/core/auth";+import { memberListOptions, workspaceListOptions } from "@multica/core/workspace/queries";+import { paths, useCurrentWorkspace, useWorkspaceSlug } from "@multica/core/paths";+import {+ formatStorageBytes,+ storageLimitReachedFromError,+ workspaceSubscriptionSummaryOptions,+ type StorageLimitReached,+} from "@multica/core/billing";+import { useOptionalNavigation } from "../navigation";+import { useT } from "../i18n";++/** An upload the storage limit refused, as the notice shows it. */+export interface StorageLimitRefusal extends StorageLimitReached {+ filename: string;+ /** "copy" when a sub-issue's copy of its source attachments was refused. */+ kind?: "upload" | "copy";+}++/** The refusal behind error, or null when error is any other failure. */+export function storageLimitRefusal(error: unknown, filename: string): StorageLimitRefusal | null {+ const reached = storageLimitReachedFromError(error);+ return reached ? { ...reached, filename } : null;+}++type UpgradeKind = "upgrade_pro" | "upgrade_business" | "manage" | "view_plans";+type UpgradeAction = { kind: UpgradeKind; href: string };++/**+ * What an admin can do about a full workspace (MUL-9489). Storage grows with+ * seats, so a Business workspace adds seats in billing; a lower plan upgrades.+ * Members, and anyone outside a workspace, get no action: they ask an admin.+ */+function storageLimitAction(+ workspaceSlug: string | null,+ role: string | null,+ plan: string | undefined,+): UpgradeAction | null {+ if (!workspaceSlug || (role !== "owner" && role !== "admin")) return null;+ const billing = `${paths.workspace(workspaceSlug).settings()}?tab=billing`;+ switch (plan) {+ case "free":+ return { kind: "upgrade_pro", href: `${billing}&upgrade=pro` };+ case "pro":+ return { kind: "upgrade_business", href: `${billing}&upgrade=business` };+ case "business":+ return { kind: "manage", href: billing };+ default:+ return { kind: "view_plans", href: billing };+ }+}++function useStorageLimitCopy() {+ const { t, i18n } = useT("billing");+ const locale = i18n.language;+ return useCallback(+ (refusal: StorageLimitRefusal, action: UpgradeAction | null) => {+ const title =+ refusal.kind === "copy"+ ? t(($) => $.storage_limit.copy_title)+ : t(($) => $.storage_limit.title, { filename: refusal.filename });+ let body: string;+ if (!action) {+ body = t(($) => $.storage_limit.member_body);+ } else if (refusal.usedBytes !== null && refusal.limitBytes !== null) {+ body = t(($) => $.storage_limit.admin_body, {+ used: formatStorageBytes(refusal.usedBytes, locale),+ limit: formatStorageBytes(refusal.limitBytes, locale),+ });+ } else {+ body = t(($) => $.storage_limit.admin_body_no_figures);+ }+ const label = action+ ? {+ upgrade_pro: t(($) => $.workspace.actions.upgrade_to, { plan: t(($) => $.workspace.plan.pro) }),+ upgrade_business: t(($) => $.workspace.actions.upgrade_to, { plan: t(($) => $.workspace.plan.business) }),+ manage: t(($) => $.workspace.actions.manage),+ view_plans: t(($) => $.paid_feature.view_plans),+ }[action.kind]+ : null;+ return { title, body, label };+ },+ [locale, t],+ );+}++/** The current user's admin action, from live queries. */+function useStorageLimitAction(): UpgradeAction | null {+ const workspace = useCurrentWorkspace();+ const wsId = workspace?.id ?? "";+ const userId = useAuthStore((state) => state.user?.id ?? null);+ const members = useQuery({ ...memberListOptions(wsId), enabled: wsId.length > 0 });+ const role = members.data?.find((m) => m.user_id === userId)?.role ?? null;+ const isAdmin = role === "owner" || role === "admin";+ const summary = useQuery({ ...workspaceSubscriptionSummaryOptions(wsId), enabled: isAdmin });+ return storageLimitAction(workspace?.slug ?? null, role, summary.data?.entitlement.plan);+}++/**+ * The card a composer shows under its editor when the storage limit refused+ * a file. The file was not uploaded; everything already attached stays.+ */+export function StorageLimitNotice({+ refusal,+ onDismiss,+ className,+}: {+ refusal: StorageLimitRefusal;+ onDismiss: () => void;+ className?: string;+}) {+ const { t } = useT("billing");+ const navigation = useOptionalNavigation();+ const describe = useStorageLimitCopy();+ const action = useStorageLimitAction();+ const { title, body, label } = describe(refusal, action);+ return (+ <div+ role="alert"+ className={cn(+ "flex items-center gap-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2",+ className,+ )}+ >+ <Paperclip className="size-4 shrink-0 text-muted-foreground" aria-hidden />+ <div className="min-w-0 flex-1">+ <p className="truncate text-body font-medium text-foreground">{title}</p>+ <p className="text-caption text-muted-foreground">{body}</p>+ </div>+ {action && label && navigation ? (+ <Button type="button" size="sm" onClick={() => navigation.push(action.href)}>+ {label}+ </Button>+ ) : null}+ <Button+ type="button"+ size="icon-xs"+ variant="ghost"+ aria-label={t(($) => $.storage_limit.dismiss)}+ className="text-muted-foreground"+ onClick={onDismiss}+ >+ <X />+ </Button>+ </div>+ );+}++/**+ * For uploads outside an editor (avatars, feedback, docs): returns a handler+ * that toasts the same notice and reports true for a storage refusal, false+ * for anything else so the caller shows its usual failure.+ *+ * It subscribes to no query, so a host pays nothing until a refusal happens;+ * the caller's role and plan are looked up then, from the cache when it has+ * them.+ */+export function useStorageLimitToast() {+ const client = useQueryClient();+ const slug = useWorkspaceSlug();+ const navigation = useOptionalNavigation();+ const describe = useStorageLimitCopy();+ return useCallback(+ (error: unknown, filename: string): boolean => {+ const refusal = storageLimitRefusal(error, filename);+ if (!refusal) return false;+ void resolveAction(client, slug).then((action) => {+ const { title, body, label } = describe(refusal, action);+ toast.error(title, {+ description: body,+ action:+ action && label && navigation+ ? { label, onClick: () => navigation.push(action.href) }+ : undefined,+ });+ });+ return true;+ },+ [client, describe, navigation, slug],+ );+}++async function resolveAction(client: QueryClient, slug: string | null): Promise<UpgradeAction | null> {+ if (!slug) return null;+ try {+ const workspace = client+ .getQueryData(workspaceListOptions().queryKey)+ ?.find((w) => w.slug === slug);+ const userId = useAuthStore.getState?.()?.user?.id ?? null;+ if (!workspace || !userId) return null;+ const members = await client.ensureQueryData(memberListOptions(workspace.id));+ const role = members.find((m) => m.user_id === userId)?.role ?? null;+ if (role !== "owner" && role !== "admin") return null;+ const summary = await client+ .ensureQueryData(workspaceSubscriptionSummaryOptions(workspace.id))+ .catch(() => undefined);+ return storageLimitAction(slug, role, summary?.entitlement.plan);+ } catch {+ return null;+ }+}diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsxindex fa86c56e30..9721ef0016 100644--- a/packages/views/chat/components/chat-input.tsx+++ b/packages/views/chat/components/chat-input.tsx@@ -32,6 +32,7 @@ import { escapeMarkdownLabel } from "../../editor/utils/escape-markdown-label";import type { Attachment, Project } from "@multica/core/types";import { ProjectPicker } from "../../projects/components/project-picker";import { ClearablePillButton } from "../../common/pill-button";+import { StorageLimitNotice } from "../../billing/storage-limit-notice";import { useT } from "../../i18n";import {useComposerVoice,@@ -366,6 +367,8 @@ export function ChatInput({attachments: draftAttachments,handleUpload,gate,+ storageRefusal,+ dismissStorageRefusal,} = useCoordinatedUploads(uploadBinding, storeUploads, {}, uploadGate, editorRef, {resolveUploadTarget: () => makeUploadBinding(editorDraftKeyRef.current),liveRegistryKey: `chat:${loadedDraftKey}`,@@ -895,6 +898,13 @@ export function ChatInput({<VoiceHud voice={voice} /><VoiceSetupDialog voice={voice} /><VoiceErrorRow voice={voice} className="mx-2 mb-1" />+ {storageRefusal && (+ <StorageLimitNotice+ refusal={storageRefusal}+ onDismiss={dismissStorageRefusal}+ className="mx-2 mb-1"+ />+ )}{voice.showStrip && (<div className="absolute inset-x-1.5 bottom-1 flex items-center"><VoiceStrip voice={voice} />diff --git a/packages/views/common/avatar-upload-control.test.tsx b/packages/views/common/avatar-upload-control.test.tsxindex 4a4fda4bf7..016f206d36 100644--- a/packages/views/common/avatar-upload-control.test.tsx+++ b/packages/views/common/avatar-upload-control.test.tsx@@ -64,6 +64,9 @@ vi.mock("./text-avatar-dialog", () => ({) : null,}));+// The storage-limit toast has its own tests; here every failure is ordinary.+vi.mock("../billing/storage-limit-notice", () => ({ useStorageLimitToast: () => () => false }));+import { AvatarUploadControl } from "./avatar-upload-control";afterEach(() => {diff --git a/packages/views/common/avatar-upload-control.tsx b/packages/views/common/avatar-upload-control.tsxindex e9495b858f..777f17c1f5 100644--- a/packages/views/common/avatar-upload-control.tsx+++ b/packages/views/common/avatar-upload-control.tsx@@ -20,6 +20,7 @@ import { Separator } from "@multica/ui/components/ui/separator";import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";import { DeferredTooltip } from "@multica/ui/components/common/deferred-tooltip";import { cn } from "@multica/ui/lib/utils";+import { useStorageLimitToast } from "../billing/storage-limit-notice";import { useT } from "../i18n";import { AvatarCropDialog } from "./avatar-crop-dialog";import { TextAvatarDialog } from "./text-avatar-dialog";@@ -157,6 +158,7 @@ export function AvatarUploadControl({}: AvatarUploadControlProps) {const { t } = useT("common");const { upload } = useFileUpload(api);+ const toastStorageLimit = useStorageLimitToast();const fileInputRef = useRef<HTMLInputElement>(null);const uploadPendingRef = useRef(false);const [pickedFile, setPickedFile] = useState<File | null>(null);@@ -215,6 +217,7 @@ export function AvatarUploadControl({toast.success(t(($) => $.avatar_upload.updated));} catch (err) {// Only the upload above can land here — see persistedByCaller.+ if (toastStorageLimit(err, file.name)) return;toast.error(err instanceof Error ? err.message : t(($) => $.avatar_upload.failed),);diff --git a/packages/views/editor/use-coordinated-uploads.test.tsx b/packages/views/editor/use-coordinated-uploads.test.tsxindex 2f73433f99..83019b3885 100644--- a/packages/views/editor/use-coordinated-uploads.test.tsx+++ b/packages/views/editor/use-coordinated-uploads.test.tsx@@ -20,8 +20,12 @@ import {// The coordinator (MUL-5181 L2) is what actually performs the request; tests// drive an upload's outcome by controlling THAT promise.const mockApiUploadFile = vi.hoisted(() => vi.fn());-vi.mock("@multica/core/api", () => ({ api: { uploadFile: mockApiUploadFile } }));-vi.mock("sonner", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));+vi.mock("@multica/core/api", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/api")>("@multica/core/api");+ return { ApiError: actual.ApiError, api: { uploadFile: mockApiUploadFile } };+});+const mockToastError = vi.hoisted(() => vi.fn());+vi.mock("sonner", () => ({ toast: { error: mockToastError, success: vi.fn() } }));const TEST_RESOURCES = { en: { common: enCommon, editor: enEditor } };@@ -202,3 +206,80 @@ describe("useCoordinatedUploads paste-as-file recovery", () => {expect(state.uploads).toHaveLength(0);});});++/**+ * A file the attachment storage limit refused (MUL-9489) is reported by the+ * composer's notice, not the generic failure toast, and the next upload that+ * goes through clears it.+ */+describe("useCoordinatedUploads storage limit", () => {+ function RefusalHost({+ binding,+ expose,+ }: {+ binding: UploadDraftBinding;+ expose: (api: ReturnType<typeof useCoordinatedUploads>) => void;+ }) {+ const editorRef = useRef<ContentEditorRef | null>(null);+ const uploads = useCoordinatedUploads(binding, [], {}, inertGate, editorRef);+ useEffect(() => {+ expose(uploads);+ });+ return null;+ }++ it("holds the refusal for the notice instead of toasting", async () => {+ const { ApiError } = await vi.importActual<typeof import("@multica/core/api")>("@multica/core/api");+ const { binding, state } = makeRecordingBinding("probe:storage");+ let latest!: ReturnType<typeof useCoordinatedUploads>;+ mockToastError.mockReset();+ mockApiUploadFile.mockRejectedValueOnce(+ new ApiError("full", 403, "Forbidden", {+ code: "storage_limit_reached",+ used_bytes: 1_000_000_000,+ limit_bytes: 1_000_000_000,+ }),+ );++ render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <RefusalHost binding={binding} expose={(u) => { latest = u; }} />+ </I18nProvider>,+ );+ await act(async () => {+ await latest.handleUpload(new File(["x"], "design-v3.fig"));+ });++ expect(latest.storageRefusal).toEqual({+ filename: "design-v3.fig",+ usedBytes: 1_000_000_000,+ limitBytes: 1_000_000_000,+ });+ expect(mockToastError).not.toHaveBeenCalled();+ expect(state.uploads).toHaveLength(0);++ mockApiUploadFile.mockResolvedValueOnce({ id: "att-1", url: "https://cdn/x", filename: "ok.png" } as Attachment);+ await act(async () => {+ await latest.handleUpload(new File(["x"], "ok.png"));+ });+ expect(latest.storageRefusal).toBeNull();+ });++ it("still toasts every other failure", async () => {+ const { binding } = makeRecordingBinding("probe:other");+ let latest!: ReturnType<typeof useCoordinatedUploads>;+ mockToastError.mockReset();+ mockApiUploadFile.mockRejectedValueOnce(new Error("network down"));++ render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <RefusalHost binding={binding} expose={(u) => { latest = u; }} />+ </I18nProvider>,+ );+ await act(async () => {+ await latest.handleUpload(new File(["x"], "a.png"));+ });+ expect(latest.storageRefusal).toBeNull();+ expect(mockToastError).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/views/editor/use-coordinated-uploads.ts b/packages/views/editor/use-coordinated-uploads.tsindex 750fe439cd..6850b890c8 100644--- a/packages/views/editor/use-coordinated-uploads.ts+++ b/packages/views/editor/use-coordinated-uploads.ts@@ -57,6 +57,7 @@ import {} from "@multica/core/hooks/use-file-upload";import { MAX_FILE_SIZE } from "@multica/core/constants/upload";import { useT } from "../i18n";+import { storageLimitRefusal, type StorageLimitRefusal } from "../billing/storage-limit-notice";import type { UploadGate } from "./use-upload-gate";import type { ContentEditorRef } from "./content-editor";import { pastedTextSource } from "./extensions/file-upload";@@ -219,6 +220,13 @@ export interface CoordinatedUploads {handleUpload: (file: File, uploadId?: string) => Promise<UploadResult | null>;/** Drop a placeholder (dismiss a failure / interrupted). */removeUpload: (clientUploadId: string) => void;+ /**+ * The last file the attachment storage limit refused (MUL-9489), shown by+ * the composer as a StorageLimitNotice under its editor. Cleared by the+ * next upload that succeeds, or by dismissStorageRefusal.+ */+ storageRefusal: StorageLimitRefusal | null;+ dismissStorageRefusal: () => void;/*** The submit gate for this composer. Combines the editor gate (this mount's* in-document uploads) with the coordinator-owned placeholders in the draft:@@ -265,6 +273,7 @@ export function useCoordinatedUploads(): CoordinatedUploads {const { t } = useT("editor");const [localUploads, setLocalUploads] = useState<DraftUpload[]>([]);+ const [storageRefusal, setStorageRefusal] = useState<StorageLimitRefusal | null>(null);// Latest-value ref: handleUpload snapshots the target at invocation time.const resolveUploadTargetRef = useRef(opts?.resolveUploadTarget);resolveUploadTargetRef.current = opts?.resolveUploadTarget;@@ -443,6 +452,7 @@ export function useCoordinatedUploads(),);}+ if (mountedRef.current) setStorageRefusal(null);resolve(toUploadResult(outcome.attachment));} else {const reason = outcome.error.message;@@ -474,7 +484,15 @@ export function useCoordinatedUploads(deliverPastedTextBack(undefined, editorRef, pastedText);}}- toast.error(t(($) => $.upload.failed, { filename: file.name, reason }));+ // A storage-limit refusal gets the notice under the editor+ // (MUL-9489), which says what to do about it; a composer that+ // has gone away still gets the plain toast.+ const refusal = storageLimitRefusal(outcome.error, file.name);+ if (refusal && mountedRef.current) {+ setStorageRefusal(refusal);+ } else {+ toast.error(t(($) => $.upload.failed, { filename: file.name, reason }));+ }resolve(null);}},@@ -518,5 +536,15 @@ export function useCoordinatedUploads(hasUploadingDraft(binding ? binding.getUploads() : localUploadsRef.current),};- return { uploads, attachments, handleUpload, removeUpload, gate };+ const dismissStorageRefusal = useCallback(() => setStorageRefusal(null), []);++ return {+ uploads,+ attachments,+ handleUpload,+ removeUpload,+ gate,+ storageRefusal,+ dismissStorageRefusal,+ };}diff --git a/packages/views/editor/use-editor-upload.test.tsx b/packages/views/editor/use-editor-upload.test.tsxindex a3eef793cc..b9214e1bed 100644--- a/packages/views/editor/use-editor-upload.test.tsx+++ b/packages/views/editor/use-editor-upload.test.tsx@@ -2,7 +2,10 @@ import { describe, it, expect, vi, beforeEach } from "vitest";import { renderHook, act } from "@testing-library/react";import type { ReactNode } from "react";import { I18nProvider } from "@multica/core/i18n/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { ApiError } from "@multica/core/api";import enEditor from "../locales/en/editor.json";+import enBilling from "../locales/en/billing.json";const mockToastError = vi.hoisted(() => vi.fn());const mockUploadFile = vi.hoisted(() => vi.fn());@@ -11,20 +14,37 @@ vi.mock("sonner", () => ({toast: { error: mockToastError },}));-vi.mock("@multica/core/api", () => ({- api: { uploadFile: mockUploadFile },+vi.mock("@multica/core/api", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/api")>("@multica/core/api");+ return { ApiError: actual.ApiError, api: { uploadFile: mockUploadFile } };+});++// The storage notice reads the caller's role; outside a workspace route it+// has none and shows the member copy.+vi.mock("@multica/core/auth", () => ({+ useAuthStore: (select: (state: { user: null }) => unknown) => select({ user: null }),}));import { useEditorUpload } from "./use-editor-upload";function wrapper({ children }: { children: ReactNode }) {return (- <I18nProvider locale="en" resources={{ en: { editor: enEditor } }}>- {children}- </I18nProvider>+ <QueryClientProvider client={new QueryClient()}>+ <I18nProvider locale="en" resources={{ en: { editor: enEditor, billing: enBilling } }}>+ {children}+ </I18nProvider>+ </QueryClientProvider>);}+function storageRefusal() {+ return new ApiError("full", 403, "Forbidden", {+ code: "storage_limit_reached",+ used_bytes: 1_000_000_000,+ limit_bytes: 1_000_000_000,+ });+}+// MUL-4808 — `uploadWithToast` only ever toasted if its caller passed// `onError`, and no composer did. So a failed upload silently removed its// placeholder and the file simply vanished with no explanation. The gate's@@ -84,4 +104,42 @@ describe("useEditorUpload", () => {expect(mockToastError).not.toHaveBeenCalled();});++ // MUL-9489: a storage refusal says what happened and what to do, not the+ // server's raw message.+ it("toasts a storage refusal as the storage notice", async () => {+ mockUploadFile.mockRejectedValue(storageRefusal());+ const { result } = renderHook(() => useEditorUpload(), { wrapper });++ await act(async () => {+ await result.current.uploadWithToast(new File(["x"], "design-v3.fig"));+ });++ expect(mockToastError).toHaveBeenCalledWith(+ "design-v3.fig wasn't uploaded",+ expect.objectContaining({+ description:+ "Attachment storage is full. Ask an admin to upgrade the plan, or delete attachments you no longer need.",+ }),+ );+ expect(result.current.storageRefusal).toBeNull();+ });++ it("holds a storage refusal for an inline notice when the host renders one", async () => {+ mockUploadFile.mockRejectedValue(storageRefusal());+ const { result } = renderHook(() => useEditorUpload({ inlineStorageNotice: true }), { wrapper });++ await act(async () => {+ await result.current.uploadWithToast(new File(["x"], "design-v3.fig"));+ });++ expect(mockToastError).not.toHaveBeenCalled();+ expect(result.current.storageRefusal).toEqual({+ filename: "design-v3.fig",+ usedBytes: 1_000_000_000,+ limitBytes: 1_000_000_000,+ });+ act(() => result.current.dismissStorageRefusal());+ expect(result.current.storageRefusal).toBeNull();+ });});diff --git a/packages/views/editor/use-editor-upload.ts b/packages/views/editor/use-editor-upload.tsindex 301af20450..1141fbca56 100644--- a/packages/views/editor/use-editor-upload.ts+++ b/packages/views/editor/use-editor-upload.ts@@ -1,10 +1,15 @@"use client";-import { useCallback } from "react";+import { useCallback, useState } from "react";import { toast } from "sonner";import { api } from "@multica/core/api";import { useFileUpload } from "@multica/core/hooks/use-file-upload";import { useT } from "../i18n";+import {+ storageLimitRefusal,+ useStorageLimitToast,+ type StorageLimitRefusal,+} from "../billing/storage-limit-notice";/*** `useFileUpload` wired to the failure toast the upload gate depends on.@@ -17,18 +22,36 @@ import { useT } from "../i18n";** `useFileUpload` lives in `@multica/core`, which may not import a UI library,* so the toast is supplied here — once, rather than per composer.+ *+ * A file the attachment storage limit refused (MUL-9489) is reported with+ * what to do about it: as `storageRefusal` for a host that renders a+ * StorageLimitNotice under its editor (`inlineStorageNotice`), otherwise as a+ * toast carrying the same notice.*/-function useEditorUpload() {+function useEditorUpload(opts?: { inlineStorageNotice?: boolean }) {const { t } = useT("editor");+ const inline = opts?.inlineStorageNotice === true;+ const [storageRefusal, setStorageRefusal] = useState<StorageLimitRefusal | null>(null);+ const toastStorageLimit = useStorageLimitToast();const onError = useCallback((error: Error, file: File) => {+ if (inline) {+ const refusal = storageLimitRefusal(error, file.name);+ if (refusal) {+ setStorageRefusal(refusal);+ return;+ }+ } else if (toastStorageLimit(error, file.name)) {+ return;+ }toast.error(t(($) => $.upload.failed, { filename: file.name, reason: error.message }),);},- [t],+ [inline, t, toastStorageLimit],);- return useFileUpload(api, onError);+ const dismissStorageRefusal = useCallback(() => setStorageRefusal(null), []);+ return { ...useFileUpload(api, onError), storageRefusal, dismissStorageRefusal };}export { useEditorUpload };diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex 34243c1d7a..7e02b3ce7c 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -33,6 +33,7 @@ import { cn } from "@multica/ui/lib/utils";import { copyText } from "@multica/ui/lib/clipboard";import { useActorName } from "@multica/core/workspace/hooks";import { useLocale, useTimeAgo } from "../../i18n";+import { StorageLimitNotice } from "../../billing/storage-limit-notice";import { ContentEditor, type ContentEditorRef, ReadonlyContent, useFileDropZone, FileDropOverlay, Attachment as AttachmentRenderer, AttachmentDownloadProvider, useUploadGate, useComposerSubmit } from "../../editor";import { useCommentUploads } from "./use-comment-uploads";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";@@ -387,7 +388,7 @@ function useEditAttachmentState(const draftKey = `edit:${issueId}:${entry.id}` as const;// `gate` widens the editor gate with coordinator-owned placeholders — see// CommentInput.- const { uploads, attachments: pendingAttachments, handleUpload, removeUpload, gate } =+ const { uploads, attachments: pendingAttachments, handleUpload, removeUpload, gate, storageRefusal, dismissStorageRefusal } =useCommentUploads(draftKey, { issueId }, uploadGate, editorRef);const [retainedStandaloneIds, setRetainedStandaloneIds] = useState<Set<string> | null>(null);const triggerPreview = useCommentTriggerPreview({@@ -558,6 +559,8 @@ function useEditAttachmentState(handleUpload,uploads,removeUpload,+ storageRefusal,+ dismissStorageRefusal,isDragOver,dropZoneProps,triggerPreview,@@ -958,6 +961,9 @@ function CommentRow({attachments={edit.editorAttachments}/></div>+ {edit.storageRefusal && (+ <StorageLimitNotice refusal={edit.storageRefusal} onDismiss={edit.dismissStorageRefusal} className="mt-2" />+ )}{edit.revisionConflict ? (<CommentRevisionConflictserverContent={entry.content ?? ""}@@ -1568,6 +1574,9 @@ function CommentCardImpl({attachments={edit.editorAttachments}/></div>+ {edit.storageRefusal && (+ <StorageLimitNotice refusal={edit.storageRefusal} onDismiss={edit.dismissStorageRefusal} className="mt-2" />+ )}{edit.revisionConflict ? (<CommentRevisionConflictserverContent={entry.content ?? ""}diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsxindex f3d6fa0bec..bb9623c651 100644--- a/packages/views/issues/components/comment-input.tsx+++ b/packages/views/issues/components/comment-input.tsx@@ -5,6 +5,7 @@ import { cn } from "@multica/ui/lib/utils";import { Info } from "@multica/ui/icons";import { useCurrentWorkspace } from "@multica/core/paths";import { useIsGuest } from "@multica/core/permissions";+import { StorageLimitNotice } from "../../billing/storage-limit-notice";import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";import { SubmitButton } from "@multica/ui/components/common/submit-button";import { Button } from "@multica/ui/components/ui/button";@@ -89,7 +90,7 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat// status chips (uploading / failed / interrupted).// `gate` widens the editor gate with coordinator-owned placeholders, so a// composer reopened over a still-in-flight upload cannot send past it.- const { attachments: pendingAttachments, handleUpload, gate } =+ const { attachments: pendingAttachments, handleUpload, gate, storageRefusal, dismissStorageRefusal } =useCommentUploads(draftKey, { issueId }, uploadGate, editorRef);const hasAttachments = useMemo(() => pendingAttachments.some((a) => contentReferencesAttachment(content, a)) || gate.uploading,@@ -348,6 +349,9 @@ function CommentInput({ issueId, onSubmit, onAccepted, onEditAnnotation, annotat<VoiceHud voice={voice} /><VoiceSetupDialog voice={voice} /><VoiceErrorRow voice={voice} className="mx-2 mb-1" />+ {storageRefusal && (+ <StorageLimitNotice refusal={storageRefusal} onDismiss={dismissStorageRefusal} className="mx-2 mb-1" />+ )}<ComposerToolbarclassName="px-1.5 pb-1"voice={voice}diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 3f9d141fc3..86c6711ef6 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -48,6 +48,7 @@ import { IconButton } from "@multica/ui/components/common/icon-button";import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@multica/ui/components/ui/resizable";import { Sheet, SheetContent } from "@multica/ui/components/ui/sheet";import { useIsMobile } from "@multica/ui/hooks/use-mobile";+import { StorageLimitNotice } from "../../billing/storage-limit-notice";import { ContentEditor, ReadonlyContent, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useEditorUpload, PreviewSequenceProvider, collectPreviewSequence } from "../../editor";import {WAKEUP_ACTIVITY_ACTIONS,@@ -1558,7 +1559,11 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d// editor already strips `blob:` before serializing and binds ids on the// later save). It still needs the failure toast, or a failed upload just// erases its own placeholder and the file disappears unexplained.- const { uploadWithToast } = useEditorUpload();+ const {+ uploadWithToast,+ storageRefusal: descStorageRefusal,+ dismissStorageRefusal: dismissDescStorageRefusal,+ } = useEditorUpload({ inlineStorageNotice: true });const { defaultLayout, onLayoutChanged } = useDefaultLayout({id: layoutId,});@@ -4194,6 +4199,13 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d/>)}</div>+ {descStorageRefusal && (+ <StorageLimitNotice+ refusal={descStorageRefusal}+ onDismiss={dismissDescStorageRefusal}+ className="mt-2"+ />+ )}<div className="flex items-center gap-1 mt-3"><ReactionBardiff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsxindex 310101adcd..7fe043376f 100644--- a/packages/views/issues/components/reply-input.tsx+++ b/packages/views/issues/components/reply-input.tsx@@ -5,6 +5,7 @@ import { annotationsWithPending, type AnnotationComposerSlot } from "./annotatioimport { ReplyAnnotations } from "./reply-annotations";import { useCallback, useRef, useState, useEffect, useImperativeHandle, useMemo, type Ref } from "react";import { toast } from "sonner";+import { StorageLimitNotice } from "../../billing/storage-limit-notice";import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";import { SubmitButton } from "@multica/ui/components/common/submit-button";import { Button } from "@multica/ui/components/ui/button";@@ -120,7 +121,7 @@ function ReplyInput({// back to session-local state inside the hook.// `gate` widens the editor gate with coordinator-owned placeholders — see// CommentInput.- const { uploads, attachments: pendingAttachments, handleUpload, removeUpload, gate } =+ const { uploads, attachments: pendingAttachments, handleUpload, removeUpload, gate, storageRefusal, dismissStorageRefusal } =useCommentUploads(draftKey, { issueId }, uploadGate, editorRef);const hasAttachments = useMemo(() => pendingAttachments.some((a) => contentReferencesAttachment(content, a)) || gate.uploading,@@ -373,6 +374,9 @@ function ReplyInput({<VoiceHud voice={voice} /><VoiceSetupDialog voice={voice} /><VoiceErrorRow voice={voice} className="mt-1" />+ {storageRefusal && (+ <StorageLimitNotice refusal={storageRefusal} onDismiss={dismissStorageRefusal} className="mt-1" />+ )}{expanded && <ComposerToolbarclassName="mt-1 animate-in fade-in slide-in-from-top-1 duration-150"voice={voice}diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex 461b051665..660e9a806a 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -28,6 +28,7 @@"actions": {"retry": "Retry","retry_autopilots": "Retry automation usage",+ "retry_storage": "Retry attachment storage usage","upgrade_to": "Upgrade to {{plan}}","switch_to": "Switch to {{plan}}","manage": "Manage billing",@@ -138,7 +139,10 @@"usage_unavailable": "Usage is temporarily unavailable","members": "Members","members_pending": "Pending invitations: {{pending}}",- "metering": "Runs from schedules, webhooks, and agents count. Runs a member starts with Run now don't."+ "metering": "Runs from schedules, webhooks, and agents count. Runs a member starts with Run now don't.",+ "storage": "Attachment storage",+ "storage_description": "Attachments in issues, comments, and chat.",+ "storage_label": "Attachment storage usage"},"seats": {"title": "Seats",@@ -320,5 +324,13 @@"after": "Existing guests keep their access after the trial. New guests need Pro or Business."}}+ },+ "storage_limit": {+ "title": "{{filename}} wasn't uploaded",+ "copy_title": "The sub-issue wasn't created: its source attachments couldn't be copied",+ "admin_body": "Attachment storage is full ({{used}} / {{limit}}). Existing attachments aren't affected.",+ "admin_body_no_figures": "Attachment storage is full. Existing attachments aren't affected.",+ "member_body": "Attachment storage is full. Ask an admin to upgrade the plan, or delete attachments you no longer need.",+ "dismiss": "Dismiss"}}diff --git a/packages/views/locales/es/billing.json b/packages/views/locales/es/billing.jsonindex c36d8785c7..9e2bfd824c 100644--- a/packages/views/locales/es/billing.json+++ b/packages/views/locales/es/billing.json@@ -28,6 +28,7 @@"actions": {"retry": "Reintentar","retry_autopilots": "Reintentar el uso de automatización",+ "retry_storage": "Reintentar uso del almacenamiento de adjuntos","upgrade_to": "Actualizar a {{plan}}","switch_to": "Cambiar a {{plan}}","manage": "Gestionar facturación",@@ -138,7 +139,10 @@"usage_unavailable": "El uso no está disponible temporalmente","members": "Miembros","members_pending": "Invitaciones pendientes: {{pending}}",- "metering": "Cuentan las ejecuciones de programaciones, webhooks y agentes. Las que un miembro inicia con Ejecutar ahora no cuentan."+ "metering": "Cuentan las ejecuciones de programaciones, webhooks y agentes. Las que un miembro inicia con Ejecutar ahora no cuentan.",+ "storage": "Almacenamiento de adjuntos",+ "storage_description": "Adjuntos de incidencias, comentarios y chats.",+ "storage_label": "Uso del almacenamiento de adjuntos"},"seats": {"title": "Puestos",@@ -320,5 +324,13 @@"after": "Los invitados actuales conservan su acceso después de la prueba. Para invitar a nuevos invitados necesitas Pro o Business."}}+ },+ "storage_limit": {+ "title": "{{filename}} no se subió",+ "copy_title": "No se creó la subincidencia: no se pudieron copiar sus adjuntos de origen",+ "admin_body": "El almacenamiento de adjuntos está lleno ({{used}} / {{limit}}). Los adjuntos existentes no se ven afectados.",+ "admin_body_no_figures": "El almacenamiento de adjuntos está lleno. Los adjuntos existentes no se ven afectados.",+ "member_body": "El almacenamiento de adjuntos está lleno. Pide a un administrador que actualice el plan o elimina los adjuntos que ya no necesites.",+ "dismiss": "Cerrar"}}diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.jsonindex da0c94c50e..e44b7f4544 100644--- a/packages/views/locales/fr/billing.json+++ b/packages/views/locales/fr/billing.json@@ -28,6 +28,7 @@"actions": {"retry": "Réessayer","retry_autopilots": "Réessayer le chargement de la consommation des automatisations",+ "retry_storage": "Réessayer l'utilisation du stockage des pièces jointes","upgrade_to": "Passer à {{plan}}","switch_to": "Basculer vers {{plan}}","manage": "Gérer la facturation",@@ -138,7 +139,10 @@"usage_unavailable": "La consommation est temporairement indisponible","members": "Membres","members_pending": "Invitations en attente : {{pending}}",- "metering": "Les exécutions lancées par une planification, un webhook ou un agent sont comptées. Celles qu'un membre lance avec Exécuter maintenant ne le sont pas."+ "metering": "Les exécutions lancées par une planification, un webhook ou un agent sont comptées. Celles qu'un membre lance avec Exécuter maintenant ne le sont pas.",+ "storage": "Stockage des pièces jointes",+ "storage_description": "Pièces jointes des tickets, commentaires et discussions.",+ "storage_label": "Utilisation du stockage des pièces jointes"},"seats": {"title": "Sièges",@@ -320,5 +324,13 @@"after": "Les invités existants gardent leur accès après l'essai. Inviter de nouveaux invités nécessite Pro ou Business."}}+ },+ "storage_limit": {+ "title": "{{filename}} n'a pas été importé",+ "copy_title": "Le sous-ticket n'a pas été créé : ses pièces jointes sources n'ont pas pu être copiées",+ "admin_body": "Le stockage des pièces jointes est plein ({{used}} / {{limit}}). Les pièces jointes existantes ne sont pas affectées.",+ "admin_body_no_figures": "Le stockage des pièces jointes est plein. Les pièces jointes existantes ne sont pas affectées.",+ "member_body": "Le stockage des pièces jointes est plein. Demandez à un administrateur de changer de forfait, ou supprimez les pièces jointes dont vous n'avez plus besoin.",+ "dismiss": "Fermer"}}diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex 68217fe6b3..bf4fa87b10 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -28,6 +28,7 @@"actions": {"retry": "再試行","retry_autopilots": "自動化の使用量を再取得",+ "retry_storage": "添付ファイルの保存容量の使用量を再試行","upgrade_to": "{{plan}} にアップグレード","switch_to": "{{plan}} に切り替え","manage": "請求を管理",@@ -137,7 +138,10 @@"usage_unavailable": "使用量は一時的に利用できません","members": "メンバー","members_pending": "保留中の招待:{{pending}} 件",- "metering": "スケジュール、Webhook、エージェントによる実行はカウントされます。メンバーが「今すぐ実行」で開始した実行はカウントされません。"+ "metering": "スケジュール、Webhook、エージェントによる実行はカウントされます。メンバーが「今すぐ実行」で開始した実行はカウントされません。",+ "storage": "添付ファイルの保存容量",+ "storage_description": "タスク、コメント、チャットの添付ファイル。",+ "storage_label": "添付ファイルの保存容量の使用量"},"seats": {"title": "席数",@@ -308,5 +312,13 @@"after": "終了後も既存のゲストはアクセスを保持します。新しいゲストの招待には Pro または Business が必要です。"}}+ },+ "storage_limit": {+ "title": "{{filename}} はアップロードされませんでした",+ "copy_title": "サブタスクは作成されませんでした:元の添付ファイルをコピーできません",+ "admin_body": "添付ファイルの保存容量が上限に達しました({{used}} / {{limit}})。既存の添付ファイルには影響しません。",+ "admin_body_no_figures": "添付ファイルの保存容量が上限に達しました。既存の添付ファイルには影響しません。",+ "member_body": "添付ファイルの保存容量が上限に達しました。管理者にプランのアップグレードを依頼するか、不要な添付ファイルを削除してください。",+ "dismiss": "閉じる"}}diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex 5df1be8b6b..57acfeb560 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -28,6 +28,7 @@"actions": {"retry": "다시 시도","retry_autopilots": "자동화 사용량 다시 시도",+ "retry_storage": "첨부 파일 저장 공간 사용량 다시 시도","upgrade_to": "{{plan}}로 업그레이드","switch_to": "{{plan}}로 전환","manage": "결제 관리",@@ -137,7 +138,10 @@"usage_unavailable": "사용량을 일시적으로 불러올 수 없습니다","members": "멤버","members_pending": "대기 중인 초대: {{pending}}건",- "metering": "일정, Webhook, 에이전트로 시작된 실행은 집계됩니다. 멤버가 지금 실행으로 시작한 실행은 집계되지 않습니다."+ "metering": "일정, Webhook, 에이전트로 시작된 실행은 집계됩니다. 멤버가 지금 실행으로 시작한 실행은 집계되지 않습니다.",+ "storage": "첨부 파일 저장 공간",+ "storage_description": "이슈, 댓글, 채팅의 첨부 파일입니다.",+ "storage_label": "첨부 파일 저장 공간 사용량"},"seats": {"title": "좌석",@@ -308,5 +312,13 @@"after": "체험 후에도 기존 게스트는 접근 권한을 유지합니다. 새 게스트를 초대하려면 Pro 또는 Business가 필요합니다."}}+ },+ "storage_limit": {+ "title": "{{filename}}을(를) 업로드하지 못했습니다",+ "copy_title": "하위 이슈가 생성되지 않았습니다: 원본 첨부 파일을 복사할 수 없습니다",+ "admin_body": "첨부 파일 저장 공간이 가득 찼습니다({{used}} / {{limit}}). 기존 첨부 파일에는 영향이 없습니다.",+ "admin_body_no_figures": "첨부 파일 저장 공간이 가득 찼습니다. 기존 첨부 파일에는 영향이 없습니다.",+ "member_body": "첨부 파일 저장 공간이 가득 찼습니다. 관리자에게 요금제 업그레이드를 요청하거나 필요 없는 첨부 파일을 삭제하세요.",+ "dismiss": "닫기"}}diff --git a/packages/views/locales/ru/billing.json b/packages/views/locales/ru/billing.jsonindex e0a234dd66..b8c93bdd64 100644--- a/packages/views/locales/ru/billing.json+++ b/packages/views/locales/ru/billing.json@@ -28,6 +28,7 @@"actions": {"retry": "Повторить","retry_autopilots": "Повторить получение использования автоматизации",+ "retry_storage": "Повторить загрузку использования хранилища вложений","upgrade_to": "Перейти на {{plan}}","switch_to": "Переключиться на {{plan}}","manage": "Управление биллингом",@@ -140,7 +141,10 @@"usage_unavailable": "Данные об использовании временно недоступны","members": "Участники","members_pending": "Ожидающие приглашения: {{pending}}",- "metering": "Учитываются запуски по расписанию, через вебхук и агентами. Запуски, которые участник начинает кнопкой «Запустить сейчас», не учитываются."+ "metering": "Учитываются запуски по расписанию, через вебхук и агентами. Запуски, которые участник начинает кнопкой «Запустить сейчас», не учитываются.",+ "storage": "Хранилище вложений",+ "storage_description": "Вложения в задачах, комментариях и чатах.",+ "storage_label": "Использование хранилища вложений"},"seats": {"title": "Места",@@ -344,5 +348,13 @@"after": "Текущие гости сохраняют доступ после пробного периода. Для приглашения новых гостей нужен Pro или Business."}}+ },+ "storage_limit": {+ "title": "Файл {{filename}} не загружен",+ "copy_title": "Подзадача не создана: не удалось скопировать исходные вложения",+ "admin_body": "Хранилище вложений заполнено ({{used}} / {{limit}}). Существующие вложения не затронуты.",+ "admin_body_no_figures": "Хранилище вложений заполнено. Существующие вложения не затронуты.",+ "member_body": "Хранилище вложений заполнено. Попросите администратора сменить тариф или удалите ненужные вложения.",+ "dismiss": "Закрыть"}}diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex 13e7ca8399..0b98e47257 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -28,6 +28,7 @@"actions": {"retry": "重试","retry_autopilots": "重试加载自动化用量",+ "retry_storage": "重试附件存储用量","upgrade_to": "升级到 {{plan}}","switch_to": "切换到 {{plan}}","manage": "管理账单",@@ -137,7 +138,10 @@"usage_unavailable": "用量暂时不可用","members": "成员","members_pending": "待接受的邀请:{{pending}}",- "metering": "时间表、Webhook 和智能体发起的运行计入额度,成员点击\"立即运行\"不计入。"+ "metering": "时间表、Webhook 和智能体发起的运行计入额度,成员点击\"立即运行\"不计入。",+ "storage": "附件存储",+ "storage_description": "任务、评论和聊天中的附件。",+ "storage_label": "附件存储用量"},"seats": {"title": "席位",@@ -308,5 +312,13 @@"after": "到期后已有访客保留访问权限,邀请新访客需要 Pro 或 Business。"}}+ },+ "storage_limit": {+ "title": "{{filename}} 没有上传",+ "copy_title": "子任务没有创建:无法复制源附件",+ "admin_body": "附件存储已满({{used}} / {{limit}}),已有附件不受影响。",+ "admin_body_no_figures": "附件存储已满,已有附件不受影响。",+ "member_body": "附件存储已满。请联系管理员升级套餐,或删除不需要的附件。",+ "dismiss": "关闭"}}diff --git a/packages/views/locales/zh-Hant/billing.json b/packages/views/locales/zh-Hant/billing.jsonindex 3e477109b2..af1c36575f 100644--- a/packages/views/locales/zh-Hant/billing.json+++ b/packages/views/locales/zh-Hant/billing.json@@ -28,6 +28,7 @@"actions": {"retry": "重試","retry_autopilots": "重試載入自動化用量",+ "retry_storage": "重試附件儲存空間用量","upgrade_to": "升級到 {{plan}}","switch_to": "切換到 {{plan}}","manage": "管理帳單",@@ -137,7 +138,10 @@"usage_unavailable": "用量暫時不可用","members": "成員","members_pending": "待接受的邀請:{{pending}}",- "metering": "時間表、Webhook 和 AI 代理發起的執行計入額度,成員點擊\"立即執行\"不計入。"+ "metering": "時間表、Webhook 和 AI 代理發起的執行計入額度,成員點擊\"立即執行\"不計入。",+ "storage": "附件儲存空間",+ "storage_description": "任務、留言和聊天中的附件。",+ "storage_label": "附件儲存空間用量"},"seats": {"title": "席位",@@ -308,5 +312,13 @@"after": "到期後既有訪客保留存取權限,邀請新訪客需要 Pro 或 Business。"}}+ },+ "storage_limit": {+ "title": "{{filename}} 沒有上傳",+ "copy_title": "子任務沒有建立:無法複製來源附件",+ "admin_body": "附件儲存空間已滿({{used}} / {{limit}}),既有附件不受影響。",+ "admin_body_no_figures": "附件儲存空間已滿,既有附件不受影響。",+ "member_body": "附件儲存空間已滿。請聯絡管理員升級套餐,或刪除不需要的附件。",+ "dismiss": "關閉"}}diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsxindex 0f5fb38524..fc038dbd5d 100644--- a/packages/views/modals/create-issue.tsx+++ b/packages/views/modals/create-issue.tsx@@ -100,6 +100,7 @@ import {} from "../issues/components/pickers/custom-property-picker";import { IssuePickerModal } from "./issue-picker-modal";import { useT } from "../i18n";+import { StorageLimitNotice, storageLimitRefusal, type StorageLimitRefusal } from "../billing/storage-limit-notice";import { SourceContextPreviewCard, useSourceContextFailureMessage } from "./source-context-preview";import { CopyParentFields } from "./copy-parent-fields";@@ -405,7 +406,10 @@ export function ManualCreatePanel({attachments: draftAttachments,handleUpload,gate,+ storageRefusal,+ dismissStorageRefusal,} = useIssueCreateUploads("manual", uploadGate, descEditorRef);+ const [storageCopyRefusal, setStorageCopyRefusal] = useState<StorageLimitRefusal | null>(null);// Sync field changes to the draft store — manual-only fields to the manual// slot, project / priority / due date to the shared slot.@@ -697,6 +701,13 @@ export function ManualCreatePanel({}return true;} catch (err) {+ // A sub-issue copies its source attachments; a full workspace refuses+ // that before creating anything (MUL-9489).+ const copyRefusal = anchorCommentId ? storageLimitRefusal(err, "") : null;+ if (copyRefusal) {+ if (mountedRef.current) setStorageCopyRefusal({ ...copyRefusal, kind: "copy" });+ return false;+ }const sourceCode = err instanceof ApiError && err.body && typeof err.body === "object"? (err.body as { code?: unknown }).code: undefined;@@ -1060,6 +1071,21 @@ export function ManualCreatePanel({{descDragOver && <FileDropOverlay />}</div>+ {storageRefusal && (+ <StorageLimitNotice+ refusal={storageRefusal}+ onDismiss={dismissStorageRefusal}+ className="mx-5 mb-2"+ />+ )}+ {storageCopyRefusal && (+ <StorageLimitNotice+ refusal={storageCopyRefusal}+ onDismiss={() => setStorageCopyRefusal(null)}+ className="mx-5 mb-2"+ />+ )}+{anchorCommentId && (<SourceContextPreviewCardpreview={sourcePreview}diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsxindex 6bbeaa452e..b561e65ebc 100644--- a/packages/views/modals/quick-create-issue.tsx+++ b/packages/views/modals/quick-create-issue.tsx@@ -87,6 +87,7 @@ import {import { useIssueCreateUploads } from "./use-issue-create-uploads";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { useT } from "../i18n";+import { StorageLimitNotice, storageLimitRefusal, type StorageLimitRefusal } from "../billing/storage-limit-notice";import { matchesPinyin } from "../editor/extensions/pinyin-match";import { SourceContextPreviewCard, useSourceContextFailureMessage } from "./source-context-preview";@@ -399,7 +400,10 @@ export function AgentCreatePanel({attachments: pendingAttachments,handleUpload: handleUploadFile,gate,+ storageRefusal,+ dismissStorageRefusal,} = useIssueCreateUploads("agent", uploadGate, editorRef);+ const [storageCopyRefusal, setStorageCopyRefusal] = useState<StorageLimitRefusal | null>(null);// The Qoder bridge cannot read attachments, so the issue it creates would be// assigned to an agent whose run fails immediately. Block instead of// silently dropping the attachment; the server re-checks.@@ -496,6 +500,13 @@ export function AgentCreatePanel({});return true;} catch (e) {+ // A sub-issue copies its source attachments; a full workspace refuses+ // that before creating anything (MUL-9489).+ const copyRefusal = anchorCommentId ? storageLimitRefusal(e, "") : null;+ if (copyRefusal) {+ setStorageCopyRefusal({ ...copyRefusal, kind: "copy" });+ return false;+ }// Server returns 422 with { code, ... } for the structured rejection// paths the modal cares about. Surface the reason in-modal so the// user can switch to a live agent / upgrade their daemon without@@ -794,6 +805,17 @@ export function AgentCreatePanel({{isDragOver && <FileDropOverlay />}</div>+ {storageRefusal && (+ <StorageLimitNotice refusal={storageRefusal} onDismiss={dismissStorageRefusal} className="mx-5 mb-2" />+ )}+ {storageCopyRefusal && (+ <StorageLimitNotice+ refusal={storageCopyRefusal}+ onDismiss={() => setStorageCopyRefusal(null)}+ className="mx-5 mb-2"+ />+ )}+{anchorCommentId && (<SourceContextPreviewCardpreview={sourcePreview}diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex de0ae5bb4c..06cc1fbafe 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -7,6 +7,7 @@ import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flagimport type {AutopilotQuotaUsage,MemberLimit,+ StorageUsage,WorkspaceSubscriptionEntitlements,WorkspaceSubscriptionPrices,WorkspaceSubscriptionSummary,@@ -36,6 +37,8 @@ const mocks = vi.hoisted(() => ({workspaceId: "workspace-1",invalidateQueries: vi.fn(() => Promise.resolve()),memberLimit: { action: "off", limit: null, members: null, pendingInvitations: null } as MemberLimit,+ storageUsage: { action: "off", usedBytes: null, limitBytes: null, reached: null } as StorageUsage,+ refetchStorage: vi.fn(),prices: null as WorkspaceSubscriptionPrices | null,pricesLoading: false,pricesFetching: false,@@ -329,8 +332,12 @@ describe("BillingTab", () => {});localStorage.clear();mocks.memberLimit = { action: "off", limit: null, members: null, pendingInvitations: null };+ mocks.storageUsage = { action: "off", usedBytes: null, limitBytes: null, reached: null };mocks.useQuery.mockImplementation((options: unknown) => {const queryKey = (options as { queryKey?: readonly unknown[] }).queryKey;+ if (queryKey?.[0] === "workspace-storage-usage") {+ return { data: mocks.storageUsage, isPending: false, isError: false, refetch: mocks.refetchStorage };+ }if (queryKey?.[queryKey.length - 1] === "limit") {return { data: mocks.memberLimit, isPending: false, isError: false };}@@ -850,6 +857,56 @@ describe("BillingTab", () => {}});+ it("shows attachment storage against the plan's limit (MUL-9489)", () => {+ mocks.storageUsage = { action: "observe", usedBytes: 23_400_000_000, limitBytes: 120_000_000_000, reached: null };+ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Attachment storage")).toBeInTheDocument();+ expect(screen.getByText("Attachments in issues, comments, and chat.")).toBeInTheDocument();+ expect(screen.getByText("23.4 GB / 120 GB")).toBeInTheDocument();+ });++ it("reports enforced full storage as reached, and hides storage without a limit", () => {+ mocks.storageUsage = { action: "enforce", usedBytes: 1_000_000_000, limitBytes: 1_000_000_000, reached: true };+ const { unmount } = renderWithI18n(<BillingTab />);+ expect(screen.getByText("1 GB / 1 GB")).toBeInTheDocument();+ expect(screen.getAllByText("Limit reached").length).toBeGreaterThan(0);+ unmount();++ mocks.storageUsage = { action: "off", usedBytes: null, limitBytes: null, reached: null };+ renderWithI18n(<BillingTab />);+ expect(screen.queryByText("Attachment storage")).not.toBeInTheDocument();+ });++ it("shows storage usage it could not read as unavailable, with a retry", async () => {+ const user = userEvent.setup();+ mocks.refetchStorage.mockReset();+ mocks.storageUsage = { action: "observe", usedBytes: null, limitBytes: 1_000_000_000, reached: null };+ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Attachment storage")).toBeInTheDocument();+ expect(screen.getByText("1 GB")).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Retry attachment storage usage" }));+ expect(mocks.refetchStorage).toHaveBeenCalledOnce();+ });++ // After Pro moves to Business (or seats are added) the summary carries+ // the new limit at once, while the usage read can still hold the old one.+ it("shows the plan's new storage limit as soon as the subscription changes", () => {+ mocks.storageUsage = { action: "observe", usedBytes: 12_000_000_000, limitBytes: 30_000_000_000, reached: null };+ mocks.entitlements.limits = { ...mocks.entitlements.limits, storageBytes: { mode: "limited", limit: 30_000_000_000 } };+ const { rerender } = renderWithI18n(<BillingTab />);+ expect(screen.getByText("12 GB / 30 GB")).toBeInTheDocument();+ mocks.invalidateQueries.mockClear();++ mocks.entitlements.limits = { ...mocks.entitlements.limits, storageBytes: { mode: "limited", limit: 300_000_000_000 } };+ mocks.entitlements.version = 1;+ rerender(<BillingTab />);++ expect(screen.getByText("12 GB / 300 GB")).toBeInTheDocument();+ expect(mocks.invalidateQueries).toHaveBeenCalledWith({ queryKey: ["workspace-storage-usage", expect.any(String)] });+ });+it("shows members and pending invitations against the plan's limit", () => {mocks.memberLimit = { action: "observe", limit: 5, members: 4, pendingInvitations: 2 };renderWithI18n(<BillingTab />);diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex 8bd6337ba7..a74e81c940 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -31,6 +31,11 @@ import {listCheckoutHeldInvites,memberLimitKeys,memberLimitOptions,+ formatStorageBytes,+ resolveStorageRow,+ storageUsageKeys,+ storageUsageOptions,+ storageUsageProgress,readUpgradeInvite,type HeldInvite,workspaceSubscriptionPricesOptions,@@ -340,6 +345,7 @@ function BillingTabContent() {// the person to send or discard.const [heldInvitesToConfirm, setHeldInvitesToConfirm] = useState<HeldInvite[]>([]);const memberLimitQuery = useQuery(memberLimitOptions(wsId));+ const storageUsageQuery = useQuery(storageUsageOptions(wsId));useEffect(() => {checkoutIntentRef.current = null;@@ -428,6 +434,17 @@ function BillingTabContent() {}, [awaitingHeldCheckoutAt, refetchSummary]);const entitlements = summaryQuery.data?.entitlement;+ // A confirmed upgrade or seat purchase changes the storage limit; the+ // entitlement already carries the new one, and this refreshes the usage+ // read behind it.+ const subscriptionVersion = summaryQuery.data?.entitlement.version;+ const seenSubscriptionVersionRef = useRef(subscriptionVersion);+ useEffect(() => {+ const seen = seenSubscriptionVersionRef.current;+ seenSubscriptionVersionRef.current = subscriptionVersion;+ if (seen === undefined || subscriptionVersion === undefined || seen === subscriptionVersion) return;+ void queryClient.invalidateQueries({ queryKey: storageUsageKeys.all(wsId) });+ }, [queryClient, subscriptionVersion, wsId]);// Checkout is done once paid seats are in effect. Neither the plan nor// Checkout going away proves it: a trial already reports Business, and a// first payment still incomplete also takes Checkout away.@@ -754,6 +771,11 @@ function BillingTabContent() {if (upgradeRequest === "pro" && summary.availableActions.checkout === true) {setHeldInvite(held);openCheckoutConfirm("pro");+ } else if (upgradeRequest === "business" && !held && resolvePlanChangeTarget(summary) === "business") {+ // A full workspace's storage notice (MUL-9489): Pro moves up to Business.+ handlePlanChangeOpenChange(true, "business");+ } else if (upgradeRequest === "business" && !held && summary.availableActions.checkout === true) {+ openCheckoutConfirm("business");} else if (held) {clearUpgradeInvite(workspaceSlug, held.token);}@@ -1262,6 +1284,11 @@ function BillingTabContent() {? formatDateTime(quotaUsage.resetAt, locale): null;const numberFormatter = new Intl.NumberFormat(locale);+ const storageRow = resolveStorageRow(+ storageUsageQuery.data,+ storageUsageQuery.isError,+ entitlements?.limits.storageBytes,+ );// Members and pending invitations against the plan's member limit, shown// whenever Cloud applies one (observed or enforced).const memberLimitData = memberLimitQuery.data;@@ -1971,6 +1998,62 @@ function BillingTabContent() {</div>)}</SettingsRow>+ {storageRow ? (+ <SettingsRow+ label={t(($) => $.workspace.limits.storage)}+ description={t(($) => $.workspace.limits.storage_description)}+ >+ {storageRow.kind === "metered" ? (+ <div className="w-full max-w-72">+ <Progress+ value={storageUsageProgress(storageRow.usedBytes, storageRow.limitBytes)}+ aria-label={t(($) => $.workspace.limits.storage_label)}+ >+ <ProgressLabel>+ {storageRow.reached+ ? t(($) => $.workspace.limits.reached)+ : t(($) => $.workspace.limits.current_usage)}+ </ProgressLabel>+ <ProgressValue>+ {() =>+ t(($) => $.workspace.limits.usage_total, {+ total: formatStorageBytes(storageRow.usedBytes, locale),+ limit: formatStorageBytes(storageRow.limitBytes, locale),+ })+ }+ </ProgressValue>+ </Progress>+ </div>+ ) : (+ <div className="flex flex-col gap-2 sm:items-end">+ {storageRow.limitBytes !== null ? (+ <span className="tabular-nums">+ {formatStorageBytes(storageRow.limitBytes, locale)}+ </span>+ ) : null}+ <span className="text-caption text-muted-foreground">+ {t(($) => $.workspace.limits.usage_unavailable)}+ </span>+ <Button+ type="button"+ variant="outline"+ size="sm"+ aria-label={t(($) => $.workspace.actions.retry_storage)}+ aria-busy={storageUsageQuery.isFetching}+ disabled={storageUsageQuery.isFetching}+ onClick={() => void storageUsageQuery.refetch()}+ >+ {storageUsageQuery.isFetching ? (+ <Loader2 className="animate-spin motion-reduce:animate-none" />+ ) : (+ <RefreshCw />+ )}+ {t(($) => $.workspace.actions.retry)}+ </Button>+ </div>+ )}+ </SettingsRow>+ ) : null}{memberLimit ? (<SettingsRow label={t(($) => $.workspace.limits.members)}><div className="flex flex-col gap-1 sm:items-end">diff --git a/packages/views/settings/components/workspace-tab.test.tsx b/packages/views/settings/components/workspace-tab.test.tsxindex 4a871c0236..908565ca2d 100644--- a/packages/views/settings/components/workspace-tab.test.tsx+++ b/packages/views/settings/components/workspace-tab.test.tsx@@ -80,6 +80,8 @@ vi.mock("../../navigation", () => ({useNavigation: () => ({ push: vi.fn() }),}));+vi.mock("../../billing/storage-limit-notice", () => ({ useStorageLimitToast: () => () => false }));+vi.mock("./delete-workspace-dialog", () => ({DeleteWorkspaceDialog: () => null,}));diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex b26b554c20..fb0dbd56de 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -158,6 +158,7 @@ var concurrentIndexCleanups = map[string]string{"704_doc_comment_pkey_index": "doc_comment_pkey_idx","706_doc_comment_doc_idx": "doc_comment_doc_idx","707_doc_comment_workspace_idx": "doc_comment_workspace_idx",+ "708_attachment_workspace_size_idx": "idx_attachment_workspace_size","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",@@ -447,6 +448,7 @@ var concurrentDownIndexCleanups = map[string]string{"463_drop_issue_description_bigm_index": "idx_issue_description_bigm","464_drop_issue_description_trgm_index": "idx_issue_description_trgm","473_drop_agent_task_queue_chat_with_session_index": "idx_agent_task_queue_chat_with_session_created_at",+ "709_drop_attachment_workspace_index": "idx_attachment_workspace",}var preMigrationHooks = func() map[string]preMigrationHook {diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex f850c86d53..b68fea1cab 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -484,6 +484,17 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bush.Features = entitlementClienth.AutopilotService.Entitlements = entitlementClienth.AutopilotService.QuotaMetrics = opts.BusinessMetrics+ storageQuota := service.StorageQuota{+ Sums: queries,+ Entitlements: entitlementClient,+ Overages: service.EntitlementOverages{Queries: queries},+ }+ if opts.BusinessMetrics != nil {+ storageQuota.Metrics = opts.BusinessMetrics+ }+ engine.SetMediaStoredHook(func(ctx context.Context, workspaceID pgtype.UUID) {+ storageQuota.RecordStored(ctx, workspaceID, service.StorageSourceChannel)+ })}// Cloud Runtime and strict seat capacity are one managed deployment. Reuse// the same base URL so Billing cannot be readable while invitation writes@@ -1846,6 +1857,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// The plan's member limit for upgrade UI; every admission// is checked on the server regardless.r.Get("/member-limit", h.GetMemberLimit)+ r.Get("/storage-usage", h.GetStorageUsage)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 df6331c796..136a8e92d7 100644--- a/server/internal/entitlement/README.md+++ b/server/internal/entitlement/README.md@@ -63,6 +63,8 @@ older consumer ignores the unknown gate, and this consumer reads a policywithout it, or with a malformed one, as `members` `off` with reason`gate_missing` or `gate_invalid`. Only that gate falls back; `autopilot_runs`and the features keep their instructions. See [Member limit](#member-limit).+`gates.storage_bytes` (revision 6) is optional the same way; see+[Attachment storage limit](#attachment-storage-limit).Responses tolerate unknown JSON fields and gates for additive compatibility.Unknown schema/action, malformed fields, a missing `autopilot_runs` gate, HTTP@@ -167,6 +169,38 @@ Clients read `GET /api/workspaces/{id}/member-limit` (member-readable), whichreturns `action` and, while a limit applies, `limit`, `members` and`pending_invitations`.+## Attachment storage limit++`storage_bytes` caps the attachment bytes a workspace holds, on every plan:+Cloud sends Free's flat limit or the paid plan's per-seat limit. It carries a+`limit` and no period. `service.StorageQuota`+(`server/internal/service/storage_quota.go`) checks it.++Usage is not stored: it is `SUM(size_bytes)` over the workspace's attachment+rows (`SumWorkspaceAttachmentBytes`, an index-only scan on+`idx_attachment_workspace_size`), so cascade deletes are reflected at once.+Every attachment row counts; thumbnails are not rows. `off` reads nothing.+The sum has its own timeout (`DefaultStorageSumTimeout`, 300 ms); a timeout or+error admits the upload and is counted in `multica_storage_quota_sum_total`.++| Path | Checked as |+| --- | --- |+| `POST /api/upload-file` with a workspace | used + file size, before the object is written |+| Create a sub-issue from a comment (copies the source attachments) | used + copied bytes, before the sub-issue or any copy exists |+| Files received through a messaging channel | recorded after they are stored, never refused |++`enforce` refuses with `403 storage_limit_reached`, `used_bytes` and+`limit_bytes`, after re-reading the policy with `RefreshGate`. `observe`+admits and records. Reads, downloads, thumbnails and deletes are never+checked. It is a soft limit: no lock is taken, so uploads in flight when a+workspace crosses its limit all pass. Attempts are recorded in+`entitlement_limit_overage` under gate `storage_bytes`, grouped by UTC+calendar month.++Clients read `GET /api/workspaces/{id}/storage-usage` (member-readable), which+returns `action` and, while a limit applies, `used_bytes` and `limit_bytes`;+`reached` is present only under `enforce`.+## Paid featuresA paid feature is restricted for a workspace whose plan does not include it.diff --git a/server/internal/entitlement/client.go b/server/internal/entitlement/client.goindex 7bdc7f0d30..b5f95f38d3 100644--- a/server/internal/entitlement/client.go+++ b/server/internal/entitlement/client.go@@ -389,7 +389,7 @@ func normalizePolicy(wire wirePolicy) (fetchedPolicy, error) {return fetchedPolicy{}, ErrInvalidPolicy}// Unknown gates are ignored for additive compatibility.- gates := make(map[GateName]Gate, 2)+ gates := make(map[GateName]Gate, 3)wireAutopilot, ok := wire.Gates[string(GateAutopilotRuns)]if !ok {return fetchedPolicy{}, ErrInvalidPolicy@@ -404,7 +404,7 @@ func normalizePolicy(wire wirePolicy) (fetchedPolicy, error) {// Cloud and Multica can deploy in either order and a bad value cannot turn// the autopilot quota off.gateReasons := make(map[GateName]Reason)- for _, name := range []GateName{GateMembers} {+ for _, name := range []GateName{GateMembers, GateStorageBytes} {if wire.undecodableGates[string(name)] {gates[name] = Gate{Action: ActionOff}gateReasons[name] = ReasonGateInvaliddiff --git a/server/internal/entitlement/members_gate_test.go b/server/internal/entitlement/members_gate_test.goindex 2c02029916..04a3b38d73 100644--- a/server/internal/entitlement/members_gate_test.go+++ b/server/internal/entitlement/members_gate_test.go@@ -197,3 +197,47 @@ func TestRefreshGateWithoutCloudIsOff(t *testing.T) {t.Fatalf("decision = %+v", decision)}}++func TestStorageBytesGateIsAPeriodlessCeiling(t *testing.T) {+ server := httptest.NewServer(policyHandler(func(p *wirePolicy) {+ p.Gates[string(GateStorageBytes)] = membersGate(ActionEnforce, 1_000_000_000)+ }))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)++ decision := client.Gate(context.Background(), uuid.New(), GateStorageBytes)+ if decision.Gate.Action != ActionEnforce || decision.Gate.Limit == nil ||+ *decision.Gate.Limit != 1_000_000_000 || decision.Gate.PeriodStart != nil {+ t.Fatalf("decision = %+v, want enforce 1e9 without a period", decision)+ }+}++// A Cloud that does not send storage_bytes yet, or sends it malformed, leaves+// storage off without touching the other gates.+func TestStorageBytesGateFailsOpenAlone(t *testing.T) {+ for _, tt := range []struct {+ name string+ mutate func(*wirePolicy)+ reason Reason+ }{+ {"missing", func(*wirePolicy) {}, ReasonGateMissing},+ {"enforce without limit", func(p *wirePolicy) {+ p.Gates[string(GateStorageBytes)] = wireGate{Action: string(ActionEnforce)}+ }, ReasonGateInvalid},+ } {+ t.Run(tt.name, func(t *testing.T) {+ server := httptest.NewServer(policyHandler(tt.mutate))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ workspaceID := uuid.New()++ storage := client.Gate(context.Background(), workspaceID, GateStorageBytes)+ if storage.Gate.Action != ActionOff || storage.Reason != tt.reason {+ t.Fatalf("storage = %+v, want off/%s", storage, tt.reason)+ }+ if autopilot := client.Gate(context.Background(), workspaceID, GateAutopilotRuns); autopilot.Gate.Action != ActionEnforce {+ t.Fatalf("autopilot = %+v, want the enforced quota from the same policy", autopilot)+ }+ })+ }+}diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.goindex bfda091170..054ae4d257 100644--- a/server/internal/entitlement/types.go+++ b/server/internal/entitlement/types.go@@ -16,11 +16,14 @@ const (// GateMembers caps a workspace's members. Guests take no slot. It has no// period: the limit is a ceiling on headcount, not a budget that resets.GateMembers GateName = "members"+ // GateStorageBytes caps the attachment bytes a workspace holds. Like+ // members it has no period: the limit is what the workspace may hold now.+ GateStorageBytes GateName = "storage_bytes")func (n GateName) valid() bool {switch n {- case GateAutopilotRuns, GateMembers:+ case GateAutopilotRuns, GateMembers, GateStorageBytes:return truedefault:return falsediff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex e3be64b024..cfc168f44d 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -21,6 +21,8 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/imagemetadata"+ "github.com/multica-ai/multica/server/internal/projectaccess"+ "github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/storage""github.com/multica-ai/multica/server/internal/thumbnail""github.com/multica-ai/multica/server/internal/util"@@ -468,7 +470,8 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {// If workspace context is available, validate membership before uploading.if workspaceID != "" {- if _, err := h.getWorkspaceMember(r.Context(), userID, workspaceID); err != nil {+ member, err := h.getWorkspaceMember(r.Context(), userID, workspaceID)+ if err != nil {writeError(w, http.StatusForbidden, "not a member of this workspace")return}@@ -599,6 +602,17 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {params.ChatSessionID = task.ChatSessionID}+ // Every field is validated; check the storage limit before writing+ // the object, so a refused upload stores nothing.+ if err := h.storageQuota().Admit(r.Context(), params.WorkspaceID, params.SizeBytes, service.StorageSourceUpload); err != nil {+ // The role read with membership above decides, so a failed+ // second lookup cannot show a guest the workspace's usage.+ if !writeStorageLimitReached(w, err, !projectaccess.IsGuestRole(member.Role)) {+ writeError(w, http.StatusInternalServerError, "upload failed")+ }+ return+ }+if dimensions, ok := imagemetadata.Dimensions(data); ok {params.Width = pgtype.Int4{Int32: dimensions.Width, Valid: true}params.Height = pgtype.Int4{Int32: dimensions.Height, Valid: true}diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.goindex 134433d2a9..b385041af7 100644--- a/server/internal/handler/source_context.go+++ b/server/internal/handler/source_context.go@@ -478,7 +478,8 @@ func (h *Handler) CreateCommentSubIssue(w http.ResponseWriter, r *http.Request)if !ok {return}- if _, ok := h.workspaceMember(w, r, workspaceID); !ok {+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {return}userID, ok := requireUserID(w, r)@@ -565,6 +566,20 @@ func (h *Handler) CreateCommentSubIssue(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusBadRequest, "mode must be manual or agent")return}+ // Copying the source attachments stores new bytes, so it is checked like+ // an upload, before the sub-issue or any copy exists.+ var copyBytes int64+ for _, row := range build.Rows {+ copyBytes += row.SizeBytes+ }+ if copyBytes > 0 {+ if err := h.storageQuota().Admit(r.Context(), wsUUID, copyBytes, service.StorageSourceSubIssue); err != nil {+ if !writeStorageLimitReached(w, err, !projectaccess.IsGuestRole(member.Role)) {+ writeError(w, http.StatusInternalServerError, "failed to check attachment storage")+ }+ return+ }+ }contextID := dbid.NewV7()capture, objectKeys, err := h.cloneSourceContext(r.Context(), wsUUID, userUUID, contextID, build)if err != nil {diff --git a/server/internal/handler/storage_limit.go b/server/internal/handler/storage_limit.gonew file mode 100644index 0000000000..c23d0d4180--- /dev/null+++ b/server/internal/handler/storage_limit.go@@ -0,0 +1,83 @@+package handler++import (+ "errors"+ "net/http"++ "github.com/multica-ai/multica/server/internal/service"+)++// Attachment storage limit (MUL-9489). The limit itself lives in+// service.StorageQuota; this file holds the HTTP side. Two paths add bytes on+// a person's request and are checked before writing anything: UploadFile and+// creating a sub-issue from a comment, which copies the source attachments.+// Files that arrive through a messaging channel are recorded, never refused.++const storageLimitReachedCode = "storage_limit_reached"++func (h *Handler) storageQuota() service.StorageQuota {+ q := service.StorageQuota{+ Sums: h.Queries,+ Entitlements: h.Entitlements,+ Overages: service.EntitlementOverages{Queries: h.Queries},+ }+ if h.Metrics != nil {+ q.Metrics = h.Metrics+ }+ return q+}++// writeStorageLimitReached answers a refused upload. It is a 403 like a+// locked paid feature: 413 already means one file over the per-file cap, and+// a 5xx would invite retries and availability alerts. The workspace's figures+// are included only for callers who may read storage usage: a guest, who+// cannot, gets the code and message alone.+func writeStorageLimitReached(w http.ResponseWriter, err error, withFigures bool) bool {+ var reached *service.StorageLimitReachedError+ if !errors.As(err, &reached) {+ return false+ }+ body := map[string]any{+ "code": storageLimitReachedCode,+ "error": "This workspace has reached its attachment storage limit. Upgrade the plan or delete attachments you no longer need.",+ }+ if withFigures {+ body["used_bytes"] = reached.Used+ body["limit_bytes"] = reached.Limit+ }+ writeJSON(w, http.StatusForbidden, body)+ return true+}++// StorageUsageResponse is the storage limit as clients render it. action is+// off when no limit applies, including self-hosted deployments. While a limit+// applies limit_bytes is present; used_bytes and reached are absent when the+// usage could not be read in time, and reached is present only under+// enforce.+type StorageUsageResponse struct {+ Action string `json:"action"`+ UsedBytes *int64 `json:"used_bytes,omitempty"`+ LimitBytes *int64 `json:"limit_bytes,omitempty"`+ Reached *bool `json:"reached,omitempty"`+}++// GetStorageUsage — GET /api/workspaces/{id}/storage-usage+//+// Member-readable: every member uploads, and the upload prompt needs it.+func (h *Handler) GetStorageUsage(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+ }+ usage := h.storageQuota().Usage(r.Context(), workspaceID)+ writeJSON(w, http.StatusOK, StorageUsageResponse{+ Action: string(usage.Action),+ UsedBytes: usage.Used,+ LimitBytes: usage.Limit,+ Reached: usage.Reached,+ })+}diff --git a/server/internal/handler/storage_limit_test.go b/server/internal/handler/storage_limit_test.gonew file mode 100644index 0000000000..808f038f6a--- /dev/null+++ b/server/internal/handler/storage_limit_test.go@@ -0,0 +1,350 @@+package handler++import (+ "bytes"+ "encoding/json"+ "mime/multipart"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "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"+)++// storageLimitWorkspace is a workspace of its own whose attachments already+// hold usedBytes, so its storage use belongs to the test alone.+func storageLimitWorkspace(t *testing.T, usedBytes int64) (workspaceID, attachmentID string) {+ t.Helper()+ workspaceID = memberLimitWorkspace(t, 0)+ dbfx.Cleanup(t, `DELETE FROM attachment WHERE workspace_id = $1`, workspaceID)+ dbfx.Cleanup(t, `DELETE FROM issue WHERE workspace_id = $1`, workspaceID)+ attachmentID = dbfx.Insert(t, "attachment", testutil.Cols{+ "workspace_id": workspaceID, "uploader_type": "member", "uploader_id": testUserID,+ "filename": "existing.bin", "url": "https://cdn.example.com/workspaces/" + workspaceID + "/existing.bin",+ "content_type": "application/octet-stream", "size_bytes": usedBytes,+ })+ return workspaceID, attachmentID+}++func useStorageLimit(t *testing.T, workspaceID string, action entitlement.Action, limit int) *entitlementtest.Stub {+ t.Helper()+ stub := entitlementtest.New()+ stub.Set(uuid.MustParse(workspaceID), entitlement.GateStorageBytes, memberLimitDecision(action, limit))+ prior := testHandler.Entitlements+ testHandler.Entitlements = stub+ t.Cleanup(func() { testHandler.Entitlements = prior })+ return stub+}++func useMockStorage(t *testing.T) *mockStorage {+ t.Helper()+ store := &mockStorage{}+ prior := testHandler.Storage+ testHandler.Storage = store+ t.Cleanup(func() { testHandler.Storage = prior })+ return store+}++func uploadBytes(t *testing.T, workspaceID, filename string, size int) *testutil.Response {+ t.Helper()+ var body bytes.Buffer+ writer := multipart.NewWriter(&body)+ part, err := writer.CreateFormFile("file", filename)+ if err != nil {+ t.Fatal(err)+ }+ part.Write(bytes.Repeat([]byte("x"), size))+ writer.Close()+ req := httptest.NewRequest(http.MethodPost, "/api/upload-file", &body)+ req.Header.Set("Content-Type", writer.FormDataContentType())+ req.Header.Set("X-User-ID", testUserID)+ req.Header.Set("X-Workspace-ID", workspaceID)+ return testutil.Call(t, testHandler.UploadFile, req)+}++func storageOverageOf(t *testing.T, workspaceID string) memberLimitOverage {+ t.Helper()+ var o memberLimitOverage+ dbfx.QueryRow(t, `+ SELECT COALESCE(MAX(limit_value), 0), COALESCE(MAX(peak_usage), 0),+ COALESCE(SUM(observed_count), 0), COALESCE(SUM(enforced_count), 0)+ FROM entitlement_limit_overage+ WHERE workspace_id = $1 AND gate = 'storage_bytes'`, workspaceID).+ Scan(&o.limit, &o.peak, &o.observed, &o.enforced)+ return o+}++type storageLimitBody struct {+ Code string `json:"code"`+ UsedBytes int64 `json:"used_bytes"`+ LimitBytes int64 `json:"limit_bytes"`+}++func wantStorageLimitReached(t *testing.T, resp *testutil.Response, used, limit int64) {+ t.Helper()+ var body storageLimitBody+ resp.Want(http.StatusForbidden).JSON(&body)+ if body.Code != storageLimitReachedCode || body.UsedBytes != used || body.LimitBytes != limit {+ t.Fatalf("body = %+v, want %s with used %d of %d", body, storageLimitReachedCode, used, limit)+ }+}++func attachmentCount(t *testing.T, workspaceID string) int {+ t.Helper()+ return dbfx.Count(t, `SELECT count(*) FROM attachment WHERE workspace_id = $1`, workspaceID)+}++// A workspace holding 900 of 1000 bytes uploads 200 more: off admits without+// reading anything, observe admits and records, enforce refuses before the+// object is written and records.+func TestUploadFileUnderEachStorageLimitAction(t *testing.T) {+ for _, tc := range []struct {+ action entitlement.Action+ record memberLimitOverage+ }{+ {entitlement.ActionOff, memberLimitOverage{}},+ {entitlement.ActionObserve, memberLimitOverage{limit: 1000, peak: 1100, observed: 1}},+ {entitlement.ActionEnforce, memberLimitOverage{limit: 1000, peak: 1100, enforced: 1}},+ } {+ t.Run(string(tc.action), func(t *testing.T) {+ workspaceID, _ := storageLimitWorkspace(t, 900)+ useStorageLimit(t, workspaceID, tc.action, 1000)+ store := useMockStorage(t)++ resp := uploadBytes(t, workspaceID, "design-v3.fig", 200)+ if tc.action == entitlement.ActionEnforce {+ wantStorageLimitReached(t, resp, 900, 1000)+ if attachmentCount(t, workspaceID) != 1 || len(store.files) != 0 {+ t.Fatalf("refused upload stored something: rows=%d objects=%d", attachmentCount(t, workspaceID), len(store.files))+ }+ } else {+ resp.Want(http.StatusOK)+ if attachmentCount(t, workspaceID) != 2 {+ t.Fatalf("admitted upload rows = %d, want 2", attachmentCount(t, workspaceID))+ }+ }+ if got := storageOverageOf(t, workspaceID); got != tc.record {+ t.Fatalf("overage = %+v, want %+v", got, tc.record)+ }+ })+ }+}++func TestUploadFileWithinStorageLimitRecordsNothing(t *testing.T) {+ workspaceID, _ := storageLimitWorkspace(t, 900)+ useStorageLimit(t, workspaceID, entitlement.ActionEnforce, 1000)+ useMockStorage(t)++ uploadBytes(t, workspaceID, "small.txt", 100).Want(http.StatusOK)+ if got := storageOverageOf(t, workspaceID); got != (memberLimitOverage{}) {+ t.Fatalf("overage = %+v, want none", got)+ }+ // Now exactly at the limit: the next byte is refused.+ wantStorageLimitReached(t, uploadBytes(t, workspaceID, "one.txt", 1), 1000, 1000)+}++// A full workspace keeps every attachment it has: reading one is never checked.+func TestFullWorkspaceStillDownloadsExistingAttachments(t *testing.T) {+ workspaceID, attachmentID := storageLimitWorkspace(t, 5000)+ stub := useStorageLimit(t, workspaceID, entitlement.ActionEnforce, 1000)+ origStorage, origCfg, origSigner := testHandler.Storage, testHandler.cfg, testHandler.CFSigner+ testHandler.Storage = &mockStorageNoCdn{}+ testHandler.cfg.AttachmentDownloadMode = "proxy"+ testHandler.CFSigner = nil+ t.Cleanup(func() {+ testHandler.Storage, testHandler.cfg, testHandler.CFSigner = origStorage, origCfg, origSigner+ })++ req := httptest.NewRequest(http.MethodGet, "/api/attachments/"+attachmentID+"/download-metadata", nil)+ req.Header.Set("X-User-ID", testUserID)+ req.Header.Set("X-Workspace-ID", workspaceID)+ var resp AttachmentResponse+ testutil.Call(t, testHandler.GetAttachmentForDownload, withURLParam(req, "id", attachmentID)).Want(http.StatusOK).JSON(&resp)+ if resp.ID != attachmentID {+ t.Fatalf("download metadata = %+v", resp)+ }+ if calls := stub.Calls(); len(calls) != 0 {+ t.Fatalf("reading an attachment consulted the storage gate: %+v", calls)+ }+}++// Right after an upgrade the cached policy is still the old one. The upload+// re-reads it before refusing and goes through on the new limit.+func TestUploadFileRefreshesPolicyBeforeRefusing(t *testing.T) {+ workspaceID, _ := storageLimitWorkspace(t, 900)+ stub := useStorageLimit(t, workspaceID, entitlement.ActionEnforce, 1000)+ stub.SetRefreshed(uuid.MustParse(workspaceID), entitlement.GateStorageBytes, memberLimitDecision(entitlement.ActionEnforce, 10_000))+ useMockStorage(t)++ uploadBytes(t, workspaceID, "after-upgrade.png", 200).Want(http.StatusOK)+ if len(stub.Refreshes()) != 1 {+ t.Fatalf("refreshes = %d, want 1", len(stub.Refreshes()))+ }+ if got := storageOverageOf(t, workspaceID); got != (memberLimitOverage{}) {+ t.Fatalf("overage = %+v, want none after the upgrade", got)+ }+}++func getStorageUsage(t *testing.T, workspaceID string) StorageUsageResponse {+ t.Helper()+ req := newRequest(http.MethodGet, "/api/workspaces/"+workspaceID+"/storage-usage", nil)+ req.Header.Set("X-Workspace-ID", workspaceID)+ var resp StorageUsageResponse+ testutil.Call(t, testHandler.GetStorageUsage, withURLParam(req, "id", workspaceID)).Want(http.StatusOK).JSON(&resp)+ return resp+}++func TestGetStorageUsage(t *testing.T) {+ workspaceID, _ := storageLimitWorkspace(t, 1000)++ if off := getStorageUsage(t, workspaceID); off.Action != "off" || off.UsedBytes != nil || off.LimitBytes != nil || off.Reached != nil {+ t.Fatalf("without a provider = %+v, want off without figures", off)+ }+ useStorageLimit(t, workspaceID, entitlement.ActionObserve, 1000)+ if got := getStorageUsage(t, workspaceID); got.Action != "observe" || got.UsedBytes == nil || *got.UsedBytes != 1000 ||+ got.LimitBytes == nil || *got.LimitBytes != 1000 || got.Reached != nil {+ t.Fatalf("observed = %+v, want 1000 of 1000 without reached", got)+ }+ useStorageLimit(t, workspaceID, entitlement.ActionEnforce, 1000)+ if got := getStorageUsage(t, workspaceID); got.Action != "enforce" || got.Reached == nil || !*got.Reached {+ t.Fatalf("enforced = %+v, want reached", got)+ }+ useStorageLimit(t, workspaceID, entitlement.ActionEnforce, 1001)+ if got := getStorageUsage(t, workspaceID); got.Reached == nil || *got.Reached {+ t.Fatalf("enforced below the limit = %+v, want reached false", got)+ }+}++func TestGetStorageUsageRefreshesBeforeReportingFull(t *testing.T) {+ workspaceID, _ := storageLimitWorkspace(t, 1000)+ stub := useStorageLimit(t, workspaceID, entitlement.ActionEnforce, 1000)+ stub.SetRefreshed(uuid.MustParse(workspaceID), entitlement.GateStorageBytes, memberLimitDecision(entitlement.ActionEnforce, 100_000))++ got := getStorageUsage(t, workspaceID)+ if got.Reached == nil || *got.Reached || got.LimitBytes == nil || *got.LimitBytes != 100_000 || len(stub.Refreshes()) != 1 {+ t.Fatalf("usage = %+v, refreshes = %d; want the upgraded limit", got, len(stub.Refreshes()))+ }+}++// Usage is summed from the rows, so attachments removed by deleting their+// issue (a database cascade the application never sees) stop counting at once.+func TestStorageUsageDropsWhenAnIssueIsDeleted(t *testing.T) {+ workspaceID, _ := storageLimitWorkspace(t, 100)+ useStorageLimit(t, workspaceID, entitlement.ActionObserve, 1000)+ fx := testutil.New(testPool, workspaceID, testUserID)+ issueID := fx.Issue(t, "Holds a large file")+ fx.Insert(t, "attachment", testutil.Cols{+ "workspace_id": workspaceID, "issue_id": issueID, "uploader_type": "member", "uploader_id": testUserID,+ "filename": "large.bin", "url": "https://cdn.example.com/large.bin",+ "content_type": "application/octet-stream", "size_bytes": 800,+ })+ if got := getStorageUsage(t, workspaceID); got.UsedBytes == nil || *got.UsedBytes != 900 {+ t.Fatalf("before delete = %+v, want 900", got)+ }+ fx.Exec(t, `DELETE FROM issue WHERE id = $1`, issueID)+ if got := getStorageUsage(t, workspaceID); got.UsedBytes == nil || *got.UsedBytes != 100 {+ t.Fatalf("after delete = %+v, want 100", got)+ }+}++// Creating a sub-issue from a comment copies the source attachments. On a+// full workspace it is refused before the sub-issue or any copy exists, and+// the source attachments stay as they were.+func TestCommentSubIssueRefusedWhenCopyWouldExceedStorage(t *testing.T) {+ workspaceID, _ := storageLimitWorkspace(t, 900)+ store := useMockStorage(t)+ fx := testutil.New(testPool, workspaceID, testUserID)+ sourceIssueID := fx.Issue(t, "Source issue")+ commentID := fx.Comment(t, sourceIssueID, "selected context")+ key := "workspaces/" + workspaceID + "/source.txt"+ store.put(key, []byte(strings.Repeat("s", 50)))+ fx.Insert(t, "attachment", testutil.Cols{+ "workspace_id": workspaceID, "issue_id": sourceIssueID, "comment_id": commentID,+ "uploader_type": "member", "uploader_id": testUserID,+ "filename": "source.txt", "url": store.ObjectURL(key), "content_type": "text/plain", "size_bytes": 50,+ })+ dbfx.Cleanup(t, `DELETE FROM issue_source_context WHERE workspace_id = $1`, workspaceID)+ dbfx.Cleanup(t, `DELETE FROM issue_source_context_object_intent WHERE workspace_id = $1`, workspaceID)++ previewReq := newRequest(http.MethodGet, "/api/comments/"+commentID+"/sub-issue-preview", nil)+ previewReq.Header.Set("X-Workspace-ID", workspaceID)+ var preview sourceContextPreviewResponse+ testutil.Call(t, testHandler.PreviewCommentSubIssue, withURLParam(previewReq, "commentId", commentID)).Want(http.StatusOK).JSON(&preview)++ // 950 used; copying 50 more passes a limit of 1000 but not 990.+ useStorageLimit(t, workspaceID, entitlement.ActionEnforce, 990)+ create := func() *testutil.Response {+ req := newRequest(http.MethodPost, "/api/comments/"+commentID+"/sub-issues", map[string]any{+ "mode": "manual", "capture_token": preview.CaptureToken,+ "issue": map[string]any{"title": "Follow-up", "status": "todo", "priority": "none"},+ })+ req.Header.Set("X-Workspace-ID", workspaceID)+ return testutil.Call(t, testHandler.CreateCommentSubIssue, withURLParam(req, "commentId", commentID))+ }+ wantStorageLimitReached(t, create(), 950, 990)+ if issues := dbfx.Count(t, `SELECT count(*) FROM issue WHERE workspace_id = $1`, workspaceID); issues != 1 {+ t.Fatalf("issues = %d, want only the source", issues)+ }+ if copies := dbfx.Count(t, `SELECT count(*) FROM attachment WHERE workspace_id = $1 AND source_context_id IS NOT NULL`, workspaceID); copies != 0 {+ t.Fatalf("copied attachments = %d, want none", copies)+ }+ if _, uploads := store.streamCopyCalls(); uploads != 0 {+ t.Fatalf("stream uploads = %d, want none", uploads)+ }+ if got := storageOverageOf(t, workspaceID); got.enforced != 1 || got.peak != 1000 {+ t.Fatalf("overage = %+v, want one refusal at 1000", got)+ }++ useStorageLimit(t, workspaceID, entitlement.ActionEnforce, 1000)+ var created IssueResponse+ create().Want(http.StatusCreated).JSON(&created)+ if created.ID == "" {+ t.Fatal("sub-issue was not created within the limit")+ }+}++func TestStorageLimitResponseShape(t *testing.T) {+ raw, err := json.Marshal(StorageUsageResponse{Action: "off"})+ if err != nil || string(raw) != `{"action":"off"}` {+ t.Fatalf("off usage = %s, err = %v", raw, err)+ }+}++// A guest cannot read the workspace's storage usage, so a refusal tells it the+// storage is full without the figures.+func TestUploadFileRefusesAGuestWithoutTheFigures(t *testing.T) {+ workspaceID, _ := storageLimitWorkspace(t, 900)+ useStorageLimit(t, workspaceID, entitlement.ActionEnforce, 1000)+ useMockStorage(t)+ guestID := dbfx.User(t, "Storage guest "+uuid.NewString()[:8], "storage-guest-"+uuid.NewString()[:8]+"@multica.ai")+ dbfx.Member(t, workspaceID, guestID, "guest")++ var body bytes.Buffer+ writer := multipart.NewWriter(&body)+ part, err := writer.CreateFormFile("file", "guest.png")+ if err != nil {+ t.Fatal(err)+ }+ part.Write(bytes.Repeat([]byte("x"), 200))+ writer.Close()+ req := httptest.NewRequest(http.MethodPost, "/api/upload-file", &body)+ req.Header.Set("Content-Type", writer.FormDataContentType())+ req.Header.Set("X-User-ID", guestID)+ req.Header.Set("X-Workspace-ID", workspaceID)++ got := testutil.Call(t, testHandler.UploadFile, req).Want(http.StatusForbidden).Map()+ if got["code"] != storageLimitReachedCode {+ t.Fatalf("body = %v, want %s", got, storageLimitReachedCode)+ }+ if _, ok := got["used_bytes"]; ok {+ t.Fatalf("guest refusal carries used_bytes: %v", got)+ }+ if _, ok := got["limit_bytes"]; ok {+ t.Fatalf("guest refusal carries limit_bytes: %v", got)+ }+}diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.goindex 5326cfbc5f..0af3860dc2 100644--- a/server/internal/integrations/channel/engine/session.go+++ b/server/internal/integrations/channel/engine/session.go@@ -7,6 +7,8 @@ import ("log/slog""sort""strings"+ "sync/atomic"+ "time""github.com/google/uuid""github.com/jackc/pgx/v5"@@ -918,9 +920,38 @@ func (s *ChatSession) BindMediaRefsWithResult(ctx context.Context, in BindMediaI// gone, atomically. Either way the reconciler settles the objects.return BindMediaResult{}, fmt.Errorf("commit media: %w", err)}+ if len(in.MediaRefs) > 0 {+ if hook := mediaStoredHook.Load(); hook != nil {+ // The bind's caller has a finish budget of its own; the hook only+ // records, so it gets a short slice of it and gives up quietly.+ hookCtx, cancel := context.WithTimeout(ctx, mediaStoredHookBudget)+ (*hook)(hookCtx, in.WorkspaceID)+ cancel()+ }+ }return result, nil}+// mediaStoredHook runs after channel media becomes attachments. Every channel+// adapter builds its own ChatSession, so the server installs the hook once+// instead of threading it through each one.+var mediaStoredHook atomic.Pointer[func(context.Context, pgtype.UUID)]++// mediaStoredHookBudget bounds the hook, so recording storage use cannot hold+// up the task the channel message is about to start.+const mediaStoredHookBudget = time.Second++// SetMediaStoredHook installs fn to run after a channel message's media is+// stored as attachments in a workspace (MUL-9489: the storage limit records,+// but never refuses, these files). nil removes it. fn must not fail the bind.+func SetMediaStoredHook(fn func(ctx context.Context, workspaceID pgtype.UUID)) {+ if fn == nil {+ mediaStoredHook.Store(nil)+ return+ }+ mediaStoredHook.Store(&fn)+}+func (s *ChatSession) clearMediaPending(ctx context.Context, q SessionQueries, in BindMediaInput) error {if err := q.ClearChatMessageChannelMediaPending(ctx, db.ClearChatMessageChannelMediaPendingParams{ID: in.MessageID,diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.goindex 3d6431a209..6841a05d63 100644--- a/server/internal/integrations/channel/engine/session_test.go+++ b/server/internal/integrations/channel/engine/session_test.go@@ -1412,3 +1412,48 @@ func TestAppendUserMessage_ReplyTargetSenderNullWhenAbsent(t *testing.T) {t.Errorf("absent sender must be NULL; got %+v", f.lastContextReply.LastSenderID)}}++// Channel media is never refused for storage; the server's hook only records+// it, once the attachments are committed (MUL-9489).+func TestBindMediaRefs_RunsMediaStoredHookAfterCommit(t *testing.T) {+ var stored []pgtype.UUID+ var deadlines []bool+ SetMediaStoredHook(func(ctx context.Context, workspaceID pgtype.UUID) {+ stored = append(stored, workspaceID)+ _, ok := ctx.Deadline()+ deadlines = append(deadlines, ok)+ })+ t.Cleanup(func() { SetMediaStoredHook(nil) })++ f := newFake()+ s := newTestSession(f)+ res, err := s.AppendUserMessage(context.Background(), AppendInput{SessionID: uid(1), Sender: uid(7), Body: "[File]", MessageID: "om_file"})+ if err != nil {+ t.Fatalf("AppendUserMessage: %v", err)+ }+ if err := s.BindMediaRefs(context.Background(), BindMediaInput{+ MessageID: res.MessageID, SessionID: uid(1), WorkspaceID: uid(9), Sender: uid(7), Body: "[File]",+ MediaRefs: []channel.MediaRef{{+ Type: channel.MsgTypeFile, StorageKey: "slack/f.pdf", StorageURL: "https://cdn.example.test/slack/f.pdf",+ Filename: "f.pdf", MimeType: "application/pdf", SizeBytes: 10,+ }},+ }); err != nil {+ t.Fatalf("BindMediaRefs: %v", err)+ }+ if len(stored) != 1 || stored[0] != uid(9) {+ t.Fatalf("hook calls = %+v, want one for the workspace", stored)+ }+ // The hook runs on a bounded budget so it cannot hold up the task start.+ if !deadlines[0] {+ t.Fatal("hook context has no deadline")+ }+ // A bind without media stores nothing and records nothing.+ if err := s.BindMediaRefs(context.Background(), BindMediaInput{+ MessageID: res.MessageID, SessionID: uid(1), WorkspaceID: uid(9), Sender: uid(7), Body: "[File]",+ }); err != nil {+ t.Fatalf("BindMediaRefs without media: %v", err)+ }+ if len(stored) != 1 {+ t.Fatalf("hook calls = %d after an empty bind, want 1", len(stored))+ }+}diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.goindex 9a19eb7670..180228891b 100644--- a/server/internal/metrics/business.go+++ b/server/internal/metrics/business.go@@ -76,6 +76,9 @@ type BusinessMetrics struct {entitlementDecision *prometheus.CounterVecentitlementVersionRegression prometheus.CounterautopilotQuotaDecision *prometheus.CounterVec+ storageQuotaSum *prometheus.CounterVec+ storageQuotaSumDuration *prometheus.HistogramVec+ storageQuotaDecision *prometheus.CounterVec// agentRuntimeLookup counts logical agent_runtime lookups by product// source — one increment per requested runtime id, whether that id was@@ -297,6 +300,18 @@ func NewBusinessMetrics() *BusinessMetrics {Namespace: "multica", Subsystem: "autopilot_quota", Name: "decision_total",Help: "Total autopilot quota admission outcomes.",}, metricLabels("multica_autopilot_quota_decision_total")),+ storageQuotaSum: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica", Subsystem: "storage_quota", Name: "sum_total",+ Help: "Total attachment storage usage sums by source and result (ok, timeout, error).",+ }, metricLabels("multica_storage_quota_sum_total")),+ storageQuotaSumDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{+ Namespace: "multica", Subsystem: "storage_quota", Name: "sum_duration_seconds",+ Help: "Duration of attachment storage usage sums.", Buckets: chatClaimResumeQueryDurationBuckets,+ }, metricLabels("multica_storage_quota_sum_duration_seconds")),+ storageQuotaDecision: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica", Subsystem: "storage_quota", Name: "decision_total",+ Help: "Total attachment storage limit outcomes.",+ }, metricLabels("multica_storage_quota_decision_total")),agentRuntimeLookup: prometheus.NewCounterVec(prometheus.CounterOpts{Namespace: "multica", Subsystem: "agent_runtime", Name: "lookup_total",Help: "Total logical agent_runtime lookups by product source and outcome (one per requested id, not per SQL query).",@@ -365,6 +380,9 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {m.entitlementDecision,m.entitlementVersionRegression,m.autopilotQuotaDecision,+ m.storageQuotaSum,+ m.storageQuotaSumDuration,+ m.storageQuotaDecision,m.agentRuntimeLookup,m.issueMetadataMutation,m.issueMetadataMutationDuration,@@ -467,6 +485,49 @@ func (m *BusinessMetrics) RecordAutopilotQuotaDecision(action, source, result stm.autopilotQuotaDecision.WithLabelValues(action, source, result).Inc()}+func normalizeStorageQuotaSource(source string) string {+ switch source {+ case "upload", "sub_issue", "channel", "usage":+ return source+ default:+ return "other"+ }+}++// RecordStorageQuotaSum records one attachment storage usage sum.+func (m *BusinessMetrics) RecordStorageQuotaSum(source, result string, durationSeconds float64) {+ if m == nil {+ return+ }+ switch result {+ case "ok", "timeout", "error":+ default:+ result = "error"+ }+ source = normalizeStorageQuotaSource(source)+ m.storageQuotaSum.WithLabelValues(source, result).Inc()+ m.storageQuotaSumDuration.WithLabelValues(source).Observe(durationSeconds)+}++// RecordStorageQuotaDecision records one storage limit outcome: admitted,+// observed, rejected, or fail_open.+func (m *BusinessMetrics) RecordStorageQuotaDecision(action, source, result string) {+ if m == nil {+ return+ }+ switch action {+ case "observe", "enforce":+ default:+ action = "other"+ }+ switch result {+ case "admitted", "observed", "rejected", "fail_open":+ default:+ result = "other"+ }+ m.storageQuotaDecision.WithLabelValues(action, normalizeStorageQuotaSource(source), result).Inc()+}+func (m *BusinessMetrics) RecordRuntimeGCDeleted() {if m == nil {returndiff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.goindex 9f943e18a0..26edeaf742 100644--- a/server/internal/metrics/business_test.go+++ b/server/internal/metrics/business_test.go@@ -203,6 +203,8 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {m.RecordEntitlementDecision("autopilot_runs", "observe", "cache_fresh")m.RecordEntitlementVersionRegression()m.RecordAutopilotQuotaDecision("observe", "manual", "admitted")+ m.RecordStorageQuotaSum("upload", "ok", 0.002)+ m.RecordStorageQuotaDecision("enforce", "upload", "rejected")m.ObserveRuntimeSweepStage(RuntimeSweepStageLiveness, time.Second, 2, 1)families, err := registry.Gather()diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex 1405f67656..fe20515d01 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -109,6 +109,9 @@ var businessMetricLabels = map[string][]string{"multica_entitlement_decision_total": {labelGate, labelAction, labelReason},"multica_entitlement_version_regression_total": {},"multica_autopilot_quota_decision_total": {labelAction, labelSource, labelResult},+ "multica_storage_quota_sum_total": {labelSource, labelResult},+ "multica_storage_quota_sum_duration_seconds": {labelSource},+ "multica_storage_quota_decision_total": {labelAction, labelSource, labelResult},}var forbiddenMetricLabels = map[string]struct{}{diff --git a/server/internal/service/storage_quota.go b/server/internal/service/storage_quota.gonew file mode 100644index 0000000000..654327a7f9--- /dev/null+++ b/server/internal/service/storage_quota.go@@ -0,0 +1,276 @@+package service++import (+ "context"+ "errors"+ "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"+)++// Attachment storage limit (MUL-9489).+//+// Cloud sends the bytes a workspace may hold through the "storage_bytes"+// gate. Usage is not kept in a counter: it is the sum of the workspace's+// attachment rows, read on demand from a covering index. Cascade deletes are+// therefore reflected at once and nothing needs a backfill. The sum runs only+// while the gate is observe or enforce; off, which is also the self-hosted+// behavior, reads nothing.+//+// The check is a soft limit. It takes no lock, so uploads that run at the+// same moment the workspace crosses its limit all pass: the overshoot is at+// most what was in flight then. Reads, downloads, thumbnails and deletes are+// never checked, so a full workspace keeps every attachment it has.++// DefaultStorageSumTimeout bounds the usage sum on an upload. A sum that runs+// longer is abandoned and the upload admitted, so a slow query cannot hold+// uploads or exhaust the pool before failing open.+const DefaultStorageSumTimeout = 300 * time.Millisecond++// Storage quota sources and results are the bounded metric labels.+const (+ StorageSourceUpload = "upload"+ StorageSourceSubIssue = "sub_issue"+ StorageSourceChannel = "channel"+ StorageSourceUsage = "usage"++ storageSumOK = "ok"+ storageSumTimeout = "timeout"+ storageSumError = "error"+)++// StorageQuotaMetrics accepts only bounded labels. Workspace identifiers and+// byte counts must never be metric labels.+type StorageQuotaMetrics interface {+ RecordStorageQuotaSum(source, result string, durationSeconds float64)+ RecordStorageQuotaDecision(action, source, result string)+}++// StorageUsageQuerier sums a workspace's attachment bytes.+type StorageUsageQuerier interface {+ SumWorkspaceAttachmentBytes(ctx context.Context, workspaceID pgtype.UUID) (int64, error)+}++// StorageLimitReachedError is returned when an enforced storage limit refuses+// new bytes. Used is what the workspace held when it was refused.+type StorageLimitReachedError struct {+ Used int64+ Limit int64+}++func (e *StorageLimitReachedError) Error() string {+ return "workspace has reached its attachment storage limit"+}++// StorageQuota checks the storage_bytes gate. A zero value with no+// Entitlements admits everything without reading the database.+type StorageQuota struct {+ Sums StorageUsageQuerier+ Entitlements entitlement.Provider+ Overages EntitlementOverages+ Metrics StorageQuotaMetrics+ // SumTimeout defaults to DefaultStorageSumTimeout.+ SumTimeout time.Duration+ now func() time.Time+}++// StorageUsage is the storage limit as clients render it. Limit is set only+// while a limit applies; Used also needs the sum to have been read in time;+// Reached is set only under enforce, because observe never refuses an upload.+type StorageUsage struct {+ Action entitlement.Action+ Used *int64+ Limit *int64+ Reached *bool+}++// Admit decides whether bytes more may be stored in the workspace. Under+// enforce it refuses with *StorageLimitReachedError when the workspace would+// go past its limit, after re-reading Cloud's policy so a workspace that has+// just upgraded is not refused on a cached one. Under observe it admits and+// records the attempt. Every failure to decide admits.+func (q StorageQuota) Admit(ctx context.Context, workspaceID pgtype.UUID, bytes int64, source string) error {+ decision, ok := q.gate(ctx, workspaceID)+ if !ok {+ return nil+ }+ used, ok := q.sum(ctx, workspaceID, source)+ if !ok {+ q.recordDecision(decision.Gate.Action, source, "fail_open")+ return nil+ }+ attempted := used + max(bytes, 0)+ if attempted <= gateLimit(decision) {+ q.recordDecision(decision.Gate.Action, source, "admitted")+ return nil+ }+ if decision.Gate.Action == entitlement.ActionEnforce {+ if refresher, isRefresher := q.Entitlements.(entitlement.Refresher); isRefresher {+ decision = refresher.RefreshGate(ctx, uuid.UUID(workspaceID.Bytes), entitlement.GateStorageBytes)+ if !storageGateActive(decision) || attempted <= gateLimit(decision) {+ q.recordDecision(decision.Gate.Action, source, "admitted")+ return nil+ }+ }+ }+ q.recordOverage(ctx, workspaceID, decision, attempted)+ if decision.Gate.Action == entitlement.ActionEnforce {+ q.recordDecision(decision.Gate.Action, source, "rejected")+ return &StorageLimitReachedError{Used: used, Limit: gateLimit(decision)}+ }+ q.recordDecision(decision.Gate.Action, source, "observed")+ return nil+}++// RecordStored is for bytes already written without a check: files that+// arrive through a messaging channel are never refused, because the sender+// would lose them with no way to see why. It records the workspace as over+// its limit, as an admitted attempt, when the stored bytes put it there.+func (q StorageQuota) RecordStored(ctx context.Context, workspaceID pgtype.UUID, source string) {+ decision, ok := q.gate(ctx, workspaceID)+ if !ok {+ return+ }+ used, ok := q.sum(ctx, workspaceID, source)+ if !ok || used <= gateLimit(decision) {+ return+ }+ // The bytes were admitted whatever the action, so they count as observed.+ decision.Gate.Action = entitlement.ActionObserve+ q.recordOverage(ctx, workspaceID, decision, used)+ q.recordDecision(entitlement.ActionObserve, source, "observed")+}++// Usage reports the workspace's storage limit and use. Before reporting a+// full workspace it re-reads Cloud's policy, as Admit does, so a client is not+// offered an upgrade the workspace already has. A sum that fails or runs past+// its timeout still reports the limit, with Used and Reached nil, so a client+// can say usage is unavailable instead of hiding the limit.+func (q StorageQuota) Usage(ctx context.Context, workspaceID pgtype.UUID) StorageUsage {+ decision, ok := q.gate(ctx, workspaceID)+ if !ok {+ return StorageUsage{Action: entitlement.ActionOff}+ }+ used, err := q.usageSum(ctx, workspaceID)+ if err != nil {+ limit := gateLimit(decision)+ return StorageUsage{Action: decision.Gate.Action, Limit: &limit}+ }+ if decision.Gate.Action == entitlement.ActionEnforce && used >= gateLimit(decision) {+ if refresher, isRefresher := q.Entitlements.(entitlement.Refresher); isRefresher {+ decision = refresher.RefreshGate(ctx, uuid.UUID(workspaceID.Bytes), entitlement.GateStorageBytes)+ if !storageGateActive(decision) {+ return StorageUsage{Action: entitlement.ActionOff}+ }+ }+ }+ limit := gateLimit(decision)+ out := StorageUsage{Action: decision.Gate.Action, Used: &used, Limit: &limit}+ if decision.Gate.Action == entitlement.ActionEnforce {+ reached := used >= limit+ out.Reached = &reached+ }+ return out+}++// usageSum is the billing page's read, bounded by the same timeout.+func (q StorageQuota) usageSum(ctx context.Context, workspaceID pgtype.UUID) (int64, error) {+ started := time.Now()+ used, result, err := q.timedSum(ctx, workspaceID)+ q.recordSum(StorageSourceUsage, result, time.Since(started).Seconds())+ return used, err+}++func (q StorageQuota) gate(ctx context.Context, workspaceID pgtype.UUID) (entitlement.Decision, bool) {+ if q.Entitlements == nil || q.Sums == nil || !workspaceID.Valid {+ return entitlement.Decision{}, false+ }+ decision := q.Entitlements.Gate(ctx, uuid.UUID(workspaceID.Bytes), entitlement.GateStorageBytes)+ return decision, storageGateActive(decision)+}++func storageGateActive(decision entitlement.Decision) bool {+ action := decision.Gate.Action+ return (action == entitlement.ActionObserve || action == entitlement.ActionEnforce) &&+ decision.Gate.Limit != nil && *decision.Gate.Limit >= 0+}++func gateLimit(decision entitlement.Decision) int64 { return int64(*decision.Gate.Limit) }++// sum reads the workspace's used bytes for an admission. ok=false means the+// sum timed out or failed and the caller must admit.+func (q StorageQuota) sum(ctx context.Context, workspaceID pgtype.UUID, source string) (int64, bool) {+ started := time.Now()+ used, result, err := q.timedSum(ctx, workspaceID)+ q.recordSum(source, result, time.Since(started).Seconds())+ if err != nil {+ slog.WarnContext(ctx, "storage usage sum failed; admitting",+ "workspace_id", util.UUIDToString(workspaceID), "source", source, "result", result, "error", err)+ return 0, false+ }+ return used, true+}++func (q StorageQuota) timedSum(ctx context.Context, workspaceID pgtype.UUID) (int64, string, error) {+ timeout := q.SumTimeout+ if timeout <= 0 {+ timeout = DefaultStorageSumTimeout+ }+ sumCtx, cancel := context.WithTimeout(ctx, timeout)+ defer cancel()+ used, err := q.Sums.SumWorkspaceAttachmentBytes(sumCtx, workspaceID)+ switch {+ case err == nil:+ return used, storageSumOK, nil+ case ctx.Err() == nil && errors.Is(sumCtx.Err(), context.DeadlineExceeded):+ return 0, storageSumTimeout, err+ default:+ return 0, storageSumError, err+ }+}++func (q StorageQuota) recordOverage(ctx context.Context, workspaceID pgtype.UUID, decision entitlement.Decision, attempted int64) {+ if q.Overages.Queries == nil {+ return+ }+ now := time.Now+ if q.now != nil {+ now = q.now+ }+ start, end := StorageLimitPeriod(now())+ q.Overages.Record(ctx, LimitExceededAttempt{+ WorkspaceID: workspaceID,+ Gate: entitlement.GateStorageBytes,+ Action: decision.Gate.Action,+ PeriodStart: start,+ PeriodEnd: end,+ Limit: gateLimit(decision),+ AttemptedUsage: attempted,+ })+}++// StorageLimitPeriod groups storage over-limit records by UTC calendar month.+// The gate has no period; the month only buckets the records, so how many+// workspaces reach the limit reads month by month like the other limits.+func StorageLimitPeriod(now time.Time) (time.Time, time.Time) {+ now = now.UTC()+ start := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)+ return start, start.AddDate(0, 1, 0)+}++func (q StorageQuota) recordSum(source, result string, seconds float64) {+ if q.Metrics != nil {+ q.Metrics.RecordStorageQuotaSum(source, result, seconds)+ }+}++func (q StorageQuota) recordDecision(action entitlement.Action, source, result string) {+ if q.Metrics != nil {+ q.Metrics.RecordStorageQuotaDecision(string(action), source, result)+ }+}diff --git a/server/internal/service/storage_quota_test.go b/server/internal/service/storage_quota_test.gonew file mode 100644index 0000000000..e6b0e6982c--- /dev/null+++ b/server/internal/service/storage_quota_test.go@@ -0,0 +1,198 @@+package service++import (+ "context"+ "errors"+ "sync"+ "testing"+ "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/entitlement/entitlementtest"+)++type fakeStorageSums struct {+ used int64+ err error+ block bool+ calls int+}++func (f *fakeStorageSums) SumWorkspaceAttachmentBytes(ctx context.Context, _ pgtype.UUID) (int64, error) {+ f.calls+++ if f.block {+ <-ctx.Done()+ return 0, ctx.Err()+ }+ return f.used, f.err+}++type fakeStorageMetrics struct {+ mu sync.Mutex+ sums []string+ decisions []string+}++func (m *fakeStorageMetrics) RecordStorageQuotaSum(source, result string, _ float64) {+ m.mu.Lock()+ defer m.mu.Unlock()+ m.sums = append(m.sums, source+":"+result)+}++func (m *fakeStorageMetrics) RecordStorageQuotaDecision(action, source, result string) {+ m.mu.Lock()+ defer m.mu.Unlock()+ m.decisions = append(m.decisions, action+":"+source+":"+result)+}++func storageDecision(action entitlement.Action, limit int) entitlement.Decision {+ gate := entitlement.Gate{Action: action}+ if action != entitlement.ActionOff {+ gate.Limit = &limit+ }+ return entitlement.Decision{Gate: gate}+}++func newTestStorageQuota(used int64, action entitlement.Action, limit int) (StorageQuota, *fakeStorageSums, *entitlementtest.Stub, pgtype.UUID) {+ id := uuid.New()+ stub := entitlementtest.New()+ stub.Set(id, entitlement.GateStorageBytes, storageDecision(action, limit))+ sums := &fakeStorageSums{used: used}+ return StorageQuota{Sums: sums, Entitlements: stub, Metrics: &fakeStorageMetrics{}}, sums, stub, pgtype.UUID{Bytes: id, Valid: true}+}++func TestStorageQuotaOffReadsNothing(t *testing.T) {+ q, sums, _, ws := newTestStorageQuota(5000, entitlement.ActionOff, 0)+ if err := q.Admit(context.Background(), ws, 100, StorageSourceUpload); err != nil {+ t.Fatalf("off admit = %v", err)+ }+ q.RecordStored(context.Background(), ws, StorageSourceChannel)+ if usage := q.Usage(context.Background(), ws); usage.Action != entitlement.ActionOff || usage.Used != nil {+ t.Fatalf("off usage = %+v", usage)+ }+ if sums.calls != 0 {+ t.Fatalf("off summed %d times, want none", sums.calls)+ }+}++// Self-hosted: no provider at all.+func TestStorageQuotaWithoutProviderAdmitsEverything(t *testing.T) {+ sums := &fakeStorageSums{used: 1 << 40}+ q := StorageQuota{Sums: sums}+ ws := pgtype.UUID{Bytes: uuid.New(), Valid: true}+ if err := q.Admit(context.Background(), ws, 1<<30, StorageSourceUpload); err != nil || sums.calls != 0 {+ t.Fatalf("admit = %v, sums = %d", err, sums.calls)+ }+}++func TestStorageQuotaActions(t *testing.T) {+ for _, tc := range []struct {+ name string+ action entitlement.Action+ bytes int64+ wantErr bool+ }{+ {"observe over", entitlement.ActionObserve, 200, false},+ {"enforce within", entitlement.ActionEnforce, 100, false},+ {"enforce over", entitlement.ActionEnforce, 101, true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ q, _, _, ws := newTestStorageQuota(900, tc.action, 1000)+ err := q.Admit(context.Background(), ws, tc.bytes, StorageSourceUpload)+ var reached *StorageLimitReachedError+ if gotErr := errors.As(err, &reached); gotErr != tc.wantErr {+ t.Fatalf("admit = %v, want refused %v", err, tc.wantErr)+ }+ if reached != nil && (reached.Used != 900 || reached.Limit != 1000) {+ t.Fatalf("refusal = %+v", reached)+ }+ })+ }+}++func TestStorageQuotaRefreshesBeforeRefusing(t *testing.T) {+ q, _, stub, ws := newTestStorageQuota(900, entitlement.ActionEnforce, 1000)+ stub.SetRefreshed(uuid.UUID(ws.Bytes), entitlement.GateStorageBytes, storageDecision(entitlement.ActionEnforce, 5000))+ if err := q.Admit(context.Background(), ws, 500, StorageSourceUpload); err != nil {+ t.Fatalf("admit after upgrade = %v", err)+ }+ if len(stub.Refreshes()) != 1 {+ t.Fatalf("refreshes = %d, want 1", len(stub.Refreshes()))+ }+ // Within the limit nothing is refreshed.+ if err := q.Admit(context.Background(), ws, 1, StorageSourceUpload); err != nil || len(stub.Refreshes()) != 1 {+ t.Fatalf("admit = %v, refreshes = %d", err, len(stub.Refreshes()))+ }+}++// A sum that runs past its timeout admits the upload and is counted, so a+// slow query never holds uploads.+func TestStorageQuotaSumTimeoutFailsOpen(t *testing.T) {+ q, sums, _, ws := newTestStorageQuota(0, entitlement.ActionEnforce, 1)+ sums.block = true+ q.SumTimeout = 20 * time.Millisecond+ metrics := q.Metrics.(*fakeStorageMetrics)++ started := time.Now()+ if err := q.Admit(context.Background(), ws, 1<<20, StorageSourceUpload); err != nil {+ t.Fatalf("timed-out admit = %v, want admitted", err)+ }+ if elapsed := time.Since(started); elapsed > time.Second {+ t.Fatalf("admit took %s, want about the timeout", elapsed)+ }+ if len(metrics.sums) != 1 || metrics.sums[0] != "upload:timeout" ||+ len(metrics.decisions) != 1 || metrics.decisions[0] != "enforce:upload:fail_open" {+ t.Fatalf("metrics = %+v / %+v", metrics.sums, metrics.decisions)+ }+}++func TestStorageQuotaSumErrorFailsOpen(t *testing.T) {+ q, sums, _, ws := newTestStorageQuota(0, entitlement.ActionEnforce, 1)+ sums.err = errors.New("connection reset")+ if err := q.Admit(context.Background(), ws, 1<<20, StorageSourceUpload); err != nil {+ t.Fatalf("errored admit = %v, want admitted", err)+ }+ if got := q.Metrics.(*fakeStorageMetrics).sums; len(got) != 1 || got[0] != "upload:error" {+ t.Fatalf("sum metrics = %+v", got)+ }+ // The billing read keeps the limit and leaves usage unknown.+ if usage := q.Usage(context.Background(), ws); usage.Action != entitlement.ActionEnforce ||+ usage.Limit == nil || *usage.Limit != 1 || usage.Used != nil || usage.Reached != nil {+ t.Fatalf("usage after a failed sum = %+v, want the limit without figures", usage)+ }+}++// Channel files are stored before anything is checked and never refused; a+// workspace they put over its limit is recorded as admitted.+func TestStorageQuotaRecordStoredNeverRefuses(t *testing.T) {+ q, sums, _, ws := newTestStorageQuota(1500, entitlement.ActionEnforce, 1000)+ q.RecordStored(context.Background(), ws, StorageSourceChannel)+ if sums.calls != 1 {+ t.Fatalf("sums = %d, want 1", sums.calls)+ }+ if got := q.Metrics.(*fakeStorageMetrics).decisions; len(got) != 1 || got[0] != "observe:channel:observed" {+ t.Fatalf("decisions = %+v", got)+ }+}++func TestStorageLimitPeriodIsTheUTCMonth(t *testing.T) {+ start, end := StorageLimitPeriod(time.Date(2026, 11, 30, 23, 0, 0, 0, time.FixedZone("x", -3*3600)))+ if !start.Equal(time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC)) || !end.Equal(time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC)) {+ t.Fatalf("period = %s..%s", start, end)+ }+}++// A sum that runs past its timeout on the billing read reports the limit with+// usage unknown, rather than failing the whole read.+func TestStorageQuotaUsageTimeoutKeepsTheLimit(t *testing.T) {+ q, sums, _, ws := newTestStorageQuota(0, entitlement.ActionObserve, 1000)+ sums.block = true+ q.SumTimeout = 20 * time.Millisecond+ usage := q.Usage(context.Background(), ws)+ if usage.Action != entitlement.ActionObserve || usage.Limit == nil || *usage.Limit != 1000 || usage.Used != nil {+ t.Fatalf("usage = %+v, want observe 1000 with usage unknown", usage)+ }+}diff --git a/server/migrations/708_attachment_workspace_size_idx.down.sql b/server/migrations/708_attachment_workspace_size_idx.down.sqlnew file mode 100644index 0000000000..fb19b8c65b--- /dev/null+++ b/server/migrations/708_attachment_workspace_size_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_attachment_workspace_size;diff --git a/server/migrations/708_attachment_workspace_size_idx.up.sql b/server/migrations/708_attachment_workspace_size_idx.up.sqlnew file mode 100644index 0000000000..1b02a137d7--- /dev/null+++ b/server/migrations/708_attachment_workspace_size_idx.up.sql@@ -0,0 +1,7 @@+-- Attachment storage limit (MUL-9489): the workspace's used bytes are summed+-- on demand rather than kept in a counter, so cascade deletes are reflected at+-- once and nothing needs a backfill. Carrying size_bytes in the index lets the+-- sum run as an index-only scan. It also serves every query the plain+-- workspace_id index served; 709 drops that one.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_attachment_workspace_size+ ON attachment (workspace_id) INCLUDE (size_bytes);diff --git a/server/migrations/709_drop_attachment_workspace_index.down.sql b/server/migrations/709_drop_attachment_workspace_index.down.sqlnew file mode 100644index 0000000000..76c74917cc--- /dev/null+++ b/server/migrations/709_drop_attachment_workspace_index.down.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_attachment_workspace ON attachment (workspace_id);diff --git a/server/migrations/709_drop_attachment_workspace_index.up.sql b/server/migrations/709_drop_attachment_workspace_index.up.sqlnew file mode 100644index 0000000000..4fb4764a2b--- /dev/null+++ b/server/migrations/709_drop_attachment_workspace_index.up.sql@@ -0,0 +1,3 @@+-- idx_attachment_workspace_size (708) has the same key and covers every+-- lookup this index served.+DROP INDEX CONCURRENTLY IF EXISTS idx_attachment_workspace;diff --git a/server/pkg/db/generated/attachment.sql.go b/server/pkg/db/generated/attachment.sql.goindex 3e6b6cb36f..6e3eb359e7 100644--- a/server/pkg/db/generated/attachment.sql.go+++ b/server/pkg/db/generated/attachment.sql.go@@ -1476,3 +1476,19 @@ func (q *Queries) ReplaceCommentAttachments(ctx context.Context, arg ReplaceComm}return result.RowsAffected(), nil}++const sumWorkspaceAttachmentBytes = `-- name: SumWorkspaceAttachmentBytes :one+SELECT COALESCE(SUM(size_bytes), 0)::bigint AS used_bytes+FROM attachment+WHERE workspace_id = $1+`++// Attachment bytes a workspace holds, for its storage limit (MUL-9489). Every+// row counts, whatever owns it; thumbnails are not attachment rows. An+// index-only scan on idx_attachment_workspace_size.+func (q *Queries) SumWorkspaceAttachmentBytes(ctx context.Context, workspaceID pgtype.UUID) (int64, error) {+ row := q.db.QueryRow(ctx, sumWorkspaceAttachmentBytes, workspaceID)+ var used_bytes int64+ err := row.Scan(&used_bytes)+ return used_bytes, err+}diff --git a/server/pkg/db/queries/attachment.sql b/server/pkg/db/queries/attachment.sqlindex 964b059ad7..e218e8cb1e 100644--- a/server/pkg/db/queries/attachment.sql+++ b/server/pkg/db/queries/attachment.sql@@ -374,3 +374,11 @@ ORDER BY id;DELETE FROM attachmentWHERE workspace_id = sqlc.arg(workspace_id)AND source_context_id IS NOT NULL;++-- name: SumWorkspaceAttachmentBytes :one+-- Attachment bytes a workspace holds, for its storage limit (MUL-9489). Every+-- row counts, whatever owns it; thumbnails are not attachment rows. An+-- index-only scan on idx_attachment_workspace_size.+SELECT COALESCE(SUM(size_bytes), 0)::bigint AS used_bytes+FROM attachment+WHERE workspace_id = sqlc.arg(workspace_id);