功能:新增云管API与Web控制台并完成现场接入
This commit is contained in:
1 parent
18a9ce995d
commit
3fb7b4da8c
79 files changed
+17367
-3
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# api: connect the Go backend; mock: browser-only demo, no real operations.
|
||||
VITE_API_MODE=api
|
||||
@@ -1 +0,0 @@
|
||||
# Keep the monorepo directory structure in Git.
|
||||
@@ -0,0 +1,13 @@
|
||||
FROM node:24-alpine AS build
|
||||
WORKDIR /src
|
||||
COPY console/package.json console/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY console/ ./
|
||||
ARG VITE_DEMO_HINT=false
|
||||
ENV VITE_API_MODE=api VITE_DEMO_HINT=$VITE_DEMO_HINT
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
COPY deploy/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /src/dist /usr/share/nginx/html
|
||||
EXPOSE 80
|
||||
@@ -0,0 +1,21 @@
|
||||
# VDI Web 管理控制台
|
||||
|
||||
Vue 3、TypeScript、Vite、Element Plus、Pinia、Vue Router。使用者是管理员,与盒子上的 Qt 桌面选择页分开。
|
||||
|
||||
运行、演示账号和完整能力边界见[开发说明](../docs/cloud-platform-development.md)。
|
||||
|
||||
后台样式已按仓库 `ui/` 设计稿接入,支持深浅主题、桌面卡片与列表、远程会话页和窄屏导航;详见 [UI 接入记录](../docs/cloud-console-ui-20261109.md)。真实现场入口为 `http://127.0.0.1:5182`。
|
||||
|
||||
```text
|
||||
src/api/ 从 OpenAPI 生成的类型与统一 HTTP 适配
|
||||
src/stores/ 会话与平台数据
|
||||
src/router/ 登录与角色路由守卫
|
||||
src/layouts/ 控制台导航与定时刷新
|
||||
src/views/ 第一阶段功能页面
|
||||
src/components/ 共用状态等组件
|
||||
src/styles/ UI 可替换的设计 token
|
||||
src/mocks/ 开发专用 MSW 模拟接口
|
||||
e2e/ Playwright 主路径验收
|
||||
```
|
||||
|
||||
`npm run api:generate` 更新接口契约与类型;API 适配使用 openapi-fetch,页面不直接发网络请求。默认 `npm run dev` 通过 `/api` 代理到本机 `8088` 端口。开发时设 `VITE_API_MODE=mock` 则使用浏览器模拟接口,生产构建不会启用模拟 Worker。
|
||||
@@ -0,0 +1,102 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
async function login(page: Page, username = 'admin') {
|
||||
await page.goto('/login')
|
||||
await page.getByRole('textbox', { name: '用户名', exact: true }).fill(username)
|
||||
await page.getByRole('textbox', { name: '密码', exact: true }).fill('Demo@2026')
|
||||
await page.getByRole('button', { name: '登录', exact: true }).click()
|
||||
await expect(page.getByRole('heading', { name: '运行总览' })).toBeVisible()
|
||||
}
|
||||
test.beforeAll(async ({ request }) => { const r = await request.get('/healthz'); expect(r.ok()).toBe(true); expect((await r.json()).mode).toBe('demo') })
|
||||
test('登录失败、登录恢复与退出', async ({ page }) => {
|
||||
await page.goto('/login')
|
||||
await page.getByRole('textbox', { name: '用户名', exact: true }).fill('admin')
|
||||
await page.getByRole('textbox', { name: '密码', exact: true }).fill('incorrect')
|
||||
await page.getByRole('button', { name: '登录', exact: true }).click()
|
||||
await expect(page.getByText('用户名或密码错误')).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '密码', exact: true }).fill('Demo@2026')
|
||||
await page.getByRole('button', { name: '登录', exact: true }).click()
|
||||
await expect(page.getByRole('heading', { name: '运行总览' })).toBeVisible()
|
||||
await page.reload()
|
||||
await expect(page.getByRole('heading', { name: '运行总览' })).toBeVisible()
|
||||
await page.getByRole('button', { name: '退出登录' }).click()
|
||||
await expect(page).toHaveURL(/\/login/)
|
||||
})
|
||||
test('桌面命令与最终任务结果', async ({ page }) => {
|
||||
await login(page)
|
||||
await page.getByRole('navigation').getByRole('link', { name: '桌面管理' }).click()
|
||||
await page.getByRole('button', { name: '列表视图' }).click()
|
||||
const row = page.getByRole('row').filter({ hasText: '国产办公桌面' })
|
||||
await expect(row).toBeVisible()
|
||||
const currentStopped = await row.getByText('已关机', { exact: true }).count()
|
||||
const action = currentStopped ? '开机' : '关机'
|
||||
await row.getByRole('button', { name: action, exact: true }).click()
|
||||
await page.getByRole('button', { name: '确认提交', exact: true }).click()
|
||||
await expect(page.getByText('任务已提交,请在任务与审计中查看最终结果')).toBeVisible()
|
||||
await page.getByRole('navigation').getByRole('link', { name: '任务与审计' }).click()
|
||||
const task = page.getByRole('row').filter({ hasText: '国产办公桌面' }).first()
|
||||
await expect(task.getByText('成功', { exact: true })).toBeVisible()
|
||||
await expect(task).toContainText('演示计算任务已完成')
|
||||
})
|
||||
test('创建用户、编辑多个桌面授权并持久化', async ({ page }) => {
|
||||
await login(page)
|
||||
await page.getByRole('navigation').getByRole('link', { name: '用户与授权' }).click()
|
||||
await page.getByRole('button', { name: '新建用户', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog')
|
||||
const name = `测试用户 ${Date.now()}`
|
||||
await dialog.getByRole('textbox', { name: /姓名/ }).fill(name)
|
||||
await dialog.getByRole('textbox', { name: /用户账号/ }).fill(`e2e.${Date.now()}`)
|
||||
await dialog.getByRole('button', { name: '创建用户', exact: true }).click()
|
||||
await page.getByRole('textbox', { name: '搜索用户' }).fill(name)
|
||||
await page.getByRole('row').filter({ hasText: name }).getByRole('button', { name: '编辑授权' }).click()
|
||||
await dialog.locator('label.el-checkbox').filter({ hasText: '设计专属桌面' }).click()
|
||||
await expect(dialog.getByRole('checkbox', { name: /设计专属桌面/ })).toBeChecked()
|
||||
await dialog.locator('label.el-checkbox').filter({ hasText: '研发办公桌面' }).click()
|
||||
await dialog.getByRole('button', { name: '保存授权' }).click()
|
||||
const row = page.getByRole('row').filter({ hasText: name })
|
||||
await expect(row).toContainText('设计专属桌面')
|
||||
await expect(row).toContainText('研发办公桌面')
|
||||
await page.reload()
|
||||
await page.getByRole('textbox', { name: '搜索用户' }).fill(name)
|
||||
await expect(page.getByRole('row').filter({ hasText: name })).toContainText('设计专属桌面')
|
||||
})
|
||||
test('登记终端只显示一次激活密钥', async ({ page }) => {
|
||||
await login(page)
|
||||
await page.getByRole('navigation').getByRole('link', { name: '终端管理' }).click()
|
||||
await page.getByRole('button', { name: '登记终端' }).click()
|
||||
const dialog = page.getByRole('dialog')
|
||||
const serial = `E2E-${Date.now()}`
|
||||
await dialog.getByRole('textbox', { name: '设备 SN' }).fill(serial)
|
||||
await dialog.getByRole('textbox', { name: '终端名称' }).fill('联调终端')
|
||||
await dialog.getByRole('button', { name: '登记并生成激活信息' }).click()
|
||||
await expect(page.getByTestId('activation-secret')).toContainText('activate_')
|
||||
await page.getByRole('button', { name: '已保存,关闭' }).click()
|
||||
await page.getByRole('textbox', { name: '搜索终端' }).fill(serial)
|
||||
await expect(page.getByRole('row').filter({ hasText: serial })).toContainText('待激活')
|
||||
})
|
||||
for (const username of ['viewer', 'operator']) test(`${username} 权限边界`, async ({ page }) => {
|
||||
await login(page, username)
|
||||
await page.getByRole('navigation').getByRole('link', { name: '用户与授权' }).click()
|
||||
await expect(page.getByRole('button', { name: '新建用户' })).toHaveCount(0)
|
||||
await expect(page.getByRole('button', { name: '编辑授权' })).toHaveCount(0)
|
||||
await page.goto('/settings')
|
||||
await expect(page.getByText('无访问权限', { exact: true })).toBeVisible()
|
||||
await page.goto('/desktops')
|
||||
await expect(page.getByRole('heading', { name: '桌面管理' })).toBeVisible()
|
||||
await page.getByRole('button', { name: '列表视图' }).click()
|
||||
if (username === 'viewer') await expect(page.getByRole('button', { name: '关机', exact: true })).toHaveCount(0)
|
||||
else await expect(page.getByRole('button', { name: '关机', exact: true }).first()).toBeVisible()
|
||||
})
|
||||
test('空列表、刷新异常及 401 处理', async ({ page }) => {
|
||||
await login(page)
|
||||
await page.getByRole('navigation').getByRole('link', { name: '桌面管理' }).click()
|
||||
await page.getByRole('textbox', { name: '搜索桌面' }).fill('不存在的桌面')
|
||||
await expect(page.getByText('暂无符合条件的桌面')).toBeVisible()
|
||||
await page.route('**/api/v1/overview', route => route.fulfill({ status: 503, json: { code: 'unavailable', message: '测试服务暂不可用', requestId: 'test-offline' } }))
|
||||
await page.getByRole('navigation').getByRole('link', { name: '云桌面总览', exact: true }).click()
|
||||
await page.getByRole('button', { name: '刷新数据' }).click()
|
||||
await expect(page.getByText('数据刷新失败,当前信息可能已过期')).toBeVisible()
|
||||
await page.unroute('**/api/v1/overview')
|
||||
await page.evaluate(() => sessionStorage.setItem('vdi.accessToken', 'invalid-token'))
|
||||
await page.reload()
|
||||
await expect(page).toHaveURL(/\/login/)
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import {test,expect} from '@playwright/test'
|
||||
import {readFileSync,mkdirSync} from 'node:fs'
|
||||
const env=Object.fromEntries(readFileSync('../.local/live/.env','utf8').trim().split(/\r?\n/).map(line=>{ const i=line.indexOf('='); return [line.slice(0,i),line.slice(i+1)] }))
|
||||
function required(key: string) { const value=env[key]; if (!value) throw new Error(`Missing live configuration: ${key}`); return value }
|
||||
test('现场真实资源、设备在线、日志采集与下载',async({page,request})=>{
|
||||
const health=await request.get('/healthz'); expect((await health.json()).mode).toBe('production')
|
||||
await page.goto('/login')
|
||||
await expect(page.getByText(/演示账号/)).toHaveCount(0)
|
||||
await page.getByRole('textbox',{name:'用户名',exact:true}).fill(required('VDI_ADMIN_USERNAME'))
|
||||
await page.getByRole('textbox',{name:'密码',exact:true}).fill(required('VDI_ADMIN_PASSWORD'))
|
||||
await page.getByRole('button',{name:'登录',exact:true}).click()
|
||||
await expect(page.getByRole('heading',{name:'运行总览'})).toBeVisible()
|
||||
await expect(page.getByText('starhe',{exact:true})).toBeVisible()
|
||||
mkdirSync('../.local/live/screenshots',{recursive:true})
|
||||
await page.screenshot({path:'../.local/live/screenshots/overview.png',fullPage:true,animations:'disabled'})
|
||||
await page.getByRole('navigation').getByRole('link',{name:'桌面管理'}).click()
|
||||
await expect(page.getByRole('heading',{name:'桌面管理',exact:true})).toBeVisible()
|
||||
await page.getByRole('button',{name:'列表视图'}).click()
|
||||
for(const name of ['Windows 10','Ubuntu','麒麟']) await expect(page.getByRole('row').filter({hasText:name})).toBeVisible()
|
||||
await page.screenshot({path:'../.local/live/screenshots/desktops.png',fullPage:true,animations:'disabled'})
|
||||
await page.getByRole('navigation').getByRole('link',{name:'终端管理'}).click()
|
||||
const row=page.getByRole('row').filter({hasText:'ee621cae7199a2e9'})
|
||||
await expect(row.getByText('在线',{exact:true})).toBeVisible()
|
||||
await row.getByRole('button',{name:'详情',exact:true}).click()
|
||||
await expect(page.getByText('qt-platform/0.2.0',{exact:true})).toBeVisible()
|
||||
await page.getByRole('button',{name:'收集日志',exact:true}).click()
|
||||
await page.getByRole('button',{name:'确认提交',exact:true}).click()
|
||||
await page.getByRole('dialog',{name:'终端详情'}).locator('button.el-drawer__close-btn').click()
|
||||
await page.getByRole('navigation').getByRole('link',{name:'任务与审计'}).click()
|
||||
const task=page.getByRole('row').filter({hasText:'收集日志'}).first()
|
||||
await expect(task.getByText('成功',{exact:true})).toBeVisible()
|
||||
await task.getByRole('button').click()
|
||||
const download=page.waitForEvent('download')
|
||||
await page.getByRole('button',{name:'下载诊断日志'}).click()
|
||||
const artifact=await download
|
||||
const path='../.local/live/device-diagnostics.json'; await artifact.saveAs(path)
|
||||
const diagnostic=JSON.parse(readFileSync(path,'utf8'))
|
||||
expect(diagnostic.agentVersion).toBe('qt-platform/0.2.0'); expect(diagnostic.bootId).toBeTruthy(); expect(diagnostic.uptimeSeconds).toBeGreaterThan(0)
|
||||
await page.screenshot({path:'../.local/live/screenshots/diagnostics.png',fullPage:true,animations:'disabled'})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
// Browser fixtures exercise UI states without sending commands to PVE or a terminal.
|
||||
async function fixtures(page: Page, role = 'super_admin', state = 'connected') {
|
||||
const now = new Date().toISOString()
|
||||
const desktop = { id: 'ui-desk', name: '界面测试桌面', os: 'Ubuntu', node: 'ui-node', vmid: 9000, pool: '', powerState: 'running', serviceState: 'unknown', provider: 'proxmox', endpoint: 'desktop.example', app: 'Desktop', width: 2560, height: 1440, fps: 45, updatedAt: now }
|
||||
const terminal = { id: 'ui-terminal', sn: 'UI-TEST-DEVICE', name: '界面测试终端', group: '测试组', status: 'online', agentVersion: 'ui-fixture', lastSeen: now, sessionDesktopId: desktop.id, sessionState: state, configVersion: 1, fps: null, rtt: null }
|
||||
const commands: unknown[] = []
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'ui-fixture-token'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), endpoint = new URL(request.url()).pathname.replace('/api/v1', '')
|
||||
if (request.method() === 'POST' && endpoint.endsWith('/commands')) {
|
||||
commands.push(request.postDataJSON())
|
||||
await route.fulfill({ status: 202, json: { id: 'ui-command', kind: 'terminal', action: 'reset-session', targetId: terminal.id, targetName: terminal.name, actor: 'ui-admin', status: 'queued', message: '等待回执', providerRef: '', createdAt: now, updatedAt: now } })
|
||||
return
|
||||
}
|
||||
if (endpoint === '/auth/me') { await route.fulfill({ json: { id: 'ui-admin', username: 'ui-admin', displayName: '界面测试管理员', role } }); return }
|
||||
if (endpoint === '/settings') { await route.fulfill({ json: { mode: 'production', computeProvider: 'proxmox', pveConfigured: true, terminalTransport: 'https-poll', capabilities: [] } }); return }
|
||||
if (endpoint === '/overview') { await route.fulfill({ json: { terminalCount: 1, onlineTerminals: 1, desktopCount: 1, runningDesktops: 1, activeSessions: state === 'connected' ? 1 : 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
const lists: Record<string, unknown[]> = {
|
||||
'/desktops': [desktop], '/terminals': [terminal], '/users': [{ id: 'ui-user', username: 'ui-user', displayName: '测试使用者', enabled: true, terminalId: terminal.id, desktopIds: [desktop.id] }],
|
||||
'/resources': [{ id: 'ui-node', name: 'ui-node', status: 'online', cpu: .2, memory: .4, storage: .3, provider: 'proxmox', updatedAt: now }], '/tasks': [], '/audit-logs': [],
|
||||
}
|
||||
if (endpoint in lists) { const items = lists[endpoint] || []; await route.fulfill({ json: { items, page: 1, pageSize: 100, total: items.length, requestId: 'ui-fixture' } }); return }
|
||||
await route.fulfill({ status: 404, json: { code: 'fixture_not_found', message: '测试接口未定义', requestId: 'ui-fixture' } })
|
||||
})
|
||||
return commands
|
||||
}
|
||||
|
||||
test('远程会话保留缺失指标,取消断开不发命令,确认后使用现有接口', async ({ page }, testInfo) => {
|
||||
const commands = await fixtures(page)
|
||||
await page.setViewportSize({ width: 1440, height: 1000 })
|
||||
await page.goto('/sessions')
|
||||
await expect(page.getByRole('heading', { name: '会话信息', exact: true })).toBeVisible()
|
||||
await expect(page.getByText('桌面正在终端显示')).toBeVisible()
|
||||
await expect(page.getByText('暂无数据', { exact: true })).toHaveCount(2)
|
||||
await expect(page.getByText('尚未采集', { exact: true })).toBeVisible()
|
||||
await page.screenshot({ path: testInfo.outputPath('session-fixture-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click()
|
||||
await page.screenshot({ path: testInfo.outputPath('session-fixture-light.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('button', { name: '断开连接', exact: true }).click()
|
||||
await page.getByRole('button', { name: '取消', exact: true }).click()
|
||||
expect(commands).toHaveLength(0)
|
||||
await page.getByRole('button', { name: '断开连接', exact: true }).click()
|
||||
await page.getByRole('button', { name: '确认提交', exact: true }).click()
|
||||
await expect(page.getByText('断开命令已提交,等待终端回执')).toBeVisible()
|
||||
expect(commands).toEqual([{ action: 'reset-session' }])
|
||||
})
|
||||
|
||||
test('只读角色可查看会话,没有断开按钮与系统设置入口', async ({ page }) => {
|
||||
await fixtures(page, 'viewer')
|
||||
await page.goto('/sessions')
|
||||
await expect(page.getByRole('heading', { name: '会话信息', exact: true })).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: '断开连接', exact: true })).toHaveCount(0)
|
||||
await expect(page.getByRole('navigation', { name: '主导航' }).getByRole('link', { name: '系统设置' })).toHaveCount(0)
|
||||
await page.goto('/settings')
|
||||
await expect(page.getByText('无访问权限', { exact: true })).toBeVisible()
|
||||
})
|
||||
|
||||
test('连接预约不显示为已连接,未上报指标保持为空', async ({ page }) => {
|
||||
await fixtures(page, 'operator', 'connecting')
|
||||
await page.goto('/sessions')
|
||||
await expect(page.getByText('终端正在建立连接')).toBeVisible()
|
||||
await expect(page.getByText('0 个已连接', { exact: true })).toBeVisible()
|
||||
await expect(page.getByText('1 个连接中', { exact: true })).toBeVisible()
|
||||
await expect(page.getByText('暂无数据', { exact: true })).toHaveCount(2)
|
||||
})
|
||||
|
||||
test('深浅主题跨页面和刷新保留,窄屏导航可用', async ({ page }) => {
|
||||
await fixtures(page)
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.goto('/overview')
|
||||
await expect(page.getByRole('heading', { name: '运行总览' })).toBeVisible()
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click()
|
||||
await expect(page.locator('html')).toHaveAttribute('data-theme', 'light')
|
||||
await page.getByRole('button', { name: '打开导航' }).click()
|
||||
await page.getByRole('navigation', { name: '主导航' }).getByRole('link', { name: '桌面管理' }).click()
|
||||
await expect(page.getByRole('heading', { name: '桌面管理', exact: true })).toBeVisible()
|
||||
await expect(page.locator('.sidebar')).not.toHaveClass(/is-open/)
|
||||
await page.reload()
|
||||
await expect(page.locator('html')).toHaveAttribute('data-theme', 'light')
|
||||
await expect(page.locator('.desktop-card')).toHaveCount(1)
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
import js from '@eslint/js'
|
||||
import ts from 'typescript-eslint'
|
||||
import vue from 'eslint-plugin-vue'
|
||||
import globals from 'globals'
|
||||
export default ts.config(
|
||||
{ ignores: ['dist/**', 'public/mockServiceWorker.js', 'playwright-report/**', 'test-results/**', 'src/api/schema.d.ts'] },
|
||||
js.configs.recommended,
|
||||
...ts.configs.recommended,
|
||||
...vue.configs['flat/recommended'],
|
||||
{ languageOptions: { globals: { ...globals.browser, ...globals.node }, parserOptions: { parser: ts.parser } }, rules: { 'vue/multi-word-component-names': 'off', 'vue/max-attributes-per-line': 'off', 'vue/html-self-closing': 'off', 'vue/singleline-html-element-content-newline': 'off', 'vue/html-indent': 'off', 'vue/html-closing-bracket-newline': 'off', 'vue/first-attribute-linebreak': 'off', 'vue/attributes-order': 'off' } },
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>VDI 云桌面管理平台</title></head><body><div id="app"></div><script type="module" src="/src/main.ts"></script></body></html>
|
||||
Generated
+4690
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "vdi-console",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"preview": "vite preview --host 127.0.0.1",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"lint": "eslint .",
|
||||
"test": "vitest run",
|
||||
"test:e2e": "playwright test",
|
||||
"api:generate": "node ../tools/generate-platform-openapi.mjs && openapi-typescript ../docs/openapi/platform.v1.json -o src/api/schema.d.ts",
|
||||
"mock:init": "msw init public --save"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.8",
|
||||
"openapi-fetch": "^0.17.0",
|
||||
"pinia": "^3.0.3",
|
||||
"vue": "^3.5.45",
|
||||
"vue-router": "^4.6.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.0",
|
||||
"@playwright/test": "^1.58.2",
|
||||
"@types/node": "^24.10.0",
|
||||
"@vitejs/plugin-vue": "^6.0.10",
|
||||
"@vue/tsconfig": "^0.8.1",
|
||||
"eslint": "^9.39.0",
|
||||
"eslint-plugin-vue": "^10.5.1",
|
||||
"globals": "^16.5.0",
|
||||
"msw": "^2.12.7",
|
||||
"openapi-typescript": "^7.13.0",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.46.3",
|
||||
"vite": "^7.2.2",
|
||||
"vitest": "^5.1.0",
|
||||
"vue-tsc": "^3.1.4"
|
||||
},
|
||||
"msw": {
|
||||
"workerDirectory": [
|
||||
"public"
|
||||
]
|
||||
},
|
||||
"overrides": {
|
||||
"@typescript-eslint/typescript-estree": {
|
||||
"minimatch": "11.0.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig, devices } from '@playwright/test'
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
testIgnore: '**/live.spec.ts',
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
timeout: 30000,
|
||||
expect: { timeout: 12000 },
|
||||
use: { baseURL: process.env.VDI_E2E_URL || 'http://127.0.0.1:5180', trace: 'retain-on-failure', screenshot: 'only-on-failure' },
|
||||
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'], ...(process.platform === 'win32' ? { channel: 'msedge' } : {}) } }],
|
||||
})
|
||||
@@ -0,0 +1,5 @@
|
||||
import { defineConfig } from '@playwright/test'
|
||||
export default defineConfig({
|
||||
testDir:'./e2e', testMatch:'live.spec.ts', workers:1, timeout:45000,
|
||||
expect:{timeout:15000}, use:{baseURL:'http://127.0.0.1:5182',...(process.platform==='win32'?{channel:'msedge'}:{})},
|
||||
})
|
||||
@@ -0,0 +1,361 @@
|
||||
/* eslint-disable */
|
||||
/* tslint:disable */
|
||||
|
||||
/**
|
||||
* Mock Service Worker.
|
||||
* @see https://github.com/mswjs/msw
|
||||
* - Please do NOT modify this file.
|
||||
*/
|
||||
|
||||
const PACKAGE_VERSION = '2.15.0'
|
||||
const INTEGRITY_CHECKSUM = '03cb67ac84128e63d7cd722a6e5b7f1e'
|
||||
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
||||
const activeClientIds = new Set()
|
||||
|
||||
addEventListener('install', function () {
|
||||
self.skipWaiting()
|
||||
})
|
||||
|
||||
addEventListener('activate', function (event) {
|
||||
event.waitUntil(self.clients.claim())
|
||||
})
|
||||
|
||||
addEventListener('message', async function (event) {
|
||||
const clientId = Reflect.get(event.source || {}, 'id')
|
||||
|
||||
if (!clientId || !self.clients) {
|
||||
return
|
||||
}
|
||||
|
||||
const client = await self.clients.get(clientId)
|
||||
|
||||
if (!client) {
|
||||
return
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
})
|
||||
|
||||
switch (event.data) {
|
||||
case 'KEEPALIVE_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'KEEPALIVE_RESPONSE',
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'INTEGRITY_CHECK_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'INTEGRITY_CHECK_RESPONSE',
|
||||
payload: {
|
||||
packageVersion: PACKAGE_VERSION,
|
||||
checksum: INTEGRITY_CHECKSUM,
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'MOCK_ACTIVATE': {
|
||||
activeClientIds.add(clientId)
|
||||
|
||||
sendToClient(client, {
|
||||
type: 'MOCKING_ENABLED',
|
||||
payload: {
|
||||
client: {
|
||||
id: client.id,
|
||||
frameType: client.frameType,
|
||||
},
|
||||
},
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case 'CLIENT_CLOSED': {
|
||||
activeClientIds.delete(clientId)
|
||||
|
||||
const remainingClients = allClients.filter((client) => {
|
||||
return client.id !== clientId
|
||||
})
|
||||
|
||||
// Unregister itself when there are no more clients
|
||||
if (remainingClients.length === 0) {
|
||||
self.registration.unregister()
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
addEventListener('fetch', function (event) {
|
||||
const requestInterceptedAt = Date.now()
|
||||
|
||||
// Bypass navigation requests.
|
||||
if (event.request.mode === 'navigate') {
|
||||
return
|
||||
}
|
||||
|
||||
// Opening the DevTools triggers the "only-if-cached" request
|
||||
// that cannot be handled by the worker. Bypass such requests.
|
||||
if (
|
||||
event.request.cache === 'only-if-cached' &&
|
||||
event.request.mode !== 'same-origin'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Bypass all requests when there are no active clients.
|
||||
// Prevents the self-unregistered worked from handling requests
|
||||
// after it's been terminated (still remains active until the next reload).
|
||||
if (activeClientIds.size === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const requestId = crypto.randomUUID()
|
||||
event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
|
||||
})
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
* @param {string} requestId
|
||||
* @param {number} requestInterceptedAt
|
||||
*/
|
||||
async function handleRequest(event, requestId, requestInterceptedAt) {
|
||||
const client = await resolveMainClient(event)
|
||||
const requestCloneForEvents = event.request.clone()
|
||||
const response = await getResponse(
|
||||
event,
|
||||
client,
|
||||
requestId,
|
||||
requestInterceptedAt,
|
||||
)
|
||||
|
||||
// Send back the response clone for the "response:*" life-cycle events.
|
||||
// Ensure MSW is active and ready to handle the message, otherwise
|
||||
// this message will pend indefinitely.
|
||||
if (client && activeClientIds.has(client.id)) {
|
||||
const serializedRequest = await serializeRequest(requestCloneForEvents)
|
||||
|
||||
// Omit the body of server-sent event stream responses.
|
||||
// Cloning such responses would prevent client-side stream cancelations
|
||||
// from reaching the original stream (a teed stream only cancels its
|
||||
// source once both of its branches cancel) and would buffer the
|
||||
// entire stream into the unconsumed clone indefinitely.
|
||||
const isEventStreamResponse = response.headers
|
||||
.get('content-type')
|
||||
?.toLowerCase()
|
||||
.startsWith('text/event-stream')
|
||||
|
||||
// Clone the response so both the client and the library could consume it.
|
||||
const responseClone = isEventStreamResponse ? null : response.clone()
|
||||
|
||||
sendToClient(
|
||||
client,
|
||||
{
|
||||
type: 'RESPONSE',
|
||||
payload: {
|
||||
isMockedResponse: IS_MOCKED_RESPONSE in response,
|
||||
request: {
|
||||
id: requestId,
|
||||
...serializedRequest,
|
||||
},
|
||||
response: {
|
||||
type: response.type,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: Object.fromEntries(response.headers.entries()),
|
||||
body: responseClone ? responseClone.body : null,
|
||||
},
|
||||
},
|
||||
},
|
||||
responseClone && responseClone.body
|
||||
? [serializedRequest.body, responseClone.body]
|
||||
: [],
|
||||
)
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the main client for the given event.
|
||||
* Client that issues a request doesn't necessarily equal the client
|
||||
* that registered the worker. It's with the latter the worker should
|
||||
* communicate with during the response resolving phase.
|
||||
* @param {FetchEvent} event
|
||||
* @returns {Promise<Client | undefined>}
|
||||
*/
|
||||
async function resolveMainClient(event) {
|
||||
const client = await self.clients.get(event.clientId)
|
||||
|
||||
if (activeClientIds.has(event.clientId)) {
|
||||
return client
|
||||
}
|
||||
|
||||
if (client?.frameType === 'top-level') {
|
||||
return client
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
})
|
||||
|
||||
return allClients
|
||||
.filter((client) => {
|
||||
// Get only those clients that are currently visible.
|
||||
return client.visibilityState === 'visible'
|
||||
})
|
||||
.find((client) => {
|
||||
// Find the client ID that's recorded in the
|
||||
// set of clients that have registered the worker.
|
||||
return activeClientIds.has(client.id)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
* @param {Client | undefined} client
|
||||
* @param {string} requestId
|
||||
* @param {number} requestInterceptedAt
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
async function getResponse(event, client, requestId, requestInterceptedAt) {
|
||||
// Clone the request because it might've been already used
|
||||
// (i.e. its body has been read and sent to the client).
|
||||
const requestClone = event.request.clone()
|
||||
|
||||
function passthrough() {
|
||||
// Cast the request headers to a new Headers instance
|
||||
// so the headers can be manipulated with.
|
||||
const headers = new Headers(requestClone.headers)
|
||||
|
||||
// Remove the "accept" header value that marked this request as passthrough.
|
||||
// This prevents request alteration and also keeps it compliant with the
|
||||
// user-defined CORS policies.
|
||||
const acceptHeader = headers.get('accept')
|
||||
if (acceptHeader) {
|
||||
const values = acceptHeader.split(',').map((value) => value.trim())
|
||||
const filteredValues = values.filter(
|
||||
(value) => value !== 'msw/passthrough',
|
||||
)
|
||||
|
||||
if (filteredValues.length > 0) {
|
||||
headers.set('accept', filteredValues.join(', '))
|
||||
} else {
|
||||
headers.delete('accept')
|
||||
}
|
||||
}
|
||||
|
||||
return fetch(requestClone, { headers })
|
||||
}
|
||||
|
||||
// Bypass mocking when the client is not active.
|
||||
if (!client) {
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
// Bypass initial page load requests (i.e. static assets).
|
||||
// The absence of the immediate/parent client in the map of the active clients
|
||||
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
|
||||
// and is not ready to handle requests.
|
||||
if (!activeClientIds.has(client.id)) {
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
// Notify the client that a request has been intercepted.
|
||||
const serializedRequest = await serializeRequest(event.request)
|
||||
const clientMessage = await sendToClient(
|
||||
client,
|
||||
{
|
||||
type: 'REQUEST',
|
||||
payload: {
|
||||
id: requestId,
|
||||
interceptedAt: requestInterceptedAt,
|
||||
...serializedRequest,
|
||||
},
|
||||
},
|
||||
[serializedRequest.body],
|
||||
)
|
||||
|
||||
switch (clientMessage.type) {
|
||||
case 'MOCK_RESPONSE': {
|
||||
return respondWithMock(clientMessage.data)
|
||||
}
|
||||
|
||||
case 'PASSTHROUGH': {
|
||||
return passthrough()
|
||||
}
|
||||
}
|
||||
|
||||
return passthrough()
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Client} client
|
||||
* @param {any} message
|
||||
* @param {Array<Transferable>} transferrables
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
function sendToClient(client, message, transferrables = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const channel = new MessageChannel()
|
||||
|
||||
channel.port1.onmessage = (event) => {
|
||||
if (event.data && event.data.error) {
|
||||
return reject(event.data.error)
|
||||
}
|
||||
|
||||
resolve(event.data)
|
||||
}
|
||||
|
||||
client.postMessage(message, [
|
||||
channel.port2,
|
||||
...transferrables.filter(Boolean),
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Response} response
|
||||
* @returns {Response}
|
||||
*/
|
||||
function respondWithMock(response) {
|
||||
// Setting response status code to 0 is a no-op.
|
||||
// However, when responding with a "Response.error()", the produced Response
|
||||
// instance will have status code set to 0. Since it's not possible to create
|
||||
// a Response instance with status code 0, handle that use-case separately.
|
||||
if (response.status === 0) {
|
||||
return Response.error()
|
||||
}
|
||||
|
||||
const mockedResponse = new Response(response.body, response)
|
||||
|
||||
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
|
||||
value: true,
|
||||
enumerable: true,
|
||||
})
|
||||
|
||||
return mockedResponse
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Request} request
|
||||
*/
|
||||
async function serializeRequest(request) {
|
||||
return {
|
||||
url: request.url,
|
||||
mode: request.mode,
|
||||
method: request.method,
|
||||
headers: Object.fromEntries(request.headers.entries()),
|
||||
cache: request.cache,
|
||||
credentials: request.credentials,
|
||||
destination: request.destination,
|
||||
integrity: request.integrity,
|
||||
redirect: request.redirect,
|
||||
referrer: request.referrer,
|
||||
referrerPolicy: request.referrerPolicy,
|
||||
body: await request.arrayBuffer(),
|
||||
keepalive: request.keepalive,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<template><router-view /></template>
|
||||
@@ -0,0 +1,74 @@
|
||||
import createClient from 'openapi-fetch'
|
||||
import type { paths, components } from './schema'
|
||||
|
||||
export type Admin = components['schemas']['Administrator']
|
||||
export type Desktop = components['schemas']['Desktop']
|
||||
export type Terminal = components['schemas']['Terminal']
|
||||
export type User = components['schemas']['User']
|
||||
export type Resource = components['schemas']['Resource']
|
||||
export type Task = components['schemas']['Task']
|
||||
export type Audit = components['schemas']['Audit']
|
||||
export type Overview = components['schemas']['Overview']
|
||||
export type Settings = components['schemas']['Settings']
|
||||
export type BindingInput = components['schemas']['BindingInput']
|
||||
export type ImportInput = components['schemas']['ImportInput']
|
||||
export type EnrollmentInput = components['schemas']['EnrollmentInput']
|
||||
export type DiscoveredVM = components['schemas']['DiscoveredVM']
|
||||
export type DesktopAction = components['schemas']['DesktopAction']['action']
|
||||
export type TerminalAction = components['schemas']['TerminalAction']['action']
|
||||
let accessToken = ''
|
||||
export function setAccessToken(value: string) { accessToken = value }
|
||||
export class ApiError extends Error {
|
||||
constructor(message: string, public status = 0, public code = 'network_error', public requestId = '') { super(message) }
|
||||
}
|
||||
const client = createClient<paths>({ baseUrl: '/api/v1', fetch: async request => {
|
||||
const timeout = AbortSignal.timeout(15000)
|
||||
try { return await fetch(new Request(request, { signal: AbortSignal.any([request.signal, timeout]) })) }
|
||||
catch { throw new ApiError('连接服务失败或请求超时,请检查网络后重试') }
|
||||
} })
|
||||
client.use({
|
||||
onRequest({ request }) { if (accessToken) request.headers.set('Authorization', `Bearer ${accessToken}`) },
|
||||
onResponse({ request, response }) { if (response.status === 401 && !request.url.endsWith('/auth/login')) window.dispatchEvent(new Event('vdi:unauthorized')) },
|
||||
})
|
||||
type Result<T> = { data?: T; error?: components['schemas']['Error']; response: Response }
|
||||
async function result<T>(promise: Promise<Result<T>>): Promise<T> {
|
||||
const r = await promise
|
||||
if (r.error) throw new ApiError(r.error.message, r.response.status, r.error.code, r.error.requestId)
|
||||
if (!r.response.ok) throw new ApiError(`请求失败(${r.response.status})`, r.response.status)
|
||||
return r.data as T
|
||||
}
|
||||
const commandHeaders = () => ({ 'Idempotency-Key': crypto.randomUUID() })
|
||||
const query = { page: 1, pageSize: 100 }
|
||||
export const api = {
|
||||
login: (username: string, password: string) => result(client.POST('/auth/login', { body: { username, password } })),
|
||||
me: () => result(client.GET('/auth/me')),
|
||||
logout: () => result(client.POST('/auth/logout')),
|
||||
overview: () => result(client.GET('/overview')),
|
||||
settings: () => result(client.GET('/settings')),
|
||||
resources: () => result(client.GET('/resources', { params: { query } })),
|
||||
desktops: (page = 1) => result(client.GET('/desktops', { params: { query: { ...query, page } } })),
|
||||
terminals: (page = 1) => result(client.GET('/terminals', { params: { query: { ...query, page } } })),
|
||||
users: (page = 1) => result(client.GET('/users', { params: { query: { ...query, page } } })),
|
||||
tasks: (page = 1) => result(client.GET('/tasks', { params: { query: { ...query, page } } })),
|
||||
taskDiagnostics: (id: string) => result(client.GET('/tasks/{id}/diagnostics', { params: { path: { id } } })),
|
||||
audits: (page = 1) => result(client.GET('/audit-logs', { params: { query: { ...query, page } } })),
|
||||
discoverVMs: () => result(client.GET('/resources/vms', { params: { query } })),
|
||||
sync: () => result(client.POST('/resources/sync', { params: { header: commandHeaders() } })),
|
||||
importDesktop: (body: ImportInput) => result(client.POST('/desktops/import', { body })),
|
||||
desktopAction: (id: string, action: DesktopAction) => result(client.POST('/desktops/{id}/actions', { params: { path: { id }, header: commandHeaders() }, body: { action } })),
|
||||
enroll: (body: EnrollmentInput) => result(client.POST('/terminals', { body })),
|
||||
terminalCommand: (id: string, action: TerminalAction) => result(client.POST('/terminals/{id}/commands', { params: { path: { id }, header: commandHeaders() }, body: { action } })),
|
||||
createUser: (body: { username: string; displayName: string }) => result(client.POST('/users', { body })),
|
||||
updateBindings: (id: string, body: BindingInput) => result(client.PUT('/users/{id}/bindings', { params: { path: { id } }, body })),
|
||||
}
|
||||
export async function allPages<T>(loader: (page: number) => Promise<{ items: T[]; total: number }>): Promise<T[]> {
|
||||
const first = await loader(1)
|
||||
const items = [...first.items]
|
||||
for (let page = 2; items.length < first.total && first.items.length > 0; page++) {
|
||||
const next = await loader(page)
|
||||
if (!next.items.length) break
|
||||
items.push(...next.items)
|
||||
}
|
||||
return items
|
||||
}
|
||||
export const errorMessage = (e: unknown) => e instanceof ApiError ? `${e.message}${e.requestId ? `(请求 ${e.requestId})` : ''}` : e instanceof Error ? e.message : '操作失败,请重试'
|
||||
Vendored
+3732
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="180 100 680 576" role="img" aria-label="百工万象"><defs><filter id="brand" color-interpolation-filters="sRGB" x="0" y="0" width="100%" height="100%"><feColorMatrix type="matrix" values="0 0 0 0 0.74117647 0 0 0 0 0.44313725 0 0 0 0 0.23137255 1.4 0 -1.4 0 0"/></filter></defs><image width="2048" height="768" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACAAAAAMACAIAAAA/whCdAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAIAKADAAQAAAABAAADAAAAAADSIaOvAABAAElEQVR4AcydjXIsOY6rtyPu+79xn7mQKH0JkZIqyz6zsZ4YF0QCIKTMSpfd8/PPn//853/01b8H+p/+0or6+qf/K+A/wdLiP6L/888/vdw4SFpj9/WQRUfYmPADTM9mOr7+I85knfw959T1lDauj222027keDw7Il4DczsPxxLHIOc7jRgiUBdwPpzIGgcpts4oWnPfrJ5jQYt5VBZGOJ4zYyLKck1Tg+V6P1BerpGq5IYfsUZ9mcWBtAz9buq2vo8m80uBhGvaZ84L2/QkiLMcbjpZN8JnuYe5QdrN07zGl/B0bWfVNPlLCagu2Rbtcw90l9abxtmwn0fbV9j6tdakJ4Ph5Vqs95vJNXAmlfYZ7/XnrPrOB7/vcMRR3AdZ9mnNgT1Hx1i002PoU35ztUeHBszM2pRfx+dMpORcO2lY2Vl1yjByH792zWXOalMD9zFPmThe6qeQj2ISyLzOiozzDDwqISzONJs7W+7XUTR6q9jc57m07nEI4wW+azWXfanOCEDSukni4yPwvHmaZ3i0749cBzLrz5WYxGElJefQSkwI3tS3VbQ8te3MD9/22JLhH5b9+7xmo/RknmOC1Qe0uQ2YDyECRCv68ygiec88go9ZaLXukmi7v2l9L9zN3WmbZ6G7/+l8mlXfZfaMDKqOeL3fvll+gzFrijybn78f+yrWmHFW7WX6OGfWehAGrPvqPdtPW88LsuxkbMry2Ch23Ec+l71HxA6gGcTp21jeqox9OG1/7V/x9eBxAGP7D1+PdvnOeeKPs/K5tIfr84JrLz3bfOYGVzxFknX7Po5AGRD43Me93w5EBYiAMPBwNGWr2+UzrUt7pKZqBt5w7O+jxp1f4vhc8Dz7xuvbnZ3Yfpc/59POf/2yNbEBvdnUYeo5fZZlnpc2hph5uxyt2L6tPs2fL0Z3/tyLSdo52DWdwj7XfGLY7D6v/TE+bInR7ofp+VD7UOoCC9+uxpNSO5t6AbSqOZ6U/roqRivNYjPzHutTxrlpegvGNTCtHVs/eMKteWa2J8qIAb9tRrXYqO2cE4mtDFl+4WhbVGs69sbM0w6NCYAwgKOlY6c5trELdK1j1zoeRzBDtOkdLxw2vIxabnvv+Fzq7XDsgjjHsXM8Az4CzufMg+wtlwSOfTwpHrR4aoGWDBd/OKgGeGyWG6Xbj94a+NlNdxgci6myOK2e9nLKMJ5SYce+msF4u7WX9m6bswTWeV36fIuIgz3vlmFnPuM2GrqRudOejmf2mYQRX/ihGUkBOCy/Xh7/EY7jGqn7XtnBw3pQ4o9d9BcjPQFWfqJzCZjbT1znUDM0d7ZPuxm+mIu/B+j4ET9oJZ204pPHFcnH9vLkf/YXd9s8r6R1W8fMBXg34VeeTmqJuR+ee0yUWfU7rP9KNfN35WT1g4sw6nPJGnfero61F0/BLiTEnmIAtv+RQ4DHiu2kPMS2c+iUKe03YgrQlx6fgUEc33V7c7Yqkb+1p32Dz/k899hCNk7XDnE7h3nQeru01vzS4QZs1bnHlnJilZ+57d5uvCH5xGl9BruPVX1uNx7mPldSH+p5JOHoPih76GdffXBspH8f59DwPJMG52aFH20j6atJQkYG1y54nlXjFyN8BOLr2UuLM7L1eQM32vRscHJCvv3e6cPYXB7/RSWik6z3jF05T4S1/lyjebFk/M+/f/6MLGadYCfEH156lqYblDhDjiYJY6nunDgyVH74HXY6XPvG7EYmhPrk6RN2/s+90ezaFuY2KnsMHC9vsi2Kbri7uxYWi8F8rtvs9CtMOvXnJW8Kqz+Poakc5zHOM31WmqR57bReDv5Un7rx2q/pFLYR42u7+zh9Y0328rrsyzrz6j5DRpP7qq1jm70ThzOPSyUcert8k8+TjZ0EbUr7mQ9luxaCvXXcmnwGQSCeDMl6+wgq4cJn3h7DAifLEMreoV3cVIhmF2q1HLpas/4oG99uvg2jcyW8jm2kldPpWdOvRZ/YXXffIvKWsw6YYttTu1z9LPNcv6ZTp9d2E633RgjDcpj0l3jfmFTQ7snm1f+1Mk6r4cbbHN6yQ88CY95WVftQvkdtw/aOcoO/NmgcZ/eOA/YxK+b5Hef6HPX+TFZx7GSOIH/cGLsL+chFhhAA+UN6UKest0E0p1Yr3/ajvKKI3oX97jxcGTyMTy2DeRzzOl/3JbHNTO8p5ZpmnNVzgfZz8yE0j1Yb9cenv4m2b+HJ7QMIQJTe7sKRoH0uYezk53S7dXsj+2Nhx8k1BrWGf6CdxOcpExXbMZR+IJvGJIzXZZb3nse4V9vB7LZ/el71FJsZ7RFafQ73Z1wI+G1Tu7cJOWPX9brHQNLsM7SbtSbr3ruhOdu4TRgyQiXH3BZrhBbqTbvERn4+Hg/f8hL3Wy83nWmdumzReaetN6vYqtsYHjfA7oiMtcB8z2yz2sfXsZl0lO1+jLfmVr9MjEU/orkZ33xzGvxAdhE2PsdSBJlWz9Co+OSdRe8Pi+3lWC5ectiewbu5ixM+0k68vt5SLFaxkHgeyLjT5zlAjhus+qYbzwmOneYY/wYOAsq23UbHZxxhq7Uv+A0/J9R777/ZCcTZzhNqA8ImBhEDb9WfYkceCVp8fn2W03ZWhuixsobdh80mS8Vc3+ztLfNsYBh9+z6KI9nMmsE2r/O+ZGTiRKjEahzbVeP4kU6LqPsxbnwmOV7nOTRibCfqHaM+XS7+arEe5bpaB9ZVN1+vTiV5RZmfZ50ylnHpuji/neL0Wnblj+5JWF/bdV7m0u6NscK9XaIPP/olaXlMEiY5/84nwj/vhd05xP3cpvBY7AOinoox+s335dzaFrhPhjpnM1M/KhMmSxMYtKtu1ba7zRmKsZyrvV9aXMv8avYcqMzwfS+z314heDGwbflpWs4G+2nmI+3CbNyuo9236730pPN6WGxjcI/oxuj3pOV6wg7UzqHBZ8qkPFcp6+eNrtDbPU6HZhvcfU7jPTAOLI8cp7neCo/oPYq3zLTjqFaDU4bNKTVhO4Un8P5MYu7+rWr3MG+Aej0iIgcay0ga+PTdD587L/JW+bMPbandk3KtLBsVTZONnuq12HthOW8is5qwn1Ww9A8A/v233UbqdbsOwnhki4X6foxptjj28yLmRPA58/K6I44L2ZIyf7Eo1VFoQno75+HiHC5aXAquiT3CmspoROmn+IwRwlgc7gykAhQxecBy0fY380PeoRgUMU6DRphTe7V97oy1/qxGzOcQnlacWe80Vo81Lqg9jp3vuAccx8kBxiWa5zS6bcJyd7rNwLHdJkA8wWTMV7danz2DkV6eu3Q5U23Y796O3Tq5fLd053EFpoFfsiWQ3ZDi2pFO5TjFcikTVctJ6a9z8djEVbK1vysooyvdZ3fzCn88OCRsuZ2/X+JYtMNi8OYdihytPGz66NNlNwC1MFEx8IXfhSPUmhjLboKFtsovFA8lHj096bO/VuRkCBMiD6kK9kkyyFMTr5+/b09typglwAVpqe2gF86sB/nZUblzYkKyiqK/L1TBv4/1Iwv6890PylUPQ2g959lyaavFZX7yOw+H3p477pKZ7jh9+vSH27iX+rjyTmzMsPOzE+7FNdmsTndbd3H/NprkneT56pnzcRROC+FOjuf1m4cxxeMdVi5B/yDwkOfxPqeTZuE3D0iF2KGZ9BDGDLjEnoPGLdHFcd82sp9Z8dkWODQ/STGpc++NUXESETrupekbNUmXB3jsyY6aQQGeQeHc3B720m27GzuU1lvlzleWchYcne1OJuSJffhybHluLAhDbW6tPpfPtRh2vbMo54LXqaUgkGeO3nJ/OV+7Hac29z2o/STahO2Xj2kU/zcCP+lRXO7UbuJOKAH5nCPOXYN4BfMC9e3iINA99Y3aqlufyc4yQdrqnNXNnSb5XD6cdV6yWpu2Wq++fOvFihFt4HxnbMzH9uNkmz/BNmSbPyC6ua9KUWUbrzPXIc1tuUeSm7IhEOjUoZlbPM5C2GeQO01oS5gcRZJAgOxMigLja+7pNrVTxymyGbsc6qcpYb6EUcm0jcAZBdu+a9aHPHOej5BBWg7LdVC70WMz641q8xuMCXvDRO13UZOU1DPmE+yZXkz60G7TWw9zzVk9RR85J/Ok7cbtm+8LQ7pHoKuyvpvwSSYceb/mj0b8dmXnXXcctDa6fl61Jt8cdShEqlchQpJQgNhbvqw0kTvQ+WuudcUuUa79tCIPYR4CVrOkjyB1X9Gscg4/CG/zz1n+KnNyAp67C6oH9u2vV8qj4oaHgBO8vsUpW9KmpRx8YsM98/g2/nlJi2732cSd9GzLjNqD3h5rMdT6LbiWNUyqawL+An1g00qY3Fo1vmajkWcG9+mDGzVdr7HBKe+Mofdaq8eXma7bnYT1NW92vQfEzYQu349u4Z8vjqiZtH+3b4/QDq6N8LmhdK/HdYPGiY233BirQLine truncated
|
||||
|
After Width: | Height: | Size: 1.2 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1 @@
|
||||
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Ubuntu</title><path d="M17.61.455a3.41 3.41 0 0 0-3.41 3.41 3.41 3.41 0 0 0 3.41 3.41 3.41 3.41 0 0 0 3.41-3.41 3.41 3.41 0 0 0-3.41-3.41zM12.92.8C8.923.777 5.137 2.941 3.148 6.451a4.5 4.5 0 0 1 .26-.007 4.92 4.92 0 0 1 2.585.737A8.316 8.316 0 0 1 12.688 3.6 4.944 4.944 0 0 1 13.723.834 11.008 11.008 0 0 0 12.92.8zm9.226 4.994a4.915 4.915 0 0 1-1.918 2.246 8.36 8.36 0 0 1-.273 8.303 4.89 4.89 0 0 1 1.632 2.54 11.156 11.156 0 0 0 .559-13.089zM3.41 7.932A3.41 3.41 0 0 0 0 11.342a3.41 3.41 0 0 0 3.41 3.409 3.41 3.41 0 0 0 3.41-3.41 3.41 3.41 0 0 0-3.41-3.41zm2.027 7.866a4.908 4.908 0 0 1-2.915.358 11.1 11.1 0 0 0 7.991 6.698 11.234 11.234 0 0 0 2.422.249 4.879 4.879 0 0 1-.999-2.85 8.484 8.484 0 0 1-.836-.136 8.304 8.304 0 0 1-5.663-4.32zm11.405.928a3.41 3.41 0 0 0-3.41 3.41 3.41 3.41 0 0 0 3.41 3.41 3.41 3.41 0 0 0 3.41-3.41 3.41 3.41 0 0 0-3.41-3.41z"/></svg>
|
||||
|
After Width: | Height: | Size: 948 B |
@@ -0,0 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
const props = defineProps<{ value: string }>()
|
||||
const labels: Record<string, string> = { running: '运行中', stopped: '已关机', online: '在线', offline: '离线', unregistered: '待激活', unknown: '未检测', ready: '已就绪', queued: '排队中', success: '成功', failed: '失败', timeout: '结果未确认', submitted: '已提交', denied: '无权限', demo: '演示', proxmox: 'Proxmox', enabled: '启用', disabled: '停用' }
|
||||
const type = computed(() => ['online', 'success', 'ready', 'enabled', 'running', 'connected'].includes(props.value) ? 'success' : ['failed', 'denied'].includes(props.value) ? 'danger' : ['queued', 'timeout', 'unregistered', '执行中', 'connecting'].includes(props.value) ? 'warning' : 'info')
|
||||
</script>
|
||||
<template><el-tag :type="type" effect="light" size="small">{{ labels[value] || value }}</el-tag></template>
|
||||
@@ -0,0 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import ubuntu from '../assets/ubuntu.svg'
|
||||
import kylin from '../assets/kylinsoft.png'
|
||||
defineProps<{ os: string }>()
|
||||
</script>
|
||||
<template>
|
||||
<img v-if="os === 'Ubuntu'" :src="ubuntu" alt="Ubuntu" class="system-logo" />
|
||||
<img v-else-if="os === '麒麟'" :src="kylin" alt="麒麟" class="system-logo" />
|
||||
<span v-else class="windows-mark" role="img" aria-label="Windows"><i /><i /><i /><i /></span>
|
||||
</template>
|
||||
<style scoped>
|
||||
.system-logo{width:28px;height:28px;object-fit:contain}.windows-mark{display:grid;grid-template-columns:repeat(2,11px);gap:3px;transform:perspective(80px) rotateY(-9deg);width:25px;height:25px}.windows-mark i{display:block;background:currentColor}
|
||||
</style>
|
||||
@@ -0,0 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import { Moon, Sunny } from '@element-plus/icons-vue'
|
||||
import { useTheme } from '../composables/useTheme'
|
||||
const { dark, toggle } = useTheme()
|
||||
</script>
|
||||
<template>
|
||||
<el-button class="theme-toggle" :aria-label="dark ? '切换浅色主题' : '切换深色主题'" :title="dark ? '切换浅色主题' : '切换深色主题'" @click="toggle"><el-icon :size="18"><Sunny v-if="dark" /><Moon v-else /></el-icon></el-button>
|
||||
</template>
|
||||
@@ -0,0 +1,20 @@
|
||||
import { ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { errorMessage } from '../api'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
|
||||
export function useAction() {
|
||||
const busy = ref(false)
|
||||
async function run(work: () => Promise<unknown>, message = '操作已完成') {
|
||||
if (busy.value) return false
|
||||
busy.value = true
|
||||
try { await work(); ElMessage.success(message); await usePlatform().refresh(); return true }
|
||||
catch (e) { ElMessage.error(errorMessage(e)); return false }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
async function confirm(title: string, message: string) {
|
||||
try { await ElMessageBox.confirm(message, title, { type: 'warning', confirmButtonText: '确认提交', cancelButtonText: '取消' }); return true }
|
||||
catch { return false }
|
||||
}
|
||||
return { busy, run, confirm }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
const key = 'vdi.theme'
|
||||
const saved = (() => { try { return localStorage.getItem(key) } catch { return null } })()
|
||||
const theme = ref<'dark' | 'light'>(saved === 'light' ? 'light' : 'dark')
|
||||
function apply() {
|
||||
document.documentElement.dataset.theme = theme.value
|
||||
document.documentElement.style.colorScheme = theme.value
|
||||
}
|
||||
apply()
|
||||
export function useTheme() {
|
||||
const dark = computed(() => theme.value === 'dark')
|
||||
function toggle() {
|
||||
theme.value = dark.value ? 'light' : 'dark'
|
||||
apply()
|
||||
try { localStorage.setItem(key, theme.value) } catch { /* The theme still works without browser storage. */ }
|
||||
}
|
||||
return { theme, dark, toggle }
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { Monitor, Menu, Cpu, User, List, Setting, DataAnalysis, Connection, ArrowRight, SwitchButton, Close, Refresh } from '@element-plus/icons-vue'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import ThemeToggle from '../components/ThemeToggle.vue'
|
||||
import brandMark from '../assets/brand-mark.svg'
|
||||
const auth = useAuth(), data = usePlatform(), route = useRoute(), router = useRouter()
|
||||
const items = [
|
||||
{ path: '/overview', title: '云桌面总览', icon: DataAnalysis, group: 'work' },
|
||||
{ path: '/desktops', title: '桌面管理', icon: Monitor, group: 'work' },
|
||||
{ path: '/sessions', title: '远程会话', icon: Connection, group: 'work' },
|
||||
{ path: '/terminals', title: '终端管理', icon: Menu, group: 'work' },
|
||||
{ path: '/resources', title: '计算资源', icon: Cpu, group: 'manage' },
|
||||
{ path: '/users', title: '用户与授权', icon: User, group: 'manage' },
|
||||
{ path: '/tasks', title: '任务与审计', icon: List, group: 'manage' },
|
||||
{ path: '/settings', title: '系统设置', icon: Setting, group: 'manage' },
|
||||
]
|
||||
const roles: Record<string, string> = { super_admin: '超级管理员', operator: '运维人员', viewer: '只读人员' }
|
||||
const pending = computed(() => data.tasks.filter(t => t.status === 'queued' || t.status === 'running').length)
|
||||
const avatar = computed(() => (auth.user?.displayName || auth.user?.username || '管').slice(0, 1))
|
||||
const mockMode = import.meta.env.VITE_API_MODE === 'mock'
|
||||
const navOpen = ref(false)
|
||||
watch(() => route.path, () => { navOpen.value = false })
|
||||
let timer: ReturnType<typeof setInterval>
|
||||
onMounted(() => { void data.refresh(); timer = setInterval(() => { if (!document.hidden) void data.refresh() }, 5000) })
|
||||
onUnmounted(() => clearInterval(timer))
|
||||
async function logout() { try { await auth.logout() } catch { /* Local session is cleared even if the network is unavailable. */ } data.clear(); await router.replace('/login') }
|
||||
</script>
|
||||
<template>
|
||||
<div class="console-shell">
|
||||
<button v-if="navOpen" class="nav-scrim" aria-label="关闭导航遮罩" @click="navOpen = false" />
|
||||
<aside id="console-navigation" class="sidebar" :class="{ 'is-open': navOpen }">
|
||||
<div class="brand-row"><router-link to="/overview" class="brand"><img :src="brandMark" alt="" /><span>百工万象<small>VDI CLOUD</small></span></router-link><el-button class="mobile-close" text aria-label="关闭导航" @click="navOpen = false"><el-icon><Close /></el-icon></el-button></div>
|
||||
<div class="organization"><small>云桌面管理平台</small><strong>VDI Cloud · 管理控制台</strong><span><i :class="{ connected: data.settings?.pveConfigured }" />{{ data.settings?.pveConfigured ? 'Proxmox 已接入' : '等待接入计算资源' }}</span></div>
|
||||
<nav aria-label="主导航"><template v-for="group in [{ id: 'work', label: '云桌面工作台' }, { id: 'manage', label: '资源与管理' }]" :key="group.id"><div class="nav-label">{{ group.label }}</div><router-link v-for="item in items.filter(i => i.group === group.id && (i.path !== '/settings' || auth.canAdmin))" :key="item.path" :to="item.path" :class="{ active: route.path === item.path }" :aria-current="route.path === item.path ? 'page' : undefined"><el-icon :size="18"><component :is="item.icon" /></el-icon><span>{{ item.title }}</span><span v-if="item.path === '/tasks' && pending" class="nav-count">{{ pending }}</span></router-link></template></nav>
|
||||
<div class="sidebar-bottom"><div class="profile"><div class="avatar">{{ avatar }}</div><div class="profile-name"><strong>{{ auth.user?.displayName }}</strong><small>{{ roles[auth.user?.role || ''] }}</small></div><el-button text aria-label="退出登录" title="退出登录" @click="logout"><el-icon :size="18"><SwitchButton /></el-icon></el-button></div><div class="sidebar-footnote">云 · 管 · 端<span>VDI Cloud</span></div></div>
|
||||
</aside>
|
||||
<div class="workspace">
|
||||
<header class="topbar"><div class="topbar-left"><el-button class="mobile-menu" aria-label="打开导航" :aria-expanded="navOpen" aria-controls="console-navigation" @click="navOpen = !navOpen"><el-icon :size="20"><Menu /></el-icon></el-button><div class="breadcrumbs"><span>VDI CLOUD</span><el-icon :size="11"><ArrowRight /></el-icon><span>{{ route.meta.title }}</span></div></div><div class="topbar-right"><span v-if="mockMode || data.settings?.mode === 'demo'" class="environment is-demo"><i />{{ mockMode ? '模拟接口' : '演示环境' }}</span><span v-else-if="data.settings?.mode === 'production'" class="environment"><i />现场联调环境</span><el-button class="header-refresh" text aria-label="刷新平台数据" title="刷新平台数据" @click="data.refresh"><el-icon :size="18"><Refresh /></el-icon></el-button><ThemeToggle /></div></header>
|
||||
<main id="main-content" class="page-container"><el-alert v-if="data.error" class="notice" type="error" :closable="false" show-icon title="数据刷新失败,当前信息可能已过期"><template #default>{{ data.error }} <el-button link type="primary" @click="data.refresh">重新加载</el-button></template></el-alert><div v-if="data.loading" class="panel"><el-skeleton :rows="8" animated /></div><router-view v-else /></main>
|
||||
<footer class="workspace-footer"><span><span class="refresh-dot" />{{ data.updatedAt ? `最近刷新 ${data.updatedAt}` : '等待加载' }}<span class="refresh-note"> · 每 5 秒更新</span></span><router-link to="/tasks">{{ pending ? `${pending} 个任务等待回执` : '查看任务与审计' }} <el-icon><ArrowRight /></el-icon></router-link></footer>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<style scoped>
|
||||
.console-shell{display:grid;grid-template-columns:248px minmax(0,1fr);min-height:100vh}.sidebar{background:var(--vdi-panel);border-right:1px solid var(--vdi-border);display:flex;flex-direction:column;padding:28px 18px 18px;position:sticky;top:0;height:100vh;overflow-y:auto;z-index:20}.brand-row{display:flex;align-items:center;justify-content:space-between}.brand{display:flex;gap:10px;align-items:center;color:var(--vdi-text);padding:0 10px;font-weight:750;font-size:21px;letter-spacing:1px}.brand img{width:34px;height:34px;object-fit:contain}.brand small{display:block;color:var(--vdi-muted);font-size:9px;font-weight:500;letter-spacing:2.2px;margin-top:5px}.organization{background:var(--vdi-panel-2);border:1px solid var(--vdi-border);border-radius:16px;padding:15px 14px;margin:26px 0 20px}.organization small{color:var(--vdi-muted);display:block;margin-bottom:8px;font-size:11px}.organization strong{font-size:13px;display:block;font-weight:600}.organization>span{display:flex;align-items:center;gap:6px;color:var(--vdi-muted);font-size:10px;margin-top:12px}.organization i,.environment i{width:6px;height:6px;display:inline-block;background:var(--vdi-muted);border-radius:50%}.organization i.connected{background:var(--vdi-ok)}.nav-label{font-size:10px;letter-spacing:1.4px;color:var(--vdi-muted);margin:18px 14px 12px}nav a{display:flex;align-items:center;gap:12px;padding:13px 15px;color:var(--vdi-muted);border-radius:12px;margin-bottom:6px;font-size:14px;min-height:47px}nav a:hover{background:var(--vdi-panel-2);color:var(--vdi-text)}nav a.active{background:var(--vdi-accent-soft);color:var(--vdi-accent);font-weight:650}.nav-count{margin-left:auto;font-size:11px;background:var(--vdi-brand);color:white;min-width:19px;text-align:center;border-radius:5px;padding:2px}.sidebar-bottom{margin-top:auto;padding-top:32px}.profile{background:var(--vdi-accent-soft);border-radius:16px;padding:12px;display:flex;align-items:center;gap:10px}.avatar{width:36px;height:36px;border-radius:11px;flex-shrink:0;background:linear-gradient(145deg,#f5ca91,#c97235);display:grid;place-items:center;color:#fff;font-weight:650}.profile-name{min-width:0;flex:1}.profile strong{font-size:13px;display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.profile small{display:block;font-size:11px;color:var(--vdi-muted);margin-top:3px}.profile .el-button{padding:4px;color:var(--vdi-muted)}.sidebar-footnote{display:flex;justify-content:space-between;color:var(--vdi-muted);font-size:10px;margin:18px 4px 0}.workspace{min-width:0;display:flex;flex-direction:column}.topbar{min-height:82px;padding:20px 42px 0;display:flex;justify-content:space-between;align-items:center;gap:16px}.topbar-left,.topbar-right,.breadcrumbs{display:flex;align-items:center;gap:16px}.breadcrumbs{font-size:11px;color:var(--vdi-muted);letter-spacing:.5px;gap:12px}.topbar-right{gap:12px}.environment{display:flex;align-items:center;gap:7px;font-size:11px;color:var(--vdi-muted)}.environment i{background:var(--vdi-ok)}.environment.is-demo i{background:var(--vdi-warn)}.header-refresh{color:var(--vdi-muted)}.page-container{padding:16px 42px 32px;flex:1;min-width:0;width:100%;max-width:1920px;margin:0 auto}.workspace-footer{padding:16px 42px;display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;font-size:11px;color:var(--vdi-muted)}.workspace-footer a{display:flex;gap:5px;align-items:center}.refresh-dot{width:5px;height:5px;border-radius:50%;background:var(--vdi-ok);display:inline-block;margin-right:6px}.mobile-menu,.mobile-close{display:none}.nav-scrim{display:none}
|
||||
@media(max-width:1200px){.console-shell{grid-template-columns:222px minmax(0,1fr)}.sidebar{padding:25px 14px 16px}.brand{font-size:20px;padding:0 6px}.page-container{padding:18px 26px 26px}.topbar{padding:18px 26px 0}.workspace-footer{padding:16px 26px}.organization{padding:14px 12px}}
|
||||
@media(max-width:760px){.console-shell{grid-template-columns:minmax(0,1fr)}.sidebar{position:fixed;left:0;top:0;bottom:0;width:248px;transform:translateX(-100%);transition:transform .2s ease}.sidebar.is-open{transform:translateX(0)}.mobile-menu,.mobile-close{display:inline-flex}.mobile-menu{padding:8px;width:38px;height:38px;min-height:38px}.mobile-close{color:var(--vdi-muted);padding:5px}.nav-scrim{display:block;position:fixed;inset:0;background:rgb(0 0 0 / 50%);border:0;z-index:19}.page-container{padding:20px 18px}.topbar{padding:16px 18px 0;min-height:68px}.topbar-left,.topbar-right{gap:10px}.breadcrumbs{gap:7px;font-size:10px}.environment{font-size:10px}.header-refresh{display:none}.workspace-footer{padding:16px 18px}.organization{margin-top:25px}}
|
||||
@media(max-width:410px){.breadcrumbs>span:first-child{display:none}.breadcrumbs>.el-icon{display:none}.refresh-note{display:none}.environment{font-size:9px}.page-container{padding:18px 14px}.topbar{padding-left:14px;padding-right:14px}}
|
||||
@media(prefers-reduced-motion:reduce){.sidebar{transition:none}}
|
||||
</style>
|
||||
@@ -0,0 +1,21 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia } from 'pinia'
|
||||
import ElementPlus from 'element-plus'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import 'element-plus/dist/index.css'
|
||||
import './styles/tokens.css'
|
||||
import App from './App.vue'
|
||||
import { router } from './router'
|
||||
import { useAuth } from './stores/auth'
|
||||
import { usePlatform } from './stores/platform'
|
||||
|
||||
async function start() {
|
||||
if (import.meta.env.DEV && import.meta.env.VITE_API_MODE === 'mock') {
|
||||
const { worker } = await import('./mocks/browser')
|
||||
await worker.start({ onUnhandledRequest: 'bypass' })
|
||||
}
|
||||
const app = createApp(App); app.use(createPinia()); app.use(router); app.use(ElementPlus, { locale: zhCn })
|
||||
window.addEventListener('vdi:unauthorized', () => { useAuth().clear(); usePlatform().clear(); if (router.currentRoute.value.path !== '/login') void router.replace('/login') })
|
||||
await router.isReady(); app.mount('#app')
|
||||
}
|
||||
void start()
|
||||
@@ -0,0 +1,3 @@
|
||||
import { setupWorker } from 'msw/browser'
|
||||
import { handlers } from './handlers'
|
||||
export const worker = setupWorker(...handlers)
|
||||
@@ -0,0 +1,47 @@
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import type { Admin, Desktop, Terminal, User, Task, Resource, Audit } from '../api'
|
||||
const now = () => new Date().toISOString()
|
||||
const administrators: Record<string, Admin> = {
|
||||
admin: { id: 'mock-admin', username: 'admin', displayName: '系统管理员', role: 'super_admin' },
|
||||
operator: { id: 'mock-operator', username: 'operator', displayName: '运维人员', role: 'operator' },
|
||||
viewer: { id: 'mock-viewer', username: 'viewer', displayName: '只读人员', role: 'viewer' },
|
||||
}
|
||||
const desktops: Desktop[] = [
|
||||
{ id: 'desk_mock_windows', name: '设计专属桌面', os: 'Windows', node: 'demo-node-a', vmid: 201, pool: '设计专属池', powerState: 'running', serviceState: 'unknown', provider: 'demo', endpoint: '', app: 'Desktop', width: 2560, height: 1440, fps: 30, updatedAt: now() },
|
||||
{ id: 'desk_mock_ubuntu', name: '研发办公桌面', os: 'Ubuntu', node: 'demo-node-a', vmid: 202, pool: '研发专属池', powerState: 'running', serviceState: 'unknown', provider: 'demo', endpoint: '', app: 'Desktop', width: 2560, height: 1440, fps: 30, updatedAt: now() },
|
||||
{ id: 'desk_mock_kylin', name: '国产办公桌面', os: '麒麟', node: 'demo-node-a', vmid: 203, pool: '通用办公池', powerState: 'stopped', serviceState: 'unknown', provider: 'demo', endpoint: '', app: 'Desktop', width: 2560, height: 1440, fps: 30, updatedAt: now() },
|
||||
]
|
||||
const terminals: Terminal[] = [{ id: 'term_mock_001', sn: 'DEMO-RK-001', name: '设计工位 01', group: '设计部', status: 'offline', agentVersion: '演示版本', lastSeen: null, sessionDesktopId: null, configVersion: 1, fps: null, rtt: null }]
|
||||
const users: User[] = [{ id: 'user_mock_wang', username: 'wang.demo', displayName: '王工', enabled: true, terminalId: 'term_mock_001', desktopIds: ['desk_mock_windows'] }]
|
||||
const tasks: Task[] = [], audits: Audit[] = []
|
||||
const resources: Resource[] = [{ id: 'demo-node-a', name: 'demo-node-a', status: 'online', cpu: 0.24, memory: 0.48, storage: 0.35, provider: 'demo', updatedAt: now() }]
|
||||
const revoked = new Set<string>()
|
||||
const keyFor = (r: Request) => r.headers.get('Authorization')?.replace('Bearer mock-', '') || ''
|
||||
const admin = (r: Request) => !revoked.has(keyFor(r)) ? administrators[keyFor(r)] : undefined
|
||||
const error = (status: number, message: string) => HttpResponse.json({ code: `mock_${status}`, message, requestId: `mock-${crypto.randomUUID()}` }, { status })
|
||||
function guard(r: Request, write = false, adminOnly = false) { const a = admin(r); if (!a) return error(401, '登录已失效,请重新登录'); if ((write && a.role === 'viewer') || (adminOnly && a.role !== 'super_admin')) return error(403, '当前账号没有该操作权限') }
|
||||
function list<T>(request: Request, items: T[]) { const q = new URL(request.url).searchParams; const page = Math.max(1, Number(q.get('page')) || 1), pageSize = Math.min(100, Math.max(1, Number(q.get('pageSize')) || 20)); return HttpResponse.json({ items: items.slice((page - 1) * pageSize, page * pageSize), page, pageSize, total: items.length, requestId: `mock-${crypto.randomUUID()}` }) }
|
||||
function audit(r: Request, action: string, target: string, result = 'success') { audits.unshift({ id: crypto.randomUUID(), actor: admin(r)?.username || '', action, target, result, requestId: crypto.randomUUID(), createdAt: now() }) }
|
||||
function submit(request: Request, kind: string, action: string, targetId: string, targetName: string, finish: () => void) {
|
||||
if (tasks.some(t => t.targetId === targetId && ['queued', 'running'].includes(t.status))) return error(409, '该对象已有任务执行中')
|
||||
const t: Task = { id: `task_mock_${crypto.randomUUID()}`, kind, action, targetId, targetName, actor: admin(request)?.username || '', status: 'queued', message: '模拟任务已提交', providerRef: '', createdAt: now(), updatedAt: now() }
|
||||
tasks.unshift(t); audit(request, action, targetName, 'submitted')
|
||||
setTimeout(() => { t.status = 'running'; t.message = '模拟执行中'; t.updatedAt = now() }, 400)
|
||||
setTimeout(() => { t.status = kind === 'terminal' ? 'failed' : 'success'; t.message = kind === 'terminal' ? '模拟终端离线,未执行' : '模拟任务已完成;没有操作真实资源'; t.updatedAt = now(); if (t.status === 'success') finish(); audit(request, action, targetName, t.status) }, 1500)
|
||||
return HttpResponse.json(t, { status: 202 })
|
||||
}
|
||||
export const handlers = [
|
||||
http.post('/api/v1/auth/login', async ({ request }) => { const b = await request.json() as { username: string; password: string }; const a = administrators[b.username]; if (!a || b.password !== 'Demo@2026') return error(401, '用户名或密码错误'); revoked.delete(b.username); audit(new Request(request.url, { headers: { Authorization: `Bearer mock-${b.username}` } }), 'login', b.username); return HttpResponse.json({ accessToken: `mock-${b.username}`, expiresIn: 3600, user: a }) }),
|
||||
http.get('/api/v1/auth/me', ({ request }) => guard(request) || HttpResponse.json(admin(request))),
|
||||
http.post('/api/v1/auth/logout', ({ request }) => { const e = guard(request); if (e) return e; revoked.add(keyFor(request)); return new HttpResponse(null, { status: 204 }) }),
|
||||
http.get('/api/v1/settings', ({ request }) => guard(request) || HttpResponse.json({ mode: 'demo', computeProvider: 'demo', pveConfigured: false, terminalTransport: 'mock', capabilities: ['auth', 'resources', 'desktops', 'terminals', 'bindings', 'tasks', 'audit'] })),
|
||||
http.get('/api/v1/overview', ({ request }) => guard(request) || HttpResponse.json({ terminalCount: terminals.length, onlineTerminals: 0, desktopCount: desktops.length, runningDesktops: desktops.filter(d => d.powerState === 'running').length, activeSessions: 0, failedTasks: tasks.filter(t => ['failed', 'timeout'].includes(t.status)).length, mode: 'demo' })),
|
||||
...([['desktops', desktops], ['terminals', terminals], ['users', users], ['resources', resources], ['tasks', tasks], ['audit-logs', audits]] as const).map(([path, data]) => http.get(`/api/v1/${path}`, ({ request }) => guard(request) || list(request, data as unknown[]))),
|
||||
http.post('/api/v1/desktops/:id/actions', async ({ request, params }) => { const e = guard(request, true); if (e) return e; const d = desktops.find(d => d.id === params.id); if (!d) return error(404, '桌面不存在'); const b = await request.json() as { action: string }; if (!['start', 'shutdown', 'reboot'].includes(b.action)) return error(400, '不支持的操作'); return submit(request, 'desktop', b.action, d.id, d.name, () => { d.powerState = b.action === 'shutdown' ? 'stopped' : 'running'; d.updatedAt = now() }) }),
|
||||
http.post('/api/v1/terminals', async ({ request }) => { const e = guard(request, true, true); if (e) return e; const b = await request.json() as { sn: string; name: string; group: string }; if (terminals.some(t => t.sn === b.sn)) return error(409, 'SN 已登记'); const id = `term_mock_${crypto.randomUUID()}`; terminals.push({ ...b, id, status: 'unregistered', agentVersion: '', lastSeen: null, sessionDesktopId: null, configVersion: 1, fps: null, rtt: null }); audit(request, 'enroll_terminal', id); return HttpResponse.json({ id, activationSecret: `mock-only-${crypto.randomUUID()}` }, { status: 201 }) }),
|
||||
http.post('/api/v1/terminals/:id/commands', async ({ request, params }) => { const e = guard(request, true); if (e) return e; const t = terminals.find(t => t.id === params.id); if (!t) return error(404, '终端不存在'); const b = await request.json() as { action: string }; return submit(request, 'terminal', b.action, t.id, t.name, () => {}) }),
|
||||
http.post('/api/v1/users', async ({ request }) => { const e = guard(request, true, true); if (e) return e; const b = await request.json() as { username: string; displayName: string }; if (users.some(u => u.username === b.username)) return error(409, '账号已存在'); const u: User = { ...b, id: `user_mock_${crypto.randomUUID()}`, enabled: true, terminalId: null, desktopIds: [] }; users.push(u); audit(request, 'create_user', u.id); return HttpResponse.json(u, { status: 201 }) }),
|
||||
http.put('/api/v1/users/:id/bindings', async ({ request, params }) => { const e = guard(request, true, true); if (e) return e; const u = users.find(u => u.id === params.id); if (!u) return error(404, '用户不存在'); const b = await request.json() as { terminalId: string | null; desktopIds: string[]; enabled: boolean }; if (b.terminalId && users.some(x => x.id !== u.id && x.terminalId === b.terminalId)) return error(409, '终端已关联其他用户'); Object.assign(u, b); audit(request, 'update_bindings', u.id); return HttpResponse.json(u) }),
|
||||
http.get('/api/v1/resources/vms', ({ request }) => guard(request) || error(503, '模拟环境未接入 Proxmox')),
|
||||
http.post('/api/v1/resources/sync', ({ request }) => guard(request, true, true) || error(503, '模拟环境未接入 Proxmox')),
|
||||
]
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import { useAuth } from '../stores/auth'
|
||||
|
||||
export const router = createRouter({ history: createWebHistory(), routes: [
|
||||
{ path: '/login', component: () => import('../views/Login.vue'), meta: { public: true } },
|
||||
{ path: '/', component: () => import('../layouts/ConsoleLayout.vue'), children: [
|
||||
{ path: '', redirect: '/overview' },
|
||||
{ path: 'overview', component: () => import('../views/Overview.vue'), meta: { title: '总览' } },
|
||||
{ path: 'resources', component: () => import('../views/Resources.vue'), meta: { title: '计算资源' } },
|
||||
{ path: 'desktops', component: () => import('../views/Desktops.vue'), meta: { title: '桌面管理' } },
|
||||
{ path: 'sessions', component: () => import('../views/Sessions.vue'), meta: { title: '远程会话' } },
|
||||
{ path: 'terminals', component: () => import('../views/Terminals.vue'), meta: { title: '终端管理' } },
|
||||
{ path: 'users', component: () => import('../views/Users.vue'), meta: { title: '用户与授权' } },
|
||||
{ path: 'tasks', component: () => import('../views/Tasks.vue'), meta: { title: '任务与审计' } },
|
||||
{ path: 'settings', component: () => import('../views/Settings.vue'), meta: { title: '系统设置', adminOnly: true } },
|
||||
{ path: 'forbidden', component: () => import('../views/Forbidden.vue'), meta: { title: '无访问权限' } },
|
||||
{ path: ':pathMatch(.*)*', component: () => import('../views/NotFound.vue'), meta: { title: '页面不存在' } },
|
||||
] },
|
||||
] })
|
||||
router.beforeEach(async to => {
|
||||
const auth = useAuth(); await auth.restore()
|
||||
if (!to.meta.public && !auth.user) return { path: '/login', query: { redirect: to.fullPath } }
|
||||
if (to.path === '/login' && auth.user) return '/overview'
|
||||
if (to.meta.adminOnly && !auth.canAdmin) return '/forbidden'
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { api, setAccessToken, type Admin } from '../api'
|
||||
import { useAuth } from './auth'
|
||||
vi.mock('../api', () => ({ api: { login: vi.fn(), me: vi.fn(), logout: vi.fn() }, setAccessToken: vi.fn() }))
|
||||
let storage: Map<string, string>
|
||||
const viewer: Admin = { id: 'viewer', username: 'viewer', displayName: '只读', role: 'viewer' }
|
||||
beforeEach(() => { vi.clearAllMocks(); storage = new Map(); vi.stubGlobal('sessionStorage', { getItem: (k: string) => storage.get(k) ?? null, setItem: (k: string, v: string) => storage.set(k, v), removeItem: (k: string) => storage.delete(k) }); setActivePinia(createPinia()) })
|
||||
describe('管理员会话', () => {
|
||||
it('只读角色登录后仍没有写权限', async () => { vi.mocked(api.login).mockResolvedValue({ accessToken: 'jwt', expiresIn: 3600, user: viewer }); const auth = useAuth(); await auth.login('viewer', 'password'); expect(auth.canOperate).toBe(false); expect(auth.canAdmin).toBe(false); expect(storage.get('vdi.accessToken')).toBe('jwt') })
|
||||
it('同时触发恢复只请求一次;令牌失效清除会话', async () => { storage.set('vdi.accessToken', 'expired'); vi.mocked(api.me).mockRejectedValue(new Error('expired')); const auth = useAuth(); await Promise.all([auth.restore(), auth.restore()]); expect(api.me).toHaveBeenCalledTimes(1); expect(auth.user).toBeNull(); expect(storage.has('vdi.accessToken')).toBe(false); expect(setAccessToken).toHaveBeenLastCalledWith('') })
|
||||
it('退出接口失败也移除本地登录凭据', async () => { vi.mocked(api.login).mockResolvedValue({ accessToken: 'jwt', expiresIn: 3600, user: viewer }); vi.mocked(api.logout).mockRejectedValue(new Error('offline')); const auth = useAuth(); await auth.login('viewer', 'password'); await expect(auth.logout()).rejects.toThrow('offline'); expect(auth.token).toBe(''); expect(auth.user).toBeNull(); expect(storage.has('vdi.accessToken')).toBe(false) })
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import { api, setAccessToken, type Admin } from '../api'
|
||||
|
||||
const tokenKey = 'vdi.accessToken'
|
||||
export const useAuth = defineStore('auth', () => {
|
||||
const user = ref<Admin | null>(null)
|
||||
const token = ref(sessionStorage.getItem(tokenKey) || '')
|
||||
const initialized = ref(false)
|
||||
let restoring: Promise<void> | undefined
|
||||
setAccessToken(token.value)
|
||||
const canOperate = computed(() => !!user.value && user.value.role !== 'viewer')
|
||||
const canAdmin = computed(() => user.value?.role === 'super_admin')
|
||||
function clear() { user.value = null; token.value = ''; initialized.value = true; sessionStorage.removeItem(tokenKey); setAccessToken('') }
|
||||
async function login(username: string, password: string) {
|
||||
const data = await api.login(username, password)
|
||||
token.value = data.accessToken; user.value = data.user; initialized.value = true
|
||||
setAccessToken(token.value); sessionStorage.setItem(tokenKey, token.value)
|
||||
}
|
||||
async function restore() {
|
||||
if (initialized.value) return
|
||||
if (!restoring) restoring = (async () => { try { if (token.value) user.value = await api.me() } catch { clear() } finally { initialized.value = true } })()
|
||||
await restoring
|
||||
}
|
||||
async function logout() { try { await api.logout() } finally { clear() } }
|
||||
return { user, token, initialized, canOperate, canAdmin, login, restore, clear, logout }
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { api, allPages, errorMessage, type Desktop, type Terminal, type User, type Task, type Audit, type Resource, type Settings, type Overview } from '../api'
|
||||
|
||||
export const usePlatform = defineStore('platform', () => {
|
||||
const desktops = ref<Desktop[]>([]), terminals = ref<Terminal[]>([]), users = ref<User[]>([])
|
||||
const tasks = ref<Task[]>([]), audits = ref<Audit[]>([]), resources = ref<Resource[]>([])
|
||||
const settings = ref<Settings | null>(null), overview = ref<Overview | null>(null)
|
||||
const loading = ref(false), error = ref(''), updatedAt = ref('')
|
||||
let inFlight: Promise<void> | undefined
|
||||
let generation = 0
|
||||
function refresh() {
|
||||
if (inFlight) return inFlight
|
||||
loading.value = !updatedAt.value
|
||||
const startedGeneration = generation
|
||||
inFlight = (async () => {
|
||||
try {
|
||||
const [d, t, u, k, a, r, s, o] = await Promise.all([allPages(api.desktops), allPages(api.terminals), allPages(api.users), allPages(api.tasks), allPages(api.audits), api.resources(), api.settings(), api.overview()])
|
||||
if (startedGeneration !== generation) return
|
||||
desktops.value = d; terminals.value = t; users.value = u; tasks.value = k; audits.value = a; resources.value = r.items; settings.value = s; overview.value = o
|
||||
updatedAt.value = new Date().toLocaleTimeString('zh-CN'); error.value = ''
|
||||
} catch (e) { if (startedGeneration === generation) error.value = errorMessage(e) }
|
||||
finally { if (startedGeneration === generation) { loading.value = false; inFlight = undefined } }
|
||||
})()
|
||||
return inFlight
|
||||
}
|
||||
function clear() { generation++; inFlight = undefined; loading.value = false; desktops.value = []; terminals.value = []; users.value = []; tasks.value = []; audits.value = []; resources.value = []; settings.value = null; overview.value = null; error.value = ''; updatedAt.value = '' }
|
||||
return { desktops, terminals, users, tasks, audits, resources, settings, overview, loading, error, updatedAt, refresh, clear }
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
:root {
|
||||
--vdi-bg:#f5f7fa; --vdi-panel:#fff; --vdi-panel-2:#f0f3f7;
|
||||
--vdi-text:#1b2533; --vdi-muted:#64748b; --vdi-border:#e5e9ef;
|
||||
--vdi-brand:#bd713b; --vdi-accent:#965421; --vdi-accent-soft:#fff0e4;
|
||||
--vdi-ok:#16845e; --vdi-warn:#9a6b10; --vdi-danger:#ce4652;
|
||||
--vdi-radius:18px; --vdi-shadow:0 16px 40px rgb(27 37 51 / 6%);
|
||||
--el-color-primary:var(--vdi-brand); --el-color-primary-light-3:#ce966f;
|
||||
--el-color-primary-light-5:#ddb495; --el-color-primary-light-7:#ebd1bd;
|
||||
--el-color-primary-light-8:#f3e2d5; --el-color-primary-light-9:#fcf3ed;
|
||||
--el-color-primary-dark-2:#a9602e;
|
||||
--el-color-success:#16845e; --el-color-success-light-3:#5fa98c;
|
||||
--el-color-success-light-5:#91c2ad; --el-color-success-light-7:#c4ded2;
|
||||
--el-color-success-light-8:#d9ebe3; --el-color-success-light-9:#eaf5ef;
|
||||
--el-color-warning:#9a6b10; --el-color-warning-light-5:#cfb78b;
|
||||
--el-color-warning-light-7:#e6d7bb; --el-color-warning-light-8:#efe5d4;
|
||||
--el-color-warning-light-9:#faf4e8;
|
||||
--el-color-danger:#ce4652; --el-color-danger-light-5:#e59ca3;
|
||||
--el-color-danger-light-7:#f0c4c8; --el-color-danger-light-8:#f5dadd;
|
||||
--el-color-danger-light-9:#fcf0f1;
|
||||
--el-color-info:#64748b; --el-color-info-light-5:#a6b0bd;
|
||||
--el-color-info-light-7:#cdd3db; --el-color-info-light-8:#e0e4e9;
|
||||
--el-color-info-light-9:#f0f3f7;
|
||||
font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;
|
||||
color:var(--vdi-text); background:var(--vdi-bg); font-synthesis:none; text-rendering:optimizeLegibility;
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
--vdi-bg:#151d27; --vdi-panel:#1d2733; --vdi-panel-2:#253241;
|
||||
--vdi-text:#edf1f6; --vdi-muted:#a5b2c3; --vdi-border:#314050;
|
||||
--vdi-accent:#f1ad62; --vdi-accent-soft:#493323;
|
||||
--vdi-ok:#36ca94; --vdi-warn:#efb744; --vdi-danger:#f07881;
|
||||
--vdi-shadow:0 18px 45px rgb(0 0 0 / 14%);
|
||||
--el-color-primary-light-3:#ce966f; --el-color-primary-light-5:#88603f;
|
||||
--el-color-primary-light-7:#5c422f; --el-color-primary-light-8:#493323;
|
||||
--el-color-primary-light-9:#352c27;
|
||||
--el-color-success:#36ca94; --el-color-success-light-3:#2fa77e;
|
||||
--el-color-success-light-5:#24644f; --el-color-success-light-7:#20453f;
|
||||
--el-color-success-light-8:#203a37; --el-color-success-light-9:#1d3332;
|
||||
--el-color-warning:#efb744; --el-color-warning-light-5:#77643c;
|
||||
--el-color-warning-light-7:#514735; --el-color-warning-light-8:#423c30;
|
||||
--el-color-warning-light-9:#34332e;
|
||||
--el-color-danger:#f07881; --el-color-danger-light-5:#85505a;
|
||||
--el-color-danger-light-7:#5c3d47; --el-color-danger-light-8:#49333d;
|
||||
--el-color-danger-light-9:#372c35;
|
||||
--el-color-info:#a5b2c3; --el-color-info-light-5:#58697d;
|
||||
--el-color-info-light-7:#3c4c60; --el-color-info-light-8:#314050;
|
||||
--el-color-info-light-9:#253241;
|
||||
}
|
||||
:root {
|
||||
--el-bg-color:var(--vdi-panel); --el-bg-color-page:var(--vdi-bg); --el-bg-color-overlay:var(--vdi-panel);
|
||||
--el-text-color-primary:var(--vdi-text); --el-text-color-regular:var(--vdi-text);
|
||||
--el-text-color-secondary:var(--vdi-muted); --el-text-color-placeholder:var(--vdi-muted);
|
||||
--el-text-color-disabled:var(--vdi-muted);
|
||||
--el-border-color:var(--vdi-border); --el-border-color-light:var(--vdi-border);
|
||||
--el-border-color-lighter:var(--vdi-border); --el-border-color-extra-light:var(--vdi-border);
|
||||
--el-border-color-dark:var(--vdi-border); --el-border-color-darker:var(--vdi-muted);
|
||||
--el-fill-color:var(--vdi-panel-2); --el-fill-color-light:var(--vdi-panel-2);
|
||||
--el-fill-color-lighter:var(--vdi-panel-2); --el-fill-color-extra-light:var(--vdi-panel-2);
|
||||
--el-fill-color-blank:var(--vdi-panel); --el-fill-color-dark:var(--vdi-border);
|
||||
--el-fill-color-darker:var(--vdi-border); --el-fill-color-disabled:var(--vdi-panel-2);
|
||||
--el-disabled-bg-color:var(--vdi-panel-2); --el-disabled-text-color:var(--vdi-muted);
|
||||
--el-disabled-border-color:var(--vdi-border);
|
||||
--el-border-radius-base:10px; --el-border-radius-small:7px;
|
||||
--el-mask-color:rgb(0 0 0 / 55%); --el-box-shadow-light:var(--vdi-shadow);
|
||||
--el-box-shadow:var(--vdi-shadow); --el-font-family:inherit;
|
||||
}
|
||||
*{box-sizing:border-box}body{margin:0;min-width:320px}button,input{font:inherit}button:focus-visible,a:focus-visible{outline:2px solid var(--vdi-accent);outline-offset:4px}a{color:var(--vdi-accent);text-decoration:none}h1,h2,h3,p{margin:0}h1{font-size:29px;line-height:1.35;font-weight:750;letter-spacing:.4px}h2{font-size:17px;font-weight:650}h3{font-size:15px;font-weight:600}
|
||||
.page-heading{display:flex;gap:16px;align-items:center;justify-content:space-between;flex-wrap:wrap;margin-bottom:25px}.subtext{font-size:13px;color:var(--vdi-muted);margin-top:7px;line-height:1.7}.eyebrow{font-size:11px;color:var(--vdi-muted);letter-spacing:1.8px;margin-bottom:9px}.panel{background:var(--vdi-panel);border:1px solid var(--vdi-border);border-radius:var(--vdi-radius);padding:22px;margin-bottom:20px;min-width:0;box-shadow:var(--vdi-shadow)}.panel-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:20px}.panel-heading a{font-size:12px}
|
||||
.toolbar{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:20px}.toolbar .el-input{width:260px}.toolbar .el-select{width:150px}.actions{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.actions .el-button+.el-button{margin-left:0}.mono{font-family:ui-monospace,monospace;font-size:12px;overflow-wrap:anywhere}.secondary{font-size:12px;color:var(--vdi-muted);line-height:1.7}.stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:18px;margin-bottom:22px}.stat{display:block;width:100%;border:1px solid var(--vdi-border);border-radius:var(--vdi-radius);background:var(--vdi-panel);padding:22px;text-align:left;color:inherit;cursor:pointer;box-shadow:var(--vdi-shadow)}.stat:hover{border-color:var(--vdi-brand)}.stat strong{display:block;font-size:32px;font-weight:750;margin:12px 0 9px;line-height:1.2}.stat span{color:var(--vdi-muted);font-size:12px}.stat-label{font-size:13px;color:var(--vdi-muted);display:flex;justify-content:space-between;align-items:center}.stat-caption{font-size:12px;color:var(--vdi-muted)}.stat-unit{font-size:14px;font-weight:500;margin-left:4px}.two-columns{display:grid;grid-template-columns:1.35fr .85fr;gap:20px}.row{display:flex;justify-content:space-between;gap:18px;align-items:center;flex-wrap:wrap;margin:16px 0}.tone-ok{color:var(--vdi-ok)}.tone-warn{color:var(--vdi-warn)}.tone-danger{color:var(--vdi-danger)}.health-dot{display:inline-block;width:8px;height:8px;background:currentColor;border-radius:50%;margin-right:9px;flex-shrink:0}
|
||||
.el-button{min-height:39px;padding:10px 16px;font-weight:500;--el-button-hover-text-color:var(--vdi-accent);--el-button-hover-bg-color:var(--vdi-accent-soft);--el-button-hover-border-color:var(--vdi-brand)}.el-button--primary{--el-button-text-color:#fff;--el-button-hover-text-color:#fff;--el-button-hover-bg-color:#ce824a;--el-button-hover-border-color:#ce824a;--el-button-active-bg-color:#a9602e;--el-button-active-border-color:#a9602e;--el-button-disabled-text-color:rgb(255 255 255 / 70%);--el-button-disabled-bg-color:#825a3d;--el-button-disabled-border-color:#825a3d}.el-button.is-link,.el-button.is-text{min-height:30px;padding:5px 8px}.el-button.is-link{color:var(--vdi-accent)}.el-button.is-disabled.is-link{color:var(--vdi-muted);opacity:.6}.el-button-group .el-button{min-height:36px}.theme-toggle.el-button{width:42px;height:42px;padding:0;flex-shrink:0;background:var(--vdi-panel-2);border-radius:11px}
|
||||
.el-table{--el-table-header-bg-color:var(--vdi-panel-2);--el-table-bg-color:var(--vdi-panel);--el-table-tr-bg-color:var(--vdi-panel);--el-table-row-hover-bg-color:var(--vdi-panel-2);--el-table-border-color:var(--vdi-border);--el-table-header-text-color:var(--vdi-muted);--el-table-text-color:var(--vdi-text);border-radius:11px}.el-table th.el-table__cell{font-weight:500;padding:14px 0;font-size:12px}.el-table td.el-table__cell{padding:17px 0}.el-table .cell{padding:0 14px}.el-table__empty-text{color:var(--vdi-muted)}.el-pagination{margin-top:22px;flex-wrap:wrap;gap:8px;justify-content:flex-end;--el-pagination-button-bg-color:var(--vdi-panel-2);--el-pagination-hover-color:var(--vdi-accent)}.el-dialog{max-width:calc(100vw - 32px);border:1px solid var(--vdi-border);border-radius:18px;padding:24px}.el-dialog__title,.el-drawer__title{color:var(--vdi-text);font-weight:650}.el-drawer{max-width:100vw;border-left:1px solid var(--vdi-border)}.el-drawer__header{margin-bottom:24px;color:var(--vdi-text)}.el-drawer__body{padding:24px}.el-descriptions__cell{overflow-wrap:anywhere}.el-descriptions__label.el-descriptions__cell.is-bordered-label{background:var(--vdi-panel-2);color:var(--vdi-muted);font-weight:500}.el-descriptions__content.el-descriptions__cell.is-bordered-content{background:var(--vdi-panel);color:var(--vdi-text)}.el-input__wrapper,.el-select__wrapper{min-height:39px;border-radius:10px;background:var(--vdi-panel-2)}.el-input__wrapper.is-focus,.el-select__wrapper.is-focused{box-shadow:0 0 0 1px var(--vdi-brand) inset}.el-tabs__item.is-active,.el-tabs__item:hover{color:var(--vdi-accent)}.el-tabs__active-bar{background:var(--vdi-brand)}.el-progress-bar__outer{background:var(--vdi-panel-2)}.el-progress__text{color:var(--vdi-muted);font-size:12px!important}.el-tag{border-radius:7px;height:auto;min-height:24px;padding:3px 8px;line-height:1.4}.el-message-box{border-radius:18px;max-width:calc(100vw - 32px)}.el-alert{border-radius:12px}.el-switch{--el-switch-on-color:var(--vdi-brand)}.el-checkbox__input.is-checked+.el-checkbox__label{color:var(--vdi-accent)}
|
||||
.secret{white-space:pre-wrap;overflow-wrap:anywhere;padding:16px;border:1px dashed var(--vdi-brand);background:var(--vdi-accent-soft);border-radius:10px}.notice{margin-bottom:20px}.empty-note{padding:26px 0;text-align:center;color:var(--vdi-muted)}.empty-panel{display:grid;place-items:center;min-height:230px;text-align:center;padding:32px}.empty-icon{display:grid;place-items:center;width:58px;height:58px;background:var(--vdi-panel-2);color:var(--vdi-accent);border-radius:18px;margin:0 auto 18px}.section-kicker{font-size:10px;letter-spacing:1.6px;color:var(--vdi-muted);margin-bottom:12px}
|
||||
@media(min-width:1600px){.stats{gap:22px}.panel{padding:26px}}
|
||||
@media(max-width:1100px){.stats{grid-template-columns:repeat(2,minmax(0,1fr))}.two-columns{grid-template-columns:1fr}}
|
||||
@media(max-width:600px){h1{font-size:24px}.panel{padding:16px;border-radius:14px}.stats{gap:12px}.stat{padding:18px}.stat strong{font-size:28px}.toolbar .el-input,.toolbar .el-select{width:100%}.el-pagination{justify-content:flex-start}.el-dialog{padding:20px}.el-drawer__body{padding:18px}.page-heading{gap:14px;margin-bottom:20px}.actions{gap:8px}}
|
||||
@@ -0,0 +1,47 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import { Grid, List, Search, Plus, ArrowRight, Monitor } from '@element-plus/icons-vue'
|
||||
import { api, type Desktop, type DesktopAction, type DiscoveredVM, type ImportInput } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
import SystemIcon from '../components/SystemIcon.vue'
|
||||
const auth = useAuth(), data = usePlatform(), { busy, run, confirm } = useAction()
|
||||
const keyword = ref(''), status = ref(''), page = ref(1), selectedId = ref(''), importVisible = ref(false)
|
||||
const view = ref<'cards' | 'table'>('cards')
|
||||
const selected = computed(() => data.desktops.find(d => d.id === selectedId.value))
|
||||
const filtered = computed(() => data.desktops.filter(d => `${d.name} ${d.vmid}`.toLowerCase().includes(keyword.value.toLowerCase()) && (!status.value || status.value === d.powerState)))
|
||||
const rows = computed(() => filtered.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
const form = reactive<ImportInput>({ name: '', os: 'Windows', node: '', vmid: 100, endpoint: '' })
|
||||
const discovered = ref<DiscoveredVM[]>([]), vmKey = ref('')
|
||||
const labels = { start: '开机', shutdown: '正常关机', reboot: '重启桌面' }
|
||||
function activeTask(d: Desktop) { return data.tasks.some(t => t.targetId === d.id && ['queued', 'running'].includes(t.status)) }
|
||||
async function action(d: Desktop, a: DesktopAction) {
|
||||
const description = a === 'start' ? '提交开机任务。开机后仍需确认连接服务是否就绪。' : '将中断该桌面的连接,请确认使用者已保存工作。'
|
||||
if (await confirm(`${labels[a]} · ${d.name}`, description)) await run(() => api.desktopAction(d.id, a), '任务已提交,请在任务与审计中查看最终结果')
|
||||
}
|
||||
async function openImport() { if (await run(async () => { discovered.value = (await api.discoverVMs()).items }, '已获取可纳管的 VM')) importVisible.value = true }
|
||||
function chooseVM(key: string) { const v = discovered.value.find(v => `${v.node}/${v.vmid}` === key); if (v) { form.node = v.node; form.vmid = v.vmid; form.name = v.name } }
|
||||
async function submitImport() { if (!form.name.trim() || !form.node) return; if (await run(() => api.importDesktop(form), '桌面已纳管')) importVisible.value = false }
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>桌面管理</h1><p class="subtext">统一管理 Windows / Ubuntu / 麒麟云桌面与授权</p></div><el-button v-if="auth.canAdmin" type="primary" :loading="busy" :disabled="!data.settings?.pveConfigured" @click="openImport"><el-icon style="margin-right:7px"><Plus /></el-icon>纳管已有 VM</el-button></div>
|
||||
<el-alert v-if="!data.settings?.pveConfigured" class="notice" type="info" title="当前可操作演示桌面;配置 Proxmox 后可纳管真实 VM。" :closable="false" show-icon />
|
||||
<section class="panel desktop-browser" :class="{ 'card-browser': view === 'cards' }">
|
||||
<div class="desktop-summary"><div><h2>云桌面资源</h2><p class="subtext">已纳管 {{ data.desktops.length }} 台桌面 · 按系统与电源状态查看</p></div><div class="summary-chips"><span>全部 <b>{{ data.desktops.length }}</b></span><span><i class="health-dot tone-ok" />运行中 <b>{{ data.desktops.filter(d => d.powerState === 'running').length }}</b></span><span>未授权 <b>{{ data.desktops.filter(d => !data.users.some(u => u.enabled && u.desktopIds.includes(d.id))).length }}</b></span></div></div>
|
||||
<div class="toolbar desktop-toolbar"><el-input v-model="keyword" aria-label="搜索桌面" placeholder="搜索名称 / VMID" clearable @input="page = 1"><template #prefix><el-icon><Search /></el-icon></template></el-input><el-select v-model="status" aria-label="电源状态筛选" placeholder="全部电源状态" clearable @change="page = 1"><el-option label="运行中" value="running" /><el-option label="已关机" value="stopped" /></el-select><span class="secondary result-count">共 {{ filtered.length }} 台</span><el-button-group class="view-switch" aria-label="桌面展示方式"><el-button :type="view === 'cards' ? 'primary' : 'default'" aria-label="卡片视图" :aria-pressed="view === 'cards'" @click="view = 'cards'"><el-icon><Grid /></el-icon></el-button><el-button :type="view === 'table' ? 'primary' : 'default'" aria-label="列表视图" :aria-pressed="view === 'table'" @click="view = 'table'"><el-icon><List /></el-icon></el-button></el-button-group></div>
|
||||
<div v-if="view === 'cards' && rows.length" class="desktop-grid"><article v-for="d in rows" :key="d.id" class="desktop-card" :data-desktop-id="d.id"><div class="desktop-cover" :class="{ ubuntu: d.os === 'Ubuntu', kylin: d.os === '麒麟' }"><div class="os-icon"><SystemIcon :os="d.os" /></div><span class="desktop-vmid">VM {{ d.vmid }}</span><div class="cover-grid" /></div><div class="desktop-body"><div class="desktop-name-row"><h2>{{ d.name }}</h2><StatusTag :value="d.powerState" /></div><p class="subtext desktop-os">{{ d.os }} · {{ d.node }}</p><div class="desktop-chips"><span>{{ d.width }} × {{ d.height }}</span><span>{{ d.fps }} FPS 请求</span><span>{{ d.provider === 'proxmox' ? 'Proxmox' : '演示资源' }}</span></div><dl class="desktop-meta"><div><dt>授权用户</dt><dd>{{ data.users.filter(u => u.enabled && u.desktopIds.includes(d.id)).map(u => u.displayName).join('、') || '尚未分配' }}</dd></div><div><dt>连接服务</dt><dd>{{ d.serviceState === 'ready' ? '已就绪' : '尚未检测' }}</dd></div></dl><div class="desktop-card-actions"><el-button link @click="selectedId = d.id">查看详情<el-icon><ArrowRight /></el-icon></el-button><el-button v-if="auth.canOperate" :type="d.powerState === 'stopped' ? 'primary' : 'default'" :disabled="busy || activeTask(d)" @click="action(d, d.powerState === 'stopped' ? 'start' : 'shutdown')">{{ activeTask(d) ? '任务执行中' : d.powerState === 'stopped' ? '开机' : '正常关机' }}</el-button></div></div></article></div>
|
||||
<div v-else-if="view === 'cards'" class="panel empty-panel"><div><div class="empty-icon"><el-icon :size="28"><Monitor /></el-icon></div><h3>暂无符合条件的桌面</h3><p class="subtext">调整筛选条件,或先纳管已有虚拟机。</p></div></div>
|
||||
<el-table v-else :data="rows" empty-text="暂无符合条件的桌面"><el-table-column label="桌面 / VMID" min-width="175"><template #default="{ row }"><el-button link type="primary" @click="selectedId = row.id">{{ row.name }}</el-button><div class="secondary">VM {{ row.vmid }} · {{ row.provider === 'demo' ? '演示资源' : 'Proxmox' }}</div></template></el-table-column><el-table-column prop="os" label="系统" width="100" /><el-table-column label="节点 / 池" min-width="150"><template #default="{ row }">{{ row.node }}<div class="secondary">{{ row.pool || '未入池' }}</div></template></el-table-column><el-table-column label="电源 / 连接服务" width="155"><template #default="{ row }"><StatusTag :value="row.powerState" /><div class="secondary" style="margin-top:5px">连接服务:{{ row.serviceState === 'ready' ? '就绪' : '未检测' }}</div></template></el-table-column><el-table-column label="操作" min-width="200"><template #default="{ row }"><div class="actions"><el-button link type="primary" @click="selectedId = row.id">详情</el-button><el-button v-if="auth.canOperate" link type="primary" :disabled="busy || activeTask(row)" @click="action(row, row.powerState === 'stopped' ? 'start' : 'shutdown')">{{ row.powerState === 'stopped' ? '开机' : '关机' }}</el-button><el-button v-if="auth.canOperate" link type="primary" :disabled="busy || row.powerState !== 'running' || activeTask(row)" @click="action(row, 'reboot')">重启</el-button><el-tag v-if="activeTask(row)" size="small">任务中</el-tag></div></template></el-table-column></el-table>
|
||||
<el-pagination v-model:current-page="page" :total="filtered.length" :page-size="10" layout="total, prev, pager, next" />
|
||||
</section>
|
||||
<el-drawer :model-value="!!selected" title="桌面详情" size="560px" @close="selectedId = ''"><template v-if="selected"><h2>{{ selected.name }}</h2><el-descriptions :column="1" border style="margin-top:22px"><el-descriptions-item label="节点 / VMID">{{ selected.node }} / {{ selected.vmid }}</el-descriptions-item><el-descriptions-item label="电源状态"><StatusTag :value="selected.powerState" /></el-descriptions-item><el-descriptions-item label="连接服务">{{ selected.serviceState === 'ready' ? '已就绪' : '尚未检测,不代表不可用' }}</el-descriptions-item><el-descriptions-item label="连接地址">{{ selected.endpoint || '未配置' }}</el-descriptions-item><el-descriptions-item label="连接参数">{{ selected.width }} × {{ selected.height }} / {{ selected.fps }} FPS</el-descriptions-item><el-descriptions-item label="授权用户">{{ data.users.filter(u => u.desktopIds.includes(selected!.id)).map(u => u.displayName).join('、') || '未分配' }}</el-descriptions-item></el-descriptions><p class="subtext" style="margin:20px 0">还原镜像和模板发放将在后续阶段接入,本版只提供开关机与重启。</p><div class="actions" v-if="auth.canOperate"><el-button :disabled="busy || activeTask(selected) || selected.powerState === 'running'" @click="action(selected, 'start')">开机</el-button><el-button :disabled="busy || activeTask(selected) || selected.powerState === 'stopped'" @click="action(selected, 'shutdown')">正常关机</el-button><el-button :disabled="busy || activeTask(selected) || selected.powerState !== 'running'" @click="action(selected, 'reboot')">重启桌面</el-button></div></template></el-drawer>
|
||||
<el-dialog v-model="importVisible" title="纳管已有 VM" width="520px"><el-form label-position="top" @submit.prevent="submitImport"><el-form-item label="选择 VM" required><el-select v-model="vmKey" placeholder="选择节点和虚拟机" @change="chooseVM"><el-option v-for="v in discovered" :key="`${v.node}/${v.vmid}`" :value="`${v.node}/${v.vmid}`" :label="`${v.node} / ${v.vmid} / ${v.name}`" /></el-select></el-form-item><el-form-item label="桌面名称" required><el-input v-model="form.name" maxlength="80" /></el-form-item><el-form-item label="操作系统"><el-select v-model="form.os"><el-option v-for="os in (['Windows', 'Ubuntu', '麒麟'] as const)" :key="os" :value="os" /></el-select></el-form-item><el-form-item label="桌面连接地址(可后续补充)"><el-input v-model="form.endpoint" placeholder="VM 的 IP 或主机名" /></el-form-item><p class="subtext">纳管不会修改 VM;使用 Moonlight 前仍需完成 Sunshine 配对。</p><div class="actions" style="justify-content:flex-end;margin-top:22px"><el-button @click="importVisible = false">取消</el-button><el-button type="primary" native-type="submit" :loading="busy" :disabled="!form.node || !form.name.trim()">确认纳管</el-button></div></el-form></el-dialog>
|
||||
</template>
|
||||
<style scoped>
|
||||
.desktop-summary{display:flex;align-items:center;justify-content:space-between;gap:20px;flex-wrap:wrap;padding-bottom:22px;margin-bottom:22px;border-bottom:1px solid var(--vdi-border)}.summary-chips{display:flex;gap:9px;flex-wrap:wrap}.summary-chips>span{background:var(--vdi-panel-2);border:1px solid var(--vdi-border);border-radius:8px;padding:8px 11px;color:var(--vdi-muted);font-size:11px;display:flex;align-items:center;gap:5px}.summary-chips b{color:var(--vdi-text);font-weight:600;margin-left:3px}.summary-chips .health-dot{margin-right:0;width:6px;height:6px}.view-switch{margin-left:auto;display:flex;flex-shrink:0}.view-switch .el-button{padding:8px 11px}.card-browser.panel{background:transparent;border:0;box-shadow:none;padding:0}.card-browser .desktop-summary{background:var(--vdi-panel);border:1px solid var(--vdi-border);border-radius:18px;padding:22px;margin-bottom:18px;box-shadow:var(--vdi-shadow)}.desktop-toolbar{margin-bottom:20px}.desktop-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:20px}.desktop-card{background:var(--vdi-panel);border:1px solid var(--vdi-border);border-radius:18px;box-shadow:var(--vdi-shadow);overflow:hidden;min-width:0}.desktop-cover{height:103px;padding:20px;background:linear-gradient(125deg,#a95e2e,#d89553);color:white;position:relative;display:flex;align-items:center;justify-content:space-between;overflow:hidden}.desktop-cover:after{content:"";position:absolute;width:160px;height:160px;border:24px solid rgb(255 255 255 / 9%);border-radius:50%;right:-32px;top:-85px}.desktop-cover.ubuntu{background:linear-gradient(125deg,#65558f,#9c8acc)}.desktop-cover.kylin{background:linear-gradient(125deg,#247a71,#67b39f)}.os-icon{width:44px;height:44px;background:rgb(255 255 255 / 18%);border:1px solid rgb(255 255 255 / 12%);border-radius:12px;display:grid;place-items:center;position:relative;z-index:1}.desktop-vmid{position:relative;z-index:1;font-size:10px;letter-spacing:1px;border:1px solid rgb(255 255 255 / 30%);background:rgb(255 255 255 / 8%);padding:5px 7px;border-radius:6px}.cover-grid{position:absolute;inset:0;background-image:linear-gradient(90deg,rgb(255 255 255 / 4%) 1px,transparent 1px),linear-gradient(rgb(255 255 255 / 4%) 1px,transparent 1px);background-size:22px 22px}.desktop-body{padding:21px 20px 17px}.desktop-name-row{display:flex;justify-content:space-between;align-items:flex-start;gap:8px}.desktop-name-row h2{font-size:17px;overflow-wrap:anywhere}.desktop-name-row .el-tag{flex-shrink:0;font-size:10px}.desktop-os{font-size:12px;margin-top:8px}.desktop-chips{display:flex;gap:6px;flex-wrap:wrap;margin:18px 0}.desktop-chips span{font-size:10px;background:var(--vdi-panel-2);border:1px solid var(--vdi-border);padding:5px 7px;border-radius:7px;color:var(--vdi-muted)}.desktop-meta{margin:0;font-size:11px}.desktop-meta>div{display:flex;justify-content:space-between;gap:12px;margin:13px 0}.desktop-meta dt{color:var(--vdi-muted);flex-shrink:0}.desktop-meta dd{margin:0;text-align:right;overflow-wrap:anywhere}.desktop-card-actions{display:flex;justify-content:space-between;align-items:center;gap:6px;margin-top:18px;border-top:1px solid var(--vdi-border);padding-top:17px}.desktop-card-actions .el-button{font-size:11px;padding:9px 12px}.desktop-card-actions .el-button.is-link{padding-left:0}.desktop-card-actions .el-icon{margin-left:4px}
|
||||
@media(min-width:1700px){.desktop-grid{grid-template-columns:repeat(4,minmax(0,1fr))}}
|
||||
@media(max-width:1200px){.desktop-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
|
||||
@media(max-width:600px){.desktop-grid{grid-template-columns:1fr}.card-browser .desktop-summary{padding:18px}.desktop-summary{gap:16px}.result-count{display:none}.view-switch{margin-left:0}.desktop-toolbar{gap:12px}.desktop-toolbar .el-input{flex:1;min-width:190px}.desktop-toolbar .el-select{width:calc(100% - 95px)}.desktop-toolbar .el-input{order:-2;flex-basis:100%}.desktop-body{padding:21px}.desktop-cover{height:95px}}
|
||||
</style>
|
||||
@@ -0,0 +1 @@
|
||||
<template><el-result icon="warning" title="无访问权限" sub-title="当前角色无权访问该页面"><template #extra><router-link to="/overview"><el-button type="primary">返回总览</el-button></router-link></template></el-result></template>
|
||||
@@ -0,0 +1,27 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { Monitor, Connection, Lock, ArrowRight } from '@element-plus/icons-vue'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { errorMessage } from '../api'
|
||||
import ThemeToggle from '../components/ThemeToggle.vue'
|
||||
import brandMark from '../assets/brand-mark.svg'
|
||||
const auth = useAuth(), router = useRouter(), route = useRoute()
|
||||
const form = reactive({ username: '', password: '' }), busy = ref(false), error = ref('')
|
||||
const demo = import.meta.env.VITE_API_MODE === 'mock' || import.meta.env.VITE_DEMO_HINT === 'true'
|
||||
async function submit() {
|
||||
if (!form.username.trim() || !form.password) { error.value = '请输入用户名和密码'; return }
|
||||
busy.value = true; error.value = ''
|
||||
try { await auth.login(form.username.trim(), form.password); const redirect = typeof route.query.redirect === 'string' && route.query.redirect.startsWith('/') && !route.query.redirect.startsWith('//') ? route.query.redirect : '/overview'; await router.replace(redirect) }
|
||||
catch (e) { error.value = errorMessage(e) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<main class="login-page"><header class="login-header"><a href="/" class="login-brand"><img :src="brandMark" alt="" /><span>百工万象<small>VDI CLOUD</small></span></a><ThemeToggle /></header><div class="login-main"><section class="login-intro"><div class="eyebrow">VDI CLOUD / MANAGEMENT PLATFORM</div><h1>让每一台桌面<br>有序连接<span>。</span></h1><p>从桌面资源到终端运维,<br>让云端的每一次连接,尽在掌握。</p><div class="intro-capabilities"><span><el-icon><Monitor /></el-icon>桌面管理</span><span><el-icon><Connection /></el-icon>终端接入</span><span><el-icon><Lock /></el-icon>安全授权</span></div><div class="login-art" aria-hidden="true"><div class="art-orbit orbit-one" /><div class="art-orbit orbit-two" /><div class="art-screen screen-back"><div class="art-dots"><i /><i /><i /></div><div class="art-rows"><b /><b /><b /></div></div><div class="art-screen screen-front"><div class="art-dots"><i /><i /><i /></div><div class="art-logo"><img :src="brandMark" alt="" /><div>VDI CLOUD<small>连接工作新方式</small></div></div><div class="art-progress"><i /></div></div><div class="art-badge"><i />云 · 管 · 端</div></div></section><section class="login-form-area"><div class="login-card"><div class="section-kicker">WELCOME BACK</div><h2>登录管理控制台</h2><p class="subtext">使用平台管理员账号,开启工作。</p><el-alert v-if="error" class="notice" style="margin-top:24px" type="error" :title="error" :closable="false" show-icon /><el-form label-position="top" @submit.prevent="submit"><el-form-item label="用户名"><el-input v-model="form.username" name="username" autocomplete="username" size="large" placeholder="请输入用户名" :disabled="busy" /></el-form-item><el-form-item label="密码"><el-input v-model="form.password" name="password" type="password" autocomplete="current-password" size="large" show-password placeholder="请输入密码" :disabled="busy" /></el-form-item><el-button type="primary" size="large" native-type="submit" :loading="busy" class="login-submit">登录<el-icon><ArrowRight /></el-icon></el-button></el-form><p class="login-security"><el-icon><Lock /></el-icon>仅限已授权的平台管理人员访问</p><p v-if="demo" class="demo-hint">演示账号:admin / operator / viewer<br>演示密码:Demo@2026<br><span>仅用于演示模式,正式环境使用独立账号。</span></p></div></section></div><footer class="login-footer"><span>百工万象 · VDI Cloud</span><span>云端服务 / 管理控制台 / 云终端</span></footer></main>
|
||||
</template>
|
||||
<style scoped>
|
||||
.login-page{min-height:100vh;display:flex;flex-direction:column;background:radial-gradient(ellipse at 8% 60%,var(--vdi-accent-soft),transparent 53%),var(--vdi-bg)}.login-header{padding:30px 5%;display:flex;justify-content:space-between;align-items:center}.login-brand{display:flex;align-items:center;gap:11px;color:var(--vdi-text);font-size:23px;font-weight:750;letter-spacing:1px}.login-brand img{width:36px;height:36px}.login-brand small{display:block;color:var(--vdi-muted);font-size:9px;letter-spacing:2.7px;font-weight:500;margin-top:4px}.login-main{flex:1;display:grid;grid-template-columns:1.15fr 1fr;align-items:center;gap:8%;width:min(1160px,88%);margin:35px auto}.login-intro{position:relative;padding-top:12px}.eyebrow{font-size:11px;letter-spacing:2px;margin-bottom:24px}.login-intro h1{font-size:48px;line-height:1.45;letter-spacing:1px;font-weight:750}.login-intro h1 span{color:var(--vdi-brand)}.login-intro>p{color:var(--vdi-muted);line-height:1.9;margin-top:20px;font-size:15px}.intro-capabilities{display:flex;gap:23px;margin-top:25px;flex-wrap:wrap}.intro-capabilities>span{display:flex;align-items:center;gap:7px;color:var(--vdi-muted);font-size:12px}.intro-capabilities .el-icon{color:var(--vdi-accent)}.login-form-area{display:flex;justify-content:center}.login-card{width:440px;max-width:100%;background:var(--vdi-panel);border:1px solid var(--vdi-border);padding:40px;border-radius:22px;box-shadow:var(--vdi-shadow)}.login-card h2{font-size:25px;margin-bottom:10px}.section-kicker{color:var(--vdi-accent);font-size:10px;letter-spacing:2px;margin-bottom:14px}.login-card .el-form{margin-top:34px}.login-card :deep(.el-form-item){margin-bottom:25px}.login-card :deep(.el-input__wrapper){min-height:46px;background:var(--vdi-bg)}.login-submit{width:100%;height:46px;margin-top:7px;font-weight:600}.login-submit .el-icon{margin-left:12px}.login-security{display:flex;justify-content:center;align-items:center;gap:6px;font-size:11px;color:var(--vdi-muted);margin-top:23px}.demo-hint{font-size:12px;line-height:1.9;color:var(--vdi-muted);margin-top:24px;padding-top:20px;border-top:1px solid var(--vdi-border)}.demo-hint span{font-size:11px}.login-footer{display:flex;justify-content:space-between;padding:25px 5%;color:var(--vdi-muted);font-size:11px;gap:16px;flex-wrap:wrap}.login-art{position:relative;width:360px;height:200px;margin-top:32px}.art-orbit{position:absolute;border:1px solid var(--vdi-border);border-radius:50%;width:340px;height:135px;bottom:4px;left:0;transform:rotate(-14deg)}.orbit-two{transform:rotate(15deg);width:300px;bottom:17px;left:20px}.art-screen{position:absolute;background:var(--vdi-panel);border:1px solid var(--vdi-border);border-radius:13px;box-shadow:var(--vdi-shadow);overflow:hidden}.screen-back{width:220px;height:133px;left:8px;top:9px;transform:rotate(-7deg)}.screen-front{width:247px;height:152px;left:89px;top:40px;transform:rotate(5deg)}.art-dots{display:flex;gap:4px;padding:11px;border-bottom:1px solid var(--vdi-border);background:var(--vdi-panel-2)}.art-dots i{width:4px;height:4px;border-radius:50%;background:var(--vdi-muted);opacity:.5}.art-rows{padding:20px 18px}.art-rows b{display:block;height:7px;background:var(--vdi-border);margin-bottom:9px;width:65%;border-radius:3px}.art-rows b:nth-child(2){width:88%}.art-rows b:nth-child(3){width:43%;background:var(--vdi-brand);opacity:.6}.art-logo{display:flex;gap:13px;align-items:center;padding:26px 25px 17px;font-size:14px;letter-spacing:1px;font-weight:600}.art-logo img{width:33px;height:33px}.art-logo small{font-size:9px;display:block;color:var(--vdi-muted);letter-spacing:1px;margin-top:6px;font-weight:400}.art-progress{margin:0 25px;height:4px;background:var(--vdi-panel-2);border-radius:4px}.art-progress i{display:block;height:100%;width:68%;background:linear-gradient(90deg,var(--vdi-brand),#f1ad62);border-radius:4px}.art-badge{position:absolute;right:0;bottom:0;background:var(--vdi-panel);border:1px solid var(--vdi-border);border-radius:9px;padding:9px 14px;font-size:10px;box-shadow:var(--vdi-shadow)}.art-badge i{width:5px;height:5px;border-radius:50%;display:inline-block;background:var(--vdi-ok);margin-right:6px}
|
||||
@media(max-width:950px){.login-main{gap:4%;width:92%}.login-intro h1{font-size:39px}.login-card{padding:30px}.login-art{transform:scale(.85);transform-origin:left top;margin-bottom:-25px}.intro-capabilities{gap:14px}}
|
||||
@media(max-width:700px){.login-header{padding:22px}.login-main{grid-template-columns:1fr;margin:24px auto 45px;gap:28px;width:min(440px,calc(100% - 36px))}.login-intro{padding-top:0}.login-intro h1{font-size:32px}.login-intro h1 br{display:none}.login-intro>p,.intro-capabilities,.login-art{display:none}.eyebrow{margin-bottom:14px;font-size:9px;letter-spacing:1.4px}.login-card{padding:28px 24px;width:100%}.login-card h2{font-size:23px}.login-footer{padding:20px 22px;font-size:10px}.login-footer>span:last-child{display:none}.login-security{font-size:10px}.login-brand{font-size:20px}}
|
||||
</style>
|
||||
@@ -0,0 +1 @@
|
||||
<template><el-result icon="info" title="页面不存在" sub-title="请通过左侧菜单选择功能"><template #extra><router-link to="/overview"><el-button type="primary">返回总览</el-button></router-link></template></el-result></template>
|
||||
@@ -0,0 +1,47 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { Monitor, Connection, Warning, Refresh, Download, Cpu, ArrowRight, CircleCheck, Clock } from '@element-plus/icons-vue'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
const data = usePlatform(), router = useRouter()
|
||||
const active = computed(() => data.terminals.filter(t => t.status === 'online' && t.sessionDesktopId && t.sessionState === 'connected'))
|
||||
const averageRTT = computed(() => {
|
||||
const samples = active.value.flatMap(t => t.rtt == null ? [] : [t.rtt])
|
||||
return samples.length ? Math.round(samples.reduce((a, b) => a + b, 0) / samples.length * 10) / 10 : null
|
||||
})
|
||||
const healthyNodes = computed(() => data.resources.filter(n => n.status === 'online' && Date.now() - Date.parse(n.updatedAt) <= 90000).length)
|
||||
const recent = computed(() => data.tasks.slice(0, 5))
|
||||
const taskLabels: Record<string, string> = { start: '开机', shutdown: '正常关机', reboot: '重启', 'reset-session': '重置会话', 'collect-logs': '收集日志', sync: '同步资源' }
|
||||
const stats = computed(() => [
|
||||
{ title: '运行桌面', value: data.overview?.runningDesktops ?? 0, total: `/ ${data.overview?.desktopCount ?? 0}`, caption: '已纳管桌面的实际电源状态', path: '/desktops', icon: Monitor, warning: false },
|
||||
{ title: '活跃会话', value: data.overview?.activeSessions ?? 0, total: '个', caption: '终端已确认画面就绪', path: '/sessions', icon: Connection, warning: false },
|
||||
{ title: '网络 RTT', value: averageRTT.value ?? '—', total: averageRTT.value === null ? '' : 'ms', caption: averageRTT.value === null ? '当前无活动会话指标' : '活动会话采样均值', path: '/sessions', icon: Clock, warning: false },
|
||||
{ title: '异常任务', value: data.overview?.failedTasks ?? 0, total: '个', caption: '最近 24 小时失败或结果未确认', path: '/tasks', icon: Warning, warning: (data.overview?.failedTasks ?? 0) > 0 },
|
||||
])
|
||||
function exportReport() {
|
||||
const lines = [
|
||||
['VDI Cloud 运行快照', new Date().toLocaleString('zh-CN')],
|
||||
['指标', '数值'], ['运行桌面', String(data.overview?.runningDesktops ?? '')],
|
||||
['桌面总数', String(data.overview?.desktopCount ?? '')], ['在线终端', String(data.overview?.onlineTerminals ?? '')],
|
||||
['终端总数', String(data.overview?.terminalCount ?? '')], ['活动连接', String(data.overview?.activeSessions ?? '')],
|
||||
['网络 RTT(ms)', averageRTT.value === null ? '暂无数据' : String(averageRTT.value)],
|
||||
['最近24小时异常任务', String(data.overview?.failedTasks ?? '')],
|
||||
]
|
||||
const url = URL.createObjectURL(new Blob(['\ufeff' + lines.map(row => row.map(v => `"${v.replace(/"/g, '""')}"`).join(',')).join('\r\n')], { type: 'text/csv;charset=utf-8;' }))
|
||||
const link = document.createElement('a'); link.href = url; link.download = `vdi-overview-${new Date().toISOString().slice(0, 10)}.csv`; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>运行总览</h1><p class="subtext">云桌面、终端连接与资源健康,一处掌握。</p></div><div class="actions"><el-button @click="exportReport"><el-icon><Download /></el-icon><span>导出快照</span></el-button><el-button type="primary" @click="data.refresh"><el-icon><Refresh /></el-icon><span>刷新数据</span></el-button></div></div>
|
||||
<div class="stats"><button v-for="stat in stats" :key="stat.title" class="stat" @click="router.push(stat.path)"><div class="stat-label">{{ stat.title }}<el-icon :size="18"><component :is="stat.icon" /></el-icon></div><strong :class="{ 'tone-warn': stat.warning }">{{ stat.value }}<span class="stat-unit">{{ stat.total }}</span></strong><div class="stat-caption">{{ stat.caption }}</div></button></div>
|
||||
<div class="two-columns overview-grid">
|
||||
<section class="panel nodes-panel"><div class="panel-heading"><div><h2>计算资源水位</h2><p class="subtext">当前节点负载 · 每 30 秒同步 PVE</p></div><router-link to="/resources">资源详情 <el-icon><ArrowRight /></el-icon></router-link></div><div v-if="!data.resources.length" class="empty-panel"><div><div class="empty-icon"><el-icon :size="27"><Cpu /></el-icon></div><h3>尚未同步计算资源</h3><p class="subtext">接入 Proxmox 后查看节点使用情况</p></div></div><div v-for="node in data.resources" :key="node.id" class="node-block"><div class="node-heading"><div class="node-name"><div class="node-icon"><el-icon :size="21"><Cpu /></el-icon></div><div><strong>{{ node.name }}</strong><small>{{ node.provider === 'demo' ? '演示节点' : 'Proxmox 计算节点' }}</small></div></div><el-tag v-if="Date.now() - Date.parse(node.updatedAt) > 90000 && node.provider !== 'demo'" type="warning">数据过期</el-tag><StatusTag v-else :value="node.status" /></div><div class="node-meters"><div v-for="meter in [{ label: 'CPU 使用率', value: node.cpu }, { label: '内存使用率', value: node.memory }, { label: '存储使用率', value: node.storage }]" :key="meter.label"><div class="meter-label"><span>{{ meter.label }}</span><strong>{{ Math.min(100, Math.round(meter.value * 100)) }}<small>%</small></strong></div><el-progress :percentage="Math.min(100, Math.round(meter.value * 100))" :show-text="false" :stroke-width="8" :color="meter.value >= .85 ? 'var(--vdi-warn)' : 'var(--vdi-brand)'" /></div></div><p class="secondary node-sync">最近同步 {{ new Date(node.updatedAt).toLocaleString('zh-CN') }}</p></div></section>
|
||||
<section class="panel health-panel"><div class="panel-heading"><h2>资源健康度</h2><span class="secondary">当前快照</span></div><div class="health-row"><span><i class="health-dot" :class="healthyNodes === data.resources.length && data.resources.length ? 'tone-ok' : 'tone-warn'" />计算节点</span><strong>{{ healthyNodes }} / {{ data.resources.length }}</strong></div><div class="health-row"><span><i class="health-dot" :class="data.overview?.onlineTerminals ? 'tone-ok' : 'tone-warn'" />在线终端</span><router-link to="/terminals">{{ data.overview?.onlineTerminals ?? 0 }} / {{ data.overview?.terminalCount ?? 0 }}</router-link></div><div class="health-row"><span><i class="health-dot" :class="data.desktops.filter(d => !data.users.some(u => u.enabled && u.desktopIds.includes(d.id))).length ? 'tone-warn' : 'tone-ok'" />未授权桌面</span><router-link to="/users">{{ data.desktops.filter(d => !data.users.some(u => u.enabled && u.desktopIds.includes(d.id))).length }} 台</router-link></div><div class="health-row"><span><i class="health-dot tone-ok" />当前账号</span><span class="tone-ok"><el-icon><CircleCheck /></el-icon> 已认证</span></div><router-link to="/tasks" class="pending-summary"><el-icon :size="19"><Clock /></el-icon><div><strong>{{ data.tasks.filter(t => ['queued', 'running'].includes(t.status)).length }} 个任务等待回执</strong><small>查看任务进度与执行结果</small></div><el-icon><ArrowRight /></el-icon></router-link></section>
|
||||
</div>
|
||||
<section class="panel"><div class="panel-heading"><div><h2>最近任务</h2><p class="subtext">每次操作都有进度和结果记录</p></div><router-link to="/tasks">查看全部 <el-icon><ArrowRight /></el-icon></router-link></div><el-table :data="recent" empty-text="尚无执行任务"><el-table-column prop="targetName" label="操作目标" min-width="150" /><el-table-column label="操作" min-width="120"><template #default="{ row }">{{ taskLabels[row.action] || row.action }}</template></el-table-column><el-table-column label="状态" width="125"><template #default="{ row }"><StatusTag :value="row.status === 'running' ? '执行中' : row.status" /></template></el-table-column><el-table-column prop="message" label="执行结果" min-width="250" /></el-table></section>
|
||||
</template>
|
||||
<style scoped>
|
||||
.actions .el-icon{margin-right:7px}.stat-unit{color:var(--vdi-muted);font-size:14px;font-weight:500}.node-block+.node-block{border-top:1px solid var(--vdi-border);padding-top:22px;margin-top:22px}.node-heading{display:flex;justify-content:space-between;align-items:center;margin:24px 0 27px}.node-name{display:flex;align-items:center;gap:12px}.node-name strong{font-size:15px}.node-name small{display:block;color:var(--vdi-muted);font-size:11px;margin-top:4px}.node-icon{display:grid;place-items:center;width:42px;height:42px;background:var(--vdi-panel-2);border-radius:12px;color:var(--vdi-accent)}.node-meters{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:24px}.meter-label{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:16px}.meter-label>span{font-size:12px;color:var(--vdi-muted)}.meter-label strong{font-size:18px}.meter-label strong small{font-size:11px;font-weight:400;margin-left:2px}.node-sync{margin-top:29px}.health-row{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:18px 0;border-bottom:1px solid var(--vdi-border);font-size:13px}.health-row>span:first-child{display:flex;align-items:center}.health-row strong{font-size:14px}.health-row .tone-ok{display:flex;align-items:center;gap:5px}.pending-summary{display:flex;align-items:center;gap:12px;background:var(--vdi-panel-2);border-radius:12px;padding:15px;margin-top:21px;color:var(--vdi-text)}.pending-summary>.el-icon:first-child{color:var(--vdi-accent)}.pending-summary>div{flex:1}.pending-summary strong{font-size:12px;font-weight:500}.pending-summary small{display:block;font-size:11px;color:var(--vdi-muted);margin-top:5px}.panel-heading>a{display:flex;gap:4px;align-items:center}
|
||||
@media(max-width:600px){.node-meters{grid-template-columns:1fr;gap:20px}.node-heading{margin-top:18px}.node-sync{margin-top:20px}.meter-label{margin-bottom:10px}.overview-grid{gap:0}}
|
||||
</style>
|
||||
@@ -0,0 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { api } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
const auth = useAuth(), data = usePlatform(), { busy, run } = useAction()
|
||||
const syncing = computed(() => data.tasks.some(t => t.kind === 'resource' && ['queued', 'running'].includes(t.status)))
|
||||
const stale = (date: string, provider: string) => provider !== 'demo' && Date.now() - Date.parse(date) > 90000
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>计算资源</h1><p class="subtext">计算节点与资源同步状态</p></div><el-button v-if="auth.canAdmin" type="primary" :disabled="!data.settings?.pveConfigured || syncing" :loading="busy" @click="run(() => api.sync(), '同步任务已提交')">{{ syncing ? '同步中' : '同步 Proxmox' }}</el-button></div>
|
||||
<el-alert v-if="!data.settings?.pveConfigured" type="info" class="notice" :closable="false" title="尚未接入 Proxmox" description="由管理员在服务端设置访问地址、API Token 和 CA 证书后重启平台。当前演示节点不代表真实资源。" show-icon />
|
||||
<section class="panel"><el-table :data="data.resources" empty-text="尚无资源,配置接入后同步节点"><el-table-column prop="name" label="节点" min-width="150" /><el-table-column label="状态" width="125"><template #default="{ row }"><el-tag v-if="stale(row.updatedAt, row.provider)" type="warning">数据过期</el-tag><StatusTag v-else :value="row.status" /></template></el-table-column><el-table-column label="CPU" min-width="140"><template #default="{ row }"><el-progress :percentage="Math.min(100, Math.round(row.cpu * 100))" /></template></el-table-column><el-table-column label="内存" min-width="140"><template #default="{ row }"><el-progress :percentage="Math.min(100, Math.round(row.memory * 100))" /></template></el-table-column><el-table-column label="存储" min-width="140"><template #default="{ row }"><el-progress :percentage="Math.min(100, Math.round(row.storage * 100))" /></template></el-table-column><el-table-column label="来源 / 最近同步" min-width="190"><template #default="{ row }"><StatusTag :value="row.provider" /><div class="secondary">{{ new Date(row.updatedAt).toLocaleString('zh-CN') }}</div></template></el-table-column></el-table></section>
|
||||
</template>
|
||||
@@ -0,0 +1,30 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { Connection, Monitor, Refresh, VideoCamera, ArrowRight } from '@element-plus/icons-vue'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import { api, type Terminal } from '../api'
|
||||
const data = usePlatform(), auth = useAuth(), { busy, run, confirm } = useAction()
|
||||
const selectedId = ref('')
|
||||
const sessions = computed(() => data.terminals.filter(t => t.status === 'online' && t.sessionDesktopId && ['connected', 'connecting'].includes(t.sessionState || '')))
|
||||
const selected = computed(() => sessions.value.find(t => t.id === selectedId.value) || sessions.value[0])
|
||||
const desktop = computed(() => data.desktops.find(d => d.id === selected.value?.sessionDesktopId))
|
||||
const user = computed(() => data.users.find(u => u.terminalId === selected.value?.id))
|
||||
const pending = (id: string) => data.tasks.some(t => t.targetId === id && ['queued', 'running'].includes(t.status))
|
||||
async function disconnect(terminal: Terminal) {
|
||||
if (await confirm('断开远程会话', `将结束 ${terminal.name} 当前的串流连接,云桌面继续运行。`)) await run(() => api.terminalCommand(terminal.id, 'reset-session'), '断开命令已提交,等待终端回执')
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>远程会话</h1><p class="subtext">查看终端的连接状态与实际上报的会话指标</p></div><el-button @click="data.refresh"><el-icon><Refresh /></el-icon><span style="margin-left:7px">刷新会话</span></el-button></div>
|
||||
<div class="session-summary"><span><i class="health-dot tone-ok" />{{ sessions.filter(t => t.sessionState === 'connected').length }} 个已连接</span><span><i class="health-dot tone-warn" />{{ sessions.filter(t => t.sessionState === 'connecting').length }} 个连接中</span><router-link to="/terminals">管理终端 <el-icon><ArrowRight /></el-icon></router-link></div>
|
||||
<div v-if="selected" class="session-layout"><section class="panel session-workspace"><div class="panel-heading"><div><h2>{{ desktop?.name || '云桌面' }}</h2><p class="subtext">{{ selected.name }} · {{ user?.displayName || '设备绑定模式' }}</p></div><el-tag :type="selected.sessionState === 'connected' ? 'success' : 'warning'">{{ selected.sessionState === 'connected' ? '已连接' : '连接中' }}</el-tag></div><div class="preview-unavailable"><div class="preview-grid" /><div class="preview-content"><div class="preview-symbol"><el-icon :size="42"><Monitor /></el-icon></div><h3>{{ selected.sessionState === 'connected' ? '桌面正在终端显示' : '终端正在建立连接' }}</h3><p>管理控制台尚未接入远程画面预览</p><span>{{ desktop?.os }} · {{ desktop?.width }} × {{ desktop?.height }}</span></div><div class="preview-caption"><el-icon><VideoCamera /></el-icon>画面预览未接入</div></div><div class="session-device-strip"><span><el-icon><Connection /></el-icon>{{ selected.name }}</span><span class="mono">{{ selected.sn }}</span></div></section><section class="panel session-details"><div class="section-kicker">SESSION DETAILS</div><h2>会话信息</h2><p class="subtext">{{ desktop?.name || '云桌面' }}</p><dl><div><dt>连接状态</dt><dd :class="selected.sessionState === 'connected' ? 'tone-ok' : 'tone-warn'">{{ selected.sessionState === 'connected' ? '已连接' : '连接中' }}</dd></div><div><dt>桌面使用者</dt><dd>{{ user?.displayName || '未关联' }}</dd></div><div><dt>分辨率</dt><dd>{{ desktop ? `${desktop.width} × ${desktop.height}` : '暂无数据' }}</dd></div><div><dt>实际帧率</dt><dd>{{ selected.sessionState === 'connected' && selected.fps !== null ? `${selected.fps} FPS` : '暂无数据' }}</dd></div><div><dt>网络 RTT</dt><dd>{{ selected.sessionState === 'connected' && selected.rtt !== null ? `${selected.rtt} ms` : '暂无数据' }}</dd></div><div><dt>GPU / 显存</dt><dd class="secondary">尚未采集</dd></div><div><dt>最近心跳</dt><dd class="heartbeat-time">{{ selected.lastSeen ? new Date(selected.lastSeen).toLocaleTimeString('zh-CN') : '暂无数据' }}</dd></div></dl><p class="subtext session-note">网络 RTT 为设备采样值,不代表整体输入延迟。</p><router-link to="/terminals" class="details-link"><el-button style="width:100%">查看终端详情</el-button></router-link><el-button v-if="auth.canOperate" type="danger" plain class="disconnect-button" :disabled="busy || pending(selected.id)" @click="disconnect(selected)">{{ pending(selected.id) ? '等待命令回执' : '断开连接' }}</el-button></section></div>
|
||||
<section v-else class="panel empty-session"><div class="empty-icon"><el-icon :size="30"><Connection /></el-icon></div><h2>当前没有活动会话</h2><p class="subtext">在终端选择已授权的云桌面并连接后,会话会显示在这里。</p><router-link to="/terminals"><el-button type="primary" style="margin-top:24px">查看终端</el-button></router-link></section>
|
||||
<section v-if="sessions.length > 1" class="panel"><div class="panel-heading"><h2>全部会话</h2><span class="secondary">{{ sessions.length }} 个连接</span></div><div class="session-list"><button v-for="t in sessions" :key="t.id" class="session-option" :class="{ active: selected?.id === t.id }" @click="selectedId = t.id"><el-icon :size="20"><Monitor /></el-icon><div><strong>{{ data.desktops.find(d => d.id === t.sessionDesktopId)?.name || '云桌面' }}</strong><span>{{ t.name }}</span></div><span :class="t.sessionState === 'connected' ? 'tone-ok' : 'tone-warn'">{{ t.sessionState === 'connected' ? '已连接' : '连接中' }}</span></button></div></section>
|
||||
</template>
|
||||
<style scoped>
|
||||
.session-summary{display:flex;gap:24px;align-items:center;flex-wrap:wrap;font-size:12px;color:var(--vdi-muted);margin-bottom:22px}.session-summary>span{display:flex;align-items:center}.session-summary>a{margin-left:auto;display:flex;gap:5px;align-items:center}.session-layout{display:grid;grid-template-columns:minmax(0,1fr) 310px;gap:20px}.session-workspace{padding:22px 22px 0;overflow:hidden}.preview-unavailable{position:relative;background:var(--vdi-bg);border:1px solid var(--vdi-border);border-radius:14px;min-height:350px;aspect-ratio:16/10;display:grid;place-items:center;overflow:hidden}.preview-grid{position:absolute;inset:0;background-image:linear-gradient(var(--vdi-border) 1px,transparent 1px),linear-gradient(90deg,var(--vdi-border) 1px,transparent 1px);background-size:35px 35px;opacity:.18;mask-image:radial-gradient(ellipse at center,#000,transparent 75%)}.preview-content{text-align:center;position:relative;padding:24px}.preview-symbol{width:96px;height:80px;background:var(--vdi-panel-2);border:1px solid var(--vdi-border);border-radius:20px;display:grid;place-items:center;margin:0 auto 24px;color:var(--vdi-accent)}.preview-content h3{font-size:18px}.preview-content p{color:var(--vdi-muted);font-size:13px;margin-top:12px}.preview-content>span{display:block;font-size:11px;color:var(--vdi-muted);margin-top:17px}.preview-caption{position:absolute;bottom:17px;left:19px;font-size:10px;color:var(--vdi-muted);display:flex;align-items:center;gap:6px}.session-device-strip{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:18px 0;flex-wrap:wrap;color:var(--vdi-muted);font-size:11px}.session-device-strip>span:first-child{display:flex;gap:7px;align-items:center}.session-details dl{margin:22px 0 0}.session-details dl>div{display:flex;justify-content:space-between;align-items:center;gap:14px;font-size:12px;padding:15px 0;border-bottom:1px solid var(--vdi-border)}.session-details dt{color:var(--vdi-muted)}.session-details dd{margin:0;font-weight:500;text-align:right}.session-note{font-size:11px;margin:20px 0}.details-link{display:block;margin-top:24px}.disconnect-button{width:100%;margin-top:10px}.disconnect-button.el-button{margin-left:0}.empty-session{text-align:center;padding:85px 28px;min-height:410px}.empty-session .subtext{max-width:400px;margin:12px auto 0}.session-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.session-option{border:1px solid var(--vdi-border);background:var(--vdi-panel-2);border-radius:12px;padding:17px;display:flex;gap:14px;align-items:center;text-align:left;color:var(--vdi-text);cursor:pointer}.session-option.active{border-color:var(--vdi-brand);background:var(--vdi-accent-soft)}.session-option>div{flex:1}.session-option strong{font-size:13px}.session-option>div>span{display:block;font-size:11px;color:var(--vdi-muted);margin-top:5px}.session-option>span{font-size:11px}
|
||||
@media(max-width:1100px){.session-layout{grid-template-columns:1fr}.session-list{grid-template-columns:1fr}.preview-unavailable{min-height:260px}}
|
||||
@media(max-width:600px){.empty-session{padding:60px 22px}.preview-unavailable{min-height:280px;aspect-ratio:auto}.session-workspace{padding:16px 16px 0}.session-summary{gap:15px}.preview-content h3{font-size:16px}.preview-content p{font-size:12px}}
|
||||
</style>
|
||||
@@ -0,0 +1,18 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { Connection, Lock, Setting, CircleCheck, Clock } from '@element-plus/icons-vue'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAuth } from '../stores/auth'
|
||||
const data = usePlatform(), auth = useAuth(), section = ref('platform')
|
||||
const sections = [{ id: 'platform', title: '平台接入', icon: Connection }, { id: 'permissions', title: '管理员权限', icon: Lock }, { id: 'capabilities', title: '功能范围', icon: Setting }]
|
||||
const planned = ['镜像模板与克隆发放', '专属 / 公共桌面池', 'GPU 资源绑定', '历史指标与告警', '终端策略下发', 'OTA 灰度与回滚']
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>系统设置</h1><p class="subtext">平台接入状态、访问权限与当前功能范围</p></div></div>
|
||||
<div class="settings-layout"><nav class="panel settings-nav" aria-label="设置分类"><button v-for="item in sections" :key="item.id" :class="{ active: section === item.id }" :aria-pressed="section === item.id" @click="section = item.id"><el-icon :size="17"><component :is="item.icon" /></el-icon>{{ item.title }}</button></nav><div class="settings-content"><section v-if="section === 'platform'" class="panel settings-panel"><div class="section-kicker">PLATFORM CONNECTION</div><h2>平台接入</h2><p class="subtext">统一查看管理服务、计算资源与终端通道</p><div class="setting-row"><div><strong>运行环境</strong><p>使用独立数据库保存平台业务数据</p></div><el-tag :type="data.settings?.mode === 'demo' ? 'warning' : 'success'">{{ data.settings?.mode === 'demo' ? '演示环境' : '现场联调环境' }}</el-tag></div><div class="setting-row"><div><strong>Proxmox 计算平台</strong><p>连接状态以最近同步任务结果为准</p></div><span :class="data.settings?.pveConfigured ? 'tone-ok' : 'secondary'"><i class="health-dot" />{{ data.settings?.pveConfigured ? '已配置' : '尚未配置' }}</span></div><div class="setting-row"><div><strong>终端管理通道</strong><p>设备注册、心跳、命令领取与执行回执</p></div><span class="setting-value">HTTPS</span></div><div class="setting-row"><div><strong>业务数据存储</strong><p>账号、设备、授权关系、任务与审计</p></div><span class="setting-value">PostgreSQL</span></div><div class="setting-row"><div><strong>当前管理员</strong><p>{{ auth.user?.displayName }}</p></div><span class="setting-value">{{ auth.user?.username }}</span></div><p class="settings-footnote">接入地址与访问凭据由服务端配置管理。</p></section><section v-else-if="section === 'permissions'" class="panel settings-panel"><div class="section-kicker">ACCESS CONTROL</div><h2>管理员权限</h2><p class="subtext">三种管理角色,按职责控制访问与操作</p><el-table :data="[{ name: '超级管理员', query: '允许', operate: '允许', assign: '允许' }, { name: '运维人员', query: '允许', operate: '允许', assign: '不允许' }, { name: '只读人员', query: '允许', operate: '不允许', assign: '不允许' }]" style="margin-top:26px"><el-table-column prop="name" label="角色" min-width="120" /><el-table-column prop="query" label="查看资源" min-width="110" /><el-table-column prop="operate" label="设备 / 桌面操作" min-width="145" /><el-table-column prop="assign" label="授权 / 接入" min-width="120" /></el-table><p class="settings-footnote">管理员账号与桌面使用者分开管理。管理员账号维护页面尚未开放。</p></section><section v-else class="panel settings-panel"><div class="section-kicker">PLATFORM CAPABILITIES</div><h2>功能范围</h2><p class="subtext">当前已接通的能力与后续开发范围</p><div class="capability-group"><h3>当前可用</h3><div class="capability-grid"><span v-for="name in ['登录与角色权限', '计算资源同步', '已有桌面纳管与电源管理', '终端注册与心跳', '用户桌面授权', '远程会话状态与重置', '诊断日志采集', '任务跟踪与操作审计']" :key="name"><el-icon class="tone-ok"><CircleCheck /></el-icon>{{ name }}</span></div></div><div class="capability-group"><h3>待接入</h3><div class="capability-grid"><span v-for="name in planned" :key="name"><el-icon class="secondary"><Clock /></el-icon>{{ name }}</span></div></div></section></div></div>
|
||||
</template>
|
||||
<style scoped>
|
||||
.settings-layout{display:grid;grid-template-columns:210px minmax(0,1fr);gap:20px;align-items:start}.settings-nav{padding:12px;display:grid;gap:5px}.settings-nav button{display:flex;gap:11px;align-items:center;border:0;padding:14px 15px;border-radius:11px;background:transparent;color:var(--vdi-muted);font-size:13px;text-align:left;cursor:pointer}.settings-nav button.active{background:var(--vdi-accent-soft);color:var(--vdi-accent);font-weight:600}.settings-nav button:hover{color:var(--vdi-accent)}.settings-panel{padding:28px}.setting-row{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:24px 0;border-bottom:1px solid var(--vdi-border);font-size:12px}.setting-row strong{font-size:13px;font-weight:550}.setting-row p{font-size:11px;color:var(--vdi-muted);margin-top:7px;line-height:1.7}.setting-row>span{flex-shrink:0}.setting-row .health-dot{width:6px;height:6px;margin-right:6px}.setting-value{color:var(--vdi-muted);font-size:12px}.settings-footnote{color:var(--vdi-muted);font-size:11px;line-height:1.8;margin-top:22px}.capability-group{margin-top:28px;padding-top:24px;border-top:1px solid var(--vdi-border)}.capability-group h3{font-size:13px;margin-bottom:20px}.capability-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:20px;font-size:12px}.capability-grid>span{display:flex;align-items:center;gap:9px}
|
||||
@media(max-width:1100px){.settings-layout{grid-template-columns:1fr}.settings-nav{display:flex;flex-wrap:wrap;margin-bottom:0}.settings-nav button{flex:1;white-space:nowrap;padding:12px;justify-content:center}.settings-panel{padding:22px}}
|
||||
@media(max-width:600px){.settings-nav{gap:3px;padding:8px}.settings-nav button{gap:6px;padding:10px 8px;font-size:11px}.settings-panel{padding:19px}.setting-row{gap:15px}.setting-row p{max-width:180px}.setting-row>span{font-size:10px}.capability-grid{grid-template-columns:1fr}}
|
||||
</style>
|
||||
@@ -0,0 +1,33 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
import { api, errorMessage } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { ElMessage } from 'element-plus'
|
||||
const auth = useAuth()
|
||||
async function downloadDiagnostics(id: string) {
|
||||
try {
|
||||
const diagnostic = await api.taskDiagnostics(id)
|
||||
const url = URL.createObjectURL(new Blob([JSON.stringify(diagnostic, null, 2)], { type: 'application/json' }))
|
||||
const link = document.createElement('a'); link.href = url; link.download = `${id}-diagnostics.json`; link.click(); URL.revokeObjectURL(url)
|
||||
} catch(e) { ElMessage.error(errorMessage(e)) }
|
||||
}
|
||||
const data = usePlatform(), tab = ref('tasks'), keyword = ref(''), status = ref(''), page = ref(1), selectedId = ref('')
|
||||
const selected = computed(() => data.tasks.find(t => t.id === selectedId.value))
|
||||
const labels: Record<string, string> = { start: '开机', shutdown: '正常关机', reboot: '重启', 'reset-session': '重置会话', 'collect-logs': '收集日志', sync: '同步资源', login: '登录', logout: '退出登录', create_user: '创建用户', enroll_terminal: '登记终端', update_bindings: '更新授权', import_desktop: '纳管桌面' }
|
||||
const filtered = computed(() => data.tasks.filter(t => `${t.targetName} ${t.id} ${t.actor}`.toLowerCase().includes(keyword.value.toLowerCase()) && (!status.value || t.status === status.value)))
|
||||
const rows = computed(() => filtered.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
const auditFiltered = computed(() => data.audits.filter(a => `${a.actor} ${a.target} ${a.action}`.toLowerCase().includes(keyword.value.toLowerCase())))
|
||||
const auditRows = computed(() => auditFiltered.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>任务与审计</h1><p class="subtext">提交记录、执行回执和最终结果分开显示</p></div><el-button @click="data.refresh">刷新</el-button></div>
|
||||
<section class="panel">
|
||||
<el-tabs v-model="tab" @tab-change="page = 1; keyword = ''; status = ''"><el-tab-pane label="执行任务" name="tasks" /><el-tab-pane label="操作审计" name="audit" /></el-tabs><div class="toolbar"><el-input v-model="keyword" placeholder="搜索目标 / 操作者 / 标识" aria-label="搜索任务" clearable @input="page = 1" /><el-select v-if="tab === 'tasks'" v-model="status" aria-label="任务状态筛选" placeholder="全部任务状态" clearable @change="page = 1"><el-option v-for="s in [{ value: 'queued', label: '排队中' }, { value: 'running', label: '执行中' }, { value: 'success', label: '成功' }, { value: 'failed', label: '失败' }, { value: 'timeout', label: '结果未确认' }]" :key="s.value" :label="s.label" :value="s.value" /></el-select></div>
|
||||
<el-table v-if="tab === 'tasks'" :data="rows" empty-text="尚无执行任务"><el-table-column label="操作目标 / 任务" min-width="200"><template #default="{ row }"><el-button link type="primary" @click="selectedId = row.id">{{ row.targetName }}</el-button><div class="mono secondary">{{ row.id.slice(0, 18) }}…</div></template></el-table-column><el-table-column label="操作" width="110"><template #default="{ row }">{{ labels[row.action] || row.action }}</template></el-table-column><el-table-column label="状态" width="125"><template #default="{ row }"><StatusTag :value="row.status === 'running' ? '执行中' : row.status" /></template></el-table-column><el-table-column prop="actor" label="操作者" width="110" /><el-table-column label="提交时间" min-width="170"><template #default="{ row }">{{ new Date(row.createdAt).toLocaleString('zh-CN') }}</template></el-table-column><el-table-column prop="message" label="执行结果" min-width="240" /></el-table>
|
||||
<el-table v-else :data="auditRows" empty-text="尚无审计记录"><el-table-column prop="actor" label="操作者" width="100" /><el-table-column label="操作" min-width="130"><template #default="{ row }">{{ labels[row.action] || row.action }}</template></el-table-column><el-table-column prop="target" label="对象" min-width="180" /><el-table-column label="结果" width="125"><template #default="{ row }"><StatusTag :value="row.result" /></template></el-table-column><el-table-column label="时间" min-width="175"><template #default="{ row }">{{ new Date(row.createdAt).toLocaleString('zh-CN') }}</template></el-table-column><el-table-column prop="requestId" label="请求标识" min-width="180" show-overflow-tooltip /></el-table>
|
||||
<el-pagination v-model:current-page="page" :total="tab === 'tasks' ? filtered.length : auditFiltered.length" :page-size="10" layout="total, prev, pager, next" />
|
||||
</section>
|
||||
<el-drawer :model-value="!!selected" title="任务详情" size="580px" @close="selectedId = ''"><el-descriptions v-if="selected" :column="1" border><el-descriptions-item label="任务 ID"><span class="mono">{{ selected.id }}</span></el-descriptions-item><el-descriptions-item label="目标">{{ selected.targetName }}</el-descriptions-item><el-descriptions-item label="操作">{{ labels[selected.action] || selected.action }}</el-descriptions-item><el-descriptions-item label="状态"><StatusTag :value="selected.status === 'running' ? '执行中' : selected.status" /></el-descriptions-item><el-descriptions-item label="结果">{{ selected.message }}</el-descriptions-item><el-descriptions-item label="操作者">{{ selected.actor }}</el-descriptions-item><el-descriptions-item label="PVE 任务标识"><span class="mono">{{ selected.providerRef || '无' }}</span></el-descriptions-item><el-descriptions-item label="更新时间">{{ new Date(selected.updatedAt).toLocaleString('zh-CN') }}</el-descriptions-item></el-descriptions><el-button v-if="selected && auth.canOperate && selected.action === 'collect-logs' && selected.status === 'success'" style="margin-top:20px" @click="downloadDiagnostics(selected.id)">下载诊断日志</el-button><p class="subtext" style="margin-top:22px">结果未确认时先核对实际设备状态,再决定是否重新提交。系统不会自动重放操作。</p></el-drawer>
|
||||
</template>
|
||||
@@ -0,0 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import { api, type Terminal, type TerminalAction } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
const auth = useAuth(), data = usePlatform(), { busy, run, confirm } = useAction()
|
||||
const keyword = ref(''), status = ref(''), page = ref(1), selectedId = ref(''), createVisible = ref(false), secret = ref(''), activationVisible = ref(false)
|
||||
const form = reactive({ sn: '', name: '', group: '' })
|
||||
const filtered = computed(() => data.terminals.filter(t => `${t.name} ${t.sn}`.toLowerCase().includes(keyword.value.toLowerCase()) && (!status.value || status.value === t.status)))
|
||||
const rows = computed(() => filtered.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
const selected = computed(() => data.terminals.find(t => t.id === selectedId.value))
|
||||
const labels = { reboot: '重启盒子', 'reset-session': '重置会话', 'collect-logs': '收集日志' }
|
||||
const desktopName = (id: string | null) => data.desktops.find(d => d.id === id)?.name || '无活动连接'
|
||||
const pending = (id: string) => data.tasks.some(t => t.targetId === id && ['queued', 'running'].includes(t.status))
|
||||
async function command(t: Terminal, action: TerminalAction) {
|
||||
const note = t.status === 'online' ? '将向终端提交命令并等待设备回执。' : '终端当前不在线,命令可能超时;不会显示为已执行成功。'
|
||||
if (await confirm(`${labels[action]} · ${t.name}`, note)) await run(() => api.terminalCommand(t.id, action), '命令已提交,等待终端回执')
|
||||
}
|
||||
async function enroll() { if (!form.sn.trim() || !form.name.trim()) return; if (await run(async () => { const r = await api.enroll(form); secret.value = r.activationSecret }, '终端已登记')) { createVisible.value = false; activationVisible.value = true; form.sn = ''; form.name = ''; form.group = '' } }
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>终端管理</h1><p class="subtext">设备身份、在线心跳与远程命令</p></div><el-button v-if="auth.canAdmin" type="primary" @click="createVisible = true">登记终端</el-button></div>
|
||||
<section class="panel"><div class="toolbar"><el-input v-model="keyword" placeholder="搜索终端名称 / SN" aria-label="搜索终端" clearable @input="page = 1" /><el-select v-model="status" placeholder="全部网络状态" aria-label="终端网络状态筛选" clearable @change="page = 1"><el-option label="在线" value="online" /><el-option label="离线" value="offline" /><el-option label="待激活" value="unregistered" /></el-select><span class="secondary">共 {{ filtered.length }} 台</span></div><el-table :data="rows" empty-text="暂无终端,先登记设备并完成激活"><el-table-column label="终端 / SN" min-width="185"><template #default="{ row }"><el-button link type="primary" @click="selectedId = row.id">{{ row.name }}</el-button><div class="mono secondary">{{ row.sn }}</div></template></el-table-column><el-table-column prop="group" label="分组" width="100" /><el-table-column label="网络状态" width="100"><template #default="{ row }"><StatusTag :value="row.status" /></template></el-table-column><el-table-column label="当前连接" min-width="150"><template #default="{ row }">{{ desktopName(row.sessionDesktopId) }}</template></el-table-column><el-table-column label="最近心跳" min-width="170"><template #default="{ row }">{{ row.lastSeen ? new Date(row.lastSeen).toLocaleString('zh-CN') : '尚未注册' }}</template></el-table-column><el-table-column label="操作" min-width="165"><template #default="{ row }"><div class="actions"><el-button link type="primary" @click="selectedId = row.id">详情</el-button><el-button v-if="auth.canOperate" link type="primary" :disabled="busy || pending(row.id)" @click="command(row, 'reboot')">重启盒子</el-button></div></template></el-table-column></el-table><el-pagination v-model:current-page="page" :total="filtered.length" :page-size="10" layout="total, prev, pager, next" /></section>
|
||||
<el-drawer :model-value="!!selected" title="终端详情" size="560px" @close="selectedId = ''"><template v-if="selected"><h2>{{ selected.name }}</h2><el-descriptions :column="1" border style="margin-top:22px"><el-descriptions-item label="设备 SN">{{ selected.sn }}</el-descriptions-item><el-descriptions-item label="网络状态"><StatusTag :value="selected.status" /></el-descriptions-item><el-descriptions-item label="Agent 版本">{{ selected.agentVersion || '尚未上报' }}</el-descriptions-item><el-descriptions-item label="配置版本">v{{ selected.configVersion }}</el-descriptions-item><el-descriptions-item label="当前连接">{{ desktopName(selected.sessionDesktopId) }}</el-descriptions-item><el-descriptions-item label="帧率">{{ selected.status === 'online' && selected.fps !== null ? `${selected.fps} FPS` : '暂无数据' }}</el-descriptions-item><el-descriptions-item label="网络 RTT">{{ selected.status === 'online' && selected.rtt !== null ? `${selected.rtt} ms` : '暂无数据' }}</el-descriptions-item></el-descriptions><p class="subtext" style="margin:20px 0">重置会话只结束终端连接,不会还原或关机云桌面。网络 RTT 不等于整体输入延迟。</p><div class="actions" v-if="auth.canOperate"><el-button :disabled="busy || pending(selected.id)" @click="command(selected, 'reboot')">重启盒子</el-button><el-button :disabled="busy || pending(selected.id)" @click="command(selected, 'reset-session')">重置会话</el-button><el-button :disabled="busy || pending(selected.id)" @click="command(selected, 'collect-logs')">收集日志</el-button></div></template></el-drawer>
|
||||
<el-dialog v-model="createVisible" title="登记终端" width="480px"><el-form label-position="top" @submit.prevent="enroll"><el-form-item label="设备 SN" required><el-input v-model="form.sn" maxlength="100" /></el-form-item><el-form-item label="终端名称" required><el-input v-model="form.name" maxlength="80" /></el-form-item><el-form-item label="分组"><el-input v-model="form.group" maxlength="80" /></el-form-item><div class="actions" style="justify-content:flex-end"><el-button @click="createVisible = false">取消</el-button><el-button type="primary" native-type="submit" :loading="busy" :disabled="!form.sn.trim() || !form.name.trim()">登记并生成激活信息</el-button></div></el-form></el-dialog>
|
||||
<el-dialog v-model="activationVisible" title="终端激活信息" width="530px" @closed="secret = ''"><p class="subtext" style="margin-bottom:16px">激活密钥只在此处显示一次,交给设备管理员配置。设备注册后即失效。</p><div class="secret mono" data-testid="activation-secret">{{ secret }}</div><template #footer><el-button type="primary" @click="activationVisible = false">已保存,关闭</el-button></template></el-dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,26 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import { api, type User } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
const auth = useAuth(), data = usePlatform(), { busy, run } = useAction()
|
||||
const keyword = ref(''), page = ref(1), createVisible = ref(false), bindingVisible = ref(false), selectedId = ref('')
|
||||
const createForm = reactive({ username: '', displayName: '' })
|
||||
const binding = reactive({ terminalId: null as string | null, desktopIds: [] as string[], enabled: true })
|
||||
const filtered = computed(() => data.users.filter(u => `${u.username} ${u.displayName}`.toLowerCase().includes(keyword.value.toLowerCase())))
|
||||
const rows = computed(() => filtered.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
const terminalName = (id: string | null) => data.terminals.find(t => t.id === id)?.name || '未关联'
|
||||
const desktopName = (id: string) => data.desktops.find(d => d.id === id)?.name || id
|
||||
function edit(u: User) { selectedId.value = u.id; binding.terminalId = u.terminalId; binding.desktopIds = [...u.desktopIds]; binding.enabled = u.enabled; bindingVisible.value = true }
|
||||
async function create() { if (!createForm.username.trim() || !createForm.displayName.trim()) return; if (await run(() => api.createUser(createForm), '用户已创建')) { createVisible.value = false; createForm.username = ''; createForm.displayName = '' } }
|
||||
async function save() { if (await run(() => api.updateBindings(selectedId.value, binding), '桌面授权已保存')) bindingVisible.value = false }
|
||||
const terminalTaken = (id: string) => data.users.some(u => u.id !== selectedId.value && u.terminalId === id)
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>用户与授权</h1><p class="subtext">每位用户可获得多个桌面;每台终端关联一位使用者</p></div><el-button v-if="auth.canAdmin" type="primary" @click="createVisible = true">新建用户</el-button></div>
|
||||
<section class="panel"><div class="toolbar"><el-input v-model="keyword" placeholder="搜索姓名 / 用户账号" aria-label="搜索用户" clearable @input="page = 1" /><span class="secondary">共 {{ filtered.length }} 位</span></div><el-table :data="rows" empty-text="暂无终端用户"><el-table-column label="用户 / 账号" min-width="160"><template #default="{ row }">{{ row.displayName }}<div class="secondary">{{ row.username }}</div></template></el-table-column><el-table-column label="关联终端" min-width="160"><template #default="{ row }">{{ terminalName(row.terminalId) }}</template></el-table-column><el-table-column label="可用桌面" min-width="220"><template #default="{ row }"><div v-for="id in row.desktopIds" :key="id">{{ desktopName(id) }}</div><span v-if="!row.desktopIds.length" class="secondary">尚未分配</span></template></el-table-column><el-table-column label="状态" width="100"><template #default="{ row }"><StatusTag :value="row.enabled ? 'enabled' : 'disabled'" /></template></el-table-column><el-table-column v-if="auth.canAdmin" label="操作" width="120"><template #default="{ row }"><el-button link type="primary" @click="edit(row)">编辑授权</el-button></template></el-table-column></el-table><el-pagination v-model:current-page="page" :total="filtered.length" :page-size="10" layout="total, prev, pager, next" /></section><p class="subtext">这里管理桌面使用者。平台管理员账号独立管理,不因拥有管理角色而自动获得桌面使用权。</p>
|
||||
<el-dialog v-model="createVisible" title="新建终端用户" width="480px"><el-form label-position="top" @submit.prevent="create"><el-form-item label="姓名" required><el-input v-model="createForm.displayName" maxlength="80" /></el-form-item><el-form-item label="用户账号" required><el-input v-model="createForm.username" maxlength="80" /></el-form-item><p class="subtext">首版使用设备绑定模式,此账号用于授权关系,不是桌面系统密码。</p><div class="actions" style="justify-content:flex-end;margin-top:22px"><el-button @click="createVisible = false">取消</el-button><el-button type="primary" native-type="submit" :disabled="!createForm.username.trim() || !createForm.displayName.trim()" :loading="busy">创建用户</el-button></div></el-form></el-dialog>
|
||||
<el-dialog v-model="bindingVisible" title="编辑桌面授权" width="540px"><el-form label-position="top" @submit.prevent="save"><el-form-item label="关联终端"><el-select v-model="binding.terminalId" placeholder="不关联终端" clearable @clear="binding.terminalId = null"><el-option v-for="t in data.terminals" :key="t.id" :label="`${t.name} / ${t.sn}`" :value="t.id" :disabled="terminalTaken(t.id)" /></el-select></el-form-item><el-form-item label="可用桌面(可多选)"><el-checkbox-group v-model="binding.desktopIds" style="display:grid"><el-checkbox v-for="d in data.desktops" :key="d.id" :value="d.id">{{ d.name }} · {{ d.os }}</el-checkbox></el-checkbox-group><p v-if="!data.desktops.length" class="subtext">尚无可授权桌面</p></el-form-item><el-form-item label="用户状态"><el-switch v-model="binding.enabled" active-text="启用" inactive-text="停用" /></el-form-item><p class="subtext">撤销授权会阻止后续连接申请;本版不会强制中断已经建立的串流。</p><div class="actions" style="justify-content:flex-end;margin-top:22px"><el-button @click="bindingVisible = false">取消</el-button><el-button type="primary" native-type="submit" :loading="busy">保存授权</el-button></div></el-form></el-dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"types": ["vite/client", "node"],
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts", "e2e/**/*.ts", "playwright.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: { port: 5180, strictPort: true, proxy: { '/api': process.env.VDI_API_PROXY || 'http://127.0.0.1:8088', '/healthz': process.env.VDI_API_PROXY || 'http://127.0.0.1:8088' } },
|
||||
build: { rollupOptions: { output: { manualChunks: { 'element-plus': ['element-plus'], framework: ['vue', 'vue-router', 'pinia'] } } } },
|
||||
})
|
||||
@@ -0,0 +1,2 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
export default defineConfig({ test: { include: ['src/**/*.test.ts'], environment: 'node' } })
|
||||
Reference in new issue
Block a user