Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(tenant): honor default storage quota across creation paths (#3213)

frodleTian6c9a1176c519
diff --git a/.env.example b/.env.example
index 1e81a1535..31670e25e 100644
--- a/.env.example
+++ b/.env.example
@@ -637,6 +637,9 @@ SYSTEM_SIGNING_KEY=
# WEKNORA_TENANT_AUTO_CREATE_API_KEY=false
# 新建空间默认存储配额(GB,默认 10)。
# WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB=10
+# 新建空间默认存储配额(MB,含注册自动创建的个人空间)。正数优先于 GB;0 或负数沿用 GB。
+# 每个设置均按系统设置 DB > 环境变量 > 内置默认值解析;只影响之后新建的空间。
+# WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_MB=0
# 空间邀请链接 TTL(Go duration,默认 168h=7 天)。
# WEKNORA_INVITATION_TTL=168h
# 全局开关:邀请已注册用户时直接加入空间。默认 false,可在系统设置页修改。
diff --git a/docker-compose.yml b/docker-compose.yml
index d3c026d18..aa1025ee3 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -143,6 +143,7 @@ services:
- WEKNORA_TENANT_ENABLE_CROSS_TENANT_ACCESS=${WEKNORA_TENANT_ENABLE_CROSS_TENANT_ACCESS:-false}
# 新建空间默认存储配额(GB,默认 10)
- WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB=${WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB:-10}
+ - WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_MB=${WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_MB:-0}
# 空间邀请链接 TTL(Go duration,默认 168h=7 天)
- WEKNORA_INVITATION_TTL=${WEKNORA_INVITATION_TTL:-168h}
# 审计日志保留天数(0 禁用清理,默认 90)
diff --git a/docs/docs.go b/docs/docs.go
index c1ec5bac8..2311327d5 100644
--- a/docs/docs.go
+++ b/docs/docs.go
@@ -20895,7 +20895,7 @@ const docTemplate = `{
},
"/system/admin/tenants/apply-default-storage-quota": {
"post": {
- "description": "Reads the current value of ` + "`" + `tenant.default_storage_quota_gb` + "`" + `\n(3-tier resolver: DB \u003e ENV \u003e default) and writes that many\nGiB into storage_quota for every row in tenants. Bypasses\nthe per-workspace PUT whitelist, which forbids storage_quota\nedits by Owners. SystemAdmin only.\nIdempotent — running twice with the same setting is a no-op.",
+ "description": "Resolves the MB override or legacy GB default (DB \u003e ENV \u003e default per setting)\nand writes the effective byte quota to every existing workspace. Bypasses\nthe per-workspace PUT whitelist, which forbids storage_quota\nedits by Owners. SystemAdmin only.\nIdempotent — running twice with the same setting is a no-op.",
"produces": [
"application/json"
],
diff --git a/docs/swagger.json b/docs/swagger.json
index 210aa56ea..c1cf05f12 100644
--- a/docs/swagger.json
+++ b/docs/swagger.json
@@ -20888,7 +20888,7 @@
},
"/system/admin/tenants/apply-default-storage-quota": {
"post": {
- "description": "Reads the current value of `tenant.default_storage_quota_gb`\n(3-tier resolver: DB \u003e ENV \u003e default) and writes that many\nGiB into storage_quota for every row in tenants. Bypasses\nthe per-workspace PUT whitelist, which forbids storage_quota\nedits by Owners. SystemAdmin only.\nIdempotent — running twice with the same setting is a no-op.",
+ "description": "Resolves the MB override or legacy GB default (DB \u003e ENV \u003e default per setting)\nand writes the effective byte quota to every existing workspace. Bypasses\nthe per-workspace PUT whitelist, which forbids storage_quota\nedits by Owners. SystemAdmin only.\nIdempotent — running twice with the same setting is a no-op.",
"produces": [
"application/json"
],
diff --git a/docs/swagger.yaml b/docs/swagger.yaml
index 1b7c38757..226bac9de 100644
--- a/docs/swagger.yaml
+++ b/docs/swagger.yaml
@@ -27991,9 +27991,8 @@ paths:
/system/admin/tenants/apply-default-storage-quota:
post:
description: |-
- Reads the current value of `tenant.default_storage_quota_gb`
- (3-tier resolver: DB > ENV > default) and writes that many
- GiB into storage_quota for every row in tenants. Bypasses
+ Resolves the MB override or legacy GB default (DB > ENV > default per setting)
+ and writes the effective byte quota to every existing workspace. Bypasses
the per-workspace PUT whitelist, which forbids storage_quota
edits by Owners. SystemAdmin only.
Idempotent — running twice with the same setting is a no-op.
diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts
index 6027e39e8..ae97ebd2d 100644
--- a/frontend/src/api/system/index.ts
+++ b/frontend/src/api/system/index.ts
@@ -531,7 +531,7 @@ export interface ApplyDefaultStorageQuotaResult {
}
/**
- * Apply the current `tenant.default_storage_quota_gb` setting to every
+ * Apply the effective MB/GB default storage quota to every
* existing tenant. Reads the resolved setting server-side (DB > ENV >
* default), then writes that quota to every row. SystemAdmin only.
*
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 23fc37768..c50aab4e0 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -4965,6 +4965,7 @@ export default {
max_owned_per_user: 'Max workspaces owned per user',
self_service_creation_enabled: 'Allow self-service workspace creation',
default_storage_quota_gb: 'Default storage quota for new workspaces (GB)',
+ default_storage_quota_mb: 'Default storage quota for new workspaces (MB)',
auto_create_api_key: 'Automatically create an API key for new workspaces',
auto_accept_invitation: 'Auto-join invited registered users'
},
@@ -4996,6 +4997,7 @@ export default {
max_owned_per_user: 'Maximum number of workspaces a non-superuser may own via self-service creation. Read on every workspace creation and takes effect immediately after saving. 0 uses the built-in default of 10; a negative value disables the cap entirely (not recommended on public deployments).',
self_service_creation_enabled: 'Whether non-superusers may create workspaces themselves. When disabled, regular users can only join existing workspaces by invitation; cross-workspace superusers remain exempt. Takes effect immediately.',
default_storage_quota_gb: 'Default storage quota (GB) assigned when a new workspace is created, covering vectors, originals, text, indexes, and related data. Read only at creation time — changes apply to newly created workspaces only and do not retroactively update existing workspaces. 0 or a negative value uses the built-in default of 10 GB.',
+ default_storage_quota_mb: 'Includes personal workspaces created at registration. Positive values override the GB setting; zero or negative values use GB. Each setting resolves from database, environment, then built-in default. Changes affect newly created workspaces only.',
auto_create_api_key: 'Automatically creates a full_access API key for a new workspace and returns its plaintext token in the create response. Use only for integrations that depend on the legacy behavior; it is disabled by default and explicit API-key creation is recommended.',
auto_accept_invitation: 'When enabled, inviting a registered user by email adds them as a member immediately instead of waiting for inbox confirmation. When off, the invitee must accept from their inbox. Takes effect immediately.'
},
@@ -5148,8 +5150,8 @@ export default {
label: 'Apply to all existing workspaces',
tooltip: 'Saving the value only affects new workspaces by default; click here to also overwrite every existing workspace.',
confirmBtn: 'Confirm apply',
- confirmBody: 'Overwrite the storage quota of every existing workspace to {value} GB. Workspaces whose quota was tuned manually by operations will also be overwritten. Continue?',
- success: 'Updated storage quota for {count} workspaces to {gb} GB',
+ confirmBody: 'Overwrite the storage quota of every existing workspace to {value} {unit}. Workspaces whose quota was tuned manually by operations will also be overwritten. Continue?',
+ success: 'Updated storage quota for {count} workspaces to {value} {unit}',
failed: 'Failed to apply to all workspaces'
},
audit: {
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index 08d16653c..c158779d5 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -4965,6 +4965,7 @@ export default {
max_owned_per_user: 'ユーザごとの所有ワークスペース数の上限',
self_service_creation_enabled: 'ユーザによるワークスペース作成を許可',
default_storage_quota_gb: '新規ワークスペースのデフォルトストレージクォータ(GB)',
+ default_storage_quota_mb: '新規ワークスペースのデフォルトストレージクォータ(MB)',
auto_create_api_key: '新規ワークスペースにAPIキーを自動作成',
auto_accept_invitation: '招待した登録済みユーザを自動的に参加させる'
},
@@ -4996,6 +4997,7 @@ export default {
max_owned_per_user: 'スーパーユーザ以外がセルフサービスで所有できるワークスペース数の上限です。ワークスペース作成のたびに参照され、保存後すぐに反映されます。0を指定すると組み込みのデフォルト値10が使われ、負の値を指定すると上限が無効になります(公開環境では非推奨)。',
self_service_creation_enabled: 'スーパーユーザ以外が自分でワークスペースを作成できるかどうかです。無効にすると、一般ユーザは招待によって既存のワークスペースに参加することしかできません。ワークスペース横断のスーパーユーザは対象外です。すぐに反映されます。',
default_storage_quota_gb: '新規ワークスペースの作成時に割り当てられるデフォルトのストレージクォータ(GB)です。ベクトル、原本、テキスト、インデックスなどのデータが対象です。作成時にのみ参照されるため、変更は新規作成のワークスペースにのみ適用され、既存のワークスペースには遡って反映されません。0または負の値の場合は組み込みのデフォルト値10GBが使われます。',
+ default_storage_quota_mb: '登録時に自動作成される個人スペースにも適用します。正の値はGB設定より優先され、0以下はGB設定を使用します。各設定はデータベース、環境変数、既定値の順に解決し、新規スペースにのみ適用します。',
auto_create_api_key: '新規ワークスペースにfull_accessのAPIキーを自動作成し、作成レスポンスで平文のトークンを返します。従来の動作に依存する連携でのみ利用してください。デフォルトでは無効で、APIキーは明示的に作成することを推奨します。',
auto_accept_invitation: '有効にすると、登録済みユーザをメールで招待した際に、受信確認を待たずにすぐメンバーとして追加されます。無効の場合、招待された側がメールから承諾する必要があります。すぐに反映されます。'
},
@@ -5148,8 +5150,8 @@ export default {
label: '既存のすべてのワークスペースに適用',
tooltip: '値を保存してもデフォルトでは新規ワークスペースにのみ適用されます。ここをクリックすると既存のすべてのワークスペースも上書きします。',
confirmBtn: '適用を確認',
- confirmBody: '既存のすべてのワークスペースのストレージクォータを{value}GBに上書きします。運用担当者が個別に調整したワークスペースも上書きされます。続行しますか?',
- success: '{count}件のワークスペースのストレージクォータを{gb}GBに更新しました',
+ confirmBody: '既存のすべてのワークスペースのストレージクォータを{value} {unit}に上書きします。運用担当者が個別に調整したワークスペースも上書きされます。続行しますか?',
+ success: '{count}件のワークスペースのストレージクォータを{value} {unit}に更新しました',
failed: 'すべてのワークスペースへの適用に失敗しました'
},
audit: {
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 418c5a9bb..4d16a100b 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -4441,8 +4441,8 @@ export default {
label: '모든 기존 워크스페이스에 적용',
tooltip: '저장한 값은 기본적으로 새로 생성되는 워크스페이스에만 적용됩니다. 이 버튼을 누르면 현재 값을 모든 기존 워크스페이스에도 덮어씁니다.',
confirmBtn: '적용 확인',
- confirmBody: '모든 기존 워크스페이스의 저장 용량을 {value} GB로 덮어씁니다. 운영팀이 개별로 조정한 워크스페이스의 용량도 함께 덮어쓰여집니다. 계속하시겠습니까?',
- success: '{count}개 워크스페이스의 저장 용량을 {gb} GB로 갱신했습니다',
+ confirmBody: '모든 기존 워크스페이스의 저장 용량을 {value} {unit}로 덮어씁니다. 운영팀이 개별로 조정한 워크스페이스의 용량도 함께 덮어쓰여집니다. 계속하시겠습니까?',
+ success: '{count}개 워크스페이스의 저장 용량을 {value} {unit}로 갱신했습니다',
failed: '모든 워크스페이스에 적용 실패'
},
userList: {
@@ -4594,6 +4594,7 @@ export default {
max_owned_per_user: '슈퍼유저가 아닌 사용자가 셀프 서비스로 소유할 수 있는 최대 워크스페이스 수입니다. 워크스페이스 생성 시마다 읽으며 저장 즉시 적용됩니다. 0은 내장 기본값 10을 사용하고, 음수는 제한을 완전히 해제합니다(공개 배포에는 권장하지 않음).',
self_service_creation_enabled: '비슈퍼유저가 공간을 직접 만들 수 있는지 설정합니다. 비활성화하면 일반 사용자는 초대로만 기존 공간에 참여할 수 있으며, 크로스 워크스페이스 슈퍼유저는 계속 만들 수 있습니다.',
default_storage_quota_gb: '신규 워크스페이스 생성 시 기본으로 할당되는 저장 용량(GB)으로, 벡터·원본·텍스트·인덱스 등을 포함합니다. 생성 시에만 읽으며, 변경은 이후 생성되는 워크스페이스에만 적용되고 기존 워크스페이스에는 소급되지 않습니다. 0 또는 음수는 내장 기본값 10GB를 사용합니다.',
+ default_storage_quota_mb: '가입 시 생성되는 개인 공간에도 적용됩니다. 양수는 GB 설정보다 우선하며 0 이하는 GB 설정을 사용합니다. 각 설정은 데이터베이스, 환경 변수, 기본값 순으로 적용되며 새 공간에만 영향을 줍니다.',
auto_create_api_key: '신규 워크스페이스에 full_access API Key를 자동 생성하고 생성 응답에 평문 token을 반환합니다. 기존 동작에 의존하는 연동에만 사용하세요. 기본값은 비활성화입니다.',
auto_accept_invitation: '켜면 워크스페이스 관리자가 이메일로 가입된 사용자를 초대할 때 상대가 바로 멤버가 되며, 받은편지함에서 수락할 필요가 없습니다. 끄면 「초대 발송 → 상대가 수락」 흐름을 유지합니다. 저장 즉시 적용됩니다.'
},
@@ -4625,6 +4626,7 @@ export default {
max_owned_per_user: '사용자당 최대 워크스페이스 수',
self_service_creation_enabled: '사용자 공간 직접 생성 허용',
default_storage_quota_gb: '신규 워크스페이스 기본 저장 용량 (GB)',
+ default_storage_quota_mb: '신규 워크스페이스 기본 저장 용량 (MB)',
auto_create_api_key: '신규 워크스페이스 API Key 자동 생성',
auto_accept_invitation: '등록된 사용자 초대 시 자동 가입'
},
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 8d65e38dd..94d7b13f8 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -4441,8 +4441,8 @@ export default {
label: 'Применить ко всем существующим пространствам',
tooltip: 'По умолчанию сохранённое значение применяется только к новым пространствам. Нажмите, чтобы также перезаписать все существующие.',
confirmBtn: 'Подтвердить применение',
- confirmBody: 'Перезаписать квоту хранилища всех существующих пространств значением {value} ГБ. Пространства, чью квоту вручную правили эксплуатация, также будут перезаписаны. Продолжить?',
- success: 'Обновлена квота хранилища у {count} пространств: {gb} ГБ',
+ confirmBody: 'Перезаписать квоту хранилища всех существующих пространств значением {value} {unit}. Пространства, чью квоту вручную правили эксплуатация, также будут перезаписаны. Продолжить?',
+ success: 'Обновлена квота хранилища у {count} пространств: {value} {unit}',
failed: 'Ошибка применения ко всем пространствам'
},
userList: {
@@ -4594,6 +4594,7 @@ export default {
max_owned_per_user: 'Максимальное число пространств, которыми может владеть обычный (не супер) пользователь через самостоятельное создание. Читается при каждом создании пространства и вступает в силу сразу после сохранения. 0 — встроенное значение по умолчанию 10; отрицательное значение полностью снимает ограничение (не рекомендуется для публичных развёртываний).',
self_service_creation_enabled: 'Разрешает обычным пользователям самостоятельно создавать пространства. Если отключено, они могут только присоединяться по приглашению; межпространственные суперпользователи не ограничены.',
default_storage_quota_gb: 'Квота хранилища по умолчанию (ГБ) для нового пространства: векторы, оригиналы, текст, индексы и т.д. Читается только при создании — изменения применяются только к новым пространствам и не перезаписывают существующие. 0 или отрицательное значение — встроенное значение по умолчанию 10 ГБ.',
+ default_storage_quota_mb: 'Применяется и к личным пространствам, созданным при регистрации. Положительное значение приоритетнее настройки ГБ; ноль и отрицательные значения используют ГБ. Порядок источников каждой настройки: база данных, окружение, значение по умолчанию. Изменения касаются только новых пространств.',
auto_create_api_key: 'Автоматически создаёт API-ключ full_access и возвращает его открытый токен при создании пространства. Включайте только для старых интеграций; по умолчанию отключено.',
auto_accept_invitation: 'Если включено, приглашение зарегистрированного пользователя по email сразу добавляет его в пространство без подтверждения во входящих. Если выключено, сохраняется схема «отправка приглашения → подтверждение». Вступает в силу сразу после сохранения.'
},
@@ -4625,6 +4626,7 @@ export default {
max_owned_per_user: 'Максимум пространств на пользователя',
self_service_creation_enabled: 'Разрешить самостоятельное создание пространств',
default_storage_quota_gb: 'Квота хранилища для новых пространств по умолчанию (ГБ)',
+ default_storage_quota_mb: 'Квота хранилища новых пространств (МБ)',
auto_create_api_key: 'Автоматически создавать API-ключ для новых пространств',
auto_accept_invitation: 'Автоматически принимать приглашённых зарегистрированных пользователей'
},
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 8b261aa5a..feba8ce55 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -4443,8 +4443,8 @@ export default {
label: '应用到所有现有空间',
tooltip: '保存的值默认只对之后新建的空间生效;点击此按钮将当前值同步写入所有现有空间。',
confirmBtn: '应用',
- confirmBody: '将把所有现有空间的存储配额覆盖为 {value} GB。如有空间被运维单独调整过的配额,也会一并被覆盖。是否继续?',
- success: '已将 {count} 个空间的存储配额更新为 {gb} GB',
+ confirmBody: '将把所有现有空间的存储配额覆盖为 {value} {unit}。如有空间被运维单独调整过的配额,也会一并被覆盖。是否继续?',
+ success: '已将 {count} 个空间的存储配额更新为 {value} {unit}',
failed: '应用到所有空间失败'
},
userList: {
@@ -4596,6 +4596,7 @@ export default {
max_owned_per_user: '每个非超管用户通过自助创建可拥有的最大空间数。每次创建空间时实时读取,修改后立即生效。0 表示使用内置默认值 10;负数表示完全关闭限制(不建议在公开部署使用)。',
self_service_creation_enabled: '是否允许非超管用户主动创建空间。关闭后,普通用户只能通过邀请加入已有空间;跨空间超管仍可创建。修改后立即生效。',
default_storage_quota_gb: '新建空间时默认分配的存储配额(GB),包含向量、原文、文本、索引等。仅在创建时读取,修改后只对之后新建的空间生效,不会回写已存在的空间。0 或负数表示使用内置默认值 10GB。',
+ default_storage_quota_mb: '包括注册自动创建的个人空间。正数优先于 GB 设置;0 或负数沿用 GB 设置。每个设置按数据库、环境变量、内置默认值的顺序读取,仅影响之后新建的空间。',
auto_create_api_key: '为新空间自动生成 full_access API Key,并在创建响应中返回明文 token。仅用于兼容依赖旧行为的集成;默认关闭,建议通过 API Key 管理显式创建。',
auto_accept_invitation: '开启后,空间管理员通过邮箱邀请已注册用户时,对方会立即成为成员,不再经过收件箱确认。关闭时保持「发出邀请 → 被邀请人确认」流程。修改后立即生效。'
},
@@ -4627,6 +4628,7 @@ export default {
max_owned_per_user: '每用户最大空间数',
self_service_creation_enabled: '允许用户自助创建空间',
default_storage_quota_gb: '新空间默认存储配额 (GB)',
+ default_storage_quota_mb: '新空间默认存储配额 (MB)',
auto_create_api_key: '创建空间时自动生成 API Key',
auto_accept_invitation: '邀请已注册用户时自动加入'
},
diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts
index b3add7161..b4df2c084 100644
--- a/frontend/src/i18n/locales/zh-TW.ts
+++ b/frontend/src/i18n/locales/zh-TW.ts
@@ -4443,8 +4443,8 @@ export default {
label: '應用到所有現有空間',
tooltip: '儲存的值預設只對之後新建的空間生效;點擊此按鈕將當前值同步寫入所有現有空間。',
confirmBtn: '應用',
- confirmBody: '將把所有現有空間的存儲配額覆蓋為 {value} GB。如有空間被運維單獨調整過的配額,也會一併被覆蓋。是否繼續?',
- success: '已將 {count} 個空間的存儲配額更新為 {gb} GB',
+ confirmBody: '將把所有現有空間的存儲配額覆蓋為 {value} {unit}。如有空間被運維單獨調整過的配額,也會一併被覆蓋。是否繼續?',
+ success: '已將 {count} 個空間的存儲配額更新為 {value} {unit}',
failed: '應用到所有空間失敗'
},
userList: {
@@ -4596,6 +4596,7 @@ export default {
max_owned_per_user: '每個非超管使用者透過自助建立可擁有的最大空間數。每次建立空間時實時讀取,修改後立即生效。0 表示使用內建預設值 10;負數表示完全關閉限制(不建議在公開部署使用)。',
self_service_creation_enabled: '是否允許非超管使用者主動建立空間。關閉後,普通使用者只能透過邀請加入已有空間;跨空間超管仍可建立。修改後立即生效。',
default_storage_quota_gb: '新建空間時預設分配的存儲配額(GB),包含向量、原文、文字、索引等。僅在建立時讀取,修改後只對之後新建的空間生效,不會回寫已存在的空間。0 或負數表示使用內建預設值 10GB。',
+ default_storage_quota_mb: '包括註冊自動建立的個人空間。正數優先於 GB 設定;0 或負數沿用 GB 設定。每個設定按資料庫、環境變數、內建預設值的順序讀取,僅影響之後新建的空間。',
auto_create_api_key: '為新空間自動生成 full_access API Key,並在建立回應中返回明文 token。僅用於相容依賴舊行為的集成;預設關閉,建議透過 API Key 管理顯式建立。',
auto_accept_invitation: '開啟後,空間管理員透過電子信箱邀請已註冊使用者時,對方會立即成為成員,不再經過收件匣確認。關閉時保持「發出邀請 → 被邀請人確認」流程。修改後立即生效。'
},
@@ -4627,6 +4628,7 @@ export default {
max_owned_per_user: '每使用者最大空間數',
self_service_creation_enabled: '允許使用者自助建立空間',
default_storage_quota_gb: '新空間預設存儲配額 (GB)',
+ default_storage_quota_mb: '新空間預設存儲配額 (MB)',
auto_create_api_key: '建立空間時自動生成 API Key',
auto_accept_invitation: '邀請已註冊使用者時自動加入'
},
diff --git a/frontend/src/views/system/SystemSettings.vue b/frontend/src/views/system/SystemSettings.vue
index eccc1f36e..ca6171d61 100644
--- a/frontend/src/views/system/SystemSettings.vue
+++ b/frontend/src/views/system/SystemSettings.vue
@@ -198,21 +198,19 @@
-->
<div v-if="hasOverride(item) || hasBulkAction(item)" class="setting-control-actions">
<!--
- Per-key bulk action. Currently only one key
- (tenant.default_storage_quota_gb) carries one — clicking
- writes the current setting value onto every existing
- tenant. We do this as a separate explicit action rather
+ Both quota rows apply the effective default (MB takes precedence)
+ to every existing tenant. We do this as a separate explicit action rather
than auto-cascade on save so a SystemAdmin who tweaks the
default while triaging a single new-tenant question
- doesn't accidentally rewrite production quotas. Hidden
- when the row is dirty because applying a not-yet-saved
- value would confuse "what just happened".
+ doesn't accidentally rewrite production quotas. Disabled
+ while either quota row is dirty, so the confirmation
+ always describes the saved effective default.
-->
- <t-popconfirm v-if="hasBulkAction(item)" :content="bulkActionConfirmBody(item)"
+ <t-popconfirm v-if="hasBulkAction(item)" :content="bulkActionConfirmBody()"
:confirm-btn="{ content: t('system.globalSettings.bulkApply.confirmBtn'), theme: 'primary' }"
:cancel-btn="{ content: t('system.globalSettings.confirm.cancelBtn') }" placement="left"
@confirm="runBulkAction(item)">
- <t-button variant="text" size="small" :disabled="savingKey === item.key || isDirty(item)"
+ <t-button variant="text" size="small" :disabled="quotaActionDisabled"
:title="t('system.globalSettings.bulkApply.tooltip')" class="setting-bulk-btn">
<template #icon><t-icon name="usergroup" /></template>
{{ t('system.globalSettings.bulkApply.label') }}
@@ -256,6 +254,7 @@ import UserManagement from './UserManagement.vue'
import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'
import { PASSWORD_SPECIAL_CHARS } from '@/utils/passwordPolicy'
import { isSettingValueDirty, resolveCurrentSetting } from './systemSettingsEdit'
+import { STORAGE_QUOTA_KEYS, resolveStorageQuota, formatStorageQuota } from './storageQuota'
const deploymentCapabilities = useDeploymentCapabilitiesStore()
@@ -394,6 +393,7 @@ const SETTINGS_SECTION_KEYS: Record<Exclude<SettingsSection, 'other' | 'users'>,
],
tenant: [
'tenant.default_storage_quota_gb',
+ 'tenant.default_storage_quota_mb',
'tenant.auto_create_api_key',
'tenant.auto_accept_invitation',
],
@@ -817,32 +817,24 @@ function highRiskConfirmBody(item: SystemSettingItem, value: unknown): string {
})
}
-// hasBulkAction tells the template whether the current row carries an
-// extra "apply to existing data" action beyond plain save/reset.
-// Currently only `tenant.default_storage_quota_gb` does — saving the
-// setting only affects future tenants, so the bulk button is the
-// escape hatch for "rewrite all current tenants too".
function hasBulkAction(item: SystemSettingItem): boolean {
- return item.key === 'tenant.default_storage_quota_gb'
+ return STORAGE_QUOTA_KEYS.some((key) => key === item.key)
}
+const quotaActionDisabled = computed(() => savingKey.value !== null ||
+ settings.value.some((item) => hasBulkAction(item) && isDirty(item)))
+
async function refreshSandboxDockerCapability(key: string) {
if (key !== 'sandbox.docker_enabled') return
await deploymentCapabilities.ensureLoaded(true)
}
-function bulkActionConfirmBody(item: SystemSettingItem): string {
- // Use the canonical (saved) value, not the in-progress edit, so the
- // operator sees exactly what will be written. The button is disabled
- // when the row is dirty (see template), so item.value is the value
- // that's currently in effect for new tenants.
- const v = item.value
- const valueText = v === null || v === undefined ? '' : String(v)
- return t('system.globalSettings.bulkApply.confirmBody', { value: valueText })
+function bulkActionConfirmBody(): string {
+ return t('system.globalSettings.bulkApply.confirmBody', resolveStorageQuota(settings.value))
}
async function runBulkAction(item: SystemSettingItem) {
- if (!hasBulkAction(item)) return
+ if (!hasBulkAction(item) || quotaActionDisabled.value) return
savedKey.value = null
savingKey.value = item.key
try {
@@ -850,7 +842,7 @@ async function runBulkAction(item: SystemSettingItem) {
MessagePlugin.success(
t('system.globalSettings.bulkApply.success', {
count: result.affected,
- gb: result.quota_gb,
+ ...formatStorageQuota(result.quota_bytes),
}),
)
markSettingSaved(item)
diff --git a/frontend/src/views/system/storageQuota.test.ts b/frontend/src/views/system/storageQuota.test.ts
new file mode 100644
index 000000000..8f9f48a78
--- /dev/null
+++ b/frontend/src/views/system/storageQuota.test.ts
@@ -0,0 +1,24 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { formatStorageQuota, resolveStorageQuota } from './storageQuota.ts'
+
+test('bulk confirmation uses the MB override even when invoked from the GB row', () => {
+ assert.deepEqual(resolveStorageQuota([
+ { key: 'tenant.default_storage_quota_gb', value: 10 },
+ { key: 'tenant.default_storage_quota_mb', value: 50 },
+ ]), { value: 50, unit: 'MB' })
+ assert.deepEqual(formatStorageQuota(50 * 1024 ** 2), { value: 50, unit: 'MB' })
+})
+
+test('disabled or overflowing MB restores the legacy default shown in confirmation', () => {
+ for (const value of [0, -1, 8796093022208]) {
+ assert.deepEqual(resolveStorageQuota([
+ { key: 'tenant.default_storage_quota_gb', value: 2 },
+ { key: 'tenant.default_storage_quota_mb', value },
+ ]), { value: 2, unit: 'GB' })
+ }
+ assert.deepEqual(resolveStorageQuota([]), { value: 10, unit: 'GB' })
+ assert.deepEqual(resolveStorageQuota([{ key: 'tenant.default_storage_quota_gb', value: -1 }]),
+ { value: 10, unit: 'GB' })
+ assert.deepEqual(formatStorageQuota(2 * 1024 ** 3), { value: 2, unit: 'GB' })
+})
diff --git a/frontend/src/views/system/storageQuota.ts b/frontend/src/views/system/storageQuota.ts
new file mode 100644
index 000000000..cc0e7ef2f
--- /dev/null
+++ b/frontend/src/views/system/storageQuota.ts
@@ -0,0 +1,17 @@
+type QuotaSetting = { key: string; value: unknown }
+
+export const STORAGE_QUOTA_KEYS = ['tenant.default_storage_quota_mb', 'tenant.default_storage_quota_gb'] as const
+
+// Match the service's byte-overflow guards before displaying a bulk action.
+export function resolveStorageQuota(settings: readonly QuotaSetting[]): { value: number; unit: string } {
+ const mb = Number(settings.find((item) => item.key === STORAGE_QUOTA_KEYS[0])?.value)
+ if (Number.isInteger(mb) && mb > 0 && mb <= 8796093022207) return { value: mb, unit: 'MB' }
+ const gb = Number(settings.find((item) => item.key === STORAGE_QUOTA_KEYS[1])?.value)
+ return { value: Number.isInteger(gb) && gb > 0 && gb <= 8589934591 ? gb : 10, unit: 'GB' }
+}
+
+export function formatStorageQuota(bytes: number): { value: number; unit: string } {
+ return bytes % (1024 ** 3) === 0
+ ? { value: bytes / (1024 ** 3), unit: 'GB' }
+ : { value: bytes / (1024 ** 2), unit: 'MB' }
+}
diff --git a/internal/application/service/extract_data_table_orphan_test.go b/internal/application/service/extract_data_table_orphan_test.go
index 1082a24ad..632e802a8 100644
--- a/internal/application/service/extract_data_table_orphan_test.go
+++ b/internal/application/service/extract_data_table_orphan_test.go
@@ -187,7 +187,7 @@ func TestDataTableSummaryHandleProcessesLiveKnowledgeAfterResourcePreparation(t
worker := &DataTableSummaryService{
knowledgeService: f.svc,
knowledgeBaseService: f.kbs,
- tenantService: NewTenantService(f.tenants, nil),
+ tenantService: NewTenantService(f.tenants, nil, nil),
modelService: tableSummaryUnusedModels{},
retrieveEngine: retriever.NewRetrieveEngineRegistry(nil, nil),
fileService: tableSummaryUnavailableFile{err: fileErr},
diff --git a/internal/application/service/storagebackend_test.go b/internal/application/service/storagebackend_test.go
index 0e3e91d63..53f4d69ff 100644
--- a/internal/application/service/storagebackend_test.go
+++ b/internal/application/service/storagebackend_test.go
@@ -49,7 +49,7 @@ func TestResolveFileServiceUsesWorkspaceDefaultForStubTenant(t *testing.T) {
tenantRepo := repository.NewTenantRepository(db)
storageRepo := repository.NewStorageBackendRepository(db)
- tenant, err := service.NewTenantService(tenantRepo, storageRepo).CreateTenant(
+ tenant, err := service.NewTenantService(tenantRepo, storageRepo, nil).CreateTenant(
context.Background(), &types.Tenant{Name: "workspace"})
require.NoError(t, err)
require.NotNil(t, tenant.DefaultStorageBackendID)
diff --git a/internal/application/service/system_setting.go b/internal/application/service/system_setting.go
index 785e7776e..d62d275e6 100644
--- a/internal/application/service/system_setting.go
+++ b/internal/application/service/system_setting.go
@@ -218,6 +218,14 @@ var registry = map[string]settingSpec{
"仅在创建时读取,修改后只对之后新建的空间生效,不会回写已存在的空间。" +
"0 或负数表示使用内置默认值 10GB。",
},
+ "tenant.default_storage_quota_mb": {
+ Type: "int",
+ EnvName: "WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_MB",
+ Default: int64(0),
+ Category: "tenant",
+ Description: "新空间默认存储配额(MB),包括注册自动创建的个人空间。" +
+ "正数优先于 GB 配额;0 或负数沿用 GB 设置。仅新建空间时读取,不自动修改现有空间。",
+ },
// tenant.auto_create_api_key restores the legacy behaviour where creating
// a tenant also minted a full-access API key and returned its plaintext
// token in the create response. Newer versions stopped doing this (keys
diff --git a/internal/application/service/tenant.go b/internal/application/service/tenant.go
index d25dea4a4..5abcee10b 100644
--- a/internal/application/service/tenant.go
+++ b/internal/application/service/tenant.go
@@ -25,11 +25,16 @@ type ListTenantsParams struct {
type tenantService struct {
repo interfaces.TenantRepository // Repository for tenant data operations
storageRepo interfaces.StorageBackendRepository
+ settings interfaces.SystemSettingService
}
// NewTenantService creates a new tenant service instance
-func NewTenantService(repo interfaces.TenantRepository, storageRepo interfaces.StorageBackendRepository) interfaces.TenantService {
- return &tenantService{repo: repo, storageRepo: storageRepo}
+func NewTenantService(
+ repo interfaces.TenantRepository,
+ storageRepo interfaces.StorageBackendRepository,
+ settings interfaces.SystemSettingService,
+) interfaces.TenantService {
+ return &tenantService{repo: repo, storageRepo: storageRepo, settings: settings}
}
// CreateTenant creates a new tenant
@@ -48,6 +53,11 @@ func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant)
tenant.Status = "active"
tenant.CreatedAt = time.Now()
tenant.UpdatedAt = time.Now()
+ // All creation paths, including registration and OIDC provisioning, must
+ // persist the resolved default instead of relying on the database default.
+ if tenant.StorageQuota <= 0 {
+ tenant.StorageQuota = ResolveDefaultTenantStorageQuota(ctx, s.settings)
+ }
if err := s.validateStorageBucketUniqueness(ctx, tenant); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
diff --git a/internal/application/service/tenant_storage_quota.go b/internal/application/service/tenant_storage_quota.go
new file mode 100644
index 000000000..ea08ddcd9
--- /dev/null
+++ b/internal/application/service/tenant_storage_quota.go
@@ -0,0 +1,38 @@
+package service
+
+import (
+ "context"
+ "math"
+
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+const (
+ quotaMiB int64 = 1024 * 1024
+ quotaGiB = 1024 * quotaMiB
+ defaultTenantStorageQuota = 10 * quotaGiB
+)
+
+// ResolveDefaultTenantStorageQuota returns the effective default in bytes.
+// Each setting uses DB > ENV > default resolution. A positive MB setting
+// takes precedence over the legacy GB setting; zero or negative MB falls
+// back to GB. Invalid GB falls back to 10 GiB. Overflow must never turn a
+// configured quota into a non-positive (unlimited) value.
+func ResolveDefaultTenantStorageQuota(ctx context.Context, settings interfaces.SystemSettingService) int64 {
+ if settings == nil {
+ return defaultTenantStorageQuota
+ }
+ mb := settings.GetInt(ctx, "tenant.default_storage_quota_mb", "WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_MB", 0)
+ if mb > 0 && mb <= math.MaxInt64/quotaMiB {
+ return mb * quotaMiB
+ }
+ if mb > math.MaxInt64/quotaMiB {
+ logger.Warn(ctx, "Default tenant storage quota in MB exceeds int64 bytes; falling back to GB")
+ }
+ gb := settings.GetInt(ctx, "tenant.default_storage_quota_gb", "WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB", 10)
+ if gb <= 0 || gb > math.MaxInt64/quotaGiB {
+ return defaultTenantStorageQuota
+ }
+ return gb * quotaGiB
+}
diff --git a/internal/application/service/tenant_storage_quota_test.go b/internal/application/service/tenant_storage_quota_test.go
new file mode 100644
index 000000000..5c37f9587
--- /dev/null
+++ b/internal/application/service/tenant_storage_quota_test.go
@@ -0,0 +1,103 @@
+package service
+
+import (
+ "context"
+ "math"
+ "strconv"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+ "gorm.io/driver/sqlite"
+ "gorm.io/gorm"
+)
+
+func quotaTestSettings(values map[string]int64) *systemSettingService {
+ s := &systemSettingService{cache: make(map[string]*types.SystemSetting)}
+ for unit, value := range values {
+ key := "tenant.default_storage_quota_" + unit
+ s.cache[key] = &types.SystemSetting{
+ Key: key, Value: types.JSON(strconv.FormatInt(value, 10)), LastModifiedBy: "admin",
+ }
+ }
+ s.loaded.Store(true)
+ return s
+}
+
+func TestResolveDefaultTenantStorageQuota(t *testing.T) {
+ tests := []struct {
+ name string
+ settings map[string]int64
+ mb, gb string
+ want int64
+ }{
+ {name: "default", want: 10 * quotaGiB},
+ {name: "legacy env", gb: "2", want: 2 * quotaGiB},
+ {name: "legacy DB overrides env", settings: map[string]int64{"gb": 3}, gb: "2", want: 3 * quotaGiB},
+ {name: "MB env overrides GB", mb: "50", settings: map[string]int64{"gb": 3}, want: 50 * quotaMiB},
+ {name: "MB DB overrides env", mb: "100", settings: map[string]int64{"mb": 50}, want: 50 * quotaMiB},
+ {
+ name: "explicit zero MB restores GB", mb: "50", gb: "2",
+ settings: map[string]int64{"mb": 0}, want: 2 * quotaGiB,
+ },
+ {name: "negative MB restores GB", mb: "-1", gb: "2", want: 2 * quotaGiB},
+ {name: "invalid MB env restores GB", mb: "invalid", gb: "2", want: 2 * quotaGiB},
+ {name: "zero GB defaults", gb: "0", want: 10 * quotaGiB},
+ {name: "negative GB defaults", gb: "-1", want: 10 * quotaGiB},
+ {name: "invalid GB defaults", gb: "invalid", want: 10 * quotaGiB},
+ {name: "overflow MB restores GB", mb: strconv.FormatInt(math.MaxInt64, 10), gb: "2", want: 2 * quotaGiB},
+ {name: "overflow GB defaults", gb: strconv.FormatInt(math.MaxInt64, 10), want: 10 * quotaGiB},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Setenv("WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_MB", tt.mb)
+ t.Setenv("WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB", tt.gb)
+ got := ResolveDefaultTenantStorageQuota(context.Background(), quotaTestSettings(tt.settings))
+ require.Equal(t, tt.want, got)
+ })
+ }
+}
+
+func TestTenantStorageQuotaPersistsAcrossCreationPaths(t *testing.T) {
+ ctx := context.Background()
+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
+ require.NoError(t, err)
+ sqlDB, err := db.DB()
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = sqlDB.Close() })
+ require.NoError(t, db.AutoMigrate(&types.Tenant{}))
+ settings := quotaTestSettings(map[string]int64{"mb": 50, "gb": 2})
+ repo := repository.NewTenantRepository(db)
+ tenants := NewTenantService(repo, nil, settings)
+
+ manual, err := tenants.CreateTenant(ctx, &types.Tenant{Name: "manual"})
+ require.NoError(t, err)
+ users := &userService{userRepo: &provisioningUserRepo{}, tenantService: tenants}
+ registered, err := users.Register(ctx, &types.RegisterRequest{
+ Username: "alice", Email: "[email protected]", Password: "password123",
+ })
+ require.NoError(t, err)
+ explicit, err := tenants.CreateTenant(ctx, &types.Tenant{Name: "explicit", StorageQuota: 75 * quotaMiB})
+ require.NoError(t, err)
+ negative, err := tenants.CreateTenant(ctx, &types.Tenant{Name: "negative", StorageQuota: -1})
+ require.NoError(t, err)
+ for _, id := range []uint64{manual.ID, registered.TenantID, negative.ID} {
+ stored, readErr := repo.GetTenantByID(ctx, id)
+ require.NoError(t, readErr)
+ require.Equal(t, int64(50)*quotaMiB, stored.StorageQuota)
+ }
+ stored, err := repo.GetTenantByID(ctx, explicit.ID)
+ require.NoError(t, err)
+ require.Equal(t, int64(75)*quotaMiB, stored.StorageQuota)
+
+ // A runtime setting change affects later creations, including registration,
+ // without rewriting established tenants or relying on the GORM 10 GiB tag.
+ settings.cache["tenant.default_storage_quota_mb"].Value = types.JSON(`100`)
+ later, err := tenants.CreateTenant(ctx, &types.Tenant{Name: "later"})
+ require.NoError(t, err)
+ require.Equal(t, int64(100)*quotaMiB, later.StorageQuota)
+ stored, err = repo.GetTenantByID(ctx, manual.ID)
+ require.NoError(t, err)
+ require.Equal(t, int64(50)*quotaMiB, stored.StorageQuota)
+}
diff --git a/internal/application/service/tenant_storagebackend_test.go b/internal/application/service/tenant_storagebackend_test.go
index 911e22a09..c6458f4ff 100644
--- a/internal/application/service/tenant_storagebackend_test.go
+++ b/internal/application/service/tenant_storagebackend_test.go
@@ -20,7 +20,7 @@ func TestCreateTenantCreatesConcreteDefaultStorageBackend(t *testing.T) {
require.NoError(t, db.AutoMigrate(&types.Tenant{}, &types.StorageBackend{}))
tenantRepo := repository.NewTenantRepository(db)
storageRepo := repository.NewStorageBackendRepository(db)
- tenantSvc := service.NewTenantService(tenantRepo, storageRepo)
+ tenantSvc := service.NewTenantService(tenantRepo, storageRepo, nil)
tenant, err := tenantSvc.CreateTenant(context.Background(), &types.Tenant{Name: "workspace"})
require.NoError(t, err)
diff --git a/internal/handler/system.go b/internal/handler/system.go
index 7b42792de..a7eda9924 100644
--- a/internal/handler/system.go
+++ b/internal/handler/system.go
@@ -2440,9 +2440,8 @@ func (h *SystemHandler) UpdateSystemSetting(c *gin.Context) {
// ApplyDefaultStorageQuotaToAllTenants godoc
// @Summary Apply the default storage quota to every existing workspace
-// @Description Reads the current value of `tenant.default_storage_quota_gb`
-// @Description (3-tier resolver: DB > ENV > default) and writes that many
-// @Description GiB into storage_quota for every row in tenants. Bypasses
+// @Description Resolves the MB override or legacy GB default (DB > ENV > default per setting)
+// @Description and writes the effective byte quota to every existing workspace. Bypasses
// @Description the per-workspace PUT whitelist, which forbids storage_quota
// @Description edits by Owners. SystemAdmin only.
// @Description Idempotent — running twice with the same setting is a no-op.
@@ -2454,18 +2453,8 @@ func (h *SystemHandler) UpdateSystemSetting(c *gin.Context) {
func (h *SystemHandler) ApplyDefaultStorageQuotaToAllTenants(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
- // Resolve via the same 3-tier path the CreateTenant handler uses
- // so the action's effect mirrors what new tenants would receive.
- gb := h.systemSettingSvc.GetInt(
- ctx,
- "tenant.default_storage_quota_gb",
- "WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB",
- 10,
- )
- if gb <= 0 {
- gb = 10
- }
- quotaBytes := gb * 1024 * 1024 * 1024
+ quotaBytes := service.ResolveDefaultTenantStorageQuota(ctx, h.systemSettingSvc)
+ gb := float64(quotaBytes) / float64(1024*1024*1024)
affected, err := h.tenantSvc.BulkSetStorageQuota(ctx, quotaBytes)
if err != nil {
diff --git a/internal/handler/system_storage_quota_test.go b/internal/handler/system_storage_quota_test.go
new file mode 100644
index 000000000..c3edf8fe2
--- /dev/null
+++ b/internal/handler/system_storage_quota_test.go
@@ -0,0 +1,54 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+type storageQuotaSettings struct {
+ interfaces.SystemSettingService
+}
+
+func (storageQuotaSettings) GetInt(_ context.Context, key, _ string, def int64) int64 {
+ if key == "tenant.default_storage_quota_mb" {
+ return 50
+ }
+ return def
+}
+
+type bulkQuotaTenantService struct {
+ interfaces.TenantService
+ quota int64
+}
+
+func (s *bulkQuotaTenantService) BulkSetStorageQuota(_ context.Context, quota int64) (int64, error) {
+ s.quota = quota
+ return 3, nil
+}
+
+func TestApplyDefaultStorageQuotaUsesMBOverride(t *testing.T) {
+ tenants := &bulkQuotaTenantService{}
+ h := &SystemHandler{tenantSvc: tenants, systemSettingSvc: storageQuotaSettings{}}
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ c.Request = httptest.NewRequest(http.MethodPost, "/system/admin/tenants/apply-default-storage-quota", nil)
+ h.ApplyDefaultStorageQuotaToAllTenants(c)
+ require.Equal(t, http.StatusOK, w.Code)
+ require.Equal(t, int64(50*1024*1024), tenants.quota)
+ var response struct {
+ Affected int64 `json:"affected"`
+ QuotaBytes int64 `json:"quota_bytes"`
+ QuotaGB float64 `json:"quota_gb"`
+ }
+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &response))
+ require.Equal(t, int64(3), response.Affected)
+ require.Equal(t, tenants.quota, response.QuotaBytes)
+ require.Equal(t, 50.0/1024, response.QuotaGB)
+}
diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go
index 7eb03e86a..87660c57f 100644
--- a/internal/handler/tenant.go
+++ b/internal/handler/tenant.go
@@ -321,29 +321,6 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
}
}
- // Apply the system-setting-driven default storage quota when the
- // caller didn't specify one (always true for self-serve; sometimes
- // true for the superuser branch when the JSON omits storage_quota).
- // We resolve at create time on purpose — the on-disk row should
- // carry an explicit value, so changing the setting later doesn't
- // silently shrink/grow established tenants. Negative values are
- // treated as "use default" so a misconfigured setting can't yield
- // a negative quota that the storage-used checks would interpret as
- // "unlimited" (StorageQuota <= 0 disables enforcement in
- // knowledge_create.go).
- if tenantData.StorageQuota <= 0 {
- gb := h.systemSettingSvc.GetInt(
- ctx,
- "tenant.default_storage_quota_gb",
- "WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB",
- 10,
- )
- if gb <= 0 {
- gb = 10
- }
- tenantData.StorageQuota = gb * 1024 * 1024 * 1024
- }
-
logger.Infof(ctx, "Creating tenant, name: %s", secutils.SanitizeForLog(tenantData.Name))
createdTenant, err := h.service.CreateTenant(ctx, &tenantData)
diff --git a/internal/handler/workspace_operations_test.go b/internal/handler/workspace_operations_test.go
index 98456158d..b514b6035 100644
--- a/internal/handler/workspace_operations_test.go
+++ b/internal/handler/workspace_operations_test.go
@@ -44,7 +44,7 @@ func TestCurrentWorkspaceProfilePersistsOnlyRequestedFields(t *testing.T) {
} {
require.NoError(t, db.Create(tenant).Error)
}
- svc := service.NewTenantService(repository.NewTenantRepository(db), nil)
+ svc := service.NewTenantService(repository.NewTenantRepository(db), nil, nil)
h := &TenantHandler{service: svc}
caller := types.Caller{TenantID: 7, UserID: "owner", Role: types.TenantRoleOwner}
enforce := true
diff --git a/internal/im/resource_storage_test.go b/internal/im/resource_storage_test.go
index 902fbb398..de43744c0 100644
--- a/internal/im/resource_storage_test.go
+++ b/internal/im/resource_storage_test.go
@@ -73,7 +73,7 @@ func newIMResourceStorageFixture(t *testing.T) *imResourceStorageFixture {
catalog := appsvc.NewResourceCatalog(repository.NewResourceRepository(db))
f := &imResourceStorageFixture{
db: db, catalog: catalog, storage: appsvc.NewStorageBackendService(storageRepo, db, catalog),
- tenants: appsvc.NewTenantService(repository.NewTenantRepository(db), storageRepo),
+ tenants: appsvc.NewTenantService(repository.NewTenantRepository(db), storageRepo, nil),
global: filesvc.NewResourceCatalogFileService(filesvc.NewLocalFileService(t.TempDir(), ""), catalog),
tenant: &types.Tenant{ID: 7}, baseURL: server.URL,
}
diff --git a/website-docs/01-getting-started/04-configuration.md b/website-docs/01-getting-started/04-configuration.md
index 742be4b1b..bfe7cf01d 100644
--- a/website-docs/01-getting-started/04-configuration.md
+++ b/website-docs/01-getting-started/04-configuration.md
@@ -234,7 +234,8 @@ AWS S3 的 `S3_ACCESS_KEY` / `S3_SECRET_KEY` 可以**同时留空**,此时走
| `WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED` | true | 普通用户自建空间 |
| `WEKNORA_TENANT_MAX_OWNED_PER_USER` | 空 | 自建空间上限 |
| `WEKNORA_TENANT_AUTO_CREATE_API_KEY` | false | 建空间时自动下发 full_access API Key(兼容旧行为) |
-| `WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB` | 10 | 新空间默认存储配额 |
+| `WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB` | 10 | 新空间默认存储配额(GB,兼容原有配置) |
+| `WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_MB` | 0 | 正数优先于 GB;0 或负数沿用 GB。支持如 `50` MB 的默认配额 |
| `WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED` | false | 复杂密码策略:大小写字母、数字、特殊字符;系统设置 auth.complex_password_enabled 优先 |
| `WEKNORA_TENANT_AUTO_ACCEPT_INVITATION` | false | 邮箱邀请已有账号直接加入;系统设置 tenant.auto_accept_invitation 优先 |
| `OIDC_AUTH_JWKS_URI` | 空 | id_token 验签公钥集;可经 discovery 补全,与 issuer/audience/有效期共同校验 |
diff --git a/website-docs/03-features/20-platform-admin.md b/website-docs/03-features/20-platform-admin.md
index 1ca367635..398ab0e52 100644
--- a/website-docs/03-features/20-platform-admin.md
+++ b/website-docs/03-features/20-platform-admin.md
@@ -78,7 +78,8 @@
| `auth.default_tenant_mode` | `create_personal` / `tenantless` | `create_personal` | 只影响之后注册的新用户 |
| `tenant.self_service_creation_enabled` | bool | `true` | 立即 |
| `tenant.max_owned_per_user` | int | `10`(0 = 用内置默认,负数 = 关闭限额) | 每次建空间时读取 |
-| `tenant.default_storage_quota_gb` | int | `10` | **仅新建空间时读取**,不回写已有空间 |
+| `tenant.default_storage_quota_gb` | int | `10` | MB 设置未启用时的新空间默认配额(GB) |
+| `tenant.default_storage_quota_mb` | int | `0` | 正数优先于 GB;0 或负数沿用 GB。包含注册自动创建的个人空间 |
| `tenant.auto_create_api_key` | bool | `false` | 每次建空间时读取 |
| `ssrf.whitelist` | 字符串列表 | 空 | 立即(`SSRF_WHITELIST_EXTRA` 仍只由部署方维护,不在此覆盖) |
| `asynq.core/postprocess/enrichment/maintenance/shared/wiki_concurrency` | int | 见[异步任务系统](../02-architecture/05-async-tasks.md) | 各 worker pool 重新装配 |
@@ -110,3 +111,18 @@
- `cmd/server/bootstrap.go`:首个系统管理员引导。
- `frontend/src/config/settingsAccess.ts`:平台设置分区。
- `internal/application/service/system_setting.go`:运行时设置注册表。
+
+### 默认空间存储配额
+
+手动创建空间、普通注册及 OIDC 注册自动创建个人空间,均在创建服务中写入相同的默认配额。
+例如设置 `WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_MB=50`,新空间获得 50 × 1024² 字节。
+MB 设置为正数时优先于 GB 设置;MB 为 0 或负数时沿用原有 GB 设置,GB 为非正数时回退到 10 GB。
+每个设置分别遵循 **数据库覆盖值 > 环境变量 > 内置默认值**,因此保存 MB 为 0 可覆盖环境变量并恢复 GB 配置。
+超出 int64 字节范围的 MB 值回退到 GB;GB 溢出时回退到 10 GB,不会产生无限配额。
+
+默认值只影响之后新建的空间。显式指定的正数 `storage_quota`(字节)继续生效;已有空间不会自动改写。
+如需更新存量空间,管理员可使用“应用到所有现有空间”,确认框展示当前实际生效的 MB/GB 配额。
+该操作会覆盖所有现有空间的配额,包括单独调整过的值。
+
+无需修改数据库列默认值。服务写入显式字节值,可避免手工 `ALTER TABLE ... SET DEFAULT` 在升级时被 GORM
+模型中的默认值重置;原有列默认值保留以兼容直接 SQL 等未经过服务的写入。