mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
feat(usage): expose ollama cloud quota mode and monthly credit
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 与迁移。
This commit is contained in:
1 parent
f3a40c7219
commit
c6c2c0733f
12 files changed
+412
-24
No files matched your search
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -596,8 +596,11 @@
|
||||
<AccountQuotaInfo v-if="account.platform === 'gemini'" :account="account" />
|
||||
<!-- Key/Bedrock accounts: show today stats + optional quota bars -->
|
||||
<div v-else class="space-y-1">
|
||||
<!-- 按 state 存在与否挂载(不再要求 eligible):ollama_cloud 本体平台
|
||||
不合格时后端也下发 state(带 eligible_reason),cell 负责展示可解释
|
||||
提示;legacy 宿主平台仍是仅 eligible 下发,行为不变。 -->
|
||||
<OllamaCloudUsageCell
|
||||
v-if="account.ollama_cloud_usage?.eligible"
|
||||
v-if="account.ollama_cloud_usage"
|
||||
:account="account"
|
||||
@updated="handleOllamaCloudUsageUpdated"
|
||||
/>
|
||||
@@ -666,7 +669,7 @@
|
||||
|
||||
<!-- No data at all -->
|
||||
<div
|
||||
v-if="!todayStats && !todayStatsLoading && !hasApiKeyQuota && !account.ollama_cloud_usage?.eligible && !account.opencode_go_usage?.eligible"
|
||||
v-if="!todayStats && !todayStatsLoading && !hasApiKeyQuota && !account.ollama_cloud_usage && !account.opencode_go_usage?.eligible"
|
||||
class="text-xs text-gray-400"
|
||||
>-</div>
|
||||
</div>
|
||||
|
||||
@@ -4,22 +4,50 @@
|
||||
class="min-w-0 max-w-full space-y-1"
|
||||
data-testid="ollama-cloud-usage-cell"
|
||||
>
|
||||
<!-- legacy 模式:官方 5h / 7d 滚动窗口。credits 账号的官方 settings 页也会
|
||||
夹带窗口数据,但与月度信用池语义不符,按 mode 不渲染以免误导运营。 -->
|
||||
<template v-if="!isCredits">
|
||||
<UsageProgressBar
|
||||
v-if="snapshot?.data?.five_hour"
|
||||
label="5h"
|
||||
:utilization="snapshot.data.five_hour.used_percent"
|
||||
:resets-at="snapshot.data.five_hour.reset_at"
|
||||
color="indigo"
|
||||
data-testid="ollama-cloud-five-hour"
|
||||
/>
|
||||
<UsageProgressBar
|
||||
v-if="snapshot?.data?.seven_day"
|
||||
label="7d"
|
||||
:utilization="snapshot.data.seven_day.used_percent"
|
||||
:resets-at="snapshot.data.seven_day.reset_at"
|
||||
color="emerald"
|
||||
data-testid="ollama-cloud-seven-day"
|
||||
/>
|
||||
</template>
|
||||
<!-- credits 模式:月度信用池已用进度((pool-balance)/pool,clamp 0-100)。
|
||||
monthly_credit_usd 未录入或余额解析失败时不渲染,只显示原始余额文本。 -->
|
||||
<UsageProgressBar
|
||||
v-if="snapshot?.data?.five_hour"
|
||||
label="5h"
|
||||
:utilization="snapshot.data.five_hour.used_percent"
|
||||
:resets-at="snapshot.data.five_hour.reset_at"
|
||||
color="indigo"
|
||||
data-testid="ollama-cloud-five-hour"
|
||||
/>
|
||||
<UsageProgressBar
|
||||
v-if="snapshot?.data?.seven_day"
|
||||
label="7d"
|
||||
:utilization="snapshot.data.seven_day.used_percent"
|
||||
:resets-at="snapshot.data.seven_day.reset_at"
|
||||
color="emerald"
|
||||
data-testid="ollama-cloud-seven-day"
|
||||
v-if="creditsPoolUtilization !== null"
|
||||
:label="t('admin.accounts.ollamaCloud.monthlyPoolShort')"
|
||||
:utilization="creditsPoolUtilization"
|
||||
color="amber"
|
||||
data-testid="ollama-cloud-monthly-pool"
|
||||
/>
|
||||
<div
|
||||
v-if="balanceText"
|
||||
class="truncate text-[10px] text-gray-500 dark:text-gray-400"
|
||||
data-testid="ollama-cloud-balance"
|
||||
>
|
||||
{{ balanceLabel }}
|
||||
</div>
|
||||
<!-- credits 模式标注快照新鲜度(余额是采样值,不是实时值)。 -->
|
||||
<div
|
||||
v-if="isCredits && snapshotTimeLabel"
|
||||
class="truncate text-[10px] text-gray-400 dark:text-dark-500"
|
||||
data-testid="ollama-cloud-snapshot-time"
|
||||
>
|
||||
{{ snapshotTimeLabel }}
|
||||
</div>
|
||||
<div v-if="state.configured" class="flex items-center pt-0.5">
|
||||
<button
|
||||
type="button"
|
||||
@@ -46,6 +74,13 @@
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 不合格:展示后端原因码的可解释提示,而不是空白占位。 -->
|
||||
<span
|
||||
v-else-if="eligibleReasonLabel"
|
||||
class="inline-block max-w-full truncate text-[10px] text-amber-600 dark:text-amber-400"
|
||||
:title="eligibleReasonLabel"
|
||||
data-testid="ollama-cloud-usage-ineligible"
|
||||
>{{ eligibleReasonLabel }}</span>
|
||||
<span v-else class="text-sm text-gray-400 dark:text-dark-500">-</span>
|
||||
</template>
|
||||
|
||||
@@ -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<number | null>(() => {
|
||||
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<number | null>(() => {
|
||||
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
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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',
|
||||
|
||||
@@ -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 浏览器会话失败',
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user