init: api-gateway v2.4.0(Agnes/b.ai/火山方舟 三家供应商网关)
This commit is contained in:
commit
d143d8da22
91 files changed
+24653
No files matched your search
@@ -0,0 +1,287 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('settings.myKeys') }}</b>
|
||||
<span class="sub">{{ keys.length }} / {{ limit === null ? '∞' : limit }}</span>
|
||||
<div class="pager">
|
||||
<!-- 标签输入留在页头:创建时仍可给 Key 起名(行为与旧版一致) -->
|
||||
<el-input
|
||||
v-model="label"
|
||||
size="small"
|
||||
class="label-inp"
|
||||
:placeholder="t('settings.keyLabel')"
|
||||
clearable
|
||||
@keyup.enter="create"
|
||||
/>
|
||||
<el-tooltip :disabled="!atLimit" :content="t('settings.keyLimitFull')">
|
||||
<span>
|
||||
<el-button type="primary" size="small" :loading="creating" :disabled="atLimit" @click="create">
|
||||
<Icon name="plus" :size="14" />
|
||||
<span>{{ atLimit ? t('settings.createKey') + '(' + t('settings.keyLimitFull') + ')' : t('settings.createKey') }}</span>
|
||||
</el-button>
|
||||
</span>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 第八轮补: 后端在 GET /auth/apikeys 里回 key_limit,前端据此提前禁用按钮 ——
|
||||
到顶了就别再发那个必然 400 的请求,提示也走人话而不是错误码。 -->
|
||||
<div v-if="atLimit" class="warn-bar">
|
||||
<Icon name="bell" :size="15" />
|
||||
<span>{{ t('settings.keyLimitFull') }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="keys.length">
|
||||
<div v-for="k in keys" :key="k.id" class="key-row">
|
||||
<div class="flex-1">
|
||||
<div class="key-t">
|
||||
<b>{{ k.label || t('common.none') }}</b>
|
||||
</div>
|
||||
<div class="code key-val">
|
||||
<span v-if="k.key">{{ k.key }}</span>
|
||||
<span v-else class="muted-2">{{ k.hint }}…… {{ t('settings.keyLegacyNoEcho') }}</span>
|
||||
</div>
|
||||
<div class="hint key-meta">{{ t('settings.keyCreated') }} · {{ fmtTs(k.created) }}</div>
|
||||
</div>
|
||||
<div class="key-acts">
|
||||
<el-button size="small" :disabled="!k.key" @click="copyKey(k.key)">
|
||||
<Icon name="copy" :size="13" />
|
||||
<span>{{ t('common.copy') }}</span>
|
||||
</el-button>
|
||||
<el-button size="small" type="danger" plain @click="remove(k.id)">
|
||||
<Icon name="trash" :size="13" />
|
||||
<span>{{ t('common.delete') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<el-empty v-else :description="t('settings.noKey')" :image-size="80" />
|
||||
|
||||
<div class="sep" />
|
||||
|
||||
<!-- 调用方式:Key 页面直接给一份调用说明,别让人去翻 README -->
|
||||
<div class="card-h">
|
||||
<b>{{ t('apidoc.title') }}</b>
|
||||
<span class="sub">{{ base }}</span>
|
||||
</div>
|
||||
|
||||
<div class="log-detail">
|
||||
<div>
|
||||
<b>{{ t('apidoc.baseUrl') }}</b>
|
||||
<span class="code">{{ base }}</span>
|
||||
<el-button text type="primary" size="small" @click="copy(base)">
|
||||
<Icon name="copy" :size="12" />
|
||||
<span>{{ t('apidoc.copyBase') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
<div><b>{{ t('apidoc.auth') }}</b> <span class="code">{{ t('apidoc.authVal') }}</span></div>
|
||||
<div><b>{{ t('apidoc.modelPick') }}</b> <span>{{ t('apidoc.modelPickVal') }}</span></div>
|
||||
<div><b>{{ t('apidoc.ctype') }}</b> <span>{{ t('apidoc.ctypeVal') }}</span></div>
|
||||
</div>
|
||||
|
||||
<div class="call-acts">
|
||||
<el-button size="small" @click="copy(examples[0].code)">
|
||||
<Icon name="copy" :size="13" />
|
||||
<span>{{ t('apidoc.copyCmd') }} curl</span>
|
||||
</el-button>
|
||||
<el-button size="small" @click="scrollDoc">
|
||||
<Icon name="chevD" :size="13" />
|
||||
<span>{{ t('apidoc.title') }}</span>
|
||||
</el-button>
|
||||
<span class="hint call-note">{{ t('apidoc.intro') }}</span>
|
||||
</div>
|
||||
|
||||
<div ref="docRef" class="doc">
|
||||
<div class="sub-title">{{ t('apidoc.endpoints') }}</div>
|
||||
<el-table :data="endpoints" size="small">
|
||||
<el-table-column prop="method" :label="t('apidoc.colMethod')" width="80">
|
||||
<template #default="{ row }">
|
||||
<span class="badge m">{{ row.method }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('apidoc.colPath')" min-width="230">
|
||||
<template #default="{ row }"><span class="code">{{ row.path }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="desc" :label="t('apidoc.colDesc')" min-width="280" />
|
||||
</el-table>
|
||||
|
||||
<div v-for="ex in examples" :key="ex.title" class="ex">
|
||||
<div class="sub-title">
|
||||
{{ ex.title }}
|
||||
<el-button text type="primary" size="small" @click="copy(ex.code)">
|
||||
<Icon name="copy" :size="12" />
|
||||
<span>{{ t('apidoc.copyCmd') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
<pre class="code pre">{{ ex.code }}</pre>
|
||||
</div>
|
||||
|
||||
<div class="sub-title">{{ t('apidoc.notes') }}</div>
|
||||
<ul class="notes">
|
||||
<li v-for="(n, i) in notes" :key="i">{{ n }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { api } from '../api'
|
||||
import Icon from '../components/Icon.vue'
|
||||
|
||||
const { t } = useI18n()
|
||||
const keys = ref<any[]>([])
|
||||
const label = ref('')
|
||||
const creating = ref(false)
|
||||
const limit = ref<number | null>(null) // null = 不限(admin)
|
||||
const base = window.location.origin
|
||||
|
||||
// 端点表:与 app/main.py 的真实路由一一对应(别写成 README 里才有的东西)
|
||||
const endpoints = computed(() => [
|
||||
{ method: 'GET', path: '/v1/models', desc: t('apidoc.epModels') },
|
||||
{ method: 'POST', path: '/v1/chat/completions', desc: t('apidoc.epChat') },
|
||||
{ method: 'POST', path: '/v1/images/generations', desc: t('apidoc.epImages') },
|
||||
{ method: 'POST', path: '/v1/videos', desc: t('apidoc.epVideoCreate') },
|
||||
{ method: 'GET', path: '/v1/videos/{video_id}?model=...', desc: t('apidoc.epVideoPoll') },
|
||||
{ method: 'GET', path: '/history/{kind}', desc: t('apidoc.epHistory') },
|
||||
{ method: 'GET', path: '/logs', desc: t('apidoc.epLogs') },
|
||||
{ method: 'GET', path: '/metrics', desc: t('apidoc.epMetrics') },
|
||||
{ method: 'GET', path: '/health', desc: t('apidoc.epHealth') },
|
||||
])
|
||||
|
||||
const notes = computed(() => [
|
||||
t('apidoc.noteVision'), t('apidoc.noteN1'), t('apidoc.noteVideo'),
|
||||
t('apidoc.notePoll'), t('apidoc.noteMedia'), t('apidoc.noteKey'), t('apidoc.noteAudit'),
|
||||
])
|
||||
|
||||
// 示例里的 Key 用占位符 $GW_KEY(不把真 Key 渲染进文档;本页的 Key 明文只在上方列表里回显)
|
||||
const examples = computed(() => {
|
||||
const H = `-H "Authorization: Bearer $GW_KEY" -H "Content-Type: application/json"`
|
||||
return [
|
||||
// 示例里的注释与示例文案也走 i18n:英文界面下照抄示例不会看到中文
|
||||
{ title: t('apidoc.exChat'), code:
|
||||
`curl ${base}/v1/chat/completions \\
|
||||
${H} \\
|
||||
-d '{"model":"wjd","messages":[{"role":"user","content":"${t('apidoc.sampleChat')}"}]}'` },
|
||||
{ title: t('apidoc.exImg'), code:
|
||||
`curl ${base}/v1/images/generations \\
|
||||
${H} \\
|
||||
-d '{"model":"agnes-image-2.5-flash","prompt":"${t('apidoc.sampleImg')}","size":"1K","ratio":"16:9","n":1}'` },
|
||||
{ title: t('apidoc.exVideo'), code:
|
||||
`# 1) ${t('apidoc.sampleStep1')}
|
||||
curl ${base}/v1/videos \\
|
||||
${H} \\
|
||||
-d '{"model":"agnes-video-2.5-flash","prompt":"${t('apidoc.sampleVideo')}","mode":"text","seconds":"5","size":"720P","aspect_ratio":"16:9"}'
|
||||
# → {"video_id":"task_xxx","status":"pending"}
|
||||
|
||||
# 2) ${t('apidoc.sampleStep2')}
|
||||
curl "${base}/v1/videos/task_xxx?model=agnes-video-2.5-flash" \\
|
||||
-H "Authorization: Bearer $GW_KEY"` },
|
||||
{ title: t('apidoc.exPy'), code:
|
||||
`from openai import OpenAI
|
||||
|
||||
c = OpenAI(base_url="${base}/v1", api_key="wjd-xxxxxxxx")
|
||||
r = c.chat.completions.create(model="wjd", messages=[{"role": "user", "content": "${t('apidoc.sampleChat')}"}])
|
||||
print(r.choices[0].message.content)` },
|
||||
]
|
||||
})
|
||||
|
||||
// 「查看接口文档」:滚动到同卡片下方的端点 / 示例 / 注意事项(文档始终可见,不做折叠)
|
||||
const docRef = ref<HTMLElement | null>(null)
|
||||
function scrollDoc() {
|
||||
docRef.value?.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
||||
}
|
||||
|
||||
async function copy(text: string) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
ElMessage.success(t('common.copyOk'))
|
||||
} catch { ElMessage.warning(t('common.copyFail')) }
|
||||
}
|
||||
|
||||
const atLimit = computed(() => limit.value !== null && keys.value.length >= limit.value)
|
||||
|
||||
function fmtTs(ts: number): string {
|
||||
if (!ts) return '—'
|
||||
const d = new Date(ts * 1000)
|
||||
const p = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const j = await api('/auth/apikeys')
|
||||
keys.value = j.keys || []
|
||||
limit.value = j.key_limit ?? null
|
||||
} catch (e: any) { ElMessage.error(e?.body?.detail || e?.message || String(e)) }
|
||||
}
|
||||
|
||||
async function create() {
|
||||
if (atLimit.value) { ElMessage.warning(t('settings.keyLimitFull')); return }
|
||||
creating.value = true
|
||||
try {
|
||||
await api('/auth/apikeys', { method: 'POST', body: JSON.stringify({ label: label.value.trim() }) })
|
||||
label.value = ''
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.body?.detail || String(e?.message || e))
|
||||
} finally {
|
||||
creating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(id: string) {
|
||||
try {
|
||||
await ElMessageBox.confirm(t('settings.confirmDeleteKey'), t('settings.confirm'), { type: 'warning' })
|
||||
} catch { return }
|
||||
try {
|
||||
await api(`/auth/apikeys/${id}`, { method: 'DELETE' })
|
||||
await load()
|
||||
} catch (e: any) { ElMessage.error(e?.body?.detail || String(e?.message || e)) }
|
||||
}
|
||||
|
||||
async function copyKey(k: string) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(k)
|
||||
ElMessage.success(t('common.copyOk'))
|
||||
} catch { ElMessage.warning(t('common.copyFail')) }
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.label-inp { width: 190px; }
|
||||
.warn-bar {
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
background: var(--warn-soft); color: var(--warn);
|
||||
border-radius: 10px; padding: 9px 12px; font-size: 12px; margin-bottom: 12px;
|
||||
}
|
||||
.key-t { display: flex; align-items: center; gap: 8px; font-size: 13px; }
|
||||
.key-val { margin-top: 5px; color: var(--muted); word-break: break-all; }
|
||||
.key-meta { margin-top: 4px; }
|
||||
.key-acts { display: flex; gap: 7px; flex: none; }
|
||||
.key-acts .gw-icon, .call-acts .gw-icon { margin-right: 5px; }
|
||||
.log-detail > div { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; }
|
||||
.log-detail > div + div { margin-top: 4px; }
|
||||
.call-acts { display: flex; align-items: center; gap: 8px; margin-top: 10px; flex-wrap: wrap; }
|
||||
.call-note { margin-left: auto; max-width: 54%; text-align: right; line-height: 1.6; }
|
||||
.sub-title { display: flex; align-items: center; gap: 4px; font-weight: 600; font-size: 13px; margin: 14px 0 8px; }
|
||||
.pre {
|
||||
background: var(--surface-2); border: 1px solid var(--line); color: var(--text);
|
||||
padding: 10px 12px; border-radius: 10px; margin: 0; font-size: 12px; line-height: 1.6;
|
||||
overflow-x: auto; white-space: pre;
|
||||
}
|
||||
.ex { margin-bottom: 4px; }
|
||||
.notes { margin: 0; padding-left: 18px; color: var(--muted); font-size: 12.5px; line-height: 1.9; }
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.label-inp { width: 100%; }
|
||||
.key-row { flex-wrap: wrap; }
|
||||
.call-note { margin-left: 0; max-width: 100%; text-align: left; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,822 @@
|
||||
<template>
|
||||
<div class="page-fill">
|
||||
<div class="chat-layout">
|
||||
<!-- 左栏:会话。窄屏由 style.css 隐藏(.chat-side),改用右栏顶部的会话下拉 -->
|
||||
<aside class="chat-side">
|
||||
<div class="card side-in">
|
||||
<el-button type="primary" class="new-conv" :disabled="streaming" @click="clearConversation">
|
||||
<Icon name="plus" :size="14" />
|
||||
<span>{{ t('chat.newChat') }}</span>
|
||||
</el-button>
|
||||
|
||||
<!-- 会话列表:当前这条(服务端 history/chat 的 current 条目)加 .on -->
|
||||
<div class="conv-list">
|
||||
<div v-for="c in conversations" :key="c.id" class="conv" :class="{ on: c.id === activeConvId }">
|
||||
{{ c.title }}
|
||||
<small>{{ c.time }} · {{ t('chat.msgsN', { n: c.n }) }}</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sep" />
|
||||
|
||||
<div class="card-h">
|
||||
<b>{{ t('chat.thisConv') }}</b>
|
||||
</div>
|
||||
<div class="pv conv-info">
|
||||
<div class="pv-i">
|
||||
<span class="nm">{{ t('chat.model') }}</span>
|
||||
<span class="st code">{{ params.model }}</span>
|
||||
</div>
|
||||
<div class="pv-i">
|
||||
<span class="nm">Tokens</span>
|
||||
<span class="st">{{ totalTokens }}</span>
|
||||
</div>
|
||||
<div class="pv-i">
|
||||
<span class="nm">{{ t('chat.elapsed') }}</span>
|
||||
<span class="st">{{ elapsedText }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="side-ops">
|
||||
<el-button class="op" size="small" :disabled="!messages.length" @click="exportConv">
|
||||
<Icon name="dl" :size="13" />
|
||||
<span>{{ t('common.export') }}</span>
|
||||
</el-button>
|
||||
<el-button class="op" size="small" :disabled="streaming || !messages.length" @click="clearConversation">
|
||||
<Icon name="trash" :size="13" />
|
||||
<span>{{ t('chat.clear') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- 右栏:参数胶囊 + 消息 + 输入区 -->
|
||||
<section class="chat-main">
|
||||
<div class="chat-top">
|
||||
<!-- 窄屏没有左栏,会话切换收在这里(只有一条会话时不显示) -->
|
||||
<el-select
|
||||
v-if="isMobile && conversations.length > 1"
|
||||
v-model="activeConvId"
|
||||
size="small"
|
||||
class="conv-sel"
|
||||
:placeholder="t('chat.session')"
|
||||
>
|
||||
<el-option v-for="c in conversations" :key="c.id" :value="c.id" :label="c.title" />
|
||||
</el-select>
|
||||
|
||||
<span class="chip-sel" :class="{ on: params.stream }" @click="paramsOpen = true">
|
||||
<Icon name="bolt" :size="13" />{{ t('chat.streaming') }}
|
||||
</span>
|
||||
<span class="chip-sel" @click="paramsOpen = true">{{ t('chat.tempShort') }} {{ params.temperature }}</span>
|
||||
<span class="chip-sel" @click="paramsOpen = true">
|
||||
{{ t('chat.maxShort') }} {{ params.max_tokens ?? t('common.none') }}
|
||||
</span>
|
||||
<span class="chip-sel" :class="{ on: !!params.system.trim() }" @click="paramsOpen = true">
|
||||
{{ t('chat.systemShort') }}
|
||||
</span>
|
||||
|
||||
<span v-if="streaming" class="stream-badge">{{ t('chat.generating') }}</span>
|
||||
<span class="vision-hint" :class="{ off: !visionOk }">
|
||||
{{ visionOk ? t('chat.visionReady') : t('chat.visionOff') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="card chat-card">
|
||||
<div class="card-h">
|
||||
<b>{{ convTitle }}</b>
|
||||
<span class="sub">{{ t('chat.msgsN', { n: messages.length }) }}<template v-if="lastAt"> · {{ fmtClock(lastAt) }}</template></span>
|
||||
<div class="pager">
|
||||
<el-button size="small" :disabled="streaming || !lastUser" @click="regenerate">
|
||||
<Icon name="refresh" :size="13" />
|
||||
<span>{{ t('chat.regenerate') }}</span>
|
||||
</el-button>
|
||||
<el-button size="small" :disabled="!messages.length" @click="copyAll">
|
||||
<Icon name="copy" :size="13" />
|
||||
<span>{{ t('chat.copyAll') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div ref="scrollEl" class="msgs" @scroll="onScroll">
|
||||
<div v-if="messages.length === 0" class="empty">
|
||||
<Icon name="chat" :size="34" />
|
||||
<div class="empty-t">{{ t('chat.empty') }}</div>
|
||||
</div>
|
||||
|
||||
<div v-for="msg in messages" :key="msg.id" class="msg" :class="msg.role === 'user' ? 'me' : 'ai'">
|
||||
<!-- 助手:降级/服务信息 -->
|
||||
<div v-if="msg.role === 'assistant' && msg.meta" class="resp-meta">
|
||||
<el-tag size="small" :type="msg.meta.fallback ? 'warning' : 'success'" effect="light">
|
||||
<template v-if="msg.meta.fallback">{{ t('chat.fallback', { provider: msg.meta.provider }) }}</template><template v-else>{{ t('chat.servedBy', { provider: msg.meta.provider }) }}</template>
|
||||
</el-tag>
|
||||
<span class="meta-txt">
|
||||
<template v-if="msg.meta.fallback">{{ t('chat.requestedTo', { req: msg.meta.requested, served: msg.meta.served }) }}</template>
|
||||
<template v-else>{{ msg.meta.served }}</template>
|
||||
</span>
|
||||
<span v-if="msg.usage || msg.cost != null" class="meta-txt">
|
||||
· {{ msg.cost != null ? `¥${msg.cost}` : '' }}
|
||||
<template v-if="msg.usage">{{ tokensText(msg.usage) }}</template>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- 助手:推理折叠 -->
|
||||
<el-collapse v-if="msg.role === 'assistant' && msg.reasoning" class="reasoning">
|
||||
<el-collapse-item :title="t('chat.reasoning')" name="r">
|
||||
<div class="reasoning-md">{{ msg.reasoning }}</div>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
|
||||
<!-- 附图缩略(用户消息) -->
|
||||
<div v-if="msg.images && msg.images.length" class="attach">
|
||||
<el-image v-for="(u, k) in msg.images" :key="k" :src="u" fit="cover"
|
||||
:title="msg.imgNames && msg.imgNames[k]"
|
||||
:preview-src-list="msg.images" :initial-index="k" preview-teleported />
|
||||
</div>
|
||||
|
||||
<template v-if="msg.role === 'user'">
|
||||
<div v-if="msg.content" class="plain">{{ msg.content }}</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div v-if="msg.content" class="md" v-html="renderMarkdown(msg.content)"></div>
|
||||
<div v-else-if="!msg.error && !msg.reasoning" class="placeholder">{{ msg.streaming ? t('chat.thinking') : t('chat.emptyResp') }}</div>
|
||||
</template>
|
||||
<span v-if="msg.streaming && !msg.error" class="cursor">▍</span>
|
||||
|
||||
<div v-if="metaText(msg)" class="meta">{{ metaText(msg) }}</div>
|
||||
|
||||
<div v-if="msg.error" class="err">
|
||||
<el-alert :title="t('chat.youError', { msg: msg.error })" type="error" :closable="false" show-icon />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 输入区 -->
|
||||
<div class="composer">
|
||||
<div class="in">
|
||||
<!-- 第十三轮: 视觉对话 —— 附图(上传的图片在浏览器内压缩成 data URI;也支持粘 URL) -->
|
||||
<div v-if="pending.length" class="img-bar">
|
||||
<el-tag v-for="(im, i) in pending" :key="i" closable type="info" size="small" class="img-chip"
|
||||
:title="im.uri" @close="pending.splice(i, 1)">{{ im.name }}</el-tag>
|
||||
</div>
|
||||
<div v-if="showImg" class="img-row">
|
||||
<el-input v-model="imgUrl" size="small" :placeholder="t('chat.imgPh')" @keyup.enter="addImg">
|
||||
<template #append><el-button @click="addImg">{{ t('chat.imgAdd') }}</el-button></template>
|
||||
</el-input>
|
||||
</div>
|
||||
<!-- 带图但所选模型没有视觉能力时提前说清楚(否则上游要么忽略图片、要么报参数错误) -->
|
||||
<el-alert v-if="pending.length && !visionOk" type="warning" show-icon :closable="false" class="vision-warn"
|
||||
:title="t('chat.visionWarn', { model: params.model })">
|
||||
<template #default>
|
||||
<el-button v-if="firstVisionModel" size="small" text type="primary" @click="useVisionModel">
|
||||
{{ t('chat.useVision', { model: firstVisionModel }) }}
|
||||
</el-button>
|
||||
</template>
|
||||
</el-alert>
|
||||
|
||||
<el-input
|
||||
v-model="text"
|
||||
type="textarea"
|
||||
:rows="2"
|
||||
resize="none"
|
||||
:placeholder="t('chat.placeholder')"
|
||||
:disabled="streaming"
|
||||
@keydown="onKeydown"
|
||||
@focus="onInputFocus"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="bar">
|
||||
<el-tooltip :content="t('chat.imgUpload')" placement="top">
|
||||
<el-button text size="small" :disabled="streaming" @click="pickImages">
|
||||
<Icon name="clip" :size="16" />
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip :content="t('chat.imgUrlBtn')" placement="top">
|
||||
<el-button text size="small" @click="showImg = !showImg">
|
||||
<Icon name="link" :size="16" />
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
<input ref="fileEl" type="file" accept="image/*" multiple class="hide-file" @change="onFiles" />
|
||||
|
||||
<el-select v-model="params.model" class="model-sel" size="small" :disabled="streaming" filterable :placeholder="t('chat.routeGroup')">
|
||||
<el-option-group :label="t('chat.routeGroup')">
|
||||
<el-option v-for="r in routes" :key="r.id" :value="r.id" :label="chainLabel(r)">
|
||||
<span class="opt">
|
||||
<span>{{ chainLabel(r) }}</span>
|
||||
<Icon v-if="r.vision" name="eye" :size="13" />
|
||||
</span>
|
||||
</el-option>
|
||||
</el-option-group>
|
||||
<el-option-group :label="t('chat.textModels')">
|
||||
<el-option v-for="m in textModels" :key="m.id" :value="m.id" :label="modelLabel(m)">
|
||||
<span class="opt">
|
||||
<span>{{ modelLabel(m) }}</span>
|
||||
<Icon v-if="m.vision" name="eye" :size="13" />
|
||||
</span>
|
||||
</el-option>
|
||||
</el-option-group>
|
||||
</el-select>
|
||||
|
||||
<span v-if="!streaming && !text.trim()" class="hint">{{ t('chat.waiting') }}</span>
|
||||
<span class="tok">{{ totalTokens }} Tokens</span>
|
||||
|
||||
<el-button v-if="!streaming" type="primary" size="small" :disabled="!text.trim() && !pending.length" @click="send">
|
||||
<Icon name="send" :size="14" />
|
||||
<span>{{ t('chat.send') }}</span>
|
||||
</el-button>
|
||||
<el-button v-else type="danger" plain size="small" @click="stop">
|
||||
<Icon name="stop" :size="14" />
|
||||
<span>{{ t('chat.stop') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<!-- 参数抽屉:窄屏按屏宽百分比,避免 330px 在小屏上顶到边 -->
|
||||
<el-drawer v-model="paramsOpen" :title="t('chat.params')" :size="isMobile ? '86%' : '330px'" :close-on-click-modal="true">
|
||||
<div class="param">
|
||||
<div class="plabel">{{ t('chat.temp') }}</div>
|
||||
<el-slider v-model="params.temperature" :min="0" :max="2" :step="0.05" show-input />
|
||||
</div>
|
||||
<div class="param">
|
||||
<div class="plabel">{{ t('chat.topP') }}</div>
|
||||
<el-slider v-model="params.top_p" :min="0" :max="1" :step="0.05" show-input />
|
||||
</div>
|
||||
<div class="param">
|
||||
<div class="plabel">{{ t('chat.maxTokens') }}</div>
|
||||
<el-input-number v-model="params.max_tokens" :min="1" :max="200000" :placeholder="t('chat.phDefault')" clearable style="width: 100%" />
|
||||
</div>
|
||||
<div class="param">
|
||||
<div class="plabel">{{ t('chat.streaming') }}</div>
|
||||
<el-switch v-model="params.stream" :active-text="t('common.yes')" :inactive-text="t('common.no')" />
|
||||
</div>
|
||||
<div class="param">
|
||||
<div class="plabel">{{ t('chat.system') }}</div>
|
||||
<el-input v-model="params.system" type="textarea" :rows="4" resize="none" :placeholder="t('chat.phOptional')" />
|
||||
</div>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { api } from '../api'
|
||||
import Icon from '../components/Icon.vue'
|
||||
import { renderMarkdown } from '../lib/markdown'
|
||||
import { streamChat, chatOnce, buildPayloadMessages, nextId, seekId, type ChatMessage } from '../lib/chat'
|
||||
import { getChatDefaults } from '../lib/settings'
|
||||
import { pullHistory, pushHistory } from '../lib/history'
|
||||
import { stamp } from '../lib/download'
|
||||
import { useIsMobile } from '../lib/ui'
|
||||
import { pickImage, PRESETS, assertBodyBudget } from '../lib/upload'
|
||||
|
||||
const { isMobile } = useIsMobile()
|
||||
|
||||
const router = useRouter()
|
||||
const { t } = useI18n()
|
||||
|
||||
// ── 模型选项 ──
|
||||
const routes = ref<any[]>([])
|
||||
const textModels = ref<any[]>([])
|
||||
async function loadModels() {
|
||||
try {
|
||||
const j = await api('/v1/models')
|
||||
const data: any[] = j.data || []
|
||||
routes.value = data.filter((x) => x.type === 'route')
|
||||
textModels.value = data.filter((x) => x.type !== 'route')
|
||||
} catch (e: any) {
|
||||
if (e && e.status === 401) { router.push('/login'); return }
|
||||
ElMessage.error(t('chat.loadModelsErr', { msg: (e && e.message) || e }))
|
||||
}
|
||||
}
|
||||
function chainLabel(r: any) {
|
||||
const chain = (r.models || []).join(' → ')
|
||||
// 括号样式(全角/半角)也交给 i18n:英文里用半角更自然
|
||||
return t('chat.chainLabel', { id: r.id, chain: chain || t('chat.emptyChain') })
|
||||
}
|
||||
|
||||
// ── 视觉能力(第十三轮)──
|
||||
// 网关 /v1/models 会回 vision 字段(Agnes 3.0 Flash = true,其余文本模型默认 false)。
|
||||
// 带图请求走路由别名时网关会把视觉模型排到链首;选了**不支持视觉的真实模型**时
|
||||
// 这里提前告警并提供一键切换,避免"发了图但模型根本没看"。
|
||||
const visionModels = computed(() =>
|
||||
textModels.value.filter((m) => m.vision).map((m) => m.id))
|
||||
const visionOk = computed(() => {
|
||||
const m = routes.value.find((r) => r.id === params.model)
|
||||
if (m) return !!m.vision || !!(m.models || []).some((id: string) => visionModels.value.includes(id))
|
||||
const t2 = textModels.value.find((x) => x.id === params.model)
|
||||
return !!t2?.vision
|
||||
})
|
||||
const firstVisionModel = computed(() => visionModels.value[0] || '')
|
||||
function useVisionModel() {
|
||||
if (firstVisionModel.value) params.model = firstVisionModel.value
|
||||
}
|
||||
function modelLabel(m: any) {
|
||||
return `${m.id} · ${m.provider_name}`
|
||||
}
|
||||
|
||||
// ── 参数与状态 ──
|
||||
const params = reactive({
|
||||
model: 'wjd',
|
||||
temperature: 0.7,
|
||||
top_p: 1,
|
||||
max_tokens: null as number | null,
|
||||
stream: true,
|
||||
system: '',
|
||||
})
|
||||
const paramsOpen = ref(false)
|
||||
const streaming = ref(false)
|
||||
const messages = ref<ChatMessage[]>([])
|
||||
const text = ref('')
|
||||
// 第十三轮: 视觉对话 —— 待发送消息附带的图片(上传的图片在浏览器内压成 data URI;也支持粘 URL)
|
||||
interface PendingImg { uri: string; name: string; thumb: string }
|
||||
const pending = ref<PendingImg[]>([])
|
||||
const showImg = ref(false)
|
||||
const imgUrl = ref('')
|
||||
const fileEl = ref<HTMLInputElement | null>(null)
|
||||
const MAX_CHAT_IMGS = 4
|
||||
|
||||
function pickImages() {
|
||||
fileEl.value?.click()
|
||||
}
|
||||
function resetFileInput() {
|
||||
if (fileEl.value) fileEl.value.value = ''
|
||||
}
|
||||
function basename(u: string): string {
|
||||
if (u.startsWith('data:')) return t('chat.uploadedImage')
|
||||
try { return decodeURIComponent((u.split('/').pop() || u)).slice(0, 24) } catch { return u.slice(0, 24) }
|
||||
}
|
||||
async function onFiles(ev: Event) {
|
||||
const input = ev.target as HTMLInputElement
|
||||
const files = Array.from(input.files || [])
|
||||
for (const f of files) {
|
||||
if (pending.value.length >= MAX_CHAT_IMGS) {
|
||||
ElMessage.warning(t('chat.imgMax', { n: MAX_CHAT_IMGS })); break
|
||||
}
|
||||
try {
|
||||
// 选图就不再只看 URL:浏览器内直接压缩成 data URI(上游实测可用)
|
||||
const m = await pickImage(f, PRESETS.chat)
|
||||
pending.value.push({ uri: m.uri, name: m.name, thumb: m.thumb })
|
||||
} catch (e: any) {
|
||||
ElMessage.error(t('chat.imgPickErr', { msg: (e && e.message) || e }))
|
||||
}
|
||||
}
|
||||
resetFileInput()
|
||||
}
|
||||
function addImg() {
|
||||
const u = (imgUrl.value || '').trim()
|
||||
if (u && !pending.value.some((x) => x.uri === u)) {
|
||||
pending.value.push({ uri: u, name: basename(u), thumb: '' })
|
||||
}
|
||||
imgUrl.value = ''
|
||||
}
|
||||
const scrollEl = ref<any>(null)
|
||||
const userScrolled = ref(false)
|
||||
let abortCtrl: AbortController | null = null
|
||||
|
||||
const SKEY = 'gw_chat_history'
|
||||
// 写失败只提示一次,避免每次流式收尾都弹一遍
|
||||
let warned = false
|
||||
|
||||
async function persist() {
|
||||
// 第十三轮: 上传的图片是 data URI(几百 KB),而服务端对话条目上限 512KB —— 直接存会被
|
||||
// 截断成坏 base64(图片显示不出来、后续带图请求还会报错)。所以落历史时**只存缩略图**,
|
||||
// 原图仅保留在本次会话内存里(发送用的仍是原图)。URL 图片不受影响,原样保存。
|
||||
const slim = messages.value.map((m) => ({
|
||||
id: m.id, role: m.role, content: m.content,
|
||||
images: (m.images || []).map((u, i) => (u.startsWith('data:') && m.imgThumbs?.[i] ? m.imgThumbs[i] : u)),
|
||||
imgNames: m.imgNames || [],
|
||||
reasoning: m.reasoning || '', meta: m.meta || null, usage: m.usage || null,
|
||||
cost: m.cost ?? null, error: m.error || '',
|
||||
}))
|
||||
const state = { params: { ...params, model: params.model }, messages: slim }
|
||||
try {
|
||||
sessionStorage.setItem(SKEY, JSON.stringify(state)) // 本地留一份当缓存/离线兜底
|
||||
} catch { /* 配额满就只靠服务端 */ }
|
||||
// 对话原先只存 sessionStorage,关标签页即丢;现在同步到服务端(按账号)
|
||||
if (!(await pushHistory('chat', [{ id: 'current', ...state }]))) {
|
||||
if (!warned) { warned = true; ElMessage.warning(t('history.saveFail')) }
|
||||
}
|
||||
}
|
||||
function applyDefaults(defs: any) {
|
||||
if (defs.model) params.model = defs.model
|
||||
if (typeof defs.temperature === 'number') params.temperature = defs.temperature
|
||||
if (typeof defs.top_p === 'number') params.top_p = defs.top_p
|
||||
if (defs.max_tokens != null) params.max_tokens = defs.max_tokens
|
||||
if (typeof defs.stream === 'boolean') params.stream = defs.stream
|
||||
if (defs.system != null) params.system = defs.system
|
||||
}
|
||||
|
||||
function applyChat(j: any) {
|
||||
if (j?.params?.model) Object.assign(params, j.params)
|
||||
if (Array.isArray(j?.messages)) {
|
||||
let maxId = 0
|
||||
for (const m of j.messages) if (m.id > maxId) maxId = m.id
|
||||
seekId(maxId)
|
||||
messages.value = j.messages.map((m: any) => ({
|
||||
id: nextId(), role: m.role, content: m.content || '', images: m.images && m.images.length ? m.images : undefined,
|
||||
// 历史里的 data URI 已是被缩小的缩略图(见 persist),回填到 imgThumbs 让再次保存/展示一致
|
||||
imgNames: m.imgNames || [],
|
||||
imgThumbs: (m.images || []).map((u: string) => (u && u.startsWith('data:') ? u : '')),
|
||||
reasoning: m.reasoning || '', meta: m.meta || null,
|
||||
usage: m.usage || null, cost: m.cost ?? null, error: m.error || '',
|
||||
streaming: false,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
async function restore() {
|
||||
// M5: 无会话历史时,用设置页保存的默认参数做初始值。
|
||||
const defs = getChatDefaults()
|
||||
const remote = await pullHistory('chat')
|
||||
if (remote && remote.length) {
|
||||
applyChat(remote.find((x: any) => x.id === 'current') || remote[0])
|
||||
return
|
||||
}
|
||||
let raw: string | null = null
|
||||
try { raw = sessionStorage.getItem(SKEY) } catch { raw = null }
|
||||
if (!raw) { applyDefaults(defs); return }
|
||||
try {
|
||||
const j = JSON.parse(raw)
|
||||
applyChat(j)
|
||||
// 首次:把浏览器里的旧对话搬上服务端,之后就跟设备无关了
|
||||
if (remote) await pushHistory('chat', [{ id: 'current', ...j }])
|
||||
} catch { applyDefaults(defs) }
|
||||
}
|
||||
|
||||
const tokensText = (u: any) =>
|
||||
[u.prompt_tokens != null ? `↑${u.prompt_tokens}` : '', u.completion_tokens != null ? `↓${u.completion_tokens}` : '']
|
||||
.filter(Boolean).join(' ') || t('chat.totalTokens', { n: u.total_tokens ?? 0 })
|
||||
|
||||
function scrollToBottom() {
|
||||
if (userScrolled.value) return
|
||||
// 第十九轮:必须等 DOM 更新完再滚。watch 默认 flush:'pre',回调跑在渲染之前,
|
||||
// 读到的 scrollHeight 还是旧的 —— 打开长会话时会停在第 1 条(要一路往下拉)。
|
||||
nextTick(() => {
|
||||
const el = scrollEl.value
|
||||
if (el) el.scrollTop = el.scrollHeight
|
||||
})
|
||||
}
|
||||
function onScroll() {
|
||||
const el = scrollEl.value
|
||||
if (!el) return
|
||||
userScrolled.value = el.scrollHeight - el.scrollTop - el.clientHeight > 60
|
||||
}
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
// 输入法组词中的回车**不算**「发送」:中文 IME 确认候选词、手机软键盘的「换行/完成」
|
||||
// 都会抛 Enter keydown,此前会把半截话直接发出去。
|
||||
// keyCode 229 = 老浏览器/安卓键盘没有 isComposing 时的等价信号。Shift+Enter 仍是换行。
|
||||
const composing = e.isComposing || e.keyCode === 229
|
||||
if (e.key === 'Enter' && !e.shiftKey && !composing) {
|
||||
e.preventDefault()
|
||||
send()
|
||||
}
|
||||
}
|
||||
|
||||
/** iOS 软键盘不会压缩 100dvh,输入框可能被键盘盖住:等键盘弹起后再滚一次。 */
|
||||
function onInputFocus() {
|
||||
setTimeout(() => {
|
||||
const el = document.activeElement as HTMLElement | null
|
||||
el?.scrollIntoView({ block: 'nearest' })
|
||||
}, 320)
|
||||
}
|
||||
|
||||
// ── 展示用:本条对话的时间 / 耗时 / token 合计 ──
|
||||
// 只在组件内记(stamps 不落历史、不改接口也不进会话存储),刷新后历史消息没有时间戳,
|
||||
// 对应字段就不显示,而不是编一个值。
|
||||
const stamps = ref<Record<number, { at: number; ms?: number }>>({})
|
||||
function markStart(id: number) { stamps.value[id] = { at: Date.now() } }
|
||||
function markEnd(id: number) {
|
||||
const s = stamps.value[id]
|
||||
if (s && s.ms == null) s.ms = Date.now() - s.at
|
||||
}
|
||||
const pad2 = (n: number) => String(n).padStart(2, '0')
|
||||
function fmtClock(ms: number) {
|
||||
const d = new Date(ms)
|
||||
return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`
|
||||
}
|
||||
function fmtStamp(ms: number) {
|
||||
const d = new Date(ms)
|
||||
const now = new Date()
|
||||
const sameDay = d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()
|
||||
return sameDay
|
||||
? `${pad2(d.getHours())}:${pad2(d.getMinutes())}`
|
||||
: `${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`
|
||||
}
|
||||
function metaText(m: ChatMessage): string {
|
||||
const s = stamps.value[m.id]
|
||||
const parts: string[] = []
|
||||
if (s) parts.push(fmtClock(s.at))
|
||||
if (m.role === 'assistant') {
|
||||
if (m.meta?.served) parts.push(m.meta.served)
|
||||
if (s && s.ms != null) parts.push((s.ms / 1000).toFixed(1) + 's')
|
||||
if (m.usage) parts.push(tokensText(m.usage))
|
||||
}
|
||||
return parts.join(' · ')
|
||||
}
|
||||
const lastAt = computed(() => {
|
||||
for (let i = messages.value.length - 1; i >= 0; i--) {
|
||||
const s = stamps.value[messages.value[i].id]
|
||||
if (s) return s.at
|
||||
}
|
||||
return 0
|
||||
})
|
||||
const convTitle = computed(() => {
|
||||
const u = messages.value.find((m) => m.role === 'user' && m.content.trim())
|
||||
const s = (u?.content || '').replace(/\s+/g, ' ').trim()
|
||||
return s ? (s.length > 18 ? s.slice(0, 18) + '…' : s) : t('chat.newChat')
|
||||
})
|
||||
// 与服务端 history/chat 里当前那条同 id(多会话尚未实现,列表暂时只有这一条)
|
||||
const activeConvId = ref('current')
|
||||
const conversations = computed(() => [{
|
||||
id: activeConvId.value,
|
||||
title: convTitle.value,
|
||||
n: messages.value.length,
|
||||
time: lastAt.value ? fmtStamp(lastAt.value) : t('common.none'),
|
||||
}])
|
||||
const totalTokens = computed(() => {
|
||||
let sum = 0
|
||||
let seen = false
|
||||
for (const m of messages.value) {
|
||||
const u = m.usage
|
||||
if (!u) continue
|
||||
const v = u.total_tokens ?? ((u.prompt_tokens || 0) + (u.completion_tokens || 0))
|
||||
if (typeof v === 'number') { sum += v; seen = true }
|
||||
}
|
||||
return seen ? String(sum) : '—'
|
||||
})
|
||||
const elapsedText = computed(() => {
|
||||
let ms = 0
|
||||
for (const m of messages.value) {
|
||||
const s = stamps.value[m.id]
|
||||
if (s && s.ms) ms += s.ms
|
||||
}
|
||||
return ms ? (ms / 1000).toFixed(1) + 's' : '—'
|
||||
})
|
||||
|
||||
// ── 发送/流式 ──
|
||||
function buildPayload() {
|
||||
const history = messages.value.map((m) => ({ role: m.role, content: m.content, images: m.images }))
|
||||
return {
|
||||
model: params.model,
|
||||
messages: buildPayloadMessages(params.system, history),
|
||||
temperature: params.temperature,
|
||||
top_p: params.top_p,
|
||||
max_tokens: params.max_tokens ?? undefined,
|
||||
stream: params.stream,
|
||||
}
|
||||
}
|
||||
|
||||
async function send() {
|
||||
const input = text.value.trim()
|
||||
if ((!input && !pending.value.length) || streaming.value) return
|
||||
const picked = pending.value.slice()
|
||||
// 整包体积兜底:素材(data URI)+ 正文必须落在网关请求体上限内,否则会拿 413
|
||||
try {
|
||||
assertBodyBudget(picked.map((p) => p.uri), input.length + 512)
|
||||
} catch (e: any) {
|
||||
ElMessage.error((e && e.message) || String(e))
|
||||
return
|
||||
}
|
||||
const userMsg: ChatMessage = {
|
||||
id: nextId(), role: 'user', content: input,
|
||||
images: picked.length ? picked.map((p) => p.uri) : undefined,
|
||||
imgNames: picked.length ? picked.map((p) => p.name) : undefined,
|
||||
imgThumbs: picked.length ? picked.map((p) => p.thumb || p.uri) : undefined,
|
||||
}
|
||||
markStart(userMsg.id)
|
||||
messages.value.push(userMsg)
|
||||
text.value = ''
|
||||
pending.value = []
|
||||
showImg.value = false
|
||||
imgUrl.value = ''
|
||||
userScrolled.value = false
|
||||
scrollToBottom()
|
||||
|
||||
if (params.stream) await runStream(input)
|
||||
else await runOnce(input)
|
||||
}
|
||||
|
||||
async function runOnce(input: string) {
|
||||
const reply: ChatMessage = { id: nextId(), role: 'assistant', content: '', streaming: true }
|
||||
markStart(reply.id)
|
||||
messages.value.push(reply)
|
||||
persist()
|
||||
try {
|
||||
const j = await chatOnce(buildPayload())
|
||||
if (j && j.choices && j.choices[0]) {
|
||||
reply.content = (j.choices[0].message && j.choices[0].message.content) || ''
|
||||
} else {
|
||||
reply.content = j?.content || ''
|
||||
}
|
||||
reply.usage = j?.usage || undefined
|
||||
reply.cost = j?.estimated_cost_cny ?? undefined
|
||||
if (j?.route || j?.provider) {
|
||||
reply.meta = {
|
||||
served: j.served_model || j.model || params.model,
|
||||
provider: j.provider_name || j.provider,
|
||||
requested: j.model || params.model,
|
||||
fallback: !!(j.route && j.route.fallback_used),
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
reply.error = e?.message || String(e)
|
||||
} finally {
|
||||
reply.streaming = false
|
||||
markEnd(reply.id)
|
||||
persist(); scrollToBottom()
|
||||
}
|
||||
}
|
||||
|
||||
async function runStream(_input: string) {
|
||||
const reply: ChatMessage = { id: nextId(), role: 'assistant', content: '', reasoning: '', streaming: true }
|
||||
markStart(reply.id)
|
||||
messages.value.push(reply)
|
||||
streaming.value = true
|
||||
abortCtrl = new AbortController()
|
||||
persist(); scrollToBottom()
|
||||
|
||||
const handle = (chunk: any) => {
|
||||
if (chunk.error) { reply.error = chunk.error; return }
|
||||
// 网关元信息帧(首次出现 served/provider 时记录)
|
||||
if (chunk.served_model || chunk.provider) {
|
||||
reply.meta = {
|
||||
served: chunk.served_model || chunk.model || params.model,
|
||||
provider: chunk.provider_name || chunk.provider,
|
||||
requested: chunk.model || params.model,
|
||||
fallback: !!(chunk.route && chunk.route.fallback_used),
|
||||
}
|
||||
}
|
||||
if (chunk.usage && !chunk.choices?.length) {
|
||||
reply.usage = chunk.usage
|
||||
if (chunk.estimated_cost_cny != null) reply.cost = chunk.estimated_cost_cny
|
||||
}
|
||||
const delta = chunk.choices && chunk.choices[0] && chunk.choices[0].delta
|
||||
if (delta) {
|
||||
if (delta.reasoning_content) reply.reasoning = (reply.reasoning || '') + delta.reasoning_content
|
||||
if (delta.content != null) reply.content += delta.content
|
||||
}
|
||||
scrollToBottom()
|
||||
}
|
||||
|
||||
const fin = () => { reply.streaming = false; streaming.value = false; markEnd(reply.id); persist(); scrollToBottom() }
|
||||
|
||||
try {
|
||||
await streamChat(buildPayload(), handle, abortCtrl.signal)
|
||||
} catch (e: any) {
|
||||
if (e && e.name === 'AbortError') {
|
||||
reply.error = reply.error || t('chat.stopped')
|
||||
} else {
|
||||
reply.error = e?.message || String(e)
|
||||
}
|
||||
} finally {
|
||||
fin()
|
||||
}
|
||||
}
|
||||
|
||||
function stop() {
|
||||
if (abortCtrl) abortCtrl.abort()
|
||||
}
|
||||
|
||||
function clearConversation() {
|
||||
messages.value = []
|
||||
persist()
|
||||
}
|
||||
|
||||
// ── 重跑 / 复制 / 导出(都走已有数据与已有接口,不新增接口也不改存储键)──
|
||||
const lastUser = computed(() => {
|
||||
for (let i = messages.value.length - 1; i >= 0; i--) {
|
||||
if (messages.value[i].role === 'user') return messages.value[i]
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
async function regenerate() {
|
||||
const u = lastUser.value
|
||||
if (!u || streaming.value) return
|
||||
// 丢掉最后一条用户消息之后的内容,再用同一段输入重跑(与 send() 同一条路径、同一份参数)
|
||||
const idx = messages.value.lastIndexOf(u)
|
||||
messages.value = messages.value.slice(0, idx)
|
||||
userScrolled.value = false
|
||||
scrollToBottom()
|
||||
if (params.stream) await runStream(u.content)
|
||||
else await runOnce(u.content)
|
||||
}
|
||||
|
||||
async function copyAll() {
|
||||
const body = messages.value.map((m) => `[${m.role}] ${m.content}`).join('\n\n')
|
||||
try {
|
||||
await navigator.clipboard.writeText(body)
|
||||
ElMessage.success(t('common.copyOk'))
|
||||
} catch { ElMessage.warning(t('common.copyFail')) }
|
||||
}
|
||||
|
||||
function exportConv() {
|
||||
const body = messages.value
|
||||
.map((m) => `## ${m.role}\n\n${m.content}${m.reasoning ? `\n\n<details>${t('chat.reasoningTag')}</details>\n\n${m.reasoning}` : ''}`)
|
||||
.join('\n\n')
|
||||
const href = URL.createObjectURL(new Blob([body], { type: 'text/markdown;charset=utf-8' }))
|
||||
const a = document.createElement('a')
|
||||
a.href = href
|
||||
a.download = `chat-${stamp()}.md`
|
||||
a.style.display = 'none'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
// 立刻 revoke 会打断部分浏览器尚未开始的保存,延后回收
|
||||
setTimeout(() => URL.revokeObjectURL(href), 10_000)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
restore()
|
||||
loadModels()
|
||||
})
|
||||
onUnmounted(() => { if (abortCtrl) abortCtrl.abort() })
|
||||
|
||||
// 内容变化时自动滚动到底部(跟随流式输出)
|
||||
watch(messages, scrollToBottom, { deep: true })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* ── 两栏骨架 ── */
|
||||
/* 第十九轮:min-height:0 是关键 —— 不加它,flex/grid 子项的 min-height 默认取内容高度,
|
||||
里面的 .msgs(overflow-y:auto)就永远撑得开、滚不动,整页只能一路往下拉。 */
|
||||
.chat-main { min-width: 0; display: flex; flex-direction: column; gap: var(--gap); height: 100%; min-height: 0; }
|
||||
|
||||
/* ── 左栏 ── */
|
||||
.side-in { display: flex; flex-direction: column; gap: 8px; height: 100%; padding: 12px; }
|
||||
.new-conv { width: 100%; }
|
||||
.conv-list { display: flex; flex-direction: column; gap: 2px; overflow-y: auto; min-height: 0; }
|
||||
.conv { cursor: pointer; }
|
||||
.conv-info .nm { width: auto; color: var(--muted); }
|
||||
.side-ops { margin-top: auto; display: flex; gap: 7px; }
|
||||
.side-ops .op { flex: 1; }
|
||||
|
||||
/* ── 顶部参数胶囊 ── */
|
||||
.chat-top { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.chat-top .chip-sel { cursor: pointer; }
|
||||
.conv-sel { width: 170px; flex: none; }
|
||||
.stream-badge { font-size: 12.5px; color: var(--warn); }
|
||||
.vision-hint { margin-left: auto; font-size: 12px; color: var(--muted); }
|
||||
.vision-hint.off { color: var(--warn); }
|
||||
|
||||
/* ── 消息卡 ── */
|
||||
.chat-card { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
.chat-card .msgs { flex: 1; min-height: 0; }
|
||||
.empty { margin: auto; text-align: center; color: var(--muted); }
|
||||
.empty-t { margin-top: 10px; font-size: 13px; }
|
||||
|
||||
.resp-meta { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; flex-wrap: wrap; }
|
||||
.meta-txt { color: var(--muted); font-size: 12px; }
|
||||
.reasoning { margin-bottom: 6px; border: 1px dashed var(--warn); border-radius: 6px; }
|
||||
.reasoning :deep(.el-collapse-item__header) { font-size: 13px; color: var(--warn); background: transparent; }
|
||||
.reasoning-md {
|
||||
white-space: pre-wrap; color: var(--muted); font-size: 12.5px;
|
||||
max-height: 240px; overflow-y: auto; background: var(--surface); padding: 6px; border-radius: 4px;
|
||||
}
|
||||
.attach :deep(.el-image) {
|
||||
width: 46px; height: 46px; border-radius: 8px; overflow: hidden;
|
||||
border: 1px solid var(--line); flex: none;
|
||||
}
|
||||
.plain { white-space: pre-wrap; }
|
||||
.placeholder { color: var(--muted-2); font-style: italic; }
|
||||
.cursor { display: inline-block; width: 2px; height: 16px; background: currentColor; vertical-align: text-bottom; animation: blink .8s infinite; }
|
||||
@keyframes blink { 50% { opacity: 0; } }
|
||||
.err { margin-top: 6px; }
|
||||
|
||||
.md :deep(pre) { background: var(--surface); border: 1px solid var(--line); border-radius: 6px; padding: 10px; overflow-x: auto; font-size: 13px; }
|
||||
.md :deep(code) { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
||||
.md :deep(h1), .md :deep(h2), .md :deep(h3) { margin: 8px 0; }
|
||||
.md :deep(table) { border-collapse: collapse; }
|
||||
.md :deep(td), .md :deep(th) { border: 1px solid var(--line); padding: 4px 8px; }
|
||||
|
||||
/* ── 输入区 ── */
|
||||
.composer .in { padding-bottom: 8px; }
|
||||
.composer .bar { flex-wrap: wrap; }
|
||||
.img-bar { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-bottom: 6px; }
|
||||
.img-row { margin-bottom: 6px; }
|
||||
.img-chip { max-width: 180px; }
|
||||
.hide-file { display: none; }
|
||||
.vision-warn { margin-bottom: 6px; }
|
||||
.model-sel { flex: 1 1 150px; min-width: 110px; max-width: 230px; }
|
||||
.opt { display: flex; align-items: center; gap: 6px; }
|
||||
.tok { margin-left: auto; font-size: 11.5px; color: var(--muted-2); font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* ── 参数抽屉 ── */
|
||||
.param { margin-bottom: 18px; }
|
||||
.plabel { font-size: 13px; color: var(--muted); margin-bottom: 6px; }
|
||||
|
||||
/* ── 窄屏 ── */
|
||||
@media (max-width: 768px) {
|
||||
.vision-hint { margin-left: 0; width: 100%; }
|
||||
.model-sel { max-width: none; }
|
||||
/* 底部预留 iPhone 安全区(Home 指示条),否则「发送」按钮会被手势条压住一半 */
|
||||
.composer { padding-bottom: calc(10px + env(safe-area-inset-bottom, 0px)); }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,293 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<el-alert v-if="err" :title="err" type="error" show-icon :closable="false" class="mb" />
|
||||
|
||||
<!-- KPI:全部来自 /metrics + /health 的真实计数,没有可得的时序就不画趋势条 -->
|
||||
<div class="kpis">
|
||||
<div v-for="c in cards" :key="c.k" class="kpi">
|
||||
<div class="k">{{ c.k }}</div>
|
||||
<div class="v">{{ c.v }}</div>
|
||||
<div class="f"><span class="muted-2">{{ c.note }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid2">
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('dashboard.latency') }}</b>
|
||||
<span class="sub">P50 / P95</span>
|
||||
<div class="legend">
|
||||
<span><i style="background: var(--chart-a)" />P50</span>
|
||||
<span><i style="background: var(--chart-b)" />P95</span>
|
||||
</div>
|
||||
</div>
|
||||
<EChart :option="latOpt" height="228px" />
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('dashboard.providerStatus') }}</b>
|
||||
<span class="sub">{{ t('dashboard.circuit') }}</span>
|
||||
</div>
|
||||
<div class="pv">
|
||||
<div v-for="p in providerRows" :key="p.name" class="pv-i">
|
||||
<span class="nm">{{ p.name }}</span>
|
||||
<span class="meter" style="width: 70px"><i :style="{ width: p.ratio + '%' }" /></span>
|
||||
<span class="st"><span class="pill" :class="p.cls">{{ p.text }}</span></span>
|
||||
</div>
|
||||
<div v-if="!providerRows.length" class="hint">{{ t('dashboard.noData') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="sep" />
|
||||
|
||||
<div class="card-h" style="margin-bottom: 8px">
|
||||
<b>{{ t('dashboard.routeAlias') }}</b>
|
||||
<span class="sub">{{ t('dashboard.routeChain') }}</span>
|
||||
</div>
|
||||
<div class="pv" style="gap: 7px">
|
||||
<div v-for="(r, i) in routeRows" :key="r.name" class="pv-i" style="font-size: 12px">
|
||||
<span class="pill mute">{{ i + 1 }}</span>
|
||||
<span class="code flex-1">{{ r.name }}</span>
|
||||
<span class="st muted-2 nowrap">{{ r.short }}</span>
|
||||
</div>
|
||||
<div v-if="!routeRows.length" class="hint">{{ t('dashboard.noData') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid3">
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('dashboard.modelCalls') }}</b>
|
||||
<span class="sub">{{ t('dashboard.live') }}</span>
|
||||
</div>
|
||||
<el-table :data="callRows" size="small" v-loading="loading" :show-header="true">
|
||||
<el-table-column prop="model" :label="t('dashboard.colModel')" min-width="170">
|
||||
<template #default="{ row }">
|
||||
<span class="code">{{ row.model }}</span>
|
||||
<div class="hint">{{ row.provider }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="calls" :label="t('dashboard.colCalls')" width="80" />
|
||||
<el-table-column prop="latency" :label="t('dashboard.colLatency')" width="96" />
|
||||
<el-table-column :label="t('dashboard.colRate')" width="92">
|
||||
<template #default="{ row }">
|
||||
<span class="pill" :class="row.rateCls">{{ row.rate }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<div v-if="!callRows.length && !loading" class="hint" style="padding: 8px 0">{{ t('dashboard.noModels') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('dashboard.provShare') }}</b>
|
||||
<span class="sub">{{ t('dashboard.share') }}</span>
|
||||
</div>
|
||||
<EChart :option="provOpt" height="228px" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card about-card">
|
||||
<div class="about-line">
|
||||
<b>{{ t('dashboard.gatewayInfo') }} · v{{ health.version || '-' }}</b>
|
||||
<span>{{ t('dashboard.running') }}</span>
|
||||
<span>{{ t('dashboard.uptime') }} {{ uptimeText }}</span>
|
||||
<span>{{ t('dashboard.inflight') }} {{ health.in_flight ?? '-' }} / {{ health.in_flight_peak ?? '-' }}</span>
|
||||
<span>{{ t('dashboard.fallback') }} {{ health.fallback_total ?? 0 }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { api } from '../api'
|
||||
import EChart from '../components/EChart.vue'
|
||||
import { categoryAxis, chartTheme, emptyTip, grid, legend, pieLabel, pieLabelLine, pieRadius, pieCenter, pieData, valueAxis } from '../lib/charts'
|
||||
import type { EChartsCoreOption } from '../lib/echarts'
|
||||
import { useTheme } from '../lib/theme'
|
||||
|
||||
const router = useRouter()
|
||||
const { t } = useI18n()
|
||||
const { resolved } = useTheme() // 主题变化时重算图表配色
|
||||
const health = ref<any>({})
|
||||
const metrics = ref<any>({})
|
||||
const models = ref<any>({})
|
||||
const routes = ref<any[]>([])
|
||||
const loading = ref(false)
|
||||
const err = ref('')
|
||||
|
||||
const textModels = ref<Record<string, string>>({})
|
||||
|
||||
function sum(list: any[], key: string): number {
|
||||
// 熔断返回的是 ProviderStat 对象,键缺失时按 0 处理
|
||||
return list.reduce((acc, x) => acc + (Number(x && x[key]) || 0), 0)
|
||||
}
|
||||
const calls = computed(() => metrics.value.calls || {})
|
||||
const totalOk = computed(() => sum(Object.values(calls.value) as any[], 'ok'))
|
||||
const totalFail = computed(() => sum(Object.values(calls.value) as any[], 'fail'))
|
||||
const total = computed(() => totalOk.value + totalFail.value)
|
||||
const rate = computed(() => (total.value ? (totalOk.value / total.value) * 100 : 100))
|
||||
|
||||
const latency = computed<any>(() => metrics.value.latency || {})
|
||||
const avgP50 = computed(() => {
|
||||
const vals = Object.values(latency.value) as any[]
|
||||
if (!vals.length) return 0
|
||||
return vals.reduce((a, x) => a + (Number(x?.p50) || 0), 0) / vals.length
|
||||
})
|
||||
const maxP95 = computed(() => {
|
||||
const vals = Object.values(latency.value) as any[]
|
||||
return vals.reduce((a, x) => Math.max(a, Number(x?.p95) || 0), 0)
|
||||
})
|
||||
|
||||
const cards = computed(() => {
|
||||
void resolved.value // 触发依赖,主题切换时 KPI 也重算(颜色走 CSS,无需改值)
|
||||
return [
|
||||
{ k: t('dashboard.requests'), v: total.value, note: t('dashboard.noteOkFail', { ok: totalOk.value, fail: totalFail.value }) },
|
||||
{ k: t('dashboard.successRate'), v: rate.value.toFixed(1) + '%', note: t('dashboard.noteFail', { n: totalFail.value }) },
|
||||
{ k: t('dashboard.avgLatency'), v: avgP50.value.toFixed(2) + 's', note: t('dashboard.noteP95', { v: maxP95.value.toFixed(2) }) },
|
||||
{ k: t('dashboard.fallbackShort'), v: health.value.fallback_total ?? 0, note: t('dashboard.noteInflight', { n: health.value.in_flight ?? 0 }) },
|
||||
]
|
||||
})
|
||||
|
||||
const providerRows = computed(() => {
|
||||
const p = health.value.providers || {}
|
||||
return Object.keys(p).map((k) => {
|
||||
const c = String(p[k].circuit || '').toUpperCase()
|
||||
const cls = c === 'CLOSED' ? 'ok' : c === 'HALF_OPEN' ? 'warn' : c === 'OPEN' ? 'err' : 'mute'
|
||||
const calls2 = metrics.value?.providers?.[k] || {}
|
||||
const ok = Number(calls2.ok) || 0
|
||||
const fail = Number(calls2.fail) || 0
|
||||
const tot = ok + fail
|
||||
return {
|
||||
name: p[k].name,
|
||||
cls,
|
||||
text: t(`dashboard.circ_${String(p[k].circuit || '').toLowerCase() || ''}`),
|
||||
ratio: tot ? Math.max(6, Math.round((ok / tot) * 100)) : 6,
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
const routeRows = computed(() => {
|
||||
const m = models.value
|
||||
return routes.value.map((r: any) => {
|
||||
const chain: string[] = (m[r.id] || []).map((x: any) => (typeof x === 'string' ? x : x.id || x.name))
|
||||
return { name: r.id, short: chain.length ? t('models.chainCount', { n: chain.length }) : '—' }
|
||||
})
|
||||
})
|
||||
|
||||
const callRows = computed(() => {
|
||||
const c = calls.value
|
||||
return Object.keys(c)
|
||||
.map((m) => {
|
||||
const ok = Number(c[m]?.ok) || 0
|
||||
const fail = Number(c[m]?.fail) || 0
|
||||
const tot = ok + fail
|
||||
const r = tot ? (ok / tot) * 100 : 100
|
||||
const p50 = latency.value[m]?.p50
|
||||
return {
|
||||
model: m,
|
||||
provider: textModels.value[m] || '—',
|
||||
calls: tot,
|
||||
latency: p50 != null ? Number(p50).toFixed(2) + 's' : '—',
|
||||
rate: r.toFixed(1) + '%',
|
||||
rateCls: r >= 99 ? 'ok' : r >= 90 ? 'warn' : 'err',
|
||||
_tot: tot,
|
||||
}
|
||||
})
|
||||
.sort((a, b) => b._tot - a._tot)
|
||||
.slice(0, 8)
|
||||
})
|
||||
|
||||
const latOpt = computed<EChartsCoreOption>(() => {
|
||||
void resolved.value
|
||||
const c = chartTheme()
|
||||
const l = latency.value
|
||||
const ms = Object.keys(l).slice(0, 10)
|
||||
const p50 = ms.map((m) => l[m]?.p50 ?? 0)
|
||||
const p95 = ms.map((m) => l[m]?.p95 ?? 0)
|
||||
return {
|
||||
tooltip: { trigger: 'axis', valueFormatter: (v: any) => `${typeof v === 'number' ? v.toFixed(3) : v}s` },
|
||||
legend: legend(['P50', 'P95']),
|
||||
grid,
|
||||
graphic: emptyTip([p50, p95], t('dashboard.noData')),
|
||||
xAxis: categoryAxis(ms),
|
||||
yAxis: valueAxis('s'),
|
||||
series: [
|
||||
{ name: 'P50', type: 'bar', data: p50, itemStyle: { color: c.a, borderRadius: [4, 4, 0, 0] } },
|
||||
{ name: 'P95', type: 'bar', data: p95, itemStyle: { color: c.b, borderRadius: [4, 4, 0, 0] } },
|
||||
],
|
||||
} as EChartsCoreOption
|
||||
})
|
||||
|
||||
const provOpt = computed<EChartsCoreOption>(() => {
|
||||
void resolved.value
|
||||
const p = metrics.value.providers || {}
|
||||
const items = Object.keys(p).map((k) => ({ name: k, value: p[k]?.ok || 0 })).filter((x) => x.value > 0)
|
||||
return {
|
||||
tooltip: { trigger: 'item' },
|
||||
series: [{
|
||||
type: 'pie', radius: pieRadius, center: pieCenter, minAngle: 6, labelLine: pieLabelLine,
|
||||
data: pieData(items, t('dashboard.noData')), label: pieLabel(), itemStyle: { borderRadius: 4 },
|
||||
}],
|
||||
}
|
||||
})
|
||||
|
||||
// 运行时间实时跳动:/health 是 5s 一拉,直接用返回值会「5 秒跳一格」。
|
||||
const uptimeAt = ref(Date.now())
|
||||
const nowTick = ref(Date.now())
|
||||
const uptimeText = computed(() => {
|
||||
const u = health.value.uptime_seconds
|
||||
if (u == null) return '-'
|
||||
void nowTick.value
|
||||
const live = u + Math.max(0, (nowTick.value - uptimeAt.value) / 1000)
|
||||
const h = Math.floor(live / 3600), m = Math.floor((live % 3600) / 60), s = Math.floor(live % 60)
|
||||
return `${h}h ${m}m ${s}s`
|
||||
})
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
err.value = ''
|
||||
try {
|
||||
health.value = await api('/health')
|
||||
uptimeAt.value = Date.now()
|
||||
try { metrics.value = await api('/metrics') } catch { /* 指标可选 */ }
|
||||
try {
|
||||
const um = await api('/v1/models')
|
||||
const data = um.data || []
|
||||
routes.value = data.filter((x: any) => x.type === 'route')
|
||||
const map: Record<string, string> = {}
|
||||
for (const x of data) if (x.type !== 'route') map[x.id] = x.provider_name || ''
|
||||
textModels.value = map
|
||||
const list = data.filter((x: any) => x.type === 'route')
|
||||
const m: Record<string, any> = {}
|
||||
for (const r of list) m[r.id] = r.models || []
|
||||
models.value = m
|
||||
} catch { /* 模型列表可选 */ }
|
||||
} catch (e: any) {
|
||||
if (e && e.status === 401) { router.push('/login'); return }
|
||||
err.value = t('settings.loadErr') + ': ' + ((e && e.message) || String(e))
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
let timer: any = null
|
||||
let tickTimer: any = null
|
||||
onMounted(() => {
|
||||
load()
|
||||
timer = setInterval(load, 8000)
|
||||
tickTimer = setInterval(() => { nowTick.value = Date.now() }, 1000)
|
||||
})
|
||||
onUnmounted(() => { clearInterval(timer); clearInterval(tickTimer) })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.kpi .v { color: var(--text); }
|
||||
.sep { height: 1px; background: var(--line-2); margin: 12px 0 10px; }
|
||||
.about-card { margin-top: var(--gap); padding: 12px 16px; }
|
||||
.about-line b { color: var(--text); }
|
||||
</style>
|
||||
@@ -0,0 +1,251 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 第二十二轮:意见反馈(普通账号 / 管理员都能提)。
|
||||
左「写」右「我提交过的」在桌面并排,窄屏自动上下堆叠。 -->
|
||||
<div class="fb-wrap">
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('nav.menufeedback') }}</b>
|
||||
<span class="sub">{{ t('feedback.imagesHint', { n: FEEDBACK_MAX_IMAGES }) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label>{{ t('feedback.write') }}</label>
|
||||
<el-input
|
||||
v-model="content"
|
||||
type="textarea"
|
||||
:rows="7"
|
||||
:maxlength="2000"
|
||||
show-word-limit
|
||||
resize="none"
|
||||
:placeholder="t('feedback.placeholder')"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="fb-picks">
|
||||
<div v-for="(m, i) in picks" :key="i" class="fb-pick">
|
||||
<img :src="m.thumb || m.uri" :alt="m.name" />
|
||||
<button class="fb-del" type="button" :title="t('feedback.remove')" @click="remove(i)">
|
||||
<Icon name="x" :size="12" />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-if="picks.length < FEEDBACK_MAX_IMAGES"
|
||||
class="fb-add"
|
||||
type="button"
|
||||
:title="t('feedback.attach')"
|
||||
@click="fileEl?.click()"
|
||||
>
|
||||
<Icon name="plus" :size="18" />
|
||||
<span>{{ t('feedback.attach') }}</span>
|
||||
</button>
|
||||
<input ref="fileEl" class="fb-file" type="file" accept="image/*" multiple @change="onPick" />
|
||||
</div>
|
||||
|
||||
<div class="fb-actions">
|
||||
<el-button type="primary" :loading="sending" :disabled="!content.trim()" @click="submit">
|
||||
{{ t('feedback.submit') }}
|
||||
</el-button>
|
||||
<span v-if="picks.length" class="hint">{{ t('inbox.imgCount', { n: picks.length }) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('feedback.mine') }}</b>
|
||||
<span class="sub">{{ t('feedback.mineSub') }}</span>
|
||||
<div class="pager">
|
||||
<el-button size="small" text :disabled="loading" @click="load()">
|
||||
<Icon name="refresh" :size="13" />
|
||||
<span>{{ t('common.refresh') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="fb-filter">
|
||||
<el-select v-model="mineStatus" size="small" class="sel-mine">
|
||||
<el-option :label="t('feedback.statusAll')" value="" />
|
||||
<el-option v-for="st in FEEDBACK_STATUSES" :key="st" :value="st" :label="t(`fbStatus.${st}`)" />
|
||||
</el-select>
|
||||
</div>
|
||||
|
||||
<div v-if="!mineView.length" class="hint">{{ t('feedback.empty') }}</div>
|
||||
<div v-else class="fb-list">
|
||||
<div v-for="it in mineView" :key="it.id" class="fb-item">
|
||||
<div class="fb-meta">
|
||||
<span class="ts">{{ fmtTs(it.created) }}</span>
|
||||
<!-- 处理进度:提交人看得到,管理员在「用户反馈」里推进 -->
|
||||
<span class="badge" :class="FEEDBACK_STATUS_CLASS[it.status] || 'm'">
|
||||
{{ t(`fbStatus.${it.status}`) }}
|
||||
</span>
|
||||
<span v-if="it.images?.length" class="pill mute">{{ t('inbox.imgCount', { n: it.images.length }) }}</span>
|
||||
<span v-if="it.status === 'pending'" class="spacer" />
|
||||
<!-- 只有还停在「待处理」的单子能撤:管理员一动就不给了(服务端也把着关) -->
|
||||
<el-button
|
||||
v-if="it.status === 'pending'"
|
||||
size="small" text type="danger"
|
||||
:loading="revoking === it.id"
|
||||
@click="revoke(it)"
|
||||
>{{ t('feedback.revoke') }}</el-button>
|
||||
</div>
|
||||
<div class="fb-text">{{ it.content }}</div>
|
||||
<FeedbackImages :item="it" />
|
||||
<!-- 处理记录:提交 + 管理员的每一次动作(含说明与是谁处理的) -->
|
||||
<FeedbackTimeline :item="it" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import Icon from '../components/Icon.vue'
|
||||
import FeedbackImages from '../components/FeedbackImages.vue'
|
||||
import FeedbackTimeline from '../components/FeedbackTimeline.vue'
|
||||
import {
|
||||
FEEDBACK_MAX_IMAGES, FEEDBACK_STATUSES, FEEDBACK_STATUS_CLASS, myFeedback, pickFeedbackImage,
|
||||
submitFeedback, withdrawFeedback, type FeedbackItem,
|
||||
} from '../lib/feedback'
|
||||
import type { PickedMedia } from '../lib/upload'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const content = ref('')
|
||||
const picks = ref<PickedMedia[]>([])
|
||||
const mine = ref<FeedbackItem[]>([])
|
||||
const sending = ref(false)
|
||||
const loading = ref(false)
|
||||
const mineStatus = ref('') // 「我提交过的」状态过滤:''=全部
|
||||
const mineView = computed(() =>
|
||||
mineStatus.value ? mine.value.filter((it) => it.status === mineStatus.value) : mine.value,
|
||||
)
|
||||
const revoking = ref('') // 正在撤回的那条 id(按钮 loading 用)
|
||||
const fileEl = ref<HTMLInputElement | null>(null)
|
||||
|
||||
function fmtTs(ts: number): string {
|
||||
if (!ts) return '—'
|
||||
const d = new Date(ts * 1000)
|
||||
const p = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try {
|
||||
mine.value = await myFeedback()
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || String(e))
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function onPick(ev: Event) {
|
||||
const el = ev.target as HTMLInputElement
|
||||
const files = Array.from(el.files || [])
|
||||
el.value = '' // 先清空:同一个文件再选一次也要能触发 change
|
||||
for (const f of files) {
|
||||
if (picks.value.length >= FEEDBACK_MAX_IMAGES) {
|
||||
ElMessage.warning(t('feedback.imagesHint', { n: FEEDBACK_MAX_IMAGES }))
|
||||
break
|
||||
}
|
||||
try {
|
||||
// pickImage 内部已生成缩略图(256px,列表 84px 显示够用),随包一起上送:
|
||||
// 服务端 JSON 只存它,列表页因此不用再逐张取原图。
|
||||
picks.value.push(await pickFeedbackImage(f))
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || String(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function remove(i: number) {
|
||||
picks.value.splice(i, 1)
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!content.value.trim()) {
|
||||
ElMessage.warning(t('feedback.needContent'))
|
||||
return
|
||||
}
|
||||
sending.value = true
|
||||
try {
|
||||
await submitFeedback({ content: content.value, images: picks.value })
|
||||
content.value = ''
|
||||
picks.value = []
|
||||
ElMessage.success(t('feedback.submitted'))
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || String(e))
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 撤回=真删,所以必须二次确认(与图像「清空历史」同一条规矩)。
|
||||
// 前端只在 pending 时给按钮,但服务端才是权威:管理员可能刚好在你点开确认框时动手,
|
||||
// 那种情况下 DELETE 会回 400,这里把服务端的话直接展示出来,别假装成功。
|
||||
async function revoke(it: FeedbackItem) {
|
||||
try {
|
||||
await ElMessageBox.confirm(t('feedback.revokeBody', { n: it.content.slice(0, 40) }), t('feedback.revokeTitle'), {
|
||||
type: 'warning',
|
||||
confirmButtonText: t('feedback.revoke'),
|
||||
cancelButtonText: t('common.cancel'),
|
||||
})
|
||||
} catch { return }
|
||||
revoking.value = it.id
|
||||
try {
|
||||
await withdrawFeedback(it.id)
|
||||
mine.value = mine.value.filter((x) => x.id !== it.id)
|
||||
ElMessage.success(t('feedback.revoked'))
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || String(e))
|
||||
await load() // 状态可能已被管理员改掉,拉一次以真实状态为准
|
||||
} finally {
|
||||
revoking.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.fb-wrap { display: grid; grid-template-columns: 1.15fr 1fr; gap: var(--gap); align-items: start; }
|
||||
@media (max-width: 900px) { .fb-wrap { grid-template-columns: 1fr; } }
|
||||
.fb-picks { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 12px; }
|
||||
.fb-pick { position: relative; width: 84px; height: 84px; border-radius: 10px; overflow: hidden; border: 1px solid var(--line); }
|
||||
.fb-pick img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
.fb-del {
|
||||
position: absolute; top: 3px; right: 3px; width: 20px; height: 20px; padding: 0;
|
||||
display: grid; place-items: center; border: 0; border-radius: 7px; cursor: pointer;
|
||||
background: rgba(0, 0, 0, .55); color: #fff;
|
||||
}
|
||||
.fb-add {
|
||||
width: 84px; height: 84px; border: 1px dashed var(--line); border-radius: 10px;
|
||||
background: var(--surface-2); color: var(--muted); cursor: pointer;
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px;
|
||||
font-size: 11px; padding: 0 4px; text-align: center;
|
||||
}
|
||||
.fb-add:hover { border-color: var(--primary); color: var(--primary); }
|
||||
.fb-file { display: none; }
|
||||
.fb-actions { display: flex; align-items: center; gap: 10px; margin-top: 14px; }
|
||||
.fb-list { display: flex; flex-direction: column; }
|
||||
.fb-item {
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
padding: 12px 14px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.fb-item:last-child { margin-bottom: 0; }
|
||||
.fb-meta { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.fb-meta .spacer { flex: 1; }
|
||||
.fb-meta .ts { font-size: 11.5px; color: var(--muted-2); font-variant-numeric: tabular-nums; }
|
||||
.fb-filter { display: flex; margin: 2px 0 6px; }
|
||||
.sel-mine { width: 128px; }
|
||||
.fb-text { margin-top: 6px; font-size: 12.5px; line-height: 1.62; white-space: pre-wrap; word-break: break-word; }
|
||||
</style>
|
||||
@@ -0,0 +1,264 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 第二十二轮:用户反馈(admin 专属)—— 全部账号提交的意见,含图片。 -->
|
||||
<div class="filters">
|
||||
<el-select v-model="account" :placeholder="t('inbox.account')" clearable size="small" class="sel-acct">
|
||||
<el-option :label="t('inbox.all')" value="" />
|
||||
<el-option v-for="a in accounts" :key="a" :value="a" :label="a" />
|
||||
</el-select>
|
||||
<el-select v-model="status" :placeholder="t('inbox.status')" clearable size="small" class="sel-st">
|
||||
<el-option :label="t('inbox.allStatus')" value="" />
|
||||
<el-option v-for="s in FEEDBACK_STATUSES" :key="s" :value="s" :label="t(`fbStatus.${s}`)" />
|
||||
</el-select>
|
||||
<el-select v-model="arch" size="small" class="sel-arch">
|
||||
<el-option :label="t('inbox.archActive')" value="active" />
|
||||
<el-option :label="t('inbox.archOnly')" value="arch" />
|
||||
<el-option :label="t('inbox.archAll')" value="" />
|
||||
</el-select>
|
||||
<el-input v-model="kw" size="small" :placeholder="t('inbox.kw')" clearable class="kw-in">
|
||||
<template #append><el-button @click="apply">{{ t('common.search') }}</el-button></template>
|
||||
</el-input>
|
||||
<span class="spacer" />
|
||||
<el-button v-if="filtered.length !== items.length" size="small" text @click="clear">{{ t('logs.clearFilter') }}</el-button>
|
||||
<el-button size="small" :disabled="loading" @click="load()">
|
||||
<Icon name="refresh" :size="13" />
|
||||
<span>{{ t('common.refresh') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('nav.menufeedbackinbox') }}</b>
|
||||
<span class="sub">{{ t('inbox.count', { n: filtered.length }) }}</span>
|
||||
<div class="pager">
|
||||
<span v-if="filtered.length > PAGE_SIZE" class="pg" :class="{ dis: page <= 1 }" @click="go(page - 1)">
|
||||
<Icon name="chev" :size="12" class="flip" />
|
||||
</span>
|
||||
<span v-if="filtered.length > PAGE_SIZE" class="hint">{{ page }} / {{ pages }}</span>
|
||||
<span v-if="filtered.length > PAGE_SIZE" class="pg" :class="{ dis: page >= pages }" @click="go(page + 1)">
|
||||
<Icon name="chev" :size="12" />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-loading="loading" class="fb-list">
|
||||
<div v-if="!filtered.length" class="hint">
|
||||
<span>{{ items.length ? t('inbox.emptyFiltered', { n: items.length }) : t('inbox.empty') }}</span>
|
||||
<el-button v-if="items.length" size="small" text @click="clear">{{ t('logs.clearFilter') }}</el-button>
|
||||
</div>
|
||||
|
||||
<div v-for="it in paged" :key="it.id" class="fb-item">
|
||||
<div class="fb-meta">
|
||||
<span class="ts">{{ fmtTs(it.created) }}</span>
|
||||
<span class="badge m">{{ it.account }}</span>
|
||||
<span class="badge" :class="FEEDBACK_STATUS_CLASS[it.status] || 'm'">{{ t(`fbStatus.${it.status}`) }}</span>
|
||||
<span v-if="it.images?.length" class="pill mute">
|
||||
<Icon name="img" :size="11" />
|
||||
{{ t('inbox.imgCount', { n: it.images.length }) }}
|
||||
</span>
|
||||
<span v-if="it.archived" class="badge m">{{ t('inbox.archived') }}</span>
|
||||
<span class="spacer" />
|
||||
<el-button size="small" @click="openHandle(it)">{{ t('inbox.handle') }}</el-button>
|
||||
<el-button size="small" text :loading="busy === it.id" @click="toggleArchive(it)">
|
||||
{{ it.archived ? t('inbox.unarchive') : t('inbox.archive') }}
|
||||
</el-button>
|
||||
<el-button size="small" text type="danger" @click="remove(it)">{{ t('inbox.delete') }}</el-button>
|
||||
</div>
|
||||
<div class="fb-text">{{ it.content }}</div>
|
||||
<FeedbackImages :item="it" />
|
||||
<!-- 处理记录:谁在什么时候把它推到哪一档、留了什么说明,逐条可查 -->
|
||||
<FeedbackTimeline :item="it" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 处理:改进度 + 给提交人留一句话(提交人在「我提交过的」里看到) -->
|
||||
<el-dialog v-model="handleShow" :title="t('inbox.dialogTitle')" width="min(520px, 92vw)">
|
||||
<div class="field">
|
||||
<label>{{ t('inbox.status') }}</label>
|
||||
<el-radio-group v-model="form.status">
|
||||
<el-radio-button v-for="s in FEEDBACK_STATUSES" :key="s" :value="s">
|
||||
{{ t(`fbStatus.${s}`) }}
|
||||
</el-radio-button>
|
||||
</el-radio-group>
|
||||
</div>
|
||||
<div class="field mt">
|
||||
<label>{{ t('inbox.noteLabel') }}</label>
|
||||
<el-input
|
||||
v-model="form.note"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
:maxlength="500"
|
||||
show-word-limit
|
||||
resize="none"
|
||||
:placeholder="t('inbox.notePlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="handleShow = false">{{ t('common.cancel') }}</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="save">{{ t('inbox.save') }}</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import Icon from '../components/Icon.vue'
|
||||
import FeedbackImages from '../components/FeedbackImages.vue'
|
||||
import FeedbackTimeline from '../components/FeedbackTimeline.vue'
|
||||
import { allFeedback, updateFeedback, archiveFeedback, adminDeleteFeedback, FEEDBACK_STATUSES, FEEDBACK_STATUS_CLASS, type FeedbackItem } from '../lib/feedback'
|
||||
|
||||
const { t } = useI18n()
|
||||
const PAGE_SIZE = 10
|
||||
|
||||
const items = ref<FeedbackItem[]>([])
|
||||
const loading = ref(false)
|
||||
const account = ref('')
|
||||
const status = ref('')
|
||||
const kw = ref('')
|
||||
const applied = ref('')
|
||||
const page = ref(1)
|
||||
const arch = ref<'active' | 'arch' | ''>('active')
|
||||
const busy = ref('')
|
||||
|
||||
// 处理弹窗
|
||||
const handleShow = ref(false)
|
||||
const saving = ref(false)
|
||||
const form = ref<{ id: string; status: FeedbackItem['status']; note: string }>({ id: '', status: 'pending', note: '' })
|
||||
|
||||
function openHandle(it: FeedbackItem) {
|
||||
form.value = { id: it.id, status: it.status, note: it.note || '' }
|
||||
handleShow.value = true
|
||||
}
|
||||
|
||||
async function save() {
|
||||
saving.value = true
|
||||
try {
|
||||
const updated = await updateFeedback(form.value.id, form.value.status, form.value.note)
|
||||
// 就地替换:不整表重拉,筛选/页码/滚动位置都不动
|
||||
const i = items.value.findIndex((x) => x.id === updated.id)
|
||||
if (i >= 0) items.value[i] = updated
|
||||
handleShow.value = false
|
||||
ElMessage.success(t('inbox.saved'))
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || String(e))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleArchive(it: FeedbackItem) {
|
||||
busy.value = it.id
|
||||
try {
|
||||
const updated = await archiveFeedback(it.id, !it.archived)
|
||||
const i = items.value.findIndex((x) => x.id === updated.id)
|
||||
if (i >= 0) items.value[i] = updated
|
||||
ElMessage.success(updated.archived ? t('inbox.archOk') : t('inbox.unarchOk'))
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || String(e))
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
async function remove(it: FeedbackItem) {
|
||||
try {
|
||||
await ElMessageBox.confirm(t('inbox.deleteConfirm'), t('inbox.delete'), {
|
||||
type: 'warning',
|
||||
confirmButtonText: t('inbox.delete'),
|
||||
cancelButtonText: t('common.cancel'),
|
||||
})
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await adminDeleteFeedback(it.id)
|
||||
items.value = items.value.filter((x) => x.id !== it.id)
|
||||
ElMessage.success(t('inbox.deleted'))
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || String(e))
|
||||
}
|
||||
}
|
||||
|
||||
/** 账号下拉直接由数据里出现过的账号生成 —— 不给服务端再加一个"谁提过反馈"的接口。 */
|
||||
const accounts = computed(() => {
|
||||
const set = new Set<string>()
|
||||
items.value.forEach((it) => it.account && set.add(it.account))
|
||||
return Array.from(set).sort()
|
||||
})
|
||||
|
||||
const filtered = computed(() => {
|
||||
const k = applied.value.trim().toLowerCase()
|
||||
return items.value.filter((it) => {
|
||||
if (account.value && it.account !== account.value) return false
|
||||
if (status.value && it.status !== status.value) return false
|
||||
if (arch.value === 'active' && it.archived) return false
|
||||
if (arch.value === 'arch' && !it.archived) return false
|
||||
if (!k) return true
|
||||
return it.content.toLowerCase().includes(k) || it.account.toLowerCase().includes(k)
|
||||
})
|
||||
})
|
||||
|
||||
const pages = computed(() => Math.max(1, Math.ceil(filtered.value.length / PAGE_SIZE)))
|
||||
const paged = computed(() => filtered.value.slice((page.value - 1) * PAGE_SIZE, page.value * PAGE_SIZE))
|
||||
|
||||
// 任何筛选变化都回第一页,免得停在一个已经空的页码上
|
||||
watch([filtered, account, status], () => { if (page.value > pages.value) page.value = 1 })
|
||||
|
||||
function apply() { applied.value = kw.value; page.value = 1 }
|
||||
function clear() { kw.value = ''; applied.value = ''; account.value = ''; status.value = ''; arch.value = 'active'; page.value = 1 }
|
||||
function go(p: number) { page.value = Math.min(Math.max(1, p), pages.value) }
|
||||
|
||||
function fmtTs(ts: number): string {
|
||||
if (!ts) return '—'
|
||||
const d = new Date(ts * 1000)
|
||||
const p = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try {
|
||||
items.value = await allFeedback()
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || String(e))
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.sel-acct { width: 150px; }
|
||||
.sel-st { width: 128px; }
|
||||
.sel-arch { width: 128px; }
|
||||
.kw-in { width: 210px; }
|
||||
.filters .spacer { flex: 1; }
|
||||
.fb-list { min-height: 60px; }
|
||||
.fb-item {
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
padding: 12px 14px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.fb-item:last-child { margin-bottom: 0; }
|
||||
.fb-meta { display: flex; align-items: center; gap: 8px; }
|
||||
.fb-meta .ts { font-size: 11.5px; color: var(--muted-2); font-variant-numeric: tabular-nums; }
|
||||
.fb-meta .pill { display: inline-flex; align-items: center; gap: 4px; }
|
||||
.fb-text { margin-top: 6px; font-size: 13px; line-height: 1.65; white-space: pre-wrap; word-break: break-word; }
|
||||
.field { margin-bottom: 12px; }
|
||||
.field.mt { margin-top: 4px; }
|
||||
.field label { display: block; margin-bottom: 6px; font-size: 12.5px; color: var(--muted); }
|
||||
.pg.dis { opacity: .35; cursor: default; }
|
||||
.flip { transform: rotate(180deg); }
|
||||
@media (max-width: 768px) {
|
||||
.sel-acct { width: 132px; }
|
||||
.sel-st { width: 112px; }
|
||||
.kw-in { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,274 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<el-alert v-if="err" class="mb" type="error" show-icon :closable="false"
|
||||
:title="t('gc.errTitle')" :description="err" />
|
||||
|
||||
<!-- 文件信息 -->
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('gc.file') }}</b>
|
||||
<span class="sub">{{ t('gc.fileSub') }}</span>
|
||||
<span class="flex-1" />
|
||||
<el-button size="small" :loading="loading" @click="load">{{ t('common.refresh') }}</el-button>
|
||||
</div>
|
||||
<div class="set-row"><div class="lb">{{ t('gc.path') }}</div><div class="rt code">{{ meta.path || '—' }}</div></div>
|
||||
<div class="set-row">
|
||||
<div class="lb">{{ t('gc.restartKeys') }}</div>
|
||||
<div class="rt wrap">
|
||||
<span v-for="k in meta.restart_keys || []" :key="k" class="pill warn code">{{ k }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- YAML 全文编辑器 -->
|
||||
<div class="card mt">
|
||||
<div class="card-h">
|
||||
<b>{{ t('gc.editorTitle') }}</b>
|
||||
<span class="sub">{{ t('gc.editorSub') }}</span>
|
||||
<span class="flex-1" />
|
||||
<el-button size="small" @click="backupCfg">{{ t('gc.backup') }}</el-button>
|
||||
<el-button size="small" plain @click="pickRestore">{{ t('gc.restore') }}</el-button>
|
||||
<el-button type="primary" size="small" :loading="saving" @click="saveYaml">{{ t('gc.save') }}</el-button>
|
||||
<span v-if="restartPending.length" class="pill warn restart-pill">{{ t('gc.restartPill') }}</span>
|
||||
</div>
|
||||
<input ref="restoreInput" type="file" accept=".json" class="hidden" @change="onRestoreFile" />
|
||||
|
||||
<textarea v-model="yamlText" class="editor" spellcheck="false"></textarea>
|
||||
|
||||
<div class="hint">{{ t('gc.saveTip') }}</div>
|
||||
<el-alert v-if="savedOk" class="mt" type="success" :closable="false" :title="t('gc.saveOk')" />
|
||||
<el-alert v-if="restartPending.length" class="mt" type="info" show-icon :closable="false"
|
||||
:title="t('gc.restartSaved', { keys: restartPending.join('、') })" />
|
||||
<el-alert v-for="(w, i) in warns" :key="i" class="mt" type="warning" :closable="false" :title="w" />
|
||||
</div>
|
||||
|
||||
<!-- API Key 环境变量 -->
|
||||
<div class="card mt">
|
||||
<div class="card-h">
|
||||
<b>{{ t('gc.envTitle') }}</b>
|
||||
<span class="sub">{{ t('gc.envSub') }}</span>
|
||||
<span class="flex-1" />
|
||||
</div>
|
||||
<div v-if="!envKeys.length" class="hint">{{ t('gc.envEmpty') }}</div>
|
||||
<div v-for="e in envKeys" :key="e.env" class="set-row">
|
||||
<div class="lb flex-1">
|
||||
<span class="code">{{ e.env }}</span>
|
||||
<span class="pill" :class="e.set ? 'ok' : 'err'">{{ e.set ? t('gc.envSet') : t('gc.envMissing') }}</span>
|
||||
<div class="sub">{{ e.provider_name || e.provider }}</div>
|
||||
</div>
|
||||
<div class="rt env-rt">
|
||||
<el-input v-model="e.value" size="small" :type="e.show ? 'text' : 'password'" class="env-in" />
|
||||
<el-button size="small" text @click="e.show = !e.show">{{ t(e.show ? 'gc.envHide' : 'gc.envShow') }}</el-button>
|
||||
<el-button size="small" text :disabled="!e.value" @click="copyEnv(e)">{{ t('gc.envCopy') }}</el-button>
|
||||
<el-button size="small" type="primary" plain :loading="savingEnv" @click="saveEnv(e)">{{ t('gc.save') }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { api } from '../api'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const savingEnv = ref(false)
|
||||
const err = ref('')
|
||||
const warns = ref<string[]>([])
|
||||
const savedOk = ref(false)
|
||||
const restartPending = ref<string[]>([])
|
||||
const meta = ref<any>({})
|
||||
const yamlText = ref('')
|
||||
const restoreInput = ref<HTMLInputElement | null>(null)
|
||||
interface EnvRow { env: string; provider: string; provider_name: string; set: boolean; value: string; show: boolean }
|
||||
const envKeys = ref<EnvRow[]>([])
|
||||
|
||||
function copyText(text: string): boolean {
|
||||
try {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
navigator.clipboard.writeText(text)
|
||||
return true
|
||||
}
|
||||
} catch { /* fall through */ }
|
||||
const ta = document.createElement('textarea')
|
||||
ta.value = text
|
||||
document.body.appendChild(ta)
|
||||
ta.select()
|
||||
try { document.execCommand('copy') } catch { /* ignore */ }
|
||||
document.body.removeChild(ta)
|
||||
return true
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
err.value = ''
|
||||
savedOk.value = false
|
||||
restartPending.value = []
|
||||
try {
|
||||
const body = await api('/config')
|
||||
meta.value = body.meta || {}
|
||||
yamlText.value = body.yaml || ''
|
||||
const envs = (body.env || {}) as Record<string, any>
|
||||
envKeys.value = Object.keys(envs).map((env) => ({
|
||||
env,
|
||||
provider: envs[env].provider || '—',
|
||||
provider_name: envs[env].provider_name || '',
|
||||
set: !!envs[env].set,
|
||||
value: envs[env].value || '',
|
||||
show: false,
|
||||
}))
|
||||
warns.value = (body.meta?.warnings || []).concat(body.meta?.route_warnings || [])
|
||||
} catch (e: any) {
|
||||
err.value = (e?.body?.detail || e?.message || String(e))
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function saveYaml() {
|
||||
err.value = ''
|
||||
savedOk.value = false
|
||||
saving.value = true
|
||||
try {
|
||||
const r = await api('/config', { method: 'PUT', body: JSON.stringify({ yaml: yamlText.value }) })
|
||||
restartPending.value = r.restart_required || []
|
||||
warns.value = r.warnings || []
|
||||
savedOk.value = true
|
||||
ElMessage.success(t('gc.saveOk'))
|
||||
} catch (e: any) {
|
||||
const d = e?.body?.detail
|
||||
err.value = typeof d === 'string' ? d : (d ? JSON.stringify(d) : (e?.message || String(e)))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function backupCfg() {
|
||||
const envs: Record<string, string> = {}
|
||||
for (const e of envKeys.value) envs[e.env] = e.value
|
||||
const data = { kind: 'api-gateway-backup', version: 1, config: yamlText.value, envs }
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
|
||||
const a = document.createElement('a')
|
||||
a.href = URL.createObjectURL(blob)
|
||||
a.download = 'gateway-backup.json'
|
||||
a.click()
|
||||
URL.revokeObjectURL(a.href)
|
||||
ElMessage.success(t('gc.backupOk'))
|
||||
}
|
||||
function pickRestore() { restoreInput.value?.click() }
|
||||
function onRestoreFile(ev: Event) {
|
||||
const f = (ev.target as HTMLInputElement).files?.[0]
|
||||
if (!f) return
|
||||
const r = new FileReader()
|
||||
r.onload = () => {
|
||||
try {
|
||||
const parsed = JSON.parse(String(r.result || '{}'))
|
||||
const cfg = typeof parsed?.config === 'string' ? parsed.config : ''
|
||||
const rawEnvs = parsed && parsed.envs && typeof parsed.envs === 'object' ? parsed.envs : {}
|
||||
const envs: Record<string, string> = {}
|
||||
for (const [k, v] of Object.entries(rawEnvs as any)) envs[k] = String(v)
|
||||
if (!cfg.trim()) throw new Error('no config')
|
||||
ElMessageBox.confirm(
|
||||
t('gc.restoreConfirm', { envs: Object.keys(envs).length }),
|
||||
t('gc.restore'),
|
||||
{ type: 'warning', confirmButtonText: t('gc.restoreGo'), cancelButtonText: t('gc.cancel') },
|
||||
).then(async () => { await applyRestore(cfg, envs) }).catch(() => { /* 取消 */ })
|
||||
} catch (e: any) {
|
||||
err.value = t('gc.restoreInvalid') + ': ' + String(e && e.message || e || '')
|
||||
}
|
||||
}
|
||||
r.readAsText(f)
|
||||
;(ev.target as HTMLInputElement).value = ''
|
||||
}
|
||||
async function applyRestore(cfg: string, envs: Record<string, string>) {
|
||||
err.value = ''
|
||||
saving.value = true
|
||||
try {
|
||||
const j = await api('/config', { method: 'PUT', body: JSON.stringify({ yaml: cfg }) })
|
||||
if (Object.keys(envs).length) await applyEnv(envs)
|
||||
restartPending.value = j.restart_required || []
|
||||
savedOk.value = true
|
||||
ElMessage.success(t('gc.restoreOk'))
|
||||
await load()
|
||||
} catch (e: any) {
|
||||
const d = e?.body?.detail
|
||||
err.value = typeof d === 'string' ? d : (d ? JSON.stringify(d) : (e?.message || String(e)))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function applyEnv(map: Record<string, string>) {
|
||||
savingEnv.value = true
|
||||
try {
|
||||
const j = await api('/config/env', { method: 'POST', body: JSON.stringify({ envs: map }) })
|
||||
const envs = (j.envs || {}) as Record<string, any>
|
||||
envKeys.value = Object.keys(envs).map((env) => ({
|
||||
env,
|
||||
provider: envs[env].provider || '—',
|
||||
provider_name: envs[env].provider_name || '',
|
||||
set: !!envs[env].set,
|
||||
value: envs[env].value || '',
|
||||
show: false,
|
||||
}))
|
||||
} catch (e: any) {
|
||||
const d = e?.body?.detail
|
||||
throw new Error(typeof d === 'string' ? d : (d ? JSON.stringify(d) : (e?.message || String(e))))
|
||||
} finally {
|
||||
savingEnv.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function copyEnv(e: EnvRow) {
|
||||
if (!e.value) return
|
||||
copyText(e.value)
|
||||
ElMessage.success(t('gc.envCopied'))
|
||||
}
|
||||
async function saveEnv(e: EnvRow) {
|
||||
err.value = ''
|
||||
try {
|
||||
await applyEnv({ [e.env]: e.value })
|
||||
ElMessage.success(t('gc.envSaved'))
|
||||
} catch (e2: any) {
|
||||
err.value = e2?.message || String(e2)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mt { margin-top: var(--gap); }
|
||||
.wrap { flex-wrap: wrap; justify-content: flex-end; gap: 6px; }
|
||||
.hidden { display: none; }
|
||||
.hint { font-size: 11.5px; color: var(--muted-2); margin: 6px 0 2px; }
|
||||
.restart-pill { margin-left: 6px; }
|
||||
.editor {
|
||||
width: 100%;
|
||||
min-height: 58vh;
|
||||
box-sizing: border-box;
|
||||
resize: vertical;
|
||||
background: var(--chip);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
white-space: pre;
|
||||
}
|
||||
.editor:focus { outline: none; border-color: var(--primary); }
|
||||
.env-rt { display: flex; align-items: center; gap: 6px; min-width: 0; }
|
||||
.env-in { flex: 0 0 260px; }
|
||||
.op-row { display: flex; gap: 8px; margin-top: 14px; }
|
||||
@media (max-width: 720px) {
|
||||
.env-rt { flex-wrap: wrap; }
|
||||
.env-in { flex: 1 1 100%; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,402 @@
|
||||
<template>
|
||||
<div class="page-fill">
|
||||
<div class="img-layout">
|
||||
<!-- 左:参数(固定 320px;窄屏自动落到上方单列) -->
|
||||
<div class="card param-card">
|
||||
<div class="field mb-field">
|
||||
<label>{{ t('images.model') }}</label>
|
||||
<el-select v-model="model" filterable class="fill">
|
||||
<el-option v-for="m in models" :key="m.id" :value="m.id" :label="`${m.id} · ${m.provider_name}`" />
|
||||
</el-select>
|
||||
</div>
|
||||
|
||||
<div class="form-row mb-field">
|
||||
<div class="field">
|
||||
<label>{{ t('images.size') }}</label>
|
||||
<el-select v-model="size" class="fill">
|
||||
<el-option v-for="s in sizes" :key="s" :value="s" :label="s" />
|
||||
</el-select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t('images.ratio') }}</label>
|
||||
<el-select v-model="ratio" class="fill">
|
||||
<el-option v-for="r in ratios" :key="r" :value="r" :label="r" />
|
||||
</el-select>
|
||||
</div>
|
||||
<div class="field field-narrow">
|
||||
<label>{{ t('images.count') }}</label>
|
||||
<!-- 第十三轮:上游接口一次只出 1 张(n>1 会被 400),这里改成"逐张生成"。
|
||||
第十八轮:controls-position="right" —— 两侧加减按钮各占 ~32px,92px 的窄列里
|
||||
内部 input 只剩 8px(数字看不见);挪到右侧后数字区约 50px。 -->
|
||||
<el-input-number v-model="count" :min="1" :max="4" controls-position="right" class="fill" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field mb-field">
|
||||
<label>{{ t('images.promptRow') }}</label>
|
||||
<el-input
|
||||
v-model="prompt"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
resize="none"
|
||||
:placeholder="t('images.placeholder')"
|
||||
:disabled="loading"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="field mb-field">
|
||||
<label>{{ t('images.refsLabel') }}</label>
|
||||
<!-- 第十三轮:图生图 / 多图合成 —— 支持直接上传(浏览器内压成 data URI),也支持粘 URL -->
|
||||
<div class="ref-btns">
|
||||
<el-button size="small" :disabled="loading" @click="pickRefs">
|
||||
<Icon name="up" :size="14" />{{ t('images.refsUpload') }}
|
||||
</el-button>
|
||||
<el-button size="small" @click="showRefUrl = !showRefUrl">
|
||||
<Icon name="link" :size="14" />{{ t('images.refsUrlBtn') }}
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="hint ref-hint">{{ t('images.refsHint') }}</div>
|
||||
<input ref="fileEl" type="file" accept="image/*" multiple class="hide-file" @change="onRefFiles" />
|
||||
<div v-if="refs.length" class="ref-thumbs">
|
||||
<div v-for="(r, i) in refs" :key="i" class="ref-thumb" :title="`${r.name} · ${formatBytes(dataUriBytes(r.uri))}`">
|
||||
<img :src="r.thumb || r.uri" alt="" />
|
||||
<span class="rm" @click="refs.splice(i, 1)"><Icon name="x" :size="11" /></span>
|
||||
<span class="rn">{{ r.name }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<el-input
|
||||
v-if="showRefUrl"
|
||||
v-model="refUrls"
|
||||
type="textarea"
|
||||
:rows="2"
|
||||
resize="none"
|
||||
:placeholder="t('images.refsPH')"
|
||||
:disabled="loading"
|
||||
class="ref-urls"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="param-foot">
|
||||
<el-alert v-if="err" :title="err" type="error" show-icon :closable="false" class="err-alert" />
|
||||
<el-button type="primary" class="go-btn" :loading="loading" :disabled="!prompt.trim()" @click="generate">
|
||||
<Icon name="img" :size="15" />{{ t('images.generate') }}
|
||||
</el-button>
|
||||
<div class="go-tip hint">
|
||||
<span v-if="loading && count > 1">{{ t('images.genProgress', { i: progress, n: count }) }}</span>
|
||||
<span v-else-if="providerName">{{ t('images.servedBy', { provider: providerName }) }}</span>
|
||||
<span v-else>{{ t('images.countTip') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右:结果(卡片自己撑满,滚动只发生在缩略图区) -->
|
||||
<div class="card result-card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('images.historyTitle') }}</b>
|
||||
<span class="sub">{{ t('images.historySub', { n: images.length }) }}</span>
|
||||
<div class="pager">
|
||||
<template v-if="images.length">
|
||||
<span class="pg" :class="{ off: page <= 1 }" @click="goPage(page - 1)"><Icon name="chev" :size="13" class="flip" /></span>
|
||||
<span v-for="p in pageCount" :key="p" class="pg" :class="{ on: p === page }" @click="goPage(p)">{{ p }}</span>
|
||||
<span class="pg" :class="{ off: page >= pageCount }" @click="goPage(page + 1)"><Icon name="chev" :size="13" /></span>
|
||||
</template>
|
||||
<el-button size="small" class="nowrap" :disabled="!images.length" @click="clearAll">{{ t('images.clear') }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 逐张生成中:先占位,出图后自动落到下面网格 -->
|
||||
<div v-if="loading" class="thumbs">
|
||||
<div v-for="i in count" :key="i" class="th">
|
||||
<div class="ph shimmer" />
|
||||
<div class="meta"><b> </b><span> </span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="images.length" class="thumbs">
|
||||
<div v-for="row in pageImages" :key="row.img.id || row.i" class="th">
|
||||
<div class="ph">
|
||||
<el-image
|
||||
:src="row.img.src"
|
||||
fit="cover"
|
||||
class="thumb"
|
||||
:preview-src-list="images.map((x: any) => x.src)"
|
||||
:initial-index="row.i"
|
||||
preview-teleported
|
||||
>
|
||||
<template #error><span class="hint">{{ t('images.imgLoadErr') }}</span></template>
|
||||
</el-image>
|
||||
</div>
|
||||
<!-- 第十七轮: 下载。产物在跨域 CDN 上(不带 CORS 头),直链下载不生效,
|
||||
走 lib/download.ts 里的后端代拉;按钮放在图下方(不做缩略图上的悬浮圆形图标,
|
||||
手机端两列时也不会挤变形)。 -->
|
||||
<div class="meta">
|
||||
<b :title="row.img.prompt">{{ row.img.prompt || t('images.promptRow') }}</b>
|
||||
<span>
|
||||
{{ row.img.served }}<template v-if="row.img.ms"> · {{ row.img.ms }}</template>
|
||||
<template v-if="row.img.refs"> · {{ t('images.refsUsed', { n: row.img.refs }) }}</template>
|
||||
</span>
|
||||
<el-button size="small" class="th-btn" :loading="dlId === (row.img.id || row.i)" @click="dlImg(row.img, row.i)">
|
||||
<Icon name="dl" :size="14" />{{ t('images.dl') }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-empty v-else :description="t('images.empty')" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import Icon from '../components/Icon.vue'
|
||||
import { api } from '../api'
|
||||
import { imageSrc } from '../lib/media'
|
||||
import { downloadMedia, nameFromPrompt, stamp } from '../lib/download'
|
||||
import { pullHistory, pushHistory, clearHistory, ensureIds } from '../lib/history'
|
||||
import { pickImage, PRESETS, dataUriBytes, formatBytes, assertBodyBudget } from '../lib/upload'
|
||||
|
||||
const router = useRouter()
|
||||
const { t } = useI18n()
|
||||
const models = ref<any[]>([])
|
||||
const model = ref('')
|
||||
const sizes = ['1K', '2K', '3K', '4K']
|
||||
const ratios = ['1:1', '3:4', '4:3', '16:9', '9:16', '2:3', '3:2', '21:9']
|
||||
const size = ref('1K')
|
||||
const ratio = ref('1:1')
|
||||
const count = ref(1) // 逐张生成:每张一次请求(上游 n 必须为 1)
|
||||
const prompt = ref('')
|
||||
// 参考图(图生图 / 多图合成):上传的走 data URI,URL 的直接透传,两类可混用
|
||||
const refs = ref<any[]>([])
|
||||
const refUrls = ref('')
|
||||
const showRefUrl = ref(false)
|
||||
const fileEl = ref<HTMLInputElement | null>(null)
|
||||
const MAX_REFS = 5
|
||||
const loading = ref(false)
|
||||
const progress = ref(0)
|
||||
const err = ref('')
|
||||
const images = ref<any[]>([])
|
||||
const SKEY = 'gw_image_history' // 只当本地缓存,真正的历史在服务端
|
||||
function cacheLocal() {
|
||||
try { localStorage.setItem(SKEY, JSON.stringify({ prompt: prompt.value, list: images.value })) } catch { /* 缓存写不进无所谓 */ }
|
||||
}
|
||||
async function save() {
|
||||
cacheLocal()
|
||||
// 写服务端失败必须吭声 —— 以前是 catch 掉静默丢历史,正是「图像还在、视频没了」的根因
|
||||
if (!(await pushHistory('images', images.value))) ElMessage.warning(t('history.saveFail'))
|
||||
}
|
||||
async function load() {
|
||||
let local: any = null
|
||||
try { local = JSON.parse(localStorage.getItem(SKEY) || 'null') } catch { local = null }
|
||||
const remote = await pullHistory('images')
|
||||
if (remote === null) {
|
||||
if (local && Array.isArray(local.list)) images.value = ensureIds(local.list, 'img')
|
||||
ElMessage.warning(t('history.offline'))
|
||||
return
|
||||
}
|
||||
if (remote.length) {
|
||||
images.value = remote
|
||||
} else if (local && Array.isArray(local.list) && local.list.length) {
|
||||
images.value = ensureIds(local.list, 'img') // 首次:把浏览器里的旧历史搬上服务端
|
||||
await pushHistory('images', images.value)
|
||||
} else {
|
||||
images.value = []
|
||||
}
|
||||
if (local && typeof local.prompt === 'string' && local.prompt && !prompt.value) prompt.value = local.prompt
|
||||
cacheLocal()
|
||||
}
|
||||
async function clearAll() {
|
||||
if (!images.value.length) return
|
||||
// 老板要求(连同视频页的「清除已完成」):真删之前必须二次确认 —— 服务端删了不可恢复。
|
||||
try {
|
||||
await ElMessageBox.confirm(t('images.confirmClear', { n: images.value.length }), t('common.confirm'),
|
||||
{ type: 'warning', confirmButtonText: t('common.delete'), cancelButtonText: t('common.cancel') })
|
||||
} catch { return }
|
||||
images.value = []
|
||||
cacheLocal()
|
||||
if (!(await clearHistory('images'))) ElMessage.warning(t('history.saveFail'))
|
||||
}
|
||||
|
||||
async function loadModels() {
|
||||
try {
|
||||
const j = await api('/v1/models')
|
||||
const all = (j.data || []).filter((x: any) => x.type === 'image')
|
||||
models.value = all
|
||||
if (all.length && !model.value) model.value = all[0].id
|
||||
} catch (e: any) {
|
||||
if (e && e.status === 401) { router.push('/login'); return }
|
||||
ElMessage.error(t('images.loadErr') + ':' + ((e && e.message) || e))
|
||||
}
|
||||
}
|
||||
|
||||
function pickRefs() {
|
||||
fileEl.value?.click()
|
||||
}
|
||||
async function onRefFiles(ev: Event) {
|
||||
const input = ev.target as HTMLInputElement
|
||||
for (const f of Array.from(input.files || [])) {
|
||||
if (refs.value.length >= MAX_REFS) { ElMessage.warning(t('images.refsMax', { n: MAX_REFS })); break }
|
||||
try {
|
||||
refs.value.push(await pickImage(f, PRESETS.ref))
|
||||
} catch (e: any) {
|
||||
ElMessage.error(t('images.refPickErr', { msg: (e && e.message) || e }))
|
||||
}
|
||||
}
|
||||
if (input) input.value = ''
|
||||
}
|
||||
/** 上传的 data URI + 手填的 URL,按顺序合成 extra_body.image 的入参 */
|
||||
function refList(): string[] {
|
||||
const urls = refUrls.value.split(/\r?\n/).map((x) => x.trim()).filter(Boolean)
|
||||
return [...refs.value.map((r) => r.uri), ...urls]
|
||||
}
|
||||
|
||||
const providerName = ref('')
|
||||
async function generate() {
|
||||
if (!prompt.value.trim() || loading.value) return
|
||||
const list = refList()
|
||||
try {
|
||||
// 素材 + 正文的整包体积要落在网关/Nginx 的请求体上限内(否则 413)
|
||||
assertBodyBudget([...list, prompt.value], 1200)
|
||||
} catch (e: any) {
|
||||
err.value = (e && e.message) || String(e)
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
err.value = ''
|
||||
const total = Math.max(1, Math.min(4, count.value))
|
||||
let done = 0
|
||||
try {
|
||||
for (let i = 1; i <= total; i++) {
|
||||
progress.value = i
|
||||
const t0 = performance.now()
|
||||
// 上游图像接口的 n 必须为 1:多张就在这里逐张调用,每张出来就上屏(进度可见)
|
||||
const body: any = { model: model.value, prompt: prompt.value, size: size.value, ratio: ratio.value, n: 1 }
|
||||
if (list.length) body.image = list // 图生图 / 多图合成(网关转成上游的 extra_body.image)
|
||||
const j = await api('/v1/images/generations', { method: 'POST', body: JSON.stringify(body) })
|
||||
const ms = (performance.now() - t0) | 0
|
||||
providerName.value = j.provider_name || j.provider || ''
|
||||
const items = (j.data || []).map((d: any, k: number) => ({
|
||||
id: `img-${Date.now()}-${i}-${k}`,
|
||||
ts: Date.now(),
|
||||
src: imageSrc(d),
|
||||
served: j.served_model || model.value,
|
||||
ms: `${ms}ms`,
|
||||
prompt: prompt.value.trim(),
|
||||
refs: list.length || undefined, // 记录本次用了多少张参考图
|
||||
})).filter((x: any) => x.src)
|
||||
if (!items.length) throw new Error(t('images.emptyResp'))
|
||||
done += items.length
|
||||
images.value = [...items, ...images.value]
|
||||
await save()
|
||||
}
|
||||
} catch (e: any) {
|
||||
// 逐张生成时中途失败:已生成的要留住,并说清是第几张断的
|
||||
const detail = (e?.body?.detail) || e?.message || String(e)
|
||||
err.value = done
|
||||
? t('images.partialFail', { done, i: Math.min(progress.value, total), msg: detail })
|
||||
: detail
|
||||
} finally {
|
||||
loading.value = false
|
||||
progress.value = 0
|
||||
}
|
||||
}
|
||||
|
||||
// ── 结果区翻页(纯展示:不裁剪数据,只决定当前渲染哪一页)──
|
||||
const PAGE_SIZE = 6
|
||||
const page = ref(1)
|
||||
const pageCount = computed(() => Math.max(1, Math.ceil(images.value.length / PAGE_SIZE)))
|
||||
const pageImages = computed(() => images.value
|
||||
.slice((page.value - 1) * PAGE_SIZE, page.value * PAGE_SIZE)
|
||||
.map((img, k) => ({ img, i: (page.value - 1) * PAGE_SIZE + k })))
|
||||
function goPage(p: number) {
|
||||
if (p < 1 || p > pageCount.value) return
|
||||
page.value = p
|
||||
}
|
||||
// 新图永远插在最前面(逐张生成也是),历史整体换掉时回到第一页
|
||||
watch(images, () => { page.value = 1 })
|
||||
|
||||
onMounted(() => { load(); loadModels() })
|
||||
|
||||
// ── 第十七轮: 单张下载 ──
|
||||
// 文件名用「提示词前缀 + 时间戳」,后端会按 Content-Type 补 .png/.jpg 并以
|
||||
// Content-Disposition 回传(前端以服务端给的名字落盘,见 lib/download.ts)。
|
||||
const dlId = ref<any>(null)
|
||||
async function dlImg(img: any, i: number) {
|
||||
if (!img?.src) { ElMessage.error(t('images.dlNoSrc')); return }
|
||||
dlId.value = img.id || i
|
||||
try {
|
||||
await downloadMedia(img.src, `${nameFromPrompt(img.prompt, 'image')}-${stamp()}`)
|
||||
ElMessage.success(t('images.dlOk'))
|
||||
} catch (e: any) {
|
||||
ElMessage.error(t('images.dlFail', { msg: e?.message || String(e) }))
|
||||
} finally {
|
||||
dlId.value = null
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 撑满高度的两栏:左参数卡、右结果卡;滚动只发生在各自内部 */
|
||||
.param-card { display: flex; flex-direction: column; overflow-y: auto; }
|
||||
.result-card { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
.result-card .thumbs { flex: 1; min-height: 0; overflow-y: auto; align-content: start; }
|
||||
|
||||
.mb-field { margin-bottom: 10px; }
|
||||
/* .field 天生是 flex:1(给 .form-row 横向用的)—— 在竖排卡片里必须收回,
|
||||
否则每个字段会纵向撑开,控件之间留下大片空白 */
|
||||
.param-card > .field { flex: none; }
|
||||
.fill { width: 100%; }
|
||||
/* 第十八轮: 92px 太窄(加减按钮吃掉大半),给到 108px 还要保证数字区不被压缩 */
|
||||
.field-narrow { flex: 0 0 108px; }
|
||||
.field-narrow :deep(.el-input__inner) { min-width: 30px; }
|
||||
.ref-btns { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
/* 参考图「上传 / URL」两个按钮文案不折行(窄列里被挤成两行是旧版的老毛病) */
|
||||
.ref-btns :deep(.el-button) { white-space: nowrap; }
|
||||
.ref-hint { margin-top: 6px; line-height: 1.5; }
|
||||
.ref-urls { margin-top: 6px; }
|
||||
.hide-file { display: none; }
|
||||
.ref-thumbs { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
|
||||
.ref-thumb { position: relative; width: 68px; }
|
||||
.ref-thumb img { width: 68px; height: 68px; object-fit: cover; border-radius: 6px; border: 1px solid var(--line); display: block; }
|
||||
.ref-thumb .rn { display: block; font-size: 11px; color: var(--muted-2); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.ref-thumb .rm {
|
||||
position: absolute; top: -6px; right: -6px; width: 18px; height: 18px;
|
||||
display: grid; place-items: center; border-radius: 50%; cursor: pointer;
|
||||
background: var(--surface); border: 1px solid var(--line); color: var(--err);
|
||||
}
|
||||
|
||||
.param-foot { margin-top: auto; padding-top: 4px; }
|
||||
.err-alert { margin-bottom: 8px; }
|
||||
.go-btn { width: 100%; }
|
||||
.go-tip { margin-top: 8px; text-align: center; line-height: 1.5; }
|
||||
|
||||
.pager { gap: 4px; }
|
||||
.pg { cursor: pointer; }
|
||||
.pg.off { opacity: .45; cursor: default; }
|
||||
.flip { transform: rotate(180deg); }
|
||||
.pager :deep(.el-button) { margin-left: 6px; }
|
||||
|
||||
/* 缩略卡:图在上、标题与下载按钮在下(不做缩略图上的悬浮圆形图标) */
|
||||
.th .ph { position: relative; }
|
||||
.thumb { width: 100%; height: 100%; display: block; }
|
||||
.th .meta b { color: var(--text); }
|
||||
.th-btn { width: 100%; margin-top: 8px; }
|
||||
.shimmer { height: 96px; background: linear-gradient(90deg, var(--chip) 25%, var(--surface-2) 37%, var(--chip) 63%); background-size: 400% 100%; animation: ph 1.4s infinite; }
|
||||
@keyframes ph { 0% { background-position: 100% 0 } 100% { background-position: -100% 0 } }
|
||||
|
||||
/* 窄屏:单列后整页滚动,两个卡片都恢复自然高度 */
|
||||
@media (max-width: 768px) {
|
||||
/* 窄屏单列后不再需要「撑满一屏」,改由 .gw-body 整页滚动 */
|
||||
.page-fill { height: auto; }
|
||||
.img-layout { height: auto; }
|
||||
.param-card { overflow: visible; }
|
||||
.result-card { flex: none; }
|
||||
.result-card .thumbs { overflow: visible; }
|
||||
.card-h { flex-wrap: wrap; }
|
||||
.th-btn { margin-top: 7px; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,211 @@
|
||||
<template>
|
||||
<!-- 登录页(第四次重做,方案一「极简白卡」,老板 2026-09-13 拍板):
|
||||
浅底 + 单列居中白卡,靠留白、柔光和极淡的几何纹理撑气质。
|
||||
与上一版的区别:去掉「顶部通栏背景图 + 左品牌区 + 右表单」的分栏卡片结构
|
||||
(老板认为不好看),也去掉自绘 SVG 背景图 —— 现在整页装饰全是 CSS 图层(见下方样式)。
|
||||
内容仍只有:logo + 品牌标题 + 用户名/密码 + 登录按钮。 -->
|
||||
<div class="login-wrap">
|
||||
<!-- 装饰层(从下到上:底色 → 柔光 → 卡片背后光雾 → 点阵肌理 → 右下同心环),
|
||||
全部 pointer-events:none,不参与交互、不引任何外链资源 -->
|
||||
<div class="wash" aria-hidden="true" />
|
||||
<div class="aurora" aria-hidden="true" />
|
||||
<div class="dots" aria-hidden="true" />
|
||||
<div class="rings" aria-hidden="true"><i /><i /><i /></div>
|
||||
|
||||
<!-- 中英切换:页面右上角白玻璃胶囊(桌面 / 窄屏同一套配色,靠 surface token 自动适配三主题) -->
|
||||
<el-dropdown class="lang-top" @command="onLang">
|
||||
<span class="lang">{{ locale === 'en' ? 'EN' : '中' }}</span>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item command="zh" :disabled="locale === 'zh'">中文</el-dropdown-item>
|
||||
<el-dropdown-item command="en" :disabled="locale === 'en'">English</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
|
||||
<main class="card">
|
||||
<span class="logo"><Icon name="bolt" :size="22" /></span>
|
||||
<h1>{{ t('login.title') }}</h1>
|
||||
|
||||
<el-alert v-if="err" :title="err" type="error" class="login-err" show-icon :closable="false" />
|
||||
|
||||
<form @submit.prevent="doLogin">
|
||||
<div class="field">
|
||||
<label>{{ t('login.userPlaceholder') }}</label>
|
||||
<el-input v-model="username" size="large" autocomplete="username" @keyup.enter="doLogin" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t('login.passPlaceholder') }}</label>
|
||||
<el-input
|
||||
v-model="password"
|
||||
type="password"
|
||||
size="large"
|
||||
show-password
|
||||
autocomplete="current-password"
|
||||
@keyup.enter="doLogin"
|
||||
/>
|
||||
</div>
|
||||
<el-button type="primary" size="large" class="submit" :loading="loading" native-type="submit">
|
||||
{{ t('login.btn') }}
|
||||
</el-button>
|
||||
</form>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useSessionStore } from '../store/session'
|
||||
import { setLocale } from '../i18n'
|
||||
import Icon from '../components/Icon.vue'
|
||||
|
||||
const router = useRouter()
|
||||
const store = useSessionStore()
|
||||
const { t, locale } = useI18n()
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const loading = ref(false)
|
||||
const err = ref('')
|
||||
|
||||
function onLang(l: string) { setLocale(l as any) }
|
||||
|
||||
async function doLogin() {
|
||||
err.value = ''
|
||||
if (!username.value.trim() || !password.value) { err.value = t('login.errEmpty'); return }
|
||||
loading.value = true
|
||||
try {
|
||||
await store.login(username.value.trim(), password.value)
|
||||
ElMessage.success(t('login.success'))
|
||||
router.push('/dashboard')
|
||||
} catch (e: any) {
|
||||
err.value = authErr(e)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function authErr(e: any): string {
|
||||
if (e && e.status === 401) return t('login.err401')
|
||||
if (e && e.status === 429) return t('login.err429')
|
||||
// 403:服务端带得出明确原因(第二十四轮的「账号已被停用,请联系管理员」就走这条),
|
||||
// 优先显示原文 —— 比页面这句笼统的「账号被禁用或角色异常」有用得多;拿不到才退回文案。
|
||||
if (e && e.status === 403) return String(e?.message || '') || t('login.err403')
|
||||
if (e && e.message) return String(e.message)
|
||||
return t('login.errConn')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 颜色口径:能用 token 的地方一律用 token(上面这套装饰层因此能在 A/B/C 三主题下自动换色);
|
||||
需要"半透明的主题色"时用 color-mix(in srgb, var(--x) N%, transparent),不再写死
|
||||
rgba(79,99,245,…) 这种只对单一主题成立的常量。color-mix 在 Chrome 111+ / Safari 16.2+
|
||||
可用,不支持时该层退化为透明(少一层柔光,不影响可读性与布局)。 */
|
||||
.login-wrap {
|
||||
min-height: 100vh; min-height: 100dvh;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
padding: 40px 24px; background: var(--bg); position: relative;
|
||||
}
|
||||
|
||||
/* ① 柔光:左上主色、右下青调,让纯色底有体积感(不抢卡片,所以透明度很低) */
|
||||
.wash {
|
||||
position: fixed; inset: 0; pointer-events: none; background:
|
||||
radial-gradient(58% 48% at 8% -6%, color-mix(in srgb, var(--primary) 13%, transparent), transparent 62%),
|
||||
radial-gradient(46% 42% at 100% 108%, color-mix(in srgb, var(--chart-b) 12%, transparent), transparent 64%);
|
||||
}
|
||||
/* ② 卡片背后的一团主色光雾:白卡浮在光雾上才有厚度(挪掉不丑,只是页面会显平) */
|
||||
.aurora {
|
||||
position: fixed; left: 50%; top: 47%; width: 920px; height: 560px;
|
||||
transform: translate(-50%, -50%); pointer-events: none; filter: blur(14px);
|
||||
background: radial-gradient(50% 50% at 50% 50%, color-mix(in srgb, var(--primary) 17%, transparent), transparent 72%);
|
||||
}
|
||||
/* ③ 点阵肌理:只在左上角渐显(mask 化开),几乎察觉不到但页面不发死 */
|
||||
.dots {
|
||||
position: fixed; inset: 0; pointer-events: none;
|
||||
background-image: radial-gradient(color-mix(in srgb, var(--text) 16%, transparent) 1px, transparent 1px);
|
||||
background-size: 24px 24px;
|
||||
-webkit-mask-image: radial-gradient(52% 46% at 14% 8%, #000, transparent 72%);
|
||||
mask-image: radial-gradient(52% 46% at 14% 8%, #000, transparent 72%);
|
||||
}
|
||||
/* ④ 右下同心环:三个同心细线圆,越外越淡,给卡片一个视觉落点 */
|
||||
.rings i { position: fixed; border-radius: 50%; pointer-events: none; border: 1px solid color-mix(in srgb, var(--primary) 14%, transparent); }
|
||||
.rings i:nth-child(1) { width: 340px; height: 340px; right: -110px; bottom: -120px; }
|
||||
.rings i:nth-child(2) { width: 540px; height: 540px; right: -210px; bottom: -220px; border-color: color-mix(in srgb, var(--primary) 10%, transparent); }
|
||||
.rings i:nth-child(3) { width: 760px; height: 760px; right: -320px; bottom: -330px; border-color: color-mix(in srgb, var(--chart-b) 10%, transparent); }
|
||||
|
||||
/* 右上角中英切换:白玻璃胶囊(窄屏同款,颜色全走 token) */
|
||||
.lang-top { display: block; position: fixed; top: 24px; right: 26px; z-index: 5; }
|
||||
.lang {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
min-width: 46px; padding: 6px 14px; border-radius: 999px; cursor: pointer; outline: none;
|
||||
background: color-mix(in srgb, var(--surface) 74%, transparent);
|
||||
border: 1px solid var(--line); color: var(--muted); font-size: 12.5px; line-height: 1.4;
|
||||
box-shadow: 0 2px 8px color-mix(in srgb, var(--text) 8%, transparent);
|
||||
backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
/* 卡片:两层阴影(token 的基础层 + 一层更深的落地层),压在柔光/光雾上要能跳出来 */
|
||||
.card {
|
||||
position: relative; z-index: 2; width: 440px; max-width: 100%;
|
||||
background: var(--surface); border: 1px solid var(--line); border-radius: 22px;
|
||||
padding: 42px 40px 40px;
|
||||
box-shadow: var(--shadow), 0 24px 50px -26px rgba(0, 0, 0, .28);
|
||||
}
|
||||
.logo {
|
||||
width: 46px; height: 46px; border-radius: 14px; display: grid; place-items: center;
|
||||
color: var(--primary-ink);
|
||||
/* 主色自身上下渐变:A/C 主题换了主色,这块自动跟着换(不用为每套主题写死色值) */
|
||||
background: linear-gradient(142deg,
|
||||
color-mix(in srgb, var(--primary) 84%, #fff), var(--primary) 55%,
|
||||
color-mix(in srgb, var(--primary) 82%, #000));
|
||||
box-shadow: 0 10px 22px -8px color-mix(in srgb, var(--primary) 62%, transparent);
|
||||
}
|
||||
.card h1 { margin: 20px 0 28px; font-size: 21px; font-weight: 650; letter-spacing: .1px; color: var(--text); }
|
||||
.login-err { margin-bottom: 16px; border-radius: 12px; }
|
||||
.field { margin-bottom: 16px; }
|
||||
.field label { display: block; font-size: 12.5px; color: var(--muted); margin-bottom: 8px; }
|
||||
|
||||
/* 输入框:Element Plus 的 wrapper 本身就是「1px 内阴影当边框」,所以覆盖它而不是加 border,
|
||||
否则会出现双边框。填充式(chip 底)比描边式更松弛,也更好压住圆角。 */
|
||||
.field :deep(.el-input__wrapper) {
|
||||
height: 48px; padding: 0 15px; border-radius: 12px; background: var(--chip);
|
||||
box-shadow: 0 0 0 1px var(--line) inset;
|
||||
transition: background .16s, box-shadow .16s;
|
||||
}
|
||||
.field :deep(.el-input__wrapper:hover) {
|
||||
box-shadow: 0 0 0 1px color-mix(in srgb, var(--primary) 34%, var(--line)) inset;
|
||||
}
|
||||
/* 聚焦态必须带 !important:全局 style.css 里有一条
|
||||
`.el-input__wrapper.is-focus { box-shadow: 0 0 0 1px var(--primary) inset !important }`
|
||||
(给全站输入框统一"细边"聚焦样式),不用 !important 的话这里的「1px 主色 + 3.5px 柔光」
|
||||
双环会被它整条盖掉,只剩 1px 细边。作用域仍只限登录页,不影响其它页面。 */
|
||||
.field :deep(.el-input__wrapper.is-focus) {
|
||||
background: var(--surface);
|
||||
box-shadow: 0 0 0 1px var(--primary) inset, 0 0 0 3.5px var(--primary-soft) !important;
|
||||
}
|
||||
.field :deep(.el-input__inner) { font-size: 14.5px; color: var(--text); }
|
||||
.field :deep(.el-input__inner::placeholder) { color: var(--muted-2); }
|
||||
|
||||
.submit {
|
||||
width: 100%; height: 48px; margin-top: 12px; border-radius: 12px;
|
||||
font-size: 15px; font-weight: 600;
|
||||
box-shadow: 0 10px 22px -10px color-mix(in srgb, var(--primary) 75%, transparent);
|
||||
}
|
||||
|
||||
/* 手机端:卡片化整为零 —— 去掉卡片的底/边/影,表单直接在页面柔光底上居中,
|
||||
下方同心环缩一档(窄屏里 760px 的环几乎全在屏幕外,留着只是白算)
|
||||
(旧版那套「顶部色块 + 上浮卡片 + 接缝」的结构整段删掉了) */
|
||||
@media (max-width: 600px) {
|
||||
.login-wrap { align-items: stretch; padding: 0; }
|
||||
.card {
|
||||
width: 100%; border: 0; border-radius: 0; box-shadow: none; background: transparent;
|
||||
padding: 104px 22px 40px; display: flex; flex-direction: column; justify-content: center;
|
||||
}
|
||||
.rings i:nth-child(1) { width: 260px; height: 260px; right: -130px; bottom: -90px; }
|
||||
.rings i:nth-child(2) { width: 400px; height: 400px; right: -200px; bottom: -160px; }
|
||||
.rings i:nth-child(3) { display: none; }
|
||||
.lang-top { top: 18px; right: 18px; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,353 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 筛选行:类型胶囊 + 原有筛选控件 + 刷新/导出 -->
|
||||
<div class="filters">
|
||||
<!-- 第十九轮:类型胶囊与「失败」互斥(原来两个维度叠加,「失败」亮着时点类型只剩空列表,
|
||||
看起来像筛选坏了);并给每个胶囊带上条数,点完立刻能看到生效与是否有该类型记录。 -->
|
||||
<span class="chip-sel" :class="{ on: kind === '' && result !== 'fail' }" @click="pickKind('')">
|
||||
{{ t('logs.all') }}<i class="cn">{{ entries.length }}</i>
|
||||
</span>
|
||||
<span class="chip-sel" :class="{ on: kind === 'chat' }" @click="pickKind('chat')">
|
||||
{{ t('logs.chat') }}<i class="cn">{{ kindCounts.chat }}</i>
|
||||
</span>
|
||||
<span class="chip-sel" :class="{ on: kind === 'image' }" @click="pickKind('image')">
|
||||
{{ t('logs.image') }}<i class="cn">{{ kindCounts.image }}</i>
|
||||
</span>
|
||||
<span class="chip-sel" :class="{ on: kind === 'video' }" @click="pickKind('video')">
|
||||
{{ t('logs.video') }}<i class="cn">{{ kindCounts.video }}</i>
|
||||
</span>
|
||||
<span class="chip-sel" :class="{ on: result === 'fail' }" @click="pickKind('fail')">
|
||||
{{ t('logs.fail') }}<i class="cn">{{ kindCounts.fail }}</i>
|
||||
</span>
|
||||
|
||||
<el-select v-model="method" :placeholder="t('logs.method')" clearable size="small" class="sel-method">
|
||||
<el-option v-for="m in ['GET', 'POST', 'OPTIONS', 'DELETE']" :key="m" :value="m" :label="m" />
|
||||
</el-select>
|
||||
<el-select v-model="result" :placeholder="t('logs.result')" clearable size="small" class="sel-result">
|
||||
<el-option value="ok" :label="t('logs.success')" />
|
||||
<el-option value="fail" :label="t('logs.fail')" />
|
||||
</el-select>
|
||||
<el-input v-model="kw" size="small" :placeholder="t('logs.searchPlaceholder')" clearable class="kw-in" @keyup.enter="applyFilter">
|
||||
<template #append><el-button @click="applyFilter">{{ t('common.search') }}</el-button></template>
|
||||
</el-input>
|
||||
<el-switch v-model="auto" size="small" :active-text="t('logs.autoRefresh')" />
|
||||
|
||||
<span class="spacer" />
|
||||
<el-button size="small" text @click="clear">{{ t('logs.clearFilter') }}</el-button>
|
||||
<el-button size="small" :disabled="loading" @click="load()">
|
||||
<Icon name="refresh" :size="13" />
|
||||
<span>{{ t('common.refresh') }}</span>
|
||||
</el-button>
|
||||
<el-button size="small" :disabled="!filtered.length" @click="exportLogs">
|
||||
<Icon name="dl" :size="13" />
|
||||
<span>{{ t('common.export') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('nav.menulogs') }}</b>
|
||||
<span class="sub">{{ t('logs.count', { n: filtered.length }) }}</span>
|
||||
<div class="pager">
|
||||
<span class="pill" :class="rateCls">{{ t('logs.success') }} {{ okRate }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="log-list" v-loading="loading">
|
||||
<div v-if="!filtered.length" class="hint">
|
||||
<span>{{ entries.length ? t('logs.emptyFiltered', { n: entries.length }) : t('logs.empty') }}</span>
|
||||
<el-button v-if="entries.length" size="small" text @click="clear">{{ t('logs.clearFilter') }}</el-button>
|
||||
</div>
|
||||
|
||||
<div v-for="row in filtered" :key="rowKey(row)">
|
||||
<div class="log-row" @click="toggle(row)">
|
||||
<span class="ts">{{ fmtTime(row.ts) }}</span>
|
||||
<span class="badge m">{{ kindLabel(row) }}</span>
|
||||
<span class="badge" :class="statusCls(row)">{{ statusText(row) }}</span>
|
||||
<span class="code path">{{ row.method }} {{ row.path }}</span>
|
||||
<span class="badge m" v-if="row.stream">{{ t('logs.streaming') }}</span>
|
||||
<span class="nowrap model">{{ row.served || row.model || '—' }}<span v-if="row.provider" class="muted-2"> @ {{ row.provider }}</span></span>
|
||||
<span class="muted note" :title="noteFull(row)">{{ noteText(row) }}</span>
|
||||
<Icon :name="isOpen(row) ? 'chevD' : 'chev'" :size="14" />
|
||||
</div>
|
||||
|
||||
<div v-if="isOpen(row)" class="log-detail">
|
||||
<p class="kv">
|
||||
<b>{{ t('logs.rid') }}</b> <span class="code">{{ row.rid || '—' }}</span>
|
||||
<b>{{ t('logs.caller') }}</b> <span class="code">{{ row.caller || '—' }}</span>
|
||||
<b>{{ t('logs.reqModel') }}</b> <span class="code">{{ row.model || '—' }}</span>
|
||||
<b>{{ t('logs.served') }}</b> <span class="code">{{ row.served || '—' }}</span>
|
||||
<b>{{ t('logs.provider') }}</b> <span class="code">{{ row.provider || '—' }}</span>
|
||||
<b>{{ t('logs.streaming') }}</b> <span class="code">{{ row.stream ? 'SSE' : t('common.no') }}</span>
|
||||
</p>
|
||||
<div class="detail-block"><label>{{ t('logs.request') }}</label><pre>{{ row.body || '—' }}</pre></div>
|
||||
<div class="detail-block"><label>{{ t('logs.response') }}</label><pre>{{ row.response || '—' }}</pre></div>
|
||||
<div class="detail-block" v-if="row.polls && row.polls.length">
|
||||
<label>{{ t('logs.polls', { n: row.polls.length }) }}</label>
|
||||
<el-timeline class="poll-timeline">
|
||||
<el-timeline-item v-for="(p, i) in row.polls" :key="i"
|
||||
:type="p.ok === false ? 'danger' : p.status === 'completed' || p.status === 'success' ? 'success' : p.status === 'failed' ? 'danger' : 'info'"
|
||||
:timestamp="fmtTime(p.ts)" placement="top" size="small">
|
||||
<div class="poll-line">
|
||||
<span class="code">{{ p.status || '—' }}</span>
|
||||
<span v-if="p.progress != null" class="sub"> · {{ p.progress }}%</span>
|
||||
<span v-if="p.error" class="err-text"> · {{ short(p.error) }}</span>
|
||||
</div>
|
||||
<pre v-if="p.raw" class="poll-raw">{{ p.raw }}</pre>
|
||||
</el-timeline-item>
|
||||
</el-timeline>
|
||||
</div>
|
||||
<div class="detail-block" v-if="!row.ok"><label>{{ t('logs.error') }}</label><pre class="err-pre">{{ row.error || '—' }}</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { api } from '../api'
|
||||
import Icon from '../components/Icon.vue'
|
||||
import { stamp } from '../lib/download'
|
||||
|
||||
const router = useRouter()
|
||||
const { t } = useI18n()
|
||||
const entries = ref<any[]>([])
|
||||
const loading = ref(false)
|
||||
const auto = ref(true)
|
||||
const method = ref('')
|
||||
const result = ref('')
|
||||
const kw = ref('')
|
||||
// 第十九轮真凶:这里原来是普通 `let appliedKw = ''`,不是 ref —— 它不参与响应式追踪,
|
||||
// 改完之后 `filtered` 这个 computed 不会重算,只能等下一次数据变化(自动刷新 5s 一轮)
|
||||
// 才顺带把关键词应用上。表现就是「输了关键词点搜索,列表纹丝不动 / 过几秒自己又变了」。
|
||||
// 类型胶囊用的是 ref(kind),所以只有关键词这一路看着像坏了。
|
||||
const appliedKw = ref('')
|
||||
// 已展开的行 key:自动刷新会整体替换数据数组。改成自绘行之后展开态直接由这个 key 集合推导,
|
||||
// 刷新后(只要这行还在)详情不会每 5s 被收回去。
|
||||
const expandedKeys = ref<string[]>([])
|
||||
const expandedSet = computed(() => new Set(expandedKeys.value))
|
||||
const rowKey = (row: any): string => row.rid || `${row.method}:${row.path}:${row.ts}`
|
||||
function isOpen(row: any): boolean {
|
||||
return expandedSet.value.has(rowKey(row))
|
||||
}
|
||||
function toggle(row: any) {
|
||||
const k = rowKey(row)
|
||||
expandedKeys.value = expandedKeys.value.includes(k)
|
||||
? expandedKeys.value.filter((x) => x !== k)
|
||||
: [...expandedKeys.value, k]
|
||||
}
|
||||
|
||||
// 视频快照是否已经有结论(有结论就不再主动追轮询)
|
||||
const pollDone = (pl: any) => /completed|success|succeeded|failed|error/i.test(String(pl?.status))
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try {
|
||||
// 先对上一条数据里「仍展开、且没生成完」的视频行主动轮询一次(幂等 GET):
|
||||
// 让正在看日志详情的老板也能实时看到轮询进度 —— 否则只有开着视频页才有快照。
|
||||
// 先轮询再取 /logs,本次刷新立刻就能看到新快照,不会慢一拍。
|
||||
const keys = expandedSet.value
|
||||
for (const e of entries.value) {
|
||||
if (!e.video_id || !keys.has(rowKey(e))) continue
|
||||
const pl = e.polls && e.polls.length ? e.polls[e.polls.length - 1] : null
|
||||
if (pl && pollDone(pl)) continue
|
||||
try {
|
||||
await api(`/v1/videos/${encodeURIComponent(e.video_id)}?model=${encodeURIComponent(e.served || e.model || '')}`)
|
||||
} catch { /* 轮询失败不打断刷新;后端会记为该次的失败快照 */ }
|
||||
}
|
||||
const j = await api('/logs?n=200')
|
||||
entries.value = j.entries || []
|
||||
// 只保留仍存在的已展开行:行被顶出窗口/被删则对应 key 一并清掉
|
||||
const alive = new Set(entries.value.map(rowKey))
|
||||
expandedKeys.value = expandedKeys.value.filter((k) => alive.has(k))
|
||||
} catch (e: any) {
|
||||
if (e && e.status === 401) { router.push('/login'); return }
|
||||
} finally { loading.value = false }
|
||||
}
|
||||
|
||||
// ── 类型筛选(全部 / 对话 / 图像 / 视频 / 失败)──
|
||||
// 「失败」直接复用原有的 result 筛选,不另立一份状态;其余按日志路径归类,纯前端过滤。
|
||||
type Kind = '' | 'chat' | 'image' | 'video'
|
||||
const kind = ref<Kind>('')
|
||||
// 第十九轮:优先用后端给的 row.kind(权威),老条目没这个字段才退回按路径猜。
|
||||
// 之前只看路径字符串,一旦以后端点改名/换前缀,筛选就会静默失效。
|
||||
function kindOf(row: any): Kind {
|
||||
const k = String(row.kind || '')
|
||||
if (k === 'chat' || k === 'image' || k === 'video') return k
|
||||
if (k === 'media') return '' // 媒体代拉(下载):不属于三类生成调用,只在「全部」里出现
|
||||
const p = String(row.path || '')
|
||||
if (p.includes('/images')) return 'image'
|
||||
if (p.includes('/videos')) return 'video'
|
||||
if (p.includes('/chat')) return 'chat'
|
||||
return ''
|
||||
}
|
||||
// 每个胶囊上的条数:直接告诉老板「这一类有几条」,筛完变空时也就不会再以为筛选没生效
|
||||
const kindCounts = computed(() => {
|
||||
const c: Record<string, number> = { chat: 0, image: 0, video: 0, fail: 0 }
|
||||
for (const e of entries.value) {
|
||||
const k = kindOf(e)
|
||||
if (k) c[k] += 1
|
||||
if (!e.ok) c.fail += 1
|
||||
}
|
||||
return c
|
||||
})
|
||||
function pickKind(k: '' | Kind | 'fail') {
|
||||
if (k === '') { kind.value = ''; result.value = ''; return }
|
||||
if (k === 'fail') {
|
||||
// 互斥:点「失败」就清掉类型,点类型就清掉「失败」(否则 类型=视频 + 结果=失败
|
||||
// 两个胶囊同时亮着、列表却是空的,看着就像筛选坏了)。要叠加筛选仍可用「结果」下拉。
|
||||
result.value = result.value === 'fail' ? '' : 'fail'
|
||||
if (result.value) kind.value = ''
|
||||
return
|
||||
}
|
||||
kind.value = kind.value === k ? '' : k
|
||||
if (kind.value) result.value = ''
|
||||
}
|
||||
function kindLabel(row: any): string {
|
||||
const k = kindOf(row)
|
||||
if (k === 'chat') return t('logs.chat')
|
||||
if (k === 'image') return t('logs.image')
|
||||
if (k === 'video') return t('logs.video')
|
||||
if (row.kind === 'media') return t('logs.media') // 下载:比裸显示 GET 更说明问题
|
||||
return row.method || '—'
|
||||
}
|
||||
// 视频还没出结果 → 用 warn 色提示「生成中」
|
||||
function videoBusy(row: any): boolean {
|
||||
if (!row.video_id) return false
|
||||
const pl = row.polls && row.polls.length ? row.polls[row.polls.length - 1] : null
|
||||
return !pl || !pollDone(pl)
|
||||
}
|
||||
function statusCls(row: any): string {
|
||||
if (!row.ok) return 'r'
|
||||
return videoBusy(row) ? 'o' : 'g'
|
||||
}
|
||||
function statusText(row: any): string {
|
||||
if (!row.ok) return t('common.fail')
|
||||
return videoBusy(row) ? t('videos.doingText') : t('common.ok')
|
||||
}
|
||||
|
||||
const filtered = computed(() => {
|
||||
let list = entries.value
|
||||
if (method.value) list = list.filter((e) => e.method === method.value)
|
||||
if (result.value) list = list.filter((e) => e.ok === (result.value === 'ok'))
|
||||
if (kind.value) list = list.filter((e) => kindOf(e) === kind.value)
|
||||
if (appliedKw.value) {
|
||||
const k = appliedKw.value.toLowerCase()
|
||||
list = list.filter((e) => [e.model, e.served, e.provider, e.path, e.body, e.response, e.error]
|
||||
.some((v) => v && String(v).toLowerCase().includes(k)))
|
||||
}
|
||||
return list
|
||||
})
|
||||
function applyFilter() { appliedKw.value = (kw.value || '').trim() }
|
||||
// 第十九轮:关键词改成「边打边筛」。原来只有点「搜索」或回车才赋值,而且那个变量还不是响应式的,
|
||||
// 输完看着列表没变,很容易和这次报的「筛选不生效」混在一起;行数最多 200 条,实时过滤开销可忽略。
|
||||
// 搜索按钮和回车保留(点一下等于强制重算,对习惯动作无害)。
|
||||
watch(kw, () => { appliedKw.value = (kw.value || '').trim() })
|
||||
function clear() { method.value = ''; result.value = ''; kw.value = ''; appliedKw.value = ''; kind.value = '' }
|
||||
|
||||
const okRate = computed(() => {
|
||||
const n = filtered.value.length
|
||||
if (!n) return '0.0'
|
||||
const ok = filtered.value.filter((e) => e.ok).length
|
||||
return ((ok / n) * 100).toFixed(1)
|
||||
})
|
||||
const rateCls = computed(() => {
|
||||
const n = filtered.value.length
|
||||
if (!n) return 'mute'
|
||||
const r = Number(okRate.value)
|
||||
return r >= 99 ? 'ok' : r >= 90 ? 'warn' : 'err'
|
||||
})
|
||||
|
||||
function fmtTime(ts: number) {
|
||||
if (!ts) return '-'
|
||||
const d = new Date(ts * 1000)
|
||||
const pad = (x: number) => String(x).padStart(2, '0')
|
||||
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
|
||||
}
|
||||
|
||||
const short = (x: any, n = 120) => {
|
||||
const t = String(x ?? '')
|
||||
return t.length > n ? t.slice(0, n) + '…' : t
|
||||
}
|
||||
function noteFull(row: any): string {
|
||||
return String((row.ok ? row.response : row.error || row.response) || row.body || '')
|
||||
}
|
||||
function noteText(row: any): string {
|
||||
const s = noteFull(row)
|
||||
return s ? short(s) : '—'
|
||||
}
|
||||
|
||||
/** 日志导出:把当前筛选结果存成 JSON(纯前端,不新增接口)。 */
|
||||
function exportLogs() {
|
||||
const body = JSON.stringify(filtered.value, null, 2)
|
||||
const href = URL.createObjectURL(new Blob([body], { type: 'application/json;charset=utf-8' }))
|
||||
const a = document.createElement('a')
|
||||
a.href = href
|
||||
a.download = `logs-${stamp()}.json`
|
||||
a.style.display = 'none'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
setTimeout(() => URL.revokeObjectURL(href), 10_000)
|
||||
}
|
||||
|
||||
let timer: any = null
|
||||
onMounted(() => { load(); timer = setInterval(() => { if (auto.value) load() }, 5000) })
|
||||
onUnmounted(() => clearInterval(timer))
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.filters .spacer { flex: 1; }
|
||||
.sel-method { width: 118px; }
|
||||
.sel-result { width: 108px; }
|
||||
/* 搜索框:桌面 280px,窄屏靠 max-width 收到工具条宽度(父级是 flex 容器,100% 有效) */
|
||||
.kw-in { width: 280px; max-width: 100%; }
|
||||
|
||||
.log-list { max-height: 68vh; overflow-y: auto; }
|
||||
.log-row { cursor: pointer; }
|
||||
.log-row:hover { background: var(--surface-2); }
|
||||
.log-row .path { flex: none; color: var(--muted); }
|
||||
.log-row .model { flex: none; max-width: 220px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.log-row .note { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.log-row :deep(.gw-icon) { color: var(--muted-2); flex: none; }
|
||||
|
||||
.kv { margin: 0 0 8px; display: flex; gap: 10px; flex-wrap: wrap; }
|
||||
.detail-block { margin-bottom: 8px; }
|
||||
.detail-block label { display: block; color: var(--muted-2); font-size: 11px; margin-bottom: 2px; }
|
||||
.detail-block pre {
|
||||
margin: 0; padding: 8px 10px; background: var(--surface); border: 1px solid var(--line);
|
||||
border-radius: 6px; white-space: pre-wrap; word-break: break-all;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px;
|
||||
max-height: 240px; overflow: auto; color: var(--text);
|
||||
}
|
||||
.err-pre { color: var(--err); }
|
||||
.poll-timeline { padding: 4px 2px; max-height: 260px; overflow: auto; }
|
||||
.poll-line { font-size: 12px; }
|
||||
.poll-raw {
|
||||
margin-top: 2px; font-size: 11px; max-height: 90px; overflow: auto;
|
||||
background: var(--surface); border: 1px solid var(--line); border-radius: 6px; padding: 6px 8px;
|
||||
white-space: pre-wrap; word-break: break-all;
|
||||
}
|
||||
.sub { font-size: 11.5px; color: var(--muted-2); }
|
||||
.err-text { color: var(--err); font-size: 12px; }
|
||||
|
||||
/* 类型胶囊上的条数:小一号、淡一档;胶囊选中时跟着主色走(.on 已给 font-weight) */
|
||||
.chip-sel .cn {
|
||||
font-style: normal; font-size: 11px; font-variant-numeric: tabular-nums;
|
||||
padding: 0 5px; border-radius: 6px; background: var(--chip); color: var(--muted-2);
|
||||
}
|
||||
.chip-sel.on .cn { background: var(--primary); color: #fff; }
|
||||
/* 筛选后为空:给出「原始有多少条」并直接给一个清空筛选的出口 */
|
||||
.hint { display: flex; align-items: center; justify-content: center; gap: 8px; flex-wrap: wrap; }
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.filters .kw-in { width: 100%; }
|
||||
.log-row { flex-wrap: wrap; }
|
||||
.log-row .path { order: 9; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.log-row .note { white-space: normal; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,262 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<el-alert v-if="err" :title="err" type="error" show-icon :closable="false" class="mb" />
|
||||
|
||||
<!-- KPI:全部来自 /metrics 当前快照。网关没有历史时序接口,
|
||||
所以这里不画趋势条、也不给「近 7 天」这类假的时间筛选。 -->
|
||||
<div class="kpis">
|
||||
<div v-for="c in cards" :key="c.k" class="kpi">
|
||||
<div class="k">{{ c.k }}</div>
|
||||
<div class="v">{{ c.v }}</div>
|
||||
<div class="f"><span class="muted-2">{{ c.note }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid-eq">
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('metrics.modelCalls') }}</b>
|
||||
<span class="sub">{{ t('metrics.snapshot') }}</span>
|
||||
<div class="legend">
|
||||
<span><i style="background: var(--ok)" />{{ t('metrics.success') }}</span>
|
||||
<span><i style="background: var(--err)" />{{ t('metrics.fail') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<EChart :option="callsOpt" height="250px" />
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('metrics.provShare') }}</b>
|
||||
<span class="sub">{{ t('metrics.snapshot') }}</span>
|
||||
</div>
|
||||
<EChart :option="provOpt" height="250px" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid-eq">
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('metrics.routeVsProvider') }}</b>
|
||||
<span class="sub">{{ t('metrics.snapshot') }}</span>
|
||||
<div class="legend">
|
||||
<span><i style="background: var(--chart-a)" />ok</span>
|
||||
<span><i style="background: var(--err)" />fail</span>
|
||||
<span><i style="background: var(--warn)" />fallback</span>
|
||||
</div>
|
||||
</div>
|
||||
<EChart :option="routeOpt" height="250px" />
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('metrics.latency') }}</b>
|
||||
<span class="sub">P50 / P95</span>
|
||||
<div class="legend">
|
||||
<span><i style="background: var(--chart-a)" />P50</span>
|
||||
<span><i style="background: var(--chart-b)" />P95</span>
|
||||
</div>
|
||||
</div>
|
||||
<EChart :option="latOpt" height="250px" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="margin-top: var(--gap)">
|
||||
<div class="card-h">
|
||||
<b>{{ t('metrics.circuitStatus') }}</b>
|
||||
<span class="sub">{{ t('metrics.circuitCard') }}</span>
|
||||
</div>
|
||||
<el-table :data="circuits" size="small" v-loading="loading">
|
||||
<el-table-column prop="provider" :label="t('metrics.provider')" min-width="140" />
|
||||
<el-table-column :label="t('metrics.state')" width="120">
|
||||
<template #default="{ row }">
|
||||
<span class="pill" :class="stateCls(row.state)">{{ row.state }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="recent_failures" :label="t('metrics.recentFailures')" width="100" />
|
||||
<el-table-column prop="window_size" :label="t('metrics.window')" width="90" />
|
||||
<el-table-column prop="threshold" :label="t('metrics.threshold')" width="90" />
|
||||
<el-table-column prop="cooldown_seconds" :label="t('metrics.cooldown')" width="110" />
|
||||
<el-table-column :label="t('metrics.probing')" width="90">
|
||||
<template #default="{ row }">
|
||||
<Icon v-if="row.probing" name="refresh" :size="14" />
|
||||
<span v-else class="muted-2">{{ t('common.no') }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<div class="card about-card">
|
||||
<div class="about-line">
|
||||
<b>{{ t('metrics.snapshot') }}</b>
|
||||
<span>{{ t('metrics.uptime') }} {{ fmtUptime }}</span>
|
||||
<span>{{ t('metrics.fallback') }} {{ data.fallback_total ?? 0 }}</span>
|
||||
<span>{{ t('metrics.inflight') }} {{ data.in_flight ?? 0 }} / {{ data.in_flight_peak ?? 0 }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { api } from '../api'
|
||||
import EChart from '../components/EChart.vue'
|
||||
import Icon from '../components/Icon.vue'
|
||||
import { categoryAxis, chartTheme, emptyTip, grid, legend, pieLabel, pieLabelLine, pieRadius, pieCenter, pieData, valueAxis } from '../lib/charts'
|
||||
import type { EChartsCoreOption } from '../lib/echarts'
|
||||
import { useTheme } from '../lib/theme'
|
||||
|
||||
const router = useRouter()
|
||||
const { t } = useI18n()
|
||||
const { resolved } = useTheme()
|
||||
const data = ref<any>({})
|
||||
const loading = ref(false)
|
||||
const err = ref('')
|
||||
// 运行时间的实时基准:uptimeAt = 上次拿到 /metrics 的时刻,nowTick = 本地每秒心跳。
|
||||
const uptimeAt = ref(Date.now())
|
||||
const nowTick = ref(Date.now())
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
err.value = ''
|
||||
try {
|
||||
data.value = await api('/metrics')
|
||||
uptimeAt.value = Date.now()
|
||||
} catch (e: any) {
|
||||
if (e && e.status === 401) { router.push('/login'); return }
|
||||
err.value = e?.message || String(e)
|
||||
} finally { loading.value = false }
|
||||
}
|
||||
|
||||
const fmtUptime = computed(() => {
|
||||
const u = data.value.uptime_seconds
|
||||
if (u == null) return '-'
|
||||
// 运行时间要实时走:/metrics 是 8s 一拉,直接用返回值会「8 秒跳一格」。
|
||||
// 这里以拿到值的那一刻为基准本地每秒累加,秒针是连续走的。
|
||||
void nowTick.value
|
||||
const live = u + Math.max(0, (nowTick.value - uptimeAt.value) / 1000)
|
||||
const d = Math.floor(live / 86400); const h = Math.floor((live % 86400) / 3600)
|
||||
const mo = Math.floor((live % 3600) / 60); const s = Math.floor(live % 60)
|
||||
return d ? `${d}d ${h}h ${mo}m ${s}s` : h ? `${h}h ${mo}m ${s}s` : `${mo}m ${s}s`
|
||||
})
|
||||
|
||||
const totals = computed(() => {
|
||||
const c = data.value.calls || {}
|
||||
let ok = 0, fail = 0
|
||||
for (const m of Object.values(c) as any[]) { ok += m?.ok || 0; fail += m?.fail || 0 }
|
||||
return { ok, fail, all: ok + fail }
|
||||
})
|
||||
|
||||
const cards = computed(() => {
|
||||
void resolved.value
|
||||
const tk = data.value.tokens || {}
|
||||
const { ok, fail, all } = totals.value
|
||||
const rate = all ? (fail / all) * 100 : 0
|
||||
return [
|
||||
{ k: t('metrics.requests'), v: all, note: t('dashboard.noteOkFail', { ok, fail }) },
|
||||
{ k: t('metrics.failCount'), v: fail, note: t('metrics.failRateNote', { v: rate.toFixed(1) }) },
|
||||
{ k: t('metrics.tokenUsage'), v: (tk.prompt || 0) + (tk.completion || 0), note: t('metrics.tokenNote', { p: tk.prompt ?? 0, c: tk.completion ?? 0 }) },
|
||||
{ k: t('metrics.inflightPeak'), v: `${data.value.in_flight ?? 0} / ${data.value.in_flight_peak ?? 0}`, note: t('metrics.fallback') + ' ' + (data.value.fallback_total ?? 0) },
|
||||
]
|
||||
})
|
||||
|
||||
const callsOpt = computed<EChartsCoreOption>(() => {
|
||||
void resolved.value
|
||||
const c = chartTheme()
|
||||
const calls = data.value.calls || {}
|
||||
const models = Object.keys(calls)
|
||||
const ok = models.map((m) => calls[m]?.ok || 0)
|
||||
const fail = models.map((m) => calls[m]?.fail || 0)
|
||||
return {
|
||||
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
legend: legend([t('metrics.success'), t('metrics.fail')]),
|
||||
grid,
|
||||
graphic: emptyTip([ok, fail], t('metrics.none')),
|
||||
xAxis: categoryAxis(models),
|
||||
yAxis: valueAxis('', 1),
|
||||
series: [
|
||||
{ name: t('metrics.success'), type: 'bar', stack: 'c', itemStyle: { color: c.ok }, data: ok },
|
||||
{ name: t('metrics.fail'), type: 'bar', stack: 'c', itemStyle: { color: c.err }, data: fail },
|
||||
],
|
||||
}
|
||||
})
|
||||
|
||||
const provOpt = computed<EChartsCoreOption>(() => {
|
||||
void resolved.value
|
||||
const p = data.value.providers || {}
|
||||
const items = Object.keys(p).map((k) => ({ name: k, value: p[k]?.ok || 0 })).filter((x) => x.value > 0)
|
||||
return {
|
||||
tooltip: { trigger: 'item' },
|
||||
series: [{
|
||||
type: 'pie', radius: pieRadius, center: pieCenter, minAngle: 6, labelLine: pieLabelLine,
|
||||
data: pieData(items, t('metrics.none')), label: pieLabel(), itemStyle: { borderRadius: 4 },
|
||||
}],
|
||||
}
|
||||
})
|
||||
|
||||
const routeOpt = computed<EChartsCoreOption>(() => {
|
||||
void resolved.value
|
||||
const c = chartTheme()
|
||||
const r = data.value.routes || {}
|
||||
const ks = Object.keys(r)
|
||||
const names = ks.length ? ks : ['wjd']
|
||||
const get = (k: string, f: string) => (r[k] || {})[f] || 0
|
||||
const ok = names.map((n) => get(n, 'ok'))
|
||||
const fail = names.map((n) => get(n, 'fail'))
|
||||
const fallback = names.map((n) => get(n, 'fallback'))
|
||||
return {
|
||||
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
|
||||
legend: legend(['ok', 'fail', 'fallback']),
|
||||
grid,
|
||||
graphic: emptyTip([ok, fail, fallback], t('metrics.none')),
|
||||
xAxis: categoryAxis(names, 10),
|
||||
yAxis: valueAxis('', 1),
|
||||
series: [
|
||||
{ name: 'ok', type: 'bar', stack: 'r', data: ok, itemStyle: { color: c.a } },
|
||||
{ name: 'fail', type: 'bar', stack: 'r', data: fail, itemStyle: { color: c.err } },
|
||||
{ name: 'fallback', type: 'bar', stack: 'r', data: fallback, itemStyle: { color: c.warn } },
|
||||
],
|
||||
}
|
||||
})
|
||||
|
||||
const latOpt = computed<EChartsCoreOption>(() => {
|
||||
void resolved.value
|
||||
const c = chartTheme()
|
||||
const l = data.value.latency || {}
|
||||
const models = Object.keys(l)
|
||||
const p50 = models.map((m) => l[m]?.p50 ?? 0)
|
||||
const p95 = models.map((m) => l[m]?.p95 ?? 0)
|
||||
return {
|
||||
tooltip: { trigger: 'axis', valueFormatter: (v: any) => `${typeof v === 'number' ? v.toFixed(3) : v}s` },
|
||||
legend: legend(['P50', 'P95']),
|
||||
grid,
|
||||
graphic: emptyTip([p50, p95], t('metrics.none')),
|
||||
xAxis: categoryAxis(models),
|
||||
yAxis: valueAxis('s'),
|
||||
series: [
|
||||
{ name: 'P50', type: 'bar', data: p50, itemStyle: { color: c.a, borderRadius: [4, 4, 0, 0] } },
|
||||
{ name: 'P95', type: 'bar', data: p95, itemStyle: { color: c.b, borderRadius: [4, 4, 0, 0] } },
|
||||
],
|
||||
}
|
||||
})
|
||||
|
||||
const circuits = computed(() => data.value.circuits || [])
|
||||
function stateCls(s: string) {
|
||||
const v = String(s || '').toUpperCase()
|
||||
return v === 'CLOSED' ? 'ok' : v === 'HALF_OPEN' ? 'warn' : 'err'
|
||||
}
|
||||
|
||||
let timer: any = null
|
||||
let tickTimer: any = null
|
||||
onMounted(() => {
|
||||
load()
|
||||
timer = setInterval(load, 8000)
|
||||
tickTimer = setInterval(() => { nowTick.value = Date.now() }, 1000)
|
||||
})
|
||||
onUnmounted(() => { clearInterval(timer); clearInterval(tickTimer) })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.about-card { margin-top: var(--gap); padding: 12px 16px; }
|
||||
.about-line b { color: var(--text); }
|
||||
</style>
|
||||
@@ -0,0 +1,333 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<el-alert v-if="err" :title="err" type="error" show-icon :closable="false" class="mb" />
|
||||
|
||||
<div class="kpis">
|
||||
<div v-for="c in cards" :key="c.k" class="kpi">
|
||||
<div class="k">{{ c.k }}</div>
|
||||
<div class="v">{{ c.v }}</div>
|
||||
<div class="f"><span class="muted-2">{{ c.note }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid2">
|
||||
<!-- 路由链:只读展示(排序策略在后端,页面不写盘) -->
|
||||
<!-- 路由别名 + 全部文本模型延迟(一键测速填充) -->
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('models.routeAliasTitle') }}</b>
|
||||
</div>
|
||||
|
||||
<div v-for="r in routeRows" :key="r.name" class="route-block">
|
||||
<div class="route-head">
|
||||
<span class="code route-name">{{ r.name }}</span>
|
||||
<span style="flex:1"></span>
|
||||
<el-button size="small" :loading="latTesting" @click="runSpeedtest()">
|
||||
{{ latTesting ? t('models.testingShort') : t('models.speedtest') }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!routeRows.length" class="hint">{{ t('models.noRoute') }}</div>
|
||||
|
||||
<div class="lat-head">
|
||||
<span class="muted-2 hint">{{ t('models.allTextModels') }}</span>
|
||||
<span style="flex:1"></span>
|
||||
<span class="muted-2 hint">{{ t('models.latency') }}</span>
|
||||
</div>
|
||||
<div v-for="m in textModelRows" :key="m.id" class="st-item">
|
||||
<div class="st-row">
|
||||
<Icon v-if="m.vision" name="eye" :size="12" class="vision" />
|
||||
<span class="code">{{ m.id }}</span>
|
||||
<span class="muted-2 st-prov">{{ m.provider }}</span>
|
||||
<span style="flex:1"></span>
|
||||
<span class="pill st-lat" :class="latCls(m.id)">
|
||||
<span v-if="m.id === latCurrentId" class="st-spin" aria-hidden="true"></span>
|
||||
<span v-else>{{ latText(m.id) }}</span>
|
||||
</span>
|
||||
<button class="st-one" :disabled="latTesting || !!latCurrentId"
|
||||
:title="t('models.testOne')" :aria-label="t('models.testOne')" @click="retestOne(m.id)">
|
||||
<Icon name="bolt" :size="13" />
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="latErr(m.id)" class="st-err">
|
||||
<Icon name="ban" :size="13" class="st-err-ico" />
|
||||
<span class="st-err-txt">{{ latErr(m.id) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!textModelRows.length" class="hint">{{ t('common.empty') }}</div>
|
||||
</div>
|
||||
|
||||
<!-- 供应商:状态取 /health 的熔断器,Key 是否配置取同一份数据 -->
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('models.providerCard') }}</b>
|
||||
<span class="sub">{{ t('models.providerCount2', { n: providerRows.length }) }}</span>
|
||||
</div>
|
||||
<div v-for="p in providerRows" :key="p.name" class="prov">
|
||||
<div class="prov-top">
|
||||
<b>{{ p.name }}</b>
|
||||
<span class="pill" :class="p.cls">{{ p.text }}</span>
|
||||
</div>
|
||||
<div class="prov-meta">
|
||||
<span class="muted-2">{{ p.models }} {{ t('models.model') }}</span>
|
||||
<span class="pill" :class="p.keySet ? 'ok' : 'err'">
|
||||
{{ p.keySet ? t('models.keyOk') : t('models.keyMissing') }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!providerRows.length" class="hint">{{ t('common.empty') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="margin-top: var(--gap)">
|
||||
<div class="card-h">
|
||||
<b>{{ t('models.modelListTitle') }}</b>
|
||||
<span class="sub">{{ t('models.capability') }}</span>
|
||||
<div class="pager">
|
||||
<span class="pill mute">{{ t('models.routeCount', { n: routeRows.length }) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<el-table :data="modelRows" size="small" v-loading="loading">
|
||||
<el-table-column :label="t('models.id')" min-width="200">
|
||||
<template #default="{ row }"><span class="code">{{ row.id }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('models.type')" width="100">
|
||||
<template #default="{ row }"><span class="pill" :class="typeCls(row.type)">{{ t(typeKey(row.type)) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('models.provider')" min-width="150">
|
||||
<template #default="{ row }">{{ row.provider_name || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('models.capability')" width="120">
|
||||
<template #default="{ row }">
|
||||
<span v-if="row.vision" class="pill ok cap">
|
||||
<Icon name="eye" :size="12" />{{ t('models.visionTag') }}
|
||||
</span>
|
||||
<span v-else class="muted-2">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('models.keySet')" width="120">
|
||||
<template #default="{ row }">
|
||||
<span class="pill" :class="row.key_set ? 'ok' : 'err'">
|
||||
{{ row.key_set ? t('common.yes') : t('common.no') }}
|
||||
</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { api } from '../api'
|
||||
import Icon from '../components/Icon.vue'
|
||||
|
||||
const router = useRouter()
|
||||
const { t } = useI18n()
|
||||
const items = ref<any[]>([])
|
||||
const health = ref<any>({})
|
||||
const loading = ref(false)
|
||||
const err = ref('')
|
||||
|
||||
const typeKeyMap: Record<string, string> = { text: 'models.text', image: 'models.image', video: 'models.video', route: 'models.route' }
|
||||
const typeClsMap: Record<string, string> = { text: 'mute', image: 'warn', video: 'warn', route: 'ok' }
|
||||
function typeKey(ty: string) { return typeKeyMap[ty] || ty }
|
||||
function typeCls(ty: string) { return typeClsMap[ty] || 'mute' }
|
||||
|
||||
const latTesting = ref(false)
|
||||
const latCurrentId = ref('') // 当前正在测的模型 id:该行延迟位显示加载图标
|
||||
const latByModel = ref<Record<string, { ok: boolean; latency_ms: number | null; error: string }>>({})
|
||||
async function runSpeedtest() {
|
||||
if (latTesting.value) return
|
||||
// 逐个测速:按列表顺序,测一个立刻显示那一行、再测下一个;当前测的行显示加载图标。
|
||||
// 串行天然不会把免费额度瞬间打满(并发时免费档供应商容易 429)。
|
||||
const ids = textModelRows.value.map((m) => m.id)
|
||||
latByModel.value = {}
|
||||
latTesting.value = true
|
||||
for (const id of ids) {
|
||||
latCurrentId.value = id
|
||||
let row: { ok: boolean; latency_ms: number | null; error: string }
|
||||
try {
|
||||
const j = await api('/v1/models/speedtest', { method: 'POST', body: JSON.stringify({ model: id }) })
|
||||
const r: any[] = (j && j.results) || []
|
||||
const hit = r[0]
|
||||
row = hit
|
||||
? { ok: !!hit.ok, latency_ms: hit.latency_ms ?? null, error: hit.error || '' }
|
||||
: { ok: false, latency_ms: null, error: t('models.speedtestFail') }
|
||||
} catch (e: any) {
|
||||
// 单个模型出错不中断整轮,标记失败后继续下一个
|
||||
row = { ok: false, latency_ms: null, error: (e && e.message) || String(e) }
|
||||
}
|
||||
latByModel.value = { ...latByModel.value, [id]: row } // 响应式替换 → 该行即时更新
|
||||
}
|
||||
latCurrentId.value = ''
|
||||
latTesting.value = false
|
||||
ElMessage.success(t('models.speedtestDone', { n: ids.length }))
|
||||
}
|
||||
// 单个模型重新测速(失败行旁的「重新测速」按钮):只重测这一个,复用当前行加载图标
|
||||
async function retestOne(id: string) {
|
||||
if (latTesting.value || latCurrentId.value) return // 整轮测速中 / 已有单测在跑 → 忽略,避免打架
|
||||
latCurrentId.value = id
|
||||
try {
|
||||
const j = await api('/v1/models/speedtest', { method: 'POST', body: JSON.stringify({ model: id }) })
|
||||
const r: any[] = (j && j.results) || []
|
||||
const hit = r[0]
|
||||
const row = hit
|
||||
? { ok: !!hit.ok, latency_ms: hit.latency_ms ?? null, error: hit.error || '' }
|
||||
: { ok: false, latency_ms: null, error: t('models.speedtestFail') }
|
||||
latByModel.value = { ...latByModel.value, [id]: row }
|
||||
} catch (e: any) {
|
||||
latByModel.value = { ...latByModel.value, [id]: { ok: false, latency_ms: null, error: (e && e.message) || String(e) } }
|
||||
} finally {
|
||||
latCurrentId.value = ''
|
||||
}
|
||||
}
|
||||
function latText(id: string): string {
|
||||
const row = latByModel.value[id]
|
||||
if (row) {
|
||||
if (row.ok) return row.latency_ms != null ? row.latency_ms + ' ms' : t('models.failed')
|
||||
return t('models.failed') // 完整错误在下方 st-err 整行展示,这里只留短标记
|
||||
}
|
||||
return '—' // 未轮到 / 空闲(当前正在测的行由模板的加载图标分支显示,不走这里)
|
||||
}
|
||||
function latErr(id: string): string {
|
||||
const row = latByModel.value[id]
|
||||
return row && !row.ok ? (row.error || '') : ''
|
||||
}
|
||||
function latCls(id: string): string {
|
||||
const row = latByModel.value[id]
|
||||
return row ? (row.ok ? 'ok' : 'err') : 'mute'
|
||||
}
|
||||
|
||||
const routes = computed(() => items.value.filter((x) => x.type === 'route'))
|
||||
const models = computed(() => items.value.filter((x) => x.type !== 'route'))
|
||||
|
||||
const providerOf = computed(() => {
|
||||
const m: Record<string, string> = {}
|
||||
for (const x of models.value) m[x.id] = x.provider_name || '—'
|
||||
return m
|
||||
})
|
||||
const visionOf = computed(() => {
|
||||
const m: Record<string, boolean> = {}
|
||||
for (const x of models.value) m[x.id] = !!x.vision
|
||||
return m
|
||||
})
|
||||
|
||||
const routeRows = computed(() =>
|
||||
routes.value.map((r) => {
|
||||
const chain: string[] = r.models || []
|
||||
return {
|
||||
name: r.id,
|
||||
models: chain.map((id) => ({ id, provider: providerOf.value[id] || '—', vision: visionOf.value[id] })),
|
||||
providerCount: new Set(chain.map((id) => providerOf.value[id] || '—')).size,
|
||||
}
|
||||
}),
|
||||
)
|
||||
const textModelRows = computed(() =>
|
||||
models.value.filter((x) => x.type === 'text').map((m) => ({
|
||||
id: m.id,
|
||||
provider: m.provider_name || '—',
|
||||
vision: !!m.vision,
|
||||
})),
|
||||
)
|
||||
|
||||
const keySet = computed(() => {
|
||||
const ks: Record<string, boolean> = {}
|
||||
for (const p of Object.values(health.value.providers || {}) as any) ks[p.name] = !!p.api_key_set
|
||||
return ks
|
||||
})
|
||||
const modelRows = computed(() => models.value.map((m) => ({ ...m, key_set: keySet.value[m.provider_name] })))
|
||||
|
||||
const providerRows = computed(() => {
|
||||
const p = health.value.providers || {}
|
||||
return Object.keys(p).map((k) => {
|
||||
const c = String(p[k].circuit || '').toUpperCase()
|
||||
return {
|
||||
name: p[k].name,
|
||||
models: p[k].models,
|
||||
keySet: !!p[k].api_key_set,
|
||||
cls: c === 'CLOSED' ? 'ok' : c === 'HALF_OPEN' ? 'warn' : c === 'OPEN' ? 'err' : 'mute',
|
||||
text: t(`dashboard.circ_${String(p[k].circuit || '').toLowerCase() || ''}`),
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
const cards = computed(() => [
|
||||
{ k: t('models.model'), v: models.value.length, note: t('models.providerCount2', { n: providerRows.value.length }) },
|
||||
{ k: t('models.textModels'), v: models.value.filter((m) => m.type === 'text').length, note: t('models.visionTag') + ' · ' + models.value.filter((m) => m.vision).length },
|
||||
{ k: t('models.imageModels'), v: models.value.filter((m) => m.type === 'image').length, note: t('images.title') },
|
||||
{ k: t('models.routes'), v: routes.value.length, note: t('models.routeAliasTitle') },
|
||||
])
|
||||
|
||||
onMounted(async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const j = await api('/v1/models')
|
||||
items.value = j.data || []
|
||||
try { health.value = await api('/health') } catch { /* 可选 */ }
|
||||
} catch (e: any) {
|
||||
if (e && e.status === 401) { router.push('/login'); return }
|
||||
err.value = t('models.loadErr') + ': ' + ((e && e.message) || String(e))
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.route-block { padding: 10px 0; border-bottom: 1px solid var(--line-2); }
|
||||
.route-block:last-child { border-bottom: 0; }
|
||||
.route-head { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
|
||||
.route-name { font-weight: 700; color: var(--text); font-size: 13px; }
|
||||
.chain { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
.chain-item { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.arrow { color: var(--muted-2); }
|
||||
.vision { color: var(--primary); }
|
||||
.prov { padding: 10px 0; border-bottom: 1px solid var(--line-2); }
|
||||
.prov:last-child { border-bottom: 0; }
|
||||
.prov-top { display: flex; align-items: center; gap: 8px; }
|
||||
.prov-top b { font-size: 13px; }
|
||||
.prov-meta { display: flex; align-items: center; gap: 8px; margin-top: 6px; font-size: 11.5px; }
|
||||
.cap { display: inline-flex; align-items: center; gap: 4px; }
|
||||
.st { margin-top: 8px; border-top: 1px dashed var(--line-2); padding-top: 6px; }
|
||||
.st-item { padding: 4px 0; }
|
||||
.st-item + .st-item { border-top: 1px dashed var(--line); }
|
||||
.st-row { display: flex; align-items: center; gap: 8px; font-size: 12px; }
|
||||
.st-err {
|
||||
display: flex; align-items: flex-start; gap: 6px;
|
||||
margin: 4px 2px 2px; padding: 6px 8px;
|
||||
border-radius: 8px;
|
||||
background: var(--err-soft);
|
||||
color: var(--err);
|
||||
font-size: 11.5px; line-height: 1.55;
|
||||
overflow-wrap: anywhere; /* 长错误(JSON / 无空格串)也能自动换行不溢出 */
|
||||
word-break: break-word;
|
||||
}
|
||||
.st-err-ico { flex: none; margin-top: 1px; color: var(--err); }
|
||||
.st-err-txt { flex: 1; min-width: 0; }
|
||||
/* 每个模型行右侧的「单独测速」图标按钮 */
|
||||
.st-one {
|
||||
flex: none; display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 24px; height: 24px; padding: 0; margin-left: 2px;
|
||||
border: 1px solid var(--line); background: transparent; color: var(--muted);
|
||||
border-radius: 8px; cursor: pointer; transition: color .15s, border-color .15s, background .15s;
|
||||
}
|
||||
.st-one:hover:not(:disabled) { color: var(--primary); border-color: var(--primary); background: var(--primary-soft); }
|
||||
.st-one:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
/* 当前正在测的模型行:延迟位显示一个旋转加载图标 */
|
||||
.st-spin {
|
||||
display: inline-block; width: 12px; height: 12px; vertical-align: middle;
|
||||
border: 2px solid var(--line); border-top-color: var(--primary);
|
||||
border-radius: 50%; animation: st-spin 0.7s linear infinite;
|
||||
}
|
||||
@keyframes st-spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) { .st-spin { animation-duration: 1.6s; } }
|
||||
.st-title { font-weight: 600; color: var(--text); }
|
||||
.st-prov { flex: 1; }
|
||||
.st-lat { min-width: 88px; text-align: center; }
|
||||
.st-loading { font-style: italic; }
|
||||
.lat-head { display: flex; align-items: center; gap: 8px; padding: 2px 0 6px; }
|
||||
</style>
|
||||
@@ -0,0 +1,20 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="card">
|
||||
<div class="ph-title">「{{ title }}」页面</div>
|
||||
<div class="ph-sub">该功能在后续里程碑开发(M2 对话 / M3 媒体 / M4 指标日志 等)。</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
const route = useRoute()
|
||||
const title = computed(() => (route.meta.title as string) || '')
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.ph-title { font-size: 18px; font-weight: 600; }
|
||||
.ph-sub { color: var(--muted); margin-top: 8px; }
|
||||
</style>
|
||||
@@ -0,0 +1,324 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<el-alert v-if="err" :title="err" type="error" show-icon :closable="false" class="mb" />
|
||||
|
||||
<div class="set-grid">
|
||||
<!-- 外观与语言:三张主题卡 + 跟随系统 + 语言 -->
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('settings.appearance') }}</b>
|
||||
<span class="sub">{{ t('settings.themeSub') }}</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="id in THEME_IDS"
|
||||
:key="id"
|
||||
class="theme-card"
|
||||
:class="{ on: theme === id }"
|
||||
@click="pickTheme(id)"
|
||||
>
|
||||
<div class="theme-prev">
|
||||
<span class="l" :style="{ background: THEME_META[id].side, borderRight: '1px solid var(--line)' }" />
|
||||
<span class="r" :style="{ background: THEME_META[id].canvas }">
|
||||
<i :style="{ background: THEME_META[id].accent, width: '70%' }" />
|
||||
<i :style="{ background: THEME_META[id].accent, opacity: .35 }" />
|
||||
<i :style="{ background: THEME_META[id].accent, opacity: .2, width: '60%' }" />
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<b>{{ t(THEME_META[id].nameKey) }}</b>
|
||||
<div class="hint">{{ t(THEME_META[id].descKey) }}</div>
|
||||
</div>
|
||||
<span v-if="theme === id" class="pill ok">{{ t('settings.current') }}</span>
|
||||
<span v-else class="chip-sel">{{ t('settings.switch') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="set-row">
|
||||
<div>
|
||||
<div class="lb">{{ t('settings.followSystem') }}</div>
|
||||
<div class="sub">{{ t('settings.followSub') }}</div>
|
||||
</div>
|
||||
<div class="rt">
|
||||
<el-switch :model-value="followSystem" @change="onFollow" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="set-row">
|
||||
<div>
|
||||
<div class="lb">{{ t('settings.language') }}</div>
|
||||
<div class="sub">{{ t('settings.langSub') }}</div>
|
||||
</div>
|
||||
<div class="rt">
|
||||
<el-radio-group :model-value="locale" size="small" @change="onLocale">
|
||||
<el-radio-button value="zh">中文</el-radio-button>
|
||||
<el-radio-button value="en">English</el-radio-button>
|
||||
</el-radio-group>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 生成默认值:新建对话时的初始参数(Chat.vue 读同一份 localStorage) -->
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('settings.chatDefaults') }}</b>
|
||||
<span class="sub">{{ t('settings.defsTip') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="set-row">
|
||||
<div class="lb">{{ t('settings.defaultModel') }}</div>
|
||||
<div class="rt">
|
||||
<el-select v-model="defs.model" size="small" clearable :placeholder="t('chat.routeGroup')" style="width: 210px">
|
||||
<el-option v-for="m in textModels" :key="m" :label="m" :value="m" />
|
||||
</el-select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lb">{{ t('settings.temperature') }}</div>
|
||||
<div class="rt">
|
||||
<el-input-number v-model="defs.temperature" size="small" :min="0" :max="2" :step="0.1" controls-position="right" style="width: 130px" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lb">{{ t('settings.topP') }}</div>
|
||||
<div class="rt">
|
||||
<el-input-number v-model="defs.top_p" size="small" :min="0" :max="1" :step="0.05" controls-position="right" style="width: 130px" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lb">{{ t('settings.maxTokens') }}</div>
|
||||
<div class="rt">
|
||||
<el-input-number v-model="defs.max_tokens" size="small" :min="1" :max="200000" :step="256" controls-position="right" style="width: 150px" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lb">{{ t('settings.streaming') }}</div>
|
||||
<div class="rt">
|
||||
<el-switch v-model="defs.stream" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="set-row" style="align-items: flex-start">
|
||||
<div class="lb flex-1">
|
||||
{{ t('settings.system') }}
|
||||
<el-input v-model="defs.system" type="textarea" :rows="2" class="mt-8" :placeholder="t('chat.system')" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="op-row">
|
||||
<el-button type="primary" size="small" :loading="savingDefs" @click="saveDefs">{{ t('settings.save') }}</el-button>
|
||||
<el-button size="small" @click="resetDefs">{{ t('common.reset') }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="set-grid mt">
|
||||
<!-- 账号与安全 -->
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('settings.account') }}</b>
|
||||
<span class="sub">{{ store.user }}<template v-if="store.isAdmin"> · {{ t('common.admin') }}</template></span>
|
||||
</div>
|
||||
|
||||
<div class="set-row">
|
||||
<div class="flex-1">
|
||||
<div class="lb">{{ t('settings.changePw') }}</div>
|
||||
<div class="sub">{{ t('settings.pwTip') }}</div>
|
||||
</div>
|
||||
<div class="rt">
|
||||
<el-input
|
||||
v-model="pw.new"
|
||||
type="password"
|
||||
show-password
|
||||
size="small"
|
||||
style="width: 150px"
|
||||
:placeholder="t('settings.newPw')"
|
||||
@keyup.enter="savePw"
|
||||
/>
|
||||
<el-button type="primary" size="small" :loading="pw.saving" @click="savePw">{{ t('common.save') }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="set-row">
|
||||
<div class="flex-1">
|
||||
<div class="lb">{{ t('settings.myKeys') }}</div>
|
||||
<div class="sub">{{ t('settings.myKeysSub') }}</div>
|
||||
</div>
|
||||
<div class="rt">
|
||||
<el-button size="small" @click="router.push('/keys')">{{ t('settings.manage') }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="set-row">
|
||||
<div class="flex-1">
|
||||
<div class="lb">{{ t('common.logout') }}</div>
|
||||
<div class="sub">{{ t('settings.logoutTip') }}</div>
|
||||
</div>
|
||||
<div class="rt">
|
||||
<el-button size="small" type="danger" plain @click="doLogout">{{ t('settings.logoutBtn') }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 网关信息:只读快照。真要改网关参数走「网关配置」页(管理员,第二十三轮)。 -->
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('settings.gwCard') }}</b>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lb">{{ t('settings.gwAddress') }}</div>
|
||||
<div class="rt code">{{ base }}</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lb">{{ t('settings.gwVersion') }}</div>
|
||||
<div class="rt">v{{ health.version || '-' }}</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lb">{{ t('settings.sessionLen') }}</div>
|
||||
<div class="rt">{{ store.expiresIn ? t('settings.hours', { n: Math.round(store.expiresIn / 3600) }) : '—' }}</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lb">{{ t('dashboard.inflight') }}</div>
|
||||
<div class="rt">{{ health.in_flight ?? '-' }} / {{ health.in_flight_peak ?? '-' }}</div>
|
||||
</div>
|
||||
<div class="set-row">
|
||||
<div class="lb">{{ t('dashboard.fallback') }}</div>
|
||||
<div class="rt">{{ health.fallback_total ?? 0 }}</div>
|
||||
</div>
|
||||
<div class="set-row" style="align-items: flex-start">
|
||||
<div class="lb">{{ t('settings.providerStatus') }}</div>
|
||||
<div class="rt" style="flex-wrap: wrap; justify-content: flex-end">
|
||||
<span v-for="p in providerRows" :key="p.name" class="pill" :class="p.cls">{{ p.name }} · {{ p.text }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 第二十三轮:管理员从这里跳去改配置(普通账号看不到这个入口);
|
||||
卡片本身也受 `GATEWAY_CONFIG_ENABLED` 管(老板要求暂时隐藏整块配置页)。 -->
|
||||
<div v-if="store.isAdmin && GATEWAY_CONFIG_ENABLED" class="set-row">
|
||||
<div class="flex-1">
|
||||
<div class="lb">{{ t('settings.gwConfig') }}</div>
|
||||
<div class="sub">{{ t('settings.gwConfigSub') }}</div>
|
||||
</div>
|
||||
<div class="rt">
|
||||
<el-button size="small" @click="router.push('/gateway-config')">{{ t('settings.gwConfigBtn') }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, reactive, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { GATEWAY_CONFIG_ENABLED } from '../lib/features'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { computed } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api } from '../api'
|
||||
import { useSessionStore } from '../store/session'
|
||||
import { setLocale } from '../i18n'
|
||||
import { getChatDefaults, setChatDefaults, type ChatDefaults } from '../lib/settings'
|
||||
import { useTheme, THEME_IDS, THEME_META, type ThemeId } from '../lib/theme'
|
||||
|
||||
const router = useRouter()
|
||||
const store = useSessionStore()
|
||||
const base = window.location.origin
|
||||
const health = ref<any>({})
|
||||
const err = ref('')
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
const { theme, followSystem, setTheme, setFollowSystem } = useTheme()
|
||||
|
||||
const TEXT_MODELS = ['wjd', 'agnes-3.0-flash', 'ark-code-latest', 'qwen3.8-flash']
|
||||
const textModels = ref<string[]>(TEXT_MODELS)
|
||||
|
||||
function pickTheme(id: ThemeId) {
|
||||
setTheme(id)
|
||||
ElMessage.success(t('theme.applied') + ' · ' + t(THEME_META[id].nameKey))
|
||||
}
|
||||
function onFollow(v: string | number | boolean) { setFollowSystem(!!v) }
|
||||
function onLocale(l: string) { setLocale(l as 'zh' | 'en') }
|
||||
|
||||
// ── 生成默认值 ──────────────────────────────────────────────
|
||||
const defs = reactive<ChatDefaults>({ temperature: 0.7, top_p: 1, max_tokens: null, stream: true, system: '' })
|
||||
const savingDefs = ref(false)
|
||||
|
||||
function loadDefs() {
|
||||
const d = getChatDefaults()
|
||||
defs.model = d.model ?? 'wjd'
|
||||
defs.temperature = d.temperature ?? 0.7
|
||||
defs.top_p = d.top_p ?? 1
|
||||
defs.max_tokens = d.max_tokens ?? null
|
||||
defs.stream = d.stream !== false
|
||||
defs.system = d.system ?? ''
|
||||
}
|
||||
function saveDefs() {
|
||||
savingDefs.value = true
|
||||
try {
|
||||
setChatDefaults({ ...defs })
|
||||
ElMessage.success(t('settings.saveOk'))
|
||||
} finally {
|
||||
savingDefs.value = false
|
||||
}
|
||||
}
|
||||
function resetDefs() {
|
||||
setChatDefaults({})
|
||||
loadDefs()
|
||||
ElMessage.success(t('settings.resetOk'))
|
||||
}
|
||||
|
||||
// ── 账号 ────────────────────────────────────────────────────
|
||||
const pw = reactive({ new: '', saving: false })
|
||||
|
||||
// 已登录会话直接设新密码(老板要求免输旧密码),改完所有会话失效
|
||||
async function savePw() {
|
||||
if (!pw.new) { ElMessage.warning(t('settings.pwNeedNew')); return }
|
||||
pw.saving = true
|
||||
try {
|
||||
await api('/auth/password', { method: 'POST', body: JSON.stringify({ new_password: pw.new }) })
|
||||
ElMessage.success(t('settings.pwChanged'))
|
||||
pw.new = ''
|
||||
await store.logout()
|
||||
router.push('/login')
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.body?.detail || (e && e.message) || String(e))
|
||||
} finally {
|
||||
pw.saving = false
|
||||
}
|
||||
}
|
||||
|
||||
async function doLogout() {
|
||||
await store.logout()
|
||||
router.push('/login')
|
||||
}
|
||||
|
||||
const providerRows = computed(() => {
|
||||
const p = health.value.providers || {}
|
||||
return Object.keys(p).map((k) => {
|
||||
const c = String(p[k].circuit || '').toUpperCase()
|
||||
const cls = c === 'CLOSED' ? 'ok' : c === 'HALF_OPEN' ? 'warn' : c === 'OPEN' ? 'err' : 'mute'
|
||||
return { name: p[k].name, cls, text: t(`dashboard.circ_${String(p[k].circuit || '').toLowerCase() || ''}`) }
|
||||
})
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
loadDefs()
|
||||
try {
|
||||
health.value = await api('/health')
|
||||
// 默认模型下拉用真实模型列表(拿不到就退回内置候选)
|
||||
try {
|
||||
const um = await api('/v1/models')
|
||||
const list = (um.data || []).filter((x: any) => x.type !== 'route').map((x: any) => x.id)
|
||||
if (list.length) textModels.value = ['wjd', ...list]
|
||||
} catch { /* 模型列表可选 */ }
|
||||
} catch (e: any) {
|
||||
if (e && e.status === 401) { router.push('/login'); return }
|
||||
err.value = t('settings.loadErr') + ': ' + ((e && e.message) || String(e))
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mt { margin-top: var(--gap); }
|
||||
.mt-8 { margin-top: 8px; }
|
||||
.op-row { display: flex; gap: 8px; margin-top: 14px; }
|
||||
</style>
|
||||
@@ -0,0 +1,446 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('settings.account') }}</b>
|
||||
<span class="sub">{{ users.length }} · {{ t('nav.subusers') }}</span>
|
||||
<div class="pager">
|
||||
<el-input v-model="q" size="small" class="search-inp" clearable :placeholder="t('common.search')">
|
||||
<template #prefix><Icon name="search" :size="14" /></template>
|
||||
</el-input>
|
||||
<el-button type="primary" size="small" @click="showCreate = true">
|
||||
<Icon name="plus" :size="14" />
|
||||
<span>{{ t('settings.createUser') }}</span>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-table
|
||||
v-if="users.length"
|
||||
:data="shown"
|
||||
size="default"
|
||||
row-key="name"
|
||||
:row-class-name="rowClass"
|
||||
:expand-row-keys="expanded"
|
||||
:empty-text="t('users.noData')"
|
||||
@expand-change="onExpand"
|
||||
>
|
||||
<el-table-column type="expand">
|
||||
<template #default="{ row }">
|
||||
<!-- 第十一轮 #2:admin 在此看该账号的调用日志 + 生成的图像/视频资产 -->
|
||||
<div class="expand-row" v-loading="act(row.name).loading">
|
||||
<el-tabs v-model="act(row.name).tab">
|
||||
<el-tab-pane :label="t('users.tabLogs')" name="logs">
|
||||
<el-table :data="act(row.name).logs" size="small" max-height="360"
|
||||
:empty-text="t('users.noData')">
|
||||
<el-table-column :label="t('logs.time')" width="92">
|
||||
<template #default="{ row: e }"><span class="code">{{ fmtClock(e.ts) }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('logs.result')" width="66">
|
||||
<template #default="{ row: e }">
|
||||
<el-tag :type="e.ok ? 'success' : 'danger'" size="small">{{ e.ok ? t('common.ok') : t('common.fail') }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('logs.path')" min-width="160">
|
||||
<template #default="{ row: e }"><span class="code">{{ e.method }} {{ e.path }}</span></template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('logs.modelProvider')" min-width="140">
|
||||
<template #default="{ row: e }">
|
||||
<span class="code">{{ e.served || e.model || '—' }}</span>
|
||||
<span v-if="e.provider" class="at-prov">@ {{ e.provider }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('logs.respContent')" min-width="220">
|
||||
<template #default="{ row: e }">
|
||||
<span v-if="e.response" class="ellip" :title="e.response">{{ e.response }}</span>
|
||||
<span v-else-if="!e.ok" class="err-text ellip" :title="e.error">{{ e.error || '—' }}</span>
|
||||
<span v-else class="muted">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-tab-pane>
|
||||
|
||||
<el-tab-pane :label="`${t('users.tabImages')} (${act(row.name).images.length})`" name="images">
|
||||
<div v-if="act(row.name).images.length" class="asset-grid">
|
||||
<div v-for="im in act(row.name).images" :key="im.id" class="asset-cell">
|
||||
<el-image :src="im.src" fit="cover" class="asset-thumb"
|
||||
:preview-src-list="act(row.name).images.map((x: any) => x.src).filter(Boolean)" :initial-index="0" preview-teleported />
|
||||
<div class="asset-cap ellip3" :title="im.prompt">{{ im.prompt || '—' }}</div>
|
||||
<div class="asset-meta code ellip">{{ im.served || im.model || '' }} · {{ fmtClock((im.ts || 0) / 1000) }}</div>
|
||||
<!-- 管理员代下载他人资产:产物在跨域 CDN 上,直链 <a download> 不生效,
|
||||
统一走后端 /v1/media/download 代拉,与图像/视频页同一个 lib/download.ts。 -->
|
||||
<el-button size="small" class="asset-dl"
|
||||
:loading="dlKey === 'i-' + im.id"
|
||||
@click="dlAsset(im.src, im.prompt, 'image', 'i-' + im.id)">
|
||||
<Icon name="dl" :size="14" />{{ t('users.dl') }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<el-empty v-else :image-size="60" :description="t('users.noData')" />
|
||||
</el-tab-pane>
|
||||
|
||||
<el-tab-pane :label="`${t('users.tabVideos')} (${act(row.name).videos.length})`" name="videos">
|
||||
<div v-if="act(row.name).videos.length" class="asset-grid">
|
||||
<div v-for="vk in act(row.name).videos" :key="vk.id" class="asset-cell">
|
||||
<video v-if="vk.src" :src="vk.src" class="asset-thumb" controls preload="metadata" />
|
||||
<div v-else class="asset-thumb video-ph">
|
||||
<el-tag :type="vk.kind === 'fail' ? 'danger' : vk.kind === 'done' ? 'success' : 'info'" size="small">{{ vk.status || vk.kind }}</el-tag>
|
||||
</div>
|
||||
<div class="asset-cap ellip3" :title="vk.prompt">{{ vk.prompt || '—' }}</div>
|
||||
<div class="asset-meta code ellip">{{ vk.model || '' }} · {{ vk.elapsed ? vk.elapsed + 's' : '' }}</div>
|
||||
<el-button v-if="vk.src" size="small" class="asset-dl"
|
||||
:loading="dlKey === 'v-' + vk.id"
|
||||
@click="dlAsset(vk.src, vk.prompt, 'video', 'v-' + vk.id)">
|
||||
<Icon name="dl" :size="14" />{{ t('users.dl') }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<el-empty v-else :image-size="60" :description="t('users.noData')" />
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column :label="t('settings.userCol')" :min-width="isMobile ? 120 : 150">
|
||||
<template #default="{ row }">
|
||||
<div class="acc">
|
||||
<span class="avatar" :class="{ alt: row.name !== store.user }">{{ initial(row.name) }}</span>
|
||||
<span class="acc-nm">{{ row.name }}</span>
|
||||
<!-- 第二十四轮: 停用状态贴在账号名后(桌面/手机都看得见),悬停显示停用时间 -->
|
||||
<span v-if="row.disabled" class="pill warn" :title="row.disabled_at ? t('settings.userDisabledAt', { ts: fmtTs(row.disabled_at) }) : ''">
|
||||
{{ t('settings.userDisabled') }}
|
||||
</span>
|
||||
</div>
|
||||
<!-- 第十八轮: 手机上把「角色 / Key 数 / 创建时间」三列收进账号单元格,
|
||||
否则五列总宽 937px 在 390 屏上必须横滑,操作列根本看不到。 -->
|
||||
<div v-if="isMobile" class="acc-sub">
|
||||
<span class="pill" :class="row.role === 'admin' ? 'ok' : 'mute'">{{ row.role }}</span>
|
||||
<span class="nowrap muted">{{ row.api_key_count }} / {{ keyLimitText(row.role) }} {{ t('settings.keyCount') }}</span>
|
||||
<span v-if="atKeyLimit(row)" class="pill warn">{{ t('settings.keyLimitFull') }}</span>
|
||||
<span class="nowrap muted">{{ fmtTs(row.created) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column v-if="!isMobile" :label="t('settings.roleCol')" width="104">
|
||||
<template #default="{ row }">
|
||||
<span class="pill" :class="row.role === 'admin' ? 'ok' : 'mute'">{{ row.role }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<!-- Key 数:admin 不限,普通账号与后端 MAX_KEYS_PER_MEMBER 一致(3 把) -->
|
||||
<el-table-column v-if="!isMobile" :label="t('settings.keyCount')" width="136">
|
||||
<template #default="{ row }">
|
||||
<span class="nowrap">{{ row.api_key_count }} / {{ keyLimitText(row.role) }}</span>
|
||||
<span v-if="atKeyLimit(row)" class="pill warn">{{ t('settings.keyLimitFull') }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column v-if="!isMobile" :label="t('settings.userCreated')" width="150">
|
||||
<template #default="{ row }"><span class="nowrap muted">{{ fmtTs(row.created) }}</span></template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column :min-width="isMobile ? 152 : 320" align="right">
|
||||
<!-- 第十八轮: 手机上操作列改图标按钮(文字版四颗要 ~320px,必然被挤出屏外) -->
|
||||
<template #default="{ row }">
|
||||
<div v-if="isMobile" class="ops">
|
||||
<el-tooltip :content="t('settings.resetPw')" placement="top">
|
||||
<el-button text type="primary" size="small" @click="resetPw(row.name)"><Icon name="key" :size="16" /></el-button>
|
||||
</el-tooltip>
|
||||
<!-- 管理员账号不可停用(唯一管理员被停用就没人能进管理页),故 admin 不给这颗按钮 -->
|
||||
<el-tooltip v-if="row.role !== 'admin'" :content="row.disabled ? t('settings.enableUser') : t('settings.disableUser')" placement="top">
|
||||
<el-button text :type="row.disabled ? 'success' : 'warning'" size="small" @click="toggleDisabled(row)">
|
||||
<Icon :name="row.disabled ? 'play' : 'ban'" :size="16" />
|
||||
</el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip :content="t('users.viewActivity')" placement="top">
|
||||
<el-button text size="small" @click="toggleActivity(row)"><Icon name="log" :size="16" /></el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip :content="t('settings.revokeKeys')" placement="top">
|
||||
<el-button text type="warning" size="small" :disabled="!row.api_key_count" @click="revokeKeys(row.name)"><Icon name="stop" :size="16" /></el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip v-if="row.name !== store.user" :content="t('common.delete')" placement="top">
|
||||
<el-button text type="danger" size="small" @click="remove(row.name)"><Icon name="trash" :size="16" /></el-button>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
<template v-else>
|
||||
<el-button text type="primary" size="small" @click="resetPw(row.name)">{{ t('settings.resetPw') }}</el-button>
|
||||
<!-- 第二十四轮: 停用/启用。停用后该账号不能登录、名下 API Key 一并失效,
|
||||
所以停用要二次确认;启用是无风险操作,点了就生效 -->
|
||||
<el-button v-if="row.role !== 'admin'" text :type="row.disabled ? 'success' : 'warning'" size="small"
|
||||
@click="toggleDisabled(row)">
|
||||
{{ row.disabled ? t('settings.enableUser') : t('settings.disableUser') }}
|
||||
</el-button>
|
||||
<el-button text size="small" @click="toggleActivity(row)">{{ t('users.viewActivity') }}</el-button>
|
||||
<el-button text type="warning" size="small" :disabled="!row.api_key_count" @click="revokeKeys(row.name)">
|
||||
{{ t('settings.revokeKeys') }}
|
||||
</el-button>
|
||||
<el-button v-if="row.name !== store.user" text type="danger" size="small" @click="remove(row.name)">
|
||||
{{ t('common.delete') }}
|
||||
</el-button>
|
||||
</template>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-empty v-else :description="t('common.none')" :image-size="80" />
|
||||
</div>
|
||||
|
||||
<!-- 新建账号:账号名 + 可选初始密码(与旧版行内输入等价,只是收进弹层) -->
|
||||
<el-dialog v-model="showCreate" :title="t('settings.createUser')" width="420px">
|
||||
<div class="field">
|
||||
<label>{{ t('settings.newUserName') }}</label>
|
||||
<el-input v-model="newUser" :placeholder="t('settings.newUserName')" clearable @keyup.enter="create" />
|
||||
</div>
|
||||
<div class="field dialog-f2">
|
||||
<label>{{ t('settings.userPwOptional') }}</label>
|
||||
<el-input v-model="newPw" type="password" show-password clearable
|
||||
:placeholder="t('settings.userPwOptional')" @keyup.enter="create" />
|
||||
</div>
|
||||
<div class="hint">{{ t('settings.newUserTip') }}</div>
|
||||
<template #footer>
|
||||
<el-button size="small" @click="showCreate = false">{{ t('common.cancel') }}</el-button>
|
||||
<el-button type="primary" size="small" :loading="creating" @click="create">{{ t('settings.createUser') }}</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { api, errText } from '../api'
|
||||
import Icon from '../components/Icon.vue'
|
||||
import { downloadMedia, nameFromPrompt, stamp } from '../lib/download'
|
||||
import { useIsMobile } from '../lib/ui'
|
||||
import { useSessionStore } from '../store/session'
|
||||
|
||||
const { t } = useI18n()
|
||||
const store = useSessionStore()
|
||||
// 第十八轮: 窄屏把「角色/Key 数/创建时间」三列折进账号单元格、操作列改图标按钮,
|
||||
// 目的是让这张表在 390 宽下不用横滑(此前列总宽 937px,操作列在屏外)。
|
||||
const { isMobile } = useIsMobile()
|
||||
const users = ref<any[]>([])
|
||||
const newUser = ref('')
|
||||
const newPw = ref('')
|
||||
const creating = ref(false)
|
||||
const showCreate = ref(false)
|
||||
const q = ref('')
|
||||
|
||||
// 与 app/users.py 的 MAX_KEYS_PER_MEMBER / key_limit_for_role 对齐,仅用于展示 n / 3
|
||||
const MEMBER_KEY_LIMIT = 3
|
||||
|
||||
// 停用的账号整行压暗一点(一眼能看出哪些不能用了),但内容照常可读 —— 不是隐藏
|
||||
function rowClass({ row }: any): string {
|
||||
return row?.disabled ? 'row-off' : ''
|
||||
}
|
||||
|
||||
function keyLimitText(role: string): string {
|
||||
return role === 'admin' ? '∞' : String(MEMBER_KEY_LIMIT)
|
||||
}
|
||||
function atKeyLimit(row: any): boolean {
|
||||
return row.role !== 'admin' && Number(row.api_key_count || 0) >= MEMBER_KEY_LIMIT
|
||||
}
|
||||
function initial(name: string): string {
|
||||
return String(name || '?').slice(0, 1).toUpperCase()
|
||||
}
|
||||
|
||||
// ── 资产下载(管理员代下载他人生成的图/视频)──
|
||||
// 与图像页/视频页同一条路:产物在跨域 CDN 上(无 CORS 头、<a download> 对跨域无效),
|
||||
// 所以走后端 /v1/media/download 代拉再落盘;文件名用「提示词前缀 + 时间戳」。
|
||||
const dlKey = ref<string>('')
|
||||
async function dlAsset(src: string, prompt: string, kind: 'image' | 'video', key: string) {
|
||||
if (!src) { ElMessage.error(t('users.dlNoSrc')); return }
|
||||
dlKey.value = key
|
||||
try {
|
||||
await downloadMedia(src, `${nameFromPrompt(prompt, kind)}-${stamp()}`)
|
||||
ElMessage.success(t('users.dlOk'))
|
||||
} catch (e: any) {
|
||||
ElMessage.error(t('users.dlFail', { msg: e?.message || String(e) }))
|
||||
} finally {
|
||||
dlKey.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
// 搜索只过滤本页已加载的账号列表(不发新请求)
|
||||
const shown = computed(() => {
|
||||
const s = q.value.trim().toLowerCase()
|
||||
if (!s) return users.value
|
||||
return users.value.filter((u) => String(u.name || '').toLowerCase().includes(s))
|
||||
})
|
||||
|
||||
// 每个账号的活动数据(日志 + 图像 + 视频),展开时懒加载一次
|
||||
type Activity = { loading: boolean; loaded: boolean; tab: string; logs: any[]; images: any[]; videos: any[] }
|
||||
const activity = reactive<Record<string, Activity>>({})
|
||||
function act(name: string): Activity {
|
||||
if (!activity[name]) {
|
||||
activity[name] = { loading: false, loaded: false, tab: 'logs', logs: [], images: [], videos: [] }
|
||||
}
|
||||
return activity[name]
|
||||
}
|
||||
const expanded = ref<string[]>([])
|
||||
|
||||
function fmtTs(ts: number): string {
|
||||
if (!ts) return '—'
|
||||
const d = new Date(ts * 1000)
|
||||
const p = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
||||
}
|
||||
function fmtClock(ts: number): string {
|
||||
if (!ts) return '—'
|
||||
const d = new Date(ts * 1000)
|
||||
const p = (n: number) => String(n).padStart(2, '0')
|
||||
return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
|
||||
}
|
||||
|
||||
function err(e: any) {
|
||||
return errText(e) // 统一从 {error:{message}} / {detail} 两种信封里取原因(见 api.ts)
|
||||
}
|
||||
|
||||
async function ask(text: string) {
|
||||
try {
|
||||
await ElMessageBox.confirm(text, t('settings.confirm'), { type: 'warning' })
|
||||
return true
|
||||
} catch { return false }
|
||||
}
|
||||
|
||||
async function loadActivity(name: string) {
|
||||
const a = act(name)
|
||||
if (a.loaded) return
|
||||
a.loading = true
|
||||
try {
|
||||
const [lg, im, vd] = await Promise.all([
|
||||
api(`/auth/users/${encodeURIComponent(name)}/logs?n=200`),
|
||||
api(`/auth/users/${encodeURIComponent(name)}/history/images`),
|
||||
api(`/auth/users/${encodeURIComponent(name)}/history/videos`),
|
||||
])
|
||||
a.logs = lg.entries || []
|
||||
a.images = im.items || []
|
||||
a.videos = vd.items || []
|
||||
a.loaded = true
|
||||
} catch (e: any) {
|
||||
ElMessage.error(err(e))
|
||||
} finally { a.loading = false }
|
||||
}
|
||||
|
||||
async function onExpand(row: any, expandedRows: any) {
|
||||
const isOpen = Array.isArray(expandedRows) ? expandedRows.includes(row) : !!expandedRows
|
||||
expanded.value = isOpen ? [row.name] : expanded.value.filter((k) => k !== row.name)
|
||||
if (isOpen) await loadActivity(row.name)
|
||||
}
|
||||
|
||||
// 行内「查看活动」按钮:复用同一个展开回调(展开态仍由 expanded 驱动)
|
||||
function toggleActivity(row: any) {
|
||||
onExpand(row, !expanded.value.includes(row.name))
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try { users.value = (await api('/auth/users')).users || [] } catch (e: any) { ElMessage.error(err(e)) }
|
||||
}
|
||||
|
||||
async function create() {
|
||||
const name = newUser.value.trim()
|
||||
if (!name) return
|
||||
creating.value = true
|
||||
try {
|
||||
const body: any = { username: name }
|
||||
if (newPw.value) body.password = newPw.value
|
||||
await api('/auth/users', { method: 'POST', body: JSON.stringify(body) })
|
||||
ElMessage.success(t('settings.createUser') + ': ' + name)
|
||||
newUser.value = ''
|
||||
newPw.value = ''
|
||||
showCreate.value = false
|
||||
await load()
|
||||
} catch (e: any) { ElMessage.error(err(e)) }
|
||||
finally { creating.value = false }
|
||||
}
|
||||
|
||||
async function resetPw(name: string) {
|
||||
if (!await ask(t('settings.confirmResetPw', { name }))) return
|
||||
try {
|
||||
const j = await api(`/auth/users/${name}/password`, { method: 'POST', body: JSON.stringify({}) })
|
||||
ElMessage.success(t('settings.resetPwOk', { name, n: j.revoked_sessions ?? 0 }))
|
||||
await load()
|
||||
} catch (e: any) { ElMessage.error(err(e)) }
|
||||
}
|
||||
|
||||
// 第二十四轮: 停用 / 启用账号(PUT /auth/users/{name}/disabled)
|
||||
// 停用后该账号 ①不能登录(密码正确也拒,服务端回 403 说明原因);②名下 API Key 立即失效
|
||||
// (Key 记录不删,重新启用即恢复);③已登录会话被立即踢掉。故停用要二次确认。
|
||||
async function toggleDisabled(row: any) {
|
||||
const name = String(row.name)
|
||||
const off = !row.disabled // off=true 表示本次要「停用」
|
||||
if (off && !await ask(t('settings.confirmDisableUser', { name }))) return
|
||||
try {
|
||||
const j = await api(`/auth/users/${encodeURIComponent(name)}/disabled`, {
|
||||
method: 'PUT', body: JSON.stringify({ disabled: off }),
|
||||
})
|
||||
if (j.disabled) ElMessage.success(t('settings.userDisabledOk', { name, n: j.revoked_sessions ?? 0 }))
|
||||
else ElMessage.success(t('settings.userEnabledOk', { name }))
|
||||
await load()
|
||||
} catch (e: any) { ElMessage.error(err(e)) }
|
||||
}
|
||||
|
||||
async function revokeKeys(name: string) {
|
||||
if (!await ask(t('settings.confirmRevokeKeys', { name }))) return
|
||||
try {
|
||||
const j = await api(`/auth/users/${name}/apikeys`, { method: 'DELETE' })
|
||||
ElMessage.success(t('settings.revokeKeysOk', { name, n: j.revoked_keys ?? 0 }))
|
||||
await load()
|
||||
} catch (e: any) { ElMessage.error(err(e)) }
|
||||
}
|
||||
|
||||
async function remove(name: string) {
|
||||
if (!await ask(t('settings.confirmDeleteUser', { name }))) return
|
||||
try {
|
||||
const j = await api(`/auth/users/${name}`, { method: 'DELETE' })
|
||||
ElMessage.success(t('settings.accountDeleted', { name, n: j.revoked_sessions ?? 0 }))
|
||||
delete activity[name]
|
||||
await load()
|
||||
} catch (e: any) { ElMessage.error(err(e)) }
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.search-inp { width: 180px; }
|
||||
.acc { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.acc-nm { color: var(--text); }
|
||||
/* 第二十四轮: 停用账号的名字压暗(状态靠旁边的「已停用」胶囊点明) */
|
||||
.row-off :deep(.acc-nm) { color: var(--muted-2); }
|
||||
/* 第十八轮: 手机端账号单元格的第二行(角色 / Key 数 / 创建时间) */
|
||||
.acc-sub { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 5px; font-size: 11.5px; }
|
||||
/* 手机端操作列:图标按钮一行排开,去掉 Element 相邻按钮的 12px 左边距。
|
||||
第二十四轮加「停用/启用」后这里变成 5 颗图标 —— 留 flex-wrap:万一某台机器上按钮宽
|
||||
超出操作列(152px)就换行,绝不让表格被撑宽、把操作列挤出屏外(第十八轮的老毛病)。 */
|
||||
.ops { display: flex; align-items: center; gap: 2px; row-gap: 2px; flex-wrap: wrap; justify-content: flex-end; }
|
||||
.ops :deep(.el-button + .el-button) { margin-left: 0; }
|
||||
.ops :deep(.el-button) { padding: 6px; }
|
||||
.at-prov { color: var(--muted-2); margin-left: 4px; font-size: 11px; }
|
||||
.err-text { color: var(--err); }
|
||||
.ellip { display: inline-block; max-width: 360px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: bottom; }
|
||||
.ellip3 {
|
||||
font-size: 12px; color: var(--text); line-height: 1.4;
|
||||
display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical;
|
||||
overflow: hidden; word-break: break-all;
|
||||
}
|
||||
.asset-grid { display: flex; flex-wrap: wrap; gap: 12px; }
|
||||
.asset-cell { width: 150px; }
|
||||
.asset-thumb {
|
||||
width: 150px; height: 110px; border-radius: 8px; display: block;
|
||||
background: var(--chip); border: 1px solid var(--line); object-fit: cover;
|
||||
}
|
||||
.video-ph { display: flex; align-items: center; justify-content: center; }
|
||||
.asset-cap { margin-top: 4px; }
|
||||
.asset-meta { color: var(--muted-2); margin-top: 2px; }
|
||||
/* 下载按钮放卡片底部整行(与图像/视频页一致),不做缩略图上的浮层:手机端不会挤变形 */
|
||||
.asset-dl { width: 100%; margin-top: 6px; }
|
||||
.dialog-f2 { margin-top: 12px; }
|
||||
.dialog-f2 + .hint { margin-top: 10px; }
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.search-inp { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,720 @@
|
||||
<template>
|
||||
<div class="page-fill">
|
||||
<div class="img-layout">
|
||||
<!-- 左:参数(固定 320px;窄屏自动落到上方单列) -->
|
||||
<div class="card param-card">
|
||||
<div class="field mb-field">
|
||||
<label>{{ t('videos.model') }}</label>
|
||||
<el-select v-model="model" filterable class="fill">
|
||||
<el-option v-for="m in models" :key="m.id" :value="m.id" :label="`${m.id} · ${m.provider_name}`" />
|
||||
</el-select>
|
||||
</div>
|
||||
|
||||
<!-- 第十一轮 #3:场景模式(对齐 Agnes Video 契约 text/keyframe/reference) -->
|
||||
<div class="field mb-field">
|
||||
<label>{{ t('videos.mode') }}</label>
|
||||
<div class="modes">
|
||||
<div class="mode" :class="{ on: mode === 'text' }" @click="mode = 'text'">
|
||||
{{ t('videos.modeText') }}<span class="mode-sub">text</span>
|
||||
</div>
|
||||
<div class="mode" :class="{ on: mode === 'keyframe' }" @click="mode = 'keyframe'">
|
||||
{{ t('videos.modeKeyframe') }}<span class="mode-sub">keyframe</span>
|
||||
</div>
|
||||
<div class="mode" :class="{ on: mode === 'reference' }" @click="mode = 'reference'">
|
||||
{{ t('videos.modeReference') }}<span class="mode-sub">reference</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row mb-field">
|
||||
<div class="field">
|
||||
<label>{{ t('videos.duration') }}</label>
|
||||
<!-- Agnes Video 2.5 Flash 文档: seconds 支持 "4"~"12"(3s 会被拒),默认 5 -->
|
||||
<el-select v-model="seconds" class="fill">
|
||||
<el-option v-for="s in durationOptions" :key="s" :value="String(s)" :label="`${s}s`" />
|
||||
</el-select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t('videos.quality') }}</label>
|
||||
<!-- Flash 固定 720P(文档「size 仅支持字符串 720P」,其它值 HTTP 400)—— 只读展示 -->
|
||||
<div class="ctl dim">720P<span class="dim-tag">{{ t('videos.fixed') }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-row mb-field">
|
||||
<div class="field">
|
||||
<label>{{ t('videos.aspect') }}</label>
|
||||
<el-select v-model="aspect" class="fill">
|
||||
<el-option v-for="a in ['21:9', '16:9', '4:3', '1:1', '3:4', '9:16']" :key="a" :value="a" :label="a" />
|
||||
</el-select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t('videos.seed') }}</label>
|
||||
<el-input-number v-model="seed" :min="0" :max="4294967295" :controls="false"
|
||||
:placeholder="t('videos.seedPH')" class="fill" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field mb-field">
|
||||
<label>{{ t('videos.promptRow') }}</label>
|
||||
<el-input v-model="prompt" type="textarea" :rows="3" resize="none" :placeholder="promptPlaceholder" :disabled="creating" />
|
||||
</div>
|
||||
|
||||
<!-- 第十三轮:首尾帧 / 参考素材 —— 支持直接上传(浏览器内压缩成 data URI),也支持粘 URL -->
|
||||
<div v-if="mode === 'keyframe'" class="field mb-field">
|
||||
<label>{{ t('videos.modeKeyframe') }}</label>
|
||||
<input ref="frameEl" type="file" accept="image/*" class="hide-file" @change="onFrameFiles" />
|
||||
|
||||
<div class="slot-row">
|
||||
<span class="slot-lb">{{ t('videos.firstFrame') }}</span>
|
||||
<el-button size="small" :disabled="creating" @click="pickFrame('first')">
|
||||
<Icon name="up" :size="14" />{{ t('videos.upload') }}
|
||||
</el-button>
|
||||
<el-input v-model="firstUrl" size="small" :placeholder="t('videos.urlPH')" clearable class="slot-u" />
|
||||
</div>
|
||||
<div v-if="firstSlot" class="slot-file" :title="firstSlot.name">
|
||||
<img :src="firstSlot.thumb || firstSlot.uri" alt="" />
|
||||
<span class="slot-name">{{ firstSlot.name }}</span>
|
||||
<span class="rm" @click="firstSlot = null"><Icon name="x" :size="11" /></span>
|
||||
</div>
|
||||
|
||||
<div class="slot-row">
|
||||
<span class="slot-lb">{{ t('videos.lastFrame') }}</span>
|
||||
<el-button size="small" :disabled="creating" @click="pickFrame('last')">
|
||||
<Icon name="up" :size="14" />{{ t('videos.upload') }}
|
||||
</el-button>
|
||||
<el-input v-model="lastUrl" size="small" :placeholder="t('videos.urlPH')" clearable class="slot-u" />
|
||||
</div>
|
||||
<div v-if="lastSlot" class="slot-file" :title="lastSlot.name">
|
||||
<img :src="lastSlot.thumb || lastSlot.uri" alt="" />
|
||||
<span class="slot-name">{{ lastSlot.name }}</span>
|
||||
<span class="rm" @click="lastSlot = null"><Icon name="x" :size="11" /></span>
|
||||
</div>
|
||||
|
||||
<div class="hint tip">{{ t('videos.keyframeTip') }}</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="mode === 'reference'" class="field mb-field">
|
||||
<label>{{ t('videos.modeReference') }}</label>
|
||||
<input ref="refImgEl" type="file" accept="image/*" multiple class="hide-file" @change="onRefImages" />
|
||||
<input ref="refAudEl" type="file" :accept="audioAccept" multiple class="hide-file" @change="onRefAudios" />
|
||||
|
||||
<div class="ref-btns">
|
||||
<el-button size="small" :disabled="creating" @click="refImgEl?.click()">
|
||||
<Icon name="up" :size="14" />{{ t('videos.uploadImg') }}
|
||||
</el-button>
|
||||
<el-button size="small" @click="showRefImgUrl = !showRefImgUrl">
|
||||
<Icon name="link" :size="14" />{{ t('videos.useUrl') }}
|
||||
</el-button>
|
||||
<span class="hint nowrap">{{ t('videos.count5', { n: refImgs.length }) }}</span>
|
||||
</div>
|
||||
<div v-if="refImgs.length" class="ref-thumbs">
|
||||
<div v-for="(r, i) in refImgs" :key="i" class="ref-thumb" :title="`${r.name} · ${formatBytes(dataUriBytes(r.uri))}`">
|
||||
<img :src="r.thumb || r.uri" alt="" />
|
||||
<span class="rm" @click="refImgs.splice(i, 1)"><Icon name="x" :size="11" /></span>
|
||||
<span class="rn">{{ i + 1 }}. {{ r.name }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<el-input v-if="showRefImgUrl" v-model="refImgUrls" type="textarea" :rows="2" resize="none"
|
||||
:placeholder="t('videos.refImagesPH')" :disabled="creating" class="ref-urls" />
|
||||
|
||||
<div class="ref-btns mt6">
|
||||
<el-button size="small" :disabled="creating" @click="refAudEl?.click()">
|
||||
<Icon name="up" :size="14" />{{ t('videos.uploadAudio') }}
|
||||
</el-button>
|
||||
<el-button size="small" @click="showRefAudUrl = !showRefAudUrl">
|
||||
<Icon name="link" :size="14" />{{ t('videos.useUrl') }}
|
||||
</el-button>
|
||||
<span class="hint nowrap">{{ t('videos.count3', { n: refAuds.length }) }}</span>
|
||||
</div>
|
||||
<div v-if="refAuds.length" class="ref-thumbs">
|
||||
<div v-for="(a, i) in refAuds" :key="i" class="ref-aud" :title="a.name">
|
||||
<Icon name="clip" :size="14" class="au-ico" />
|
||||
<span class="rn">{{ i + 1 }}. {{ a.name }} · {{ formatBytes(a.bytes) }}</span>
|
||||
<span class="rm" @click="refAuds.splice(i, 1)"><Icon name="x" :size="11" /></span>
|
||||
</div>
|
||||
</div>
|
||||
<el-input v-if="showRefAudUrl" v-model="refAudUrls" type="textarea" :rows="2" resize="none"
|
||||
:placeholder="t('videos.refAudiosPH')" :disabled="creating" class="ref-urls" />
|
||||
|
||||
<div class="hint tip">{{ t('videos.referenceTip') }}</div>
|
||||
<div class="hint tip">{{ t('videos.uploadTip') }}</div>
|
||||
</div>
|
||||
|
||||
<div class="field async-row">
|
||||
<el-checkbox v-model="stream" :disabled="creating">{{ t('videos.async') }}</el-checkbox>
|
||||
</div>
|
||||
|
||||
<div class="param-foot">
|
||||
<el-alert v-if="err" :title="err" type="error" show-icon :closable="false" class="err-alert" />
|
||||
<el-button type="primary" class="go-btn" :loading="creating" :disabled="!prompt.trim()" @click="create">
|
||||
<Icon name="vid" :size="15" />{{ t('videos.generate') }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右:任务列表(卡片自己撑满,滚动只发生在任务区) -->
|
||||
<div class="card result-card">
|
||||
<div class="card-h">
|
||||
<b>{{ t('videos.taskTitle') }}</b>
|
||||
<span class="sub">{{ t('videos.taskCount', { n: tasks.length }) }}</span>
|
||||
<div class="pager">
|
||||
<span class="chip-sel" :class="{ on: filter === 'all' }" @click="filter = 'all'">{{ t('common.all') }}</span>
|
||||
<span class="chip-sel" :class="{ on: filter === 'doing' }" @click="filter = 'doing'">{{ t('videos.doingText') }}</span>
|
||||
<span class="chip-sel" :class="{ on: filter === 'done' }" @click="filter = 'done'">{{ t('videos.doneText') }}</span>
|
||||
<el-button size="small" class="nowrap" :disabled="!doneCount" @click="clearDone">{{ t('videos.clear') }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="task-list">
|
||||
<!-- 第十九轮版式:左 16:9 缩略图 + 右三行紧凑信息(标题/状态 · 摘要行 · 任务号+操作)。
|
||||
原来是「小缩略图 + 5 行 key/value + 折叠栏 + 单占一行的按钮」,卡片被撑到 228px,
|
||||
缩略图下面空出 140px,看着散;状态还在胶囊(上游英文 completed)和正文(已生成)里说了两遍。 -->
|
||||
<div v-for="tk in shownTasks" :key="tk.id" class="vid-card" :class="'k-' + tk.kind">
|
||||
<div class="vid-thumb">
|
||||
<video v-if="tk.src" :src="tk.src" controls preload="metadata" class="vid-el" :poster="tk.poster || undefined"></video>
|
||||
<span v-else-if="tk.kind === 'pending'" class="spinner"></span>
|
||||
<Icon v-else :name="tk.kind === 'fail' ? 'x' : 'play'" :size="22" />
|
||||
</div>
|
||||
|
||||
<div class="vid-body">
|
||||
<div class="vid-head">
|
||||
<b class="t" :title="tk.prompt">{{ tk.prompt || tk.video_id }}</b>
|
||||
<span class="pill" :class="pillCls(tk.kind)">{{ stateShort(tk) }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 摘要行:服务 · 耗时/等待 · 场景 挤成一行;失败时这里就是失败原因(原来藏在折叠里) -->
|
||||
<div class="s" :class="{ 's-err': tk.kind === 'fail' }" :title="tk.kind === 'fail' ? (tk.error || '') : ''">
|
||||
{{ subLine(tk) }}
|
||||
</div>
|
||||
<div v-if="tk.refs" class="s refs" :title="tk.refs">{{ tk.refs }}</div>
|
||||
|
||||
<!-- 进度条只在「生成中」出现:已完成的满格绿条 / 失败的红条像一条卡片分隔线,纯噪声 -->
|
||||
<div v-if="tk.kind === 'pending'" class="progress"><i class="bar-wait" /></div>
|
||||
|
||||
<div class="vid-foot">
|
||||
<span class="vid-k">{{ t('videos.task') }}</span>
|
||||
<span class="vid-id code" :title="tk.video_id">{{ tk.video_id }}</span>
|
||||
<div class="acts">
|
||||
<!-- 第十七轮: 下载。产物在跨域 CDN(不带 CORS 头)上,直链 <a download> 不生效,
|
||||
统一走后端 /v1/media/download 代拉,见 lib/download.ts。 -->
|
||||
<el-button v-if="tk.src" size="small" :loading="dlId === (tk.id ?? tk.video_id)" @click="dlVideo(tk)">
|
||||
<Icon name="dl" :size="14" />{{ t('videos.dl') }}
|
||||
</el-button>
|
||||
<!-- 「原始返回」改成内联按钮(原 el-collapse 独占一行还多一道边框),展开就在卡片底部 -->
|
||||
<el-button v-if="tk.error || tk.rawtext" size="small" text @click="toggleRaw(tk.id)">
|
||||
{{ t('videos.raw') }}<Icon :name="rawOpen(tk.id) ? 'chevD' : 'chev'" :size="14" />
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<pre v-if="rawOpen(tk.id)" class="raw-text">{{ tk.error || tk.rawtext }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-empty v-if="!shownTasks.length" :description="t('videos.empty')" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import Icon from '../components/Icon.vue'
|
||||
import { api } from '../api'
|
||||
import { findVideoUrl, videoStatusKind } from '../lib/media'
|
||||
import { downloadMedia, nameFromPrompt, stamp } from '../lib/download'
|
||||
import { pullHistory, pushHistory, deleteHistoryItem, ensureIds } from '../lib/history'
|
||||
import { pickImage, pickAudio, PRESETS, dataUriBytes, formatBytes, assertBodyBudget } from '../lib/upload'
|
||||
|
||||
interface VTask {
|
||||
id: number
|
||||
video_id: string
|
||||
model: string
|
||||
provider: string
|
||||
status: string
|
||||
kind: 'pending' | 'done' | 'fail'
|
||||
src: string
|
||||
poster: string
|
||||
started: number
|
||||
prompt?: string
|
||||
elapsed?: number
|
||||
mode?: string
|
||||
refs?: string // 素材摘要(文件名,不放 data URI —— 历史单条只有 16KB)
|
||||
retryAt?: number // 上游轮询被限流时,到这个时间点前不再问(避免撞 429)
|
||||
error?: string
|
||||
rawtext: string
|
||||
}
|
||||
|
||||
interface Slot { uri: string; name: string; thumb: string; bytes: number }
|
||||
|
||||
const router = useRouter()
|
||||
const { t } = useI18n()
|
||||
const models = ref<any[]>([])
|
||||
const model = ref('')
|
||||
const prompt = ref('')
|
||||
const seconds = ref('5')
|
||||
const aspect = ref('16:9')
|
||||
const quality = ref('720P')
|
||||
const seed = ref<number | null>(null)
|
||||
// 第十一轮 #3:场景模式与对应素材
|
||||
const mode = ref<'text' | 'keyframe' | 'reference'>('text')
|
||||
const frameEl = ref<HTMLInputElement | null>(null)
|
||||
const refImgEl = ref<HTMLInputElement | null>(null)
|
||||
const refAudEl = ref<HTMLInputElement | null>(null)
|
||||
let frameTarget: 'first' | 'last' = 'first'
|
||||
const firstSlot = ref<Slot | null>(null)
|
||||
const lastSlot = ref<Slot | null>(null)
|
||||
const firstUrl = ref('')
|
||||
const lastUrl = ref('')
|
||||
const refImgs = ref<Slot[]>([]) // 参考图(最多 5,文档 images ≤ 5)
|
||||
const refAuds = ref<Slot[]>([]) // 参考音频(最多 3,文档 audios ≤ 3)
|
||||
const refImgUrls = ref('') // 每行一个 URL / data:
|
||||
const refAudUrls = ref('')
|
||||
const showRefImgUrl = ref(false)
|
||||
const showRefAudUrl = ref(false)
|
||||
const audioAccept = 'audio/*,.mp3,.wav,.m4a,.aac,.ogg,.flac,.opus'
|
||||
const durationOptions = [4, 5, 6, 7, 8, 9, 10, 11, 12]
|
||||
const stream = ref(true) // 异步提交,后台轮询
|
||||
const creating = ref(false)
|
||||
const err = ref('')
|
||||
const tasks = ref<VTask[]>([])
|
||||
// 已完成(含失败)的任务数:决定「清除已完成」是否可点 —— 没东西可清时按钮直接置灰,
|
||||
// 免得点了弹一个「确定要清除 0 个吗」的框。
|
||||
const doneCount = computed(() => tasks.value.filter((t) => t.kind !== 'pending').length)
|
||||
|
||||
// 任务列表筛选(纯展示:轮询与统计仍然针对全部任务,不裁剪原数组)
|
||||
const filter = ref<'all' | 'doing' | 'done'>('all')
|
||||
const shownTasks = computed(() => tasks.value.filter((tk) =>
|
||||
filter.value === 'all' ? true : filter.value === 'doing' ? tk.kind === 'pending' : tk.kind !== 'pending'))
|
||||
|
||||
// 把多行文本切成非空 URL 数组
|
||||
function toList(s: string): string[] {
|
||||
return (s || '').split(/\r?\n/).map((x) => x.trim()).filter(Boolean)
|
||||
}
|
||||
const promptPlaceholder = computed(() =>
|
||||
mode.value === 'reference' ? t('videos.placeholderRef') : t('videos.placeholder'))
|
||||
|
||||
const SKEY = 'gw_video_tasks' // 本地只当缓存,历史以服务端为准
|
||||
|
||||
function cacheLocal() {
|
||||
try { localStorage.setItem(SKEY, JSON.stringify(tasks.value)) } catch { /* 缓存写不进无所谓 */ }
|
||||
}
|
||||
async function save() {
|
||||
cacheLocal()
|
||||
// 视频任务原先因为 rawtext 太大把 localStorage 配额撑满、写失败又被静默吞掉 —— 这里必须报出来
|
||||
if (!(await pushHistory('videos', tasks.value))) ElMessage.warning(t('history.saveFail'))
|
||||
}
|
||||
async function load() {
|
||||
let local: VTask[] = []
|
||||
try {
|
||||
const j = JSON.parse(localStorage.getItem(SKEY) || '[]')
|
||||
if (Array.isArray(j)) local = j as VTask[]
|
||||
} catch { local = [] }
|
||||
const remote = await pullHistory('videos')
|
||||
if (remote === null) {
|
||||
tasks.value = local.map((t) => ({ ...t, kind: videoStatusKind(t.status) }))
|
||||
ElMessage.warning(t('history.offline'))
|
||||
return
|
||||
}
|
||||
if (remote.length) {
|
||||
tasks.value = remote.map((t: any) => ({ ...t, kind: videoStatusKind(t.status) }))
|
||||
} else if (local.length) {
|
||||
tasks.value = ensureIds(local, 'vid').map((t: any) => ({ ...t, kind: videoStatusKind(t.status) }))
|
||||
await pushHistory('videos', tasks.value) // 首次:把浏览器里的旧任务搬上服务端
|
||||
} else {
|
||||
tasks.value = []
|
||||
}
|
||||
cacheLocal()
|
||||
}
|
||||
|
||||
async function loadModels() {
|
||||
try {
|
||||
const j = await api('/v1/models')
|
||||
const all = (j.data || []).filter((x: any) => x.type === 'video')
|
||||
models.value = all
|
||||
if (all.length && !model.value) model.value = all[0].id
|
||||
} catch (e: any) {
|
||||
if (e && e.status === 401) { router.push('/login'); return }
|
||||
ElMessage.error(t('videos.loadErr') + ':' + ((e && e.message) || e))
|
||||
}
|
||||
}
|
||||
|
||||
// 卡片状态文案。注意参数别叫 t —— 那会遮蔽 i18n 的 t(),videos.failText 分支会当场抛错。
|
||||
// 第十九轮:胶囊里只放短状态(原来直接显示上游的 completed / failed 英文原样,
|
||||
// 而正文里又写一遍「已生成」,同一件事说两遍;失败原因挪到摘要行,仍可见)
|
||||
const stateShort = (tk: VTask) =>
|
||||
tk.kind === 'fail' ? t('videos.failText') : tk.kind === 'done' ? t('videos.doneText') : t('videos.doingText')
|
||||
|
||||
// 「生成中」已等待了多久(started 是毫秒时间戳;轮询每次刷新会重算)
|
||||
const waitSec = (tk: VTask) => (tk.started ? Math.max(0, Math.round((Date.now() - tk.started) / 1000)) : 0)
|
||||
|
||||
// 摘要行:服务 · 耗时/等待 · 场景,一行说完;失败时整行就是失败原因
|
||||
function subLine(tk: VTask): string {
|
||||
if (tk.kind === 'fail') return tk.error || t('videos.failText')
|
||||
const parts: string[] = []
|
||||
if (tk.provider) parts.push(tk.provider)
|
||||
if (tk.kind === 'done' && tk.elapsed) parts.push(t('videos.subElapsed', { n: tk.elapsed }))
|
||||
if (tk.kind === 'pending') { const w = waitSec(tk); if (w) parts.push(t('videos.subWait', { n: w })) }
|
||||
if (tk.mode) parts.push(modeLabel(tk.mode))
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
// 「原始返回」的展开态(内联按钮切换,替代原来的 el-collapse)
|
||||
const rawIds = ref<number[]>([])
|
||||
const rawOpen = (id: number) => rawIds.value.includes(id)
|
||||
function toggleRaw(id: number) {
|
||||
rawIds.value = rawIds.value.includes(id) ? rawIds.value.filter((x) => x !== id) : [...rawIds.value, id]
|
||||
}
|
||||
|
||||
const pillCls = (k: string) => (k === 'done' ? 'ok' : k === 'fail' ? 'err' : 'warn')
|
||||
|
||||
const modeLabel = (m: string) =>
|
||||
m === 'keyframe' ? t('videos.modeKeyframe') : m === 'reference' ? t('videos.modeReference') : t('videos.modeText')
|
||||
|
||||
// ── 素材上传(第十三轮)──
|
||||
function pickFrame(which: 'first' | 'last') {
|
||||
frameTarget = which
|
||||
frameEl.value?.click()
|
||||
}
|
||||
async function onFrameFiles(ev: Event) {
|
||||
const input = ev.target as HTMLInputElement
|
||||
const f = (input.files || [])[0]
|
||||
if (f) {
|
||||
try {
|
||||
// 首/尾帧会给到 1280px(画面直接进视频,比参考图要求更高)
|
||||
const m = await pickImage(f, PRESETS.frame)
|
||||
if (frameTarget === 'first') firstSlot.value = m
|
||||
else lastSlot.value = m
|
||||
} catch (e: any) {
|
||||
ElMessage.error(t('videos.pickErr', { msg: (e && e.message) || e }))
|
||||
}
|
||||
}
|
||||
if (input) input.value = ''
|
||||
}
|
||||
async function onRefImages(ev: Event) {
|
||||
const input = ev.target as HTMLInputElement
|
||||
for (const f of Array.from(input.files || [])) {
|
||||
if (refImgs.value.length >= 5) { ElMessage.warning(t('videos.refMax', { n: 5 })); break }
|
||||
try {
|
||||
refImgs.value.push(await pickImage(f, PRESETS.videoRef))
|
||||
} catch (e: any) {
|
||||
ElMessage.error(t('videos.pickErr', { msg: (e && e.message) || e }))
|
||||
}
|
||||
}
|
||||
if (input) input.value = ''
|
||||
}
|
||||
async function onRefAudios(ev: Event) {
|
||||
const input = ev.target as HTMLInputElement
|
||||
for (const f of Array.from(input.files || [])) {
|
||||
if (refAuds.value.length >= 3) { ElMessage.warning(t('videos.audMax', { n: 3 })); break }
|
||||
try {
|
||||
refAuds.value.push(await pickAudio(f))
|
||||
} catch (e: any) {
|
||||
ElMessage.error(t('videos.pickErr', { msg: (e && e.message) || e }))
|
||||
}
|
||||
}
|
||||
if (input) input.value = ''
|
||||
}
|
||||
/** 上传的 data URI 与手填 URL 合成上游字段(首/尾帧取其一:上传优先) */
|
||||
const firstFrame = computed(() => (firstSlot.value?.uri || firstUrl.value).trim())
|
||||
const lastFrame = computed(() => (lastSlot.value?.uri || lastUrl.value).trim())
|
||||
const imageList = computed(() => [...refImgs.value.map((r) => r.uri), ...toList(refImgUrls.value)])
|
||||
const audioList = computed(() => [...refAuds.value.map((r) => r.uri), ...toList(refAudUrls.value)])
|
||||
/** 卡片上展示的素材摘要(只存名字/数量,data URI 不进历史) */
|
||||
function mediaSummary(): string {
|
||||
if (mode.value === 'keyframe') {
|
||||
const names: string[] = []
|
||||
if (firstSlot.value) names.push(`首帧:${firstSlot.value.name}`)
|
||||
else if (firstUrl.value.trim()) names.push('首帧:URL')
|
||||
if (lastSlot.value) names.push(`尾帧:${lastSlot.value.name}`)
|
||||
else if (lastUrl.value.trim()) names.push('尾帧:URL')
|
||||
return names.join(' / ')
|
||||
}
|
||||
if (mode.value === 'reference') {
|
||||
const names: string[] = []
|
||||
refImgs.value.forEach((r, i) => names.push(`图${i + 1}:${r.name}`))
|
||||
if (toList(refImgUrls.value).length) names.push(`图URL×${toList(refImgUrls.value).length}`)
|
||||
refAuds.value.forEach((r, i) => names.push(`音${i + 1}:${r.name}`))
|
||||
if (toList(refAudUrls.value).length) names.push(`音URL×${toList(refAudUrls.value).length}`)
|
||||
return names.join(' / ')
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
async function create() {
|
||||
if (!prompt.value.trim() || creating.value) return
|
||||
// 第十一轮 #3:按模式做前端轻校验(后端也会挡,这里提前给反馈)
|
||||
if (mode.value === 'keyframe' && !firstFrame.value && !lastFrame.value) {
|
||||
err.value = t('videos.needFrame'); return
|
||||
}
|
||||
if (mode.value === 'reference' && !imageList.value.length && !audioList.value.length) {
|
||||
err.value = t('videos.needRef'); return
|
||||
}
|
||||
// 整包体积(素材 data URI + 正文)必须落在网关请求体上限内
|
||||
try {
|
||||
assertBodyBudget([prompt.value, firstFrame.value, lastFrame.value, ...imageList.value, ...audioList.value], 1200)
|
||||
} catch (e: any) {
|
||||
err.value = (e && e.message) || String(e); return
|
||||
}
|
||||
creating.value = true
|
||||
err.value = ''
|
||||
const t0 = Date.now()
|
||||
const summary = mediaSummary()
|
||||
try {
|
||||
const body: any = {
|
||||
model: model.value,
|
||||
prompt: prompt.value,
|
||||
seconds: seconds.value,
|
||||
size: quality.value,
|
||||
aspect_ratio: aspect.value,
|
||||
mode: mode.value,
|
||||
}
|
||||
if (seed.value != null) body.seed = seed.value
|
||||
if (mode.value === 'keyframe') {
|
||||
if (firstFrame.value) body.first_frame = firstFrame.value
|
||||
if (lastFrame.value) body.last_frame = lastFrame.value
|
||||
} else if (mode.value === 'reference') {
|
||||
if (imageList.value.length) body.images = imageList.value
|
||||
if (audioList.value.length) body.audios = audioList.value
|
||||
}
|
||||
if (!stream.value) body.wait = true // 同步等结果
|
||||
const j = await api('/v1/videos', { method: 'POST', body: JSON.stringify(body) })
|
||||
const task: VTask = {
|
||||
id: Date.now() + Math.random(), video_id: j.video_id || `unknown-${Date.now()}`,
|
||||
model: model.value, provider: j.provider_name || j.provider || '',
|
||||
status: j.status || 'submitted', kind: videoStatusKind(j.status || 'submitted'),
|
||||
src: '', poster: '', started: t0, rawtext: '',
|
||||
mode: mode.value,
|
||||
refs: summary || undefined,
|
||||
prompt: prompt.value.trim(), // 卡片下面要能回看当时填的提示词
|
||||
}
|
||||
if (j.final) {
|
||||
// 同步等待已返回最终 raw
|
||||
task.src = findVideoUrl(j.final)
|
||||
task.rawtext = JSON.stringify(j.final, null, 2)
|
||||
if (task.src) task.kind = 'done'
|
||||
}
|
||||
tasks.value.unshift(task)
|
||||
save()
|
||||
if (task.kind === 'done') {
|
||||
ElMessage.success(t('videos.doneMsg'))
|
||||
} else if (stream.value) {
|
||||
ElMessage.success(t('videos.submitMsg', { id: task.video_id }))
|
||||
}
|
||||
} catch (e: any) {
|
||||
// 第九轮: 优先展示后端给的人话(如「上游拒绝请求:size 必须是 720P 之一」)
|
||||
err.value = (e?.body?.detail) || e?.message || String(e)
|
||||
} finally {
|
||||
creating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 轮询所有 pending 任务
|
||||
// 间隔保持 5s(不按文档建议的 1~2s):实测上游 /agnesapi 在 3s 一次的频率下就会
|
||||
// 回 429「查询过于频繁」,网关已把 429 折成 throttled(不报错、不计熔断),
|
||||
// 这里再退避一点,避免多个任务同时轮询把额度打满。
|
||||
async function poll() {
|
||||
const now = Date.now()
|
||||
for (const tk of tasks.value) {
|
||||
if (tk.kind !== 'pending') continue
|
||||
if (!tk.video_id || tk.video_id.startsWith('unknown')) continue
|
||||
if (tk.retryAt && tk.retryAt > now) continue
|
||||
try {
|
||||
const j = await api(`/v1/videos/${encodeURIComponent(tk.video_id)}?model=${encodeURIComponent(tk.model)}`)
|
||||
if (j && j.throttled) {
|
||||
// 上游限流:任务还在跑,这次只是没问到 —— 不算失败,也别把卡片显示成出错
|
||||
const wait = Number(j.retry_after) || 3
|
||||
tk.retryAt = Date.now() + wait * 1000
|
||||
continue
|
||||
}
|
||||
const st = j.status || 'pending'
|
||||
tk.status = st
|
||||
const k = videoStatusKind(st)
|
||||
if (k === 'done') {
|
||||
tk.src = findVideoUrl(j.raw)
|
||||
tk.rawtext = JSON.stringify(j.raw, null, 2)
|
||||
tk.elapsed = ((Date.now() - tk.started) / 1000) | 0
|
||||
} else if (k === 'fail') {
|
||||
tk.error = JSON.stringify(j.raw || j).slice(0, 300)
|
||||
}
|
||||
if (tk.src) tk.kind = 'done'
|
||||
else if (k === 'fail') tk.kind = 'fail'
|
||||
save()
|
||||
} catch (e: any) {
|
||||
// 任务暂不存在/仍提交中:不打断轮询,仅记住错误供展示
|
||||
tk.error = (e && e.message) || String(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function clearDone() {
|
||||
const gone = tasks.value.filter((t) => t.kind !== 'pending')
|
||||
if (!gone.length) return
|
||||
// 老板要求:清除已完成要二次确认 —— 这是服务端真删(不可逆),点错就没了。
|
||||
try {
|
||||
await ElMessageBox.confirm(t('videos.confirmClear', { n: gone.length }), t('common.confirm'),
|
||||
{ type: 'warning', confirmButtonText: t('common.delete'), cancelButtonText: t('common.cancel') })
|
||||
} catch { return }
|
||||
tasks.value = tasks.value.filter((t) => t.kind === 'pending')
|
||||
cacheLocal()
|
||||
// 逐条按 id 删,别整份覆盖(覆盖会把另一台设备刚生成的也抹掉)
|
||||
for (const tk of gone) {
|
||||
if (!(await deleteHistoryItem('videos', tk.id))) ElMessage.warning(t('history.saveFail'))
|
||||
}
|
||||
}
|
||||
|
||||
let timer: any = null
|
||||
onMounted(() => {
|
||||
load()
|
||||
loadModels()
|
||||
timer = setInterval(poll, 5000)
|
||||
})
|
||||
|
||||
// ── 第十七轮: 下载已生成的视频 ──
|
||||
// CDN 不给 CORS 头,所以由后端代拉(/v1/media/download)再落盘;文件名取
|
||||
// 「提示词前缀 + 时间戳」,后缀由后端按 Content-Type 补(默认 .mp4)。
|
||||
const dlId = ref<any>(null)
|
||||
async function dlVideo(tk: VTask) {
|
||||
if (!tk?.src) { ElMessage.error(t('videos.dlNoSrc')); return }
|
||||
dlId.value = tk.id ?? tk.video_id
|
||||
try {
|
||||
await downloadMedia(tk.src, `${nameFromPrompt(tk.prompt || '', 'video')}-${stamp()}`)
|
||||
ElMessage.success(t('videos.dlOk'))
|
||||
} catch (e: any) {
|
||||
ElMessage.error(t('videos.dlFail', { msg: e?.message || String(e) }))
|
||||
} finally {
|
||||
dlId.value = null
|
||||
}
|
||||
}
|
||||
onUnmounted(() => clearInterval(timer))
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 撑满高度的两栏:左参数卡、右任务卡;滚动只发生在各自内部 */
|
||||
.param-card { display: flex; flex-direction: column; overflow-y: auto; }
|
||||
.result-card { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
.task-list { flex: 1; min-height: 0; overflow-y: auto; }
|
||||
|
||||
.mb-field { margin-bottom: 10px; }
|
||||
/* .field 天生是 flex:1(给 .form-row 横向用的)—— 在竖排卡片里必须收回,
|
||||
否则每个字段会纵向撑开,控件之间留下大片空白 */
|
||||
.param-card > .field { flex: none; }
|
||||
.fill { width: 100%; }
|
||||
.mt6 { margin-top: 8px; }
|
||||
.mode-sub { display: block; font-size: 10px; line-height: 1.3; color: var(--muted-2); margin-top: 1px; }
|
||||
.mode.on .mode-sub { color: var(--primary); opacity: .75; }
|
||||
/* 分辨率只读展示:半透明 + 「固定」说明 */
|
||||
.ctl.dim { opacity: .6; }
|
||||
.dim-tag { margin-left: auto; font-size: 11px; }
|
||||
.async-row { margin-top: 2px; }
|
||||
|
||||
.ref-btns { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||
/* 「上传 / 用 URL」文案不折行(窄列里被挤成两行是旧版的老毛病) */
|
||||
.ref-btns :deep(.el-button) { white-space: nowrap; }
|
||||
.hide-file { display: none; }
|
||||
.ref-urls { margin-top: 6px; }
|
||||
.ref-thumbs { display: flex; flex-wrap: wrap; gap: 8px; margin: 8px 0; }
|
||||
.ref-thumb { position: relative; width: 68px; }
|
||||
.ref-thumb img { width: 68px; height: 68px; object-fit: cover; border-radius: 6px; border: 1px solid var(--line); display: block; }
|
||||
.ref-thumb .rn { display: block; font-size: 11px; color: var(--muted-2); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.ref-aud {
|
||||
position: relative; display: flex; align-items: center; gap: 6px; padding: 4px 22px 4px 8px;
|
||||
border: 1px solid var(--line); border-radius: 6px; background: var(--surface-2);
|
||||
}
|
||||
.ref-aud .au-ico { color: var(--muted-2); }
|
||||
.ref-aud .rn { font-size: 12px; color: var(--muted); max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
.rm {
|
||||
position: absolute; top: -6px; right: -6px; width: 18px; height: 18px;
|
||||
display: grid; place-items: center; border-radius: 50%; cursor: pointer;
|
||||
background: var(--surface); border: 1px solid var(--line); color: var(--err);
|
||||
}
|
||||
.ref-aud .rm { top: 50%; right: 2px; transform: translateY(-50%); }
|
||||
|
||||
.slot-row { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; flex-wrap: wrap; }
|
||||
.slot-lb { flex: 0 0 60px; font-size: 12px; color: var(--muted); }
|
||||
.slot-u { flex: 1 1 150px; min-width: 140px; }
|
||||
.slot-row :deep(.el-button) { white-space: nowrap; }
|
||||
.slot-file {
|
||||
position: relative; display: inline-flex; align-items: center; gap: 6px; padding: 2px 6px;
|
||||
border: 1px solid var(--line); border-radius: 6px; background: var(--surface-2); margin-bottom: 8px;
|
||||
}
|
||||
.slot-file img { width: 30px; height: 30px; object-fit: cover; border-radius: 4px; display: block; }
|
||||
.slot-name { font-size: 12px; color: var(--muted); max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tip { margin-top: 6px; line-height: 1.5; }
|
||||
|
||||
.param-foot { margin-top: auto; padding-top: 8px; }
|
||||
.err-alert { margin-bottom: 8px; }
|
||||
.go-btn { width: 100%; }
|
||||
|
||||
.pager { gap: 6px; flex-wrap: wrap; }
|
||||
.chip-sel { cursor: pointer; }
|
||||
.pager :deep(.el-button) { margin-left: 6px; }
|
||||
|
||||
/* 任务卡:缩略占位 + 右侧标题 / 状态 / 摘要 / 操作 */
|
||||
/* 第十九轮:卡片改成「缩略图垂直居中 + 右侧三行信息」的紧凑版式。
|
||||
信息压到 3 行(原来 5 行 key/value + 折叠栏 + 独占一行的按钮 = 228px 高的卡片,
|
||||
缩略图下方空 140px)。 */
|
||||
.vid-card { align-items: center; }
|
||||
.vid-card.k-fail { border-color: color-mix(in srgb, var(--err) 35%, var(--line)); }
|
||||
.vid-card .vid-thumb { overflow: hidden; }
|
||||
.vid-el { width: 100%; height: 100%; object-fit: contain; background: var(--surface-2); }
|
||||
.spinner {
|
||||
width: 22px; height: 22px; border: 3px solid var(--line); border-top-color: var(--primary);
|
||||
border-radius: 50%; animation: rot .8s linear infinite;
|
||||
}
|
||||
@keyframes rot { to { transform: rotate(360deg); } }
|
||||
.vid-body { flex: 1; min-width: 0; }
|
||||
.vid-head { display: flex; align-items: center; gap: 8px; }
|
||||
.vid-head .t {
|
||||
font-size: 13px; font-weight: 600; color: var(--text); min-width: 0;
|
||||
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
|
||||
}
|
||||
.vid-head .pill { margin-left: auto; }
|
||||
/* 摘要行:一行放不下就省略(原来换成 5 行 key/value,卡片高度翻倍) */
|
||||
.vid-card .s {
|
||||
font-size: 11.5px; color: var(--muted-2); margin-top: 3px;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.vid-card .s.refs { color: var(--muted); }
|
||||
.vid-card .s.s-err { color: var(--err); }
|
||||
.progress { height: 5px; }
|
||||
.bar-wait { width: 38%; background: var(--primary); animation: wait 1.4s ease-in-out infinite; }@keyframes wait { 0%, 100% { opacity: .35 } 50% { opacity: 1 } }
|
||||
/* 底部一行:任务号 + 操作按钮;窄屏放不下时按钮自动换到下一行 */
|
||||
.vid-foot { display: flex; align-items: center; gap: 8px; margin-top: 7px; flex-wrap: wrap; }
|
||||
.vid-k { color: var(--muted-2); flex: none; font-size: 12px; }
|
||||
.vid-id { color: var(--muted); flex: 1 1 auto; min-width: 90px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.raw-text {
|
||||
white-space: pre-wrap; font-size: 11px; color: var(--muted); max-height: 160px; overflow-y: auto;
|
||||
background: var(--surface-2); padding: 6px; border-radius: 4px; border: 1px solid var(--line);
|
||||
margin: 7px 0 0;
|
||||
}
|
||||
.acts { display: flex; flex-wrap: wrap; gap: 7px; margin-left: auto; }
|
||||
.acts :deep(.el-button) { margin-left: 0; }
|
||||
|
||||
/* 窄屏:单列后整页滚动,两个卡片都恢复自然高度 */
|
||||
@media (max-width: 768px) {
|
||||
/* 窄屏单列后不再需要「撑满一屏」,改由 .gw-body 整页滚动 */
|
||||
.page-fill { height: auto; }
|
||||
.img-layout { height: auto; }
|
||||
.param-card { overflow: visible; }
|
||||
.result-card { flex: none; }
|
||||
.task-list { overflow: visible; }
|
||||
.card-h { flex-wrap: wrap; }
|
||||
.slot-lb { flex: 0 0 52px; }
|
||||
/* 第十八轮: 场景卡副标题原 10px,手机上太小(与底部 Tab 一起抬到 11.5px) */
|
||||
.mode-sub { font-size: 11.5px; }
|
||||
/* 第十九轮:窄屏下按钮会换到第二行,卡片本来就比 61px 的缩略图高一截,
|
||||
缩略图改为撑满卡片高度 + cover 裁切(与图像页缩略图 fit=cover 一致),
|
||||
左侧不再悬着一张 61px 高的小图、上下各空 45px。 */
|
||||
.vid-card .vid-thumb { align-self: stretch; height: auto; min-height: 61px; }
|
||||
.vid-el { object-fit: cover; }
|
||||
/* 场景卡的两列布局已上移到 style.css 的 .modes(原为「窄屏两列、桌面三列」,
|
||||
改后桌面也是两列 —— 桌面参数列只有 ~289px,三列每格 91px 放不下长标签)。 */
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user