feat(frontend): 客户端损耗保护弹窗与共享密钥提示

- 30 秒轮询损耗状态;暂停时红色弹窗/横幅并提供「继续任务」
- 共享密钥黄色提示条,按类型去重,不重复刷屏
- 通知铃铛登记 cost_guard / secret_shared 场景
This commit is contained in:
2026-10-24 10:50:24 +08:00
parent 9c4905c94e
commit b94555f411
7 changed files with 466 additions and 1 deletions
+2
View File
@@ -3,6 +3,7 @@
<router-view />
<ExpiryNotice />
<ProxyBalanceAlert />
<CostGuardAlert />
<ForceUpdateGate />
</el-config-provider>
</template>
@@ -18,6 +19,7 @@ import { onBeforeUnmount } from 'vue'
import ExpiryNotice from '@/shared/components/ExpiryNotice.vue'
import ForceUpdateGate from '@/shared/components/ForceUpdateGate.vue'
import ProxyBalanceAlert from '@/shared/components/ProxyBalanceAlert.vue'
import CostGuardAlert from '@/shared/components/CostGuardAlert.vue'
import { disposeGlobalErrorGuard } from '@/shared/utils/app-error'
import { uninstallUserTokenSync } from '@/shared/auth/user-token-sync'
import { disposeDownloadProgressListener } from '@/shared/utils/download-progress'
+4
View File
@@ -207,6 +207,10 @@ export const API_ENDPOINTS = {
proxyBalance: '/api/user-secrets/proxy-balance',
proxyPlan: '/api/user-secrets/proxy-plan',
},
costGuard: {
status: '/api/user/cost-guard/status',
resume: '/api/user/cost-guard/resume',
},
notification: {
summary: '/api/notifications/summary',
list: '/api/notifications',
@@ -0,0 +1,52 @@
import { get, post, type JavaApiResponse, unwrapJavaResponse } from '../../http.ts'
import { buildJavaUrl } from '../../url.ts'
import { API_ENDPOINTS } from '../../endpoints.ts'
/** 代理/LLM 共享密钥提示:只报账号数,不暴露其他账号身份。 */
export interface SharedSecretWarning {
type: 'proxy' | 'llm' | string
moduleLabel: string
accounts: number
threshold: number
message: string
}
export interface CostGuardUsage {
proxy: number
llmCalls: number
llmTokens: number
}
export interface CostGuardStatus {
paused: boolean
reason: string
pausedAt: string | null
today: CostGuardUsage
window: CostGuardUsage & { seconds: number }
thresholds: {
proxyWindow: number
llmCallsWindow: number
llmTokensWindow: number
proxyDaily: number
llmCallsDaily: number
llmTokensDaily: number
sharedAccounts: number
}
sharedWarnings: SharedSecretWarning[]
}
export function fetchCostGuardStatus() {
return unwrapJavaResponse(
get<JavaApiResponse<CostGuardStatus>>(buildJavaUrl(API_ENDPOINTS.costGuard.status)),
)
}
/** 排查后手动继续:只清暂停闸,不删除已完成任务与结果行。 */
export function resumeCostGuard() {
return unwrapJavaResponse(
post<JavaApiResponse<CostGuardStatus>, undefined>(
buildJavaUrl(API_ENDPOINTS.costGuard.resume),
undefined,
),
)
}
@@ -2,7 +2,7 @@ import { get, post, type JavaApiResponse, unwrapJavaResponse } from '../../http.
import { buildJavaUrl } from '../../url.ts'
import { API_ENDPOINTS } from '../../endpoints.ts'
/** 通知场景:密钥欠费 / 密钥失效 / 任务失败 / 交付不完整 / 服务异常 / 麦象异常 / 系统。 */
/** 通知场景:密钥欠费 / 密钥失效 / 任务失败 / 交付不完整 / 服务异常 / 麦象异常 / 损耗暂停 / 密钥共用 / 系统。 */
export type NotificationScene =
| 'secret_balance'
| 'secret_invalid'
@@ -10,6 +10,8 @@ export type NotificationScene =
| 'task_partial'
| 'service_down'
| 'maixiang_anomaly'
| 'cost_guard'
| 'secret_shared'
| 'system'
/**
@@ -0,0 +1,278 @@
<script setup lang="ts">
/**
* 代理/LLM 损耗保护常驻提示(2026-10-24 需求):
* 异常时客户端立刻弹窗并暂停该账号的新任务;已跑完的任务与结果行不受影响。
*
* - 暂停:红色不可忽略横幅 + 首次弹确认框,用户排查后点「继续任务」走 resume;
* - 共用密钥:黄色提示条,只报账号数,不阻断任务;
* - 轮询失败保留上一轮状态(与 ProxyBalanceAlert 同口径),不把网络抖动刷成误报。
*/
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
fetchCostGuardStatus,
resumeCostGuard,
type CostGuardStatus,
type SharedSecretWarning,
} from '@/shared/api/types/modules/cost-guard'
import { AUTH_TOKEN_KEY } from '@/shared/auth/session-keys'
import {
COST_GUARD_POLL_MS,
pausedPromptKey,
sharedWarningKey,
usageLine,
} from '@/shared/utils/cost-guard-alert'
const status = ref<CostGuardStatus | null>(null)
const sharedWarnings = ref<SharedSecretWarning[]>([])
const resuming = ref(false)
let timer: number | null = null
let inflight = false
let disposed = false
let promptedKey = ''
const warnedSharedKeys = new Set<string>()
function hasLoginToken(): boolean {
if (typeof window === 'undefined') return false
return Boolean(window.localStorage.getItem(AUTH_TOKEN_KEY))
}
async function refresh(): Promise<void> {
if (disposed || inflight) return
if (!hasLoginToken()) {
status.value = null
sharedWarnings.value = []
return
}
inflight = true
try {
const next = await fetchCostGuardStatus().catch((error) => {
console.warn('[cost-guard] 损耗状态读取失败,本轮不提示:', error)
return null
})
if (next === null || disposed) return
status.value = next
sharedWarnings.value = next.sharedWarnings || []
notifySharedWarnings(sharedWarnings.value)
maybePromptPaused(next)
} finally {
inflight = false
}
}
function notifySharedWarnings(warnings: SharedSecretWarning[]): void {
for (const warning of warnings) {
const key = sharedWarningKey(warning)
if (warnedSharedKeys.has(key)) continue
warnedSharedKeys.add(key)
ElMessage.warning({ message: warning.message, duration: 8000, showClose: true })
}
}
function maybePromptPaused(next: CostGuardStatus): void {
const key = pausedPromptKey(next)
if (!key || key === promptedKey) return
promptedKey = key
ElMessageBox.confirm(
`${next.reason}\n\n${usageLine(next)}\n\n已完成的任务与数据不受影响。排查后点击「继续任务」;也可以先点「稍后处理」,处理完再从右上角横幅继续。`,
'任务已自动暂停(损耗保护)',
{
confirmButtonText: '继续任务',
cancelButtonText: '稍后处理',
distinguishCancelAndClose: true,
closeOnClickModal: false,
closeOnPressEscape: false,
type: 'error',
customStyle: { whiteSpace: 'pre-line' },
},
)
.then(() => resume())
.catch(() => {
/* 稍后处理/关闭:保留横幅,不重复弹 */
})
}
async function resume(): Promise<void> {
if (resuming.value) return
resuming.value = true
try {
const next = await resumeCostGuard()
status.value = next
sharedWarnings.value = next.sharedWarnings || []
promptedKey = ''
ElMessage.success('已继续任务,后续派发会从当前进度接着跑')
} catch (error) {
console.warn('[cost-guard] 继续任务失败:', error)
ElMessage.error('继续任务失败,请稍后重试')
} finally {
resuming.value = false
}
}
function refreshWhenVisible(): void {
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
void refresh()
}
onMounted(() => {
void refresh()
timer = window.setInterval(() => void refresh(), COST_GUARD_POLL_MS)
window.addEventListener('focus', refreshWhenVisible)
document.addEventListener('visibilitychange', refreshWhenVisible)
})
onBeforeUnmount(() => {
disposed = true
if (timer !== null) window.clearInterval(timer)
window.removeEventListener('focus', refreshWhenVisible)
document.removeEventListener('visibilitychange', refreshWhenVisible)
})
</script>
<template>
<div v-if="status?.paused || sharedWarnings.length" class="cost-guard-stack">
<div
v-if="status?.paused"
class="cost-guard-alert cost-guard-alert--paused"
role="alert"
aria-live="assertive"
>
<div class="cost-guard-alert-icon" aria-hidden="true">!</div>
<div class="cost-guard-alert-content">
<div class="cost-guard-alert-title">任务已自动暂停(损耗保护)</div>
<div class="cost-guard-alert-reason">{{ status.reason }}</div>
<div class="cost-guard-alert-metrics">{{ usageLine(status) }}</div>
<div class="cost-guard-alert-hint">
已完成的任务与结果行不受影响。请检查「密钥设置」与被暂停任务,排查后继续。
</div>
<button class="cost-guard-alert-button" :disabled="resuming" @click="resume">
{{ resuming ? '正在恢复…' : '继续任务' }}
</button>
</div>
</div>
<div
v-if="sharedWarnings.length"
class="cost-guard-alert cost-guard-alert--shared"
role="status"
>
<div class="cost-guard-alert-icon" aria-hidden="true">i</div>
<div class="cost-guard-alert-content">
<div class="cost-guard-alert-title">密钥共用提示</div>
<div
v-for="warning in sharedWarnings"
:key="sharedWarningKey(warning)"
class="cost-guard-alert-reason"
>
{{ warning.message }}
</div>
</div>
</div>
</div>
</template>
<style scoped>
/* 放在代理余量警告(top:68px)下方,两个常驻提示同时出现时不互相遮挡 */
.cost-guard-stack {
position: fixed;
top: 230px;
right: 16px;
z-index: 3000;
display: flex;
flex-direction: column;
gap: 12px;
width: 400px;
max-width: calc(100vw - 32px);
}
.cost-guard-alert {
display: flex;
align-items: flex-start;
gap: 10px;
width: 100%;
padding: 14px 16px;
box-sizing: border-box;
border-radius: 12px;
box-shadow: 0 14px 36px -18px rgba(60, 20, 20, 0.55);
}
.cost-guard-alert--paused {
border: 1px solid #d64545;
background: #fff1f1;
color: #7d1d1d;
}
.cost-guard-alert--shared {
border: 1px solid #e0a13c;
background: #fff8e8;
color: #7a4a06;
}
.cost-guard-alert-icon {
flex-shrink: 0;
width: 22px;
height: 22px;
border-radius: 50%;
color: #ffffff;
font-size: 14px;
font-weight: 800;
line-height: 22px;
text-align: center;
}
.cost-guard-alert--paused .cost-guard-alert-icon {
background: #d64545;
}
.cost-guard-alert--shared .cost-guard-alert-icon {
background: #e0a13c;
}
.cost-guard-alert-content {
display: flex;
flex-direction: column;
gap: 5px;
min-width: 0;
}
.cost-guard-alert-title {
font-size: 14px;
font-weight: 700;
}
.cost-guard-alert-reason,
.cost-guard-alert-metrics {
font-size: 13px;
line-height: 1.5;
word-break: break-word;
}
.cost-guard-alert-metrics {
color: #9a4a4a;
font-size: 12px;
}
.cost-guard-alert-hint {
color: #9a4a4a;
font-size: 12px;
line-height: 1.5;
}
.cost-guard-alert-button {
align-self: flex-start;
margin-top: 4px;
padding: 6px 14px;
border: 0;
border-radius: 8px;
background: #d64545;
color: #ffffff;
font-size: 13px;
font-weight: 600;
cursor: pointer;
}
.cost-guard-alert-button:disabled {
opacity: 0.6;
cursor: default;
}
</style>
@@ -0,0 +1,29 @@
import type { CostGuardStatus, SharedSecretWarning } from '@/shared/api/types/modules/cost-guard'
/** 损耗状态轮询间隔:与后端每分钟扫描配合,30 秒足够把暂停提示送到界面。 */
export const COST_GUARD_POLL_MS = 30_000
export function formatCount(value: number | null | undefined): string {
const number = Number(value ?? 0)
if (!Number.isFinite(number)) return '0'
return number.toLocaleString('zh-CN')
}
/** 暂停弹窗/横幅里的用量行:当日累计 + 本轮增量,用户一眼看出是哪一项超了。 */
export function usageLine(status: CostGuardStatus | null): string {
if (!status) return ''
const today = status.today
const window = status.window
return `今日代理提取 ${formatCount(today.proxy)} 次 · LLM ${formatCount(today.llmCalls)} 次 / ${formatCount(today.llmTokens)} tokens;`
+ `最近 ${window.seconds} 秒:代理 ${formatCount(window.proxy)} 次 · LLM ${formatCount(window.llmCalls)} 次 / ${formatCount(window.llmTokens)} tokens`
}
/** 同一个暂停事件只弹一次:pausedAt 变化(新的自动暂停)才重新弹。 */
export function pausedPromptKey(status: CostGuardStatus | null): string {
if (!status?.paused) return ''
return status.pausedAt || status.reason || 'paused'
}
export function sharedWarningKey(warning: SharedSecretWarning): string {
return `${warning.type}|${warning.moduleLabel}|${warning.accounts}`
}
@@ -0,0 +1,98 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
/**
* 代理/LLM 损耗保护(2026-10-24 需求):
* 「异常要立刻弹窗警告在客户端界面上,并暂停任务;排查后手动点击接着跑」。
*
* 分两层钉:
* ① 行为层:暂停键只随 pausedAt 变化、用量行含当日与窗口两段、共享提示按键去重;
* ② 源码层:全局挂载、30 秒轮询、暂停弹窗带「继续任务」、resume 走独立接口。
*/
const COMPONENT = 'src/shared/components/CostGuardAlert.vue'
const APP = 'src/App.vue'
const ENDPOINTS = 'src/shared/api/endpoints.ts'
const NOTIFICATION_TYPES = 'src/shared/api/types/modules/notification.ts'
function read(rel: string): string {
return readFileSync(join(process.cwd(), rel), 'utf8')
}
const component = read(COMPONENT)
const app = read(APP)
test('用量行同时给出当日累计与最近窗口增量', async () => {
const { usageLine, formatCount } = await import('../src/shared/utils/cost-guard-alert.ts')
const status = {
paused: true,
reason: '代理提取异常',
pausedAt: '2026-10-24T10:00:00',
today: { proxy: 12345, llmCalls: 678, llmTokens: 900000 },
window: { seconds: 120, proxy: 600, llmCalls: 180, llmTokens: 600000 },
thresholds: {
proxyWindow: 600,
llmCallsWindow: 180,
llmTokensWindow: 600000,
proxyDaily: 8000,
llmCallsDaily: 6000,
llmTokensDaily: 20000000,
sharedAccounts: 3,
},
sharedWarnings: [],
}
const line = usageLine(status as never)
assert.match(line, /今日代理提取 12,345 次/)
assert.match(line, /最近 120 秒:代理 600 次/)
assert.match(line, /LLM 180 次 \/ 600,000 tokens/)
assert.equal(formatCount(undefined), '0')
})
test('同一个暂停事件只弹一次,pausedAt 变化才重新弹', async () => {
const { pausedPromptKey } = await import('../src/shared/utils/cost-guard-alert.ts')
const base = { paused: true, reason: 'r', pausedAt: '2026-10-24T10:00:00' }
const next = { paused: true, reason: 'r', pausedAt: '2026-10-24T11:00:00' }
assert.equal(pausedPromptKey(base as never), pausedPromptKey({ ...base } as never))
assert.notEqual(pausedPromptKey(base as never), pausedPromptKey(next as never))
assert.equal(pausedPromptKey({ paused: false, reason: 'r', pausedAt: null } as never), '')
})
test('共享密钥提示按键去重,不按文案去重', async () => {
const { sharedWarningKey } = await import('../src/shared/utils/cost-guard-alert.ts')
assert.equal(
sharedWarningKey({ type: 'proxy', moduleLabel: '代理设置', accounts: 3, threshold: 3, message: 'a' }),
sharedWarningKey({ type: 'proxy', moduleLabel: '代理设置', accounts: 3, threshold: 3, message: 'b' }),
)
assert.notEqual(
sharedWarningKey({ type: 'llm', moduleLabel: '代理设置', accounts: 3, threshold: 3, message: 'a' }),
sharedWarningKey({ type: 'proxy', moduleLabel: '代理设置', accounts: 3, threshold: 3, message: 'a' }),
)
})
test('全局挂载并在暂停时提供「继续任务」', () => {
assert.ok(app.includes("import CostGuardAlert from '@/shared/components/CostGuardAlert.vue'"))
assert.ok(app.includes('<CostGuardAlert />'), '组件没挂到 App.vue,异常时界面不会弹')
assert.ok(component.includes('setInterval'), '缺少轮询,用户停在页面上等不到暂停提示')
assert.ok(component.includes('COST_GUARD_POLL_MS'))
assert.ok(component.includes('fetchCostGuardStatus'))
assert.ok(component.includes('resumeCostGuard'))
assert.ok(component.includes('ElMessageBox.confirm'))
assert.ok(component.includes('继续任务'))
assert.ok(component.includes('已完成的任务与数据不受影响'))
})
test('接口与通知场景已登记', () => {
const endpoints = read(ENDPOINTS)
assert.ok(endpoints.includes("status: '/api/user/cost-guard/status'"))
assert.ok(endpoints.includes("resume: '/api/user/cost-guard/resume'"))
const notification = read(NOTIFICATION_TYPES)
assert.ok(notification.includes("| 'cost_guard'"))
assert.ok(notification.includes("| 'secret_shared'"))
})