feat(用户端): 密钥设置面板 LLM 两卡加人民币余额行,与代理余量同形
现状纠偏(写死免得下次重研):桌面壳加载的是 frontend-vue 的 Vue SPA(app_client/blueprints/main.py:52 供产物、 config.py:96 WEB_HOME_URL 直载),所谓"客户端密钥设置"不在 Python 里;而密钥明文只在后端(前端手里只有掩码), 所以余额必须由后端查、前端不自打上游——本面只消费 GET /api/user-secrets/llm-balance。 - 新建 SecretBalanceRow.vue:根元素就是 <div class="secret-meta">,保住既有挂载测试按 .secret-meta 取数的断言不破; LLM 卡插一行、代理卡那 8 行 div 换成同一组件 ⇒ 两卡同形自动达成。面板 763→789 行,在 800 报警线内, 可读棘轮基线不用动(该文件本就未点名)。 - 新建 shared/utils/llm-balance-text.ts(零依赖纯函数,node --test 直测)+ shared/composables/useLlmBalance.ts (按 moduleKey 存 items、三态文案、available=false 原样透出后端 message)。不引任何汇率乘算:绊线 tests/llm-balance-text.test.ts 里钉住源码不得出现 7.2/per_usd 类字样——换算只在上游 credits.per_usd 里。 - loadLlmBalance() 移出 if (props.showProxy):原形状下 LLM 卡永远空白。刷新时机=挂载、保存该模块后、清空后、 「检测已存值」后;⚠ 刻意不在「检测输入框未保存值」后刷——checkMyApiSecret(moduleKey,value) 探的是没落库的那把 key,而余额读服务端已存密钥,刷出来是上一把 key 的钱挂在新渠道名下=串档形状(同一格绊线盯着这条)。 - 不动 ProxyBalanceAlert.vue / utils/proxy-balance-alert.ts:没要求告警,引阈值就是自造口径。 - 复用 jikip 那套 VO 的 surplus/scope/low 语义不 borrow 给 LLM(铁律 25):types/modules/user-secret.ts 里 新类型与 :48-59 的 jikip VO 并置但互不相通。 测试:tests/llm-balance-text.test.ts 10 例(含源码绊线:面板行数<800、useLlmBalance 无汇率乘算、检测输入值路径 不触发 loadLlmBalance)+ tests/mount/密钥面板余额显示.mount.test.ts 11 例(两 LLM 卡各有 .secret-meta;龙抬头行 含 ¥+「龙抬头」、贞贞行含「不提供余额查询」且不含 ¥;两卡夹具给不同数字并交叉断言不互串;代理余量文案未变); endpoints.test.ts 金样加一行;两支既有挂载夹具补 fetchLlmBalanceSafely 默认值。 catch-silence 棘轮:useLlmBalance.ts 那一枚 catch 的**首条语句是界面可见出口**(清空该 moduleKey 的展示), console.warn 留在其后——按"首条即 log 才算静默"的口径它不该入账,实测入账了就把 blocks 311→312 如实登记并写明 理由,不删那个 catch(删了就是把失败读成"没有这一项")。vue-tsc rc=0、node --test 1018 例、vitest 66 例。
This commit is contained in:
@@ -211,6 +211,7 @@ export const API_ENDPOINTS = {
|
|||||||
check: '/api/user-secrets/{moduleKey}/check',
|
check: '/api/user-secrets/{moduleKey}/check',
|
||||||
migrate: '/api/user-secrets/migrate',
|
migrate: '/api/user-secrets/migrate',
|
||||||
proxyBalance: '/api/user-secrets/proxy-balance',
|
proxyBalance: '/api/user-secrets/proxy-balance',
|
||||||
|
llmBalance: '/api/user-secrets/llm-balance',
|
||||||
proxyPlan: '/api/user-secrets/proxy-plan',
|
proxyPlan: '/api/user-secrets/proxy-plan',
|
||||||
proxyWhitelist: '/api/user-secrets/proxy-whitelist',
|
proxyWhitelist: '/api/user-secrets/proxy-whitelist',
|
||||||
clientIp: '/api/user-secrets/client-ip',
|
clientIp: '/api/user-secrets/client-ip',
|
||||||
|
|||||||
@@ -58,6 +58,30 @@ export interface UserApiSecretBalance {
|
|||||||
lowReason?: string | null
|
lowReason?: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* LLM 渠道余额(人民币口径)。
|
||||||
|
*
|
||||||
|
* 与 `UserApiSecretBalance` 分开的理由在后端 `UserLlmBalanceVo` 上写着:那一个的
|
||||||
|
* surplus/scope/low 全是 jikip 套餐语义。这里同样不复用——一个字段名在两处表示两种东西,
|
||||||
|
* 下一个读代码的人一定会照错的用(铁律 25「口径不得借」)。
|
||||||
|
*/
|
||||||
|
export interface UserLlmBalance {
|
||||||
|
moduleKey: string
|
||||||
|
moduleLabel: string
|
||||||
|
/** longtaitou / t8star */
|
||||||
|
channel: string
|
||||||
|
channelLabel: string
|
||||||
|
available: boolean
|
||||||
|
/** 总余额,人民币(⚡)口径的上游原样小数串;available=false 时为 null。 */
|
||||||
|
balance: string | null
|
||||||
|
availableBalance: string | null
|
||||||
|
frozen: string | null
|
||||||
|
/** 恒为 CREDIT(站内 ⚡=人民币)。 */
|
||||||
|
unit: string | null
|
||||||
|
message: string | null
|
||||||
|
checkedAt: string | null
|
||||||
|
}
|
||||||
|
|
||||||
export interface UserProxyPlan {
|
export interface UserProxyPlan {
|
||||||
planId: string | null
|
planId: string | null
|
||||||
jikipUserId: string | null
|
jikipUserId: string | null
|
||||||
@@ -130,6 +154,21 @@ export function fetchProxyBalance() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* LLM 渠道余额(人民币口径)。`moduleKey` 留空=一次回齐两张密钥卡。
|
||||||
|
*
|
||||||
|
* 服务端最坏一次上游读 8 秒(`LongtaitouBalanceClient` 的读超时)+ 本地取密钥,
|
||||||
|
* 界面上限给到 20 秒:比它短会把「查得慢」报成「查不到」,比它长则用户盯着转圈没反馈。
|
||||||
|
*/
|
||||||
|
export function fetchLlmBalance(moduleKey?: string) {
|
||||||
|
return unwrapJavaResponse(
|
||||||
|
get<JavaApiResponse<UserLlmBalance[]>>(
|
||||||
|
buildJavaUrl(API_ENDPOINTS.userSecret.llmBalance, moduleKey ? { moduleKey } : undefined),
|
||||||
|
{ timeout: 20000 },
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/** 读取当前用户填写的 jikip 套餐 ID / 用户 ID(只用于余量查询)。 */
|
/** 读取当前用户填写的 jikip 套餐 ID / 用户 ID(只用于余量查询)。 */
|
||||||
export function fetchProxyPlan() {
|
export function fetchProxyPlan() {
|
||||||
return unwrapJavaResponse(
|
return unwrapJavaResponse(
|
||||||
|
|||||||
@@ -78,6 +78,13 @@
|
|||||||
{{ statusTextOf(module.moduleKey) }}
|
{{ statusTextOf(module.moduleKey) }}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<SecretBalanceRow
|
||||||
|
:text="llmMetaText(module.moduleKey)"
|
||||||
|
:updated-at="llmBalanceUpdatedAtOf(module.moduleKey)"
|
||||||
|
:refreshing="llmBalanceLoading"
|
||||||
|
@refresh="() => loadLlmBalance(module.moduleKey)"
|
||||||
|
/>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section v-if="showProxy" class="secret-card">
|
<section v-if="showProxy" class="secret-card">
|
||||||
@@ -252,14 +259,7 @@
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="secret-meta">
|
<SecretBalanceRow :text="proxyMetaText" :refreshing="balanceLoading" @refresh="loadBalance" />
|
||||||
<span v-if="proxyLoading">正在读取代理配置...</span>
|
|
||||||
<span v-else-if="proxyLoadFailed">代理配置读取失败,请关闭弹窗后重试</span>
|
|
||||||
<span v-else-if="!proxySupported">代理设置仅在桌面客户端中可用</span>
|
|
||||||
<span v-else-if="balanceLoading">正在查询代理余量...</span>
|
|
||||||
<span v-else-if="balance">{{ balanceText }}</span>
|
|
||||||
<span v-else>{{ balanceUnavailableText }}</span>
|
|
||||||
</div>
|
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -308,7 +308,9 @@ import {
|
|||||||
} from '@/shared/utils/api-secret-proxy-config'
|
} from '@/shared/utils/api-secret-proxy-config'
|
||||||
import { useProxyBalance, useProxyPlan } from '@/shared/composables/useProxyPlan'
|
import { useProxyBalance, useProxyPlan } from '@/shared/composables/useProxyPlan'
|
||||||
import { useKeyedSecretVisibility, useSecretVisibility } from '@/shared/composables/useSecretVisibility'
|
import { useKeyedSecretVisibility, useSecretVisibility } from '@/shared/composables/useSecretVisibility'
|
||||||
|
import { useLlmBalance } from '@/shared/composables/useLlmBalance'
|
||||||
import SecretVisibilityToggle from '@/shared/components/SecretVisibilityToggle.vue'
|
import SecretVisibilityToggle from '@/shared/components/SecretVisibilityToggle.vue'
|
||||||
|
import SecretBalanceRow from '@/shared/components/SecretBalanceRow.vue'
|
||||||
import { createModuleView, proxyCheckPresentation, type ModuleState } from '@/shared/utils/api-secret-module-view'
|
import { createModuleView, proxyCheckPresentation, type ModuleState } from '@/shared/utils/api-secret-module-view'
|
||||||
|
|
||||||
const props = withDefaults(
|
const props = withDefaults(
|
||||||
@@ -383,6 +385,23 @@ const proxyCheckResult = ref<UserApiSecretCheckResult | null>(null)
|
|||||||
const proxyCheckError = ref('')
|
const proxyCheckError = ref('')
|
||||||
|
|
||||||
const { balance, balanceLoading, balanceText, balanceUnavailableText, loadBalance } = useProxyBalance({ proxyProvider })
|
const { balance, balanceLoading, balanceText, balanceUnavailableText, loadBalance } = useProxyBalance({ proxyProvider })
|
||||||
|
|
||||||
|
const { llmBalanceLoading, llmBalanceTextOf, llmBalanceUpdatedAtOf, loadLlmBalance } = useLlmBalance()
|
||||||
|
|
||||||
|
/** LLM 卡余额行:渠道名以服务端回传为准(库里那把 key 才是余额接口读的,本地未保存的单选不参与取数)。 */
|
||||||
|
function llmMetaText(moduleKey: string): string {
|
||||||
|
if (llmBalanceLoading.value) return '正在查询密钥余额...'
|
||||||
|
return llmBalanceTextOf(moduleKey, llmChannelLabel(moduleChannels[moduleKey]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 代理卡那一行的既有优先级原样搬过来(读取中 → 失败 → 不支持 → 查询中 → 数值 → 查不到)。 */
|
||||||
|
const proxyMetaText = computed(() => {
|
||||||
|
if (proxyLoading.value) return '正在读取代理配置...'
|
||||||
|
if (proxyLoadFailed.value) return '代理配置读取失败,请关闭弹窗后重试'
|
||||||
|
if (!proxySupported.value) return '代理设置仅在桌面客户端中可用'
|
||||||
|
if (balanceLoading.value) return '正在查询代理余量...'
|
||||||
|
return balance.value ? balanceText.value : balanceUnavailableText.value
|
||||||
|
})
|
||||||
const {
|
const {
|
||||||
proxyPlanId,
|
proxyPlanId,
|
||||||
proxyPlanUserId,
|
proxyPlanUserId,
|
||||||
@@ -557,6 +576,8 @@ async function runCheck(moduleKey: ApiSecretModuleKey) {
|
|||||||
} finally {
|
} finally {
|
||||||
state.checking = false
|
state.checking = false
|
||||||
refreshSnapshots()
|
refreshSnapshots()
|
||||||
|
// 只有「检测已存密钥」才顺带刷余额:检测输入值时库里还是上一把 key,刷出来是上一把的钱(串档形状)
|
||||||
|
if (!inputValue) void loadLlmBalance(moduleKey)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -571,6 +592,8 @@ async function clearModule(moduleKey: ApiSecretModuleKey) {
|
|||||||
state.error = ''
|
state.error = ''
|
||||||
channelDirty[moduleKey] = false
|
channelDirty[moduleKey] = false
|
||||||
refreshSnapshots()
|
refreshSnapshots()
|
||||||
|
// 清空后库里已经没有这把 key:不刷的话,这一行会继续挂着上一把 key 的钱
|
||||||
|
void loadLlmBalance(moduleKey)
|
||||||
ElMessage.success('已清空密钥')
|
ElMessage.success('已清空密钥')
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
ElMessage.error(error instanceof Error ? error.message : '清空失败')
|
ElMessage.error(error instanceof Error ? error.message : '清空失败')
|
||||||
@@ -679,6 +702,7 @@ async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean>
|
|||||||
}
|
}
|
||||||
secretsSaved = true
|
secretsSaved = true
|
||||||
refreshSnapshots()
|
refreshSnapshots()
|
||||||
|
void loadLlmBalance()
|
||||||
|
|
||||||
if (props.showProxy && proxyReady.value && proxyDirty.value && !proxyLocked.value) {
|
if (props.showProxy && proxyReady.value && proxyDirty.value && !proxyLocked.value) {
|
||||||
const api = getPywebviewApi()
|
const api = getPywebviewApi()
|
||||||
@@ -741,6 +765,8 @@ onMounted(() => {
|
|||||||
// 先拉服务端密钥包(后台锁定的代理会先对齐到本地配置),再读本地代理,避免展示对齐前的旧值
|
// 先拉服务端密钥包(后台锁定的代理会先对齐到本地配置),再读本地代理,避免展示对齐前的旧值
|
||||||
void (async () => {
|
void (async () => {
|
||||||
await reload()
|
await reload()
|
||||||
|
// 读的是服务端已存密钥 ⇒ 排在 reload 之后;且它不属代理卡(浏览器形态 showProxy=false 会永远空白)
|
||||||
|
void loadLlmBalance()
|
||||||
if (props.showProxy) {
|
if (props.showProxy) {
|
||||||
await loadProxyConfig()
|
await loadProxyConfig()
|
||||||
if (proxySupported.value) {
|
if (proxySupported.value) {
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
<template>
|
||||||
|
<div class="secret-meta">
|
||||||
|
<span>{{ text }}</span>
|
||||||
|
<span v-if="updatedAt" class="meta-updated">更新于 {{ updatedAt }}</span>
|
||||||
|
<button
|
||||||
|
v-if="refreshable"
|
||||||
|
type="button"
|
||||||
|
class="meta-refresh"
|
||||||
|
:disabled="refreshing"
|
||||||
|
@click="emit('refresh')"
|
||||||
|
>
|
||||||
|
{{ refreshing ? '查询中...' : '刷新余额' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
/**
|
||||||
|
* 密钥卡上的「余额/余量」那一行(LLM 两卡与代理卡共用同一个形状)。
|
||||||
|
*
|
||||||
|
* 根元素刻意就是 `<div class="secret-meta">`:面板的样式与既有挂载用例都按这个类取数
|
||||||
|
* (`tests/mount/密钥面板青果检测.mount.test.ts` 的 `proxyCard(panel).find('.secret-meta')`),
|
||||||
|
* 抽组件不许把这条既有判据挪走。父作用域的 `.secret-meta` 规则会照常落到本组件根元素上
|
||||||
|
* (Vue 给子组件根节点同时挂父子两个 scope 属性),所以这里不重复定义行色。
|
||||||
|
*
|
||||||
|
* 文案由调用方算好整条传进来(含「正在读取…」那几档),本组件只管显示与「刷新」这个动作——
|
||||||
|
* 三态优先级留在面板里,一处一份,不在组件里再造第二套判定。
|
||||||
|
*/
|
||||||
|
withDefaults(defineProps<{
|
||||||
|
/** 整行文案(loading / 数值 / 查不到,都由调用方按既有优先级算好)。 */
|
||||||
|
text: string
|
||||||
|
/** 取数时刻(`HH:mm`);为空就不显示——没有数的时候不该假装知道它是几点取的。 */
|
||||||
|
updatedAt?: string
|
||||||
|
refreshing?: boolean
|
||||||
|
refreshable?: boolean
|
||||||
|
}>(), {
|
||||||
|
updatedAt: '',
|
||||||
|
refreshing: false,
|
||||||
|
refreshable: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const emit = defineEmits<{ refresh: [] }>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.meta-updated {
|
||||||
|
margin-left: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.meta-refresh {
|
||||||
|
margin-left: 8px;
|
||||||
|
border: 1px solid #cdd4dd;
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 0 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.meta-refresh:disabled {
|
||||||
|
cursor: default;
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { ref } from 'vue'
|
||||||
|
import { fetchLlmBalanceSafely } from '@/shared/utils/api-secret-store'
|
||||||
|
import {
|
||||||
|
llmBalanceText,
|
||||||
|
llmBalanceUnavailableText,
|
||||||
|
llmBalanceUpdatedAt,
|
||||||
|
} from '@/shared/utils/llm-balance-text'
|
||||||
|
import type { UserLlmBalance } from '@/shared/api/types/modules/user-secret'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* LLM 渠道余额(人民币口径):两张密钥卡各一格,形状与代理余量同一套三态。
|
||||||
|
*
|
||||||
|
* 三条口径写在这里,因为它们是「看着像成功、其实是错的」的成因:
|
||||||
|
* 1. **只在读服务端已存密钥的时刻刷**。输入框里那把还没保存的 key 不是余额接口读的那把
|
||||||
|
* (`checkApiSecret(value)` 探的是输入值,余额读的是库里那把)——在「检测输入值」后刷,
|
||||||
|
* 得到的是**上一把 key 的钱挂在新渠道名下**,与切渠道后不刷相比更容易被骗。
|
||||||
|
* 2. **失败即清空数字**,只留原因。留着上一次的读数就是上一条那个串档形状。
|
||||||
|
* 3. 不做任何汇率换算:`credits` 块本身就是人民币(⚡),乘一次系数等于自造一套口径
|
||||||
|
* (铁律 25)。
|
||||||
|
*/
|
||||||
|
export function useLlmBalance() {
|
||||||
|
const llmBalanceItems = ref<Record<string, UserLlmBalance>>({})
|
||||||
|
const llmBalanceLoading = ref(false)
|
||||||
|
|
||||||
|
function llmBalanceTextOf(moduleKey: string, channelLabel = ''): string {
|
||||||
|
const item = llmBalanceItems.value[moduleKey]
|
||||||
|
return item?.available
|
||||||
|
? llmBalanceText(item)
|
||||||
|
: llmBalanceUnavailableText(item, channelLabel)
|
||||||
|
}
|
||||||
|
|
||||||
|
function llmBalanceUpdatedAtOf(moduleKey: string): string {
|
||||||
|
return llmBalanceUpdatedAt(llmBalanceItems.value[moduleKey])
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `moduleKey` 留空=一次刷两张卡(面板打开时用);带 key=只刷那一格(保存/切渠道后用)。 */
|
||||||
|
async function loadLlmBalance(moduleKey?: string): Promise<void> {
|
||||||
|
llmBalanceLoading.value = true
|
||||||
|
try {
|
||||||
|
const list = await fetchLlmBalanceSafely(moduleKey)
|
||||||
|
const next = { ...llmBalanceItems.value }
|
||||||
|
for (const item of list || []) {
|
||||||
|
if (item && item.moduleKey) next[item.moduleKey] = item
|
||||||
|
}
|
||||||
|
llmBalanceItems.value = next
|
||||||
|
} catch (error) {
|
||||||
|
// 失败的第一出口是界面那一行(清空数字 ⇒ 渲染成「这次没查到」,与代理余量同一口径);
|
||||||
|
// 余额是打开面板时的附带读取,弹全局打扰会把用户下一次正常操作也打断,所以不 ElMessage。
|
||||||
|
// 顺序有意义:先给用户看得见的交代,控制台只作留链(catch-silence 棘轮按首条语句判静默)。
|
||||||
|
if (moduleKey) {
|
||||||
|
const next = { ...llmBalanceItems.value }
|
||||||
|
delete next[moduleKey]
|
||||||
|
llmBalanceItems.value = next
|
||||||
|
} else {
|
||||||
|
llmBalanceItems.value = {}
|
||||||
|
}
|
||||||
|
console.warn('[api-secret] LLM 余额查询失败:', error)
|
||||||
|
} finally {
|
||||||
|
llmBalanceLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
llmBalanceItems,
|
||||||
|
llmBalanceLoading,
|
||||||
|
llmBalanceTextOf,
|
||||||
|
llmBalanceUpdatedAtOf,
|
||||||
|
loadLlmBalance,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
checkMyApiSecret,
|
checkMyApiSecret,
|
||||||
deleteMyApiSecret,
|
deleteMyApiSecret,
|
||||||
fetchMyApiSecrets,
|
fetchMyApiSecrets,
|
||||||
|
fetchLlmBalance,
|
||||||
fetchProxyBalance,
|
fetchProxyBalance,
|
||||||
migrateMyApiSecrets,
|
migrateMyApiSecrets,
|
||||||
putMyApiSecret,
|
putMyApiSecret,
|
||||||
@@ -21,6 +22,7 @@ import {
|
|||||||
type UserApiSecretBundle,
|
type UserApiSecretBundle,
|
||||||
type UserApiSecretCheckResult,
|
type UserApiSecretCheckResult,
|
||||||
type UserApiSecretItem,
|
type UserApiSecretItem,
|
||||||
|
type UserLlmBalance,
|
||||||
} from '../api/types/modules/user-secret.ts'
|
} from '../api/types/modules/user-secret.ts'
|
||||||
import {
|
import {
|
||||||
applyInheritedSecrets,
|
applyInheritedSecrets,
|
||||||
@@ -979,6 +981,15 @@ export async function fetchProxyBalanceSafely() {
|
|||||||
return fetchProxyBalance()
|
return fetchProxyBalance()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* LLM 渠道余额(人民币口径)。`moduleKey` 留空=一次回齐两张密钥卡。
|
||||||
|
* 与 `fetchProxyBalanceSafely` 同层:只做薄封装、不吞异常——吞掉异常就把「查不到」
|
||||||
|
* 混成「余额为零」了,判红分支由调用方(useLlmBalance)如实分流。
|
||||||
|
*/
|
||||||
|
export async function fetchLlmBalanceSafely(moduleKey?: string): Promise<UserLlmBalance[]> {
|
||||||
|
return fetchLlmBalance(moduleKey)
|
||||||
|
}
|
||||||
|
|
||||||
/** 登出清理:内存与镜像一并清空(旧 v1 记录保留,供下次登录迁移)。 */
|
/** 登出清理:内存与镜像一并清空(旧 v1 记录保留,供下次登录迁移)。 */
|
||||||
export function clearApiSecretCache(): void {
|
export function clearApiSecretCache(): void {
|
||||||
for (const moduleKey of [...DEFAULT_REQUIRED_MODULES]) {
|
for (const moduleKey of [...DEFAULT_REQUIRED_MODULES]) {
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
/**
|
||||||
|
* LLM 余额的显示口径(纯函数,零 vue、零 `@/` 别名)。
|
||||||
|
*
|
||||||
|
* 单独成文件与本仓 `proxy-balance-alert.ts` / `user-secret-model.ts` 同一理由:
|
||||||
|
* 判据要能被 `node --test` 直接钉住。放进 composable 里就得拖起 vue 运行时,
|
||||||
|
* 或者干脆没人钉——而「把美元读成人民币」「把查不到显示成 ¥0」正是没人钉就会复发的形状。
|
||||||
|
*/
|
||||||
|
import type { UserLlmBalance } from '../api/types/modules/user-secret.ts'
|
||||||
|
|
||||||
|
/** 站内 ⚡=人民币口径;单位由服务端 `credits.unit` 判定,这里只负责加符号。 */
|
||||||
|
const YUAN = '¥'
|
||||||
|
|
||||||
|
function isFiniteNumber(value: number): boolean {
|
||||||
|
return Number.isFinite(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 人民币金额显示:保留两位小数。
|
||||||
|
*
|
||||||
|
* 上游给的是原样小数串(`88.888882`)——**四舍五入只发生在这里**,落库/传值都不提前取整,
|
||||||
|
* 否则账单对不上时没人能回溯当时到底是多少。解析不出数字时原样回显,不返回 `'¥0.00'`:
|
||||||
|
* 一格 0 会被读成「没钱了」,而真值可能只是上游换了写法。
|
||||||
|
*/
|
||||||
|
export function formatYuan(raw: string | null | undefined): string {
|
||||||
|
const text = (raw ?? '').trim()
|
||||||
|
if (!text) return ''
|
||||||
|
const value = Number(text.replace(/,/g, ''))
|
||||||
|
if (!isFiniteNumber(value)) return text
|
||||||
|
return `${YUAN}${value.toFixed(2)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 有数时的整行文案;可用/冻结按字段在不在追加(缺字段不补 0)。 */
|
||||||
|
export function llmBalanceText(item: UserLlmBalance | null | undefined): string {
|
||||||
|
if (!item || !item.available) return ''
|
||||||
|
const label = item.channelLabel || '该渠道'
|
||||||
|
const parts = [`总 ${formatYuan(item.balance) || '—'}`]
|
||||||
|
if (item.availableBalance) parts.push(`可用 ${formatYuan(item.availableBalance)}`)
|
||||||
|
if (item.frozen) parts.push(`冻结 ${formatYuan(item.frozen)}`)
|
||||||
|
return `${label}余额(人民币):${parts.join(' · ')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 没数时的诚实文案。
|
||||||
|
*
|
||||||
|
* 后端已经把原因说清了(渠道不支持/没配密钥/上游拒绝/超时),这里只补前缀、不改写;
|
||||||
|
* 已经以渠道名开头的话就不再叠一遍(免得读出「贞贞余额:贞贞渠道不提供余额查询」)。
|
||||||
|
* 兜底那句刻意说明「不是欠费、也不是不支持」——这一格空白最容易被读成没钱。
|
||||||
|
*
|
||||||
|
* `fallbackLabel` 只在整条 item 都没有时兜底(请求整个失败时,界面至少要说清这一行是谁的钱;
|
||||||
|
* 此时**不许**留着上一把 key 的数字,那是串档形状)。
|
||||||
|
*/
|
||||||
|
export function llmBalanceUnavailableText(
|
||||||
|
item: UserLlmBalance | null | undefined,
|
||||||
|
fallbackLabel = '',
|
||||||
|
): string {
|
||||||
|
const label = (item?.channelLabel || fallbackLabel || '该渠道').trim()
|
||||||
|
const reason = (item?.message ?? '').trim()
|
||||||
|
if (reason) return reason.startsWith(label) ? reason : `${label}余额:${reason}`
|
||||||
|
return `${label}余额这次没查到:接口没返回可用值(不是欠费,也不是不支持),可稍后重开设置页再看`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `checkedAt` 是 ISO 串:只取到分钟,给「这一格数是什么时候的」一个可核对的落点。 */
|
||||||
|
export function llmBalanceUpdatedAt(item: UserLlmBalance | null | undefined): string {
|
||||||
|
const raw = (item?.checkedAt ?? '').trim()
|
||||||
|
if (!raw) return ''
|
||||||
|
const parsed = new Date(raw)
|
||||||
|
if (Number.isNaN(parsed.getTime())) return ''
|
||||||
|
const pad = (value: number) => String(value).padStart(2, '0')
|
||||||
|
return `${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`
|
||||||
|
}
|
||||||
@@ -58,7 +58,13 @@ const BASELINE = {
|
|||||||
// interruptTaskRecord 包住中断请求,失败 ElMessage.error 当场报给用户、成功 ElMessage.success
|
// interruptTaskRecord 包住中断请求,失败 ElMessage.error 当场报给用户、成功 ElMessage.success
|
||||||
// 并刷新看板——与 308 的 retryTaskRecord 同口径,不是吞错;两处 ElMessageBox.confirm 的
|
// 并刷新看板——与 308 的 retryTaskRecord 同口径,不是吞错;两处 ElMessageBox.confirm 的
|
||||||
// 取消分支走 .then 两臂(确认框 reject 属正常交互),刻意不新增 catch 块。silent 一格没涨。
|
// 取消分支走 .then 两臂(确认框 reject 属正常交互),刻意不新增 catch 块。silent 一格没涨。
|
||||||
blocks: 311,
|
// 312 = 311 + 1(2026-11-05 B83 龙抬头余额进界面):useLlmBalance.ts 的 loadLlmBalance 包住
|
||||||
|
// 余额请求一支 try/catch。失败出口是**面板内那一行**(清空数字 ⇒ 渲染「这次没查到:接口没返回
|
||||||
|
// 可用值(不是欠费,也不是不支持)」),与代理余量同一口径;余额是打开面板时的附带读取,
|
||||||
|
// 弹全局打扰会把用户下一次正常操作也打断,所以刻意不 ElMessage。
|
||||||
|
// 按扫描器口径这一支不算静默(首条语句是状态写入、不是 console.*,console 只作留链),
|
||||||
|
// 所以 silent 一格没涨、逐文件台账不动,只进 blocks。
|
||||||
|
blocks: 312,
|
||||||
// 2026-10-30(ops Phase 6/可读棘轮):ApiSecretSettingsPanel.vue 1113→775 行,面板里那处
|
// 2026-10-30(ops Phase 6/可读棘轮):ApiSecretSettingsPanel.vue 1113→775 行,面板里那处
|
||||||
// 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进
|
// 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进
|
||||||
// useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动,
|
// useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动,
|
||||||
|
|||||||
@@ -319,6 +319,7 @@ test('test_endpoints_frozen_snapshot', () => {
|
|||||||
"check": "/api/user-secrets/{moduleKey}/check",
|
"check": "/api/user-secrets/{moduleKey}/check",
|
||||||
"migrate": "/api/user-secrets/migrate",
|
"migrate": "/api/user-secrets/migrate",
|
||||||
"proxyBalance": "/api/user-secrets/proxy-balance",
|
"proxyBalance": "/api/user-secrets/proxy-balance",
|
||||||
|
"llmBalance": "/api/user-secrets/llm-balance",
|
||||||
"proxyPlan": "/api/user-secrets/proxy-plan",
|
"proxyPlan": "/api/user-secrets/proxy-plan",
|
||||||
"proxyWhitelist": "/api/user-secrets/proxy-whitelist",
|
"proxyWhitelist": "/api/user-secrets/proxy-whitelist",
|
||||||
"clientIp": "/api/user-secrets/client-ip"
|
"clientIp": "/api/user-secrets/client-ip"
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
/**
|
||||||
|
* LLM 余额显示口径的纯函数判据(B83:龙抬头余额要显示人民币)。
|
||||||
|
*
|
||||||
|
* 靶子是「两套口径挑了哪一套」:上游同一份响应里美元串与 ⚡(人民币)数字并存,
|
||||||
|
* 挑错那一套不会报错、只会安静地差 7.2 倍。所以除了正向读数,这里还钉两条反向的:
|
||||||
|
* ① 美元形状不许被渲染成 `¥…`;② 源码里不许出现汇率乘算(自己乘一次=自造一套口径)。
|
||||||
|
*
|
||||||
|
* 跑法:`cd crawler-plugin/frontend-vue && npm test`
|
||||||
|
*/
|
||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
import {
|
||||||
|
formatYuan,
|
||||||
|
llmBalanceText,
|
||||||
|
llmBalanceUnavailableText,
|
||||||
|
llmBalanceUpdatedAt,
|
||||||
|
} from '../src/shared/utils/llm-balance-text.ts'
|
||||||
|
import type { UserLlmBalance } from '../src/shared/api/types/modules/user-secret.ts'
|
||||||
|
|
||||||
|
function item(over: Partial<UserLlmBalance> = {}): UserLlmBalance {
|
||||||
|
return {
|
||||||
|
moduleKey: 'appearance-patent',
|
||||||
|
moduleLabel: '外观专利密钥',
|
||||||
|
channel: 'longtaitou',
|
||||||
|
channelLabel: '龙抬头',
|
||||||
|
available: true,
|
||||||
|
balance: '88.888882',
|
||||||
|
availableBalance: '85.288882',
|
||||||
|
frozen: '3.6',
|
||||||
|
unit: 'CREDIT',
|
||||||
|
message: null,
|
||||||
|
checkedAt: '2026-11-05T10:30:00',
|
||||||
|
...over,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test('人民币读数只吃 credits 的数值并保留两位', () => {
|
||||||
|
assert.equal(formatYuan('88.888882'), '¥88.89')
|
||||||
|
assert.equal(formatYuan('0'), '¥0.00')
|
||||||
|
assert.equal(formatYuan(null), '')
|
||||||
|
assert.equal(formatYuan(''), '')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('美元形状绝不渲染成人民币', () => {
|
||||||
|
// 顶层那串是美元:解析不出数字时原样回显,不套 ¥ 符号——套了就等于宣称它是人民币
|
||||||
|
assert.equal(formatYuan('$12.345678'), '$12.345678')
|
||||||
|
assert.ok(!formatYuan('$12.345678').startsWith('¥'))
|
||||||
|
})
|
||||||
|
|
||||||
|
test('有数时的整行读数带渠道、总额与可用', () => {
|
||||||
|
const text = llmBalanceText(item())
|
||||||
|
assert.match(text, /龙抬头余额(人民币)/)
|
||||||
|
assert.match(text, /¥88\.89/)
|
||||||
|
assert.match(text, /可用 ¥85\.29/)
|
||||||
|
assert.match(text, /冻结 ¥3\.60/)
|
||||||
|
// 美元那两个数一旦混进来,读数就会差 7.2 倍还看着正常
|
||||||
|
assert.ok(!text.includes('12.34'), `读数里不该出现美元串:${text}`)
|
||||||
|
assert.ok(!text.includes('11.84'), `读数里不该出现美元串:${text}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('缺可用与冻结时不补零', () => {
|
||||||
|
const text = llmBalanceText(item({ availableBalance: null, frozen: null }))
|
||||||
|
assert.match(text, /总 ¥88\.89/)
|
||||||
|
assert.ok(!text.includes('可用 ¥0'), `缺字段不许读成 0:${text}`)
|
||||||
|
assert.ok(!text.includes('冻结 ¥0'), `缺字段不许读成 0:${text}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('贞贞那一档说不提供查询,且一个金额都不给', () => {
|
||||||
|
const unsupported = item({
|
||||||
|
available: false,
|
||||||
|
channel: 't8star',
|
||||||
|
channelLabel: '贞贞',
|
||||||
|
balance: null,
|
||||||
|
availableBalance: null,
|
||||||
|
frozen: null,
|
||||||
|
unit: null,
|
||||||
|
message: '贞贞渠道不提供余额查询;用量请看 ai.t8star.org 自己的控制台。',
|
||||||
|
})
|
||||||
|
assert.equal(llmBalanceText(unsupported), '')
|
||||||
|
const text = llmBalanceUnavailableText(unsupported)
|
||||||
|
assert.match(text, /不提供余额查询/)
|
||||||
|
assert.ok(!text.includes('¥'), `查不到时不许出现金额:${text}`)
|
||||||
|
assert.ok(!text.includes('0.00'), `查不到不许读成欠费:${text}`)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('后端没给原因时才兜底,且兜底句说明不是欠费', () => {
|
||||||
|
const text = llmBalanceUnavailableText(item({ available: false, message: null }))
|
||||||
|
assert.match(text, /龙抬头余额这次没查到/)
|
||||||
|
assert.match(text, /不是欠费/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('整格都没取到时用本地渠道名兜底(服务端连渠道都没回)', () => {
|
||||||
|
assert.match(llmBalanceUnavailableText(null, '贞贞'), /贞贞余额这次没查到/)
|
||||||
|
// item 在的时候一律以服务端回传的渠道名为准:库里那把 key 是哪家,钱就是哪家的
|
||||||
|
assert.match(llmBalanceUnavailableText(item({ available: false, message: '密钥失效' })), /龙抬头余额:密钥失效/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('原因已以渠道名开头时不叠第二遍前缀', () => {
|
||||||
|
const text = llmBalanceUnavailableText(item({
|
||||||
|
available: false, balance: null, message: '龙抬头没有返回人民币(⚡)口径的余额块',
|
||||||
|
}))
|
||||||
|
assert.equal(text, '龙抬头没有返回人民币(⚡)口径的余额块')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('取数时刻只到分钟,脏值不显示', () => {
|
||||||
|
assert.equal(llmBalanceUpdatedAt(item()), '10:30')
|
||||||
|
assert.equal(llmBalanceUpdatedAt(item({ checkedAt: null })), '')
|
||||||
|
assert.equal(llmBalanceUpdatedAt(item({ checkedAt: '不是时间' })), '')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('两张卡各回各的钱,不互串', () => {
|
||||||
|
const ap = llmBalanceText(item({ balance: '88.888882', availableBalance: '85.288882' }))
|
||||||
|
const sa = llmBalanceText(item({
|
||||||
|
moduleKey: 'similar-asin', balance: '12.5', availableBalance: '10', frozen: null,
|
||||||
|
}))
|
||||||
|
assert.match(ap, /¥88\.89/)
|
||||||
|
assert.match(sa, /¥12\.50/)
|
||||||
|
assert.ok(!sa.includes('88.89'), 'A 卡的数不许出现在 B 卡')
|
||||||
|
assert.ok(!ap.includes('12.50'), 'B 卡的数不许出现在 A 卡')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('源码绊线:不许自己乘汇率,也不许在面板里再造一套余额判定', () => {
|
||||||
|
const read = (path: string) => readFileSync(
|
||||||
|
fileURLToPath(new URL(path, import.meta.url)), 'utf8',
|
||||||
|
)
|
||||||
|
const textModule = read('../src/shared/utils/llm-balance-text.ts')
|
||||||
|
const composable = read('../src/shared/composables/useLlmBalance.ts')
|
||||||
|
|
||||||
|
// 7.2 是上游 credits.per_usd 的当前值,把它写进代码=自造第二套口径(上游一改就静默错)
|
||||||
|
for (const source of [textModule, composable]) {
|
||||||
|
assert.doesNotMatch(source, /7\.2/, '余额换算必须只用 credits 块,不许出现汇率字面量')
|
||||||
|
assert.doesNotMatch(source, /perUsd|per_usd/, '前端不参与口径换算,per_usd 只该在后端判定')
|
||||||
|
}
|
||||||
|
// 三态判定只有一处:面板按 proxyMetaText/llmMetaText 走,组件不自己判
|
||||||
|
const row = read('../src/shared/components/SecretBalanceRow.vue')
|
||||||
|
assert.doesNotMatch(row, /available/, '行组件只渲染调用方算好的文案,不再判一次 available')
|
||||||
|
})
|
||||||
@@ -39,6 +39,7 @@ const store = vi.hoisted(() => ({
|
|||||||
saveApiSecret: vi.fn(),
|
saveApiSecret: vi.fn(),
|
||||||
subscribeApiSecrets: vi.fn(),
|
subscribeApiSecrets: vi.fn(),
|
||||||
fetchProxyBalanceSafely: vi.fn(),
|
fetchProxyBalanceSafely: vi.fn(),
|
||||||
|
fetchLlmBalanceSafely: vi.fn(),
|
||||||
}))
|
}))
|
||||||
const secretApi = vi.hoisted(() => ({
|
const secretApi = vi.hoisted(() => ({
|
||||||
putMyApiSecret: vi.fn(),
|
putMyApiSecret: vi.fn(),
|
||||||
@@ -63,6 +64,7 @@ vi.mock('@/shared/utils/api-secret-store', () => ({
|
|||||||
saveApiSecret: store.saveApiSecret,
|
saveApiSecret: store.saveApiSecret,
|
||||||
subscribeApiSecrets: store.subscribeApiSecrets,
|
subscribeApiSecrets: store.subscribeApiSecrets,
|
||||||
fetchProxyBalanceSafely: store.fetchProxyBalanceSafely,
|
fetchProxyBalanceSafely: store.fetchProxyBalanceSafely,
|
||||||
|
fetchLlmBalanceSafely: store.fetchLlmBalanceSafely,
|
||||||
}))
|
}))
|
||||||
vi.mock('@/shared/api/types/modules/user-secret', () => ({
|
vi.mock('@/shared/api/types/modules/user-secret', () => ({
|
||||||
putMyApiSecret: secretApi.putMyApiSecret,
|
putMyApiSecret: secretApi.putMyApiSecret,
|
||||||
@@ -169,6 +171,8 @@ beforeEach(() => {
|
|||||||
store.fetchProxyBalanceSafely.mockResolvedValue({
|
store.fetchProxyBalanceSafely.mockResolvedValue({
|
||||||
available: true, surplus: '12', balance: '34', message: null, scope: 'user', low: false, lowReason: null,
|
available: true, surplus: '12', balance: '34', message: null, scope: 'user', low: false, lowReason: null,
|
||||||
})
|
})
|
||||||
|
// 本文件的靶子是掩码输入的显隐;LLM 余额回空数组即可,不参与任何断言
|
||||||
|
store.fetchLlmBalanceSafely.mockResolvedValue([])
|
||||||
secretApi.putMyApiSecret.mockResolvedValue({})
|
secretApi.putMyApiSecret.mockResolvedValue({})
|
||||||
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
|
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
|
||||||
bridge.readConfig.mockResolvedValue(qingguoConfig())
|
bridge.readConfig.mockResolvedValue(qingguoConfig())
|
||||||
|
|||||||
@@ -0,0 +1,290 @@
|
|||||||
|
/**
|
||||||
|
* 密钥设置面板「余额行」的挂载用例(B83:龙抬头余额显示人民币,形状与代理余量统一)。
|
||||||
|
*
|
||||||
|
* 五组靶子:
|
||||||
|
* ① 两张 LLM 卡各有一行 `.secret-meta`(改回「余额只属于代理卡」即红);
|
||||||
|
* ② 龙抬头那一格给的是**人民币**读数(¥),且美元那两个数一个都不出现;
|
||||||
|
* ③ 贞贞那一格说「不提供余额查询」,一个金额都不给(不借别家的数、也不显示 0);
|
||||||
|
* ④ 两卡各回各的钱,交叉不串;代理卡余量文案在抽组件后**逐字未变**;
|
||||||
|
* ⑤ 刷新时机:只有读服务端已存密钥的那几次会刷;「检测输入值(未保存)」不刷(那时刷的是上一把 key 的钱)。
|
||||||
|
*
|
||||||
|
* ⚠ 用例里的数字一律假值,真实密钥与真实余额不得进任何跟踪件。
|
||||||
|
*
|
||||||
|
* 跑法:`npx vitest run tests/mount/密钥面板余额显示.mount.test.ts`
|
||||||
|
*/
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
|
||||||
|
|
||||||
|
import ApiSecretSettingsPanel from '@/shared/components/ApiSecretSettingsPanel.vue'
|
||||||
|
|
||||||
|
const UID = '1301'
|
||||||
|
|
||||||
|
const message = vi.hoisted(() => ({
|
||||||
|
error: vi.fn(),
|
||||||
|
warning: vi.fn(),
|
||||||
|
success: vi.fn(),
|
||||||
|
info: vi.fn(),
|
||||||
|
}))
|
||||||
|
const store = vi.hoisted(() => ({
|
||||||
|
checkApiSecret: vi.fn(),
|
||||||
|
clearApiSecret: vi.fn(),
|
||||||
|
getServerProxySnapshot: vi.fn(),
|
||||||
|
getStoredApiSecretSnapshot: vi.fn(),
|
||||||
|
listApiSecretModules: vi.fn(),
|
||||||
|
loadApiSecrets: vi.fn(),
|
||||||
|
saveApiSecret: vi.fn(),
|
||||||
|
subscribeApiSecrets: vi.fn(),
|
||||||
|
fetchProxyBalanceSafely: vi.fn(),
|
||||||
|
fetchLlmBalanceSafely: vi.fn(),
|
||||||
|
}))
|
||||||
|
const secretApi = vi.hoisted(() => ({
|
||||||
|
putMyApiSecret: vi.fn(),
|
||||||
|
deleteMyApiSecret: vi.fn(),
|
||||||
|
fetchProxyPlan: vi.fn(),
|
||||||
|
saveProxyPlan: vi.fn(),
|
||||||
|
clearProxyPlan: vi.fn(),
|
||||||
|
}))
|
||||||
|
const bridge = vi.hoisted(() => ({
|
||||||
|
readConfig: vi.fn(),
|
||||||
|
saveConfig: vi.fn(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
vi.mock('element-plus', () => ({ ElMessage: message }))
|
||||||
|
vi.mock('@/shared/utils/api-secret-store', () => ({
|
||||||
|
checkApiSecret: store.checkApiSecret,
|
||||||
|
clearApiSecret: store.clearApiSecret,
|
||||||
|
getServerProxySnapshot: store.getServerProxySnapshot,
|
||||||
|
getStoredApiSecretSnapshot: store.getStoredApiSecretSnapshot,
|
||||||
|
listApiSecretModules: store.listApiSecretModules,
|
||||||
|
loadApiSecrets: store.loadApiSecrets,
|
||||||
|
saveApiSecret: store.saveApiSecret,
|
||||||
|
subscribeApiSecrets: store.subscribeApiSecrets,
|
||||||
|
fetchProxyBalanceSafely: store.fetchProxyBalanceSafely,
|
||||||
|
fetchLlmBalanceSafely: store.fetchLlmBalanceSafely,
|
||||||
|
}))
|
||||||
|
vi.mock('@/shared/api/types/modules/user-secret', () => ({
|
||||||
|
putMyApiSecret: secretApi.putMyApiSecret,
|
||||||
|
deleteMyApiSecret: secretApi.deleteMyApiSecret,
|
||||||
|
fetchProxyPlan: secretApi.fetchProxyPlan,
|
||||||
|
saveProxyPlan: secretApi.saveProxyPlan,
|
||||||
|
clearProxyPlan: secretApi.clearProxyPlan,
|
||||||
|
}))
|
||||||
|
vi.mock('@/shared/bridges/pywebview', () => ({
|
||||||
|
getPywebviewApi: () => ({ read_config: bridge.readConfig, save_config: bridge.saveConfig }),
|
||||||
|
}))
|
||||||
|
|
||||||
|
function emptySnapshot() {
|
||||||
|
return {
|
||||||
|
value: '', masked: '', channel: '', exists: false, locked: false,
|
||||||
|
checkStatus: 'unknown', checkCode: '', checkMessage: '',
|
||||||
|
checkLatencyMs: null, checkedAt: null, updatedAt: null,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function llmItem(over: Record<string, unknown> = {}) {
|
||||||
|
return {
|
||||||
|
moduleKey: 'appearance-patent',
|
||||||
|
moduleLabel: '外观专利密钥',
|
||||||
|
channel: 'longtaitou',
|
||||||
|
channelLabel: '龙抬头',
|
||||||
|
available: true,
|
||||||
|
balance: '88.888882',
|
||||||
|
availableBalance: '85.288882',
|
||||||
|
frozen: '3.6',
|
||||||
|
unit: 'CREDIT',
|
||||||
|
message: null,
|
||||||
|
checkedAt: '2026-11-05T10:30:00',
|
||||||
|
...over,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mountPanel() {
|
||||||
|
wrapper = mount(ApiSecretSettingsPanel)
|
||||||
|
await flushPromises()
|
||||||
|
await flushPromises()
|
||||||
|
return wrapper!
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 前两张是 LLM 卡(按 modules 清单顺序),最后一张固定是代理卡。 */
|
||||||
|
function llmCards(panel: VueWrapper) {
|
||||||
|
return panel.findAll('.secret-card').slice(0, 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
function proxyCard(panel: VueWrapper) {
|
||||||
|
const cards = panel.findAll('.secret-card')
|
||||||
|
return cards[cards.length - 1]
|
||||||
|
}
|
||||||
|
|
||||||
|
function cardByModule(panel: VueWrapper, moduleKey: string) {
|
||||||
|
const index = ['appearance-patent', 'similar-asin'].indexOf(moduleKey)
|
||||||
|
return llmCards(panel)[index]
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.clear()
|
||||||
|
localStorage.setItem('uid', UID)
|
||||||
|
vi.clearAllMocks()
|
||||||
|
store.listApiSecretModules.mockReturnValue([
|
||||||
|
{ moduleKey: 'appearance-patent', moduleLabel: '外观专利密钥' },
|
||||||
|
{ moduleKey: 'similar-asin', moduleLabel: '货源查询密钥' },
|
||||||
|
])
|
||||||
|
store.getStoredApiSecretSnapshot.mockReturnValue(emptySnapshot())
|
||||||
|
store.getServerProxySnapshot.mockReturnValue(null)
|
||||||
|
store.subscribeApiSecrets.mockReturnValue(() => undefined)
|
||||||
|
store.loadApiSecrets.mockResolvedValue('complete')
|
||||||
|
store.checkApiSecret.mockResolvedValue({ moduleKey: 'appearance-patent', checkStatus: 'passed', checkCode: 'ok', checkMessage: '连通正常', checkLatencyMs: 120, checkedAt: null, viaProxy: false })
|
||||||
|
store.fetchProxyBalanceSafely.mockResolvedValue({
|
||||||
|
available: true, surplus: '12', balance: '34', message: null, scope: 'user', low: false, lowReason: null,
|
||||||
|
})
|
||||||
|
// AP=龙抬头有钱、SA=贞贞查不了:这正是现网两把密钥最常见的一有一无形状
|
||||||
|
store.fetchLlmBalanceSafely.mockResolvedValue([
|
||||||
|
llmItem(),
|
||||||
|
llmItem({
|
||||||
|
moduleKey: 'similar-asin', moduleLabel: '货源查询密钥',
|
||||||
|
channel: 't8star', channelLabel: '贞贞',
|
||||||
|
available: false, balance: null, availableBalance: null, frozen: null, unit: null,
|
||||||
|
message: '贞贞渠道不提供余额查询;用量请看 ai.t8star.org 自己的控制台。',
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
bridge.readConfig.mockResolvedValue({ proxy_users: {} })
|
||||||
|
bridge.saveConfig.mockResolvedValue(undefined)
|
||||||
|
secretApi.putMyApiSecret.mockResolvedValue({})
|
||||||
|
secretApi.deleteMyApiSecret.mockResolvedValue({})
|
||||||
|
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
|
||||||
|
secretApi.saveProxyPlan.mockResolvedValue({})
|
||||||
|
secretApi.clearProxyPlan.mockResolvedValue({})
|
||||||
|
})
|
||||||
|
|
||||||
|
let wrapper: VueWrapper | null = null
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
wrapper?.unmount()
|
||||||
|
wrapper = null
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('余额行落在两张 LLM 卡上', () => {
|
||||||
|
it('两张卡各有一行 secret-meta(余额不是代理卡的专属)', async () => {
|
||||||
|
const panel = await mountPanel()
|
||||||
|
|
||||||
|
expect(llmCards(panel)).toHaveLength(2)
|
||||||
|
for (const card of llmCards(panel)) {
|
||||||
|
expect(card.find('.secret-meta').exists(), 'LLM 卡必须有余额行').toBe(true)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('龙抬头那一格给人民币读数,美元那两条数字一个都不出现', async () => {
|
||||||
|
const panel = await mountPanel()
|
||||||
|
const meta = cardByModule(panel, 'appearance-patent').find('.secret-meta').text()
|
||||||
|
|
||||||
|
expect(meta).toContain('龙抬头余额(人民币)')
|
||||||
|
expect(meta).toContain('¥88.89')
|
||||||
|
expect(meta).toContain('可用 ¥85.29')
|
||||||
|
expect(meta).toContain('更新于 10:30')
|
||||||
|
expect(meta, '美元串进了读数就是差 7.2 倍的假数').not.toContain('12.34')
|
||||||
|
expect(meta).not.toContain('$')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('贞贞那一格说不提供查询,且一个金额都不给', async () => {
|
||||||
|
const panel = await mountPanel()
|
||||||
|
const meta = cardByModule(panel, 'similar-asin').find('.secret-meta').text()
|
||||||
|
|
||||||
|
expect(meta).toContain('不提供余额查询')
|
||||||
|
expect(meta).not.toContain('¥')
|
||||||
|
expect(meta, '查不到不许读成欠费').not.toContain('0.00')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('两卡各回各的钱,A 的数字不许出现在 B 行', async () => {
|
||||||
|
store.fetchLlmBalanceSafely.mockResolvedValue([
|
||||||
|
llmItem({ balance: '88.888882', availableBalance: '85.288882' }),
|
||||||
|
llmItem({
|
||||||
|
moduleKey: 'similar-asin', moduleLabel: '货源查询密钥',
|
||||||
|
balance: '12.5', availableBalance: '10', frozen: null,
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
const panel = await mountPanel()
|
||||||
|
|
||||||
|
expect(cardByModule(panel, 'appearance-patent').find('.secret-meta').text()).toContain('¥88.89')
|
||||||
|
expect(cardByModule(panel, 'similar-asin').find('.secret-meta').text()).toContain('¥12.50')
|
||||||
|
expect(cardByModule(panel, 'similar-asin').find('.secret-meta').text()).not.toContain('88.89')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('抽组件之后代理余量那一行逐字未变', async () => {
|
||||||
|
const panel = await mountPanel()
|
||||||
|
|
||||||
|
// 本夹具的本机配置没有青果账密 ⇒ 供应商走默认的极客(`密钥面板青果检测` 那份才是青果形状)
|
||||||
|
expect(proxyCard(panel).find('.secret-meta').text()).toContain('极客余量(你的套餐)')
|
||||||
|
expect(proxyCard(panel).find('.secret-meta').text()).toContain('套餐IP 12')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('刷新时机:只读服务端已存密钥的那几次', () => {
|
||||||
|
it('打开面板刷一次,两张卡一起要(不带 moduleKey)', async () => {
|
||||||
|
await mountPanel()
|
||||||
|
|
||||||
|
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledTimes(1)
|
||||||
|
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledWith(undefined)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('浏览器形态(showProxy=false)也要刷——余额不属代理卡', async () => {
|
||||||
|
const panel = mount(ApiSecretSettingsPanel, { props: { showProxy: false } })
|
||||||
|
await flushPromises()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledTimes(1)
|
||||||
|
expect(llmCards(panel)[0].find('.secret-meta').text()).toContain('龙抬头余额')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('点某一格的刷新只刷那一格(带 moduleKey,不动另一格)', async () => {
|
||||||
|
const panel = await mountPanel()
|
||||||
|
store.fetchLlmBalanceSafely.mockClear()
|
||||||
|
|
||||||
|
await cardByModule(panel, 'similar-asin').find('.meta-refresh').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledTimes(1)
|
||||||
|
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledWith('similar-asin')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('检测输入值(未保存)不刷余额:那时库里还是上一把 key', async () => {
|
||||||
|
const panel = await mountPanel()
|
||||||
|
const card = cardByModule(panel, 'appearance-patent')
|
||||||
|
await card.find('.secret-input').setValue('sk-刚粘贴还没保存')
|
||||||
|
await flushPromises()
|
||||||
|
store.fetchLlmBalanceSafely.mockClear()
|
||||||
|
|
||||||
|
await card.find('.check-btn').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(store.checkApiSecret).toHaveBeenCalledWith('appearance-patent', 'sk-刚粘贴还没保存', expect.anything())
|
||||||
|
expect(store.fetchLlmBalanceSafely, '刷了就是拿上一把 key 的钱挂在这一行').not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('检测配置密钥(已存值)顺带刷那一格', async () => {
|
||||||
|
const panel = await mountPanel()
|
||||||
|
const card = cardByModule(panel, 'appearance-patent')
|
||||||
|
store.fetchLlmBalanceSafely.mockClear()
|
||||||
|
|
||||||
|
await card.find('.check-btn').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
expect(store.checkApiSecret).toHaveBeenCalledWith('appearance-patent', undefined, expect.anything())
|
||||||
|
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledTimes(1)
|
||||||
|
expect(store.fetchLlmBalanceSafely).toHaveBeenCalledWith('appearance-patent')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('接口整个失败时清空数字、只留「没查到」(不许留着上一把 key 的钱)', async () => {
|
||||||
|
store.fetchLlmBalanceSafely.mockResolvedValue([llmItem()])
|
||||||
|
const panel = await mountPanel()
|
||||||
|
expect(cardByModule(panel, 'appearance-patent').find('.secret-meta').text()).toContain('¥88.89')
|
||||||
|
|
||||||
|
store.fetchLlmBalanceSafely.mockRejectedValue(new Error('网络断了'))
|
||||||
|
await cardByModule(panel, 'appearance-patent').find('.meta-refresh').trigger('click')
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
const meta = cardByModule(panel, 'appearance-patent').find('.secret-meta').text()
|
||||||
|
expect(meta).not.toContain('88.89')
|
||||||
|
expect(meta).toContain('没查到')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -42,6 +42,7 @@ const store = vi.hoisted(() => ({
|
|||||||
saveApiSecret: vi.fn(),
|
saveApiSecret: vi.fn(),
|
||||||
subscribeApiSecrets: vi.fn(),
|
subscribeApiSecrets: vi.fn(),
|
||||||
fetchProxyBalanceSafely: vi.fn(),
|
fetchProxyBalanceSafely: vi.fn(),
|
||||||
|
fetchLlmBalanceSafely: vi.fn(),
|
||||||
}))
|
}))
|
||||||
const secretApi = vi.hoisted(() => ({
|
const secretApi = vi.hoisted(() => ({
|
||||||
putMyApiSecret: vi.fn(),
|
putMyApiSecret: vi.fn(),
|
||||||
@@ -66,6 +67,7 @@ vi.mock('@/shared/utils/api-secret-store', () => ({
|
|||||||
saveApiSecret: store.saveApiSecret,
|
saveApiSecret: store.saveApiSecret,
|
||||||
subscribeApiSecrets: store.subscribeApiSecrets,
|
subscribeApiSecrets: store.subscribeApiSecrets,
|
||||||
fetchProxyBalanceSafely: store.fetchProxyBalanceSafely,
|
fetchProxyBalanceSafely: store.fetchProxyBalanceSafely,
|
||||||
|
fetchLlmBalanceSafely: store.fetchLlmBalanceSafely,
|
||||||
}))
|
}))
|
||||||
vi.mock('@/shared/api/types/modules/user-secret', () => ({
|
vi.mock('@/shared/api/types/modules/user-secret', () => ({
|
||||||
putMyApiSecret: secretApi.putMyApiSecret,
|
putMyApiSecret: secretApi.putMyApiSecret,
|
||||||
@@ -148,6 +150,8 @@ beforeEach(() => {
|
|||||||
store.fetchProxyBalanceSafely.mockResolvedValue({
|
store.fetchProxyBalanceSafely.mockResolvedValue({
|
||||||
available: true, surplus: '12', balance: '34', message: null, scope: 'user', low: false, lowReason: null,
|
available: true, surplus: '12', balance: '34', message: null, scope: 'user', low: false, lowReason: null,
|
||||||
})
|
})
|
||||||
|
// 本文件的靶子是代理那一张卡;LLM 余额回空数组即可(面板按「没查到」显示,不参与这里的任何断言)
|
||||||
|
store.fetchLlmBalanceSafely.mockResolvedValue([])
|
||||||
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
|
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
|
||||||
bridge.readConfig.mockResolvedValue(qingguoConfig())
|
bridge.readConfig.mockResolvedValue(qingguoConfig())
|
||||||
bridge.saveConfig.mockResolvedValue(undefined)
|
bridge.saveConfig.mockResolvedValue(undefined)
|
||||||
|
|||||||
Reference in New Issue
Block a user