From c6c2c0733f75a95c8bfee9f4506658e8b4bd808d Mon Sep 17 00:00:00 2001 From: alfadb Date: Sun, 13 Sep 2026 08:21:03 +0800 Subject: [PATCH] feat(usage): expose ollama cloud quota mode and monthly credit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit D7+E3+E26:把 ollama_cloud 双额度模式(legacy 滚动窗口 / credits 月度 信用池)在用量展示上打通。 - 后端 OllamaCloudUsageState 新增 mode(复用 GetOllamaCloudAccountMode 解析 credentials.account_mode,非 ollama_cloud 平台留空)与 monthly_credit_usd(*float64,读 credentials.monthly_credit_usd, 缺失/非法/非正数时为 nil,不报错不填假值) - dto mapper 对 platform=ollama_cloud 一律下发 state:不合格账号也要把 eligible_reason 送到前端用量格;legacy 宿主平台维持仅 eligible 下发 - 前端类型补 eligible_reason / mode / monthly_credit_usd 声明 - 用量格按 mode 分支:legacy 渲染 5h/7d 窗口 + 追加余额文本;credits 隐藏窗口条、渲染月池进度((pool-balance)/pool clamp,前端派生)+ 余额/分母文本 + 快照时间;池缺失时只显示原始余额文本 - 不合格账号展示 eligible_reason 可解释提示(不再空白占位) - AccountUsageCell 对 ollama_cloud 本体平台按 state 存在与否挂载 cell 派生展示百分比按规格放前端(D7 二选一);未动建号表单、渠道监控、 ratelimit_service 与迁移。 --- .../account_mapper_ollama_cloud_usage_test.go | 57 ++++++++++ backend/internal/handler/dto/mappers.go | 6 +- backend/internal/service/account.go | 30 ++++++ .../internal/service/ollama_cloud_usage.go | 20 +++- .../service/ollama_cloud_usage_test.go | 91 ++++++++++++++++ .../components/account/AccountUsageCell.vue | 7 +- .../account/OllamaCloudUsageCell.vue | 101 +++++++++++++++--- .../__tests__/AccountUsageCell.spec.ts | 33 +++++- .../__tests__/OllamaCloudUsageCell.spec.ts | 73 ++++++++++++- .../src/i18n/locales/en/admin/accounts.ts | 6 ++ .../src/i18n/locales/zh/admin/accounts.ts | 6 ++ frontend/src/types/index.ts | 6 ++ 12 files changed, 412 insertions(+), 24 deletions(-) create mode 100644 backend/internal/handler/dto/account_mapper_ollama_cloud_usage_test.go diff --git a/backend/internal/handler/dto/account_mapper_ollama_cloud_usage_test.go b/backend/internal/handler/dto/account_mapper_ollama_cloud_usage_test.go new file mode 100644 index 0000000000..5257cb5ec9 --- /dev/null +++ b/backend/internal/handler/dto/account_mapper_ollama_cloud_usage_test.go @@ -0,0 +1,57 @@ +package dto + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/Wei-Shaw/sub2api/internal/service" +) + +// ollama_cloud 平台账号无论合格与否都下发 ollama_cloud_usage state:不合格 +// 时管理端要靠 EligibleReason 解释「为什么没有窗口/余额」。legacy 宿主平台 +// (openai/kimi 等)无法与普通同平台账号区分,不合格时不挂 state。 +func TestAccountFromServiceShallow_OllamaCloudUsageAttachment(t *testing.T) { + t.Parallel() + + ollamaCloud := func() *service.Account { + return &service.Account{ + ID: 1, + Platform: service.PlatformOllamaCloud, + Type: service.AccountTypeAPIKey, + Credentials: map[string]any{ + "base_url": "https://ollama.example.test", // 反代 → 不合格 + "api_key": "key-1", + }, + } + } + + ineligible := AccountFromServiceShallow(ollamaCloud()) + require.NotNil(t, ineligible.OllamaCloudUsage) + require.False(t, ineligible.OllamaCloudUsage.Eligible) + require.Equal(t, "unsupported_base_url", ineligible.OllamaCloudUsage.EligibleReason) + + eligibleAccount := ollamaCloud() + eligibleAccount.Credentials["base_url"] = "https://ollama.com" + eligible := AccountFromServiceShallow(eligibleAccount) + require.NotNil(t, eligible.OllamaCloudUsage) + require.True(t, eligible.OllamaCloudUsage.Eligible) + + // legacy 宿主平台不合格账号:不挂 state(普通 openai 账号不受影响)。 + cnHost := &service.Account{ + ID: 2, + Platform: service.PlatformKimi, + Type: service.AccountTypeAPIKey, + Credentials: map[string]any{"base_url": "https://api.kimi.com", "api_key": "key-2"}, + } + require.Nil(t, AccountFromServiceShallow(cnHost).OllamaCloudUsage) + + // 完全无关平台(如 gemini):照旧不挂 state。 + gemini := &service.Account{ + ID: 3, + Platform: service.PlatformGemini, + Type: service.AccountTypeOAuth, + Credentials: map[string]any{}, + } + require.Nil(t, AccountFromServiceShallow(gemini).OllamaCloudUsage) +} diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index 42a1d82594..6ff1858b51 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -238,7 +238,11 @@ func AccountFromServiceShallow(a *service.Account) *Account { redactedCreds, credsStatus := RedactCredentials(a.Credentials) extra := redactAccountManagedExtra(a.Extra) var ollamaCloudUsage *service.OllamaCloudUsageState - if state := service.OllamaCloudUsageStateFromAccount(a); state.Eligible { + // platform=ollama_cloud 一律下发 state:不合格账号(反代 base_url、oauth + // 类型)也要把 EligibleReason 送到前端用量格做可解释提示。legacy 宿主 + // 平台(openai/anthropic/国产)无法与普通同平台账号区分,维持仅在 + // eligible 时下发,避免给正常 CN/OpenAI 账号挂上无意义的 ineligible 状态。 + if state := service.OllamaCloudUsageStateFromAccount(a); state.Eligible || a.Platform == service.PlatformOllamaCloud { ollamaCloudUsage = state } var openCodeGoUsage *service.OpenCodeGoUsageState diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 7ba8b76d0b..b08f2cad5a 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -443,6 +443,36 @@ func (a *Account) GetCredentialAsInt64(key string) int64 { return 0 } +// GetCredentialAsFloat64 返回浮点型凭据值,缺失或无法解析时返回 0。与 +// GetCredentialAsInt64 同样的类型容忍(JSONB 数字为 float64/json.Number, +// 运营也可能手写成字符串),供 Ollama Cloud monthly_credit_usd 等金额键读取。 +func (a *Account) GetCredentialAsFloat64(key string) float64 { + if a == nil || a.Credentials == nil { + return 0 + } + val, ok := a.Credentials[key] + if !ok || val == nil { + return 0 + } + switch v := val.(type) { + case float64: + return v + case int64: + return float64(v) + case int: + return float64(v) + case json.Number: + if f, err := v.Float64(); err == nil { + return f + } + case string: + if f, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil { + return f + } + } + return 0 +} + func (a *Account) IsTempUnschedulableEnabled() bool { if a.Credentials == nil { return false diff --git a/backend/internal/service/ollama_cloud_usage.go b/backend/internal/service/ollama_cloud_usage.go index 5fee972c36..f9abc53c83 100644 --- a/backend/internal/service/ollama_cloud_usage.go +++ b/backend/internal/service/ollama_cloud_usage.go @@ -163,7 +163,17 @@ type OllamaCloudUsageState struct { // EligibleReason 说明 eligible=false 的具体原因("" 表示合格): // platform_not_eligible / wrong_account_type / unsupported_base_url, // 供管理端区分「平台不合规 / 类型不对 / base_url 反代」。 - EligibleReason string `json:"eligible_reason,omitempty"` + EligibleReason string `json:"eligible_reason,omitempty"` + // Mode 是 Ollama Cloud 双额度模式:ollama_legacy(5h/7d 滚动窗口)/ + // ollama_credits(月度美元信用池),由 GetOllamaCloudAccountMode 解析 + // credentials.account_mode,未设置或值不认识时保守默认 legacy。 + // 非 ollama_cloud 平台(含用量白名单里的 legacy 宿主平台)留空。 + Mode string `json:"mode,omitempty"` + // MonthlyCreditUSD 是 credits 模式的月度信用池分母(USD),读 + // credentials.monthly_credit_usd(建号表单录入)。凭据缺失、无法解析或 + // 非正数时为 nil——表示「无该字段」,不报错也不填假值,前端回落为只 + // 展示原始余额文本。 + MonthlyCreditUSD *float64 `json:"monthly_credit_usd,omitempty"` Configured bool `json:"configured"` AutoRefreshEnabled bool `json:"auto_refresh_enabled"` EncryptionKeyConfigured bool `json:"encryption_key_configured"` @@ -1024,6 +1034,14 @@ func OllamaCloudUsageStateFromAccount(account *Account) *OllamaCloudUsageState { return state } state.AccountID = account.ID + // mode / monthly credit 在资格判定之前填充:不合格的 ollama_cloud 账号 + // (反代 base_url、oauth 类型)同样带着额度模式与原因码下发,供管理端 + // 解释「为什么没有窗口/余额」。GetOllamaCloudAccountMode 对非 + // ollama_cloud 平台返回空串,Mode 随 omitempty 留空。 + state.Mode = account.GetOllamaCloudAccountMode() + if credit := account.GetCredentialAsFloat64("monthly_credit_usd"); credit > 0 { + state.MonthlyCreditUSD = &credit + } state.EligibleReason = ollamaCloudUsageEligibilityReason(account) state.Eligible = state.EligibleReason == "" if !state.Eligible { diff --git a/backend/internal/service/ollama_cloud_usage_test.go b/backend/internal/service/ollama_cloud_usage_test.go index f15c30f2b4..d8857e6b48 100644 --- a/backend/internal/service/ollama_cloud_usage_test.go +++ b/backend/internal/service/ollama_cloud_usage_test.go @@ -566,6 +566,97 @@ func TestOllamaCloudUsageStateEligibleReason(t *testing.T) { require.Empty(t, state.EligibleReason) } +// OllamaCloudUsageState 的双额度字段(D7):mode 由 GetOllamaCloudAccountMode +// 解析(缺省/不认识 → legacy,非 ollama_cloud 平台留空),monthly_credit_usd +// 缺失或非法时为 nil(无该字段语义,不报错不填假值)。 +func TestOllamaCloudUsageStateModeAndMonthlyCredit(t *testing.T) { + tests := []struct { + name string + credentials map[string]any + wantMode string + wantMonthlyCredit *float64 + }{ + { + name: "未设置 account_mode 默认 legacy,无月度信用池", + credentials: map[string]any{}, + wantMode: AccountModeOllamaLegacy, + }, + { + name: "显式 legacy", + credentials: map[string]any{"account_mode": AccountModeOllamaLegacy}, + wantMode: AccountModeOllamaLegacy, + }, + { + name: "credits + 月度信用池 60(JSONB 数字为 float64)", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": float64(60)}, + wantMode: AccountModeOllamaCredits, + wantMonthlyCredit: float64Ptr(60), + }, + { + name: "月度信用池手写字符串也可解析", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": "300"}, + wantMode: AccountModeOllamaCredits, + wantMonthlyCredit: float64Ptr(300), + }, + { + name: "credits 但信用池缺失 → 只透出 mode", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits}, + wantMode: AccountModeOllamaCredits, + }, + { + name: "信用池为 0 / 负数 / 垃圾值 → 视为无该字段", + credentials: map[string]any{"account_mode": AccountModeOllamaCredits, "monthly_credit_usd": float64(0)}, + wantMode: AccountModeOllamaCredits, + }, + { + name: "不认识的 mode 值保守回落 legacy", + credentials: map[string]any{"account_mode": "ollama_turbo"}, + wantMode: AccountModeOllamaLegacy, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + account := ollamaUsageAccount(1) + account.Platform = PlatformOllamaCloud + account.Credentials = map[string]any{"base_url": "https://ollama.com", "api_key": "key-1"} + for key, value := range test.credentials { + account.Credentials[key] = value + } + + state := OllamaCloudUsageStateFromAccount(account) + require.True(t, state.Eligible) + require.Equal(t, test.wantMode, state.Mode) + if test.wantMonthlyCredit == nil { + require.Nil(t, state.MonthlyCreditUSD) + } else { + require.NotNil(t, state.MonthlyCreditUSD) + require.InDelta(t, *test.wantMonthlyCredit, *state.MonthlyCreditUSD, 1e-9) + } + }) + } + + // 非 ollama_cloud 平台(legacy 宿主平台)mode 留空,JSON 随 omitempty 缺省。 + hostAccount := ollamaUsageAccount(2) + hostAccount.Credentials["account_mode"] = AccountModeOllamaCredits + hostState := OllamaCloudUsageStateFromAccount(hostAccount) + require.Empty(t, hostState.Mode) + + payload, err := json.Marshal(hostState) + require.NoError(t, err) + require.NotContains(t, string(payload), `"mode"`) + + // credits 账号的 JSON 形状:mode + monthly_credit_usd 均按 tag 透出。 + creditsAccount := ollamaUsageAccount(3) + creditsAccount.Platform = PlatformOllamaCloud + creditsAccount.Credentials["account_mode"] = AccountModeOllamaCredits + creditsAccount.Credentials["monthly_credit_usd"] = float64(60) + creditsState := OllamaCloudUsageStateFromAccount(creditsAccount) + payload, err = json.Marshal(creditsState) + require.NoError(t, err) + require.Contains(t, string(payload), `"mode":"ollama_credits"`) + require.Contains(t, string(payload), `"monthly_credit_usd":60`) +} + // 错误文案由平台白名单派生(D2):platform 化后必须包含 ollama_cloud,不再 // 残留「OpenAI or Anthropic」旧文案;错误码是对外契约,保持不变。 func TestOllamaCloudUsageAccountInvalidMessageDerivedFromWhitelist(t *testing.T) { diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index 598064c036..5a5770fea9 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -596,8 +596,11 @@
+ @@ -666,7 +669,7 @@
-
diff --git a/frontend/src/components/account/OllamaCloudUsageCell.vue b/frontend/src/components/account/OllamaCloudUsageCell.vue index 17c09050c0..9935f0a94b 100644 --- a/frontend/src/components/account/OllamaCloudUsageCell.vue +++ b/frontend/src/components/account/OllamaCloudUsageCell.vue @@ -4,22 +4,50 @@ class="min-w-0 max-w-full space-y-1" data-testid="ollama-cloud-usage-cell" > + + + - +
+ {{ balanceLabel }} +
+ +
+ {{ snapshotTimeLabel }} +
+ + {{ eligibleReasonLabel }} - @@ -62,6 +97,44 @@ const { t } = useI18n() const state = ref(props.account.ollama_cloud_usage) const refreshing = ref(false) const snapshot = computed(() => state.value?.snapshot) +const isCredits = computed(() => state.value?.mode === 'ollama_credits') + +// balance 是官方文本(如 "$12.00"),派生池进度需要数值:剥掉货币符号与 +// 千分位后 parseFloat;解析不了返回 null(回落为只显示原始文本)。 +const balanceNumber = computed(() => { + const raw = snapshot.value?.data?.balance + if (!raw) return null + const parsed = Number.parseFloat(raw.replace(/[^0-9.]/g, '')) + return Number.isFinite(parsed) ? parsed : null +}) + +// credits 模式的月度信用池已用百分比:(pool - balance) / pool,clamp 0-100。 +const creditsPoolUtilization = computed(() => { + const pool = state.value?.monthly_credit_usd + if (!isCredits.value || !pool || pool <= 0 || balanceNumber.value === null) return null + const used = ((pool - balanceNumber.value) / pool) * 100 + return Math.min(Math.max(used, 0), 100) +}) + +const balanceText = computed(() => snapshot.value?.data?.balance ?? '') +const balanceLabel = computed(() => { + const prefix = `${t('admin.accounts.ollamaCloud.balance')}: ${balanceText.value}` + const pool = state.value?.monthly_credit_usd + return isCredits.value && pool && pool > 0 ? `${prefix} / $${pool}` : prefix +}) + +const eligibleReasonLabel = computed(() => { + const reason = state.value?.eligible_reason + return reason ? t(`admin.accounts.ollamaCloud.eligibleReason.${reason}`) : '' +}) + +const snapshotTimeLabel = computed(() => { + const raw = snapshot.value?.fetched_at + if (!raw) return '' + const date = new Date(raw) + const formatted = Number.isNaN(date.getTime()) ? raw : date.toLocaleString() + return `${t('admin.accounts.ollamaCloud.updatedAt')}: ${formatted}` +}) watch(() => props.account.ollama_cloud_usage, (next) => { state.value = next diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts index 2daa85e6e9..56e60d467a 100644 --- a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts @@ -290,17 +290,14 @@ describe('AccountUsageCell', () => { expect(getUsage).not.toHaveBeenCalled() }) - it.each([ - { name: '无 ollama_cloud_usage', usage: undefined }, - { name: 'eligible=false', usage: makeOllamaUsage(9101, { eligible: false }) } - ])('ollama_cloud apikey 账号($name)渲染占位而非 CN quota 格', async ({ usage }) => { + it('ollama_cloud apikey 账号(无 ollama_cloud_usage)渲染占位而非 CN quota 格', async () => { const wrapper = mount(AccountUsageCell, { props: { account: makeAccount({ id: 9101, platform: 'ollama_cloud', type: 'apikey', - ollama_cloud_usage: usage + ollama_cloud_usage: undefined }) }, global: { @@ -316,6 +313,32 @@ describe('AccountUsageCell', () => { expect(getUsage).not.toHaveBeenCalled() }) + // 不合格(如反代 base_url):后端也下发 state(带 eligible_reason),cell + // 照常挂载以展示可解释提示,而不是空白占位。 + it('ollama_cloud apikey 账号(eligible=false)仍渲染 OllamaCloudUsageCell 展示原因', async () => { + const wrapper = mount(AccountUsageCell, { + props: { + account: makeAccount({ + id: 9102, + platform: 'ollama_cloud', + type: 'apikey', + ollama_cloud_usage: makeOllamaUsage(9102, { + eligible: false, + eligible_reason: 'unsupported_base_url' + }) + }) + }, + global: { + stubs: { ...cnUsageCellStubs, UsageProgressBar: true, AccountQuotaInfo: true } + } + }) + + await flushPromises() + + expect(wrapper.find('[data-test="embedded-ollama"]').exists()).toBe(true) + expect(getUsage).not.toHaveBeenCalled() + }) + it.each(['opencode_go', 'kimi', 'zhipu', 'deepseek', 'minimax'] as const)( '%s 平台 OpenCode Go eligible 时只渲染 OpenCode 用量单元格并跳过 CN 子单元格', async (platform) => { diff --git a/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts b/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts index e38f3d3729..49febab9a8 100644 --- a/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/OllamaCloudUsageCell.spec.ts @@ -27,6 +27,7 @@ vi.mock('vue-i18n', async () => { const usageState = (): OllamaCloudUsageState => ({ account_id: 7, eligible: true, + mode: 'ollama_legacy', configured: true, auto_refresh_enabled: false, encryption_key_configured: true, @@ -104,8 +105,55 @@ describe('OllamaCloudUsageCell', () => { expect(query.classes()).toEqual(expect.arrayContaining(['text-blue-600', 'hover:bg-blue-50'])) expect(query.text()).toContain('admin.accounts.usageWindow.activeQuery') expect(wrapper.text()).not.toContain('max') - expect(wrapper.text()).not.toContain('$0') expect(wrapper.text()).not.toContain('gpt-oss:120b-cloud') + // legacy 模式追加 balance 文本(不含信用池分母)。 + const balance = wrapper.get('[data-testid="ollama-cloud-balance"]') + expect(balance.text()).toBe('admin.accounts.ollamaCloud.balance: $0') + }) + + it('renders legacy 5h/7d window bars and skips the pool bar', () => { + const wrapper = mount(OllamaCloudUsageCell, { props: { account: account() } }) + + expect(wrapper.find('[data-testid="ollama-cloud-monthly-pool"]').exists()).toBe(false) + const bars = wrapper.findAllComponents(UsageProgressBar) + expect(bars.map(bar => bar.props('label'))).toEqual(['5h', '7d']) + expect(wrapper.find('[data-testid="ollama-cloud-snapshot-time"]').exists()).toBe(false) + }) + + it('renders the monthly pool bar for credits mode instead of window bars', () => { + const state = usageState() + state.mode = 'ollama_credits' + state.monthly_credit_usd = 60 + state.snapshot!.data!.balance = '$12.00' + + const wrapper = mount(OllamaCloudUsageCell, { props: { account: account(state) } }) + + expect(wrapper.find('[data-testid="ollama-cloud-five-hour"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="ollama-cloud-seven-day"]').exists()).toBe(false) + const bars = wrapper.findAllComponents(UsageProgressBar) + expect(bars).toHaveLength(1) + expect(bars[0].props()).toMatchObject({ + // (60 - 12) / 60 = 80% + label: 'admin.accounts.ollamaCloud.monthlyPoolShort', + utilization: 80, + color: 'amber' + }) + expect(wrapper.get('[data-testid="ollama-cloud-balance"]').text()) + .toBe('admin.accounts.ollamaCloud.balance: $12.00 / $60') + expect(wrapper.get('[data-testid="ollama-cloud-snapshot-time"]').text()) + .toContain('admin.accounts.ollamaCloud.updatedAt') + }) + + it('falls back to the raw balance text when the credits pool is missing', () => { + const state = usageState() + state.mode = 'ollama_credits' + state.snapshot!.data!.balance = '$12.00' + + const wrapper = mount(OllamaCloudUsageCell, { props: { account: account(state) } }) + + expect(wrapper.find('[data-testid="ollama-cloud-monthly-pool"]').exists()).toBe(false) + expect(wrapper.get('[data-testid="ollama-cloud-balance"]').text()) + .toBe('admin.accounts.ollamaCloud.balance: $12.00') }) it('reacts to an account snapshot update', async () => { @@ -140,4 +188,27 @@ describe('OllamaCloudUsageCell', () => { expect(wrapper.find('[data-testid="ollama-cloud-usage-query"]').exists()).toBe(false) }) + + it('explains an ineligible account via the backend reason code', () => { + const state = usageState() + state.eligible = false + state.eligible_reason = 'unsupported_base_url' + state.snapshot = undefined + + const wrapper = mount(OllamaCloudUsageCell, { props: { account: account(state) } }) + + const hint = wrapper.get('[data-testid="ollama-cloud-usage-ineligible"]') + expect(hint.text()).toBe('admin.accounts.ollamaCloud.eligibleReason.unsupported_base_url') + expect(hint.attributes('title')).toBe('admin.accounts.ollamaCloud.eligibleReason.unsupported_base_url') + }) + + it('keeps the dash placeholder when no state is available', () => { + const wrapper = mount(OllamaCloudUsageCell, { + props: { account: account(null as unknown as OllamaCloudUsageState) } + }) + + expect(wrapper.find('[data-testid="ollama-cloud-usage-ineligible"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="ollama-cloud-usage-cell"]').exists()).toBe(false) + expect(wrapper.get('span').classes()).toContain('text-sm') + }) }) diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index 2cb0ee110c..ab366c1283 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -316,6 +316,7 @@ export default { sevenDay: '7 day', sevenDayShort: '7d', balance: 'Balance', + monthlyPoolShort: 'Pool', models: 'Models', status: 'Status', updatedAt: 'Updated', @@ -323,6 +324,11 @@ export default { unauthorized: 'Session expired', failed: 'Refresh failed', windowWithReset: '{percent} used, resets {reset}', + eligibleReason: { + platform_not_eligible: 'Platform is not in the Ollama Cloud usage allowlist', + wrong_account_type: 'Only API key accounts support usage queries', + unsupported_base_url: 'base_url is not the official ollama.com host; usage is unavailable' + }, loadFailed: 'Failed to load Ollama Cloud usage settings', sessionSaved: 'Ollama browser session saved', sessionSaveFailed: 'Failed to save Ollama browser session', diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index 3217f89fc8..3e5c9d6d65 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -164,6 +164,7 @@ export default { sevenDay: '7 天', sevenDayShort: '7d', balance: '余额', + monthlyPoolShort: '月池', models: '模型', status: '状态', updatedAt: '更新时间', @@ -171,6 +172,11 @@ export default { unauthorized: '会话已过期', failed: '刷新失败', windowWithReset: '已用 {percent},{reset} 重置', + eligibleReason: { + platform_not_eligible: '平台不在 Ollama Cloud 用量白名单内', + wrong_account_type: '仅 API Key 账号支持用量查询', + unsupported_base_url: 'base_url 非官方 ollama.com,无法查询用量' + }, loadFailed: '加载 Ollama Cloud 用量设置失败', sessionSaved: 'Ollama 浏览器会话已保存', sessionSaveFailed: '保存 Ollama 浏览器会话失败', diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 96ec2bcb0c..db5076e8e3 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -1141,6 +1141,12 @@ export interface OllamaCloudUsageSnapshot { export interface OllamaCloudUsageState { account_id: number eligible: boolean + /** eligible=false 的原因码(后端 EligibleReason,"" 缺省表示合格)。 */ + eligible_reason?: 'platform_not_eligible' | 'wrong_account_type' | 'unsupported_base_url' + /** 双额度模式:legacy=5h/7d 滚动窗口,credits=月度美元信用池;非 ollama_cloud 平台缺省。 */ + mode?: 'ollama_legacy' | 'ollama_credits' + /** credits 模式的月度信用池(USD,credentials.monthly_credit_usd);未录入时缺省。 */ + monthly_credit_usd?: number configured: boolean auto_refresh_enabled: boolean encryption_key_configured: boolean