feat: 交付任务005-021全量改动(自动化/AI/联系人中心、消息中心改造、运维与容器化)

- 自动化中心:规则引擎、流程画布与触发器(V7/V10/V12/V18/V21)、测试全流程、安全边界、执行记录
- AI 中心:服务商/模型/调用与工具授权/治理(V8/V17)及配套前端页面
- 联系人中心:联系人目录、分组/标签、同步幂等(V19)与实装页面
- 消息中心:三栏布局重做、头像昵称服务端抓取与缓存(V16 conversation_profile)、出站归属修复
- 接入管理:NapCat 反向 WS/HTTP 回调多通道发送传输、连接状态统一口径
- 运维中心:备份保留与恢复确认(V13/V22/V24)、监控告警(V23)、日志与审计
- 全局:账号上下文切换(V20 account_profile)、统一 UI 基础组件、分页样式、Flyway 增量迁移护栏
- 部署:Dockerfile/docker-compose/Nginx 容器化编排与 CI 校验脚本
- 文档:任务 005-021 交付记录、设计画板导出、接口/数据库/架构文档同步
This commit is contained in:
2026-11-17 17:29:06 +08:00
parent d804696fd0
commit 27182fc7d2
518 changed files with 80433 additions and 1905 deletions
-124
View File
@@ -1,124 +0,0 @@
<script setup>
import { ref } from 'vue'
import { demoState, MOCK_NOTE } from '../demo/config'
import { PLANNED_DEPS, aiCalls, aiCapabilities, aiProviders } from '../demo/planned'
import PageHead from '../components/PageHead.vue'
import DemoBadge from '../components/DemoBadge.vue'
import PlannedNotice from '../components/PlannedNotice.vue'
import StatusTag from '../components/StatusTag.vue'
const tab = ref('providers')
</script>
<template>
<PageHead kicker="工作空间" title="AI 能力" desc="服务商、模型能力、调用记录与成本。后端尚未提供 AI 接口,本页内容全部为演示数据。">
<template #actions>
<button class="btn" type="button" disabled title="后端未提供 AI 服务商创建接口">新增服务商</button>
<button class="btn primary" type="button" disabled title="后端未提供 AI 测试接口">打开测试台</button>
</template>
</PageHead>
<PlannedNotice
v-if="!demoState.enabled"
title="AI 能力尚未开发"
summary="服务商适配、能力声明、Tool Calling 与调用审计均依赖后端尚未提供的接口;关闭演示数据时页面不展示任何占位数据。"
:deps="PLANNED_DEPS.ai"
/>
<template v-else>
<div class="demo-banner">{{ MOCK_NOTE }}<DemoBadge /></div>
<div class="grid stats">
<div class="card">
<div class="stat-top"><span>已启用服务商<DemoBadge /></span><span class="stat-icon">✦</span></div>
<div class="stat-value">{{ aiProviders.length }}</div>
<div class="stat-foot">全部为 OpenAI 兼容协议</div>
</div>
<div class="card">
<div class="stat-top"><span>今日调用<DemoBadge /></span><span class="stat-icon">≡</span></div>
<div class="stat-value">{{ aiProviders.reduce((sum, item) => sum + item.todayCalls, 0) }}</div>
<div class="stat-foot">含失败与降级调用</div>
</div>
<div class="card">
<div class="stat-top"><span>本月预算使用<DemoBadge /></span><span class="stat-icon">%</span></div>
<div class="stat-value">81%</div>
<div class="stat-foot">超出阈值需人工确认</div>
</div>
<div class="card">
<div class="stat-top"><span>自动执行能力<DemoBadge /></span><span class="stat-icon">!</span></div>
<div class="stat-value">0</div>
<div class="stat-foot">高风险动作必须经人工确认</div>
</div>
</div>
<div class="tabs">
<button class="tab" :class="{ active: tab === 'providers' }" type="button" @click="tab = 'providers'">服务商</button>
<button class="tab" :class="{ active: tab === 'capabilities' }" type="button" @click="tab = 'capabilities'">能力</button>
<button class="tab" :class="{ active: tab === 'calls' }" type="button" @click="tab = 'calls'">调用记录</button>
</div>
<div v-if="tab === 'providers'" class="grid three-col">
<div v-for="provider in aiProviders" :key="provider.name" class="card" v-show="true">
<div class="card-head">
<h3 class="card-title">{{ provider.name }} <DemoBadge /></h3>
<StatusTag value="ACTIVE" :label="provider.status" />
</div>
<div class="kv">
<div class="kv-row"><span>协议</span><span>{{ provider.protocol }}</span></div>
<div class="kv-row"><span>模型</span><span>{{ provider.model }}</span></div>
<div class="kv-row"><span>今日调用</span><span>{{ provider.todayCalls }}</span></div>
<div class="kv-row"><span>预算使用</span><span>{{ provider.budget }}%</span></div>
<div class="kv-row"><span>最近测试</span><span>{{ provider.test }}</span></div>
</div>
<div class="progress" style="margin-top: 12px"><span :style="{ width: `${provider.budget}%` }"></span></div>
<div class="form-actions" style="margin-top: 12px">
<button class="btn sm" type="button" disabled title="后端未提供 AI 服务商测试接口">测试连接</button>
<button class="btn sm" type="button" disabled title="后端未提供 AI 服务商编辑接口">编辑</button>
</div>
</div>
</div>
<div v-else-if="tab === 'capabilities'" class="card">
<div class="card-head">
<h3 class="card-title">模型能力声明<DemoBadge /></h3>
<span class="small-muted">服务商宣传能力不等同于项目已验证能力</span>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>能力</th><th>使用模型</th><th>说明</th><th>状态</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="item in aiCapabilities" :key="item.name">
<td><strong>{{ item.name }}</strong></td>
<td>{{ item.model }}</td>
<td>{{ item.desc }}</td>
<td><StatusTag :value="item.enabled ? 'ACTIVE' : 'DISABLED'" :label="item.enabled ? '已启用' : '未启用'" /></td>
<td><button class="btn sm" type="button" disabled title="后端未提供能力开关接口">配置</button></td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-else class="card">
<div class="card-head">
<h3 class="card-title">调用记录<DemoBadge /></h3>
<span class="small-muted">真实调用日志需后端 /ai/calls 接口</span>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>时间</th><th>能力</th><th>模型</th><th>耗时</th><th>Token</th><th>结果</th></tr></thead>
<tbody>
<tr v-for="call in aiCalls" :key="`${call.time}-${call.capability}`">
<td>{{ call.time }}</td>
<td>{{ call.capability }}</td>
<td>{{ call.model }}</td>
<td>{{ call.duration }}</td>
<td>{{ call.tokens }}</td>
<td><StatusTag :value="call.result === '成功' ? 'SUCCESS' : 'FAILED'" :label="call.result" /></td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
</template>
File diff suppressed because it is too large Load Diff
+802 -90
View File
@@ -1,103 +1,815 @@
<script setup>
import { ref } from 'vue'
import { demoState, MOCK_NOTE } from '../demo/config'
import { PLANNED_DEPS, backupPlans, backupRecords } from '../demo/planned'
import { computed, onMounted, reactive, ref } from 'vue'
import { api } from '../api'
import { describeError, formatTime, notify } from '../ui'
import PageHead from '../components/PageHead.vue'
import DemoBadge from '../components/DemoBadge.vue'
import PlannedNotice from '../components/PlannedNotice.vue'
import ConfirmDialog from '../components/ConfirmDialog.vue'
import DetailDrawer from '../components/DetailDrawer.vue'
import Pagination from '../components/Pagination.vue'
import StatusTag from '../components/StatusTag.vue'
import Select from '../components/ui/Select.vue'
import { can, denialReason } from '../permissions'
const tab = ref('plans')
const BACKUP_STATUS_OPTIONS = [
{ value: '', label: '全部状态' },
{ value: 'RUNNING', label: 'RUNNING · 执行中' },
{ value: 'SUCCEEDED', label: 'SUCCEEDED · 成功' },
{ value: 'FAILED', label: 'FAILED · 失败' }
]
const BACKUP_TYPE_OPTIONS = [
{ value: 'LOGICAL_JSONL', label: 'LOGICAL_JSONL(逻辑备份 · MinIO)' },
{ value: 'MYSQL_DUMP', label: 'MYSQL_DUMP(mysqldump 全量)' }
]
const tab = ref('records')
const rows = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const statusFilter = ref('')
const loading = ref(false)
const error = ref(null)
const canRead = computed(() => can('backup.read'))
const canExecute = computed(() => can('backup.execute'))
const executeReason = computed(() => denialReason('backup.execute', '执行备份或恢复'))
const createModal = ref(null)
const createBusy = ref(false)
const createError = ref(null)
const restoreModal = ref(null)
const restoreBusy = ref(false)
const restoreError = ref(null)
const confirmRow = ref(null)
const confirmBusy = ref(false)
const confirmError = ref(null)
// 运维运行模式:由后端强制,前端只做提示与禁用。
const runtimeMode = ref(null)
const preflightResult = ref(null)
const preflightBusy = ref(false)
const preflightError = ref(null)
const succeeded = computed(() => rows.value.filter((row) => String(row.status).toUpperCase() === 'SUCCEEDED').length)
const failed = computed(() => rows.value.filter((row) => String(row.status).toUpperCase() === 'FAILED').length)
const corrupt = computed(() => rows.value.filter((row) => String(row.checksumStatus).toUpperCase() === 'CORRUPT').length)
const lastSucceeded = computed(() => rows.value.find((row) => String(row.status).toUpperCase() === 'SUCCEEDED'))
function formatBytes(value) {
const size = Number(value)
if (!Number.isFinite(size) || size <= 0) return '—'
const units = ['B', 'KB', 'MB', 'GB', 'TB']
let index = 0
let current = size
while (current >= 1024 && index < units.length - 1) {
current /= 1024
index += 1
}
return `${current.toFixed(index === 0 ? 0 : 1)} ${units[index]}`
}
function checksumLabel(value) {
const text = String(value || '').toUpperCase()
if (text === 'VALID') return '校验通过'
if (text === 'CORRUPT') return '校验不一致'
if (text === 'PENDING') return '待校验'
return value || '—'
}
function statusLabel(value) {
const text = String(value || '').toUpperCase()
if (text === 'SUCCEEDED') return '成功'
if (text === 'FAILED') return '失败'
if (text === 'RUNNING') return '执行中'
return value || '—'
}
async function load(nextPage = page.value) {
if (canRead.value === false) return
loading.value = true
error.value = null
try {
const data = await api.backups({
status: statusFilter.value || undefined,
page: nextPage,
pageSize: pageSize.value
})
rows.value = data?.items || []
total.value = data?.total || 0
page.value = data?.page || nextPage
} catch (e) {
rows.value = []
total.value = 0
error.value = describeError(e)
} finally {
loading.value = false
}
}
function onPageChange({ page: nextPage, pageSize: nextSize }) {
pageSize.value = nextSize
load(nextPage)
}
function openCreate() {
createModal.value = { backupType: 'LOGICAL_JSONL', reason: '' }
createError.value = null
}
async function submitCreate() {
if (!createModal.value || createBusy.value) return
createBusy.value = true
createError.value = null
try {
const data = await api.createBackup({
backupType: createModal.value.backupType,
reason: createModal.value.reason.trim() || null
})
notify('备份已创建', `${data?.backupUid || '备份记录'}:${statusLabel(data?.status)};校验 ${checksumLabel(data?.checksumStatus)}。`, 'success')
createModal.value = null
await load(1)
} catch (e) {
createError.value = describeError(e)
} finally {
createBusy.value = false
}
}
function askVerify(row) {
confirmRow.value = row
confirmError.value = null
}
async function doVerify() {
if (!confirmRow.value || confirmBusy.value) return
confirmBusy.value = true
confirmError.value = null
try {
const data = await api.verifyBackup(confirmRow.value.backupUid)
notify(
data?.verified ? '完整性校验通过' : '完整性校验失败',
data?.verified ? '重算 SHA-256 与记录一致。' : '备份文件哈希与记录不一致,已标记 CORRUPT,禁止恢复。',
data?.verified ? 'success' : 'error'
)
confirmRow.value = null
await load(page.value)
} catch (e) {
confirmError.value = describeError(e)
} finally {
confirmBusy.value = false
}
}
function openRestore(row) {
restoreModal.value = {
row,
reason: '',
confirmationToken: null,
tokenInput: '',
step: 'request'
}
restoreError.value = null
}
async function requestRestoreToken() {
if (!restoreModal.value || restoreBusy.value) return
restoreBusy.value = true
restoreError.value = null
try {
const data = await api.createRestoreConfirmation(
restoreModal.value.row.backupUid,
restoreModal.value.reason.trim() || null
)
restoreModal.value.confirmationToken = data
restoreModal.value.step = 'confirm'
} catch (e) {
restoreError.value = describeError(e)
} finally {
restoreBusy.value = false
}
}
async function executeRestore() {
const modal = restoreModal.value
if (!modal || restoreBusy.value) return
restoreBusy.value = true
restoreError.value = null
try {
const data = await api.restoreBackup(
modal.row.backupUid,
modal.tokenInput.trim(),
modal.reason.trim() || null
)
notify('恢复已提交', `目标库 ${data?.databaseName || '—'};后端已完成实例身份与备份完整性校验。`, 'success')
restoreModal.value = null
await load(page.value)
} catch (e) {
restoreError.value = describeError(e)
} finally {
restoreBusy.value = false
}
}
function canRestore(row) {
return canExecute.value &&
runtimeMode.value?.restoreAllowed !== false &&
String(row.status).toUpperCase() === 'SUCCEEDED' &&
String(row.checksumStatus).toUpperCase() === 'VALID'
}
// 删除备份产物属于恢复类动作,只读观察模式下后端会返回 409,这里同步禁用入口。
const deleteBlockedByMode = computed(() => runtimeMode.value?.restoreAllowed === false)
async function loadRuntimeMode() {
try {
runtimeMode.value = await api.runtimeMode()
} catch (e) {
// 无系统读权限时不展示模式卡片,不阻断备份页。
runtimeMode.value = null
}
}
async function doPreflight(row) {
if (preflightBusy.value) return
preflightBusy.value = true
preflightError.value = null
preflightResult.value = null
try {
preflightResult.value = await api.preflightBackup(row.backupUid)
} catch (e) {
preflightError.value = describeError(e)
} finally {
preflightBusy.value = false
}
}
function closePreflight() {
preflightResult.value = null
preflightError.value = null
}
// 保存备份保留策略、清理候选与两阶段删除确认。所有数据均来自后端真实响应。
const retention = ref(null)
const retentionLoading = ref(false)
const retentionError = ref(null)
const retentionBusy = ref(false)
const deleteModal = ref(null)
const deleteBusy = ref(false)
const deleteError = ref(null)
const PROTECTION_LABELS = {
LATEST_SUCCEEDED: '最新成功备份',
NOT_SUCCEEDED: '失败或状态不明',
CHECKSUM_NOT_VALID: '校验未通过',
RECENTLY_VERIFIED: '近期校验通过',
RECENT_PREFLIGHT: '近期恢复预检'
}
const CANDIDATE_LABELS = {
EXCEEDS_COUNT: '超出保留数量',
EXCEEDS_AGE: '超出保留天数'
}
const retentionCandidates = computed(() => (retention.value?.items || []).filter((item) => item.candidate))
function protectionText(list) {
if (!list || !list.length) return '—'
return list.map((code) => PROTECTION_LABELS[code] || code).join('、')
}
function candidateText(list) {
if (!list || !list.length) return '—'
return list.map((code) => CANDIDATE_LABELS[code] || code).join('、')
}
async function loadRetention() {
if (canRead.value === false) return
retentionLoading.value = true
retentionError.value = null
try {
retention.value = await api.backupRetention()
} catch (e) {
retention.value = null
retentionError.value = describeError(e)
} finally {
retentionLoading.value = false
}
}
async function recalculateRetention() {
if (retentionBusy.value || canExecute.value === false) return
retentionBusy.value = true
retentionError.value = null
try {
retention.value = await api.recalculateBackupRetention()
notify('候选计算完成', '已重新计算并标记清理候选,未删除任何备份产物。', 'success')
await load(page.value)
} catch (e) {
retentionError.value = describeError(e)
} finally {
retentionBusy.value = false
}
}
function switchTab(next) {
tab.value = next
if (next === 'retention' && !retention.value && !retentionLoading.value) {
loadRetention()
}
}
function openDelete(row) {
if (deleteBlockedByMode.value) return
deleteModal.value = { row, reason: '', preflight: null, token: null, tokenInput: '', step: 'preflight' }
deleteError.value = null
}
async function runDeletePreflight() {
const modal = deleteModal.value
if (!modal || deleteBusy.value) return
deleteBusy.value = true
deleteError.value = null
try {
modal.preflight = await api.backupDeletePreflight(modal.row.backupUid)
} catch (e) {
deleteError.value = describeError(e)
} finally {
deleteBusy.value = false
}
}
async function requestDeleteToken() {
const modal = deleteModal.value
if (!modal || deleteBusy.value) return
deleteBusy.value = true
deleteError.value = null
try {
modal.token = await api.createBackupDeleteConfirmation(modal.row.backupUid, modal.reason.trim() || null)
modal.step = 'confirm'
} catch (e) {
deleteError.value = describeError(e)
} finally {
deleteBusy.value = false
}
}
async function executeDelete() {
const modal = deleteModal.value
if (!modal || deleteBusy.value) return
deleteBusy.value = true
deleteError.value = null
try {
const data = await api.deleteBackup(modal.row.backupUid, modal.tokenInput.trim(), modal.reason.trim() || null)
notify('备份产物已删除', `${data?.backupUid || ''} 已标记为 ${data?.retentionState || 'DELETED'};该操作不可恢复。`, 'success')
deleteModal.value = null
await loadRetention()
await load(page.value)
} catch (e) {
deleteError.value = describeError(e)
} finally {
deleteBusy.value = false
}
}
onMounted(() => {
load(1)
loadRuntimeMode()
})
</script>
<template>
<PageHead kicker="平台管理" title="备份与恢复" desc="备份策略、备份记录与恢复演练。后端尚未提供备份接口,本页内容全部为演示数据。">
<PageHead kicker="平台管理" title="备份与恢复" desc="备份记录、完整性校验与恢复前检查均来自后端;恢复会覆盖当前数据库,必须单独申请一次性确认令牌。">
<template #actions>
<button class="btn" type="button" disabled title="后端未提供恢复接口">恢复数据</button>
<button class="btn primary" type="button" disabled title="后端未提供立即备份接口">立即备份</button>
<button class="btn" type="button" :disabled="loading" @click="load(page)">{{ loading ? '刷新中…' : '刷新' }}</button>
<button
class="btn primary"
type="button"
:disabled="canExecute === false" v-tooltip="canExecute === false ? executeReason : '立即创建数据库备份'"
@click="openCreate"
>
立即备份
</button>
</template>
</PageHead>
<PlannedNotice
v-if="!demoState.enabled"
title="备份与恢复尚未开发"
summary="备份任务、完整性校验与恢复演练依赖后端尚未提供的接口。备份属于高风险操作,未实现前不提供任何触发入口。"
:deps="PLANNED_DEPS.backup"
<div v-if="runtimeMode" class="notice" :class="{ warn: runtimeMode.mode !== 'READ_WRITE' }">
<strong>运行模式:{{ runtimeMode.description || runtimeMode.mode }}</strong>
<span>模式由后端强制:只读观察模式禁止发起恢复类动作;维护模式禁止新建备份,预检仍可执行。</span>
</div>
<div class="grid stats">
<div class="card">
<div class="stat-top"><span>备份记录</span><span class="stat-icon">⛁</span></div>
<div class="stat-value">{{ total }}</div>
<div class="stat-foot">当前筛选条件下的记录数</div>
</div>
<div class="card">
<div class="stat-top"><span>本页成功</span><span class="stat-icon">✓</span></div>
<div class="stat-value">{{ succeeded }}</div>
<div class="stat-foot">失败 {{ failed }} · 校验不一致 {{ corrupt }}</div>
</div>
<div class="card">
<div class="stat-top"><span>最近成功</span><span class="stat-icon">◷</span></div>
<div class="stat-value">{{ lastSucceeded ? formatTime(lastSucceeded.finishedAt || lastSucceeded.startedAt) : '—' }}</div>
<div class="stat-foot">{{ lastSucceeded ? formatBytes(lastSucceeded.fileSize) : '暂无成功记录' }}</div>
</div>
<div class="card">
<div class="stat-top"><span>恢复门槛</span><span class="stat-icon">↺</span></div>
<div class="stat-value">校验 + 令牌</div>
<div class="stat-foot">实例身份不一致或旧实例库一律拒绝</div>
</div>
</div>
<div class="tabs">
<button class="tab" :class="{ active: tab === 'records' }" type="button" @click="switchTab('records')">备份记录</button>
<button class="tab" :class="{ active: tab === 'restore' }" type="button" @click="switchTab('restore')">恢复与安全</button>
<button class="tab" :class="{ active: tab === 'retention' }" type="button" @click="switchTab('retention')">保留与容量</button>
</div>
<div v-if="tab === 'records'" class="card">
<div class="card-head">
<h3 class="card-title">备份记录</h3>
<span class="pill">{{ total }} 条</span>
</div>
<div class="filterbar" style="display: flex; gap: 8px; margin-bottom: 10px">
<Select
v-model="statusFilter"
:options="BACKUP_STATUS_OPTIONS"
style="width: 140px"
aria-label="备份状态筛选"
@update:model-value="load(1)"
/>
<button class="btn sm" type="button" :disabled="loading || canRead === false" @click="load(1)">查询</button>
</div>
<div v-if="canRead === false" class="notice warn">
<strong>缺少权限</strong><span>{{ denialReason('backup.read', '查询备份记录') }}</span>
</div>
<div v-if="error" class="notice danger">
<strong>{{ error.title }}</strong><span>{{ error.message }}</span>
<button class="btn sm" type="button" @click="load(page)">重试</button>
</div>
<div v-else-if="loading && !rows.length" class="loading-row"><span class="spinner"></span>正在读取备份记录…</div>
<div v-else-if="!rows.length" class="empty-line">还没有备份记录。数据库备份工具未配置时,后端会拒绝创建且不写入记录。</div>
<div v-else class="table-wrap">
<table class="tbl table-compact">
<thead>
<tr><th>开始时间</th><th>方式</th><th>文件</th><th>大小</th><th>校验</th><th>状态</th><th>错误</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.backupUid">
<td class="small-muted">{{ formatTime(row.startedAt) }}</td>
<td>{{ row.backupType }}</td>
<td class="small-muted">{{ row.fileName || '—' }}</td>
<td>{{ formatBytes(row.fileSize) }}</td>
<td><StatusTag :value="row.checksumStatus" :label="checksumLabel(row.checksumStatus)" /></td>
<td><StatusTag :value="row.status" :label="statusLabel(row.status)" /></td>
<td class="small-muted">{{ row.errorMessage || '—' }}</td>
<td>
<div class="table-actions">
<button
class="btn sm"
type="button"
:disabled="canRead === false || String(row.status).toUpperCase() !== 'SUCCEEDED'" v-tooltip="'只读校验产物并列出将被覆盖的表与行数'"
@click="doPreflight(row)"
>
预检
</button>
<button
class="btn sm"
type="button"
:disabled="canExecute === false || String(row.status).toUpperCase() !== 'SUCCEEDED'" v-tooltip="canExecute === false ? executeReason : '重算 SHA-256 校验备份完整性'"
@click="askVerify(row)"
>
校验
</button>
<button
class="btn sm danger"
type="button"
:disabled="!canRestore(row)" v-tooltip="canRestore(row) ? '申请一次性确认令牌后恢复' : '仅成功且校验通过、且非只读观察模式允许恢复'"
@click="openRestore(row)"
>
恢复
</button>
</div>
</td>
</tr>
</tbody>
</table>
<Pagination :page="page" :page-size="pageSize" :total="total" @change="onPageChange" />
</div>
</div>
<div v-else-if="tab === 'restore'" class="card">
<div class="card-head">
<h3 class="card-title">恢复与安全</h3>
<span class="pill">破坏性操作</span>
</div>
<div class="kv">
<div class="kv-row"><span>备份完整性</span><span>恢复前必须为 SUCCEEDED 且 checksumStatus=VALID;可以重新校验。</span></div>
<div class="kv-row"><span>实例身份</span><span>后端会比对 instance-state.json 的 databaseName 与当前 JDBC catalog,不一致直接拒绝。</span></div>
<div class="kv-row"><span>旧实例保护</span><span>包含 dblhns39 的旧实例库一律拒绝,不会触碰旧实例。</span></div>
<div class="kv-row"><span>二次确认</span><span>必须申请一次性确认令牌(10 分钟有效、仅可用一次),并在弹窗中手动输入令牌。</span></div>
<div class="kv-row"><span>工具配置</span><span>未配置 QLINKER_MYSQL_PATH 时后端拒绝恢复,不会执行任何命令。</span></div>
</div>
<p class="small-muted" style="margin-top: 10px">恢复会覆盖当前数据库,请先完成独立备份并确认影响范围。</p>
</div>
<div v-else class="card">
<div class="card-head">
<h3 class="card-title">保留策略与清理候选</h3>
<span class="pill">默认只标记,不自动删除</span>
<button
class="btn sm"
type="button"
:disabled="retentionBusy || canExecute === false"
v-tooltip="canExecute === false ? executeReason : '重新计算并标记清理候选'"
@click="recalculateRetention"
>
{{ retentionBusy ? '计算中…' : '重新计算候选' }}
</button>
</div>
<div v-if="canRead === false" class="notice warn">
<strong>缺少权限</strong><span>{{ denialReason('backup.read', '查看保留策略与清洗候选') }}</span>
</div>
<div v-if="retentionError" class="notice danger">
<strong>{{ retentionError.title }}</strong><span>{{ retentionError.message }}</span>
<button class="btn sm" type="button" @click="loadRetention">重试</button>
</div>
<div v-else-if="retentionLoading" class="loading-row"><span class="spinner"></span>正在读取保留策略…</div>
<template v-else-if="retention">
<div class="kv">
<div class="kv-row"><span>保留数量</span><span>最多保留 {{ retention.policy?.maxCount }} 份成功备份(最新一份始终受保护)</span></div>
<div class="kv-row"><span>保留天数</span><span>{{ retention.policy?.retentionDays > 0 ? `超过 ${retention.policy.retentionDays} 天的成功备份进入候选` : '未启用按时间清理' }}</span></div>
<div class="kv-row"><span>保护窗口</span><span>{{ retention.policy?.protectPreflightDays }} 天内被完整性校验或恢复预检引用的备份不进入候选</span></div>
<div class="kv-row"><span>自动删除</span><span>{{ retention.policy?.autoDelete ? '开启' : '关闭(默认只计算并标记)' }}</span></div>
<div class="kv-row"><span>容量阈值</span><span>总量 {{ formatBytes(retention.policy?.capacityWarningBytes) }} · 近 7 天增长 {{ formatBytes(retention.policy?.growthWarningBytes) }}</span></div>
</div>
<div class="grid stats" style="margin-top: 12px">
<div class="card">
<div class="stat-top"><span>成功备份</span><span class="stat-icon">⛁</span></div>
<div class="stat-value">{{ retention.totals?.backupCount ?? '—' }}</div>
<div class="stat-foot">未删除的 SUCCEEDED 记录</div>
</div>
<div class="card">
<div class="stat-top"><span>备份总量</span><span class="stat-icon">∑</span></div>
<div class="stat-value">{{ formatBytes(retention.totals?.totalBytes) }}</div>
<div class="stat-foot">{{ retention.totals?.capacityExceeded ? '已达到容量阈值' : '低于容量阈值' }}</div>
</div>
<div class="card">
<div class="stat-top"><span>近 7 天增长</span><span class="stat-icon">↑</span></div>
<div class="stat-value">{{ formatBytes(retention.totals?.growthBytes7d) }}</div>
<div class="stat-foot">{{ retention.totals?.growthExceeded ? '已达到增长阈值' : '低于增长阈值' }}</div>
</div>
<div class="card">
<div class="stat-top"><span>清理候选</span><span class="stat-icon">⌫</span></div>
<div class="stat-value">{{ retention.totals?.candidateCount ?? 0 }}</div>
<div class="stat-foot">预计可释放 {{ formatBytes(retention.totals?.candidateBytes) }}</div>
</div>
</div>
<div v-if="retention.totals?.capacityExceeded || retention.totals?.growthExceeded" class="notice warn">
<strong>容量告警</strong>
<span v-if="retention.totals?.capacityExceeded">备份总量已达到容量阈值,健康聚合与告警规则(backup-capacity)会产出告警事件。</span>
<span v-if="retention.totals?.growthExceeded">近 7 天备份增长已达到阈值,告警规则(backup-growth)会产出告警事件。</span>
</div>
<div class="notice">
<strong>{{ retention.notice }}</strong>
<span>候选清单基于后端实时计算;真正删除必须经过预检与一次性令牌确认。</span>
</div>
<div v-if="!retentionCandidates.length" class="empty-line">当前没有可清理候选。最新成功备份、失败/状态不明、校验未通过以及保护窗口内的备份都不会成为候选。</div>
<div v-else class="table-wrap">
<table class="tbl table-compact">
<thead><tr><th>备份</th><th>创建时间</th><th>大小</th><th>候选原因</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="item in retentionCandidates" :key="item.backupUid">
<td>
<div>{{ item.backupUid }}</div>
<div class="small-muted">{{ item.backupType }} · {{ checksumLabel(item.checksumStatus) }}</div>
</td>
<td class="small-muted">{{ formatTime(item.createdAt) }}</td>
<td>{{ formatBytes(item.fileSize) }}</td>
<td class="small-muted">{{ candidateText(item.candidateReasons) }}</td>
<td>
<button
class="btn sm danger"
type="button"
:disabled="!item.deletable || canExecute === false || deleteBlockedByMode"
v-tooltip="deleteBlockedByMode ? '只读观察模式下禁止删除备份产物' : (item.deletable ? '预检并通过一次性令牌删除该备份产物' : '仅 MinIO 受控前缀下的逻辑备份产物可删除')"
@click="openDelete(item)"
>
删除
</button>
</td>
</tr>
</tbody>
</table>
</div>
<p class="small-muted" style="margin-top: 10px">
受保护记录示例:{{ protectionText(['LATEST_SUCCEEDED', 'RECENTLY_VERIFIED', 'RECENT_PREFLIGHT']) }}。
</p>
</template>
</div>
<DetailDrawer :open="Boolean(createModal)" title="立即备份" subtitle="数据库全量" @close="createModal = null">
<div v-if="createModal">
<div class="fld" style="margin-bottom: 12px">
<label>备份方式</label>
<Select v-model="createModal.backupType" :options="BACKUP_TYPE_OPTIONS" block aria-label="备份方式" />
</div>
<div class="fld" style="margin-bottom: 12px">
<label>原因</label>
<input v-model="createModal.reason" class="field" placeholder="写入审计,可选" />
</div>
<div v-if="createError" class="notice danger"><strong>{{ createError.title }}</strong><span>{{ createError.message }}</span></div>
<div class="table-actions" style="margin-top: 16px">
<button class="btn primary" type="button" :disabled="createBusy" @click="submitCreate">{{ createBusy ? '执行中…' : '开始备份' }}</button>
<button class="btn" type="button" @click="createModal = null">取消</button>
</div>
<p class="small-muted" style="margin-top: 12px">
LOGICAL_JSONL 由后端逐表导出并写入 MinIO 受控前缀,不依赖外部命令;MYSQL_DUMP 需要配置 QLINKER_MYSQLDUMP_PATH,未配置时返回 409 且不写入记录。
</p>
</div>
</DetailDrawer>
<DetailDrawer :open="Boolean(restoreModal)" title="恢复到该备份" :subtitle="restoreModal?.row?.backupUid" @close="restoreModal = null">
<div v-if="restoreModal">
<div class="notice danger">
<strong>恢复会覆盖当前数据库</strong>
<span>这是破坏性操作。后端会校验实例身份、备份完整性与一次性令牌,但不会自动执行任何恢复。</span>
</div>
<div class="fld" style="margin-bottom: 12px">
<label>恢复原因</label>
<input v-model="restoreModal.reason" class="field" placeholder="写入审计" :disabled="restoreModal.step === 'confirm'" />
</div>
<template v-if="restoreModal.step === 'request'">
<div class="table-actions">
<button class="btn danger" type="button" :disabled="restoreBusy || canExecute === false" @click="requestRestoreToken">
{{ restoreBusy ? '申请中…' : '申请一次性确认令牌' }}
</button>
</div>
</template>
<template v-else>
<div class="notice warn">
<strong>确认令牌仅显示一次</strong>
<div><code class="code">{{ restoreModal.confirmationToken?.confirmationToken }}</code></div>
<span>{{ restoreModal.confirmationToken?.notice }}</span>
</div>
<div class="fld" style="margin-bottom: 12px">
<label>输入确认令牌</label>
<input v-model="restoreModal.tokenInput" class="field" placeholder="rc_..." />
</div>
<div class="table-actions">
<button
class="btn danger"
type="button"
:disabled="restoreBusy || !restoreModal.tokenInput.trim()"
@click="executeRestore"
>
{{ restoreBusy ? '执行中…' : '确认执行恢复' }}
</button>
<button class="btn" type="button" @click="restoreModal = null">取消</button>
</div>
</template>
<div v-if="restoreError" class="notice danger"><strong>{{ restoreError.title }}</strong><span>{{ restoreError.message }}</span></div>
</div>
</DetailDrawer>
<DetailDrawer
:open="Boolean(preflightResult) || Boolean(preflightError)"
title="恢复预检"
subtitle="只读校验,不修改现网数据"
@close="closePreflight"
>
<div v-if="preflightError" class="notice danger">
<strong>{{ preflightError.title }}</strong><span>{{ preflightError.message }}</span>
</div>
<div v-else-if="preflightResult">
<div class="notice" :class="preflightResult.valid ? '' : 'danger'">
<strong>{{ preflightResult.valid ? '产物完整可用' : '产物校验未通过' }}</strong>
<span>校验 {{ checksumLabel(preflightResult.checksumStatus) }} · 大小 {{ formatBytes(preflightResult.actualSize) }} · 库名一致 {{ preflightResult.databaseMatches ? '是' : '否' }}</span>
</div>
<div v-if="preflightResult.problems?.length" class="notice danger">
<strong>问题</strong>
<span v-for="(item, index) in preflightResult.problems" :key="`p-${index}`">{{ item }}</span>
</div>
<div v-if="preflightResult.warnings?.length" class="notice warn">
<strong>提示</strong>
<span v-for="(item, index) in preflightResult.warnings" :key="`w-${index}`">{{ item }}</span>
</div>
<div class="table-wrap">
<table class="tbl table-compact">
<thead><tr><th>表</th><th>备份行数</th><th>当前行数</th><th>当前存在</th></tr></thead>
<tbody>
<tr v-for="item in preflightResult.tables || []" :key="item.table">
<td>{{ item.table }}</td>
<td>{{ item.backupRows }}</td>
<td>{{ item.currentRows }}</td>
<td>{{ item.exists ? '是' : '否' }}</td>
</tr>
</tbody>
</table>
</div>
<p class="small-muted" style="margin-top: 10px">
真实覆盖式恢复本阶段未开放(restoreExecutionEnabled={{ preflightResult.restoreExecutionEnabled }});预检结果仅供人工确认影响范围。
</p>
</div>
</DetailDrawer>
<DetailDrawer
:open="Boolean(deleteModal)"
title="删除备份产物"
:subtitle="deleteModal?.row?.backupUid"
@close="deleteModal = null"
>
<div v-if="deleteModal">
<div class="notice danger">
<strong>删除不可恢复</strong>
<span>只会移除 MinIO 受控前缀下的备份产物并把记录标记为 DELETED,不会触碰实例数据库、bucket 与本地冷备份目录。</span>
</div>
<template v-if="deleteModal.step === 'preflight'">
<div class="kv">
<div class="kv-row"><span>备份方式</span><span>{{ deleteModal.row?.backupType || '—' }}</span></div>
<div class="kv-row"><span>创建时间</span><span>{{ formatTime(deleteModal.row?.createdAt) }}</span></div>
<div class="kv-row"><span>大小</span><span>{{ formatBytes(deleteModal.row?.fileSize) }}</span></div>
<div class="kv-row"><span>候选原因</span><span>{{ candidateText(deleteModal.row?.candidateReasons) }}</span></div>
</div>
<div v-if="deleteModal.preflight" class="notice">
<strong>{{ deleteModal.preflight.deletable ? '预检通过' : '预检未通过' }}</strong>
<span>{{ deleteModal.preflight.artifactScope }}</span>
<span>{{ deleteModal.preflight.notice }}</span>
</div>
<div class="table-actions" style="margin-top: 12px">
<button class="btn" type="button" :disabled="deleteBusy" @click="runDeletePreflight">
{{ deleteBusy ? '预检中…' : '执行删除预检' }}
</button>
<button v-if="deleteModal.preflight" class="btn danger" type="button" :disabled="deleteBlockedByMode" @click="deleteModal.step = 'token'">下一步</button>
<button class="btn" type="button" @click="deleteModal = null">取消</button>
</div>
</template>
<template v-else-if="deleteModal.step === 'token'">
<div class="fld" style="margin-bottom: 12px">
<label>删除原因</label>
<input v-model="deleteModal.reason" class="field" placeholder="写入审计,可选(最多 500 字)" />
</div>
<div class="table-actions">
<button class="btn danger" type="button" :disabled="deleteBusy || deleteBlockedByMode" @click="requestDeleteToken">
{{ deleteBusy ? '申请中…' : '申请一次性确认令牌' }}
</button>
<button class="btn" type="button" @click="deleteModal = null">取消</button>
</div>
</template>
<template v-else>
<div class="notice warn">
<strong>确认令牌仅显示一次</strong>
<div><code class="code">{{ deleteModal.token?.confirmationToken }}</code></div>
<span>{{ deleteModal.token?.notice }}</span>
</div>
<div class="fld" style="margin-bottom: 12px">
<label>输入确认令牌</label>
<input v-model="deleteModal.tokenInput" class="field" placeholder="bd_..." />
</div>
<div class="table-actions">
<button
class="btn danger"
type="button"
:disabled="deleteBusy || deleteBlockedByMode || !deleteModal.tokenInput.trim()"
@click="executeDelete"
>
{{ deleteBusy ? '删除中…' : '确认删除备份产物' }}
</button>
<button class="btn" type="button" @click="deleteModal = null">取消</button>
</div>
</template>
<div v-if="deleteError" class="notice danger"><strong>{{ deleteError.title }}</strong><span>{{ deleteError.message }}</span></div>
</div>
</DetailDrawer>
<ConfirmDialog
:open="Boolean(confirmRow)"
title="校验备份完整性"
:message="confirmRow ? `重新计算 ${confirmRow.backupUid} 的 SHA-256?` : ''"
hint="校验不一致会把记录标记为 CORRUPT,并禁止该备份用于恢复。"
confirm-text="开始校验"
:busy="confirmBusy"
@cancel="confirmRow = null"
@confirm="doVerify"
/>
<template v-else>
<div class="demo-banner">{{ MOCK_NOTE }}<DemoBadge /></div>
<div class="grid stats">
<div class="card">
<div class="stat-top"><span>备份策略<DemoBadge /></span><span class="stat-icon">⛁</span></div>
<div class="stat-value">{{ backupPlans.length }}</div>
<div class="stat-foot">全部启用</div>
</div>
<div class="card">
<div class="stat-top"><span>最近备份<DemoBadge /></span><span class="stat-icon">◷</span></div>
<div class="stat-value">今天 08:40</div>
<div class="stat-foot">数据库全量 · 1.8 GB</div>
</div>
<div class="card">
<div class="stat-top"><span>完整性校验<DemoBadge /></span><span class="stat-icon">✓</span></div>
<div class="stat-value">通过</div>
<div class="stat-foot">最近 5 次全部通过</div>
</div>
<div class="card">
<div class="stat-top"><span>恢复演练<DemoBadge /></span><span class="stat-icon">↺</span></div>
<div class="stat-value">14 天前</div>
<div class="stat-foot">演练结果:通过</div>
</div>
</div>
<div class="tabs">
<button class="tab" :class="{ active: tab === 'plans' }" type="button" @click="tab = 'plans'">备份策略</button>
<button class="tab" :class="{ active: tab === 'records' }" type="button" @click="tab = 'records'">备份记录</button>
</div>
<div v-if="tab === 'plans'" class="card">
<div class="card-head">
<h3 class="card-title">备份策略<DemoBadge /></h3>
<button class="btn sm" type="button" disabled title="后端未提供备份策略创建接口">新建策略</button>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>策略</th><th>范围</th><th>计划</th><th>保留</th><th>状态</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="plan in backupPlans" :key="plan.name">
<td><strong>{{ plan.name }}</strong></td>
<td>{{ plan.scope }}</td>
<td>{{ plan.schedule }}</td>
<td>{{ plan.retention }}</td>
<td><StatusTag :value="plan.enabled ? 'ACTIVE' : 'DISABLED'" :label="plan.enabled ? '启用' : '停用'" /></td>
<td><button class="btn sm" type="button" disabled title="后端未提供备份策略编辑接口">编辑</button></td>
</tr>
</tbody>
</table>
</div>
</div>
<div v-else class="card">
<div class="card-head">
<h3 class="card-title">备份记录<DemoBadge /></h3>
<button class="btn sm" type="button" disabled title="后端未提供备份下载接口">下载</button>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>时间</th><th>范围</th><th>方式</th><th>大小</th><th>校验</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="record in backupRecords" :key="`${record.time}-${record.scope}`">
<td>{{ record.time }}</td>
<td>{{ record.scope }}</td>
<td>{{ record.type }}</td>
<td>{{ record.size }}</td>
<td><StatusTag value="SUCCESS" :label="record.verify" /></td>
<td><button class="btn sm" type="button" disabled title="后端未提供恢复接口">恢复</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<div v-if="confirmError" class="notice danger" style="margin-top: 8px">
<strong>{{ confirmError.title }}</strong><span>{{ confirmError.message }}</span>
</div>
</template>
<style scoped>
.filterbar .field {
height: 30px;
}
</style>
-2
View File
@@ -95,9 +95,7 @@ onMounted(loadStatus)
<template>
<div class="auth-card" style="max-width: 520px">
<div class="auth-card-head">
<p class="eyebrow">FIRST RUN</p>
<h1 class="auth-title">初始化管理员</h1>
<p class="auth-sub">首次启动专用。创建第一个管理员后,引导入口会永久关闭。</p>
</div>
<div v-if="success" class="notice">
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+8 -2
View File
@@ -7,6 +7,7 @@ import PageHead from '../components/PageHead.vue'
import StatCard from '../components/StatCard.vue'
import SectionState from '../components/SectionState.vue'
import StatusTag from '../components/StatusTag.vue'
import AvatarBadge from '../components/AvatarBadge.vue'
import DemoBadge from '../components/DemoBadge.vue'
import { demoState } from '../demo/config'
import { automationRules, automationSummary, dashboardTrend24h } from '../demo/planned'
@@ -137,7 +138,12 @@ onMounted(load)
<tr v-for="item in bindings" :key="item.bindingUid">
<td>
<div class="identity">
<span class="mini-avatar">{{ (item.displayName || 'N').slice(0, 1) }}</span>
<AvatarBadge
size="sm"
:name="item.displayName"
:media-uid="item.avatarMediaUid"
type="ACCOUNT"
/>
<div>
<strong>{{ item.displayName || '—' }}</strong>
<span>{{ item.endpoint || '—' }}</span>
@@ -151,7 +157,7 @@ onMounted(load)
<div class="small-muted" style="margin-top: 4px">{{ item.connectionStatus || '—' }}</div>
</td>
<td>{{ formatTime(item.lastEventAt) }}</td>
<td class="muted" title="后端未提供按绑定的今日消息统计">—</td>
<td class="muted" v-tooltip="'后端未提供按绑定的今日消息统计'">—</td>
</tr>
</tbody>
</table>
-2
View File
@@ -75,9 +75,7 @@ onMounted(loadStatus)
<template>
<div class="auth-card">
<div class="auth-card-head">
<p class="eyebrow">QLINKER ADMIN</p>
<h1 class="auth-title">登录管理台</h1>
<p class="auth-sub">单管理员实例。登录后可查看消息、管理连接、执行受控发送。</p>
</div>
<div v-if="statusLoading" class="loading-row">
+176 -88
View File
@@ -1,104 +1,192 @@
<script setup>
import { computed, ref } from 'vue'
import { demoState, MOCK_NOTE } from '../demo/config'
import { PLANNED_DEPS, logRows } from '../demo/planned'
import { computed, onMounted, reactive, ref } from 'vue'
import { api } from '../api'
import { describeError, formatTime } from '../ui'
import PageHead from '../components/PageHead.vue'
import DemoBadge from '../components/DemoBadge.vue'
import PlannedNotice from '../components/PlannedNotice.vue'
import Pagination from '../components/Pagination.vue'
import StatusTag from '../components/StatusTag.vue'
import Select from '../components/ui/Select.vue'
import { can, denialReason } from '../permissions'
const level = ref('')
const keyword = ref('')
const LOG_LEVEL_OPTIONS = [
{ value: '', label: '全部级别' },
{ value: 'TRACE', label: 'TRACE' },
{ value: 'DEBUG', label: 'DEBUG' },
{ value: 'INFO', label: 'INFO' },
{ value: 'WARN', label: 'WARN' },
{ value: 'ERROR', label: 'ERROR' },
{ value: 'FATAL', label: 'FATAL' }
]
const filtered = computed(() =>
logRows.filter((row) =>
(!level.value || row.level === level.value) &&
(!keyword.value.trim() || `${row.source} ${row.summary} ${row.trace}`.includes(keyword.value.trim()))
)
)
const filters = reactive({ traceId: '', level: '', keyword: '', from: '', to: '' })
const rows = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(50)
const loading = ref(false)
const error = ref(null)
const errorCount = computed(() => logRows.filter((row) => row.level === 'ERROR').length)
const warnCount = computed(() => logRows.filter((row) => row.level === 'WARN').length)
const canRead = computed(() => can('log.read'))
const readReason = computed(() => denialReason('log.read', '查询运行日志'))
const levelCounts = computed(() => {
const counts = { ERROR: 0, WARN: 0, INFO: 0 }
for (const row of rows.value) {
const level = String(row.level || '').toUpperCase()
if (level in counts) counts[level] += 1
}
return counts
})
function toIso(value) {
if (!value) return undefined
const date = new Date(value)
return Number.isNaN(date.getTime()) ? undefined : date.toISOString()
}
async function load(nextPage = page.value) {
if (canRead.value === false) return
loading.value = true
error.value = null
try {
const data = await api.logs({
traceId: filters.traceId.trim() || undefined,
level: filters.level || undefined,
keyword: filters.keyword.trim() || undefined,
from: toIso(filters.from),
to: toIso(filters.to),
page: nextPage,
pageSize: pageSize.value
})
rows.value = data?.items || []
total.value = data?.total || 0
page.value = data?.page || nextPage
} catch (e) {
rows.value = []
total.value = 0
error.value = describeError(e)
} finally {
loading.value = false
}
}
function onPageChange({ page: nextPage, pageSize: nextSize }) {
pageSize.value = nextSize
load(nextPage)
}
function reset() {
filters.traceId = ''
filters.level = ''
filters.keyword = ''
filters.from = ''
filters.to = ''
load(1)
}
onMounted(() => load(1))
</script>
<template>
<PageHead kicker="连接与运维" title="运行日志" desc="统一日志检索与链路追踪。后端尚未提供日志查询接口,本页内容全部为演示数据。">
<PageHead kicker="连接与运维" title="运行日志" desc="日志来自后端日志文件尾部(最近 2MB、最多 500 行),输出已脱敏;未配置 QLINKER_LOG_FILE 时后端返回 409。">
<template #actions>
<button class="btn" type="button" disabled title="后端未提供日志导出接口">导出日志</button>
<button class="btn" type="button" :disabled="loading || canRead === false" @click="load(page)">{{ loading ? '刷新中…' : '刷新' }}</button>
</template>
</PageHead>
<PlannedNotice
v-if="!demoState.enabled"
title="运行日志尚未开发"
summary="日志检索、链路追踪与导出均依赖后端尚未提供的接口;关闭演示数据时不展示任何占位日志。"
:deps="PLANNED_DEPS.logs"
/>
<template v-else>
<div class="demo-banner">{{ MOCK_NOTE }}<DemoBadge /></div>
<div class="grid stats">
<div class="card">
<div class="stat-top"><span>日志条数<DemoBadge /></span><span class="stat-icon">≡</span></div>
<div class="stat-value">{{ logRows.length }}</div>
<div class="stat-foot">仅演示样本</div>
</div>
<div class="card">
<div class="stat-top"><span>错误<DemoBadge /></span><span class="stat-icon">!</span></div>
<div class="stat-value">{{ errorCount }}</div>
<div class="stat-foot">ERROR 级别</div>
</div>
<div class="card">
<div class="stat-top"><span>警告<DemoBadge /></span><span class="stat-icon">△</span></div>
<div class="stat-value">{{ warnCount }}</div>
<div class="stat-foot">WARN 级别</div>
</div>
<div class="card">
<div class="stat-top"><span>保留策略<DemoBadge /></span><span class="stat-icon">◷</span></div>
<div class="stat-value">7 天</div>
<div class="stat-foot">容量与保留策略待后端配置接口</div>
</div>
</div>
<div class="grid stats">
<div class="card">
<div class="card-head">
<h3 class="card-title">日志检索<DemoBadge /></h3>
<span class="small-muted">本地筛选仅作用于演示样本</span>
</div>
<div class="filterbar" style="display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 12px">
<div class="fld">
<label for="log-level">级别</label>
<select id="log-level" v-model="level" class="field">
<option value="">全部级别</option>
<option value="INFO">INFO</option>
<option value="WARN">WARN</option>
<option value="ERROR">ERROR</option>
</select>
</div>
<div class="fld searchfield">
<label for="log-keyword">来源 / 内容 / 追踪号</label>
<input id="log-keyword" v-model="keyword" class="field" placeholder="例如:object storage、trc_9f16" />
</div>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>时间</th><th>级别</th><th>来源</th><th>摘要</th><th>追踪号</th><th>耗时</th><th>操作</th></tr></thead>
<tbody>
<tr v-for="row in filtered" :key="row.trace">
<td>{{ row.time }}</td>
<td><StatusTag :value="row.level" :label="row.level" /></td>
<td>{{ row.source }}</td>
<td>{{ row.summary }}</td>
<td>{{ row.trace }}</td>
<td>{{ row.cost }}</td>
<td><button class="btn sm" type="button" disabled title="后端未提供链路详情接口">链路详情</button></td>
</tr>
</tbody>
</table>
</div>
<div v-if="!filtered.length" class="state-block" style="margin-top: 12px">没有匹配的演示日志。</div>
<p class="small-muted" style="margin-top: 12px">按用户确认,日志页不再显示「检索延迟 86ms」等无法由后端验证的指标。</p>
<div class="stat-top"><span>匹配条数</span><span class="stat-icon">≡</span></div>
<div class="stat-value">{{ total }}</div>
<div class="stat-foot">当前筛选条件下</div>
</div>
</template>
<div class="card">
<div class="stat-top"><span>ERROR</span><span class="stat-icon">!</span></div>
<div class="stat-value">{{ levelCounts.ERROR }}</div>
<div class="stat-foot">仅统计当前页</div>
</div>
<div class="card">
<div class="stat-top"><span>WARN</span><span class="stat-icon">△</span></div>
<div class="stat-value">{{ levelCounts.WARN }}</div>
<div class="stat-foot">仅统计当前页</div>
</div>
<div class="card">
<div class="stat-top"><span>读取上限</span><span class="stat-icon">◷</span></div>
<div class="stat-value">500 行</div>
<div class="stat-foot">每页最多 200 行;尾部 2MB</div>
</div>
</div>
<div class="card">
<div class="card-head">
<h3 class="card-title">日志检索</h3>
<span class="pill">只读</span>
</div>
<div class="filterbar" style="display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 10px">
<input v-model="filters.traceId" class="field" style="width: 180px" placeholder="traceId" @keyup.enter="load(1)" />
<Select
v-model="filters.level"
:options="LOG_LEVEL_OPTIONS"
style="width: 120px"
aria-label="日志级别筛选"
@update:model-value="load(1)"
/>
<input v-model="filters.keyword" class="field" style="width: 200px" placeholder="关键字 / logger / 内容" @keyup.enter="load(1)" />
<el-date-picker
v-model="filters.from"
type="datetime"
placeholder="起始时间"
format="YYYY-MM-DD HH:mm"
value-format="YYYY-MM-DDTHH:mm"
style="width: 168px"
aria-label="起始时间"
v-tooltip="'起始时间'"
/>
<el-date-picker
v-model="filters.to"
type="datetime"
placeholder="结束时间"
format="YYYY-MM-DD HH:mm"
value-format="YYYY-MM-DDTHH:mm"
style="width: 168px"
aria-label="结束时间"
v-tooltip="'结束时间'"
/>
<button class="btn sm primary" type="button" :disabled="loading || canRead === false" v-tooltip="canRead === false ? readReason : '查询日志'" @click="load(1)">查询</button>
<button class="btn sm" type="button" :disabled="loading" @click="reset">重置</button>
</div>
<div v-if="canRead === false" class="notice warn"><strong>缺少权限</strong><span>{{ readReason }}</span></div>
<div v-if="error" class="notice danger">
<strong>{{ error.title }}</strong><span>{{ error.message }}</span>
<button class="btn sm" type="button" @click="load(page)">重试</button>
</div>
<div v-else-if="loading && !rows.length" class="loading-row"><span class="spinner"></span>正在读取日志…</div>
<div v-else-if="!rows.length" class="empty-line">当前条件下没有日志。页面不生成占位日志。</div>
<div v-else class="table-wrap">
<table class="tbl table-compact">
<thead>
<tr><th>时间</th><th>级别</th><th>Logger</th><th>traceId</th><th>内容</th></tr>
</thead>
<tbody>
<tr v-for="(row, index) in rows" :key="`${row.timestamp}-${row.traceId}-${index}`">
<td class="small-muted">{{ formatTime(row.timestamp) }}</td>
<td><StatusTag :value="row.level" :label="row.level" /></td>
<td class="small-muted">{{ row.logger }}</td>
<td><code class="code">{{ row.traceId || '—' }}</code></td>
<td class="log-message">{{ row.message }}</td>
</tr>
</tbody>
</table>
<Pagination :page="page" :page-size="pageSize" :total="total" @change="onPageChange" />
</div>
</div>
</template>
<style scoped>
.log-message {
max-width: 520px;
word-break: break-word;
font-size: 11px;
line-height: 1.5;
}
</style>
+89 -33
View File
@@ -1,5 +1,5 @@
<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { api } from '../api'
import { describeError, directionLabel, formatNumber, formatTime, typeLabel } from '../ui'
@@ -8,10 +8,32 @@ import SectionState from '../components/SectionState.vue'
import StatusTag from '../components/StatusTag.vue'
import DetailDrawer from '../components/DetailDrawer.vue'
import Pagination from '../components/Pagination.vue'
import Select from '../components/ui/Select.vue'
import { accountParam, accountState } from '../account-context.js'
const route = useRoute()
const router = useRouter()
const CONVERSATION_TYPE_OPTIONS = [
{ value: '', label: '全部类型' },
{ value: 'GROUP', label: '群聊 GROUP' },
{ value: 'FRIEND', label: '私聊 FRIEND' }
]
const DIRECTION_OPTIONS = [
{ value: '', label: '全部方向' },
{ value: 'INBOUND', label: '收到 INBOUND' },
{ value: 'OUTBOUND', label: '发出 OUTBOUND(发送记录)' }
]
const PAGE_SIZE_OPTIONS = [10, 20, 50, 100].map((size) => ({ value: size, label: `${size} 条/页` }))
const UNSUPPORTED_OPTIONS = [{ value: '', label: '后端未支持(不筛选)' }]
const bindingOptions = computed(() => [
{ value: '', label: '全部绑定' },
...(bindings.value || []).map((item) => ({
value: item.bindingUid,
label: `${item.displayName || item.bindingUid}${item.qqAccountId ? ` · ${item.qqAccountId}` : ''}`
}))
])
const filters = reactive({
keyword: '',
bindingUid: '',
@@ -44,6 +66,7 @@ const appliedList = computed(() => {
const source = applied.value
if (source.keyword) items.push(`关键词(摘要前缀):${source.keyword}`)
if (source.bindingUid) items.push(`绑定:${source.bindingUid}`)
if (source.qqAccount) items.push(`QQ 账号:${source.qqAccount}`)
if (source.conversationType) items.push(`会话类型:${source.conversationType}`)
if (source.conversationId) items.push(`会话 ID:${source.conversationId}`)
if (source.direction) items.push(`方向:${directionLabel(source.direction)}`)
@@ -77,6 +100,14 @@ function validate() {
async function search(nextPage = 1) {
if (!validate()) return
// 没有可用账号时不发无账号过滤的检索请求,结果区保持空态。
if (!accountParam()) {
rows.value = []
total.value = 0
error.value = null
loading.value = false
return
}
page.value = nextPage
loading.value = true
error.value = null
@@ -90,7 +121,8 @@ async function search(nextPage = 1) {
from: localToIso(filters.from),
to: localToIso(filters.to),
page: nextPage,
pageSize: pageSize.value
pageSize: pageSize.value,
qqAccount: accountParam() || undefined
}
applied.value = payload
try {
@@ -172,12 +204,17 @@ onMounted(async () => {
if (route.query.direction) filters.direction = String(route.query.direction)
if (route.query.keyword || route.query.conversationId) search()
})
// 切换 QQ 账号后若已有检索条件,回到第 1 页按新账号重新检索。
watch(() => accountState.current, () => {
if (hasApplied.value) search(1)
})
</script>
<template>
<PageHead kicker="工作空间" title="消息检索" desc="按后端 /api/v1/messages 支持的参数检索已入库消息。关键词只做 raw_summary 前缀匹配,不检索正文与原始 payload。">
<template #actions>
<button class="btn" type="button" disabled title="后端未提供导出接口">导出结果</button>
<button class="btn" type="button" disabled v-tooltip="'后端未提供导出接口'">导出结果</button>
<button class="btn" type="button" :disabled="loading" @click="search(1)">刷新结果</button>
</template>
</PageHead>
@@ -196,20 +233,18 @@ onMounted(async () => {
</div>
<div class="fld">
<label for="ms-binding">账号 / 绑定</label>
<select id="ms-binding" v-model="filters.bindingUid" class="field">
<option value="">全部绑定</option>
<option v-for="item in bindings" :key="item.bindingUid" :value="item.bindingUid">
{{ item.displayName || item.bindingUid }}{{ item.qqAccountId ? ` · ${item.qqAccountId}` : '' }}
</option>
</select>
<Select
id="ms-binding"
v-model="filters.bindingUid"
:options="bindingOptions"
block
searchable
aria-label="绑定筛选"
/>
</div>
<div class="fld">
<label for="ms-conv-type">会话类型</label>
<select id="ms-conv-type" v-model="filters.conversationType" class="field">
<option value="">全部类型</option>
<option value="GROUP">群聊 GROUP</option>
<option value="FRIEND">私聊 FRIEND</option>
</select>
<Select id="ms-conv-type" v-model="filters.conversationType" :options="CONVERSATION_TYPE_OPTIONS" block />
</div>
<div class="fld">
<label for="ms-conv-id">会话 ID</label>
@@ -217,11 +252,7 @@ onMounted(async () => {
</div>
<div class="fld">
<label for="ms-direction">方向(发送记录)</label>
<select id="ms-direction" v-model="filters.direction" class="field">
<option value="">全部方向</option>
<option value="INBOUND">收到 INBOUND</option>
<option value="OUTBOUND">发出 OUTBOUND(发送记录)</option>
</select>
<Select id="ms-direction" v-model="filters.direction" :options="DIRECTION_OPTIONS" block />
</div>
<div class="fld">
<label for="ms-sender">发送者 ID</label>
@@ -229,34 +260,59 @@ onMounted(async () => {
</div>
<div class="fld">
<label for="ms-from">起始时间</label>
<input id="ms-from" v-model="filters.from" class="field" type="datetime-local" :class="{ invalid: validationError }" />
<el-date-picker
id="ms-from"
v-model="filters.from"
type="datetime"
placeholder="选择起始时间"
format="YYYY-MM-DD HH:mm"
value-format="YYYY-MM-DDTHH:mm"
:class="{ invalid: validationError }"
style="width: 100%"
/>
</div>
<div class="fld">
<label for="ms-to">结束时间</label>
<input id="ms-to" v-model="filters.to" class="field" type="datetime-local" :class="{ invalid: validationError }" />
<el-date-picker
id="ms-to"
v-model="filters.to"
type="datetime"
placeholder="选择结束时间"
format="YYYY-MM-DD HH:mm"
value-format="YYYY-MM-DDTHH:mm"
:class="{ invalid: validationError }"
style="width: 100%"
/>
</div>
<div class="fld">
<label for="ms-type">消息类型</label>
<select id="ms-type" class="field" disabled title="后端 /messages 未提供 messageType 筛选参数">
<option>后端未支持(不筛选)</option>
</select>
<Select
id="ms-type"
:model-value="''"
:options="UNSUPPORTED_OPTIONS"
block
disabled
placeholder="后端未支持(不筛选)"
aria-label="消息类型(后端未支持)"
/>
<p class="field-hint">类型筛选置灰:后端列表接口不支持 messageType 参数。</p>
</div>
<div class="fld">
<label for="ms-status">处理状态</label>
<select id="ms-status" class="field" disabled title="后端 /messages 未提供处理状态筛选参数">
<option>后端未支持(不筛选)</option>
</select>
<Select
id="ms-status"
:model-value="''"
:options="UNSUPPORTED_OPTIONS"
block
disabled
placeholder="后端未支持(不筛选)"
aria-label="处理状态(后端未支持)"
/>
<p class="field-hint">处理状态置灰:后端列表接口不支持 normalizedStatus 参数。</p>
</div>
<div class="fld">
<label for="ms-size">每页条数</label>
<select id="ms-size" v-model.number="pageSize" class="field">
<option :value="10">10 条/页</option>
<option :value="20">20 条/页</option>
<option :value="50">50 条/页</option>
<option :value="100">100 条/页</option>
</select>
<Select id="ms-size" v-model="pageSize" :options="PAGE_SIZE_OPTIONS" block />
</div>
</div>
File diff suppressed because it is too large Load Diff
+342 -84
View File
@@ -2,126 +2,277 @@
import { computed, onMounted, ref } from 'vue'
import { api } from '../api'
import { describeError, formatNumber, formatTime } from '../ui'
import { demoState } from '../demo/config'
import PageHead from '../components/PageHead.vue'
import SectionState from '../components/SectionState.vue'
import StatusTag from '../components/StatusTag.vue'
import DemoBadge from '../components/DemoBadge.vue'
import { opsAlerts, opsResources } from '../demo/planned'
import { can, denialReason } from '../permissions'
const health = ref(null)
const status = ref(null)
const loading = ref(false)
const error = ref(null)
const sendTotal = computed(() =>
health.value ? ['PENDING', 'RUNNING', 'SUCCEEDED', 'FAILED', 'UNKNOWN'].reduce((sum, key) => sum + (Number(health.value.send?.[key]) || 0), 0) : 0
)
const health = ref(null)
const healthError = ref(null)
const alertSummary = ref(null)
const alertRules = ref([])
const alertEvents = ref([])
const alertTotal = ref(0)
const alertError = ref(null)
const monitoringLoading = ref(false)
const actionMessage = ref(null)
const actionError = ref(null)
const ruleDrafts = ref({})
const lastEvent = computed(() => {
const items = health.value?.napcat?.items || []
const times = items.map((item) => item.lastEventAt).filter(Boolean).sort()
return times.length ? times[times.length - 1] : null
})
const canRead = computed(() => can('system.read'))
const readReason = computed(() => denialReason('system.read', '查看系统状态'))
const canUpdate = computed(() => can('system.update'))
const updateReason = computed(() => denialReason('system.update', '处理告警与调整规则'))
const sendCounts = computed(() => status.value?.send?.counts || {})
const sendTotal = computed(() => Object.values(sendCounts.value).reduce((sum, value) => sum + (Number(value) || 0), 0))
const rows = computed(() => {
if (!health.value) return []
const m = health.value.messages || {}
const media = health.value.media || {}
const send = health.value.send || {}
const napcat = health.value.napcat || {}
if (!status.value) return []
const database = status.value.database || {}
const storage = status.value.objectStorage || {}
const events = status.value.events || {}
const tasks = status.value.tasks || {}
const send = status.value.send || {}
return [
{ name: '应用进程', status: health.value.application || 'UNKNOWN', detail: 'HTTP 存活仅代表进程可响应', at: '—' },
{ name: '实例身份', status: health.value.instance ? 'INITIALIZED' : 'PENDING', detail: health.value.instance || '未取得实例标识', at: '—' },
{
name: 'NapCat 连接',
status: napcat.connections?.receiverEnabled ? 'CONNECTED' : 'DISABLED',
detail: `受管连接 ${formatNumber(napcat.connections?.managedConnections)} · 绑定 ${formatNumber(napcat.total)} · 事件接收${napcat.connections?.receiverEnabled ? '已启用' : '未启用'}`,
at: formatTime(lastEvent.value)
},
{
name: '消息入库',
status: Number(m.failedEvents) > 0 ? 'FAILED' : Number(m.unprocessedEvents) > 0 ? 'PENDING' : 'ACTIVE',
detail: `总量 ${formatNumber(m.totalMessages)} · 待处理 ${formatNumber(m.unprocessedEvents)} · 失败 ${formatNumber(m.failedEvents)}`,
name: '应用进程',
status: status.value.application?.status,
detail: '仅代表进程可响应;依赖项单独探测',
at: '—'
},
{
name: '媒体对象存储',
status: Number(media.FAILED) > 0 ? 'FAILED' : Number(media.OBJECT_MISSING) > 0 ? 'WARN' : 'STORED',
detail: `已入库 ${formatNumber(media.STORED)} · 失败 ${formatNumber(media.FAILED)} · 对象缺失 ${formatNumber(media.OBJECT_MISSING)}`,
name: 'MySQL',
status: database.status,
detail: database.detail || 'SELECT 1 探测',
at: '—'
},
{
name: '发送操作',
status: Number(send.UNKNOWN) > 0 ? 'UNKNOWN' : Number(send.FAILED) > 0 ? 'FAILED' : 'ACTIVE',
detail: `总计 ${formatNumber(sendTotal.value)} · 成功 ${formatNumber(send.SUCCEEDED)} · 结果未知 ${formatNumber(send.UNKNOWN)}`,
name: 'MinIO 对象存储',
status: storage.status,
detail: storage.detail || (storage.status === 'UP' ? 'bucket 可访问' : 'bucket 不可访问'),
at: '—'
},
{ name: 'MySQL 连接', status: 'UNKNOWN', detail: '后端 health-detail 未提供数据库独立探测结果', at: '—' },
{ name: 'MinIO 连接', status: 'UNKNOWN', detail: '后端 health-detail 未提供对象存储独立探测结果', at: '—' },
{ name: '异步任务队列', status: 'UNKNOWN', detail: '后端 health-detail 未提供队列积压指标', at: '—' }
{
name: '事件接收积压',
status: events.status,
detail: `待处理事件 ${formatNumber(events.pending)}${events.detail ? ` · ${events.detail}` : ''}`,
at: events.oldestPendingAt ? formatTime(events.oldestPendingAt) : '—'
},
{
name: '异步任务队列',
status: tasks.status,
detail: `PENDING ${formatNumber(tasks.pending)} · WAITING ${formatNumber(tasks.waiting)} · FAILED ${formatNumber(tasks.failed)}${tasks.detail ? ` · ${tasks.detail}` : ''}`,
at: tasks.nextResumeAt ? formatTime(tasks.nextResumeAt) : '—'
},
{
name: '发送任务',
status: send.status,
detail: Object.entries(sendCounts.value).map(([key, value]) => `${key} ${formatNumber(value)}`).join(' · ') || '无记录',
at: '—'
}
]
})
async function load() {
if (canRead.value === false) return
loading.value = true
error.value = null
try {
health.value = await api.healthDetail()
status.value = await api.systemStatus()
} catch (e) {
health.value = null
status.value = null
error.value = describeError(e)
} finally {
loading.value = false
}
}
onMounted(load)
function healthTone(componentStatus) {
if (componentStatus === 'NORMAL') return 'success'
if (componentStatus === 'DEGRADED') return 'warning'
if (componentStatus === 'ABNORMAL') return 'error'
return 'muted'
}
function alertTone(eventStatus) {
if (eventStatus === 'FIRING') return 'error'
if (eventStatus === 'ACKNOWLEDGED') return 'warning'
if (eventStatus === 'RESOLVED') return 'success'
return 'muted'
}
function severityTone(severity) {
if (severity === 'CRITICAL') return 'error'
if (severity === 'WARNING') return 'warning'
if (severity === 'INFO') return 'info'
return 'muted'
}
async function loadMonitoring() {
if (canRead.value === false) return
monitoringLoading.value = true
healthError.value = null
alertError.value = null
const [healthResult, summaryResult, rulesResult, eventsResult] = await Promise.allSettled([
api.opsHealth(),
api.opsAlertSummary(),
api.opsAlertRules(),
api.opsAlertEvents({ page: 1, pageSize: 20 })
])
if (healthResult.status === 'fulfilled') health.value = healthResult.value
else {
health.value = null
healthError.value = describeError(healthResult.reason)
}
if (summaryResult.status === 'fulfilled') alertSummary.value = summaryResult.value
if (rulesResult.status === 'fulfilled') {
alertRules.value = rulesResult.value || []
const drafts = {}
for (const rule of alertRules.value) drafts[rule.ruleKey] = String(rule.threshold)
ruleDrafts.value = drafts
}
if (eventsResult.status === 'fulfilled') {
alertEvents.value = eventsResult.value?.items || []
alertTotal.value = eventsResult.value?.total || 0
}
const firstRejected = [summaryResult, rulesResult, eventsResult].find((item) => item.status === 'rejected')
if (firstRejected) alertError.value = describeError(firstRejected.reason)
monitoringLoading.value = false
}
async function refreshAll() {
actionMessage.value = null
actionError.value = null
await Promise.all([load(), loadMonitoring()])
}
async function saveRule(rule) {
actionMessage.value = null
actionError.value = null
const threshold = Number(ruleDrafts.value[rule.ruleKey])
if (!Number.isFinite(threshold)) {
actionError.value = '阈值必须是有效数字'
return
}
try {
await api.updateOpsAlertRule(rule.ruleKey, { threshold })
actionMessage.value = `已保存规则「${rule.name}」的阈值`
await loadMonitoring()
} catch (e) {
actionError.value = describeError(e)
}
}
async function toggleRule(rule) {
actionMessage.value = null
actionError.value = null
try {
await api.updateOpsAlertRule(rule.ruleKey, { enabled: !rule.enabled })
actionMessage.value = `规则「${rule.name}」已${rule.enabled ? '停用' : '启用'}`
await loadMonitoring()
} catch (e) {
actionError.value = describeError(e)
}
}
async function acknowledgeEvent(event) {
actionMessage.value = null
actionError.value = null
try {
await api.acknowledgeOpsAlert(event.eventUid)
actionMessage.value = `已确认告警「${event.summary}」`
await loadMonitoring()
} catch (e) {
actionError.value = describeError(e)
}
}
async function closeEvent(event) {
actionMessage.value = null
actionError.value = null
const note = window.prompt('关闭原因(可选,最多 255 字符)', '')
if (note === null) return
try {
await api.closeOpsAlert(event.eventUid, note)
actionMessage.value = `已关闭告警「${event.summary}」`
await loadMonitoring()
} catch (e) {
actionError.value = describeError(e)
}
}
onMounted(refreshAll)
</script>
<template>
<PageHead kicker="连接与运维" title="运维监控" desc="健康总览分项来自后端 health-detail;数据库、对象存储独立探测与主机资源尚未提供,按实显示「未提供」。">
<PageHead kicker="连接与运维" title="运维监控" desc="分层健康聚合与告警:未配置、正常、降级、异常分别展示,失败原因与下一步建议来自后端真实探测。">
<template #actions>
<button class="btn" type="button" :disabled="loading" @click="load">{{ loading ? '刷新中…' : '刷新' }}</button>
<button class="btn" type="button" :disabled="loading || monitoringLoading" @click="refreshAll">
{{ loading || monitoringLoading ? '刷新中…' : '刷新' }}
</button>
</template>
</PageHead>
<div class="grid stats">
<div class="card">
<div class="stat-top"><span>整体健康</span><span class="stat-icon">◇</span></div>
<div class="stat-value">{{ health?.overallLabel || '—' }}</div>
<div class="stat-foot">运行模式 {{ health?.runtimeMode || '—' }} · 未配置项不参与降级</div>
</div>
<div class="card">
<div class="stat-top"><span>应用进程</span><span class="stat-icon">◉</span></div>
<div class="stat-value">{{ health?.application || '—' }}</div>
<div class="stat-foot">进程存活不等于全部依赖可用</div>
<div class="stat-value">{{ status?.application?.status || '—' }}</div>
<div class="stat-foot">不代表依赖可用</div>
</div>
<div class="card">
<div class="stat-top"><span>NapCat 受管连接</span><span class="stat-icon">⇄</span></div>
<div class="stat-value">{{ health ? formatNumber(health.napcat?.connections?.managedConnections) : '—' }}</div>
<div class="stat-foot">事件接收{{ health?.napcat?.connections?.receiverEnabled ? '已启用' : '未启用' }}</div>
<div class="stat-top"><span>MySQL</span><span class="stat-icon">⛁</span></div>
<div class="stat-value">{{ status?.database?.status || '—' }}</div>
<div class="stat-foot">{{ status?.database?.detail || 'SELECT 1' }}</div>
</div>
<div class="card">
<div class="stat-top"><span>消息失败 / 待处理</span><span class="stat-icon">≡</span></div>
<div class="stat-value">{{ health ? `${formatNumber(health.messages?.failedEvents)} / ${formatNumber(health.messages?.unprocessedEvents)}` : '—' }}</div>
<div class="stat-foot">总量 {{ health ? formatNumber(health.messages?.totalMessages) : '—' }}</div>
<div class="stat-top"><span>MinIO</span><span class="stat-icon">▤</span></div>
<div class="stat-value">{{ status?.objectStorage?.status || '—' }}</div>
<div class="stat-foot">{{ status?.objectStorage?.detail || 'bucket 探测' }}</div>
</div>
<div class="card">
<div class="stat-top"><span>发送结果未知</span><span class="stat-icon">➤</span></div>
<div class="stat-value">{{ health ? formatNumber(health.send?.UNKNOWN) : '—' }}</div>
<div class="stat-foot">需人工核实,禁止自动重试</div>
<div class="stat-top"><span>任务队列</span><span class="stat-icon">≡</span></div>
<div class="stat-value">{{ status ? formatNumber(status.tasks?.pending) : '—' }}</div>
<div class="stat-foot">WAITING {{ status ? formatNumber(status.tasks?.waiting) : '—' }} · FAILED {{ status ? formatNumber(status.tasks?.failed) : '—' }}</div>
</div>
<div class="card">
<div class="stat-top"><span>事件积压</span><span class="stat-icon">◷</span></div>
<div class="stat-value">{{ status ? formatNumber(status.events?.pending) : '—' }}</div>
<div class="stat-foot">{{ status?.events?.oldestPendingAt ? `最早 ${formatTime(status.events.oldestPendingAt)}` : '无积压' }}</div>
</div>
<div class="card">
<div class="stat-top"><span>发送任务</span><span class="stat-icon">➤</span></div>
<div class="stat-value">{{ status ? formatNumber(sendTotal) : '—' }}</div>
<div class="stat-foot">UNKNOWN 需人工核实,禁止自动重试</div>
</div>
</div>
<div v-if="canRead === false" class="notice warn"><strong>缺少权限</strong><span>{{ readReason }}</span></div>
<div v-if="status?.generatedAt" class="small-muted" style="margin-bottom: 10px">探测时间 {{ formatTime(status.generatedAt) }}</div>
<SectionState :loading="loading" :error="error" @retry="load">
<div class="card" style="margin-bottom: 18px">
<div class="card-head">
<h3 class="card-title">健康总览</h3>
<span class="small-muted">最近事件已并入本表,不另设独立列表</span>
<h3 class="card-title">依赖探测</h3>
<span class="small-muted">/api/v1/system/status</span>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>依赖项</th><th>状态</th><th>说明</th><th>最近事件</th></tr></thead>
<table class="tbl table-compact">
<thead><tr><th>依赖项</th><th>状态</th><th>说明</th><th>最近时间</th></tr></thead>
<tbody>
<tr v-for="row in rows" :key="row.name">
<td><strong>{{ row.name }}</strong></td>
<td><StatusTag :value="row.status" :label="row.status" /></td>
<td class="muted">{{ row.detail }}</td>
<td class="small-muted">{{ row.detail }}</td>
<td>{{ row.at }}</td>
</tr>
</tbody>
@@ -130,31 +281,138 @@ onMounted(load)
</div>
</SectionState>
<template v-if="demoState.enabled">
<div class="demo-banner">以下主机资源与告警为演示数据,仅用于界面预览;后端未提供对应接口。<DemoBadge /></div>
<div class="grid two-col">
<div class="card">
<div class="card-head"><h3 class="card-title">主机资源<DemoBadge /></h3><span class="pill">演示</span></div>
<div v-for="item in opsResources" :key="item.name" style="margin-bottom: 14px">
<div class="context-line"><span>{{ item.name }}</span><span>{{ item.value }}</span></div>
<div class="progress"><span :style="{ width: `${item.width}%` }"></span></div>
</div>
<p class="small-muted">CPU / 内存 / 磁盘使用率需后端主机监控接口。</p>
</div>
<div class="card">
<div class="card-head"><h3 class="card-title">告警<DemoBadge /></h3><span class="pill">演示</span></div>
<div v-for="alert in opsAlerts" :key="alert.title" class="activity">
<span class="activity-icon" :class="alert.level === 'error' ? 'error' : alert.level === 'warning' ? 'warning' : 'success'">!</span>
<div>
<p>{{ alert.title }}</p>
<small>{{ alert.time }} · {{ alert.status }}</small>
</div>
</div>
<div class="form-actions" style="margin-top: 10px">
<button class="btn sm" type="button" disabled title="后端未提供告警确认/分派/关闭接口">处理告警</button>
</div>
</div>
<div v-if="actionMessage" class="notice" style="margin-bottom: 12px">{{ actionMessage }}</div>
<div v-if="actionError" class="notice warn" style="margin-bottom: 12px"><strong>操作失败</strong><span>{{ actionError }}</span></div>
<div class="card" style="margin-bottom: 18px">
<div class="card-head">
<h3 class="card-title">分层健康聚合</h3>
<span class="small-muted">/api/v1/ops/health</span>
</div>
</template>
<div v-else class="notice">演示数据已关闭:主机资源与告警区块依赖的后端接口尚未提供,因此不显示。</div>
<div v-if="healthError" class="notice warn"><strong>健康聚合不可用</strong><span>{{ healthError }}</span></div>
<div v-else-if="health" class="table-wrap">
<div class="small-muted" style="margin-bottom: 8px">
整体 {{ health.overallLabel }}({{ health.overall }}) · 生成时间 {{ formatTime(health.generatedAt) }}
</div>
<table class="tbl table-compact">
<thead><tr><th>组件</th><th>状态</th><th>说明</th><th>下一步建议</th></tr></thead>
<tbody>
<tr v-for="item in health.components" :key="item.key">
<td><strong>{{ item.name }}</strong></td>
<td><StatusTag :value="item.status" :label="item.statusLabel" :tone="healthTone(item.status)" /></td>
<td class="small-muted">{{ item.detail || '—' }}</td>
<td class="small-muted">{{ item.hint || '—' }}</td>
</tr>
</tbody>
</table>
</div>
<div v-else class="small-muted">暂无健康数据</div>
</div>
<div class="card" style="margin-bottom: 18px">
<div class="card-head">
<h3 class="card-title">告警事件</h3>
<span class="small-muted">
FIRING {{ alertSummary?.firingCount ?? '—' }} · ACKNOWLEDGED {{ alertSummary?.acknowledgedCount ?? '—' }}
· 活跃 {{ alertSummary?.activeCount ?? '—' }} · 共 {{ alertTotal }}
</span>
</div>
<div class="small-muted" style="margin-bottom: 8px">
通知渠道 {{ alertSummary?.notification?.channel || '—' }},
{{ alertSummary?.notification?.enabled ? '已启用' : '默认关闭(仅记录告警事件,不发起外部请求)' }}
</div>
<div v-if="alertError" class="notice warn"><strong>告警数据不可用</strong><span>{{ alertError }}</span></div>
<div v-else-if="alertEvents.length" class="table-wrap">
<table class="tbl table-compact">
<thead>
<tr><th>级别</th><th>摘要</th><th>状态</th><th>次数</th><th>最近触发</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="event in alertEvents" :key="event.eventUid">
<td><StatusTag :value="event.severity" :label="event.severity" :tone="severityTone(event.severity)" /></td>
<td>
<strong>{{ event.summary }}</strong>
<div class="small-muted">{{ event.detail?.hint || '—' }}</div>
</td>
<td><StatusTag :value="event.status" :label="event.status" :tone="alertTone(event.status)" /></td>
<td>{{ event.occurrenceCount }}</td>
<td>{{ formatTime(event.lastFiredAt) }}</td>
<td>
<button
v-if="event.status === 'FIRING'"
class="btn btn-sm"
type="button"
:disabled="!canUpdate"
:title="canUpdate ? '' : updateReason"
@click="acknowledgeEvent(event)"
>确认</button>
<button
v-if="event.status !== 'CLOSED'"
class="btn btn-sm"
type="button"
:disabled="!canUpdate"
:title="canUpdate ? '' : updateReason"
@click="closeEvent(event)"
>关闭</button>
</td>
</tr>
</tbody>
</table>
</div>
<div v-else class="small-muted">当前没有告警事件。规则命中后会在此出现,恢复后自动转为 RESOLVED。</div>
</div>
<div class="card">
<div class="card-head">
<h3 class="card-title">告警规则</h3>
<span class="small-muted">阈值 / 持续时长 / 静默期由后端强制执行</span>
</div>
<div v-if="alertRules.length" class="table-wrap">
<table class="tbl table-compact">
<thead>
<tr><th>规则</th><th>指标</th><th>阈值</th><th>持续</th><th>静默</th><th>级别</th><th>状态</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="rule in alertRules" :key="rule.ruleKey">
<td>
<strong>{{ rule.name }}</strong>
<div class="small-muted">{{ rule.description || '—' }}</div>
</td>
<td class="small-muted">{{ rule.metric }} {{ rule.comparator }}</td>
<td>
<input
v-model="ruleDrafts[rule.ruleKey]"
class="input"
type="number"
step="any"
style="width: 110px"
:disabled="!canUpdate"
/>
</td>
<td>{{ rule.durationSeconds }}s</td>
<td>{{ rule.silenceMinutes }}min</td>
<td>{{ rule.severity }}</td>
<td><StatusTag :value="rule.enabled ? 'ENABLED' : 'DISABLED'" :label="rule.enabled ? '启用' : '停用'" /></td>
<td>
<button
class="btn btn-sm"
type="button"
:disabled="!canUpdate"
:title="canUpdate ? '' : updateReason"
@click="saveRule(rule)"
>保存</button>
<button
class="btn btn-sm"
type="button"
:disabled="!canUpdate"
:title="canUpdate ? '' : updateReason"
@click="toggleRule(rule)"
>{{ rule.enabled ? '停用' : '启用' }}</button>
</td>
</tr>
</tbody>
</table>
</div>
<div v-else class="small-muted">暂无告警规则。后端首次评估会自动写入默认规则,也可检查告警评估任务是否运行。</div>
</div>
</template>
File diff suppressed because it is too large Load Diff
+211 -53
View File
@@ -1,24 +1,112 @@
<script setup>
import { onMounted, ref } from 'vue'
import { computed, onMounted, ref } from 'vue'
import { api } from '../api'
import { demoState, MOCK_NOTE, setDemoEnabled } from '../demo/config'
import { PLANNED_DEPS, settingsValues } from '../demo/planned'
import { describeError, formatTime, notify } from '../ui'
import PageHead from '../components/PageHead.vue'
import DemoBadge from '../components/DemoBadge.vue'
import Select from '../components/ui/Select.vue'
import { can, denialReason } from '../permissions'
const tab = ref('basic')
const NOTIFY_CHANNEL_OPTIONS = [{ value: 'IN_APP', label: 'IN_APP(站内)' }]
const tab = ref('retention')
const instance = ref(null)
const instanceError = ref('')
const dark = ref(document.documentElement.style.colorScheme === 'dark')
const items = ref([])
const loading = ref(false)
const error = ref(null)
const saving = ref(false)
const canRead = computed(() => can('setting.read'))
const canUpdate = computed(() => can('setting.update'))
const updateReason = computed(() => denialReason('setting.update', '修改系统设置'))
const retention = computed(() => ({
eventDays: numberValue('retention.eventDays'),
messageDays: numberValue('retention.messageDays'),
mediaDays: numberValue('retention.mediaDays')
}))
const notifyEnabled = computed(() => boolValue('notification.enabled'))
const notifyChannel = computed(() => textValue('notification.channel'))
const sendConfirmEnabled = computed(() => boolValue('send.confirm.enabled'))
function findItem(key) {
return items.value.find((item) => item.key === key)
}
function numberValue(key) {
return Number(findItem(key)?.value ?? 0)
}
function boolValue(key) {
return String(findItem(key)?.value ?? 'false') === 'true'
}
function textValue(key) {
return String(findItem(key)?.value ?? '')
}
function updateLocal(key, value) {
const item = findItem(key)
if (item) item.value = value
}
function setTheme(mode) {
dark.value = mode === 'dark'
document.documentElement.style.colorScheme = dark.value ? 'dark' : 'light'
localStorage.setItem('qlinker.theme', dark.value ? 'dark' : 'light')
}
function toggleDemo() {
setDemoEnabled(!demoState.enabled)
async function loadSettings() {
if (canRead.value === false) return
loading.value = true
error.value = null
try {
const data = await api.settings()
items.value = data?.items || []
} catch (e) {
items.value = []
error.value = describeError(e)
} finally {
loading.value = false
}
}
async function save(key, value) {
if (canUpdate.value === false || saving.value) return
saving.value = true
try {
const item = await api.updateSetting(key, value)
updateLocal(key, item?.value ?? value)
notify('设置已保存', `${key} = ${item?.value ?? value};后端已写入 system_setting 并记录审计。`, 'success')
} catch (e) {
notify('设置保存失败', describeError(e).message, 'error')
} finally {
saving.value = false
}
}
async function saveRetention() {
if (canUpdate.value === false || saving.value) return
saving.value = true
try {
const pairs = [
['retention.eventDays', String(retention.value.eventDays)],
['retention.messageDays', String(retention.value.messageDays)],
['retention.mediaDays', String(retention.value.mediaDays)]
]
for (const [key, value] of pairs) {
const item = await api.updateSetting(key, value)
updateLocal(key, item?.value ?? value)
}
notify('保留策略已保存', '三项保留天数已写入 system_setting 并记录审计。', 'success')
} catch (e) {
notify('保留策略保存失败', describeError(e).message, 'error')
} finally {
saving.value = false
}
}
onMounted(async () => {
@@ -27,11 +115,15 @@ onMounted(async () => {
} catch {
instanceError.value = '实例初始化信息读取失败(后端可能未启动)。'
}
loadSettings()
})
</script>
<template>
<PageHead kicker="平台管理" title="系统设置" desc="实例身份来自后端;外观与演示数据开关为本地真实设置;业务配置项后端尚未提供。">
<PageHead kicker="平台管理" title="系统设置" desc="保留策略与通知配置由后端 system_setting 提供读写接口;未知键与越界值由后端拒绝。">
<template #actions>
<button class="btn" type="button" :disabled="loading" @click="loadSettings">{{ loading ? '刷新中…' : '刷新配置' }}</button>
</template>
</PageHead>
<div class="card" style="margin-bottom: 16px">
@@ -48,77 +140,143 @@ onMounted(async () => {
</div>
</div>
<div class="tabs">
<button class="tab" :class="{ active: tab === 'basic' }" type="button" @click="tab = 'basic'">基础</button>
<button class="tab" :class="{ active: tab === 'notify' }" type="button" @click="tab = 'notify'">通知</button>
<button class="tab" :class="{ active: tab === 'appearance' }" type="button" @click="tab = 'appearance'">外观与预览</button>
<button class="tab" :class="{ active: tab === 'data' }" type="button" @click="tab = 'data'">数据</button>
<div v-if="canRead === false" class="notice warn"><strong>缺少权限</strong><span>{{ denialReason('setting.read', '读取系统设置') }}</span></div>
<div v-if="error" class="notice danger">
<strong>{{ error.title }}</strong><span>{{ error.message }}</span>
<button class="btn sm" type="button" @click="loadSettings">重试</button>
</div>
<div v-if="tab === 'basic'" class="card">
<div class="card-head"><h3 class="card-title">基础配置<DemoBadge /></h3><span class="small-muted">后端未提供实例设置接口</span></div>
<div class="form-grid">
<div class="tabs">
<button class="tab" :class="{ active: tab === 'retention' }" type="button" @click="tab = 'retention'">数据保留</button>
<button class="tab" :class="{ active: tab === 'notify' }" type="button" @click="tab = 'notify'">通知</button>
<button class="tab" :class="{ active: tab === 'send' }" type="button" @click="tab = 'send'">发送</button>
<button class="tab" :class="{ active: tab === 'appearance' }" type="button" @click="tab = 'appearance'">外观</button>
<button class="tab" :class="{ active: tab === 'catalog' }" type="button" @click="tab = 'catalog'">配置项</button>
</div>
<div v-if="tab === 'retention'" class="card">
<div class="card-head">
<h3 class="card-title">数据保留</h3>
<span class="pill">system_setting</span>
</div>
<div v-if="loading && !items.length" class="loading-row"><span class="spinner"></span>正在读取设置…</div>
<div v-else class="form-grid">
<div class="fld">
<label for="set-name">实例名称</label>
<input id="set-name" class="field" :value="settingsValues.instanceName" disabled />
<label for="set-event-days">原始事件保留天数</label>
<input id="set-event-days" v-model.number="retention.eventDays" class="field" type="number" min="1" max="3650" :disabled="canUpdate === false" />
</div>
<div class="fld">
<label for="set-code">实例编号</label>
<input id="set-code" class="field" :value="settingsValues.instanceCode" disabled />
<label for="set-message-days">归一化消息保留天数</label>
<input id="set-message-days" v-model.number="retention.messageDays" class="field" type="number" min="1" max="3650" :disabled="canUpdate === false" />
</div>
<div class="fld">
<label for="set-tz">时区</label>
<input id="set-tz" class="field" :value="settingsValues.timezone" disabled />
</div>
<div class="fld">
<label for="set-retention">消息保留天数</label>
<input id="set-retention" class="field" :value="settingsValues.retention" disabled />
<label for="set-media-days">媒体对象保留天数</label>
<input id="set-media-days" v-model.number="retention.mediaDays" class="field" type="number" min="1" max="3650" :disabled="canUpdate === false" />
</div>
</div>
<div class="form-actions">
<button class="btn primary" type="button" disabled title="后端未提供实例设置保存接口">保存设置</button>
<button class="btn primary" type="button" :disabled="saving || canUpdate === false" v-tooltip="canUpdate === false ? updateReason : '保存保留策略'" @click="saveRetention">
{{ saving ? '保存中…' : '保存保留策略' }}
</button>
</div>
<p class="small-muted" style="margin-top: 10px">依赖:{{ PLANNED_DEPS.settings.join('、') }}</p>
<p class="small-muted" style="margin-top: 10px">取值范围 1–3650 天;后端在写入前校验,越界返回 400。此处只保存策略值,实际清理任务由运维流程执行。</p>
</div>
<div v-else-if="tab === 'notify'" class="card">
<div class="card-head"><h3 class="card-title">通知<DemoBadge /></h3><span class="small-muted">演示数据</span></div>
<div class="context-line"><span>实时事件提醒</span><span>{{ settingsValues.realtime ? '开启' : '关闭' }}</span></div>
<div class="context-line"><span>移动端通知</span><span>{{ settingsValues.mobileNotify ? '开启' : '关闭' }}</span></div>
<div class="form-actions">
<button class="btn" type="button" disabled title="后端未提供通知设置接口">保存</button>
<div class="card-head">
<h3 class="card-title">通知</h3>
<span class="pill">站内</span>
</div>
<div class="kv">
<div class="kv-row">
<span>启用站内通知</span>
<span>
<button
class="btn sm"
:class="{ primary: notifyEnabled }"
type="button"
:disabled="saving || canUpdate === false"
@click="save('notification.enabled', notifyEnabled ? 'false' : 'true')"
>
{{ notifyEnabled ? '已开启' : '已关闭' }}
</button>
</span>
</div>
<div class="kv-row">
<span>通知渠道</span>
<span>
<Select
:model-value="notifyChannel"
:options="NOTIFY_CHANNEL_OPTIONS"
style="width: 140px"
:disabled="saving || canUpdate === false"
aria-label="通知渠道"
@update:model-value="(value) => save('notification.channel', value)"
/>
</span>
</div>
<div class="kv-row"><span>第三方渠道</span><span>未开放:notification.channel.manage(后端未实现外部通知渠道)</span></div>
</div>
<p class="small-muted" style="margin-top: 10px">修改写入 system_setting 并记录 setting.update 审计。</p>
</div>
<div v-else-if="tab === 'send'" class="card">
<div class="card-head">
<h3 class="card-title">发送</h3>
<span class="pill">system_setting</span>
</div>
<div class="kv">
<div class="kv-row">
<span>手动发送二次确认</span>
<span>
<button
class="btn sm"
:class="{ primary: sendConfirmEnabled }"
type="button"
:disabled="saving || canUpdate === false"
@click="save('send.confirm.enabled', sendConfirmEnabled ? 'false' : 'true')"
>
{{ sendConfirmEnabled ? '已开启' : '已关闭' }}
</button>
</span>
</div>
</div>
<p class="small-muted" style="margin-top: 10px">关闭后,消息中心手动发送不再弹出确认框,确认后直接调用统一发送服务;可在此重新开启。修改写入 system_setting 并记录 setting.update 审计。</p>
</div>
<div v-else-if="tab === 'appearance'" class="card">
<div class="card-head"><h3 class="card-title">外观与预览</h3><span class="pill">本地真实设置</span></div>
<div class="card-head">
<h3 class="card-title">外观</h3>
<span class="pill">本地设置</span>
</div>
<div class="context-line"><span>主题</span><span>{{ dark ? '深色' : '浅色' }}</span></div>
<div class="actions" style="margin: 10px 0 18px">
<button class="btn sm" :class="{ primary: !dark }" type="button" @click="setTheme('light')">浅色</button>
<button class="btn sm" :class="{ primary: dark }" type="button" @click="setTheme('dark')">深色</button>
</div>
<p class="small-muted">主题保存在浏览器本地(localStorage),不写入后端配置。</p>
<div class="drawer-section" style="margin-top: 14px">
<h4>演示数据总开关</h4>
<div class="context-line">
<span>演示数据</span>
<button class="btn sm" :class="{ primary: demoState.enabled }" type="button" @click="toggleDemo">
{{ demoState.enabled ? '已开启' : '已关闭' }}
</button>
</div>
<p class="small-muted" style="margin-top: 10px">{{ demoState.enabled ? MOCK_NOTE : '演示数据已关闭:所有未实现页面整体显示「未开发 / 规划中」,按钮保持禁用并标注原因。' }}</p>
<p class="small-muted">默认值由构建变量 VITE_ENABLE_MOCK 决定;本地切换会覆盖默认值并持久化。</p>
</div>
<p class="small-muted">主题保存在浏览器 localStorage,不写入后端配置。</p>
</div>
<div v-else class="card">
<div class="card-head"><h3 class="card-title">数据与迁移<DemoBadge /></h3><span class="small-muted">后端未提供迁移与容量接口</span></div>
<div class="context-line"><span>数据库迁移版本</span><span>—</span></div>
<div class="context-line"><span>对象存储使用量</span><span>—</span></div>
<div class="context-line"><span>日志保留策略</span><span>7 天(演示)</span></div>
<div class="form-actions">
<button class="btn" type="button" disabled title="后端未提供迁移接口">执行迁移</button>
<div class="card-head">
<h3 class="card-title">配置项目录</h3>
<span class="pill">{{ items.length }} 项</span>
</div>
<div v-if="!items.length" class="empty-line">没有可读取的配置项。</div>
<div v-else class="table-wrap">
<table class="tbl table-compact">
<thead><tr><th>键</th><th>当前值</th><th>默认值</th><th>类型</th><th>来源</th><th>更新时间</th></tr></thead>
<tbody>
<tr v-for="item in items" :key="item.key">
<td><code class="code">{{ item.key }}</code><div class="small-muted">{{ item.description }}</div></td>
<td>{{ item.value }}</td>
<td class="small-muted">{{ item.defaultValue }}</td>
<td>{{ item.valueType }}</td>
<td><span class="status" :class="item.source === 'DATABASE' ? 'success' : 'neutral'">{{ item.source === 'DATABASE' ? '已配置' : '默认值' }}</span></td>
<td class="small-muted">{{ item.updatedAt ? formatTime(item.updatedAt) : '—' }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
+110
View File
@@ -0,0 +1,110 @@
<script setup>
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { aiApi } from '../../api/ai'
import ChannelPanel from './ChannelPanel.vue'
import CallPanel from './CallPanel.vue'
import ToolPanel from './ToolPanel.vue'
import GovernancePanel from './GovernancePanel.vue'
const route = useRoute()
const router = useRouter()
const TABS = [
{ key: 'channels', label: '渠道', hint: '模型服务商与模型能力合并管理' },
{ key: 'calls', label: '调用与成本', hint: '用量、成本、耗时与错误分类' },
{ key: 'tools', label: '工具授权', hint: '风险分级、人工确认与执行审计' },
{ key: 'governance', label: '治理设置', hint: '脱敏、缓存与记忆保留' }
]
const tab = ref(String(route.query.tab || 'channels'))
if (!TABS.some((item) => item.key === tab.value)) tab.value = 'channels'
const counts = ref({ channels: null, tools: null })
const channelMeta = ref({ reserved: 0, unverified: 0 })
async function loadCounts() {
const [providerRows, modelRows, pending] = await Promise.allSettled([
aiApi.providers(),
aiApi.models(),
aiApi.toolCalls({ authorizationStatus: 'APPROVAL_REQUIRED', executionStatus: 'PENDING', page: 1, pageSize: 1 })
])
const providers = providerRows.status === 'fulfilled' ? (providerRows.value || []) : []
const models = modelRows.status === 'fulfilled' ? (modelRows.value || []) : []
counts.value = {
channels: providerRows.status === 'fulfilled' ? providers.length : null,
tools: pending.status === 'fulfilled' ? Number(pending.value?.total || 0) : null
}
channelMeta.value = {
reserved: providers.filter((item) => item.providerStatus !== 'ACTIVE').length,
unverified: models.filter((item) => item.modelStatus === 'UNVERIFIED').length
}
}
function select(key) {
if (tab.value === key) return
tab.value = key
router.replace({ query: { ...route.query, tab: key === 'channels' ? undefined : key } })
loadCounts()
}
watch(() => route.query.tab, (value) => {
const next = value ? String(value) : 'channels'
if (TABS.some((item) => item.key === next) && next !== tab.value) tab.value = next
})
loadCounts()
</script>
<template>
<div class="tabs-row">
<div class="tabs">
<button
v-for="item in TABS"
:key="item.key"
class="tab"
:class="{ active: tab === item.key }"
type="button" v-tooltip="item.hint"
@click="select(item.key)"
>
{{ item.label }}
<span
v-if="item.key === 'channels' && counts.channels"
:class="tab === 'channels' ? 'tab-badge' : 'tab-count'"
>{{ counts.channels }}</span>
<span
v-else-if="item.key === 'tools' && counts.tools"
:class="tab === 'tools' ? 'tab-badge' : 'tab-count'"
>{{ counts.tools }}</span>
</button>
</div>
<div v-if="tab === 'channels'" class="tab-side">
<span v-if="channelMeta.reserved" class="side-pill amber">预留 {{ channelMeta.reserved }}</span>
<span v-if="channelMeta.unverified" class="side-pill">未验证 {{ channelMeta.unverified }} 项</span>
</div>
</div>
<ChannelPanel v-if="tab === 'channels'" @changed="loadCounts" />
<CallPanel v-else-if="tab === 'calls'" />
<ToolPanel v-else-if="tab === 'tools'" />
<GovernancePanel v-else />
</template>
<style scoped>
.tabs-row {
display: flex; align-items: center; gap: 16px; border-bottom: 1px solid #edf0f5; margin-bottom: 12px;
}
.tabs-row .tabs { flex: 1; margin: 0; border-bottom: 0; }
.tab-badge {
display: inline-flex; align-items: center; justify-content: center; min-width: 16px; height: 16px;
margin-left: 5px; padding: 0 5px; border-radius: 8px; background: #eef0fe; color: #4f5bef;
font-size: 9px; font-weight: 600; line-height: 1; vertical-align: 1px; font-variant-numeric: tabular-nums;
}
.tab-count { margin-left: 5px; color: #9aa1b2; font-size: 9px; font-variant-numeric: tabular-nums; }
.tab-side { display: flex; flex: none; gap: 8px; padding-right: 2px; }
.side-pill {
display: inline-flex; align-items: center; height: 20px; padding: 0 7px; border-radius: 4px;
background: #f3f4f6; color: #6b7280; font-size: 10px;
}
.side-pill.amber { background: #fffbeb; color: #b45309; }
</style>
+820
View File
@@ -0,0 +1,820 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { aiApi } from '../../api/ai'
import { describeError, formatNumber, formatShortTime, formatTime, notify } from '../../ui'
import DetailDrawer from '../../components/DetailDrawer.vue'
import Pagination from '../../components/Pagination.vue'
import Select from '../../components/ui/Select.vue'
import Checkbox from '../../components/ui/Checkbox.vue'
import { accountParam, accountState } from '../../account-context.js'
/**
* AI 中心 · 调用与成本(对齐 05-ai-tools 画板,即「调用与成本」页)。
* 所有指标与记录都来自 /ai/calls 与 /ai/calls/summary;成本不可用时显示「不可用」,不推算。
*/
const STATUS_LABEL = {
SUCCEEDED: '成功',
FAILED: '失败',
TIMEOUT: '超时',
DEGRADED: '降级',
UNKNOWN: '结果未知',
PENDING: '进行中'
}
const SOURCE_LABEL = {
API: '接口调用',
RULE: '规则引擎',
AUTOMATION: '自动化规则',
MESSAGE: '消息中心',
TOOL: '工具调用',
MANUAL: '手动调用',
TEST: '连通性测试'
}
const ERROR_LABEL = {
AI_PROVIDER_UNAVAILABLE: '服务商不可用',
AI_PROVIDER_TIMEOUT: '调用超时',
AI_PROVIDER_RESULT_UNKNOWN: '结果未知',
AI_MODEL_NOT_FOUND: '模型不存在',
AI_MODEL_UNSUPPORTED: '模型能力不支持',
AI_INPUT_REJECTED: '请求参数不合法',
AI_STATE_CONFLICT: '状态冲突',
AI_TOOL_NOT_ALLOWED: '工具未获授权',
AI_TOOL_APPROVAL_REQUIRED: '待人工确认',
AI_TOOL_ARGUMENT_INVALID: '工具参数不合法',
AI_TOOL_RATE_LIMITED: '工具触发限流',
AI_TOOL_EXECUTION_FAILED: '工具执行失败',
AI_REDACTION_FORBIDDEN: '脱敏被拒绝',
AI_DISABLED: 'AI 能力已停用'
}
const REDACTION_LABEL = { NONE: '不脱敏', BASIC: '基础', STRICT: '严格' }
const OPTIONAL_COLUMNS = [
{ key: 'source', label: '来源' },
{ key: 'cache', label: '缓存' },
{ key: 'redaction', label: '脱敏' }
]
const route = useRoute()
const router = useRouter()
const rows = ref([])
const providers = ref([])
const models = ref([])
const summary = ref(null)
const loading = ref(false)
const error = ref(null)
const exporting = ref(false)
const range = ref('7d')
const errorOptions = ref([])
const sourceOptions = ref([])
const filters = ref({ providerUid: '', modelUid: '', status: '', sourceType: '', errorCode: '', keyword: '' })
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)
const detailOpen = ref(false)
const detail = ref(null)
const columnsOpen = ref(false)
const hiddenColumns = ref(loadColumnPrefs())
const loadedAt = ref('')
const governance = ref(null)
const redactionMode = computed(() => governance.value?.defaultRedactionMode || '')
const loadedTimeText = computed(() => (loadedAt.value ? formatTime(loadedAt.value).slice(11) : '—'))
const retentionText = computed(() => governance.value?.memory?.defaultRetentionDays
? `${governance.value.memory.defaultRetentionDays} 天` : '—')
const RANGES = [
{ key: 'today', label: '今日' },
{ key: '7d', label: '近 7 天' },
{ key: '30d', label: '近 30 天' }
]
function loadColumnPrefs() {
try {
const raw = localStorage.getItem('qlinker.ai.calls.columns')
const parsed = raw ? JSON.parse(raw) : []
return Array.isArray(parsed) ? parsed : []
} catch {
return []
}
}
function saveColumnPrefs() {
try {
localStorage.setItem('qlinker.ai.calls.columns', JSON.stringify(hiddenColumns.value))
} catch {
/* 本地存储不可用时只影响偏好记忆,不阻断查询 */
}
}
function toggleColumn(key) {
const list = hiddenColumns.value
hiddenColumns.value = list.includes(key) ? list.filter((item) => item !== key) : [...list, key]
saveColumnPrefs()
}
function isHidden(key) {
return hiddenColumns.value.includes(key)
}
const period = computed(() => {
const now = new Date()
if (range.value === 'today') {
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate())
return { from: start.toISOString(), to: now.toISOString() }
}
const days = range.value === '30d' ? 30 : 7
return { from: new Date(now.getTime() - days * 86400000).toISOString(), to: now.toISOString() }
})
const modelOptions = computed(() => {
const list = filters.value.providerUid
? models.value.filter((model) => model.providerUid === filters.value.providerUid)
: models.value
return list
})
// 筛选下拉选项:把后端返回的列表转成统一 { value, label } 结构。
const providerSelectOptions = computed(() => [
{ value: '', label: '全部' },
...providers.value.map((provider) => ({
value: provider.providerUid,
label: provider.providerName || provider.providerCode
}))
])
const modelSelectOptions = computed(() => [
{ value: '', label: '全部' },
...modelOptions.value.map((model) => ({
value: model.modelUid,
label: model.displayName || model.modelCode
}))
])
const sourceSelectOptions = computed(() => [
{ value: '', label: '全部' },
...sourceOptions.value.map((item) => ({
value: item.sourceType,
label: `${sourceLabel(item.sourceType)}(${formatNumber(item.calls)})`
}))
])
const statusSelectOptions = computed(() => [
{ value: '', label: '全部' },
...Object.keys(STATUS_LABEL).map((key) => ({ value: key, label: STATUS_LABEL[key] }))
])
const errorSelectOptions = computed(() => [
{ value: '', label: '全部' },
...errorOptions.value.map((item) => ({
value: item.errorCode,
label: ERROR_LABEL[item.errorCode] || item.errorCode
}))
])
const kpi = computed(() => {
const data = summary.value || {}
const totalCalls = Number(data.totalCalls || 0)
const failed = Number(data.failed || 0) + Number(data.timedOut || 0) + Number(data.unknownResult || 0)
return {
totalCalls,
failedRate: totalCalls ? failed / totalCalls : null,
failed,
timedOut: Number(data.timedOut || 0),
unknown: Number(data.unknownResult || 0),
degraded: Number(data.degraded || 0),
tokens: Number(data.inputTokens || 0) + Number(data.outputTokens || 0),
inputTokens: Number(data.inputTokens || 0),
outputTokens: Number(data.outputTokens || 0),
cost: data.estimatedCost === null || data.estimatedCost === undefined ? null : Number(data.estimatedCost),
costUnavailable: Number(data.costUnavailableCalls || 0),
currency: data.currency || '',
cacheRate: totalCalls ? Number(data.cacheHitRate || 0) : null,
cacheHits: Number(data.cacheHits || 0),
cacheMiss: totalCalls - Number(data.cacheHits || 0),
avgLatency: Number(data.avgLatencyMs || 0)
}
})
const trend = computed(() => {
const days = summary.value?.byDay || []
const list = days.map((item) => ({
day: String(item.day || ''),
input: Number(item.inputTokens || 0),
output: Number(item.outputTokens || 0),
calls: Number(item.calls || 0),
failed: Number(item.failed || 0),
cost: Number(item.estimatedCost || 0)
}))
const max = Math.max(1, ...list.map((item) => Math.max(item.input, item.output)))
return list.map((item) => ({
...item,
inputHeight: Math.round((item.input / max) * 100),
outputHeight: Math.round((item.output / max) * 100)
}))
})
const errorRows = computed(() => {
const rowsList = summary.value?.byError || []
const max = Math.max(1, ...rowsList.map((item) => Number(item.calls || 0)))
return rowsList.map((item) => ({
code: item.errorCode || '',
label: ERROR_LABEL[item.errorCode] || item.errorCode || '未分类错误',
status: item.status || '',
calls: Number(item.calls || 0),
width: Math.round((Number(item.calls || 0) / max) * 100)
}))
})
const errorTotal = computed(() => errorRows.value.reduce((sum, item) => sum + item.calls, 0))
const cacheHitText = computed(() => {
if (kpi.value.cacheRate === null) return '—'
return `${(kpi.value.cacheRate * 100).toFixed(0)}%`
})
function tokenText(value) {
if (value >= 10000) return `${(value / 10000).toFixed(1)} 万`
return formatNumber(value)
}
function percentText(value) {
return value === null || value === undefined ? '—' : `${(value * 100).toFixed(1)}%`
}
function sourceLabel(value) {
return SOURCE_LABEL[String(value || '').toUpperCase()] || value || '—'
}
function statusLabel(value) {
return STATUS_LABEL[String(value || '').toUpperCase()] || value || '—'
}
function statusClass(value) {
const text = String(value || '').toUpperCase()
if (text === 'SUCCEEDED') return 'success'
if (text === 'DEGRADED' || text === 'TIMEOUT' || text === 'UNKNOWN') return 'warning'
if (text === 'FAILED') return 'danger'
return 'muted'
}
function redactionLabel(value) {
return REDACTION_LABEL[String(value || '').toUpperCase()] || value || '—'
}
function costText(value, currency) {
if (value === null || value === undefined) return '不可用'
return `${currency || ''} ${Number(value).toFixed(2)}`.trim()
}
function latencyText(value) {
const number = Number(value)
if (!Number.isFinite(number)) return '—'
return `${(number / 1000).toFixed(1)} 秒`
}
function errorText(err) {
const base = describeError(err)
return `${base.title}。${base.hint}`
}
async function load() {
// 没有可用账号时不发跨账号聚合请求,调用记录与用量显示空态。
if (!accountParam()) {
rows.value = []
summary.value = null
total.value = 0
error.value = null
loading.value = false
return
}
loading.value = true
error.value = null
const params = {
providerUid: filters.value.providerUid,
modelUid: filters.value.modelUid,
status: filters.value.status,
sourceType: filters.value.sourceType,
errorCode: filters.value.errorCode,
keyword: filters.value.keyword,
from: period.value.from,
to: period.value.to,
qqAccount: accountParam() || undefined
}
try {
const [pageData, summaryData] = await Promise.all([
aiApi.calls({ ...params, page: page.value, pageSize: pageSize.value }),
aiApi.callSummary(params)
])
rows.value = pageData?.items || []
page.value = pageData?.page || page.value
pageSize.value = pageData?.pageSize || pageSize.value
total.value = pageData?.total || 0
summary.value = summaryData || null
if (!filters.value.errorCode) errorOptions.value = summaryData?.byError || []
if (!filters.value.sourceType) sourceOptions.value = summaryData?.bySource || []
loadedAt.value = new Date().toISOString()
} catch (e) {
rows.value = []
summary.value = null
total.value = 0
error.value = errorText(e)
} finally {
loading.value = false
}
}
async function loadProviders() {
try {
const [providerRows, modelRows, governanceData] = await Promise.all([
aiApi.providers(), aiApi.models(), aiApi.governance()
])
providers.value = providerRows || []
models.value = modelRows || []
governance.value = governanceData || null
} catch {
providers.value = []
models.value = []
governance.value = null
}
}
function changeRange(key) {
if (range.value === key) return
range.value = key
page.value = 1
load()
}
let keywordTimer = 0
function onKeywordInput() {
window.clearTimeout(keywordTimer)
keywordTimer = window.setTimeout(() => {
page.value = 1
load()
}, 350)
}
function onFilterChange() {
page.value = 1
load()
}
function reset() {
filters.value = { providerUid: '', modelUid: '', status: '', sourceType: '', errorCode: '', keyword: '' }
page.value = 1
load()
}
function onPageChange(next) {
page.value = next.page
pageSize.value = next.pageSize
load()
}
function openDetail(row) {
detail.value = row
detailOpen.value = true
}
async function exportCsv() {
if (exporting.value) return
exporting.value = true
const base = {
providerUid: filters.value.providerUid,
modelUid: filters.value.modelUid,
status: filters.value.status,
sourceType: filters.value.sourceType,
errorCode: filters.value.errorCode,
keyword: filters.value.keyword,
from: period.value.from,
to: period.value.to
}
const collected = []
const cap = 1000
try {
let current = 1
while (collected.length < cap) {
const data = await aiApi.calls({ ...base, page: current, pageSize: 100 })
const items = data?.items || []
collected.push(...items)
const fetched = (data?.page || current) * (data?.pageSize || 100)
if (!items.length || fetched >= Number(data?.total || 0)) break
current += 1
}
} catch (e) {
exporting.value = false
error.value = errorText(e)
return
}
const header = ['时间', '调用标识', '服务商', '模型', '来源', '状态', '耗时(毫秒)', '输入Token', '输出Token', '估算成本', '币种', '缓存命中', '脱敏模式', '错误码']
const lines = collected.map((row) => [
formatTime(row.createdAt),
row.callUid,
row.providerName || row.providerUid || '',
row.modelName || row.modelCode || '',
sourceLabel(row.sourceType),
statusLabel(row.status),
row.latencyMs ?? '',
row.inputTokens ?? '',
row.outputTokens ?? '',
row.estimatedCost ?? '',
row.currency || '',
row.cacheHit ? '命中' : '未命中',
redactionLabel(row.redactionMode),
row.errorCode || ''
])
const csv = [header, ...lines]
.map((cells) => cells.map((cell) => `"${String(cell ?? '').replace(/"/g, '""')}"`).join(','))
.join('\r\n')
const blob = new Blob([`\ufeff${csv}`], { type: 'text/csv;charset=utf-8' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = `ai-calls-${new Date().toISOString().slice(0, 10)}.csv`
link.click()
URL.revokeObjectURL(url)
exporting.value = false
notify('导出完成', `已导出 ${lines.length} 条调用记录(最多 ${cap} 条)。`, 'success')
}
function goGovernance() {
router.replace({ query: { ...route.query, tab: 'governance' } })
}
onMounted(() => {
loadProviders()
load()
})
onBeforeUnmount(() => {
window.clearTimeout(keywordTimer)
})
// 切换 QQ 账号后回到第 1 页重新加载调用记录与汇总。
watch(() => accountState.current, () => {
page.value = 1
load()
})
watch(() => filters.value.providerUid, () => {
if (filters.value.modelUid && !modelOptions.value.some((item) => item.modelUid === filters.value.modelUid)) {
filters.value.modelUid = ''
}
})
</script>
<template>
<section class="ai-calls">
<div class="toolbar">
<div class="range-group">
<button
v-for="item in RANGES"
:key="item.key"
class="range-btn"
:class="{ active: range === item.key }"
type="button"
@click="changeRange(item.key)"
>{{ item.label }}</button>
</div>
<label class="filter-field">
<span>服务商</span>
<Select v-model="filters.providerUid" :options="providerSelectOptions" aria-label="服务商筛选" @update:model-value="onFilterChange" />
</label>
<label class="filter-field">
<span>模型</span>
<Select v-model="filters.modelUid" :options="modelSelectOptions" aria-label="模型筛选" @update:model-value="onFilterChange" />
</label>
<label class="filter-field">
<span>来源</span>
<Select v-model="filters.sourceType" :options="sourceSelectOptions" aria-label="调用来源筛选" @update:model-value="onFilterChange" />
</label>
<label class="filter-field">
<span>状态</span>
<Select v-model="filters.status" :options="statusSelectOptions" aria-label="调用状态筛选" @update:model-value="onFilterChange" />
</label>
<label class="filter-field">
<span>错误分类</span>
<Select v-model="filters.errorCode" :options="errorSelectOptions" aria-label="错误分类筛选" @update:model-value="onFilterChange" />
</label>
<label class="search-field">
<input v-model="filters.keyword" type="search" placeholder="搜索调用标识 / 来源标识" @input="onKeywordInput" />
</label>
<div class="columns-wrap">
<button class="btn sm" type="button" :class="{ primary: columnsOpen }" :aria-pressed="columnsOpen"
@click="columnsOpen = !columnsOpen">列设置</button>
<div v-if="columnsOpen" class="columns-pop">
<Checkbox
v-for="item in OPTIONAL_COLUMNS"
:key="item.key"
class="columns-item"
:model-value="!isHidden(item.key)"
:label="item.label"
@update:model-value="toggleColumn(item.key)"
/>
</div>
</div>
<span class="toolbar-meta">数据截至 {{ loadedTimeText }}</span>
<button class="btn sm" type="button" :disabled="exporting || loading" @click="exportCsv">
{{ exporting ? '导出中…' : '导出表格' }}
</button>
</div>
<p v-if="error" class="inline-error">{{ error }}</p>
<div class="kpi-row">
<div class="card kpi-cell">
<span class="kpi-label">调用量</span>
<strong class="kpi-value">{{ formatNumber(kpi.totalCalls) }} <em>次</em></strong>
<span class="kpi-note">按当前筛选统计</span>
</div>
<div class="card kpi-cell">
<span class="kpi-label">失败率</span>
<strong class="kpi-value" :class="kpi.failedRate && kpi.failedRate > 0.1 ? 'danger' : ''">
{{ percentText(kpi.failedRate) }}
</strong>
<span class="kpi-note">
失败 {{ formatNumber(kpi.failed) }} 次 · 超时 {{ formatNumber(kpi.timedOut) }}
· 结果未知 {{ formatNumber(kpi.unknown) }}
</span>
</div>
<div class="card kpi-cell">
<span class="kpi-label">全局总耗</span>
<strong class="kpi-value">{{ tokenText(kpi.tokens) }}</strong>
<span class="kpi-note">输入 {{ tokenText(kpi.inputTokens) }} · 输出 {{ tokenText(kpi.outputTokens) }}</span>
</div>
<div class="card kpi-cell">
<span class="kpi-label">估算成本</span>
<strong class="kpi-value">{{ kpi.cost === null ? '不可用' : `${kpi.currency} ${kpi.cost.toFixed(2)}` }}</strong>
<span class="kpi-note">成本不可用 {{ formatNumber(kpi.costUnavailable) }} 次 · 按服务商单价估算</span>
</div>
<div class="card kpi-cell">
<span class="kpi-label">缓存命中</span>
<strong class="kpi-value">{{ cacheHitText }}</strong>
<span class="kpi-note">命中 {{ formatNumber(kpi.cacheHits) }} 次 · 未命中 {{ formatNumber(kpi.cacheMiss) }} 次</span>
</div>
</div>
<div class="content-grid">
<div class="card table-card">
<div class="table-head">
<div>
<h3>调用记录</h3>
<p class="table-sub">仅展示元数据、用量、耗时与成本,不展示提示词与模型响应。</p>
</div>
<div class="table-tags">
<span v-if="redactionMode" class="tag">脱敏:{{ redactionLabel(redactionMode) }}</span>
<span class="tag">成本不可用时显示「不可用」</span>
</div>
</div>
<p v-if="accountState.current" class="table-sub" style="margin: 0 0 8px">
当前按 QQ 账号筛选:仅显示可经规则执行任务追溯到该账号的调用;无法归属的调用记录不计入。
</p>
<div v-if="loading" class="inline-loading">正在加载调用记录…</div>
<div v-else-if="!rows.length" class="empty-state">
<p>当前条件下没有调用记录。</p>
<p class="muted-text">成功、失败、超时与降级调用都会留下记录;成本不可用时显示「不可用」。</p>
</div>
<div v-else class="table-wrap">
<table class="call-table">
<thead>
<tr>
<th>时间</th>
<th>调用标识</th>
<th>服务商 / 模型</th>
<th v-if="!isHidden('source')">来源</th>
<th>状态</th>
<th>耗时</th>
<th>输入 / 输出</th>
<th>成本</th>
<th v-if="!isHidden('cache')">缓存</th>
<th v-if="!isHidden('redaction')">脱敏</th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.callUid" @click="openDetail(row)">
<td class="nowrap">{{ formatShortTime(row.createdAt) }}</td>
<td class="mono">{{ row.callUid }}</td>
<td>
<strong>{{ row.modelName || row.modelCode || '—' }}</strong>
<div class="cell-sub">{{ row.providerName || row.providerUid }}</div>
</td>
<td v-if="!isHidden('source')" class="cell-sub">{{ sourceLabel(row.sourceType) }}</td>
<td>
<span class="status-pill" :class="statusClass(row.status)">{{ statusLabel(row.status) }}</span>
<div v-if="row.errorCode" class="cell-sub">{{ ERROR_LABEL[row.errorCode] || row.errorCode }}</div>
</td>
<td class="nowrap">{{ latencyText(row.latencyMs) }}</td>
<td class="nowrap">{{ formatNumber(row.inputTokens) }} / {{ formatNumber(row.outputTokens) }}</td>
<td class="nowrap">{{ costText(row.estimatedCost, row.currency) }}</td>
<td v-if="!isHidden('cache')">{{ row.cacheHit ? '命中' : '未命中' }}</td>
<td v-if="!isHidden('redaction')">{{ redactionLabel(row.redactionMode) }}</td>
</tr>
</tbody>
</table>
</div>
<div class="table-foot">
<span class="muted-text">共 {{ formatNumber(total) }} 条 · 每页 {{ pageSize }} 条</span>
<Pagination :page="page" :page-size="pageSize" :total="total" @change="onPageChange" />
</div>
</div>
<aside class="side-col">
<div class="card side-card">
<header class="side-head">
<h3>成本趋势 · {{ range === 'today' ? '今日' : range === '30d' ? '近 30 天' : '近 7 天' }}</h3>
<span class="side-meta">合计 {{ kpi.cost === null ? '不可用' : `${kpi.currency} ${kpi.cost.toFixed(2)}` }}</span>
</header>
<div v-if="!trend.length" class="side-empty">当前时间范围内没有调用数据。</div>
<div v-else class="bar-chart">
<div v-for="item in trend" :key="item.day" class="bar-col" v-tooltip="`${item.day}:输入 ${formatNumber(item.input)} · 输出 ${formatNumber(item.output)} · 调用 ${item.calls} 次`">
<div class="bar-stack">
<span class="bar bar-input" :style="{ height: `${item.inputHeight}%` }"></span>
<span class="bar bar-output" :style="{ height: `${item.outputHeight}%` }"></span>
</div>
<span class="bar-label">{{ item.day.slice(5) }}</span>
</div>
</div>
<div class="chart-legend">
<span><i class="dot dot-input"></i>输入 Token</span>
<span><i class="dot dot-output"></i>输出 Token</span>
</div>
</div>
<div class="card side-card">
<header class="side-head">
<h3>错误分类</h3>
<span class="side-meta">{{ formatNumber(errorTotal) }} 次</span>
</header>
<div v-if="!errorRows.length" class="side-empty">当前时间范围没有失败或超时记录。</div>
<ul v-else class="error-list">
<li v-for="item in errorRows" :key="`${item.code}-${item.status}`">
<span class="error-name">{{ item.label }}</span>
<span class="error-bar"><i :style="{ width: `${item.width}%` }"></i></span>
<span class="error-count">{{ formatNumber(item.calls) }}</span>
</li>
</ul>
<p class="side-note">统计口径来自错误码分组;超时与限流独立计数,降级与结果未知单列,不混入成功。</p>
</div>
<div class="card side-card">
<header class="side-head">
<h3>数据最小化</h3>
<span class="tag success">已启用</span>
</header>
<p class="side-note">
只保存调用元数据、用量、耗时、成本与失败摘要,不保存完整提示词与模型响应。
</p>
<dl class="mini-facts">
<dt>脱敏模式</dt>
<dd>{{ redactionLabel(redactionMode) }}<template v-if="redactionMode">(可切换{{ redactionLabel('STRICT') }})</template></dd>
<dt>记忆保留</dt>
<dd>{{ retentionText }}</dd>
<dt>平均耗时</dt>
<dd>{{ latencyText(kpi.avgLatency) }}</dd>
<dt>降级调用</dt>
<dd>{{ formatNumber(kpi.degraded) }} 次</dd>
</dl>
<button class="link-btn" type="button" @click="goGovernance">进入治理设置 →</button>
</div>
</aside>
</div>
<DetailDrawer :open="detailOpen" title="调用详情" :subtitle="detail?.callUid || ''" @close="detailOpen = false">
<div v-if="detail" class="detail-grid">
<div class="fld"><label>状态</label><div>{{ statusLabel(detail.status) }}</div></div>
<div class="fld"><label>模型</label><div>{{ detail.modelName || detail.modelCode }}({{ detail.modelUid }})</div></div>
<div class="fld"><label>服务商</label><div>{{ detail.providerName || detail.providerUid }}</div></div>
<div class="fld"><label>来源</label><div>{{ sourceLabel(detail.sourceType) }} / {{ detail.sourceId || '—' }}</div></div>
<div class="fld"><label>Token(入 / 出)</label>
<div>{{ formatNumber(detail.inputTokens) }} / {{ formatNumber(detail.outputTokens) }}({{ detail.usageSource || '—' }})</div>
</div>
<div class="fld"><label>估算成本</label>
<div>{{ costText(detail.estimatedCost, detail.currency) }}({{ detail.costSource || '—' }})</div>
</div>
<div class="fld"><label>耗时</label><div>{{ latencyText(detail.latencyMs) }}</div></div>
<div class="fld"><label>脱敏模式</label><div>{{ redactionLabel(detail.redactionMode) }}</div></div>
<div class="fld"><label>缓存 / 工具调用</label>
<div>{{ detail.cacheHit ? '命中缓存' : '未命中' }} / {{ formatNumber(detail.toolCallCount) }}</div>
</div>
<div class="fld"><label>降级回退模型</label><div>{{ detail.fallbackModelConfigId || '未降级' }}</div></div>
<div class="fld"><label>开始 / 结束</label>
<div>{{ formatTime(detail.startedAt) }} → {{ formatTime(detail.finishedAt) }}</div>
</div>
<div class="fld"><label>错误</label>
<div>{{ detail.errorCode ? (ERROR_LABEL[detail.errorCode] || detail.errorCode) : '—' }} {{ detail.errorMessage || '' }}</div>
</div>
</div>
</DetailDrawer>
</section>
</template>
<style scoped>
.ai-calls { display: flex; flex-direction: column; gap: 14px; }
.toolbar {
position: relative; display: flex; align-items: center; flex-wrap: wrap; gap: 10px; padding: 10px 12px;
border: 1px solid light-dark(var(--qk-line, #e5e7eb), #273247); border-radius: 8px;
background: light-dark(var(--qk-card, #fff), #121b2b);
}
.range-group { display: inline-flex; border: 1px solid light-dark(var(--qk-line, #e5e7eb), #273247); border-radius: 6px; overflow: hidden; }
.range-btn {
padding: 5px 12px; font-size: 12px; border: 0; background: transparent; cursor: pointer;
color: light-dark(var(--qk-text-1, #111827), #e7ecf6);
}
.range-btn + .range-btn { border-left: 1px solid light-dark(var(--qk-line, #e5e7eb), #273247); }
.range-btn.active { background: #eef4ff; color: #2558ba; font-weight: 600; }
.filter-field { display: flex; align-items: center; gap: 6px; font-size: 12px; }
.filter-field span { color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.filter-field :deep(.qk-select) { min-width: 96px; }
.filter-field :deep(.el-select__wrapper) { min-height: 28px; font-size: 12px; }
.search-field input { width: 190px; padding: 5px 8px; font-size: 12px; border-radius: 6px; }
.columns-wrap { position: relative; }
.columns-pop {
position: absolute; top: 32px; right: 0; z-index: 12; display: flex; flex-direction: column; gap: 6px;
padding: 8px 12px; border: 1px solid light-dark(var(--qk-line, #e5e7eb), #273247); border-radius: 8px;
background: light-dark(var(--qk-card, #fff), #121b2b); box-shadow: 0 10px 26px rgba(15, 23, 42, 0.16);
}
.columns-item { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; white-space: nowrap; }
.toolbar-meta { margin-left: auto; font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.kpi-row { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 12px; }
.kpi-cell { display: flex; flex-direction: column; gap: 4px; padding: 12px 14px; }
.kpi-label { font-size: 12px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.kpi-value { font-size: 24px; line-height: 1.25; font-variant-numeric: tabular-nums; }
.kpi-value em { font-size: 12px; font-style: normal; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.kpi-value.danger { color: #b42318; }
.kpi-note { font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.content-grid { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 14px; align-items: start; }
.table-card { display: flex; flex-direction: column; gap: 10px; }
.table-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.table-head h3 { margin: 0; font-size: 15px; }
.table-sub { margin: 3px 0 0; font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.table-tags { display: flex; gap: 6px; flex-wrap: wrap; }
.tag {
padding: 1px 7px; font-size: 11px; border-radius: 999px;
border: 1px solid light-dark(var(--qk-line, #e5e7eb), #273247); color: #64748b; background: #f8f9fc;
}
.tag.success { border-color: #b7e2c4; background: #effaf2; color: #15803d; }
.table-wrap { overflow: auto; }
.call-table { width: 100%; border-collapse: collapse; font-size: 12px; }
.call-table th {
padding: 7px 8px; text-align: left; white-space: nowrap; font-weight: 600;
border-bottom: 1px solid light-dark(var(--qk-line, #e5e7eb), #273247);
color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd);
}
.call-table td {
padding: 7px 8px; border-bottom: 1px dashed light-dark(var(--qk-line, #e5e7eb), #273247); vertical-align: top;
}
.call-table tbody tr { cursor: pointer; }
.call-table tbody tr:hover { background: #f7f9fd; }
.mono { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; }
.nowrap { white-space: nowrap; }
.cell-sub { font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.status-pill { padding: 1px 7px; font-size: 11px; border-radius: 999px; }
.status-pill.success { background: #effaf2; color: #15803d; }
.status-pill.warning { background: #fff8e6; color: #b45309; }
.status-pill.danger { background: #fdecec; color: #b42318; }
.status-pill.muted { background: #f4f5f8; color: #64748b; }
.table-foot { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-top: 8px; }
.side-col { display: flex; flex-direction: column; gap: 12px; }
.side-card { display: flex; flex-direction: column; gap: 8px; padding: 12px 14px; }
.side-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.side-head h3 { margin: 0; font-size: 13px; }
.side-meta { font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.side-note { margin: 0; font-size: 11px; line-height: 1.6; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.side-empty { padding: 10px 0; font-size: 12px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.bar-chart { display: flex; align-items: flex-end; gap: 6px; height: 92px; padding-top: 6px; }
.bar-col { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 4px; }
.bar-stack { display: flex; align-items: flex-end; gap: 2px; height: 72px; }
.bar { width: 8px; border-radius: 2px 2px 0 0; min-height: 2px; }
.bar-input { background: #93b4f5; }
.bar-output { background: #2f5fd0; }
.bar-label { font-size: 10px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.chart-legend { display: flex; gap: 12px; font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 2px; margin-right: 4px; vertical-align: middle; }
.dot-input { background: #93b4f5; }
.dot-output { background: #2f5fd0; }
.error-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
.error-list li { display: grid; grid-template-columns: 1fr 82px 34px; align-items: center; gap: 8px; font-size: 12px; }
.error-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.error-bar { display: block; height: 6px; border-radius: 3px; background: #eef1f7; overflow: hidden; }
.error-bar i { display: block; height: 100%; border-radius: 3px; background: linear-gradient(90deg, #f3b46b, #e2582f); }
.error-count { text-align: right; font-variant-numeric: tabular-nums; }
.mini-facts { margin: 0; display: grid; grid-template-columns: auto 1fr; gap: 4px 10px; font-size: 11px; }
.mini-facts dt { color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.mini-facts dd { margin: 0; }
.link-btn { align-self: flex-start; padding: 0; border: 0; background: transparent; color: #2558ba; font-size: 12px; cursor: pointer; }
.inline-error { margin: 0; padding: 10px 12px; border: 1px solid #f0b4b4; border-radius: 8px; background: #fdecec; color: #b42318; font-size: 12px; }
.inline-loading { padding: 16px; font-size: 12px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.empty-state { padding: 26px 12px; text-align: center; border: 1px dashed #d9dce6; border-radius: 8px; }
.empty-state p { margin: 0 0 6px; font-size: 13px; }
.muted-text { font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.detail-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
.fld label { display: block; font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); margin-bottom: 2px; }
.fld div { font-size: 12px; }
</style>
File diff suppressed because it is too large Load Diff
+414
View File
@@ -0,0 +1,414 @@
<script setup>
import { onMounted, ref } from 'vue'
import { aiApi } from '../../api/ai'
import { describeError, formatTime, notify } from '../../ui'
import ConfirmDialog from '../../components/ConfirmDialog.vue'
import Pagination from '../../components/Pagination.vue'
import SectionState from '../../components/SectionState.vue'
import StatusTag from '../../components/StatusTag.vue'
import Select from '../../components/ui/Select.vue'
const SCOPE_TYPE_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'CONVERSATION', label: 'CONVERSATION' },
{ value: 'BINDING', label: 'BINDING' },
{ value: 'INSTANCE', label: 'INSTANCE' }
]
const SCOPE_TYPE_FORM_OPTIONS = SCOPE_TYPE_OPTIONS.slice(1)
const MEMORY_STATUS_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'ACTIVE', label: 'ACTIVE' },
{ value: 'EXPIRED', label: 'EXPIRED' },
{ value: 'DELETED', label: 'DELETED' }
]
const MEMORY_TYPE_OPTIONS = [
{ value: 'SUMMARY', label: 'SUMMARY(摘要)' },
{ value: 'PREFERENCE', label: 'PREFERENCE(偏好)' },
{ value: 'FACT', label: 'FACT(事实)' }
]
const governance = ref(null)
const loading = ref(false)
const error = ref(null)
const memories = ref([])
const memoryTotal = ref(0)
const memoryPage = ref(1)
const memoryPageSize = ref(20)
const memoryLoading = ref(false)
const memoryError = ref(null)
const memoryFilter = ref({ scopeType: '', scopeId: '', status: '' })
const createOpen = ref(false)
const createForm = ref(defaultMemory())
const createSubmitting = ref(false)
const createError = ref(null)
const confirmState = ref({ open: false, title: '', message: '', action: null })
async function loadGovernance() {
loading.value = true
error.value = null
try {
governance.value = await aiApi.governance()
} catch (e) {
governance.value = null
error.value = describeError(e)
} finally {
loading.value = false
}
}
async function loadMemories() {
memoryLoading.value = true
memoryError.value = null
try {
const pageData = await aiApi.memories({
scopeType: memoryFilter.value.scopeType,
scopeId: memoryFilter.value.scopeId.trim(),
status: memoryFilter.value.status,
page: memoryPage.value,
pageSize: memoryPageSize.value
})
memories.value = pageData?.items || []
memoryPage.value = pageData?.page || memoryPage.value
memoryPageSize.value = pageData?.pageSize || memoryPageSize.value
memoryTotal.value = pageData?.total || 0
} catch (e) {
memories.value = []
memoryError.value = describeError(e)
} finally {
memoryLoading.value = false
}
}
function defaultMemory() {
return { scopeType: 'CONVERSATION', scopeId: '', memoryType: 'SUMMARY', content: '', retentionDays: 30 }
}
function searchMemories() {
memoryPage.value = 1
loadMemories()
}
function onPageChange(next) {
memoryPage.value = next.page
memoryPageSize.value = next.pageSize
loadMemories()
}
function openCreateMemory() {
createError.value = null
createForm.value = defaultMemory()
createOpen.value = true
}
async function submitMemory() {
if (createSubmitting.value) return
createError.value = null
if (!createForm.value.scopeId.trim()) {
createError.value = { title: '缺少作用域 ID', message: '记忆必须绑定明确作用域,不能写入无归属的全局记忆。' }
return
}
createSubmitting.value = true
try {
await aiApi.createMemory({
scopeType: createForm.value.scopeType,
scopeId: createForm.value.scopeId.trim(),
memoryType: createForm.value.memoryType,
content: createForm.value.content,
retentionDays: Number(createForm.value.retentionDays)
})
notify('记忆已写入', '内容已按 STRICT 模式脱敏并限长,到期后由定时任务清理。', 'success')
createOpen.value = false
await loadMemories()
} catch (e) {
createError.value = describeError(e)
} finally {
createSubmitting.value = false
}
}
function askDelete(memory) {
confirmState.value = {
open: true,
title: '删除记忆',
message: `记忆 ${memory.memoryUid}(${memory.scopeType} / ${memory.scopeId})将被软删除。`,
action: async () => {
await aiApi.deleteMemory(memory.memoryUid)
notify('记忆已删除', '软删除后不会再参与上下文拼装。', 'success')
await loadMemories()
}
}
}
function askPurge() {
confirmState.value = {
open: true,
title: '清理过期记忆',
message: '将扫描并清理所有已过期记忆,该操作不可恢复。',
action: async () => {
const result = await aiApi.purgeMemories()
notify('清理完成', `本次清理 ${result?.expiredCount ?? 0} 条过期记忆。`, 'success')
await loadMemories()
}
}
}
function askClearCache() {
confirmState.value = {
open: true,
title: '清空响应缓存',
message: '将立即清空当前进程内的 AI 响应缓存,后续调用需要重新访问模型。',
action: async () => {
const result = await aiApi.clearCache()
notify('缓存已清空', `清除 ${result?.clearedEntries ?? 0} 条缓存条目。`, 'success')
await loadGovernance()
}
}
}
async function runConfirm() {
const action = confirmState.value.action
try {
if (action) await action()
confirmState.value.open = false
} catch (e) {
notify('操作失败', describeError(e).message, 'error')
confirmState.value.open = false
}
}
function scopeLabel(memory) {
return `${memory.scopeType} / ${memory.scopeId}`
}
function contentPreview(content) {
const text = String(content || '')
return text.length > 80 ? `${text.slice(0, 80)}…` : (text || '—')
}
onMounted(() => {
loadGovernance()
loadMemories()
})
</script>
<template>
<div class="notice" style="margin-bottom: 16px">
以下为后端生效的运行配置(qlinker.ai.*),页面只读展示,不提供绕过受控配置的开关;关闭脱敏等高风险变更必须在服务端配置中完成并发起调用方权限校验。
</div>
<div class="card" style="margin-bottom: 16px">
<div class="card-head">
<h3 class="card-title">数据最小化、缓存与记忆治理</h3>
<div class="actions">
<button class="btn sm" type="button" :disabled="loading" @click="loadGovernance">{{ loading ? '刷新中…' : '刷新' }}</button>
</div>
</div>
<SectionState
:loading="loading"
:error="error"
:empty="!loading && !error && !governance"
empty-title="无法读取治理配置"
empty-text="请确认后端已启动且当前账号具备 ai.read 权限。"
@retry="loadGovernance"
>
<div v-if="governance" class="grid stats">
<div class="card stat">
<span class="stat-label">AI 总开关</span>
<strong class="stat-value">{{ governance.enabled ? '已启用' : '已停用' }}</strong>
<span class="small-muted">停用后所有生成请求都会被拒绝</span>
</div>
<div class="card stat">
<span class="stat-label">默认脱敏模式</span>
<strong class="stat-value">{{ governance.defaultRedactionMode }}</strong>
<span class="small-muted">可选:{{ governance.redactionModes.join(' / ') }}</span>
</div>
<div class="card stat">
<span class="stat-label">输入上限</span>
<strong class="stat-value">{{ governance.maxInputChars }} 字符</strong>
<span class="small-muted">超限自动截断,不完全外发</span>
</div>
<div class="card stat">
<span class="stat-label">上下文消息</span>
<strong class="stat-value">{{ governance.maxContextMessages }} 条</strong>
<span class="small-muted">按需加载,不默认上传全部聊天记录</span>
</div>
<div class="card stat">
<span class="stat-label">缓存</span>
<strong class="stat-value">{{ governance.cache.enabled ? '启用' : '关闭' }}</strong>
<span class="small-muted">TTL {{ governance.cache.ttlSeconds }}s · {{ governance.cache.currentEntries }}/{{ governance.cache.maxEntries }} 条</span>
<button class="btn sm" type="button" style="margin-top: 6px" :disabled="!governance.cache.enabled" @click="askClearCache">清空缓存</button>
</div>
<div class="card stat">
<span class="stat-label">记忆保留</span>
<strong class="stat-value">{{ governance.memory.defaultRetentionDays }} 天</strong>
<span class="small-muted">上限 {{ governance.memory.maxRetentionDays }} 天 · 单条 {{ governance.memory.maxContentChars }} 字符</span>
</div>
</div>
<div v-if="governance" class="grid two-col" style="margin-top: 12px">
<div class="fld">
<label>重试与超时</label>
<div>最大尝试 {{ governance.retry.maxAttempts }} 次 · 初始间隔 {{ governance.retry.backoffMs }} ms · 上限 {{ governance.retry.maxBackoffMs }} ms</div>
<p class="field-hint">结果未知不会按普通失败无限重试,由调用记录单独标注。</p>
</div>
<div class="fld">
<label>工具限流</label>
<div>默认 {{ governance.defaultToolRateLimitPerMinute }} 次/分钟 · 单工具上限 {{ governance.maxToolExecutionsPerMinute }} 次/分钟</div>
<p class="field-hint">限流在进程内按工具维度统计;多实例部署时各实例独立生效。</p>
</div>
<div class="fld">
<label>输出上限</label>
<div>默认 {{ governance.defaultMaxOutputTokens }} token · 最大 {{ governance.maxOutputTokensLimit }} token</div>
</div>
<div class="fld">
<label>记忆清理计划</label>
<div>{{ governance.memory.purgeCron }}</div>
<p class="field-hint">作用域:{{ governance.memory.scopeTypes.join(' / ') }};类型:{{ governance.memory.memoryTypes.join(' / ') }}</p>
</div>
</div>
</SectionState>
</div>
<div class="card">
<div class="card-head">
<h3 class="card-title">记忆记录</h3>
<div class="actions">
<button class="btn sm" type="button" :disabled="memoryLoading" @click="askPurge">清理过期</button>
<button class="btn primary sm" type="button" @click="openCreateMemory">写入记忆</button>
</div>
</div>
<div class="filterbar">
<label>
作用域类型
<Select v-model="memoryFilter.scopeType" :options="SCOPE_TYPE_OPTIONS" aria-label="作用域类型筛选" />
</label>
<label>
作用域 ID
<input v-model="memoryFilter.scopeId" class="field" placeholder="精确匹配" />
</label>
<label>
状态
<Select v-model="memoryFilter.status" :options="MEMORY_STATUS_OPTIONS" aria-label="记忆状态筛选" />
</label>
<button class="btn primary sm" type="button" :disabled="memoryLoading" @click="searchMemories">查询</button>
</div>
<SectionState
:loading="memoryLoading"
:error="memoryError"
:empty="!memoryLoading && !memoryError && !memories.length"
empty-title="没有记忆记录"
empty-text="记忆只在明确作用域和保留期内生效,过期或删除后不再参与上下文。"
@retry="loadMemories"
>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>记忆</th>
<th>作用域</th>
<th>类型</th>
<th>状态</th>
<th>过期时间</th>
<th>内容摘要</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="memory in memories" :key="memory.memoryUid">
<td style="font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px">{{ memory.memoryUid }}</td>
<td>{{ scopeLabel(memory) }}</td>
<td>{{ memory.memoryType }}</td>
<td><StatusTag :value="memory.status" :label="memory.status" /></td>
<td class="small-muted">{{ formatTime(memory.expiresAt) }}</td>
<td class="small-muted">{{ contentPreview(memory.content) }}</td>
<td>
<button class="btn sm" type="button" :disabled="memory.status !== 'ACTIVE'" @click="askDelete(memory)">删除</button>
</td>
</tr>
</tbody>
</table>
</div>
<Pagination :page="memoryPage" :page-size="memoryPageSize" :total="memoryTotal" @change="onPageChange" />
</SectionState>
</div>
<el-dialog
v-model="createOpen"
title="写入记忆"
width="576px"
append-to-body
:close-on-click-modal="!createSubmitting"
:close-on-press-escape="!createSubmitting"
:show-close="!createSubmitting"
:style="{ maxWidth: 'calc(100vw - 32px)' }"
>
<div v-if="createError" class="notice danger" style="margin-bottom: 12px">
<div>
<strong>{{ createError.title }}</strong>
<div style="margin-top: 4px">{{ createError.message }}</div>
</div>
</div>
<div class="form-grid">
<div class="fld">
<label for="memory-scope-type">作用域类型<span class="req">*</span></label>
<Select
id="memory-scope-type"
v-model="createForm.scopeType"
:options="SCOPE_TYPE_FORM_OPTIONS"
block
aria-label="记忆作用域类型"
/>
</div>
<div class="fld">
<label for="memory-scope-id">作用域 ID<span class="req">*</span></label>
<input id="memory-scope-id" v-model="createForm.scopeId" class="field" maxlength="64" />
</div>
<div class="fld">
<label for="memory-type">记忆类型</label>
<Select
id="memory-type"
v-model="createForm.memoryType"
:options="MEMORY_TYPE_OPTIONS"
block
aria-label="记忆类型"
/>
</div>
<div class="fld">
<label for="memory-retention">保留天数</label>
<input id="memory-retention" v-model.number="createForm.retentionDays" class="field" type="number" min="1" />
</div>
<div class="fld full">
<label for="memory-content">内容<span class="req">*</span></label>
<textarea id="memory-content" v-model="createForm.content" class="field" rows="4" placeholder="写入前会按 STRICT 模式脱敏并限制长度" />
<p class="field-hint">不要写入凭据、完整聊天记录或不必要的个人信息。</p>
</div>
</div>
<template #footer>
<div style="display: flex; justify-content: flex-end; gap: 8px">
<button class="btn" type="button" :disabled="createSubmitting" @click="createOpen = false">取消</button>
<button class="btn primary" type="button" :disabled="createSubmitting" @click="submitMemory">
{{ createSubmitting ? '正在写入…' : '写入记忆' }}
</button>
</div>
</template>
</el-dialog>
<ConfirmDialog
:open="confirmState.open"
:title="confirmState.title"
:message="confirmState.message"
tone="danger"
confirm-text="确认执行"
@confirm="runConfirm"
@cancel="confirmState.open = false"
/>
</template>
+829
View File
@@ -0,0 +1,829 @@
<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { aiApi } from '../../api/ai'
import { describeError, formatNumber, formatShortTime, formatTime, notify } from '../../ui'
import ConfirmDialog from '../../components/ConfirmDialog.vue'
import DetailDrawer from '../../components/DetailDrawer.vue'
import Pagination from '../../components/Pagination.vue'
import Select from '../../components/ui/Select.vue'
import Checkbox from '../../components/ui/Checkbox.vue'
const SCOPE_OPTIONS = [
{ value: 'GLOBAL', label: '全局(全部实例)' },
{ value: 'INSTANCE', label: '仅当前实例' }
]
const POLICY_STATUS_OPTIONS = [
{ value: 'ACTIVE', label: '启用' },
{ value: 'DISABLED', label: '停用' }
]
const toolFilterOptions = computed(() => [
{ value: '', label: '全部工具' },
...tools.value.map((tool) => ({ value: tool.toolCode, label: tool.toolName || tool.toolCode }))
])
const toolFormOptions = computed(() => tools.value.map((tool) => ({
value: tool.toolCode,
label: `${tool.toolName}(${tool.toolCode})`
})))
const authFilterOptions = computed(() => [
{ value: '', label: '全部授权' },
...Object.keys(AUTH_LABEL).map((key) => ({ value: key, label: AUTH_LABEL[key] }))
])
const execFilterOptions = computed(() => [
{ value: '', label: '全部执行状态' },
...Object.keys(EXEC_LABEL).map((key) => ({ value: key, label: EXEC_LABEL[key] }))
])
/**
* AI 中心 · 工具授权(对齐 04-ai-cost 画板,即「工具授权」页)。
* 工具只能由后端注册表提供;未命中 ACTIVE 策略的工具一律拒绝执行,
* 高风险工具无论策略如何都必须人工确认。
*/
const RISK_LABEL = { HIGH: '高风险', MEDIUM: '中风险', LOW: '低风险' }
const AUTH_LABEL = { ALLOWED: '已授权', APPROVAL_REQUIRED: '待确认', DENIED: '已拒绝' }
const APPROVAL_LABEL = { PENDING: '待确认', APPROVED: '已批准', REJECTED: '已拒绝' }
const EXEC_LABEL = { PENDING: '待执行', RUNNING: '执行中', SUCCEEDED: '已成功', FAILED: '已失败', REJECTED: '已拒绝' }
const route = useRoute()
const router = useRouter()
const tools = ref([])
const policies = ref([])
const governance = ref(null)
const calls = ref([])
const callTotal = ref(0)
const callPage = ref(1)
const callPageSize = ref(20)
const pendingCalls = ref([])
const pendingTotalCount = ref(0)
const loading = ref(false)
const error = ref(null)
const actionError = ref(null)
const callFilters = ref({ toolCode: '', authorizationStatus: '', executionStatus: '' })
const policyDialog = ref(false)
const policyEditing = ref(null)
const policyForm = ref(defaultPolicy())
const policySubmitting = ref(false)
const policyFieldErrors = ref({})
const approvalOpen = ref(false)
const approvalTarget = ref(null)
const approvalReason = ref('')
const approvalDecision = ref('APPROVED')
const approvalSubmitting = ref(false)
const detailOpen = ref(false)
const detail = ref(null)
const busyUid = ref('')
let callsSeq = 0
let pendingSeq = 0
function defaultPolicy() {
return {
policyName: '',
toolCode: '',
scopeType: 'GLOBAL',
scopeId: '',
approvalRequired: false,
rateLimitPerMinute: 5,
policyStatus: 'ACTIVE'
}
}
const activePolicies = computed(() => policies.value.filter((item) => item.policyStatus === 'ACTIVE'))
const highRiskCount = computed(() => tools.value.filter((item) => String(item.riskLevel).toUpperCase() === 'HIGH').length)
const approvalCount = computed(() => activePolicies.value.filter((item) => item.approvalRequired).length)
const pendingTotal = computed(() => pendingTotalCount.value)
function policyOf(tool) {
return policies.value.find((item) => item.toolCode === tool.toolCode) || null
}
function execPolicyOf(tool) {
const policy = policyOf(tool)
if (!policy || policy.policyStatus !== 'ACTIVE') return '默认拒绝'
if (policy.approvalRequired || String(tool.riskLevel).toUpperCase() === 'HIGH') return '需人工确认'
return '自动执行'
}
function rateLimitOf(tool) {
const policy = policyOf(tool)
return policy ? `${policy.maxPerMinute} 次/分` : '—'
}
function toolStateOf(tool) {
if (String(tool.toolStatus || '').toUpperCase() === 'DISABLED') return { label: '工具已停用', tone: 'muted' }
const policy = policyOf(tool)
if (!policy) return { label: '未配置策略', tone: 'warning' }
return policy.policyStatus === 'ACTIVE'
? { label: '启用', tone: 'success' }
: { label: '停用', tone: 'muted' }
}
function riskTone(value) {
const text = String(value || '').toUpperCase()
if (text === 'HIGH') return 'danger'
if (text === 'MEDIUM') return 'warning'
return 'muted'
}
function authTone(value) {
const text = String(value || '').toUpperCase()
if (text === 'ALLOWED') return 'success'
if (text === 'APPROVAL_REQUIRED') return 'warning'
return 'danger'
}
function execTone(value) {
const text = String(value || '').toUpperCase()
if (text === 'SUCCEEDED') return 'success'
if (text === 'FAILED' || text === 'REJECTED') return 'danger'
if (text === 'RUNNING') return 'info'
return 'warning'
}
function gov(key, fallback = '—') {
const value = governance.value?.[key]
return value === null || value === undefined || value === '' ? fallback : value
}
function errorText(err) {
const base = describeError(err)
return `${base.title}。${base.hint}`
}
async function loadAll() {
loading.value = true
error.value = null
try {
const [toolList, policyList, governanceData] = await Promise.all([
aiApi.tools(), aiApi.toolPolicies(), aiApi.governance()
])
tools.value = toolList || []
policies.value = policyList || []
governance.value = governanceData || null
await Promise.all([loadCalls(), loadPending()])
} catch (e) {
tools.value = []
policies.value = []
governance.value = null
calls.value = []
pendingCalls.value = []
error.value = errorText(e)
} finally {
loading.value = false
}
}
async function loadCalls() {
const seq = ++callsSeq
const params = {
toolCode: callFilters.value.toolCode,
authorizationStatus: callFilters.value.authorizationStatus,
executionStatus: callFilters.value.executionStatus,
page: callPage.value,
pageSize: callPageSize.value
}
try {
const data = await aiApi.toolCalls(params)
if (seq !== callsSeq) return
calls.value = data?.items || []
callPage.value = data?.page || callPage.value
callPageSize.value = data?.pageSize || callPageSize.value
callTotal.value = data?.total || 0
} catch (e) {
if (seq !== callsSeq) return
calls.value = []
callTotal.value = 0
notify('读取工具调用失败', errorText(e), 'error')
}
}
async function loadPending() {
const seq = ++pendingSeq
try {
const data = await aiApi.toolCalls({
authorizationStatus: 'APPROVAL_REQUIRED',
executionStatus: 'PENDING',
page: 1,
pageSize: 5
})
if (seq !== pendingSeq) return
pendingCalls.value = data?.items || []
pendingTotalCount.value = Number(data?.total || 0)
} catch {
if (seq !== pendingSeq) return
pendingCalls.value = []
pendingTotalCount.value = 0
}
}
function onCallFilterChange() {
callPage.value = 1
loadCalls()
}
function onCallPageChange(next) {
callPage.value = next.page
callPageSize.value = next.pageSize
loadCalls()
}
function openPolicyCreate(tool) {
policyEditing.value = null
policyFieldErrors.value = {}
policyForm.value = {
...defaultPolicy(),
toolCode: tool?.toolCode || tools.value[0]?.toolCode || '',
rateLimitPerMinute: Number(gov('defaultToolRateLimitPerMinute', 5))
}
policyDialog.value = true
}
function openPolicyEdit(policy) {
policyEditing.value = policy
policyFieldErrors.value = {}
policyForm.value = {
policyName: policy.policyName || '',
toolCode: policy.toolCode || '',
scopeType: policy.scopeType || 'GLOBAL',
scopeId: policy.scopeId || '',
approvalRequired: Boolean(policy.approvalRequired),
rateLimitPerMinute: policy.maxPerMinute ?? 5,
policyStatus: policy.policyStatus || 'ACTIVE'
}
policyDialog.value = true
}
function openToolPolicy(tool) {
const policy = policyOf(tool)
if (policy) openPolicyEdit(policy)
else openPolicyCreate(tool)
}
function validatePolicy() {
const errors = {}
if (!policyForm.value.toolCode) errors.toolCode = '请选择工具'
if (policyForm.value.scopeType === 'INSTANCE' && !String(policyForm.value.scopeId || '').trim()) {
errors.scopeId = '仅当前实例作用域必须填写实例标识'
}
const rate = Number(policyForm.value.rateLimitPerMinute)
if (!Number.isInteger(rate) || rate < 1 || rate > 120) {
errors.rateLimitPerMinute = '每分钟限流必须是 1 到 120 之间的整数'
}
policyFieldErrors.value = errors
return Object.keys(errors).length === 0
}
async function submitPolicy() {
if (policySubmitting.value) return
if (!validatePolicy()) return
policySubmitting.value = true
actionError.value = null
try {
if (policyEditing.value) {
await aiApi.updateToolPolicy(policyEditing.value.policyUid, {
policyName: policyForm.value.policyName.trim() || null,
approvalRequired: Boolean(policyForm.value.approvalRequired),
rateLimitPerMinute: Number(policyForm.value.rateLimitPerMinute),
policyStatus: policyForm.value.policyStatus
})
notify('策略已更新', '策略变更立即影响后续执行前的授权检查。', 'success')
} else {
await aiApi.createToolPolicy({
policyName: policyForm.value.policyName.trim() || null,
toolCode: policyForm.value.toolCode,
scopeType: policyForm.value.scopeType,
scopeId: policyForm.value.scopeType === 'INSTANCE' ? policyForm.value.scopeId.trim() : null,
approvalRequired: Boolean(policyForm.value.approvalRequired),
rateLimitPerMinute: Number(policyForm.value.rateLimitPerMinute),
policyStatus: policyForm.value.policyStatus
})
notify('策略已创建', '未配置有效策略的工具默认拒绝执行。', 'success')
}
policyDialog.value = false
await loadAll()
} catch (e) {
actionError.value = describeError(e)
} finally {
policySubmitting.value = false
}
}
async function toggleToolPolicy(tool) {
const policy = policyOf(tool)
if (!policy) {
openPolicyCreate(tool)
return
}
const next = policy.policyStatus === 'ACTIVE' ? 'DISABLED' : 'ACTIVE'
try {
await aiApi.updateToolPolicy(policy.policyUid, { policyStatus: next })
notify('策略状态已更新', `工具「${tool.toolName || tool.toolCode}」当前状态:${next === 'ACTIVE' ? '启用' : '停用'}`,
next === 'ACTIVE' ? 'success' : 'warning')
await loadAll()
} catch (e) {
notify('策略更新失败', errorText(e), 'error')
}
}
function openApproval(row, decision) {
approvalTarget.value = row
approvalDecision.value = decision
approvalReason.value = ''
approvalOpen.value = true
}
async function confirmApproval() {
if (approvalSubmitting.value || !approvalTarget.value) return
approvalSubmitting.value = true
try {
await aiApi.approveToolCall(approvalTarget.value.toolCallUid, approvalDecision.value,
approvalReason.value.trim() || null)
notify('人工确认已记录',
approvalDecision.value === 'APPROVED' ? '已批准,可继续执行。' : '已拒绝,该调用不会被自动重试。',
approvalDecision.value === 'APPROVED' ? 'success' : 'warning')
approvalOpen.value = false
await loadAll()
} catch (e) {
notify('确认失败', errorText(e), 'error')
} finally {
approvalSubmitting.value = false
}
}
async function execute(row) {
if (busyUid.value) return
busyUid.value = row.toolCallUid
try {
const result = await aiApi.executeToolCall(row.toolCallUid)
notify('工具执行完成', result?.resultSummary || '执行成功,结果摘要已记录。', 'success')
await loadAll()
} catch (e) {
notify('工具执行未完成', errorText(e), 'error')
await loadAll()
} finally {
busyUid.value = ''
}
}
async function showDetail(row) {
detail.value = row
detailOpen.value = true
try {
detail.value = await aiApi.toolCall(row.toolCallUid)
} catch (e) {
notify('读取详情失败', errorText(e), 'error')
}
}
function goGovernance() {
router.replace({ query: { ...route.query, tab: 'governance' } })
}
onMounted(loadAll)
</script>
<template>
<section class="ai-tools">
<div class="toolbar">
<div class="toolbar-title">
<h3>工具授权</h3>
<p>未登记工具与未命中有效策略的调用一律拒绝;高风险工具必须人工确认后才可执行。</p>
</div>
<button class="btn sm" type="button" :disabled="loading" @click="loadAll">{{ loading ? '刷新中…' : '刷新' }}</button>
<button class="btn primary sm" type="button" @click="openPolicyCreate(null)">新增策略</button>
</div>
<p v-if="error" class="inline-error">{{ error }}</p>
<div v-if="actionError" class="inline-error">
<strong>{{ actionError.title }}</strong>
<div>{{ actionError.message }}</div>
<button class="link-btn" type="button" @click="actionError = null">关闭</button>
</div>
<div class="kpi-row">
<div class="card kpi-cell">
<span class="kpi-label">已注册工具</span>
<strong class="kpi-value">{{ formatNumber(tools.length) }} <em>个</em></strong>
<span class="kpi-note">全部由后端注册表提供 · 接口不开放任意创建</span>
</div>
<div class="card kpi-cell">
<span class="kpi-label">启用策略</span>
<strong class="kpi-value">{{ formatNumber(activePolicies.length) }} <em>条</em></strong>
<span class="kpi-note">高风险 {{ highRiskCount }} 个 · 需人工确认 {{ approvalCount }} 条</span>
</div>
<div class="card kpi-cell">
<span class="kpi-label">待人工确认</span>
<strong class="kpi-value" :class="pendingTotal ? 'warning' : ''">{{ formatNumber(pendingTotal) }} <em>次</em></strong>
<span class="kpi-note">确认后仍需单独触发执行,模型输出不会自动产生副作用</span>
</div>
<div class="card kpi-cell">
<span class="kpi-label">工具调用记录</span>
<strong class="kpi-value">{{ formatNumber(callTotal) }} <em>次</em></strong>
<span class="kpi-note">按当前筛选统计</span>
</div>
</div>
<div class="content-grid">
<div class="main-col">
<div class="card">
<div class="card-head">
<div>
<h3>工具目录与执行策略</h3>
<p class="card-sub">工具、风险等级与所需权限来自后端注册表;执行策略以 ACTIVE 策略为准。</p>
</div>
</div>
<div v-if="loading && !tools.length" class="inline-loading">正在加载工具目录…</div>
<div v-else-if="!tools.length" class="empty-state">后端注册表尚未登记任何工具。</div>
<div v-else class="table-wrap">
<table>
<thead>
<tr>
<th>工具</th>
<th>风险等级</th>
<th>所需权限</th>
<th>执行策略</th>
<th>限流</th>
<th>状态</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="tool in tools" :key="tool.toolUid">
<td>
<strong>{{ tool.toolName || tool.toolCode }}</strong>
<div class="cell-sub">{{ tool.toolCode }} · {{ tool.toolVersion }}</div>
</td>
<td>
<span class="pill" :class="riskTone(tool.riskLevel)">{{ RISK_LABEL[tool.riskLevel] || tool.riskLevel }}</span>
</td>
<td class="mono">{{ tool.requiredPermission }}</td>
<td>
<span class="pill" :class="execPolicyOf(tool) === '自动执行' ? 'success' : execPolicyOf(tool) === '需人工确认' ? 'warning' : 'muted'">
{{ execPolicyOf(tool) }}
</span>
</td>
<td class="nowrap">{{ rateLimitOf(tool) }}</td>
<td>
<span class="pill" :class="toolStateOf(tool).tone">{{ toolStateOf(tool).label }}</span>
</td>
<td>
<div class="row-actions">
<button class="btn sm" type="button" @click="toggleToolPolicy(tool)">
{{ policyOf(tool) ? (policyOf(tool).policyStatus === 'ACTIVE' ? '停用' : '启用') : '配置' }}
</button>
<button class="btn sm" type="button" @click="openToolPolicy(tool)">策略</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="card">
<div class="card-head">
<div>
<h3>工具调用记录</h3>
<p class="card-sub">模型提出的工具调用只登记,不自动执行;此处记录每次授权、确认与执行结果。</p>
</div>
<div class="call-filters">
<Select v-model="callFilters.toolCode" :options="toolFilterOptions" aria-label="工具筛选" @update:model-value="onCallFilterChange" />
<Select v-model="callFilters.authorizationStatus" :options="authFilterOptions" aria-label="授权状态筛选" @update:model-value="onCallFilterChange" />
<Select v-model="callFilters.executionStatus" :options="execFilterOptions" aria-label="执行状态筛选" @update:model-value="onCallFilterChange" />
</div>
</div>
<div v-if="!calls.length" class="empty-state">
<p>当前筛选条件下没有工具调用记录。</p>
<p class="muted-text">没有被拒绝或待确认的调用时,这里是空的;这不是错误。</p>
</div>
<div v-else class="table-wrap">
<table>
<thead>
<tr>
<th>时间</th>
<th>工具</th>
<th>授权</th>
<th>人工确认</th>
<th>执行</th>
<th>结果 / 错误</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="row in calls" :key="row.toolCallUid">
<td class="nowrap">{{ formatShortTime(row.createdAt) }}</td>
<td>
<strong>{{ row.toolName || row.toolCode }}</strong>
<div class="cell-sub">{{ row.toolCode }}</div>
</td>
<td><span class="pill" :class="authTone(row.authorizationStatus)">{{ AUTH_LABEL[row.authorizationStatus] || row.authorizationStatus }}</span></td>
<td>
<span class="pill" :class="row.approvalStatus === 'APPROVED' ? 'success' : row.approvalStatus === 'REJECTED' ? 'danger' : 'warning'">
{{ APPROVAL_LABEL[row.approvalStatus] || row.approvalStatus || '—' }}
</span>
</td>
<td><span class="pill" :class="execTone(row.executionStatus)">{{ EXEC_LABEL[row.executionStatus] || row.executionStatus }}</span></td>
<td class="cell-sub">{{ row.resultSummary || row.errorCode || '—' }}</td>
<td>
<div class="row-actions">
<button v-if="row.executionStatus === 'PENDING' && row.approvalStatus === 'PENDING'"
class="btn sm" type="button" @click="openApproval(row, 'APPROVED')">批准</button>
<button v-if="row.executionStatus === 'PENDING' && row.approvalStatus === 'PENDING'"
class="btn sm" type="button" @click="openApproval(row, 'REJECTED')">拒绝</button>
<button v-if="row.executionStatus === 'PENDING'"
class="btn primary sm" type="button" :disabled="busyUid === row.toolCallUid"
@click="execute(row)">
{{ busyUid === row.toolCallUid ? '执行中…' : '执行' }}
</button>
<button class="btn sm" type="button" @click="showDetail(row)">详情</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="table-foot">
<span class="muted-text">共 {{ formatNumber(callTotal) }} 条 · 每页 {{ callPageSize }} 条</span>
<Pagination :page="callPage" :page-size="callPageSize" :total="callTotal" @change="onCallPageChange" />
</div>
</div>
</div>
<aside class="side-col">
<div class="card side-card">
<header class="side-head">
<h3>授权策略</h3>
<button class="link-btn" type="button" @click="goGovernance">治理设置 →</button>
</header>
<dl class="mini-facts">
<dt>全局默认</dt>
<dd>默认拒绝</dd>
<dt>未登记工具</dt>
<dd>拒绝执行</dd>
<dt>高风险工具</dt>
<dd>必须人工确认</dd>
<dt>单工具默认限流</dt>
<dd>{{ gov('defaultToolRateLimitPerMinute') }} 次/分</dd>
<dt>工具执行上限</dt>
<dd>{{ gov('maxToolExecutionsPerMinute') }} 次/分(服务端固定)</dd>
<dt>默认脱敏模式</dt>
<dd>{{ gov('defaultRedactionMode') }}</dd>
</dl>
<p class="side-note">以上为服务端运行配置,页面不提供修改入口;如需调整请在受控配置中变更并重启。</p>
</div>
<div class="card side-card">
<header class="side-head">
<h3>待人工确认</h3>
<span class="side-meta">{{ formatNumber(pendingTotal) }} 次</span>
</header>
<div v-if="!pendingCalls.length" class="side-empty">当前没有待人工确认的工具调用。</div>
<ul v-else class="pending-list">
<li v-for="row in pendingCalls" :key="row.toolCallUid">
<div class="pending-main">
<strong>{{ row.toolName || row.toolCode }}</strong>
<span class="cell-sub">{{ formatShortTime(row.createdAt) }} · {{ row.toolCallUid }}</span>
</div>
<div class="pending-actions">
<button class="btn sm" type="button" @click="openApproval(row, 'APPROVED')">批准</button>
<button class="btn sm" type="button" @click="openApproval(row, 'REJECTED')">拒绝</button>
</div>
</li>
</ul>
<p class="side-note">确认动作会写入审计记录;确认不等于执行,执行仍需单独触发。</p>
</div>
</aside>
</div>
<el-dialog
v-model="policyDialog"
:title="policyEditing ? '编辑授权策略' : '新增授权策略'"
width="576px"
append-to-body
:close-on-click-modal="!policySubmitting"
:close-on-press-escape="!policySubmitting"
:show-close="!policySubmitting"
:style="{ maxWidth: 'calc(100vw - 32px)' }"
>
<p v-if="Object.keys(policyFieldErrors).length" class="form-summary">
{{ Object.keys(policyFieldErrors).length }} 项校验未通过:{{ Object.values(policyFieldErrors).join('、') }}。修正前无法保存。
</p>
<div class="form-grid">
<div class="fld">
<label for="policy-tool">工具<span class="req">*</span></label>
<Select
id="policy-tool"
v-model="policyForm.toolCode"
:options="toolFormOptions"
block
:disabled="Boolean(policyEditing)"
aria-label="策略工具"
/>
<p v-if="policyFieldErrors.toolCode" class="field-error">{{ policyFieldErrors.toolCode }}</p>
</div>
<div class="fld">
<label for="policy-name">策略名称</label>
<input id="policy-name" v-model="policyForm.policyName" class="field" maxlength="100"
placeholder="留空则按工具自动命名" />
</div>
<div class="fld">
<label for="policy-scope">作用域</label>
<Select
id="policy-scope"
v-model="policyForm.scopeType"
:options="SCOPE_OPTIONS"
block
:disabled="Boolean(policyEditing)"
aria-label="策略作用域"
/>
</div>
<div class="fld">
<label for="policy-scope-id">作用域标识</label>
<input id="policy-scope-id" v-model="policyForm.scopeId" class="field"
:disabled="policyForm.scopeType !== 'INSTANCE' || Boolean(policyEditing)"
placeholder="仅当前实例作用域必填" />
<p v-if="policyFieldErrors.scopeId" class="field-error">{{ policyFieldErrors.scopeId }}</p>
</div>
<div class="fld">
<label for="policy-rate">每分钟限流</label>
<input id="policy-rate" v-model.number="policyForm.rateLimitPerMinute" class="field" type="number" min="1" max="120" />
<p v-if="policyFieldErrors.rateLimitPerMinute" class="field-error">{{ policyFieldErrors.rateLimitPerMinute }}</p>
</div>
<div class="fld">
<label for="policy-status">策略状态</label>
<Select
id="policy-status"
v-model="policyForm.policyStatus"
:options="POLICY_STATUS_OPTIONS"
block
aria-label="策略状态"
/>
</div>
<div class="fld full">
<Checkbox v-model="policyForm.approvalRequired" label="执行前必须人工确认" />
<p class="field-hint">高风险工具无论是否勾选,后端都会强制要求人工确认。</p>
</div>
</div>
<template #footer>
<div class="dialog-foot">
<span class="foot-hint">未配置 ACTIVE 策略的工具默认拒绝执行。</span>
<div class="foot-actions">
<button class="btn" type="button" :disabled="policySubmitting" @click="policyDialog = false">取消</button>
<button class="btn primary" type="button" :disabled="policySubmitting" @click="submitPolicy">
{{ policySubmitting ? '正在保存…' : (policyEditing ? '保存修改' : '创建策略') }}
</button>
</div>
</div>
</template>
</el-dialog>
<ConfirmDialog
:open="approvalOpen"
:title="approvalDecision === 'APPROVED' ? '批准工具调用' : '拒绝工具调用'"
:tone="approvalDecision === 'APPROVED' ? 'primary' : 'danger'"
:message="`工具:${approvalTarget?.toolName || approvalTarget?.toolCode || '—'};调用:${approvalTarget?.toolCallUid || '—'}`"
hint="人工确认会写入审计记录;批准后仍需单独触发执行,模型输出不会自动产生副作用。"
:confirm-text="approvalDecision === 'APPROVED' ? '确认批准' : '确认拒绝'"
:busy="approvalSubmitting"
@confirm="confirmApproval"
@cancel="approvalOpen = false"
>
<label class="fld" style="display: block">
确认说明(可选)
<textarea v-model="approvalReason" class="field" rows="3" maxlength="200" placeholder="说明批准或拒绝的依据" />
</label>
</ConfirmDialog>
<DetailDrawer :open="detailOpen" title="工具调用详情" :subtitle="detail?.toolCallUid || ''" @close="detailOpen = false">
<div v-if="detail" class="grid two-col">
<div class="fld">
<label>工具</label>
<div>{{ detail.toolName }}({{ detail.toolCode }})</div>
</div>
<div class="fld">
<label>风险 / 所需权限</label>
<div>{{ RISK_LABEL[detail.riskLevel] || detail.riskLevel }} / {{ detail.requiredPermission }}</div>
</div>
<div class="fld">
<label>授权 / 确认 / 执行</label>
<div>
{{ AUTH_LABEL[detail.authorizationStatus] || detail.authorizationStatus }} /
{{ APPROVAL_LABEL[detail.approvalStatus] || '—' }} /
{{ EXEC_LABEL[detail.executionStatus] || detail.executionStatus }}
</div>
</div>
<div class="fld">
<label>确认人 / 时间</label>
<div>{{ detail.approvedBy || '—' }} / {{ formatTime(detail.approvedAt) }}</div>
</div>
<div class="fld full">
<label>参数快照(已脱敏)</label>
<pre class="json-box">{{ JSON.stringify(detail.arguments, null, 2) }}</pre>
</div>
<div class="fld full">
<label>结果摘要</label>
<pre class="json-box">{{ detail.resultSummary || '—' }}</pre>
<div v-if="detail.errorCode" class="cell-sub">错误:{{ detail.errorCode }}</div>
</div>
</div>
</DetailDrawer>
</section>
</template>
<style scoped>
.ai-tools { display: flex; flex-direction: column; gap: 14px; }
.toolbar {
display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 8px;
border: 1px solid light-dark(var(--qk-line, #e5e7eb), #273247);
background: light-dark(var(--qk-card, #fff), #121b2b);
}
.toolbar-title { display: flex; flex-direction: column; gap: 2px; margin-right: auto; }
.toolbar-title h3 { margin: 0; font-size: 15px; }
.toolbar-title p { margin: 0; font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.kpi-row { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
.kpi-cell { display: flex; flex-direction: column; gap: 4px; padding: 12px 14px; }
.kpi-label { font-size: 12px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.kpi-value { font-size: 24px; line-height: 1.25; font-variant-numeric: tabular-nums; }
.kpi-value em { font-size: 12px; font-style: normal; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.kpi-value.warning { color: #b45309; }
.kpi-note { font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.content-grid { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 14px; align-items: start; }
.main-col { display: flex; flex-direction: column; gap: 14px; }
.card-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
.card-head h3 { margin: 0; font-size: 15px; }
.card-sub { margin: 3px 0 0; font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.call-filters { display: flex; gap: 6px; flex-wrap: wrap; }
.call-filters :deep(.el-select__wrapper) { min-height: 28px; font-size: 12px; }
.table-wrap { overflow: auto; }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
th {
padding: 7px 8px; text-align: left; white-space: nowrap; font-weight: 600;
border-bottom: 1px solid light-dark(var(--qk-line, #e5e7eb), #273247);
color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd);
}
td { padding: 7px 8px; vertical-align: top; border-bottom: 1px dashed light-dark(var(--qk-line, #e5e7eb), #273247); }
.mono { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; }
.nowrap { white-space: nowrap; }
.cell-sub { font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.pill { padding: 1px 7px; font-size: 11px; border-radius: 999px; white-space: nowrap; }
.pill.success { background: #effaf2; color: #15803d; }
.pill.warning { background: #fff8e6; color: #b45309; }
.pill.danger { background: #fdecec; color: #b42318; }
.pill.info { background: #eef4ff; color: #2558ba; }
.pill.muted { background: #f4f5f8; color: #64748b; }
.row-actions { display: flex; gap: 6px; flex-wrap: wrap; }
.table-foot { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-top: 8px; }
.side-col { display: flex; flex-direction: column; gap: 12px; }
.side-card { display: flex; flex-direction: column; gap: 8px; padding: 12px 14px; }
.side-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.side-head h3 { margin: 0; font-size: 13px; }
.side-meta { font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.side-note { margin: 0; font-size: 11px; line-height: 1.6; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.side-empty { padding: 10px 0; font-size: 12px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.mini-facts { margin: 0; display: grid; grid-template-columns: auto 1fr; gap: 5px 10px; font-size: 11px; }
.mini-facts dt { color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.mini-facts dd { margin: 0; }
.pending-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
.pending-list li {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding-bottom: 8px;
border-bottom: 1px dashed light-dark(var(--qk-line, #e5e7eb), #273247);
}
.pending-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.pending-main strong { font-size: 12px; }
.pending-main .cell-sub { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pending-actions { display: flex; gap: 6px; }
.inline-error { margin: 0; padding: 10px 12px; border: 1px solid #f0b4b4; border-radius: 8px; background: #fdecec; color: #b42318; font-size: 12px; }
.inline-loading { padding: 16px; font-size: 12px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.empty-state { padding: 26px 12px; text-align: center; border: 1px dashed #d9dce6; border-radius: 8px; }
.empty-state p { margin: 0 0 6px; font-size: 13px; }
.muted-text { font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.link-btn { padding: 0; border: 0; background: transparent; color: #2558ba; font-size: 12px; cursor: pointer; }
.form-summary {
margin: 0 0 12px; padding: 8px 10px; border: 1px solid #f0b4b4; border-radius: 8px;
background: #fdecec; color: #b42318; font-size: 12px;
}
.field-error { margin: 4px 0 0; font-size: 11px; color: #b42318; }
.field-hint { margin: 4px 0 0; font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.check-line { display: flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 400; }
.form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
.form-grid .full { grid-column: 1 / -1; }
.dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: 12px; width: 100%; }
.foot-hint { font-size: 11px; color: light-dark(var(--qk-text-3, #6b7280), #9aa7bd); }
.foot-actions { display: flex; gap: 8px; }
.json-box {
margin: 0; padding: 8px; border-radius: 6px; max-height: 220px; overflow: auto;
background: light-dark(#f7f8fb, #0d1522); white-space: pre-wrap; word-break: break-all; font-size: 11px;
}
</style>
+306
View File
@@ -0,0 +1,306 @@
<script setup>
import { computed, ref, watch } from 'vue'
import Input from '../../components/ui/Input.vue'
import Select from '../../components/ui/Select.vue'
import { askConfirm } from '../../components/ui/index'
import { notify } from '../../ui'
import { contactsApi } from '../../api/contacts'
import { errorText } from './util'
/**
* 批量操作面板:只允许本地操作(软删/拉黑/解除拉黑/标签)。
* QQ 侧删除、拉黑不可逆,按口径只能单条执行;批量上限 50,限制由前端与后端共同保证。
*/
const props = defineProps({
contacts: { type: Array, default: () => [] },
qqAccount: { type: String, default: '' },
canManage: { type: Boolean, default: true },
tags: { type: Array, default: () => [] },
max: { type: Number, default: 50 },
mode: { type: String, default: 'panel' }
})
const emit = defineEmits(['close', 'clear', 'remove', 'done'])
const action = ref('DELETE')
const tagName = ref('')
const tagUid = ref('')
const busy = ref(false)
const error = ref('')
const result = ref(null)
const ACTIONS = [
{ value: 'DELETE', label: '本地删除', hint: '从联系人索引移除,历史消息与审计保留。' },
{ value: 'BLOCK', label: '本地拉黑', hint: '仅写入本地标记与筛选,不拦截 QQ 消息投递,QQ 关系不变。' },
{ value: 'UNBLOCK', label: '解除本地拉黑', hint: '仅解除本地拉黑;QQ 黑名单无法由本系统解除。' },
{ value: 'TAG_ADD', label: '添加标签', hint: '已存在的标签自动复用,不会重复创建。' },
{ value: 'TAG_REMOVE', label: '移除标签', hint: '移除所选联系人与指定标签的关联。' }
]
const selectedCount = computed(() => props.contacts.length)
const overLimit = computed(() => selectedCount.value > props.max)
const noAccount = computed(() => !props.qqAccount)
const tagOptions = computed(() => props.tags.map((tag) => ({ value: tag.tagUid, label: tag.name })))
const actionMeta = computed(() => ACTIONS.find((item) => item.value === action.value) || ACTIONS[0])
const canApply = computed(() => {
if (!props.canManage || noAccount.value || overLimit.value || !selectedCount.value || busy.value) return false
if (action.value === 'TAG_ADD') return Boolean(tagName.value.trim())
if (action.value === 'TAG_REMOVE') return Boolean(tagUid.value)
return true
})
const applyText = computed(() => {
if (busy.value) return '执行中…'
const count = selectedCount.value
return {
DELETE: `本地删除 ${count} 人`,
BLOCK: `本地拉黑 ${count} 人`,
UNBLOCK: `解除拉黑 ${count} 人`,
TAG_ADD: `添加标签(${count} 人)`,
TAG_REMOVE: `移除标签(${count} 人)`
}[action.value] || '应用变更'
})
watch(action, () => {
error.value = ''
result.value = null
tagName.value = ''
tagUid.value = ''
})
function close() {
if (busy.value) return
emit('close')
}
function confirmOptions() {
const count = selectedCount.value
if (action.value === 'DELETE') {
return {
title: '批量本地删除',
message: `将从本地联系人列表移除 ${count} 人。历史消息、媒体与审计记录保留;重新同步后若仍为好友可再次出现。`,
hint: 'QQ 好友关系不受影响。该操作只能批量执行本地软删。',
confirmText: `删除 ${count} 人`,
tone: 'danger'
}
}
if (action.value === 'BLOCK') {
return {
title: '批量本地拉黑',
message: `将为 ${count} 人写入本地拉黑标记(不拦截 QQ 消息投递)。`,
hint: 'QQ 好友与 QQ 黑名单不受影响;QQ 不可逆拉黑只能单条执行。',
confirmText: `拉黑 ${count} 人`,
tone: 'danger'
}
}
if (action.value === 'UNBLOCK') {
return {
title: '批量解除本地拉黑',
message: `将解除 ${count} 人的本地拉黑状态。`,
hint: '仅解除本地状态;QQ 黑名单无法通过本系统解除。',
confirmText: '确认解除'
}
}
if (action.value === 'TAG_ADD') {
return {
title: '批量添加标签',
message: `为 ${count} 人添加标签「${tagName.value.trim()}」。`,
hint: '同名标签会自动复用,不会重复创建。',
confirmText: '确认添加'
}
}
const tag = props.tags.find((item) => item.tagUid === tagUid.value)
return {
title: '批量移除标签',
message: `从 ${count} 人移除标签「${tag?.name || tagUid.value}」。`,
hint: '仅解除联系人与标签的关联,不删除标签本身。',
confirmText: '确认移除'
}
}
async function apply() {
if (!canApply.value) return
const confirmed = await askConfirm(confirmOptions())
if (!confirmed) return
busy.value = true
error.value = ''
result.value = null
const payload = {
qqAccount: props.qqAccount,
confirm: true,
action: action.value,
contactUids: props.contacts.map((contact) => contact.contactUid),
mode: 'LOCAL'
}
if (action.value === 'TAG_ADD') payload.tagName = tagName.value.trim()
if (action.value === 'TAG_REMOVE') payload.tagUid = tagUid.value
try {
const data = await contactsApi.batch(payload)
result.value = data
const failed = Number(data?.failed || 0)
if (failed > 0) {
notify('批量操作部分失败', `请求 ${data.requested} 条 · 成功 ${data.succeeded} 条 · 失败 ${failed} 条`, 'warning')
} else {
notify('批量操作已完成', `请求 ${data?.requested ?? selectedCount.value} 条 · 成功 ${data?.succeeded ?? selectedCount.value} 条`, 'success')
}
emit('done')
} catch (e) {
error.value = errorText(e)
} finally {
busy.value = false
}
}
function failureText(failure) {
if (!failure) return ''
return `${failure.contactUid || '未知联系人'}:${failure.message || '操作失败'}`
}
</script>
<template>
<aside class="card batch-panel" :class="`mode-${mode}`" aria-label="批量操作">
<header class="batch-head">
<div>
<strong>批量操作</strong>
<span class="batch-count">已选 {{ selectedCount }} 人</span>
</div>
<div class="batch-head-actions">
<button class="btn sm ghost" type="button" :disabled="busy || !selectedCount" @click="$emit('clear')">取消选择</button>
<button class="btn sm ghost" type="button" :disabled="busy" aria-label="退出批量管理" @click="close">×</button>
</div>
</header>
<div class="batch-body">
<div v-if="!canManage" class="notice warn">当前账号缺少「contact.manage」权限,无法执行批量操作。</div>
<div v-else-if="noAccount" class="notice warn">批量操作仅对具体 QQ 账号生效,请先在顶部选择具体账号。</div>
<div v-else-if="overLimit" class="notice danger">已选 {{ selectedCount }} 人,超过批量上限 {{ max }} 人,请减少选择后再执行。</div>
<div class="notice info">
批量仅支持本地操作。QQ 侧删除/拉黑不可逆,不能批量执行,只能在单条详情中操作。
</div>
<section class="batch-section">
<div class="batch-section-head">
<span>已选联系人</span>
<span class="batch-count">{{ selectedCount }} / {{ max }}</span>
</div>
<div class="selected-row">
<button
v-for="contact in contacts"
:key="contact.contactUid"
class="selected-chip"
type="button"
:disabled="busy"
:title="`从选择中移除 ${contact.displayName || contact.nickname}`"
@click="$emit('remove', contact.contactUid)"
>
{{ contact.displayName || contact.nickname || contact.contactId }}
<span aria-hidden="true">×</span>
</button>
<span v-if="!contacts.length" class="small-muted">尚未选择联系人,请在列表中勾选,或使用「全选本页」。</span>
</div>
</section>
<section class="batch-section">
<div class="batch-section-head"><span>操作类型</span></div>
<div class="action-grid">
<label v-for="item in ACTIONS" :key="item.value" class="action-item" :class="{ active: action === item.value, danger: item.value === 'DELETE' || item.value === 'BLOCK' }">
<input v-model="action" type="radio" :value="item.value" :disabled="busy" />
<span>
<strong>{{ item.label }}</strong>
<em>{{ item.hint }}</em>
</span>
</label>
</div>
</section>
<section v-if="action === 'TAG_ADD'" class="batch-section">
<Input v-model="tagName" label="标签名" placeholder="输入标签名后执行" hint="同名标签会自动复用,不会重复创建。" :maxlength="32" :disabled="busy" />
</section>
<section v-else-if="action === 'TAG_REMOVE'" class="batch-section">
<span class="field-label">选择要移除的标签</span>
<Select v-model="tagUid" :options="tagOptions" placeholder="请选择标签" :disabled="busy" block />
</section>
<div v-if="error" class="notice danger">{{ error }}</div>
<section v-if="result" class="batch-section result-section">
<div class="batch-section-head"><span>执行结果</span></div>
<div class="result-line">
<span>请求 <b>{{ result.requested }}</b></span>
<span class="ok">成功 <b>{{ result.succeeded }}</b></span>
<span :class="{ bad: Number(result.failed) > 0 }">失败 <b>{{ result.failed }}</b></span>
</div>
<ul v-if="result.failures?.length" class="failure-list">
<li v-for="(failure, index) in result.failures" :key="index">{{ failureText(failure) }}</li>
</ul>
</section>
</div>
<footer class="batch-foot">
<button class="btn ghost" type="button" :disabled="busy" @click="close">取消</button>
<button class="btn" :class="action === 'DELETE' || action === 'BLOCK' ? 'danger' : 'primary'" type="button" :disabled="!canApply" @click="apply">
{{ applyText }}
</button>
</footer>
</aside>
</template>
<style scoped>
.batch-panel { display: flex; flex-direction: column; padding: 0; overflow: hidden; }
.mode-panel { position: sticky; top: 12px; max-height: calc(100vh - 190px); }
.mode-sheet { position: fixed; left: 0; right: 0; bottom: 0; z-index: 42; max-height: 72vh; border-radius: 14px 14px 0 0; box-shadow: 0 -18px 45px rgb(15 23 42 / 18%); }
.batch-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 11px 14px; border-bottom: 1px solid var(--qk-line); flex: none; }
.batch-head strong { font-size: 12px; }
.batch-count { margin-left: 8px; font-size: 10px; color: var(--qk-text-4); font-family: var(--qk-font-num); }
.batch-head-actions { display: flex; align-items: center; gap: 4px; }
.batch-body { padding: 10px 14px; overflow: auto; display: flex; flex-direction: column; gap: 9px; }
.batch-section { display: flex; flex-direction: column; gap: 6px; padding-top: 8px; border-top: 1px solid var(--qk-line); }
.batch-section:first-of-type { border-top: 0; padding-top: 0; }
.batch-section-head { display: flex; align-items: center; justify-content: space-between; font-size: 10px; color: var(--qk-text-3); }
.selected-row { display: flex; flex-wrap: wrap; gap: 5px; max-height: 86px; overflow: auto; }
.selected-chip {
display: inline-flex;
align-items: center;
gap: 5px;
height: 22px;
padding: 0 6px;
border: 1px solid var(--qk-line-strong);
border-radius: 4px;
background: var(--qk-card);
color: var(--qk-text-3);
font-size: 10px;
cursor: pointer;
}
.selected-chip:hover:not(:disabled) { border-color: #fca5a5; color: var(--qk-red-ink); }
.selected-chip:disabled { opacity: .6; cursor: not-allowed; }
.action-grid { display: grid; grid-template-columns: 1fr; gap: 4px; }
.action-item {
display: flex;
align-items: flex-start;
gap: 7px;
padding: 7px 8px;
border: 1px solid var(--qk-line);
border-radius: 6px;
cursor: pointer;
}
.action-item.active { border-color: var(--qk-primary); background: var(--qk-primary-weak); }
.action-item.danger.active { border-color: #fca5a5; background: var(--qk-red-weak); }
.action-item input { margin-top: 2px; accent-color: var(--qk-primary); }
.action-item.danger input { accent-color: var(--qk-red-ink); }
.action-item span { display: flex; flex-direction: column; gap: 2px; }
.action-item strong { font-size: 10.5px; color: var(--qk-text-2); }
.action-item em { font-style: normal; font-size: 9.5px; line-height: 1.5; color: var(--qk-text-4); }
.field-label { font-size: 10px; color: var(--qk-text-3); }
.result-section { gap: 8px; }
.result-line { display: flex; gap: 12px; font-size: 10.5px; color: var(--qk-text-3); }
.result-line b { font-family: var(--qk-font-num); }
.result-line .ok { color: var(--qk-green-ink, #047857); }
.result-line .bad { color: var(--qk-red-ink); }
.failure-list { margin: 0; padding-left: 16px; max-height: 100px; overflow: auto; font-size: 9.5px; line-height: 1.55; color: var(--qk-red-ink); }
.batch-foot { display: flex; justify-content: flex-end; gap: 8px; padding: 9px 14px; border-top: 1px solid var(--qk-line); flex: none; }
.small-muted { font-size: 10px; color: var(--qk-text-4); }
@media (max-width: 720px) {
.batch-body { max-height: 58vh; }
}
</style>
+179
View File
@@ -0,0 +1,179 @@
<script setup>
import { computed, ref, watch } from 'vue'
import Modal from '../../components/ui/Modal.vue'
import Input from '../../components/ui/Input.vue'
import Checkbox from '../../components/ui/Checkbox.vue'
import { contactsApi, newIdempotencyKey } from '../../api/contacts'
import { notify } from '../../ui'
import { errorText } from './util'
/**
* 拉黑联系人:默认仅本地拉黑;也可显式选择同时加入 QQ 黑名单。
* QQ 黑名单加入后无法通过本系统解除,文案必须写明;只允许单条执行。
*/
const props = defineProps({
open: { type: Boolean, default: false },
contact: { type: Object, default: null },
qqAccount: { type: String, default: '' }
})
const emit = defineEmits(['close', 'done'])
const mode = ref('LOCAL')
const reason = ref('')
const acked = ref(false)
const busy = ref(false)
const error = ref('')
const idempotencyKey = ref('')
const contact = computed(() => props.contact || {})
const isPerson = computed(() => String(contact.value.contactType || '').toUpperCase() === 'PERSON')
const displayName = computed(() => contact.value.displayName || contact.value.nickname || '该联系人')
const qqModeDisabled = computed(() => !isPerson.value)
const canSubmit = computed(() => !busy.value && acked.value && Boolean(props.qqAccount))
function reset() {
mode.value = 'LOCAL'
reason.value = ''
acked.value = false
busy.value = false
error.value = ''
idempotencyKey.value = newIdempotencyKey()
}
watch(
() => [props.open, contact.value.contactUid],
([open]) => {
if (open) reset()
},
{ immediate: true }
)
watch(mode, () => {
acked.value = false
error.value = ''
idempotencyKey.value = newIdempotencyKey()
})
function close() {
if (busy.value) return
emit('close')
}
async function submit() {
if (!canSubmit.value) return
if (!props.qqAccount) {
error.value = '请先选择具体 QQ 账号后再拉黑联系人。'
return
}
if (mode.value === 'QQ' && !isPerson.value) {
error.value = '群聊联系人不能加入 QQ 黑名单。'
return
}
busy.value = true
error.value = ''
try {
await contactsApi.block(
contact.value.contactUid,
{
qqAccount: props.qqAccount,
confirm: true,
mode: mode.value,
reason: reason.value.trim()
},
idempotencyKey.value
)
notify(
mode.value === 'QQ' ? '已请求加入 QQ 黑名单' : '已本地拉黑该联系人',
mode.value === 'QQ'
? 'QQ 黑名单加入已由上游确认;加入后无法通过本系统解除,只能在 QQ 客户端手动处理。'
: '已写入本地拉黑标记:不拦截 QQ 消息投递,历史会话、媒体与审计记录保留。',
'success'
)
emit('done')
emit('close')
} catch (e) {
error.value = errorText(e)
} finally {
busy.value = false
}
}
</script>
<template>
<Modal :open="open" size="sm" title="拉黑联系人" :subtitle="`${displayName} · QQ ${contact.contactId || '—'}`" :busy="busy" @close="close">
<div class="block-form">
<p class="block-intro">本地拉黑只在联系人中心打标记与筛选,不拦截 QQ 消息投递;QQ 侧加入黑名单则由 QQ 自行拦截。两种模式都不会删除已有历史记录。</p>
<label class="option-card" :class="{ active: mode === 'LOCAL' }">
<input v-model="mode" type="radio" value="LOCAL" :disabled="busy" />
<span class="option-main">
<strong>仅本地拉黑(默认)</strong>
<em>仅写入本地标记用于筛选与提示,不拦截 QQ 消息投递;历史会话、媒体与审计记录全部保留,可在详情中解除。QQ 侧好友关系不变。</em>
</span>
</label>
<label class="option-card is-danger" :class="{ active: mode === 'QQ', disabled: qqModeDisabled }">
<input v-model="mode" type="radio" value="QQ" :disabled="busy || qqModeDisabled" />
<span class="option-main">
<strong>同时加入 QQ 黑名单</strong>
<em v-if="!qqModeDisabled">将调用 NapCat 加入黑名单。加入后无法通过本系统解除,只能在 QQ 客户端手动处理;群聊联系人不可使用此选项。</em>
<em v-else>群聊联系人不能加入 QQ 黑名单。</em>
</span>
</label>
<div v-if="mode === 'QQ'" class="notice danger">
重要:QQ 黑名单加入后不可逆地脱离本系统控制,无法通过本系统解除。请确认确实需要在 QQ 侧拉黑。该操作只能单条执行。
</div>
<Input
v-model="reason"
label="拉黑原因(可选)"
placeholder="仅本地记录,便于后续核查"
hint="仅保存到本地与审计,不会发送给联系人,也不会同步到 QQ。"
:maxlength="255"
:disabled="busy"
show-count
/>
<Checkbox
v-model="acked"
:disabled="busy"
:label="mode === 'QQ' ? '我已知晓 QQ 黑名单加入后无法通过本系统解除,只能在 QQ 客户端处理。' : '我已知晓本地拉黑只写入本地标记,不会拦截 QQ 消息投递。'"
/>
<div v-if="error" class="notice danger">{{ error }}</div>
<p class="form-footnote">拉黑与解除拉黑都会写入审计记录;QQ 黑名单状态无法由本系统解除或反查。</p>
</div>
<template #foot>
<button class="btn ghost" type="button" :disabled="busy" @click="close">取消</button>
<button class="btn danger" type="button" :disabled="!canSubmit" @click="submit">
{{ busy ? '执行中…' : '确认拉黑' }}
</button>
</template>
</Modal>
</template>
<style scoped>
.block-form { display: flex; flex-direction: column; gap: 10px; }
.block-intro { margin: 0; font-size: 10.5px; line-height: 1.6; color: var(--qk-text-3); }
.option-card {
display: flex;
align-items: flex-start;
gap: 9px;
padding: 9px 10px;
border: 1px solid var(--qk-line);
border-radius: 8px;
cursor: pointer;
}
.option-card.active { border-color: var(--qk-primary); background: var(--qk-primary-weak); }
.option-card.is-danger.active { border-color: #fca5a5; background: var(--qk-red-weak); }
.option-card.disabled { opacity: .55; cursor: not-allowed; }
.option-card input { margin-top: 2px; accent-color: var(--qk-primary); }
.is-danger input { accent-color: var(--qk-red-ink); }
.option-main { display: flex; flex-direction: column; gap: 3px; }
.option-main strong { font-size: 11px; color: var(--qk-text-2); }
.option-main em { font-style: normal; font-size: 9.5px; line-height: 1.55; color: var(--qk-text-4); }
.form-footnote { margin: 0; font-size: 9.5px; line-height: 1.55; color: var(--qk-text-4); }
</style>
@@ -0,0 +1,426 @@
<script setup>
import { computed, ref } from 'vue'
import { formatNumber, formatTime } from '../../ui'
import AvatarBadge from '../../components/AvatarBadge.vue'
/**
* 联系人详情:宽屏为右列卡片,≤1280 为右侧抽屉,≤720 为底部浮动卡片。
* 在线状态与个性签名没有真实来源,统一显示“未获取”,不推测;不展示“关联规则”。
*/
const props = defineProps({
contact: { type: Object, default: null },
mode: { type: String, default: 'panel' },
qqAccount: { type: String, default: '' },
canManage: { type: Boolean, default: true },
tagBusy: { type: Boolean, default: false },
tagError: { type: String, default: '' }
})
const emit = defineEmits(['close', 'edit', 'restore', 'delete', 'block', 'unblock', 'jump', 'add-tag', 'remove-tag'])
const SOURCE_LABELS = {
FRIENDS_WITH_CATEGORY: '好友分组同步',
FRIEND_LIST: '好友列表同步',
GROUP_LIST: '群列表同步'
}
const SOURCE_STATUS_LABELS = {
ACTIVE: '正常',
REMOVED_BY_PEER: '对方已删除',
DISMISSED: '群已解散',
LEFT: '已退群'
}
const JOB_LABELS = {
PENDING: '等待执行',
RUNNING: '运行中',
SUCCEEDED: '成功',
PARTIAL: '部分成功',
FAILED: '失败',
STALE: '未同步'
}
const tagInputOpen = ref(false)
const tagName = ref('')
const tagNotice = ref('')
const contact = computed(() => props.contact || {})
const isPerson = computed(() => String(contact.value.contactType || '').toUpperCase() === 'PERSON')
const typeLabel = computed(() => (isPerson.value ? '好友' : '群聊'))
const hasAccount = computed(() => Boolean(props.qqAccount))
const tags = computed(() => (Array.isArray(contact.value.tags) ? contact.value.tags : []))
const commonGroups = computed(() => (Array.isArray(contact.value.commonGroups) ? contact.value.commonGroups : []))
const syncState = computed(() => contact.value.syncState || null)
function deny(action) {
if (!props.canManage) return `当前账号缺少「contact.manage」权限,无法${action}。`
if (!hasAccount.value) return '请先选择具体 QQ 账号'
return ''
}
function sourceLabel(value) {
return SOURCE_LABELS[String(value || '').toUpperCase()] || value || '—'
}
function sourceStatusLabel(value) {
return SOURCE_STATUS_LABELS[String(value || '').toUpperCase()] || value || '—'
}
function sourceStatusTone(value) {
const text = String(value || '').toUpperCase()
if (text === 'ACTIVE') return 'success'
if (text === 'REMOVED_BY_PEER' || text === 'DISMISSED' || text === 'LEFT') return 'warning'
return 'muted'
}
function jobLabel(value) {
return JOB_LABELS[String(value || '').toUpperCase()] || value || '—'
}
function jobTone(value) {
const text = String(value || '').toUpperCase()
if (text === 'SUCCEEDED') return 'success'
if (text === 'FAILED') return 'error'
if (text === 'PARTIAL' || text === 'RUNNING' || text === 'PENDING') return 'warning'
return 'muted'
}
function tagColor(tag) {
const color = String(tag?.color || '')
return /^#[0-9a-f]{3,8}$/i.test(color) ? color : ''
}
function openTagInput() {
tagNotice.value = ''
if (tags.value.length >= 8) {
tagNotice.value = '每个联系人最多 8 个标签,请先移除其他标签。'
return
}
tagInputOpen.value = true
}
function submitTag() {
const name = tagName.value.trim()
tagNotice.value = ''
if (!name) return
if (tags.value.length >= 8) {
tagNotice.value = '每个联系人最多 8 个标签,请先移除其他标签。'
return
}
if (tags.value.some((tag) => String(tag.name || '').toLowerCase() === name.toLowerCase())) {
tagNotice.value = '该标签已存在于当前联系人。'
return
}
emit('add-tag', name)
tagName.value = ''
tagInputOpen.value = false
}
function commonGroupCount() {
if (isPerson.value) {
return contact.value.commonGroupCount !== undefined && contact.value.commonGroupCount !== null
? contact.value.commonGroupCount
: commonGroups.value.length
}
return null
}
</script>
<template>
<aside class="card contact-detail" :class="`mode-${mode}`" aria-label="联系人详情">
<div v-if="mode === 'sheet'" class="sheet-grab" aria-hidden="true"></div>
<header class="detail-head">
<div class="detail-person">
<AvatarBadge
size="lg"
:name="contact.displayName || contact.nickname"
:media-uid="contact.avatarMediaUid"
:type="isPerson ? 'PRIVATE' : 'GROUP'"
/>
<div class="detail-name">
<div class="detail-name-line">
<strong>{{ contact.displayName || contact.nickname || '—' }}</strong>
<span class="status info">{{ typeLabel }}</span>
<span v-if="contact.blocked" class="status error">已拉黑</span>
<span v-if="contact.deletedLocal" class="status warning">本地已删除</span>
</div>
<div class="detail-sub">QQ {{ contact.contactId || '—' }}</div>
<div class="detail-online">在线状态 未获取</div>
</div>
</div>
<button class="btn sm ghost" type="button" aria-label="关闭详情" @click="$emit('close')">×</button>
</header>
<div class="detail-body">
<div class="detail-actions">
<button class="btn primary sm" type="button" :disabled="contact.deletedLocal" v-tooltip="contact.deletedLocal ? '联系人已本地删除,恢复后可发起会话' : '跳转到消息中心并定位该会话'" @click="$emit('jump')">
发起会话
</button>
<button class="btn sm" type="button" :disabled="Boolean(deny('编辑备注'))" v-tooltip="deny('编辑备注') || '修改本地备注与标签'" @click="$emit('edit')">
编辑备注
</button>
<template v-if="contact.deletedLocal">
<button class="btn sm" type="button" :disabled="Boolean(deny('恢复联系人'))" v-tooltip="deny('恢复联系人') || '清除本地删除标记,重新显示该联系人'" @click="$emit('restore')">
恢复
</button>
</template>
<template v-else>
<button v-if="contact.blocked" class="btn sm" type="button" :disabled="Boolean(deny('解除拉黑'))" v-tooltip="deny('解除拉黑') || '仅解除本地拉黑;QQ 黑名单需在 QQ 客户端处理'" @click="$emit('unblock')">
解除拉黑
</button>
<button v-else class="btn sm danger-ghost" type="button" :disabled="Boolean(deny('拉黑'))" v-tooltip="deny('拉黑') || '选择仅本地拉黑或同时加入 QQ 黑名单'" @click="$emit('block')">
拉黑
</button>
<button class="btn sm danger" type="button" :disabled="Boolean(deny('删除'))" v-tooltip="deny('删除') || '选择仅本地软删或同时删除 QQ 好友'" @click="$emit('delete')">
删除
</button>
</template>
</div>
<div v-if="!hasAccount" class="notice warn detail-notice">
未确定当前 QQ 账号,无法编辑联系人。请先在接入管理确认绑定在线。
</div>
<div v-if="contact.blocked" class="notice danger detail-notice">
该联系人已被本地标记为拉黑:仅用于本地索引与筛选,不拦截 QQ 侧的私聊或群消息投递。若同时执行了 QQ 侧拉黑,好友关系已在 QQ 侧移除;历史会话、媒体与审计记录仍保留。
</div>
<div v-if="contact.deletedLocal" class="notice warn detail-notice">
该联系人已被本地删除,仅从联系人索引隐藏;历史消息、媒体与审计记录保留。重新同步后若仍为好友可再次出现。
</div>
<section class="detail-section">
<div class="detail-section-head">
<strong>资料</strong>
<span>数据来自 NapCat 同步</span>
</div>
<div class="kv-grid">
<div class="kv"><span>QQ 号</span><b class="mono">{{ contact.contactId || '—' }}</b></div>
<div class="kv"><span>昵称</span><b>{{ contact.nickname || '—' }}</b></div>
<div class="kv"><span>本地备注</span><b>{{ contact.remark || '—' }}</b></div>
<div class="kv"><span>QQ 备注</span><b>{{ contact.qqRemark || '—' }}</b></div>
<div class="kv">
<span>分组</span>
<b>{{ contact.groupName || '未分组' }}</b>
<em>仅展示 QQ 同步分组,不支持本地修改</em>
</div>
<div class="kv"><span>来源</span><b>{{ sourceLabel(contact.source) }}</b></div>
<div class="kv">
<span>来源状态</span>
<b><span class="status" :class="sourceStatusTone(contact.sourceStatus)">{{ sourceStatusLabel(contact.sourceStatus) }}</span></b>
</div>
<div class="kv"><span>最近同步</span><b>{{ formatTime(contact.lastSyncedAt) }}</b></div>
<div v-if="!isPerson" class="kv"><span>成员数</span><b>{{ formatNumber(contact.memberCount) }}<template v-if="contact.maxMemberCount"> / {{ formatNumber(contact.maxMemberCount) }}</template></b></div>
<div v-if="isPerson" class="kv"><span>共同群聊</span><b>{{ formatNumber(commonGroupCount()) }} 个</b></div>
</div>
</section>
<section class="detail-section">
<div class="detail-section-head">
<strong>在线状态与签名</strong>
</div>
<div class="kv-grid">
<div class="kv"><span>在线状态</span><b class="unavailable">未获取</b></div>
<div class="kv"><span>个性签名</span><b class="unavailable">未获取</b></div>
</div>
<p class="section-hint">后端未提供真实在线状态与签名数据,本页不推测、不伪造。</p>
</section>
<section class="detail-section">
<div class="detail-section-head">
<strong>标签</strong>
<span>{{ tags.length }} / 8</span>
</div>
<div class="tag-row">
<span v-for="tag in tags" :key="tag.tagUid" class="tag-chip">
<i v-if="tagColor(tag)" :style="{ background: tagColor(tag) }" aria-hidden="true"></i>
{{ tag.name }}
<button
class="tag-remove"
type="button"
:disabled="Boolean(deny('移除标签')) || tagBusy"
v-tooltip="deny('移除标签') || `移除标签「${tag.name}」`"
:aria-label="`移除标签 ${tag.name}`"
@click="$emit('remove-tag', tag)"
>×</button>
</span>
<span v-if="!tags.length" class="small-muted">暂无标签</span>
<button
v-if="!tagInputOpen"
class="tag-add"
type="button"
:disabled="Boolean(deny('添加标签')) || tags.length >= 8"
v-tooltip="deny('添加标签') || (tags.length >= 8 ? '每个联系人最多 8 个标签' : '添加本地标签')"
@click="openTagInput"
>+ 添加标签</button>
</div>
<div v-if="tagInputOpen" class="tag-input-row">
<input
v-model="tagName"
class="field"
maxlength="32"
placeholder="输入标签名,回车添加"
aria-label="新标签名称"
@keydown.enter.prevent="submitTag"
/>
<button class="btn sm primary" type="button" :disabled="tagBusy || !tagName.trim()" @click="submitTag">
{{ tagBusy ? '保存中…' : '添加' }}
</button>
<button class="btn sm ghost" type="button" @click="tagInputOpen = false; tagName = ''">取消</button>
</div>
<p v-if="tagNotice || tagError" class="field-error">{{ tagError || tagNotice }}</p>
<p v-else class="section-hint">标签用于批量筛选,也会作为自动化规则的筛选条件;不会写入 QQ。</p>
</section>
<section v-if="isPerson" class="detail-section">
<div class="detail-section-head">
<strong>共同群聊</strong>
<span>{{ commonGroups.length }} 个</span>
</div>
<ul v-if="commonGroups.length" class="common-group-list">
<li v-for="group in commonGroups" :key="group.groupId || group.groupContactUid">
<span>{{ group.groupName || group.groupId }}</span>
<small>{{ formatNumber(group.memberCount) }} 人</small>
</li>
</ul>
<p v-else class="section-hint">未记录共同群聊。仅展示已同步的群成员关系,不代表完整群列表。</p>
</section>
<section class="detail-section">
<div class="detail-section-head">
<strong>同步信息</strong>
</div>
<div class="kv-grid">
<div class="kv"><span>好友同步</span><b>{{ formatTime(syncState?.friendsSyncedAt) }}</b></div>
<div class="kv"><span>群聊同步</span><b>{{ formatTime(syncState?.groupsSyncedAt) }}</b></div>
<div class="kv"><span>群成员同步</span><b>{{ formatTime(syncState?.membersSyncedAt) }}</b></div>
<div class="kv">
<span>最近任务</span>
<b><span class="status" :class="jobTone(syncState?.lastJobStatus)">{{ jobLabel(syncState?.lastJobStatus) }}</span></b>
</div>
</div>
<p v-if="syncState?.lastErrorMessage" class="field-error">同步失败原因:{{ syncState.lastErrorMessage }}</p>
</section>
<p class="detail-footnote">联系人数据仅更新本地索引;除在详情中显式执行「QQ 侧删除 / 拉黑」外,不会改动 QQ 好友关系;同步不会覆盖已有备注与本地标签。</p>
</div>
</aside>
</template>
<style scoped>
.contact-detail {
display: flex;
flex-direction: column;
min-width: 0;
padding: 0;
overflow: hidden;
}
.mode-panel {
position: sticky;
top: 12px;
max-height: calc(100vh - 190px);
}
.mode-drawer {
position: fixed;
top: 0;
right: 0;
bottom: 0;
z-index: 41;
width: min(420px, 94vw);
border-radius: 0;
border-right: 0;
border-top: 0;
border-bottom: 0;
box-shadow: -18px 0 45px rgb(15 23 42 / 18%);
}
.mode-sheet {
position: fixed;
left: 0;
right: 0;
bottom: 0;
z-index: 41;
max-height: 80vh;
border-radius: 14px 14px 0 0;
box-shadow: 0 -18px 45px rgb(15 23 42 / 18%);
}
.sheet-grab {
width: 38px;
height: 4px;
border-radius: 999px;
background: var(--qk-line-strong, #d7dce8);
margin: 7px auto 0;
flex: none;
}
.detail-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
padding: 14px 16px 12px;
border-bottom: 1px solid var(--qk-line);
flex: none;
}
.detail-person { display: flex; gap: 10px; min-width: 0; }
.detail-name { min-width: 0; }
.detail-name-line { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; }
.detail-name-line strong { font-size: 14px; line-height: 20px; }
.detail-sub { margin-top: 2px; font-size: 10px; color: var(--qk-text-4); font-family: var(--qk-font-num); }
.detail-online { margin-top: 4px; font-size: 10px; color: var(--qk-text-4); display: flex; align-items: center; gap: 4px; }
.detail-online:before { content: ""; width: 5px; height: 5px; border-radius: 50%; background: var(--qk-text-4); }
.detail-body { padding: 12px 16px 16px; overflow: auto; flex: 1; min-height: 0; }
.detail-actions { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 10px; }
.detail-actions .btn { height: 26px; }
.detail-notice { margin: 0 0 10px; font-size: 10px; }
.detail-section { padding: 10px 0; border-top: 1px solid var(--qk-line); }
.detail-section:first-of-type { border-top: 0; padding-top: 0; }
.detail-section-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 7px; }
.detail-section-head strong { font-size: 11px; font-weight: 600; }
.detail-section-head span { font-size: 9.5px; color: var(--qk-text-4); }
.kv-grid { display: grid; grid-template-columns: 1fr; gap: 5px; }
.kv { display: grid; grid-template-columns: 76px minmax(0, 1fr); align-items: start; gap: 8px; font-size: 10.5px; line-height: 1.55; }
.kv span { color: var(--qk-text-4); }
.kv b { font-weight: 500; color: var(--qk-text-2); word-break: break-word; }
.kv em { grid-column: 2; font-style: normal; font-size: 9.5px; color: var(--qk-text-4); }
.kv .mono { font-family: var(--qk-font-num); }
.unavailable { color: var(--qk-text-4) !important; }
.section-hint { margin: 7px 0 0; font-size: 9.5px; line-height: 1.55; color: var(--qk-text-4); }
.tag-row { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; }
.tag-chip {
display: inline-flex;
align-items: center;
gap: 4px;
height: 21px;
padding: 0 5px 0 7px;
border-radius: 4px;
border: 1px solid var(--qk-line-strong, #d7dce8);
background: var(--qk-card);
color: var(--qk-text-3);
font-size: 10px;
}
.tag-chip i { width: 5px; height: 5px; border-radius: 50%; background: var(--qk-text-4); }
.tag-remove { border: 0; background: none; color: var(--qk-text-4); font-size: 12px; line-height: 1; padding: 0 1px; cursor: pointer; }
.tag-remove:hover:not(:disabled) { color: var(--qk-red-ink); }
.tag-remove:disabled { opacity: .4; cursor: not-allowed; }
.tag-add {
height: 21px;
padding: 0 6px;
border: 1px dashed var(--qk-line-strong, #d7dce8);
border-radius: 4px;
background: none;
color: var(--qk-primary);
font-size: 10px;
cursor: pointer;
}
.tag-add:disabled { opacity: .45; cursor: not-allowed; }
.tag-input-row { display: flex; gap: 5px; margin-top: 6px; }
.tag-input-row .field { height: 26px; font-size: 10.5px; }
.tag-input-row .btn { height: 26px; }
.common-group-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }
.common-group-list li { display: flex; justify-content: space-between; gap: 8px; font-size: 10.5px; color: var(--qk-text-3); padding: 3px 0; border-bottom: 1px dashed var(--qk-line); }
.common-group-list li:last-child { border-bottom: 0; }
.common-group-list small { color: var(--qk-text-4); font-family: var(--qk-font-num); }
.detail-footnote { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--qk-line); font-size: 9.5px; line-height: 1.6; color: var(--qk-text-4); }
.danger-ghost { color: var(--qk-red-ink); border-color: #fecaca; background: var(--qk-red-weak); }
@media (max-width: 720px) {
.detail-head { padding: 8px 14px 10px; }
.detail-body { padding: 10px 14px 14px; }
.kv { grid-template-columns: 70px minmax(0, 1fr); }
}
</style>
@@ -0,0 +1,111 @@
<script setup>
import ContactDetail from './ContactDetail.vue'
/**
* 详情槽位:负责未选择占位、首次加载、首次失败状态;具体资料渲染交给 ContactDetail。
* $attrs 继续向下透传 close/edit/delete/block/... 事件,避免中间层逐项复制。
*/
defineProps({
selected: { type: Boolean, default: false },
contact: { type: Object, default: null },
loading: { type: Boolean, default: false },
error: { type: Object, default: null },
mode: { type: String, default: 'panel' },
qqAccount: { type: String, default: '' },
canManage: { type: Boolean, default: true },
tagBusy: { type: Boolean, default: false },
tagError: { type: String, default: '' }
})
defineOptions({ inheritAttrs: false })
defineEmits(['retry'])
</script>
<template>
<aside v-if="!selected" class="card detail-placeholder">
<div class="placeholder-icon" aria-hidden="true">◍</div>
<h3>暂无可查看的联系人</h3>
<p>当前分组为空,可切换到其他分组,或调整搜索与筛选条件查看其他联系人;分组由 QQ 同步,本系统不支持本地调整。</p>
<ol class="guide-list">
<li><b>1</b><span>查看 QQ 号、备注、来源与共同群聊</span></li>
<li><b>2</b><span>添加本地标签,或直接发起会话</span></li>
<li><b>3</b><span>发起会话将跳转到消息中心并定位该会话</span></li>
</ol>
<p class="placeholder-footnote">联系人数据由 NapCat 事件同步,暂不支持手动新建。</p>
</aside>
<div v-else-if="!contact" class="card detail-placeholder">
<div v-if="error" class="notice danger detail-error">
<strong>{{ error.title }}:{{ error.message }}</strong>
<p v-if="error.hint" class="small-muted">{{ error.hint }}</p>
</div>
<span v-else class="spinner" aria-hidden="true"></span>
<p v-if="!error">正在读取联系人资料…</p>
<p v-else class="small-muted">资料未加载成功,依赖详情的编辑、删除、拉黑与标签操作已停用,避免与列表数据混用。</p>
<button v-if="error" class="btn sm" type="button" :disabled="loading" @click="$emit('retry')">
{{ loading ? '重试中…' : '重试' }}
</button>
</div>
<!-- 已有资料但刷新失败:保留上一次成功加载的真实资料,并在顶部常驻错误提示,不使用列表行兜底。 -->
<div v-else class="detail-stack">
<div v-if="error" class="notice danger detail-error">
<strong>{{ error.title }}:{{ error.message }}</strong>
<p v-if="error.hint" class="small-muted">{{ error.hint }}</p>
<p class="small-muted">当前展示的是上一次成功加载的资料,可能已过期。</p>
<button class="btn sm" type="button" :disabled="loading" @click="$emit('retry')">
{{ loading ? '重试中…' : '重试' }}
</button>
</div>
<ContactDetail
v-bind="$attrs"
:contact="contact"
:mode="mode"
:qq-account="qqAccount"
:can-manage="canManage"
:tag-busy="tagBusy"
:tag-error="tagError"
/>
</div>
</template>
<style scoped>
.detail-placeholder {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
min-height: 320px;
padding: 22px 18px;
text-align: center;
position: sticky;
top: 12px;
}
.placeholder-icon {
width: 40px;
height: 40px;
display: grid;
place-items: center;
border-radius: 10px;
background: var(--qk-surface-2, #f8f9fc);
border: 1px solid var(--qk-line);
color: var(--qk-text-4);
font-size: 18px;
margin-bottom: 4px;
}
.detail-placeholder h3 { margin: 0; font-size: 12px; font-weight: 600; }
.detail-placeholder p { max-width: 280px; margin: 0; font-size: 10px; line-height: 1.6; color: var(--qk-text-4); }
.guide-list { list-style: none; margin: 10px 0 0; padding: 0; display: flex; flex-direction: column; gap: 7px; width: 100%; max-width: 280px; text-align: left; }
.guide-list li { display: flex; align-items: flex-start; gap: 7px; font-size: 9.5px; line-height: 1.55; color: var(--qk-text-3); }
.guide-list b { flex: none; width: 16px; height: 16px; display: grid; place-items: center; border-radius: 50%; background: var(--qk-primary-weak); color: var(--qk-primary); font-size: 9px; font-weight: 600; }
.placeholder-footnote { margin-top: 12px; padding-top: 9px; border-top: 1px solid var(--qk-line); font-size: 9px; color: var(--qk-text-4); }
.detail-placeholder .spinner { width: 18px; height: 18px; }
.small-muted { font-size: 9.5px; color: var(--qk-text-4); }
.detail-error { width: 100%; text-align: left; }
.detail-error strong { display: block; font-size: 10.5px; }
.detail-error p { margin: 4px 0 0; max-width: none; }
.detail-error .btn { margin-top: 6px; }
.detail-stack { display: flex; flex-direction: column; gap: 8px; min-width: 0; }
</style>
@@ -0,0 +1,184 @@
<script setup>
import { computed } from 'vue'
/**
* 系统级空态:区分“未接入 NapCat”和“已接入但从未同步/同步失败”两个分支(v3-08)。
* 账号是全局必需上下文;未确定当前账号时不触发同步。
*/
const props = defineProps({
accounts: { type: Array, default: () => [] },
current: { type: String, default: '' },
syncState: { type: Object, default: null },
syncError: { type: String, default: '' },
syncLoading: { type: Boolean, default: false }
})
const emit = defineEmits(['goto-connections', 'sync', 'refresh', 'pick-account'])
const hasAccounts = computed(() => props.accounts.length > 0)
const status = computed(() => String(props.syncState?.status || '').toUpperCase())
const running = computed(() => status.value === 'RUNNING' || props.syncLoading)
const statusLabel = computed(() => {
return {
RUNNING: '同步进行中',
SUCCEEDED: '最近同步成功',
PARTIAL: '最近同步部分成功',
FAILED: '最近同步失败',
OFFLINE: '账号离线',
STALE: '未同步'
}[status.value] || '未获取同步状态'
})
const title = computed(() => {
if (!hasAccounts.value) return '联系人中心暂无数据'
if (!props.current) return '尚未确定当前 QQ 账号'
if (status.value === 'RUNNING') return '正在同步联系人'
return '尚未同步联系人'
})
const description = computed(() => {
if (!hasAccounts.value) {
return '联系人来自 NapCat 同步,当前没有可展示的联系人。请先在接入管理绑定 NapCat 并确认连接在线。'
}
if (!props.current) {
return '账号目录尚未就绪,无法确定同步对象。请刷新账号目录,或到接入管理确认绑定已上线。'
}
if (status.value === 'RUNNING') {
return `账号 ${props.current} 正在同步联系人,完成后列表会自动刷新。`
}
if (status.value === 'OFFLINE') {
return `账号 ${props.current} 当前离线,联系人同步已暂停。请保持账号在线后重新同步。`
}
if (status.value === 'FAILED') {
return `账号 ${props.current} 最近一次同步失败,联系人索引可能不完整。请查看失败原因并重试。`
}
return `账号 ${props.current} 已绑定,但尚未完成首次联系人同步。请执行同步后重试。`
})
const branchTwoText = computed(() => {
if (!props.current) {
return hasAccounts.value
? `已绑定 ${props.accounts.length} 个 QQ 账号,但当前账号尚未确定,无法确认同步记录。`
: '绑定 NapCat 后,未完成首次同步时使用此分支处理。'
}
const parts = [`QQ ${props.current}`, statusLabel.value]
if (props.syncState?.lastJobFinishedAt) parts.push(`最近任务 ${formatShort(props.syncState.lastJobFinishedAt)}`)
return `${parts.join(' · ')}。点「立即同步」重新拉取联系人。`
})
function formatShort(value) {
const date = new Date(value)
if (Number.isNaN(date.getTime())) return '—'
return `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}
</script>
<template>
<section class="card contacts-empty">
<header class="empty-head">
<div>
<strong>联系人数据</strong>
<span class="empty-count">0 人</span>
</div>
<div class="empty-head-meta">
<span class="status" :class="hasAccounts ? 'muted' : 'warning'">{{ hasAccounts ? (current ? statusLabel : '待确定账号') : '未接入' }}</span>
<button class="btn sm ghost" type="button" @click="$emit('refresh')">刷新</button>
<button class="btn sm" type="button" @click="$emit('goto-connections')">接入管理</button>
</div>
</header>
<div class="empty-main">
<div class="empty-icon" aria-hidden="true">◍</div>
<h2>{{ title }}</h2>
<p class="empty-desc">{{ description }}</p>
<p class="empty-status">当前状态:<b>{{ hasAccounts ? (current ? statusLabel : '待确定当前账号') : '未绑定任何 NapCat 账号' }}</b></p>
<p v-if="syncError" class="field-error">同步状态读取失败:{{ syncError }}</p>
<p v-if="syncState?.lastErrorMessage" class="field-error">同步失败原因:{{ syncState.lastErrorMessage }}</p>
<div class="empty-actions">
<template v-if="!hasAccounts">
<button class="btn primary" type="button" @click="$emit('goto-connections')">去接入管理</button>
<button class="btn" type="button" @click="$emit('refresh')">刷新</button>
</template>
<template v-else-if="!current">
<button class="btn primary" type="button" @click="$emit('goto-connections')">去接入管理</button>
<button class="btn" type="button" @click="$emit('refresh')">刷新</button>
</template>
<template v-else>
<button class="btn primary" type="button" :disabled="running" @click="$emit('sync')">
{{ running ? '同步进行中…' : '立即同步' }}
</button>
<button class="btn" type="button" @click="$emit('refresh')">刷新</button>
</template>
</div>
</div>
<div class="branch-grid">
<article class="branch-card" :class="{ active: !hasAccounts }">
<span class="branch-badge">1</span>
<div class="branch-body">
<div class="branch-title">未绑定任何 NapCat 账号 <span class="branch-tag">{{ hasAccounts ? '另一种情况' : '当前' }}</span></div>
<p>实例尚未绑定 NapCat,没有同步的联系人来源。绑定后保持账号在线,联系人会自动出现在列表;也可在接入管理中手动触发同步。</p>
<div class="branch-actions">
<button class="btn sm" type="button" @click="$emit('goto-connections')">去接入管理</button>
<button class="btn sm ghost" type="button" @click="$emit('refresh')">查看绑定说明</button>
</div>
</div>
</article>
<article class="branch-card" :class="{ active: hasAccounts }">
<span class="branch-badge">2</span>
<div class="branch-body">
<div class="branch-title">已绑定,但从未同步 <span class="branch-tag">{{ hasAccounts ? '当前' : '另一种情况' }}</span></div>
<p>{{ branchTwoText }}</p>
<div class="branch-actions">
<button class="btn sm" type="button" :disabled="!current || running" :title="!current ? '请先选择具体 QQ 账号' : ''" @click="$emit('sync')">立即同步</button>
<button class="btn sm ghost" type="button" @click="$emit('goto-connections')">查看同步记录</button>
</div>
</div>
</article>
</div>
<div class="empty-stats">
<div class="empty-stat"><span>同步来源</span><b>NapCat 绑定账号</b></div>
<div class="empty-stat"><span>同步范围</span><b>好友 · 群聊 · 群成员</b></div>
<div class="empty-stat"><span>触发方式</span><b>绑定后自动 · 手动同步</b></div>
<div class="empty-stat"><span>同步记录</span><b>接入管理可查</b></div>
</div>
<p class="empty-footnote">同步只更新本地联系人索引,不改动 QQ 好友关系;已有备注、分组与标签在同步后仍保留。</p>
</section>
</template>
<style scoped>
.contacts-empty { padding: 0; overflow: hidden; }
.empty-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 10px 14px; border-bottom: 1px solid var(--qk-line); }
.empty-head strong { font-size: 12px; }
.empty-count { margin-left: 6px; font-size: 10px; color: var(--qk-text-4); font-family: var(--qk-font-num); }
.empty-head-meta { display: flex; align-items: center; gap: 6px; }
.empty-main { max-width: 560px; margin: 0 auto; padding: 28px 20px 20px; text-align: center; }
.empty-icon { width: 46px; height: 46px; margin: 0 auto 10px; display: grid; place-items: center; border-radius: 12px; background: var(--qk-primary-weak); color: var(--qk-primary); font-size: 20px; }
.empty-main h2 { margin: 0; font-size: 15px; font-weight: 600; }
.empty-desc { max-width: 430px; margin: 6px auto 10px; font-size: 10.5px; line-height: 1.65; color: var(--qk-text-3); }
.empty-status { margin: 0 0 4px; font-size: 10px; color: var(--qk-text-4); }
.empty-status b { color: var(--qk-text-2); font-weight: 600; }
.empty-actions { display: flex; justify-content: center; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
.branch-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; padding: 0 14px; }
.branch-card { display: flex; gap: 8px; padding: 10px; border: 1px solid var(--qk-line); border-radius: 8px; background: var(--qk-surface-2, #f8f9fc); }
.branch-card.active { border-color: var(--qk-primary); background: var(--qk-primary-weak); }
.branch-badge { flex: none; width: 18px; height: 18px; display: grid; place-items: center; border-radius: 50%; border: 1px solid var(--qk-line-strong); font-size: 9px; color: var(--qk-text-4); }
.branch-card.active .branch-badge { background: var(--qk-primary); border-color: var(--qk-primary); color: #fff; }
.branch-body { min-width: 0; }
.branch-title { display: flex; align-items: center; flex-wrap: wrap; gap: 5px; font-size: 11px; font-weight: 600; }
.branch-tag { padding: 0 4px; border-radius: 3px; border: 1px solid var(--qk-line-strong); font-size: 9px; font-weight: 400; color: var(--qk-text-4); }
.branch-body p { margin: 4px 0 8px; font-size: 9.5px; line-height: 1.6; color: var(--qk-text-3); }
.branch-actions { display: flex; gap: 6px; flex-wrap: wrap; }
.empty-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1px; margin: 14px; border: 1px solid var(--qk-line); border-radius: 8px; overflow: hidden; background: var(--qk-line); }
.empty-stat { display: flex; flex-direction: column; gap: 2px; padding: 9px 10px; background: var(--qk-card); }
.empty-stat span { font-size: 9px; color: var(--qk-text-4); }
.empty-stat b { font-size: 10px; font-weight: 500; color: var(--qk-text-2); }
.empty-footnote { margin: 0; padding: 0 14px 14px; font-size: 9.5px; line-height: 1.6; color: var(--qk-text-4); }
@media (max-width: 720px) {
.branch-grid { grid-template-columns: 1fr; }
.empty-stats { grid-template-columns: 1fr 1fr; }
}
</style>
@@ -0,0 +1,158 @@
<script setup>
import { computed, ref, watch } from 'vue'
import Modal from '../../components/ui/Modal.vue'
import Checkbox from '../../components/ui/Checkbox.vue'
import { contactsApi, newIdempotencyKey } from '../../api/contacts'
import { notify } from '../../ui'
import { errorText } from './util'
/**
* 删除联系人:默认仅本地软删;也可显式选择同时删除 QQ 好友。
* QQ 删除不可逆,只允许单条执行;必须勾选二次确认,失败/结果未知不提示成功。
*/
const props = defineProps({
open: { type: Boolean, default: false },
contact: { type: Object, default: null },
qqAccount: { type: String, default: '' }
})
const emit = defineEmits(['close', 'done'])
const mode = ref('LOCAL')
const acked = ref(false)
const busy = ref(false)
const error = ref('')
const idempotencyKey = ref('')
const contact = computed(() => props.contact || {})
const isPerson = computed(() => String(contact.value.contactType || '').toUpperCase() === 'PERSON')
const displayName = computed(() => contact.value.displayName || contact.value.nickname || '该联系人')
const qqModeDisabled = computed(() => !isPerson.value)
const canSubmit = computed(() => !busy.value && acked.value && Boolean(props.qqAccount))
function reset() {
mode.value = 'LOCAL'
acked.value = false
busy.value = false
error.value = ''
idempotencyKey.value = newIdempotencyKey()
}
watch(
() => [props.open, contact.value.contactUid],
([open]) => {
if (open) reset()
},
{ immediate: true }
)
watch(mode, () => {
acked.value = false
error.value = ''
idempotencyKey.value = newIdempotencyKey()
})
function close() {
if (busy.value) return
emit('close')
}
async function submit() {
if (!canSubmit.value) return
if (!props.qqAccount) {
error.value = '请先选择具体 QQ 账号后再删除联系人。'
return
}
if (mode.value === 'QQ' && !isPerson.value) {
error.value = '群聊联系人不能执行 QQ 删除好友操作。'
return
}
busy.value = true
error.value = ''
try {
await contactsApi.delete(
contact.value.contactUid,
{ qqAccount: props.qqAccount, confirm: true, mode: mode.value },
idempotencyKey.value
)
notify(
mode.value === 'QQ' ? 'QQ 好友删除已由上游确认' : '已从本地联系人列表删除',
mode.value === 'QQ'
? '该操作不可逆,系统不会自动恢复好友关系;历史消息与审计记录仍保留。'
: '历史消息、媒体与审计记录保留;后续同步若仍为好友可再次出现。',
'success'
)
emit('done')
emit('close')
} catch (e) {
error.value = errorText(e)
} finally {
busy.value = false
}
}
</script>
<template>
<Modal :open="open" size="sm" title="删除联系人" :subtitle="`${displayName} · QQ ${contact.contactId || '—'}`" :busy="busy" @close="close">
<div class="delete-form">
<p class="delete-intro">请选择删除方式。删除会影响后续联系人展示,但不会自动清理历史数据。</p>
<label class="option-card" :class="{ active: mode === 'LOCAL' }">
<input v-model="mode" type="radio" value="LOCAL" :disabled="busy" />
<span class="option-main">
<strong>仅本地删除(默认)</strong>
<em>从联系人列表隐藏,历史消息、媒体与审计记录保留;后续同步若仍为好友可再次出现。</em>
</span>
</label>
<label class="option-card is-danger" :class="{ active: mode === 'QQ', disabled: qqModeDisabled }">
<input v-model="mode" type="radio" value="QQ" :disabled="busy || qqModeDisabled" />
<span class="option-main">
<strong>同时删除 QQ 好友</strong>
<em v-if="!qqModeDisabled">将调用 NapCat 删除好友。QQ 侧删除不可逆,系统不会自动恢复;群聊联系人不可使用此选项。</em>
<em v-else>群聊联系人不能执行 QQ 删除好友操作。</em>
</span>
</label>
<div v-if="mode === 'QQ'" class="notice danger">
QQ 删除不可逆,且无法保证对方客户端已即时感知;如上游超时,后端会返回「结果未知」,请先核实再决定是否重试。该操作只能单条执行。
</div>
<Checkbox v-model="acked" :disabled="busy" :label="mode === 'QQ' ? '我已知晓 QQ 侧删除不可逆,且系统不会自动恢复好友关系。' : '我已知晓该联系人将从本地联系人列表移除。'" />
<div v-if="error" class="notice danger">{{ error }}</div>
<p class="form-footnote">本地删除与 QQ 删除都会写入审计记录;本地软删可通过「显示已软删」筛选后恢复。</p>
</div>
<template #foot>
<button class="btn ghost" type="button" :disabled="busy" @click="close">取消</button>
<button class="btn danger" type="button" :disabled="!canSubmit" @click="submit">
{{ busy ? '执行中…' : '确认删除' }}
</button>
</template>
</Modal>
</template>
<style scoped>
.delete-form { display: flex; flex-direction: column; gap: 10px; }
.delete-intro { margin: 0; font-size: 10.5px; line-height: 1.6; color: var(--qk-text-3); }
.option-card {
display: flex;
align-items: flex-start;
gap: 9px;
padding: 9px 10px;
border: 1px solid var(--qk-line);
border-radius: 8px;
cursor: pointer;
transition: border-color .15s ease, background .15s ease;
}
.option-card.active { border-color: var(--qk-primary); background: var(--qk-primary-weak); }
.option-card.is-danger.active { border-color: #fca5a5; background: var(--qk-red-weak); }
.option-card.disabled { opacity: .55; cursor: not-allowed; }
.option-card input { margin-top: 2px; accent-color: var(--qk-primary); }
.is-danger input { accent-color: var(--qk-red-ink); }
.option-main { display: flex; flex-direction: column; gap: 3px; }
.option-main strong { font-size: 11px; color: var(--qk-text-2); }
.option-main em { font-style: normal; font-size: 9.5px; line-height: 1.55; color: var(--qk-text-4); }
.form-footnote { margin: 0; font-size: 9.5px; color: var(--qk-text-4); line-height: 1.55; }
</style>
@@ -0,0 +1,236 @@
<script setup>
import { computed, ref, watch } from 'vue'
import Modal from '../../components/ui/Modal.vue'
import Input from '../../components/ui/Input.vue'
import { contactsApi } from '../../api/contacts'
import { notify } from '../../ui'
import { errorText } from './util'
/**
* 编辑备注与标签。分组只展示 QQ 同步结果,不提供本地改分组(口径已确认)。
* 标签的增删与备注保存属于本地写操作,均需 confirm=true;失败不做成功提示。
*/
const props = defineProps({
open: { type: Boolean, default: false },
contact: { type: Object, default: null },
qqAccount: { type: String, default: '' }
})
const emit = defineEmits(['close', 'saved'])
const remark = ref('')
const visibleTags = ref([])
const newTags = ref([])
const removedTags = ref([])
const tagName = ref('')
const saving = ref(false)
const error = ref('')
const tagError = ref('')
const MAX_TAGS = 8
const contact = computed(() => props.contact || {})
const typeLabel = computed(() => (String(contact.value.contactType || '').toUpperCase() === 'PERSON' ? '好友' : '群聊'))
const tagLimitReached = computed(() => visibleTags.value.length >= MAX_TAGS)
function reset() {
remark.value = contact.value.remark || ''
visibleTags.value = Array.isArray(contact.value.tags) ? contact.value.tags.map((tag) => ({ ...tag })) : []
newTags.value = []
removedTags.value = []
tagName.value = ''
error.value = ''
tagError.value = ''
}
watch(
() => [props.open, contact.value.contactUid],
([open]) => {
if (open) reset()
},
{ immediate: true }
)
function addTag() {
tagError.value = ''
const name = tagName.value.trim()
if (!name) return
if (tagLimitReached.value) {
tagError.value = `每个联系人最多 ${MAX_TAGS} 个标签。`
return
}
if (visibleTags.value.some((tag) => String(tag.name || '').toLowerCase() === name.toLowerCase())) {
tagError.value = '该标签已存在于当前联系人。'
return
}
visibleTags.value.push({ name, tagUid: '', pending: true })
newTags.value.push(name)
tagName.value = ''
}
function removeTag(tag) {
tagError.value = ''
visibleTags.value = visibleTags.value.filter((item) => item !== tag)
if (tag.pending) {
newTags.value = newTags.value.filter((name) => name !== tag.name)
} else if (tag.tagUid) {
removedTags.value.push(tag.tagUid)
}
}
function close() {
if (saving.value) return
emit('close')
}
async function save() {
if (saving.value) return
if (!props.qqAccount) {
error.value = '请先选择具体 QQ 账号后再保存。'
return
}
saving.value = true
error.value = ''
tagError.value = ''
const failures = []
let remarkSaved = false
try {
await contactsApi.updateRemark(contact.value.contactUid, {
qqAccount: props.qqAccount,
confirm: true,
remark: remark.value.trim()
})
remarkSaved = true
for (const name of newTags.value) {
try {
await contactsApi.addTag(contact.value.contactUid, {
qqAccount: props.qqAccount,
confirm: true,
name
})
} catch (e) {
failures.push(`添加标签「${name}」失败:${errorText(e)}`)
}
}
for (const tagUid of removedTags.value) {
try {
await contactsApi.removeTag(contact.value.contactUid, tagUid, {
qqAccount: props.qqAccount,
confirm: true
})
} catch (e) {
failures.push(`移除标签失败:${errorText(e)}`)
}
}
} catch (e) {
error.value = errorText(e)
saving.value = false
return
}
saving.value = false
if (failures.length) {
tagError.value = failures.join(';')
notify('备注已保存,但标签未全部生效', tagError.value, 'warning')
emit('saved')
return
}
if (remarkSaved) notify('联系人资料已保存', '备注与标签已更新,变更已写入审计。', 'success')
emit('saved')
emit('close')
}
</script>
<template>
<Modal :open="open" size="md" title="编辑备注与标签" :subtitle="`${contact.displayName || contact.nickname || '—'} · QQ ${contact.contactId || '—'} · ${typeLabel}`" :busy="saving" @close="close">
<div class="edit-form">
<Input
v-model="remark"
label="备注名"
placeholder="留空时显示昵称"
hint="优先显示在联系人列表与会话消息中,留空时显示昵称。"
:maxlength="255"
show-count
size="md"
/>
<div class="readonly-row">
<div class="readonly-label">好友分组</div>
<div class="readonly-value">{{ contact.groupName || '未分组' }}</div>
<p class="readonly-hint">分组只由 QQ 同步,不支持在本系统修改,也不改变 QQ 好友关系。</p>
</div>
<div class="tag-field">
<div class="tag-field-head">
<span>标签</span>
<span class="tag-count">最多 {{ MAX_TAGS }} 个 · 已选 {{ visibleTags.length }}</span>
</div>
<div class="tag-row">
<span v-for="tag in visibleTags" :key="tag.tagUid || `new-${tag.name}`" class="tag-chip">
{{ tag.name }}
<button class="tag-remove" type="button" :aria-label="`移除标签 ${tag.name}`" @click="removeTag(tag)">×</button>
</span>
<span v-if="!visibleTags.length" class="small-muted">暂无标签</span>
</div>
<div class="tag-input-row">
<Input
v-model="tagName"
placeholder="输入标签名,回车添加"
:disabled="tagLimitReached"
:maxlength="32"
size="sm"
@enter="addTag"
/>
<button class="btn sm" type="button" :disabled="tagLimitReached || !tagName.trim()" @click="addTag">添加</button>
</div>
<p v-if="tagError" class="field-error">{{ tagError }}</p>
<p v-else class="tag-hint">建议使用「客户」「同事」「临时」等短标签;标签用于批量筛选与自动化规则筛选,不会写入 QQ。</p>
</div>
<div v-if="error" class="notice danger form-notice">{{ error }}</div>
<p class="form-footnote">保存将写入审计记录,包含操作人、时间与变更值。</p>
</div>
<template #foot>
<button class="btn ghost" type="button" :disabled="saving" @click="close">取消</button>
<button class="btn primary" type="button" :disabled="saving" @click="save">
{{ saving ? '保存中…' : '保存' }}
</button>
</template>
</Modal>
</template>
<style scoped>
.edit-form { display: flex; flex-direction: column; gap: 14px; }
.readonly-row {
padding: 9px 10px;
border: 1px solid var(--qk-line);
border-radius: 8px;
background: var(--qk-surface-2, #f8f9fc);
}
.readonly-label { font-size: 10px; color: var(--qk-text-4); }
.readonly-value { margin-top: 2px; font-size: 11px; font-weight: 600; color: var(--qk-text-2); }
.readonly-hint { margin: 4px 0 0; font-size: 9.5px; line-height: 1.55; color: var(--qk-text-4); }
.tag-field { display: flex; flex-direction: column; gap: 6px; }
.tag-field-head { display: flex; align-items: center; justify-content: space-between; font-size: 10px; color: var(--qk-text-3); }
.tag-count { font-size: 9.5px; color: var(--qk-text-4); font-family: var(--qk-font-num); }
.tag-row { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; }
.tag-chip {
display: inline-flex;
align-items: center;
gap: 4px;
height: 22px;
padding: 0 5px 0 7px;
border: 1px solid var(--qk-line-strong);
border-radius: 4px;
background: var(--qk-card);
color: var(--qk-text-3);
font-size: 10px;
}
.tag-remove { border: 0; background: none; padding: 0 1px; color: var(--qk-text-4); font-size: 12px; line-height: 1; cursor: pointer; }
.tag-remove:hover { color: var(--qk-red-ink); }
.tag-input-row { display: flex; gap: 6px; align-items: center; }
.tag-input-row :deep(.qk-field) { height: 28px; font-size: 10.5px; }
.tag-hint, .form-footnote { margin: 0; font-size: 9.5px; line-height: 1.6; color: var(--qk-text-4); }
.form-footnote { padding-top: 8px; border-top: 1px solid var(--qk-line); }
.form-notice { font-size: 10px; }
.small-muted { font-size: 10px; color: var(--qk-text-4); }
</style>
+10
View File
@@ -0,0 +1,10 @@
import { describeError } from '../../ui'
/** 联系人模块统一错误文案:保留后端 message、错误码与追踪标识,不吞异常。 */
export function errorText(error) {
const info = describeError(error)
const parts = [`${info.title}:${info.message}`]
if (info.code) parts.push(`错误码 ${info.code}`)
if (info.requestId) parts.push(`追踪 ${info.requestId}`)
return parts.join(';')
}