feat: 交付本地可运行 V1 候选版

实现初始化、单管理员认证、NapCat 被动接收、消息查询、媒体与发送闭环,补齐前端、自动化测试及同步文档。
This commit is contained in:
2026-11-04 11:34:34 +08:00
parent 46010f9fd2
commit 5432d61571
90 changed files with 10665 additions and 130 deletions
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>QLinker 管理台</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
+1419
View File
File diff suppressed because it is too large Load Diff
+19
View File
@@ -0,0 +1,19 @@
{
"name": "qlinker-frontend",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.5.13",
"vue-router": "^4.5.0"
},
"devDependencies": {
"@vitejs/plugin-vue": "^5.2.1",
"vite": "^6.3.5"
}
}
+100
View File
@@ -0,0 +1,100 @@
<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { api, getToken, setToken } from './api'
const router = useRouter()
const user = ref(null)
const loadError = ref('')
async function loadUser() {
if (!getToken()) return
try {
user.value = await api.me()
} catch (e) {
if (e.code === 'UNAUTHENTICATED') {
setToken('')
router.push('/login')
} else {
loadError.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
}
}
}
async function logout() {
try {
await api.logout()
} finally {
setToken('')
user.value = null
router.push('/login')
}
}
onMounted(loadUser)
</script>
<template>
<div class="layout">
<header class="topbar">
<span class="brand">QLinker 管理台</span>
<nav>
<RouterLink to="/overview">总览</RouterLink>
<RouterLink to="/bindings">NapCat 连接</RouterLink>
<RouterLink to="/messages">消息</RouterLink>
<RouterLink to="/send">发送</RouterLink>
</nav>
<div class="user">
<span v-if="user">{{ user.username }}</span>
<button v-if="user" class="ghost" @click="logout">退出登录</button>
</div>
</header>
<p v-if="loadError" class="error">{{ loadError }}</p>
<main>
<RouterView />
</main>
</div>
</template>
<style>
:root {
--bg: #f5f6f8;
--card: #ffffff;
--line: #dfe3e8;
--text: #1f2329;
--muted: #6b7280;
--danger: #c62828;
--ok: #2e7d32;
--warn: #ef6c00;
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text); font-family: system-ui, "Microsoft YaHei", sans-serif; }
.topbar { display: flex; align-items: center; gap: 24px; padding: 12px 20px; background: var(--card); border-bottom: 1px solid var(--line); }
.topbar .brand { font-weight: 700; }
.topbar nav { display: flex; gap: 16px; flex: 1; }
.topbar nav a { color: var(--muted); text-decoration: none; }
.topbar nav a.router-link-active { color: var(--text); font-weight: 600; }
.topbar .user { display: flex; align-items: center; gap: 12px; color: var(--muted); }
main { padding: 20px; max-width: 1200px; margin: 0 auto; }
.card { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 16px; margin-bottom: 16px; }
.card h2 { margin: 0 0 12px; font-size: 16px; }
.grid { display: grid; gap: 12px; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
.stat { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 14px; }
.stat .value { font-size: 22px; font-weight: 700; }
.stat .label { color: var(--muted); font-size: 13px; }
table { width: 100%; border-collapse: collapse; font-size: 14px; }
th, td { text-align: left; padding: 8px; border-bottom: 1px solid var(--line); }
th { color: var(--muted); font-weight: 500; }
button { padding: 7px 14px; border: 1px solid var(--line); border-radius: 6px; background: #1f6feb; color: #fff; cursor: pointer; }
button.ghost { background: transparent; color: var(--muted); }
button:disabled { opacity: 0.5; cursor: not-allowed; }
input, select, textarea { padding: 8px; border: 1px solid var(--line); border-radius: 6px; font: inherit; width: 100%; }
label { display: block; margin-bottom: 10px; font-size: 13px; color: var(--muted); }
label > span { display: block; margin-bottom: 4px; }
.error { color: var(--danger); font-size: 14px; }
.ok { color: var(--ok); font-size: 14px; }
.warn { color: var(--warn); font-size: 14px; }
.muted { color: var(--muted); font-size: 13px; }
.row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
pre { background: #f3f4f6; padding: 10px; border-radius: 6px; overflow: auto; font-size: 12px; }
</style>
+80
View File
@@ -0,0 +1,80 @@
const TOKEN_KEY = 'qlinker.token'
export function getToken() {
return localStorage.getItem(TOKEN_KEY) || ''
}
export function setToken(token) {
if (token) localStorage.setItem(TOKEN_KEY, token)
else localStorage.removeItem(TOKEN_KEY)
}
/** 后端统一响应:success/code/message/data/requestId。失败时抛出携带 code 与 requestId 的错误。 */
export async function request(path, options = {}) {
const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) }
const token = getToken()
if (token) headers.Authorization = `Bearer ${token}`
const response = await fetch(path, { ...options, headers })
let body = null
try {
body = await response.json()
} catch {
throw new Error(`服务返回非 JSON 响应(HTTP ${response.status})`)
}
if (!body || body.success !== true) {
const error = new Error(body?.message || `请求失败(HTTP ${response.status})`)
error.code = body?.code
error.requestId = body?.requestId
error.httpStatus = response.status
throw error
}
return body.data
}
export const api = {
initialization: () => request('/api/v1/system/initialization'),
healthDetail: () => request('/api/v1/system/health-detail'),
bootstrap: (bootstrapToken, username, password) =>
request('/api/v1/auth/bootstrap', {
method: 'POST',
body: JSON.stringify({ bootstrapToken, username, password })
}),
login: (username, password) =>
request('/api/v1/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) }),
logout: () => request('/api/v1/auth/logout', { method: 'POST' }),
me: () => request('/api/v1/auth/me'),
bindings: () => request('/api/v1/napcat-bindings'),
createBinding: (payload) => request('/api/v1/napcat-bindings', { method: 'POST', body: JSON.stringify(payload) }),
rotateToken: (uid, accessToken) =>
request(`/api/v1/napcat-bindings/${uid}/access-token`, {
method: 'PUT',
body: JSON.stringify({ accessToken })
}),
deactivateBinding: (uid) => request(`/api/v1/napcat-bindings/${uid}`, { method: 'DELETE' }),
messages: (params) => request(`/api/v1/messages?${new URLSearchParams(params)}`),
message: (uid) => request(`/api/v1/messages/${uid}`),
messageStats: () => request('/api/v1/messages/stats'),
mediaStats: () => request('/api/v1/media/stats'),
media: (uid) => request(`/api/v1/media/${uid}`),
mediaAccessUrl: (uid) => request(`/api/v1/media/${uid}/access-url`),
prepareText: (payload, idempotencyKey) =>
request('/api/v1/send/text', {
method: 'POST',
headers: { 'Idempotency-Key': idempotencyKey },
body: JSON.stringify(payload)
}),
executeSend: (uid, confirmToken) =>
request(`/api/v1/send/operations/${uid}/execute`, {
method: 'POST',
body: JSON.stringify({ confirmToken })
}),
sendOperation: (uid) => request(`/api/v1/send/operations/${uid}`),
sendOperations: (limit = 50) => request(`/api/v1/send/operations?limit=${limit}`),
sendSummary: () => request('/api/v1/send/summary')
}
+31
View File
@@ -0,0 +1,31 @@
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import BootstrapView from './views/BootstrapView.vue'
import LoginView from './views/LoginView.vue'
import OverviewView from './views/OverviewView.vue'
import BindingsView from './views/BindingsView.vue'
import MessagesView from './views/MessagesView.vue'
import SendView from './views/SendView.vue'
import { getToken } from './api'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', redirect: '/overview' },
{ path: '/bootstrap', component: BootstrapView, meta: { public: true } },
{ path: '/login', component: LoginView, meta: { public: true } },
{ path: '/overview', component: OverviewView },
{ path: '/bindings', component: BindingsView },
{ path: '/messages', component: MessagesView },
{ path: '/send', component: SendView }
]
})
// 未登录一律跳转登录页;是否需要先初始化由登录页根据后端状态提示。
router.beforeEach((to) => {
if (!to.meta.public && !getToken()) return '/login'
return true
})
createApp(App).use(router).mount('#app')
+124
View File
@@ -0,0 +1,124 @@
<script setup>
import { ref, onMounted } from 'vue'
import { api } from '../api'
const rows = ref([])
const loading = ref(false)
const error = ref('')
const notice = ref('')
const form = ref({ displayName: '', endpoint: '', accessToken: '' })
const creating = ref(false)
const createError = ref('')
const rotating = ref('')
const rotateToken = ref('')
const rotateError = ref('')
async function load() {
loading.value = true
error.value = ''
try {
rows.value = await api.bindings()
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
loading.value = false
}
}
async function create() {
createError.value = ''
notice.value = ''
creating.value = true
try {
await api.createBinding({ ...form.value })
form.value = { displayName: '', endpoint: '', accessToken: '' }
notice.value = '绑定已创建。连接与在线状态将在总览页刷新后可见。'
await load()
} catch (e) {
createError.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
creating.value = false
}
}
async function rotate(bindingUid) {
rotateError.value = ''
try {
await api.rotateToken(bindingUid, rotateToken.value)
rotating.value = ''
rotateToken.value = ''
notice.value = '访问令牌已更新。'
await load()
} catch (e) {
rotateError.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
}
}
async function deactivate(row) {
if (!window.confirm(`确认解绑「${row.displayName || row.bindingUid}」?历史消息与事件会保留。`)) return
error.value = ''
try {
await api.deactivateBinding(row.bindingUid)
await load()
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
}
}
onMounted(load)
</script>
<template>
<div>
<div class="card">
<h2>新增 NapCat 绑定</h2>
<p class="muted">
采用正向 WebSocket:QLinker 主动连接 NapCat 的事件上报地址。同一 NapCat 实例最多保留一条有效绑定。
</p>
<form @submit.prevent="create">
<label><span>显示名称</span><input v-model="form.displayName" required /></label>
<label><span>连接地址(ws://…)</span><input v-model="form.endpoint" placeholder="ws://127.0.0.1:3001" required /></label>
<label><span>访问令牌</span><input v-model="form.accessToken" type="password" autocomplete="off" /></label>
<button type="submit" :disabled="creating">{{ creating ? '提交中…' : '创建绑定' }}</button>
<p v-if="createError" class="error">{{ createError }}</p>
</form>
<p v-if="notice" class="ok">{{ notice }}</p>
</div>
<div class="card">
<div class="row" style="justify-content: space-between;">
<h2 style="margin: 0;">绑定列表</h2>
<button class="ghost" :disabled="loading" @click="load">{{ loading ? '刷新中…' : '刷新' }}</button>
</div>
<p v-if="error" class="error">{{ error }}</p>
<table>
<thead>
<tr><th>名称</th><th>地址</th><th>绑定状态</th><th>连接状态</th><th>QQ 账号</th><th>凭据</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.bindingUid">
<td>{{ row.displayName }}</td>
<td class="muted">{{ row.endpoint }}</td>
<td>{{ row.bindingStatus }}</td>
<td>{{ row.connectionStatus }}</td>
<td>{{ row.qqAccountId || '-' }}</td>
<td>{{ row.hasCredential ? '已保存' : '未设置' }}</td>
<td class="row">
<button v-if="rotating !== row.bindingUid" class="ghost" @click="rotating = row.bindingUid">轮换令牌</button>
<button class="ghost" @click="deactivate(row)">解绑</button>
</td>
</tr>
<tr v-if="!rows.length && !loading"><td colspan="7" class="muted">暂无绑定。</td></tr>
</tbody>
</table>
<div v-if="rotating" class="row" style="margin-top: 12px;">
<input v-model="rotateToken" type="password" placeholder="新的访问令牌" style="max-width: 320px;" />
<button @click="rotate(rotating)">确认轮换</button>
<button class="ghost" @click="rotating = ''; rotateToken = ''">取消</button>
</div>
<p v-if="rotateError" class="error">{{ rotateError }}</p>
</div>
</div>
</template>
+65
View File
@@ -0,0 +1,65 @@
<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { api } from '../api'
const router = useRouter()
const bootstrapToken = ref('')
const username = ref('')
const password = ref('')
const confirm = ref('')
const busy = ref(false)
const error = ref('')
const status = ref(null)
async function loadStatus() {
try {
status.value = await api.initialization()
} catch (e) {
error.value = e.message
}
}
async function submit() {
error.value = ''
if (password.value !== confirm.value) {
error.value = '两次输入的口令不一致'
return
}
busy.value = true
try {
await api.bootstrap(bootstrapToken.value, username.value, password.value)
router.push('/login')
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
busy.value = false
}
}
onMounted(loadStatus)
</script>
<template>
<div class="card" style="max-width: 460px; margin: 60px auto;">
<h2>首次初始化:创建唯一管理员</h2>
<p v-if="status && status.administratorExists" class="warn">
本实例已存在管理员,引导流程已永久关闭。请直接登录。
</p>
<p v-else-if="status && !status.bootstrapTokenActive" class="warn">
当前没有有效引导令牌。请查看后端启动日志中的「首次初始化引导令牌」。
</p>
<p v-else class="muted">
引导令牌只输出一次且不可找回;创建管理员后令牌立即失效,无法再次创建管理员。
</p>
<form v-if="status && !status.administratorExists" @submit.prevent="submit">
<label><span>引导令牌</span><input v-model="bootstrapToken" required /></label>
<label><span>管理员用户名</span><input v-model="username" autocomplete="username" required /></label>
<label><span>口令</span><input v-model="password" type="password" autocomplete="new-password" required /></label>
<label><span>确认口令</span><input v-model="confirm" type="password" autocomplete="new-password" required /></label>
<button type="submit" :disabled="busy">{{ busy ? '提交中…' : '创建管理员' }}</button>
<p v-if="error" class="error">{{ error }}</p>
</form>
<p style="margin-top: 16px;"><RouterLink to="/login">返回登录</RouterLink></p>
</div>
</template>
+60
View File
@@ -0,0 +1,60 @@
<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { api, setToken } from '../api'
const router = useRouter()
const username = ref('')
const password = ref('')
const busy = ref(false)
const error = ref('')
const status = ref(null)
const statusError = ref('')
async function loadStatus() {
statusError.value = ''
try {
status.value = await api.initialization()
} catch (e) {
statusError.value = e.message
}
}
async function submit() {
error.value = ''
busy.value = true
try {
const result = await api.login(username.value, password.value)
setToken(result.token)
router.push('/overview')
} catch (e) {
// 后端不区分账号不存在与口令错误,此处只展示统一提示与请求号,便于定位。
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
busy.value = false
}
}
onMounted(loadStatus)
</script>
<template>
<div class="card" style="max-width: 420px; margin: 60px auto;">
<h2>登录</h2>
<p v-if="statusError" class="warn">无法读取实例状态:{{ statusError }}</p>
<template v-else-if="status && status.bootstrapRequired">
<p class="warn">本实例尚未创建管理员,需要先使用启动日志中的引导令牌完成初始化。</p>
<RouterLink to="/bootstrap">前往初始化</RouterLink>
</template>
<template v-else-if="status && !status.administratorExists && !status.bootstrapTokenActive">
<p class="warn">实例尚未初始化,且当前没有有效引导令牌。请检查后端启动日志或实例状态。</p>
<p v-if="status.recoveryRequired" class="error">{{ status.recoveryRequired }}</p>
</template>
<form v-else @submit.prevent="submit">
<label><span>用户名</span><input v-model="username" autocomplete="username" required /></label>
<label><span>口令</span><input v-model="password" type="password" autocomplete="current-password" required /></label>
<button type="submit" :disabled="busy">{{ busy ? '登录中…' : '登录' }}</button>
<p v-if="error" class="error">{{ error }}</p>
</form>
</div>
</template>
+145
View File
@@ -0,0 +1,145 @@
<script setup>
import { ref, onMounted } from 'vue'
import { api } from '../api'
const filters = ref({ conversationType: '', conversationId: '', keyword: '', direction: '' })
const page = ref(1)
const pageSize = ref(20)
const data = ref({ items: [], page: 1, pageSize: 20, total: 0 })
const loading = ref(false)
const error = ref('')
const detail = ref(null)
const detailLoading = ref(false)
const detailError = ref('')
const accessUrl = ref('')
const accessError = ref('')
async function load() {
loading.value = true
error.value = ''
try {
const params = { page: page.value, pageSize: pageSize.value }
for (const [key, value] of Object.entries(filters.value)) if (value) params[key] = value
data.value = await api.messages(params)
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
loading.value = false
}
}
async function open(row) {
detail.value = null
detailError.value = ''
accessUrl.value = ''
accessError.value = ''
detailLoading.value = true
try {
detail.value = await api.message(row.messageUid)
} catch (e) {
detailError.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
detailLoading.value = false
}
}
async function openMedia(mediaUid) {
accessUrl.value = ''
accessError.value = ''
try {
const result = await api.mediaAccessUrl(mediaUid)
accessUrl.value = result.url || ''
accessError.value = result.note || ''
} catch (e) {
accessError.value = e.message
}
}
function search() {
page.value = 1
load()
}
function move(delta) {
page.value = Math.max(1, page.value + delta)
load()
}
onMounted(load)
</script>
<template>
<div>
<div class="card">
<h2>消息查询</h2>
<div class="row">
<select v-model="filters.conversationType" style="max-width: 160px;">
<option value="">全部会话类型</option>
<option value="group">群聊</option>
<option value="private">私聊</option>
</select>
<input v-model="filters.conversationId" placeholder="会话 ID" style="max-width: 180px;" />
<select v-model="filters.direction" style="max-width: 160px;">
<option value="">全部方向</option>
<option value="INBOUND">接收</option>
<option value="OUTBOUND">发送</option>
</select>
<input v-model="filters.keyword" placeholder="关键词" style="max-width: 220px;" />
<button :disabled="loading" @click="search">{{ loading ? '查询中…' : '查询' }}</button>
</div>
<p v-if="error" class="error">{{ error }}</p>
<p class="muted">共 {{ data.total }} 条,第 {{ data.page }} 页(每页 {{ data.pageSize }} 条)。</p>
<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 data.items" :key="row.messageUid" @click="open(row)" style="cursor: pointer;">
<td class="muted">{{ row.messageTime }}</td>
<td>{{ row.conversationType }}:{{ row.conversationId }}</td>
<td>{{ row.direction }}</td>
<td>{{ row.senderName || row.senderId || '-' }}</td>
<td>{{ row.summary }}</td>
<td>{{ row.segmentCount }} / {{ row.mediaCount }}</td>
<td>{{ row.normalizedStatus }}</td>
</tr>
<tr v-if="!data.items.length && !loading"><td colspan="7" class="muted">没有符合条件的消息。</td></tr>
</tbody>
</table>
<div class="row" style="margin-top: 12px;">
<button class="ghost" :disabled="loading || page <= 1" @click="move(-1)">上一页</button>
<button class="ghost" :disabled="loading || page * pageSize >= data.total" @click="move(1)">下一页</button>
</div>
</div>
<div v-if="detailLoading" class="card">详情加载中…</div>
<div v-else-if="detailError" class="card"><p class="error">{{ detailError }}</p></div>
<div v-else-if="detail" class="card">
<h2>消息详情 {{ detail.message.messageUid }}</h2>
<p class="muted">
会话 {{ detail.message.conversationType }}:{{ detail.message.conversationId }},
来源事件 {{ detail.rawEventUid || '-' }}({{ detail.rawEventType || '-' }})
</p>
<table>
<thead><tr><th>#</th><th>类型</th><th>状态</th><th>内容</th><th>媒体</th></tr></thead>
<tbody>
<tr v-for="seg in detail.segments" :key="seg.index">
<td>{{ seg.index }}</td>
<td>{{ seg.type }}</td>
<td>{{ seg.status }}</td>
<td>{{ seg.content || '-' }}</td>
<td>
<button v-if="seg.mediaUid" class="ghost" @click="openMedia(seg.mediaUid)">访问对象</button>
<span v-else class="muted">-</span>
</td>
</tr>
</tbody>
</table>
<p v-if="accessUrl" class="ok">临时访问地址:<a :href="accessUrl" target="_blank" rel="noreferrer">{{ accessUrl }}</a></p>
<p v-if="accessError" class="warn">{{ accessError }}</p>
<h2 style="margin-top: 16px;">原始事件</h2>
<pre>{{ detail.rawPayload }}</pre>
</div>
</div>
</template>
+87
View File
@@ -0,0 +1,87 @@
<script setup>
import { ref, onMounted } from 'vue'
import { api } from '../api'
const detail = ref(null)
const error = ref('')
const loading = ref(false)
async function load() {
loading.value = true
error.value = ''
try {
detail.value = await api.healthDetail()
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
loading.value = false
}
}
onMounted(load)
</script>
<template>
<div>
<div class="card">
<div class="row" style="justify-content: space-between;">
<h2 style="margin: 0;">系统总览</h2>
<button class="ghost" :disabled="loading" @click="load">{{ loading ? '刷新中…' : '刷新' }}</button>
</div>
<p v-if="error" class="error">{{ error }}</p>
<p v-else-if="!detail && !loading" class="muted">暂无数据。</p>
</div>
<template v-if="detail">
<div class="card">
<h2>实例与依赖</h2>
<div class="grid">
<div class="stat"><div class="value">{{ detail.instance || '-' }}</div><div class="label">实例标识</div></div>
<div class="stat"><div class="value">{{ detail.napcat?.total ?? '-' }}</div><div class="label">NapCat 绑定数</div></div>
<div class="stat"><div class="value">{{ detail.messages?.totalMessages ?? '-' }}</div><div class="label">已入库消息</div></div>
<div class="stat"><div class="value">{{ detail.messages?.unprocessedEvents ?? '-' }}</div><div class="label">待处理事件</div></div>
</div>
<p class="muted">
事件处理失败 {{ detail.messages?.failedEvents ?? 0 }} 条,未知类型事件 {{ detail.messages?.unknownTypeEvents ?? 0 }} 条。
未知类型不会被丢弃,但也不会被强行归一化为已知消息。
</p>
</div>
<div class="card">
<h2>NapCat 连接状态</h2>
<p class="muted">在线状态以收到 lifecycle 或有效事件为准,握手成功不代表在线。</p>
<table>
<thead>
<tr><th>绑定</th><th>绑定状态</th><th>连接状态</th><th>QQ 账号</th><th>最近事件</th><th>最近错误</th></tr>
</thead>
<tbody>
<tr v-for="item in detail.napcat?.items || []" :key="item.bindingUid">
<td>{{ item.displayName || item.bindingUid }}</td>
<td>{{ item.bindingStatus }}</td>
<td>{{ item.connectionStatus }}</td>
<td>{{ item.qqAccountId || '-' }}</td>
<td>{{ item.lastEventAt || '-' }}</td>
<td>{{ item.lastErrorCode || '-' }}</td>
</tr>
<tr v-if="!(detail.napcat?.items || []).length">
<td colspan="6" class="muted">尚未绑定 NapCat 实例。</td>
</tr>
</tbody>
</table>
</div>
<div class="card">
<h2>媒体与发送</h2>
<div class="grid">
<div class="stat"><div class="value">{{ detail.media?.STORED ?? 0 }}</div><div class="label">媒体已入库</div></div>
<div class="stat"><div class="value">{{ detail.media?.FAILED ?? 0 }}</div><div class="label">媒体下载失败</div></div>
<div class="stat"><div class="value">{{ detail.media?.SOURCE_EXPIRED ?? 0 }}</div><div class="label">媒体源已过期</div></div>
<div class="stat"><div class="value">{{ detail.send?.SUCCEEDED ?? 0 }}</div><div class="label">发送成功</div></div>
<div class="stat"><div class="value">{{ detail.send?.UNKNOWN ?? 0 }}</div><div class="label">发送结果未知</div></div>
<div class="stat"><div class="value">{{ detail.send?.FAILED ?? 0 }}</div><div class="label">发送失败</div></div>
</div>
<p class="warn">「结果未知」表示上游可能已执行但本地未收到确认,不会自动重试,需要人工核实。</p>
</div>
</template>
</div>
</template>
+152
View File
@@ -0,0 +1,152 @@
<script setup>
import { ref, onMounted } from 'vue'
import { api } from '../api'
const bindings = ref([])
const form = ref({ bindingUid: '', targetType: 'group', targetId: '', text: '', reason: '' })
const phase = ref('idle')
const prepared = ref(null)
const operations = ref([])
const summary = ref(null)
const busy = ref(false)
const error = ref('')
const notice = ref('')
function newIdempotencyKey() {
return typeof crypto !== 'undefined' && crypto.randomUUID
? crypto.randomUUID()
: `idem_${Date.now()}_${Math.random().toString(36).slice(2)}`
}
let idempotencyKey = newIdempotencyKey()
async function loadAll() {
error.value = ''
try {
const [list, ops, sum] = await Promise.all([api.bindings(), api.sendOperations(), api.sendSummary()])
bindings.value = list.filter((b) => b.bindingStatus === 'ACTIVE')
operations.value = ops
summary.value = sum
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
}
}
async function prepare() {
error.value = ''
notice.value = ''
busy.value = true
try {
prepared.value = await api.prepareText({ ...form.value }, idempotencyKey)
phase.value = 'prepared'
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
busy.value = false
}
}
async function execute() {
error.value = ''
busy.value = true
try {
const result = await api.executeSend(prepared.value.operationUid, prepared.value.confirmToken)
phase.value = 'done'
if (result.status === 'SUCCEEDED') {
notice.value = `发送成功(操作号 ${result.operationUid})。「上游确认成功」不必然代表接收方已看到消息。`
} else if (result.status === 'UNKNOWN') {
error.value = `结果未知(操作号 ${result.operationUid}):上游可能已执行,系统不会自动重试,请人工核实。`
} else {
error.value = `发送未完成(操作号 ${result.operationUid},状态 ${result.status},错误 ${result.errorCode || '-'})`
}
// 一次操作只允许一次确认执行,之后重新开始,避免重复提交。
idempotencyKey = newIdempotencyKey()
prepared.value = null
await loadAll()
} catch (e) {
error.value = `${e.message}${e.requestId ? `(请求号 ${e.requestId})` : ''}`
} finally {
busy.value = false
}
}
function cancel() {
prepared.value = null
phase.value = 'idle'
idempotencyKey = newIdempotencyKey()
}
onMounted(loadAll)
</script>
<template>
<div>
<div class="card">
<h2>发送文本消息(两阶段确认)</h2>
<p class="muted">第一步只创建发送操作,不产生任何外部副作用;第二步携带确认令牌才真正调用 NapCat。</p>
<template v-if="phase !== 'prepared'">
<label>
<span>NapCat 绑定</span>
<select v-model="form.bindingUid" required>
<option value="" disabled>请选择绑定</option>
<option v-for="b in bindings" :key="b.bindingUid" :value="b.bindingUid">
{{ b.displayName }}({{ b.connectionStatus }})
</option>
</select>
</label>
<div class="row">
<label style="max-width: 160px;">
<span>目标类型</span>
<select v-model="form.targetType">
<option value="group">群</option>
<option value="private">个人</option>
</select>
</label>
<label style="flex: 1;"><span>目标 ID</span><input v-model="form.targetId" required /></label>
</div>
<label><span>消息正文</span><textarea v-model="form.text" rows="4" required></textarea></label>
<label><span>操作原因(写入审计)</span><input v-model="form.reason" /></label>
<button :disabled="busy || !form.bindingUid || !form.targetId || !form.text" @click="prepare">
{{ busy ? '处理中…' : '第一步:创建发送操作' }}
</button>
</template>
<template v-else>
<p class="warn">
即将向 <b>{{ prepared.targetSummary }}</b> 发送消息。确认令牌有效期很短,过期后需要重新创建操作。
</p>
<pre>{{ form.text }}</pre>
<div class="row">
<button :disabled="busy" @click="execute">{{ busy ? '发送中…' : '第二步:确认并发送' }}</button>
<button class="ghost" :disabled="busy" @click="cancel">取消</button>
</div>
</template>
<p v-if="notice" class="ok">{{ notice }}</p>
<p v-if="error" class="error">{{ error }}</p>
</div>
<div class="card">
<h2>发送操作记录</h2>
<p class="muted" v-if="summary">
待发送 {{ summary.PENDING ?? 0 }},发送中 {{ summary.RUNNING ?? 0 }},成功 {{ summary.SUCCEEDED ?? 0 }},
失败 {{ summary.FAILED ?? 0 }},结果未知 {{ summary.UNKNOWN ?? 0 }}
</p>
<table>
<thead>
<tr><th>操作号</th><th>目标</th><th>状态</th><th>尝试</th><th>错误</th><th>创建时间</th><th>完成时间</th></tr>
</thead>
<tbody>
<tr v-for="op in operations" :key="op.operationUid">
<td class="muted">{{ op.operationUid }}</td>
<td>{{ op.targetType }}:{{ op.targetId }}</td>
<td>{{ op.status }}</td>
<td>{{ op.attemptCount }}</td>
<td>{{ op.errorCode || '-' }}</td>
<td class="muted">{{ op.createdAt }}</td>
<td class="muted">{{ op.finishedAt || '-' }}</td>
</tr>
<tr v-if="!operations.length"><td colspan="7" class="muted">暂无发送操作。</td></tr>
</tbody>
</table>
</div>
</div>
</template>
+16
View File
@@ -0,0 +1,16 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// 开发期通过代理访问后端,避免在生产配置里写死后端地址。
export default defineConfig({
plugins: [vue()],
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://127.0.0.1:8080',
changeOrigin: true
}
}
}
})