Files
crawler-plugin/frontend-vue/src/shared/components/CostGuardAlert.vue
T

254 lines
6.9 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
/**
* 代理/LLM 损耗保护常驻提示(2026-10-24 需求):
* 异常时客户端立刻弹窗并暂停该账号的新任务;已跑完的任务与结果行不受影响。
*
* - 暂停:红色不可忽略横幅 + 首次弹确认框,用户排查后点「继续任务」走 resume;
* - 共用密钥:仅代理 IP 密钥共用弹 ElMessage 通知(铃铛有服务端 secret_shared 推送),
* LLM 密钥共用可接受、不弹窗;不再常驻界面;
* - 轮询失败保留上一轮状态(与 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,
proxySharedToastText,
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) {
// LLM 密钥共用可接受,不弹窗;只对代理 IP 密钥共用做通知
if (warning.type !== 'proxy') continue
const key = sharedWarningKey(warning)
if (warnedSharedKeys.has(key)) continue
warnedSharedKeys.add(key)
ElMessage.warning({ message: proxySharedToastText(warning), 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" class="cost-guard-stack">
<div
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>
</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-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-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>