a10aa6bda3
现状纠偏(写死免得下次重研):桌面壳加载的是 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 例。
790 lines
32 KiB
Vue
790 lines
32 KiB
Vue
<template>
|
||
<div class="secret-settings-body">
|
||
<section v-for="module in modules" :key="module.moduleKey" class="secret-card">
|
||
<div class="secret-card-head">
|
||
<div class="secret-card-heading">
|
||
<div class="secret-card-title">
|
||
{{ module.moduleLabel }}
|
||
<span class="source-tag">{{ moduleSourceLabel(module.moduleKey, moduleChannels[module.moduleKey]) }}</span>
|
||
<span class="status-pill" :class="statusPillClassOf(module.moduleKey)">
|
||
{{ statusPillTextOf(module.moduleKey) }}
|
||
</span>
|
||
</div>
|
||
<div class="secret-card-desc">{{ descriptionOf(module.moduleKey) }}</div>
|
||
</div>
|
||
<button
|
||
v-if="snapshotOf(module.moduleKey).exists"
|
||
type="button"
|
||
class="link-danger"
|
||
:disabled="busy"
|
||
@click="clearModule(module.moduleKey as ApiSecretModuleKey)"
|
||
>
|
||
清空
|
||
</button>
|
||
</div>
|
||
|
||
<div class="source-picker" role="radiogroup" :aria-label="`${module.moduleLabel}渠道`">
|
||
<button
|
||
v-for="option in LLM_CHANNEL_OPTIONS"
|
||
:key="option.key"
|
||
type="button"
|
||
role="radio"
|
||
:aria-checked="moduleChannels[module.moduleKey] === option.key"
|
||
class="source-option"
|
||
:class="{ 'source-option--active': moduleChannels[module.moduleKey] === option.key }"
|
||
:disabled="busy"
|
||
@click="selectChannel(module.moduleKey, option.key)"
|
||
>
|
||
<span class="source-option-label">{{ option.label }}</span>
|
||
<span class="source-option-hint">{{ option.hint }}</span>
|
||
</button>
|
||
</div>
|
||
|
||
<div class="secret-field">
|
||
<label class="field-label" :for="`secret-input-${module.moduleKey}`">接口密钥</label>
|
||
<div class="password-field">
|
||
<input
|
||
:id="`secret-input-${module.moduleKey}`"
|
||
v-model="moduleStates[module.moduleKey].input"
|
||
class="secret-input"
|
||
:type="llmVisibility.inputTypeOf(module.moduleKey)"
|
||
:placeholder="placeholderOf(module.moduleKey)"
|
||
autocomplete="off"
|
||
spellcheck="false"
|
||
:disabled="busy"
|
||
/>
|
||
<SecretVisibilityToggle
|
||
:visible="llmVisibility.visibleOf(module.moduleKey)"
|
||
:disabled="busy"
|
||
@toggle="llmVisibility.toggle(module.moduleKey)"
|
||
/>
|
||
</div>
|
||
</div>
|
||
|
||
<div v-if="channelSwitchNeedsValue(module.moduleKey)" class="inline-warn">
|
||
已切换到「{{ llmChannelLabel(moduleChannels[module.moduleKey]) }}」,请填写该渠道的密钥后再保存(两家渠道的密钥不通用)。
|
||
</div>
|
||
|
||
<div class="secret-actions">
|
||
<button
|
||
type="button"
|
||
class="check-btn"
|
||
:disabled="busy || moduleStates[module.moduleKey].checking"
|
||
@click="runCheck(module.moduleKey as ApiSecretModuleKey)"
|
||
>
|
||
{{ moduleStates[module.moduleKey].checking ? '检测中...' : (moduleStates[module.moduleKey].input.trim() ? '检测输入值(未保存)' : '检测配置密钥') }}
|
||
</button>
|
||
<span class="check-result" :class="resultClassOf(module.moduleKey)">
|
||
{{ statusTextOf(module.moduleKey) }}
|
||
</span>
|
||
</div>
|
||
|
||
<SecretBalanceRow
|
||
:text="llmMetaText(module.moduleKey)"
|
||
:updated-at="llmBalanceUpdatedAtOf(module.moduleKey)"
|
||
:refreshing="llmBalanceLoading"
|
||
@refresh="() => loadLlmBalance(module.moduleKey)"
|
||
/>
|
||
</section>
|
||
|
||
<section v-if="showProxy" class="secret-card">
|
||
<div class="secret-card-head">
|
||
<div class="secret-card-heading">
|
||
<div class="secret-card-title">
|
||
代理设置
|
||
<span class="source-tag">{{ proxyProviderLabel(proxyProvider) }}</span>
|
||
<span v-if="proxyLocked" class="lock-tag">后台锁定</span>
|
||
</div>
|
||
<div class="secret-card-desc">
|
||
{{ proxyLocked
|
||
? '代理由管理员统一配置并锁定,客户端不可修改或清空;如需变更请联系管理员。'
|
||
: (proxyProvider === 'qingguo'
|
||
? '青果用 Authkey / Authpwd 直连隧道代理,无需填写提取链接。'
|
||
: '供客户端任务连接代理服务,支持静态代理地址或代理服务商的提取链接。') }}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="source-picker" role="radiogroup" aria-label="代理供应商">
|
||
<button
|
||
v-for="option in PROXY_PROVIDER_OPTIONS"
|
||
:key="option.key"
|
||
type="button"
|
||
role="radio"
|
||
:aria-checked="proxyProvider === option.key"
|
||
class="source-option"
|
||
:class="{ 'source-option--active': proxyProvider === option.key }"
|
||
:disabled="!proxyReady || busy || proxyLocked"
|
||
@click="selectProxyProvider(option.key)"
|
||
>
|
||
<span class="source-option-label">{{ option.label }}</span>
|
||
<span class="source-option-hint">{{ option.hint }}</span>
|
||
</button>
|
||
</div>
|
||
|
||
<div v-if="proxyProvider !== 'qingguo'" class="proxy-field">
|
||
<label class="field-label" for="proxy-url">代理地址</label>
|
||
<input
|
||
id="proxy-url"
|
||
v-model="proxyUrl"
|
||
class="secret-input"
|
||
type="text"
|
||
:placeholder="proxyPlaceholder"
|
||
autocomplete="off"
|
||
spellcheck="false"
|
||
:disabled="!proxyReady || busy || proxyLocked"
|
||
@input="proxyDirty = true"
|
||
/>
|
||
</div>
|
||
|
||
<div v-if="proxyReady && proxyProvider === 'qingguo'" class="retention-block">
|
||
<div class="field-label">隧道代理账号(青果 Authkey / Authpwd)</div>
|
||
<div class="proxy-plan-row">
|
||
<input
|
||
v-model="proxyAccount"
|
||
class="secret-input"
|
||
type="text"
|
||
placeholder="Authkey,如 40F79A90"
|
||
autocomplete="off"
|
||
spellcheck="false"
|
||
:disabled="busy || proxyLocked"
|
||
@input="proxyDirty = true"
|
||
/>
|
||
<div class="password-field">
|
||
<input
|
||
v-model="proxyPassword"
|
||
class="secret-input"
|
||
:type="proxyPasswordType"
|
||
placeholder="Authpwd"
|
||
autocomplete="off"
|
||
spellcheck="false"
|
||
:disabled="busy || proxyLocked"
|
||
@input="proxyDirty = true"
|
||
/>
|
||
<SecretVisibilityToggle
|
||
:visible="proxyPasswordVisible"
|
||
:disabled="busy || proxyLocked"
|
||
@toggle="toggleProxyPasswordVisibility"
|
||
/>
|
||
</div>
|
||
</div>
|
||
<div class="proxy-plan-hint">
|
||
青果没有可填的提取链接:保存时用 Authkey / Authpwd 自动拼出
|
||
<code>overseas.proxy.qg.net/get?key=…&format=json</code>(Basic 认证也带在同一条链接里),
|
||
本地与后台密钥各存一份。服务端的商标检测用的就是这条链接,不填账密它会按「未配置代理」拦下任务。
|
||
Authpwd 默认掩码,点输入框右侧的眼睛可核对;保存成功后自动回到掩码。
|
||
</div>
|
||
</div>
|
||
|
||
<div v-if="proxySupported && proxyProvider === 'jikip'" class="retention-block">
|
||
<div class="field-label">jikip 套餐信息(余量查询)
|
||
</div>
|
||
<div class="proxy-plan-row">
|
||
<input
|
||
v-model="proxyPlanId"
|
||
class="secret-input"
|
||
type="text"
|
||
placeholder="套餐 ID"
|
||
autocomplete="off"
|
||
spellcheck="false"
|
||
:disabled="proxyPlanLoading || proxyPlanSaving"
|
||
/>
|
||
<input
|
||
v-model="proxyPlanUserId"
|
||
class="secret-input"
|
||
type="text"
|
||
placeholder="用户 ID"
|
||
autocomplete="off"
|
||
spellcheck="false"
|
||
:disabled="proxyPlanLoading || proxyPlanSaving"
|
||
/>
|
||
</div>
|
||
<div class="proxy-plan-row proxy-plan-row--single">
|
||
<div class="password-field">
|
||
<input
|
||
v-model="proxyPlanKey"
|
||
class="secret-input"
|
||
:type="planKeyType"
|
||
:placeholder="proxyPlanKeyPlaceholder"
|
||
autocomplete="off"
|
||
spellcheck="false"
|
||
:disabled="proxyPlanLoading || proxyPlanSaving"
|
||
/>
|
||
<SecretVisibilityToggle
|
||
:visible="planKeyVisible"
|
||
:disabled="proxyPlanLoading || proxyPlanSaving"
|
||
@toggle="togglePlanKeyVisibility"
|
||
/>
|
||
</div>
|
||
</div>
|
||
<div class="secret-actions">
|
||
<button
|
||
type="button"
|
||
class="check-btn"
|
||
:disabled="proxyPlanLoading || proxyPlanSaving"
|
||
@click="saveProxyPlanInfo"
|
||
>
|
||
{{ proxyPlanSaving ? '保存中...' : '保存套餐信息' }}
|
||
</button>
|
||
<button
|
||
v-if="proxyPlanConfigured"
|
||
type="button"
|
||
class="link-danger"
|
||
:disabled="proxyPlanSaving"
|
||
@click="clearProxyPlanInfo"
|
||
>
|
||
清除
|
||
</button>
|
||
</div>
|
||
<div class="proxy-plan-hint">
|
||
填写后,下方余量按你自己的 jikip 套餐查询;套餐 key 保存后只显示掩码,留空保存则保留已存值。套餐 ID / 用户 ID / key 在 jikip 后台「我的套餐」「账户信息」「套餐列表」查看。
|
||
</div>
|
||
</div>
|
||
<div v-else-if="proxySupported && proxyProvider === 'qingguo'" class="proxy-plan-hint">
|
||
青果的套餐与通道用量以青果后台为准;这里的「检测」会真打一次提取并经隧道验连——
|
||
它会占掉你那一条通道的存活期(约 3 分钟),期间再点会得到「无可用通道」。若隔几分钟仍报同一句,多半不是被占,而是这把 key 的套餐到期/无余量,或后台把鉴权切成了 IP 白名单档——去青果控制台核对通道数与有效期。
|
||
</div>
|
||
|
||
<div class="secret-actions">
|
||
<button
|
||
type="button"
|
||
class="check-btn"
|
||
:disabled="!proxyReady || busy || proxyChecking"
|
||
@click="runProxyCheck"
|
||
>
|
||
{{ proxyCheckLabel }}
|
||
</button>
|
||
<span class="check-result" :class="proxyResultClass">
|
||
{{ proxyStatusText }}
|
||
</span>
|
||
</div>
|
||
|
||
<SecretBalanceRow :text="proxyMetaText" :refreshing="balanceLoading" @refresh="loadBalance" />
|
||
</section>
|
||
</div>
|
||
</template>
|
||
|
||
<script setup lang="ts">
|
||
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
|
||
import { ElMessage } from 'element-plus'
|
||
import {
|
||
checkApiSecret,
|
||
clearApiSecret,
|
||
getServerProxySnapshot,
|
||
getStoredApiSecretSnapshot,
|
||
listApiSecretModules,
|
||
loadApiSecrets,
|
||
saveApiSecret,
|
||
subscribeApiSecrets,
|
||
type ApiSecretModuleKey,
|
||
type ApiSecretSnapshot,
|
||
type ServerProxySnapshot,
|
||
type UserApiSecretCheckResult,
|
||
} from '@/shared/utils/api-secret-store'
|
||
import {
|
||
DEFAULT_LLM_CHANNEL,
|
||
DEFAULT_PROXY_PROVIDER,
|
||
LLM_CHANNEL_OPTIONS,
|
||
PROXY_PROVIDER_OPTIONS,
|
||
llmChannelLabel,
|
||
moduleSourceLabel,
|
||
normalizeLlmChannel,
|
||
normalizeProxyProvider,
|
||
proxyCheckValue,
|
||
proxyProviderLabel,
|
||
type LlmChannelKey,
|
||
type ProxyProviderKey,
|
||
} from '@/shared/utils/api-secret-channel'
|
||
import { getPywebviewApi, type ProxyMode, type DesktopConfigUpdate } from '@/shared/bridges/pywebview'
|
||
import {
|
||
deleteMyApiSecret,
|
||
putMyApiSecret,
|
||
} from '@/shared/api/types/modules/user-secret'
|
||
import {
|
||
composeQingguoLink,
|
||
proxyUserId,
|
||
readUserProxy,
|
||
userProxyPatch,
|
||
} from '@/shared/utils/api-secret-proxy-config'
|
||
import { useProxyBalance, useProxyPlan } from '@/shared/composables/useProxyPlan'
|
||
import { useKeyedSecretVisibility, useSecretVisibility } from '@/shared/composables/useSecretVisibility'
|
||
import { useLlmBalance } from '@/shared/composables/useLlmBalance'
|
||
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'
|
||
|
||
const props = withDefaults(
|
||
defineProps<{
|
||
/** 是否展示代理设置区(默认展示)。 */
|
||
showProxy?: boolean
|
||
}>(),
|
||
{
|
||
showProxy: true,
|
||
},
|
||
)
|
||
|
||
const modules = ref(listApiSecretModules())
|
||
const moduleStates = reactive<Record<string, ModuleState>>({})
|
||
/** 每个模块当前选择的渠道:默认龙抬头,加载后以服务端已存值为准。 */
|
||
const moduleChannels = reactive<Record<string, LlmChannelKey>>({})
|
||
/** 用户手动切过渠道、但还没为这个渠道填写密钥:保存前必须拦住(两家密钥不通用)。 */
|
||
const channelDirty = reactive<Record<string, boolean>>({})
|
||
// 首次渲染即需可读:按模块清单预初始化状态(后续 refreshSnapshots 兜底补齐)
|
||
for (const module of modules.value) {
|
||
moduleStates[module.moduleKey] = { input: '', checking: false, result: null, error: '', lastCheckSource: '' }
|
||
moduleChannels[module.moduleKey] = DEFAULT_LLM_CHANNEL
|
||
channelDirty[module.moduleKey] = false
|
||
}
|
||
const snapshots = ref<Record<string, ApiSecretSnapshot>>({})
|
||
const busy = ref(false)
|
||
|
||
/** 服务端代理状态:后台代填并锁定时客户端只读。 */
|
||
const serverProxy = ref<ServerProxySnapshot | null>(getServerProxySnapshot())
|
||
const proxyLocked = computed(() => Boolean(serverProxy.value?.locked && serverProxy.value?.exists))
|
||
|
||
const proxyUrl = ref('')
|
||
const proxyMode = ref<ProxyMode>(1)
|
||
const proxyProvider = ref<ProxyProviderKey>(DEFAULT_PROXY_PROVIDER)
|
||
/** 青果隧道端点的代理账密(Authkey/Authpwd):只存本机 app.json,不上报服务端。 */
|
||
const proxyAccount = ref('')
|
||
const proxyPassword = ref('')
|
||
/**
|
||
* 面板里每一把"掩码输入"的显隐,同一个出处(2026-11-02 用户点名:填错了看不见,只能靠猜)。
|
||
* 眼睛只切自己那一格的 type;状态不落 localStorage、不进日志与上报,
|
||
* 重新读取本机配置 / 切供应商 / 保存成功 / 组件卸载全部回到掩码(与「保存成功即清空输入」同一口径)。
|
||
*
|
||
* LLM 那两把(外观专利/货源查询)共用同一段循环模板 ⇒ 必须按键隔离,
|
||
* 否则点一张卡的眼睛会把另一张也摊成明文。
|
||
*/
|
||
const {
|
||
visible: proxyPasswordVisible,
|
||
inputType: proxyPasswordType,
|
||
toggle: toggleProxyPasswordVisibility,
|
||
reset: resetProxyPasswordVisibility,
|
||
} = useSecretVisibility()
|
||
const {
|
||
visible: planKeyVisible,
|
||
inputType: planKeyType,
|
||
toggle: togglePlanKeyVisibility,
|
||
reset: resetPlanKeyVisibility,
|
||
} = useSecretVisibility()
|
||
const llmVisibility = useKeyedSecretVisibility()
|
||
function resetSecretVisibility() {
|
||
resetProxyPasswordVisibility()
|
||
resetPlanKeyVisibility()
|
||
llmVisibility.resetAll()
|
||
}
|
||
const proxyLoading = ref(false)
|
||
const proxyLoadFailed = ref(false)
|
||
const proxyReady = ref(false)
|
||
const proxySupported = ref(false)
|
||
const proxyDirty = ref(false)
|
||
|
||
const proxyChecking = ref(false)
|
||
const proxyCheckResult = ref<UserApiSecretCheckResult | null>(null)
|
||
const proxyCheckError = ref('')
|
||
|
||
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 {
|
||
proxyPlanId,
|
||
proxyPlanUserId,
|
||
proxyPlanKey,
|
||
proxyPlanKeyConfigured,
|
||
proxyPlanKeyMasked,
|
||
proxyPlanConfigured,
|
||
proxyPlanLoading,
|
||
proxyPlanSaving,
|
||
proxyPlanKeyPlaceholder,
|
||
loadProxyPlan,
|
||
saveProxyPlanInfo,
|
||
clearProxyPlanInfo,
|
||
} = useProxyPlan({ proxyProvider, resetWhitelistStatus: () => {}, loadBalance })
|
||
|
||
const proxyPlaceholder = 'https://api.jikip.com/ip-get?num=1&minute=3&key=... 或 http://user:pass@host:port'
|
||
|
||
/**
|
||
* 「检测」要送出去的链接:没改动→undefined(服务端用库里那条),改了没保存→当前输入。
|
||
* 空串=草稿拼不出链接(青果没填 Authkey/极客把地址清空),这种检测必然失败,按钮与点击都拦住。
|
||
*/
|
||
const proxyCheckDraft = computed(() => proxyCheckValue({
|
||
provider: proxyProvider.value,
|
||
url: proxyUrl.value,
|
||
dirty: proxyDirty.value,
|
||
account: proxyAccount.value,
|
||
password: proxyPassword.value,
|
||
}))
|
||
const proxyDraftUnusable = computed(() => proxyDirty.value && !proxyCheckDraft.value)
|
||
|
||
/** 按钮文案要说清「检的是哪一条」:未保存的输入值,还是库里已存的配置。 */
|
||
const proxyCheckLabel = computed(() => {
|
||
if (proxyChecking.value) return '检测中...'
|
||
if (proxyDraftUnusable.value) {
|
||
return proxyProvider.value === 'qingguo' ? '请先填写青果账密' : '请先填写代理地址'
|
||
}
|
||
if (proxyCheckDraft.value === undefined) return '检测配置代理'
|
||
return proxyProvider.value === 'qingguo' ? '检测输入账密(未保存)' : '检测输入地址(未保存)'
|
||
})
|
||
|
||
/** 检测结果:文案原样用接口返回值,语气(颜色)只按后端 status 分档,见 proxyCheckPresentation。 */
|
||
const proxyCheckView = computed(() => proxyCheckPresentation(
|
||
proxyCheckResult.value,
|
||
proxyChecking.value,
|
||
proxyCheckError.value,
|
||
))
|
||
const proxyStatusText = computed(() => proxyCheckView.value.text)
|
||
|
||
const proxyResultClass = computed(() => ({
|
||
'check-result--ok': proxyCheckView.value.tone === 'ok',
|
||
'check-result--fail': proxyCheckView.value.tone === 'fail',
|
||
'check-result--warn': proxyCheckView.value.tone === 'retry',
|
||
}))
|
||
|
||
/** 切换代理供应商:只改本地选择,保存时与地址一起写入(检测也会按新供应商解析响应)。 */
|
||
function selectProxyProvider(provider: ProxyProviderKey) {
|
||
if (proxyProvider.value === provider) return
|
||
proxyProvider.value = provider
|
||
// 青果只支持账号密码直连,模式随供应商锁死;切回极客再让用户自选
|
||
if (provider === 'qingguo') proxyMode.value = 2
|
||
proxyDirty.value = true
|
||
proxyCheckResult.value = null
|
||
proxyCheckError.value = ''
|
||
// 换的是「哪一家的账密」,明文状态没有理由跟着走过去
|
||
resetSecretVisibility()
|
||
}
|
||
|
||
|
||
/** 检测代理连通性:改动过就送当前输入(不落库),没改动就送 undefined 让服务端检库里那条。 */
|
||
async function runProxyCheck() {
|
||
if (proxyChecking.value) return
|
||
if (proxyDraftUnusable.value) {
|
||
// 拼不出链接就别发一次必然失败的请求:空串送上去等于「不送 override」,服务端会去检库里那条旧链接
|
||
ElMessage.warning(proxyProvider.value === 'qingguo'
|
||
? '青果要先填 Authkey(Authpwd 也必填)才拼得出可检测的链接;填完直接点检测即可,不必先保存'
|
||
: '请先填写代理地址,再点检测')
|
||
return
|
||
}
|
||
const draft = proxyCheckDraft.value
|
||
const fromDraft = draft !== undefined
|
||
proxyChecking.value = true
|
||
proxyCheckError.value = ''
|
||
proxyCheckResult.value = null
|
||
try {
|
||
// 供应商一起提交:检测要按对应供应商解析提取响应(青果/极客返回体不同)
|
||
proxyCheckResult.value = await checkApiSecret('proxy', draft, proxyProvider.value)
|
||
const result = proxyCheckResult.value
|
||
if (result.checkStatus === 'passed') {
|
||
ElMessage.success(fromDraft ? '输入值连通正常(未保存)' : '代理连通正常')
|
||
} else {
|
||
// 弹窗与行内用同一段文字:都是接口返回的原文,前端不再按错误码另写一套措辞
|
||
ElMessage.warning(proxyCheckPresentation(result, false, '').text || '代理检测失败')
|
||
}
|
||
} catch (error) {
|
||
proxyCheckError.value = error instanceof Error ? error.message : '代理检测失败'
|
||
ElMessage.error(proxyCheckError.value)
|
||
} finally {
|
||
proxyChecking.value = false
|
||
}
|
||
}
|
||
|
||
function ensureModuleState(moduleKey: string) {
|
||
if (!moduleStates[moduleKey]) {
|
||
moduleStates[moduleKey] = { input: '', checking: false, result: null, error: '', lastCheckSource: '' }
|
||
}
|
||
if (!moduleChannels[moduleKey]) {
|
||
moduleChannels[moduleKey] = DEFAULT_LLM_CHANNEL
|
||
}
|
||
return moduleStates[moduleKey]
|
||
}
|
||
|
||
/** 用户切换渠道:只改选择,保存时随密钥一起提交;已有密钥但没重新填写时给出提示。 */
|
||
function selectChannel(moduleKey: string, channel: LlmChannelKey) {
|
||
if (moduleChannels[moduleKey] === channel) return
|
||
moduleChannels[moduleKey] = channel
|
||
channelDirty[moduleKey] = true
|
||
}
|
||
|
||
/** 切到新渠道但没填新密钥(且已有旧渠道密钥):保存前必须拦住。 */
|
||
function channelSwitchNeedsValue(moduleKey: string) {
|
||
return Boolean(channelDirty[moduleKey]) && !ensureModuleState(moduleKey).input.trim() && snapshotOf(moduleKey).exists
|
||
}
|
||
|
||
function refreshSnapshots() {
|
||
modules.value = listApiSecretModules()
|
||
const next: Record<string, ApiSecretSnapshot> = {}
|
||
for (const module of modules.value) {
|
||
next[module.moduleKey] = getStoredApiSecretSnapshot(module.moduleKey as ApiSecretModuleKey)
|
||
ensureModuleState(module.moduleKey)
|
||
// 只在用户没主动切换过时跟服务端对齐,避免把手动选择回退掉
|
||
if (!channelDirty[module.moduleKey]) {
|
||
moduleChannels[module.moduleKey] = normalizeLlmChannel(next[module.moduleKey].channel)
|
||
}
|
||
}
|
||
snapshots.value = next
|
||
serverProxy.value = getServerProxySnapshot()
|
||
}
|
||
|
||
function snapshotOf(moduleKey: string): ApiSecretSnapshot {
|
||
return snapshots.value[moduleKey] || getStoredApiSecretSnapshot(moduleKey as ApiSecretModuleKey)
|
||
}
|
||
|
||
const { descriptionOf, placeholderOf, statusPillTextOf, statusPillClassOf, statusTextOf, resultClassOf } = createModuleView({
|
||
moduleChannels,
|
||
ensureModuleState,
|
||
snapshotOf,
|
||
})
|
||
|
||
async function runCheck(moduleKey: ApiSecretModuleKey) {
|
||
const state = ensureModuleState(moduleKey)
|
||
if (state.checking) return
|
||
state.checking = true
|
||
state.error = ''
|
||
state.result = null
|
||
const inputValue = state.input.trim()
|
||
state.lastCheckSource = inputValue ? 'input' : 'saved'
|
||
try {
|
||
// 不传 override 时服务端检测的是当前登录用户在密钥配置里保存的密钥(按 uid 绑定)
|
||
// 渠道一起提交:检测必须走所选渠道,否则「连通」是别的渠道的结论
|
||
const result = await checkApiSecret(moduleKey, inputValue || undefined, moduleChannels[moduleKey])
|
||
state.result = result
|
||
if (result.checkStatus === 'failed') {
|
||
ElMessage.warning(result.checkMessage || '密钥无效')
|
||
} else if (result.checkStatus === 'error') {
|
||
ElMessage.warning(result.checkMessage || '暂时无法判定密钥有效性')
|
||
} else {
|
||
ElMessage.success(inputValue ? '输入值检测通过(未保存)' : '配置密钥检测通过')
|
||
}
|
||
} catch (error) {
|
||
state.error = error instanceof Error ? error.message : '检测失败'
|
||
ElMessage.error(state.error)
|
||
} finally {
|
||
state.checking = false
|
||
refreshSnapshots()
|
||
// 只有「检测已存密钥」才顺带刷余额:检测输入值时库里还是上一把 key,刷出来是上一把的钱(串档形状)
|
||
if (!inputValue) void loadLlmBalance(moduleKey)
|
||
}
|
||
}
|
||
|
||
async function clearModule(moduleKey: ApiSecretModuleKey) {
|
||
if (busy.value) return
|
||
busy.value = true
|
||
try {
|
||
await clearApiSecret(moduleKey)
|
||
const state = ensureModuleState(moduleKey)
|
||
state.input = ''
|
||
state.result = null
|
||
state.error = ''
|
||
channelDirty[moduleKey] = false
|
||
refreshSnapshots()
|
||
// 清空后库里已经没有这把 key:不刷的话,这一行会继续挂着上一把 key 的钱
|
||
void loadLlmBalance(moduleKey)
|
||
ElMessage.success('已清空密钥')
|
||
} catch (error) {
|
||
ElMessage.error(error instanceof Error ? error.message : '清空失败')
|
||
} finally {
|
||
busy.value = false
|
||
}
|
||
}
|
||
|
||
async function loadProxyConfig() {
|
||
proxyLoading.value = true
|
||
proxyLoadFailed.value = false
|
||
proxyReady.value = false
|
||
proxyDirty.value = false
|
||
// 每次重新读取本机配置=换号或重开弹窗:读到的可能就是另一个账号的 Authpwd,不许还亮着明文
|
||
resetSecretVisibility()
|
||
|
||
const api = getPywebviewApi()
|
||
proxySupported.value = Boolean(api?.read_config && api?.save_config)
|
||
if (!api?.read_config || !api.save_config) {
|
||
proxyUrl.value = ''
|
||
proxyMode.value = 1
|
||
proxyLoading.value = false
|
||
return
|
||
}
|
||
|
||
try {
|
||
const config = await api.read_config()
|
||
const own = readUserProxy(config as Record<string, unknown>)
|
||
proxyUrl.value = own.url
|
||
proxyMode.value = (own.mode === 2 ? 2 : 1) as ProxyMode
|
||
proxyAccount.value = own.account
|
||
proxyPassword.value = own.password
|
||
// 本地配置是权威(客户端任务链读的就是它);本地没写过时才用服务端里记的供应商
|
||
proxyProvider.value = own.url
|
||
? own.provider
|
||
: normalizeProxyProvider(serverProxy.value?.channel ?? own.provider)
|
||
// 青果只走账密认证,历史配置若停在白名单也强制拉回账号密码
|
||
if (proxyProvider.value === 'qingguo') proxyMode.value = 2
|
||
proxyReady.value = true
|
||
} catch (error) {
|
||
proxyLoadFailed.value = true
|
||
ElMessage.error(error instanceof Error ? error.message : '代理配置读取失败')
|
||
} finally {
|
||
proxyLoading.value = false
|
||
}
|
||
}
|
||
|
||
/** 代理配置上报服务端(后台密钥管理观测/检测):有地址则保存、清空则删除;失败不阻断本地保存。 */
|
||
async function syncProxyToServer(url: string): Promise<boolean> {
|
||
if (proxyUserId() === '0') return false
|
||
try {
|
||
if (url) {
|
||
// 供应商随地址一起上报:服务端检测要按供应商解析提取响应
|
||
await putMyApiSecret('proxy', url, proxyProvider.value)
|
||
} else {
|
||
await deleteMyApiSecret('proxy')
|
||
}
|
||
return true
|
||
} catch (error) {
|
||
console.warn('[api-secret] 代理配置上报失败(不影响本地任务):', error)
|
||
ElMessage.warning('代理已保存到本地,但上报后台失败')
|
||
return false
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 保存:逐模块保存非空输入(空输入保留服务端原值),代理仅在改动时保存。
|
||
* 检测一律由用户手动点击触发;保存时服务端会沿用「刚检测过的同一个输入值」的结果,
|
||
* 其余情况(改过值 / 从未检测)保持未检测,需用户点「检测」确认可用性。
|
||
*/
|
||
async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean> {
|
||
if (busy.value || proxyLoading.value) return false
|
||
// 切了渠道却只留着旧渠道的密钥:两家密钥不通用,必须让用户补填,否则保存后必然不可用
|
||
const needRefill = modules.value.filter((module) => channelSwitchNeedsValue(module.moduleKey))
|
||
if (needRefill.length) {
|
||
ElMessage.warning(
|
||
`已切换渠道,请填写该渠道的密钥:${needRefill.map((module) => module.moduleLabel).join('、')}`,
|
||
)
|
||
return false
|
||
}
|
||
const pendingModules = modules.value.filter((module) => ensureModuleState(module.moduleKey).input.trim())
|
||
if (options.requireAll) {
|
||
const missing = modules.value.filter(
|
||
(module) => !ensureModuleState(module.moduleKey).input.trim() && !snapshotOf(module.moduleKey).exists,
|
||
)
|
||
if (missing.length) {
|
||
ElMessage.warning(`请填写:${missing.map((module) => module.moduleLabel).join('、')}`)
|
||
return false
|
||
}
|
||
}
|
||
|
||
busy.value = true
|
||
let secretsSaved = false
|
||
try {
|
||
for (const module of pendingModules) {
|
||
const moduleKey = module.moduleKey as ApiSecretModuleKey
|
||
const state = ensureModuleState(module.moduleKey)
|
||
await saveApiSecret(moduleKey, state.input.trim(), moduleChannels[module.moduleKey])
|
||
state.input = ''
|
||
// 输入值已保存:本地那次「检测输入值」的结果不再代表当前配置,清掉后展示统一走服务端快照
|
||
// (保存前检测过的同一个值,服务端会沿用那次结果,快照里直接是「检测通过」)
|
||
state.result = null
|
||
state.lastCheckSource = ''
|
||
state.error = ''
|
||
channelDirty[module.moduleKey] = false
|
||
}
|
||
secretsSaved = true
|
||
refreshSnapshots()
|
||
void loadLlmBalance()
|
||
|
||
if (props.showProxy && proxyReady.value && proxyDirty.value && !proxyLocked.value) {
|
||
const api = getPywebviewApi()
|
||
if (!api?.save_config) throw new Error('当前客户端未提供代理配置保存能力')
|
||
// 青果走账密直连隧道,不保存提取链接;切回极客时输入框里的旧值仍在
|
||
const tunnelMode = proxyProvider.value === 'qingguo'
|
||
// 青果没有提取链接可填:由 Authkey/Authpwd 拼出来(2026-10-31 用户拍板)。
|
||
// 本地与服务端用同一条链接——服务端商标检测(16890)只收得到 proxy_url,
|
||
// 拼空串等于用户填了账密却仍被判「未配置代理」。
|
||
const nextProxyUrl = tunnelMode
|
||
? composeQingguoLink(proxyAccount.value, proxyPassword.value)
|
||
: proxyUrl.value.trim()
|
||
const nextProxyMode = tunnelMode ? 2 : proxyMode.value
|
||
await api.save_config(
|
||
userProxyPatch(nextProxyUrl, nextProxyMode, proxyProvider.value, proxyAccount.value, proxyPassword.value) as DesktopConfigUpdate,
|
||
)
|
||
if (!tunnelMode) proxyUrl.value = nextProxyUrl
|
||
proxyDirty.value = false
|
||
// 同上:地址已保存,本地「未保存」的检测文案不再适用
|
||
proxyCheckResult.value = null
|
||
proxyCheckError.value = ''
|
||
await syncProxyToServer(nextProxyUrl)
|
||
void loadProxyPlan()
|
||
void loadBalance()
|
||
}
|
||
|
||
// 保存后不再自动检测:检测一律由用户手动点击「检测」触发
|
||
// 保存成功=账密已落到本机与服务端,界面没有理由还把 Authpwd 亮着明文;
|
||
// 失败分支不动(那时用户正需要核对填错在哪一位)。
|
||
resetSecretVisibility()
|
||
refreshSnapshots()
|
||
return true
|
||
} catch (error) {
|
||
const message = error instanceof Error ? error.message : '设置保存失败'
|
||
ElMessage.error(secretsSaved ? `密钥已保存,但后续步骤失败:${message}` : message)
|
||
return false
|
||
} finally {
|
||
busy.value = false
|
||
}
|
||
}
|
||
|
||
/** 重新从服务端拉取(设置页/弹窗打开时调用)。 */
|
||
async function reload() {
|
||
await loadApiSecrets({ force: true })
|
||
refreshSnapshots()
|
||
}
|
||
|
||
watch(proxyProvider, (provider) => {
|
||
// 切到极客时补拉套餐信息(含套餐 key 是否已配置)
|
||
if (provider === 'jikip' && proxySupported.value) {
|
||
void loadProxyPlan()
|
||
}
|
||
})
|
||
|
||
let unsubscribe: (() => void) | null = null
|
||
|
||
onMounted(() => {
|
||
refreshSnapshots()
|
||
unsubscribe = subscribeApiSecrets(refreshSnapshots)
|
||
// 先拉服务端密钥包(后台锁定的代理会先对齐到本地配置),再读本地代理,避免展示对齐前的旧值
|
||
void (async () => {
|
||
await reload()
|
||
// 读的是服务端已存密钥 ⇒ 排在 reload 之后;且它不属代理卡(浏览器形态 showProxy=false 会永远空白)
|
||
void loadLlmBalance()
|
||
if (props.showProxy) {
|
||
await loadProxyConfig()
|
||
if (proxySupported.value) {
|
||
void loadProxyPlan()
|
||
}
|
||
void loadBalance()
|
||
}
|
||
})()
|
||
})
|
||
|
||
onUnmounted(() => {
|
||
if (unsubscribe) unsubscribe()
|
||
// 卸载即回到掩码:弹窗若是 v-show 留着复用,重载路径上不该还显示着上一个账号的明文
|
||
resetSecretVisibility()
|
||
})
|
||
|
||
defineExpose({ saveAll, reload })
|
||
</script>
|
||
|
||
<style scoped src="./api-secret-settings-panel.css"></style>
|