Compare commits
75
Commits
8d24a5b2f2
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f7b01e4db | ||
|
|
b6026f9759 | ||
|
|
9f05aa20ea | ||
|
|
5ac692724d | ||
|
|
6134d49c16 | ||
|
|
eef485306f | ||
|
|
d87fa47e24 | ||
|
|
3fb7b4da8c | ||
|
|
18a9ce995d | ||
|
|
8276da0d45 | ||
|
|
b979b12286 | ||
|
|
249e8f8537 | ||
|
|
a47968496e | ||
|
|
a14f028402 | ||
|
|
65f92df8b7 | ||
|
|
6f2ff67300 | ||
|
|
e35abf6dc0 | ||
|
|
b1082f8465 | ||
|
|
bb5f554820 | ||
|
|
b2de05c6a6 | ||
|
|
853bcb7574 | ||
|
|
1439028833 | ||
|
|
b29b59c62f | ||
|
|
a98d9ddeee | ||
|
|
1bed1948b5 | ||
|
|
3b48430f05 | ||
|
|
938ec97cce | ||
|
|
e47b01beec | ||
|
|
4f9565a768 | ||
|
|
6d9541df9a | ||
|
|
6823fc4bb9 | ||
|
|
7d23169d95 | ||
|
|
13f645a503 | ||
|
|
b08486046b | ||
|
|
73a635c4cf | ||
|
|
85f64df1a5 | ||
|
|
7fdcb53dd9 | ||
|
|
26fde0369e | ||
|
|
56b9f1faf3 | ||
|
|
2f1f935e38 | ||
|
|
26fdbec479 | ||
|
|
91a0d00d88 | ||
|
|
ec5d839075 | ||
|
|
24291dd1b7 | ||
|
|
936b2cd343 | ||
|
|
8abc4210e8 | ||
|
|
14673f8802 | ||
|
|
47f97ac764 | ||
|
|
eb081a3914 | ||
|
|
8bbb9e9b0e | ||
|
|
a050e4ce58 | ||
|
|
8cbb867371 | ||
|
|
d15833cdc2 | ||
|
|
ec1566a80e | ||
|
|
c6b6f88c93 | ||
|
|
23fcc8408f | ||
|
|
72179f2389 | ||
|
|
791f49e987 | ||
|
|
ee6f449bf1 | ||
|
|
d739b2c9a1 | ||
|
|
4b5fde5915 | ||
|
|
0fa1ace57a | ||
|
|
e51100b3fd | ||
|
|
b982e36487 | ||
|
|
83e75367c2 | ||
|
|
5ba7eb87d3 | ||
|
|
c81c35331e | ||
|
|
d06893e421 | ||
|
|
475850e682 | ||
|
|
b3a670aedc | ||
|
|
162dcc1e02 | ||
|
|
61127fb714 | ||
|
|
f74d3ceadf | ||
|
|
24529b80b0 | ||
|
|
c25bc2908a |
No files matched your search
@@ -0,0 +1,12 @@
|
||||
.git
|
||||
**/node_modules
|
||||
**/dist
|
||||
**/test-results
|
||||
**/playwright-report
|
||||
**/.env
|
||||
**/.env.local
|
||||
**/*.exe
|
||||
terminal
|
||||
docs
|
||||
tools
|
||||
.local
|
||||
@@ -0,0 +1,2 @@
|
||||
# Patches are applied to LF sources on the Linux terminal.
|
||||
terminal/moonlight/patches/*.patch text eol=lf
|
||||
+22
@@ -1,3 +1,25 @@
|
||||
build/
|
||||
CMakeFiles/
|
||||
CMakeCache.txt
|
||||
*.o
|
||||
*.so
|
||||
*.log
|
||||
*.tmp
|
||||
.zcode/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
~$*
|
||||
test-output/
|
||||
screenshots/
|
||||
.DS_Store
|
||||
.playwright-cli/
|
||||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
playwright-report/
|
||||
coverage/
|
||||
test-results/
|
||||
.local/
|
||||
*.exe
|
||||
@@ -1,79 +1,11 @@
|
||||
# 继续开发前必读
|
||||
|
||||
完整对话总结在:`D:\DAIMA\vdi-cloud\PROJECT_CONTEXT.md`
|
||||
更新:2026-11-09。状态与计划统一维护在主题文档,本文件只保留导航,避免多处历史“最新”描述相互矛盾。
|
||||
|
||||
## 当前状态
|
||||
- 项目目录:`D:\DAIMA\vdi-cloud`
|
||||
- 终端盒子:RK3528 PRO DDR4,Armbian Ubuntu Noble,aarch64,IP `192.168.1.188`
|
||||
- 当前图形:LightDM + Xorg;正式文档要求 Weston + Wayland + Qt,当前只是 POC
|
||||
- Proxmox:9.2.2 节点 `starhe`。VM 100 win10-test `192.168.1.70`(Sunshine/Moonlight 云桌面);
|
||||
VM 101 kylin-test `192.168.1.71`(test1)、VM 102 ubuntu-test `192.168.1.72`(test2),
|
||||
密码均 `yx66668888`,SSH 可登、图形会话在跑,**尚未装 Sunshine**,暂不能串流
|
||||
- `kiosk-shell`(Qt/C++):**开机直进桌面列表**(2026-10-30 起,设备 SN 即用户自动登录,
|
||||
登录页代码保留待平台正式认证接入)→ 选择桌面 → Moonlight 会话;**RDP 代码已于 2026-10-29
|
||||
全部删除**(git 历史可查),Moonlight 是唯一会话通道,无 freerdp 构建依赖
|
||||
- 新增退出三层与会话过场层:`Ctrl+Alt+Shift+Q` 退串流回列表;列表页"退出登录";
|
||||
登录页无退出按钮(退出终端只在管理菜单);点连接有全屏过场层,首帧后淡出。
|
||||
详见 `docs/moonlight-kiosk-20261028.md` 2026-10-29 下午节
|
||||
- 代码位置:`terminal/kiosk-shell`
|
||||
- 远程安装路径:`~/vdi-terminal/bin/`(`kiosk-shell`、`vdi-kiosk-monitor`、`vdi-moonlight`)
|
||||
1. 阅读[项目上下文](PROJECT_CONTEXT.md)与[当前状态](docs/current-status.md),再查看 `git status`,保留已有改动。
|
||||
2. 终端进出窗口、显示守护和当前客户端 SHA 见[终端说明](docs/terminal-guide.md);Linux 光标升级/回退必须匹配二进制与 profile SHA。
|
||||
3. Linux 硬编仍未打通;Intel 直通与显存 64MB 试验已回退。合成回显不等于物理端到端延迟,详见[云桌面说明](docs/desktop-guide.md)。
|
||||
4. 日常监控在独立 `D:\DAIMA\vdi-monitor`;开发证据、失败记录与回退仍保留在本仓库,见[运维说明](docs/operations.md)。
|
||||
5. VPN/Clash、软件白名单与品牌兜底画面只列[未来计划](docs/roadmap.md),目前不实施。
|
||||
|
||||
## GPU 直通进行中(2026-10-30 下午,见 moonlight-kiosk 文档当日追加节)
|
||||
- 宿主侧已就绪:nouveau 已黑名单、GPU 在 vfio-pci、IOMMU 组 2(root port+GPU)
|
||||
- 关键坑:vfio 清零 Subsystem ID(必须 `x-pci-sub-vendor-id/device-id` 注入 1558:6557);
|
||||
移动卡 vBIOS 需 sysfs 抽取(/usr/share/kvm/gtx965m.rom);NVIDIA 安装器在 SYSTEM 会话
|
||||
挂起(用 7zr 解包 + pnputil);582.78 绑定后 D3D 全灭已换 566.36(D3D 待验证)
|
||||
- **当前 VM 100 未挂 GPU**:另一并行会话在改配置(hv_vendor_id 方案),本会话已停手避撞,
|
||||
两个会话不要同时改 VM 100 配置!
|
||||
- Sunshine 配对 2026.914 改为"Web UI 批准式":`moonlight pair --pin NNNN` +
|
||||
`GET /api/csrf-token` + `POST /api/pin {pairing_id,pin}`;Web 凭据 vdiadmin/VdiPass2026;
|
||||
删 sunshine_state.json = 全部失配;盒子 Moonlight 配置目录缓存旧 uniqueid 会卡死配对
|
||||
|
||||
## 必须遵守
|
||||
- 所有实现严格参考用户提供的两个正式 Word 和会议纪要;文档未确定的技术只能标记待调研,不得擅自定版。
|
||||
- 终端先做,后接自研管理平台 API;终端不直接调用 Proxmox API。
|
||||
- 正式状态机:`BOOT -> CONFIG -> CONNECTING -> SESSION -> RECONNECT -> ERROR`
|
||||
- 正式 Kiosk 选型:Weston + Wayland + Qt;会话通道统一 Moonlight(RDP 已删,勿在代码里复活协议分支)。
|
||||
- `/cert:ignore`、空密码仅限局域网 POC。
|
||||
- 项目经理新增待调研:RDP 是否适合 GPU/CAD/3D;研究 Moonlight/Sunshine,但不要在调研前删除 RDP、确定 Moonlight 参数或定版双协议。
|
||||
|
||||
## 已知关键结论
|
||||
- WiFi:约 -47 dBm,协商约 200 Mbps,零丢包/重传;卷帘问题不能简单归因于 WiFi。
|
||||
- HDMI 当前原生:`1920x1440@75Hz`(10-23 记录);2026-10-28 实测盒子系统已是 `1920x1080@60Hz`,
|
||||
与 Sunshine 侧虚拟显示器一致,串流 1:1 无缩放。以现场 `xrandr` 为准。
|
||||
- `/dev/mpp_service`、`/dev/rga` 存在,但 `mppvideodec` GStreamer 插件未确认;Weston/DRM 零拷贝待验证。
|
||||
- FreeRDP 3:`gdi_init` 必须在 PostConnect;NLA 空密码传 `strdup("")`;BGRX32 需转换为 Qt RGB;`/gfx` 是能力组合语义。
|
||||
- Moonlight/Sunshine(2026-10-28 实测):Windows 防火墙挡 ICMP,ping 不通不代表不通,
|
||||
可达性判断必须用 TCP 探测;`moonlight-qt` 的 app id 会随服务端重装失效,
|
||||
命令行要用应用名 `Desktop`;RK3528 上 `--video-decoder auto` 会选到不可用的
|
||||
`h264_v4l2m2m`,必须显式 `software`。
|
||||
- **21.6 FPS 上限根因(2026-10-29 修正)**:不是 x264 编码算力——ultrafast 前后帧率分毫不差,
|
||||
串流中 VM CPU 仅 0.5%、sunshine 累计 14 秒 CPU/3 分钟会话,鼠标运动也不变;
|
||||
真正瓶颈在虚拟显示/捕获节奏(MttVDD 呈现 + Desktop Duplication 脏帧 + QEMU 显示栈,
|
||||
VM CPU 型号 `QEMU Virtual CPU version 2.5+` 未透传宿主 AVX2)。
|
||||
根治 = GPU 直通(NVENC + 真实显示栈);备选 = VirtIO-GPU / cpu=host 排除 QEMU 显示栈因素。
|
||||
客户端解码 10~15 ms、网络丢包 0%、延迟 3 ms,链路健康。
|
||||
|
||||
## Web 控制台(2026-10-28 方案确认)
|
||||
- `console/` 是管理员 Web 管理控制台,不是 RK3528 盒子的用户登录页。
|
||||
- 正式技术栈:Vue3 + Vite + TypeScript 严格模式 + Element Plus;后端通过 api-gateway,JWT + RBAC。
|
||||
- 页面:仪表盘、终端管理、桌面管理、用户与绑定、GPU 池、监控、OTA、审计日志。
|
||||
- 角色:超级管理员、运维、只读。
|
||||
- 终端产品流程仍应是 `kiosk-shell 登录/首配 -> 桌面列表 -> 获取短期连接票据 -> RDP/Moonlight 会话`;
|
||||
当前开机直连 Moonlight 仅是串流技术验证,不是最终产品登录流程。
|
||||
- 开发策略:先做功能骨架、Mock API、OpenAPI 契约、RBAC 与 E2E;项目经理 UI 稿到后替换视觉层。
|
||||
- 完整方案:`docs/web-console-mvp-plan-20261028.md`。
|
||||
|
||||
## 尚未完成
|
||||
- 服务端 GPU 直通:GPU 为 CLEVO 准系统上的 GM204M/965M(10de:13d9,宿主被 nouveau 占用需解绑);
|
||||
**IOMMU 已启用**(组 2 = root port 00:01.0 + GPU 01:00.0,整组直通);VM 内需装 R580 legacy 驱动。
|
||||
操作单与 GPU 看板见 `docs/gpu-passthrough-20261030.md`,看板 `http://192.168.1.51:8090/`(systemd 自启)
|
||||
- RK3528 VPU 硬解(h264_v4l2m2m 等缺可用设备,需 MPP FFmpeg 补丁或 V4L2 request 驱动)
|
||||
- 2K 分辨率链路验证(虚拟显示器 + 盒子显示模式需同步调整)
|
||||
- Weston/DRM/mppvideodec
|
||||
- 后端 API 注册、配置、MQTT 心跳(Moonlight 路径目前是本地静态配置)
|
||||
- 终端音频出音现场确认
|
||||
- 协议最终选型定版(RDP / Moonlight / 双协议,需实测数据 + 产品方案共同确认)
|
||||
- 监控与运维脚本、OTA、USB 重定向等终端其余能力
|
||||
|
||||
先读 `PROJECT_CONTEXT.md`,再查看 `git status`,不要丢弃未提交改动。
|
||||
整理前本文件与 PROJECT_CONTEXT、README 的完整内容,以及 35 份原专题文档,都可通过[历史归档](docs/archive/README.md)恢复。历史结论按日期与当前证据核对,不直接当作现网状态。
|
||||
+11
-403
@@ -1,409 +1,17 @@
|
||||
# 数字员工 VDI 云终端项目上下文
|
||||
# 项目上下文入口
|
||||
|
||||
> 这是本项目后续继续开发时的必读上下文。所有实现必须优先以项目经理提供的正式文档和会议纪要为准;文档未明确的地方只能标记为待确认/待调研,不能擅自定版。
|
||||
>
|
||||
> 本文件整理自截至 2026-10-23 的完整开发对话。
|
||||
更新:2026-11-09。旧文件主要记录 10 月的 RDP、软解、1080p 和开机直连试验,已完整保存在[历史归档](docs/archive/README.md)的同名文件中;继续开发以以下主题文档核对当前状态。
|
||||
|
||||
## 1. 项目目标
|
||||
- [当前架构、环境与验证边界](docs/current-status.md)
|
||||
- [终端启动、进出、快捷键、构建](docs/terminal-guide.md)
|
||||
- [三系统显示、输入、USB 与电源策略](docs/desktop-guide.md)
|
||||
- [监控分工、日志与恢复](docs/operations.md)
|
||||
- [未来计划及暂缓范围](docs/roadmap.md)
|
||||
|
||||
项目是“云-管-端” VDI 云桌面方案:
|
||||
当前协议主线为 Moonlight/Sunshine;终端 Qt/C++,现场 LightDM/Xorg 独占 kiosk,正式目标 Weston/Wayland。盒子开机直接进入选择页;11-09 已接通真实平台认证、授权桌面和票据,现场配置见[真实接入说明](docs/cloud-live-integration.md)。平台 Go,控制台 Vue3/TypeScript/Element Plus,Agent/OTA/USB 方向为 Rust;已有 POC 和完整产品交付需区分。
|
||||
|
||||
```text
|
||||
RK3528 云终端
|
||||
-> 终端接入程序
|
||||
-> 自研管理平台 API
|
||||
-> Proxmox VE 管理的虚拟机
|
||||
-> Windows / Ubuntu / 麒麟 / 后续安卓桌面
|
||||
```
|
||||
终端不调用 PVE API、不保存 PVE 管理凭据。`console/` 是管理员 Web 控制台,和盒子客户选择页不同。盒子开关不会自动控制 VM 生命周期;客户图形电源入口限制保留管理员维护能力。
|
||||
|
||||
终端侧最终职责:
|
||||
原始需求来自 `docs/` 三份 Word 与用户提供的会议资料,出处见[索引](docs/README.md)。旧文档中的协议建议、状态机和失败实验不自动覆盖后续已确认的实现;未定事项写入计划,不能把猜测写为定版。
|
||||
|
||||
- 开机进入 Kiosk/首配登录页;
|
||||
- WiFi/有线联网;
|
||||
- 终端注册、心跳、配置下发、日志上报;
|
||||
- 连接远程桌面;
|
||||
- 显示远程画面并传递键盘、鼠标、U 盘等外设;
|
||||
- 断线重连;
|
||||
- 独立 Monitor 看门狗;
|
||||
- A/B OTA;
|
||||
- 后续使用 VPU/DRM 硬件解码与零拷贝显示。
|
||||
|
||||
项目经理新增方向:RDP 可能不适合 GPU/CAD/3D 高质量低延迟串流,周一需要调研 RDP 与 Moonlight。Moonlight 只作为待调研/待验证的协议方向,不能在未验证前替换 RDP 或擅自确定端口、认证字段、嵌入方式。
|
||||
|
||||
## 2. 权威需求来源
|
||||
|
||||
1. `E:\Desktop\数字员工\VDI云终端产品方案-定版摘要(1).docx`
|
||||
- 产品定版 v2.1。
|
||||
- 规定 RK3528 终端、2K 默认/4K 上限、FreeRDP 3、GStreamer + mppvideodec、Proxmox/KVM/VFIO、GPU 算力池、管理平台等。
|
||||
2. `E:\Desktop\数字员工\VDI云桌面软件开发方案(1).docx`
|
||||
- 软件开发 v1.0。
|
||||
- 规定 monorepo、终端/云端/控制台技术栈、20 项需求追踪矩阵、测试层次、M1-M4 里程碑。
|
||||
3. `E:\Documents\xwechat_files\wxid_q6y4us6kip0g22_aa63\msg\file\2026-10\export_1792654201375.docx`
|
||||
- 会议纪要。
|
||||
- 规定当前优先:先拿盒子、终端基础连接、Proxmox 逻辑/API、2K/4K/发热/网络验证、Monitor、OTA 后置;张帅协助 P100 GPU 验证。
|
||||
4. 会议纪要图片:项目技术要点思维导图。
|
||||
|
||||
核心纪律:如果代码实现与上述文档不一致,先指出偏差并等待确认;不能以“更快”或“更方便”为理由改用未定版技术栈。
|
||||
|
||||
## 3. 正式技术选型与边界
|
||||
|
||||
正式开发方案 2.1/2.2 节:
|
||||
|
||||
```text
|
||||
vdi-cloud/
|
||||
├─ terminal/
|
||||
│ ├─ meta-vdi/ # Yocto:BSP/内核/设备树/U-Boot/Kiosk/Agent 配方
|
||||
│ ├─ kiosk-shell/ # Weston + 全屏 Qt 壳
|
||||
│ ├─ freerdp-rk/ # FreeRDP 3 fork + MPP/VPU 硬解补丁
|
||||
│ ├─ vdt-agent/ # Rust:注册/心跳/命令/日志
|
||||
│ ├─ ota-updater/ # Rust:manifest/签名/A-B/回滚
|
||||
│ └─ usb-monitor/ # Rust:udev/挂载/重定向策略
|
||||
├─ platform/ # Go 云端服务
|
||||
├─ console/ # Vue3 + TS + Element Plus
|
||||
├─ deploy/ # compose/Helm/离线包
|
||||
├─ docs/ # OpenAPI/MQTT/DB schema
|
||||
└─ tools/ # 烧录/压测/CI
|
||||
```
|
||||
|
||||
终端技术栈定版:
|
||||
|
||||
- Kiosk 壳:C/C++ + Qt,目标显示环境 Weston/Wayland;
|
||||
- FreeRDP 插件:C/C++;
|
||||
- Agent/OTA/USB:Rust;
|
||||
- 协议主线:FreeRDP 3;SPICE 备用;自研 H.265 over QUIC 只作为后续预留;
|
||||
- 云端:Go;
|
||||
- 前端:Vue3 + TypeScript + Element Plus;
|
||||
- 数据库:PostgreSQL + VictoriaMetrics;
|
||||
- 通信:HTTPS + MQTT;
|
||||
- 云端底座:Proxmox VE + KVM/QEMU + VFIO;
|
||||
- GPU:NVIDIA CUDA、华为 CANN 等按卡型池化;终端不安装 GPU 计算组件。
|
||||
|
||||
开发方案 3.2 对 kiosk-shell 的明确要求:
|
||||
|
||||
- 技术:Weston(Wayland)+ 全屏 Qt 壳进程;
|
||||
- 状态机:`BOOT -> CONFIG -> CONNECTING -> SESSION -> RECONNECT -> ERROR`;
|
||||
- 首配页:SN 绑定、WiFi 扫码、服务器地址;
|
||||
- 状态条:网络、会话、OTA 进度;
|
||||
- FreeRDP:以 `libfreerdp3` API 内嵌,不拉起外部进程;
|
||||
- 全局热键:`Ctrl+Alt+Shift+M` 呼出管理菜单。
|
||||
|
||||
当前实现是在现有 Armbian 的 LightDM + Xorg 环境中先完成 Qt/Kiosk POC;这不是对正式 Weston 选型的替代。Weston/DRM 必须继续验证。
|
||||
|
||||
## 4. 盒子与联调环境
|
||||
|
||||
### 盒子
|
||||
|
||||
- 型号:RK3528 PRO DDR4;
|
||||
- OS:Armbian v25.05 rolling,Ubuntu Noble 用户空间;
|
||||
- Kernel:`6.1.115-vendor-rk35xx`;
|
||||
- 架构:`aarch64`;
|
||||
- 内存:约 3.83 GB;
|
||||
- 存储:约 29 GB;
|
||||
- IP:`192.168.1.188`;
|
||||
- SSH:`ssh armbian@192.168.1.188`;
|
||||
- 图形:LightDM + Xorg,当前不是 Wayland;
|
||||
- 显示器:`HDMI-1 1920x1440 @ 75Hz`,没有 2560x1440 EDID 模式;
|
||||
- DRM:`/dev/dri/card0`、`card1`、`renderD128`、`renderD129`;
|
||||
- 权限:用户已在 `video`、`render` 组;
|
||||
- 温度:空载约 53°C;
|
||||
- WiFi:`wlan0`,SSID `YXTech`,信号约 -47 dBm,协商约 200 Mbit/s,实测无丢包/重传;
|
||||
- 设备节点:`/dev/mpp_service`、`/dev/rga` 存在;
|
||||
- OpenGL:Mali450,Mesa 25.0.7;Xorg 日志显示 modesetting + glamor initialized。
|
||||
|
||||
### 已安装环境
|
||||
|
||||
- gcc/g++ 13;
|
||||
- make、cmake 3.28、ninja、pkg-config、git;
|
||||
- Qt5 5.15.13(Core/Gui/Widgets/Wayland 包);
|
||||
- Weston 13.0.0;
|
||||
- `freerdp3-dev` 3.32.1;
|
||||
- `freerdp3-x11`,实际命令:`xfreerdp3`;
|
||||
- `freerdp3-wayland`,实际命令:`wlfreerdp3`,但当前没有 Wayland 会话;
|
||||
- `mesa-utils`;
|
||||
- `xdotool`(测试用);
|
||||
- 当前未确认 `mppvideodec`,Ubuntu 官方源没有 Rockchip MPP GStreamer 插件。
|
||||
|
||||
### apt 源
|
||||
|
||||
旧 `/etc/apt/sources.list` 中普通 Ubuntu 源会造成 ARM64 404,已备份为 `sources.list.bak` 并注释。有效配置在 `/etc/apt/sources.list.d/ubuntu.sources`,使用 TUNA 的 `ubuntu-ports`。
|
||||
|
||||
不要执行:
|
||||
|
||||
- `sudo apt upgrade`:曾显示约 298 个包待升级,当前不要整体升级;
|
||||
- `do-release-upgrade`:不要升级系统版本;
|
||||
- 不要在盒子上安装 Proxmox,盒子是 ARM64 终端,不是 Proxmox 主机。
|
||||
|
||||
本机已经给盒子安装了 SSH 公钥(注释 `zcode-dev`),可以免密远程执行:
|
||||
|
||||
```bash
|
||||
ssh armbian@192.168.1.188
|
||||
```
|
||||
|
||||
SSH 中执行图形命令要带:
|
||||
|
||||
```bash
|
||||
export DISPLAY=:0
|
||||
export XAUTHORITY=/home/armbian/.Xauthority
|
||||
```
|
||||
|
||||
## 5. Proxmox/Windows 联调环境
|
||||
|
||||
- Proxmox VE:9.2.2;
|
||||
- 节点:`starhe`;
|
||||
- VM:101,名称 `win10-gongchang01`;
|
||||
- Windows:Windows 10 22H2 专业版;
|
||||
- VM IP:`192.168.1.70`;
|
||||
- RDP:TCP 3389;
|
||||
- 用户:`test1`;
|
||||
- 当前 POC 允许空密码登录,正式环境不能使用空密码。
|
||||
|
||||
边界:终端最终不应直接调用 Proxmox API。最终关系是:
|
||||
|
||||
```text
|
||||
终端 -> 自研管理平台 API -> Proxmox API -> 虚拟机
|
||||
终端 -> 管理平台返回的桌面连接地址/网关 -> RDP 或其他协议
|
||||
```
|
||||
|
||||
## 6. 已完成工作
|
||||
|
||||
### 6.1 网络与远程桌面基础验证
|
||||
|
||||
已完成:
|
||||
|
||||
- 盒子 WiFi 联通;
|
||||
- Windows 10 VM 可达;
|
||||
- 手工命令 `xfreerdp3` 成功显示 Windows 10 桌面;
|
||||
- 键盘鼠标可操作;
|
||||
- 退出全屏最可靠方式:从 SSH 执行 `pkill -f xfreerdp3`;
|
||||
- 当前 X11 环境下不要直接在 SSH 无 DISPLAY 会话中启动 GUI。
|
||||
|
||||
### 6.2 monorepo
|
||||
|
||||
项目已在:
|
||||
|
||||
```text
|
||||
D:\DAIMA\vdi-cloud
|
||||
```
|
||||
|
||||
已初始化 git。最近已提交:
|
||||
|
||||
```text
|
||||
589cde4 feat(kiosk-shell): FreeRDP 3 内嵌客户端跑通,登录页可进入远程桌面
|
||||
419630f feat(kiosk-shell): 首版登录页与状态机骨架
|
||||
```
|
||||
|
||||
当前 git 在日报暂停开发时有未提交改动,主要是 Monitor、心跳、网络显示修复等。不要丢弃这些改动。
|
||||
|
||||
### 6.3 kiosk-shell
|
||||
|
||||
位置:`D:\DAIMA\vdi-cloud\terminal\kiosk-shell`
|
||||
|
||||
已实现:
|
||||
|
||||
- Qt5 全屏登录页;
|
||||
- 深色 UI;
|
||||
- SN 显示;
|
||||
- 服务器地址、账号、密码、显示分辨率;
|
||||
- 记住连接参数;
|
||||
- 本地配置文件:`~/.config/vdi-terminal/client.conf`;
|
||||
- 状态机:`BOOT/CONFIG/CONNECTING/SESSION/RECONNECT/ERROR`;
|
||||
- `Ctrl+Alt+Shift+M` 管理菜单;
|
||||
- RDP 会话状态;
|
||||
- 连接断开后重连状态;
|
||||
- 主进程心跳文件设计:`/tmp/vdi-kiosk.heartbeat`;
|
||||
- CMake + Ninja 原生 ARM64 编译通过过多次。
|
||||
|
||||
当前盒子上的实际运行路径:
|
||||
|
||||
```text
|
||||
~/vdi-terminal/bin/kiosk-shell
|
||||
```
|
||||
|
||||
配置示例:
|
||||
|
||||
```text
|
||||
version=1
|
||||
sn=...
|
||||
deviceKey=
|
||||
server=192.168.1.70
|
||||
username=test1
|
||||
password=
|
||||
wifiSsid=
|
||||
wifiPassword=
|
||||
resolution=1920x1440
|
||||
remember=1
|
||||
```
|
||||
|
||||
### 6.4 libfreerdp3 内嵌
|
||||
|
||||
已实现 `rdp_session.cpp/h`,不拉起外部 `xfreerdp3` 进程:
|
||||
|
||||
```text
|
||||
freerdp_new()
|
||||
freerdp_context_new_ex()
|
||||
freerdp_connect()
|
||||
FreeRDP 3 AuthenticateEx
|
||||
GDI primary buffer
|
||||
Qt QImage/QLabel 显示
|
||||
```
|
||||
|
||||
已实测修复的坑:
|
||||
|
||||
1. `gdi_init` 必须放在 `PostConnect` 中;连接前调用会在 `gdi_init_ex` 段错误;
|
||||
2. 不能依赖扩展 `ContextSize` 保存自定义指针,`gdi_init_ex` 可能重新分配 context 导致段错误;当前使用按 `freerdp*` 的静态注册表和 `RdpgfxClientContext.custom`;
|
||||
3. NLA 认证回调空密码必须传 `strdup("")`,不能传 `nullptr`,否则出现 `SEC_E_NO_CREDENTIALS`;
|
||||
4. FreeRDP 3 设置键使用 `FreeRDP_ServerHostname`、`FreeRDP_Username`、`FreeRDP_DesktopWidth` 等,不要照抄 FreeRDP 2.x 键名;
|
||||
5. `PIXEL_FORMAT_BGRX32` 是 B/G/R/X 四字节布局,Qt 显示前需要 BGR -> RGB 转换;
|
||||
6. `/gfx` 命令行是能力组合语义,不能把 `AVC420`/`AVC444` 当作单个值使用。实测可解析形式包括 `progressive|RFX|AVC420|AVC444`。
|
||||
|
||||
重要:当前 POC 已成功显示 Windows 10 的真实远程桌面画面,颜色正确,进程保持运行。这是目前最重要的实测成果。
|
||||
|
||||
详细说明在:
|
||||
|
||||
```text
|
||||
D:\DAIMA\vdi-cloud\docs\freerdp3-embedding-notes.md
|
||||
```
|
||||
|
||||
### 6.5 显示问题
|
||||
|
||||
曾出现“从上到下卷帘式渲染”。目前确认:
|
||||
|
||||
- WiFi 信号/速率/丢包不是主要原因;
|
||||
- 显示器原生是 1920x1440,而曾请求 2560x1440,存在缩放;
|
||||
- X11/MATE/FreeRDP CPU 侧渲染路径性能有限;
|
||||
- 正式文档要求 Weston + DRM plane + GStreamer mppvideodec 零拷贝,这正是后续方向;
|
||||
- 该问题按用户要求暂时不阻断当前 GUI/登录页主线,后续处理。
|
||||
|
||||
注意:此前对“X11 无 glamor 硬件合成”的判断不准确,Xorg 日志实际显示 `glamor X acceleration enabled on Mali450`;后续不要继续引用这个错误结论。正确表述是:当前路径仍未达到目标流畅度,具体瓶颈需要后续基准测试确认。
|
||||
|
||||
### 6.6 Moonlight 云桌面开机直达(2026-10-28)
|
||||
|
||||
RDP/Moonlight 实测对比见 `docs/rdp-vs-moonlight-comparison-20261028.md`,
|
||||
落地记录见 `docs/moonlight-kiosk-20261028.md`。
|
||||
|
||||
盒子当前开机默认走 Moonlight 直连云桌面,链路:
|
||||
|
||||
```text
|
||||
~/.config/autostart/vdi-moonlight.desktop
|
||||
-> vdi-kiosk-monitor --heartbeat-file /tmp/vdi-moonlight.heartbeat --max-restart 200
|
||||
-- /home/armbian/vdi-terminal/bin/vdi-moonlight
|
||||
-> moonlight-qt stream 192.168.1.70 Desktop (fullscreen, 1920x1080, H.264, 软解)
|
||||
```
|
||||
|
||||
仓库新增:`terminal/kiosk-shell/scripts/vdi-moonlight`、`etc/moonlight.conf`、
|
||||
`vdi-moonlight.desktop`;`src/monitor.cpp` 改为按进程组结束整棵进程树。
|
||||
|
||||
实测:满屏云桌面 1:1 无缩放;杀客户端 5 秒内重连;杀启动器 3 秒内被看门狗拉起;
|
||||
性能叠图 1080p60 实际 21.59 FPS、网络丢包 0%、延迟 3 ms、解码 15.04 ms、抖动丢帧 13.64%。
|
||||
|
||||
关键坑位(后续维护必须知道):
|
||||
|
||||
1. Windows 防火墙屏蔽 ICMP,盒子 ping 不到云桌面主机,但 TCP/UDP 正常;
|
||||
可达性判断必须用 TCP 探测,ping 会误判;
|
||||
2. `moonlight-qt` 的应用 id 随服务端重装/升级失效,旧 id 会报“找不到应用程序 <id>”;
|
||||
命令行要用应用名 `Desktop`;
|
||||
3. RK3528 上 `--video-decoder auto` 会选到不可用的 `h264_v4l2m2m`,
|
||||
必须显式 `--video-decoder software`;
|
||||
4. RDP 路径的自启项已禁用但保留,可随时切回。
|
||||
|
||||
|
||||
## 7. 当前未完成/未验证
|
||||
|
||||
1. 服务端 GPU 直通未做:宿主机 `starhe` 有 GTX 965M(`0000:01:00.0`,IOMMU Group 2 独占),
|
||||
主机同时有 Intel 核显 `0000:00:02.0` 可继续驱动本机显示,具备直通条件;
|
||||
直通后 Sunshine 才能用 NVENC 硬编码,把 1080p 帧率从 ~21.6 FPS 提到 60 FPS;
|
||||
2. RK3528 VPU 硬解不可用:`h264_v4l2m2m` / `hevc_v4l2m2m` / `hevc_v4l2request` 均报
|
||||
`Could not find a valid device`,当前只能用软件解码,4K 目标必须先解决;
|
||||
3. 2K 分辨率链路未验证:盒子屏幕现为 1920x1080@60Hz,Sunshine 侧虚拟显示器也是 1920x1080@60Hz;
|
||||
4. 当前实现仍使用 X11 POC,正式方案要求 Weston/Wayland;
|
||||
5. 当前 RDP 会话使用 CPU GDI -> Qt 复制,尚未接 GStreamer/mppvideodec/VPU;
|
||||
6. `mppvideodec` 来源和可用性未确认;
|
||||
7. 终端注册、MQTT 心跳、配置下发、日志上报、OTA、USB 尚未接后端 API;
|
||||
8. 前端/后端管理平台尚未接入;Moonlight 路径目前读本地静态配置文件;
|
||||
9. 终端音频出音未现场确认(`--audio-on-host` 已开);
|
||||
10. 协议最终选型未定版:实测已证明 Moonlight 画面质量与 CPU 代价优于 RDP,
|
||||
但“办公用 RDP、GPU/CAD/3D 用 Moonlight”的双协议结论仍需产品方案确认。
|
||||
|
||||
## 8. 下一步建议(按优先级)
|
||||
|
||||
### A. 服务端 GPU 直通(当前最高价值项)
|
||||
|
||||
Sunshine 在 VM 内用 libx264 软件编码,4 核同时承担 1080p 捕获与编码,
|
||||
是 21.6 FPS 与 13.64% 抖动丢帧的唯一原因;客户端侧链路完全健康。
|
||||
|
||||
```text
|
||||
宿主机 starhe(Xeon E3-1200 v3 + Intel 核显 + GTX 965M)
|
||||
-> 确认内核 IOMMU 已启用(PCI 设备已有独立 IOMMU group)
|
||||
-> vfio-pci 绑定 0000:01:00.0,提取 vBIOS ROM
|
||||
-> VM 100 增加 hostpci,Windows 内装 GeForce 驱动
|
||||
-> nvidia-smi 正常后 Sunshine 切 NVENC 硬编码
|
||||
-> 复测 1080p60 帧率、抖动丢帧、服务端 CPU
|
||||
```
|
||||
|
||||
主机 root 密码已知(`yx66668888`),可用 `SSH_ASKPASS` 非交互登录。
|
||||
|
||||
### B. 收尾当前终端 POC
|
||||
|
||||
1. 保留当前 Moonlight 开机直达版本作为可回退基线(`docs/moonlight-kiosk-20261028.md`);
|
||||
2. 确认开机自启在真实重启后生效(当前只验证了手动拉起与被守护重启);
|
||||
3. 网络状态显示修复(此前显示错误的 `600`)尚未确认最新二进制效果;
|
||||
4. RDP 路径代码保留但自启已禁用,按需切回。
|
||||
|
||||
### C. 协议策略与代码结构
|
||||
|
||||
实测结论已经支持双协议方向,但仍未定版:
|
||||
|
||||
```text
|
||||
普通办公 -> RDP
|
||||
GPU/CAD/3D -> Moonlight
|
||||
```
|
||||
|
||||
如果确认需要双协议,代码结构应演进为:
|
||||
|
||||
```text
|
||||
DesktopSession 接口
|
||||
├─ RdpSession # 保留当前 libfreerdp3
|
||||
└─ MoonlightSession # 当前是 shell 启动器 + moonlght-qt 子进程
|
||||
SessionManager # 根据 API 下发 protocol 选择实现
|
||||
```
|
||||
|
||||
不要在定版前擅自确定 Moonlight 的嵌入方式、认证字段或删除 RDP 代码。
|
||||
|
||||
|
||||
### C. 后续 API 对接
|
||||
|
||||
与后端确认:
|
||||
|
||||
- `/api/v1/terminal/register`;
|
||||
- 配置拉取接口;
|
||||
- MQTT 心跳和命令格式;
|
||||
- 桌面连接信息字段;
|
||||
- 返回 VM 地址还是 RDP/Moonlight 网关地址;
|
||||
- 是否使用一次性票据;
|
||||
- GPU 桌面如何标记协议/资源池;
|
||||
- 终端不直接调用 Proxmox API。
|
||||
|
||||
## 9. 安全与工程注意事项
|
||||
|
||||
- `/cert:ignore` 只能用于当前局域网 POC,正式版本必须证书校验;
|
||||
- 空密码只能用于当前测试 VM,正式环境必须禁用;
|
||||
- 不要把密码提交到 git;当前本地配置仅用于 POC;
|
||||
- 终端正式版本不要长期保存 Windows 密码,应使用管理平台/网关/短期凭据方案;
|
||||
- 不要执行 `git reset --hard`、删除用户已有改动或覆盖未审阅文件;
|
||||
- 不要把推测写成“已实现”;日报和项目状态要区分“已验证/已完成/待验证/待调研”。
|
||||
|
||||
## 10. 今日日报关联
|
||||
|
||||
日报模板:`E:\Desktop\日报.txt`。
|
||||
已按 10 月 23 日实际情况填入并保存:
|
||||
|
||||
- 终端硬件与系统基线;
|
||||
- 编译环境;
|
||||
- monorepo/kiosk-shell;
|
||||
- libfreerdp3 内嵌 RDP;
|
||||
- Windows 10 远程桌面实机验证;
|
||||
- 2K 显示异常初步定位;
|
||||
- 明日 Monitor/Weston/mppvideodec/API 待办;
|
||||
- AVC444、mppvideodec、Weston、API 契约风险。
|
||||
|
||||
如果继续写日报,必须以实际工具执行结果为准,不能把未编译或未实测项目写成完成。
|
||||
开发前查看 `git status`,不丢弃未提交改动;不随手整体升级盒子系统或改变宿主/GPU 配置。部署、设备重启、回退应结合当前任务授权与现场使用情况执行。本次文档整理未执行现场操作。
|
||||
@@ -0,0 +1,58 @@
|
||||
# VDI 云桌面项目
|
||||
|
||||
面向 RK3528 云终端的“云—管—端”VDI 项目。当前已接通 Windows、Ubuntu、麒麟的 Moonlight/Sunshine 会话,仍处于终端 POC 与产品流程验证阶段。
|
||||
|
||||
## 文档入口
|
||||
|
||||
| 文档 | 内容 |
|
||||
| --- | --- |
|
||||
| [文档索引](docs/README.md) | 全部维护文档、历史归档与原始需求 |
|
||||
| [当前状态](docs/current-status.md) | 三系统配置、最新实施结果与验证边界 |
|
||||
| [终端说明](docs/terminal-guide.md) | 开机直达选择页、进出交接、快捷键、显示与构建 |
|
||||
| [云桌面说明](docs/desktop-guide.md) | 编码、光标、客体电源按钮、USB |
|
||||
| [运维说明](docs/operations.md) | 日志、监控分工、排障和回退 |
|
||||
| [云管开发说明](docs/cloud-platform-development.md) | Go API、Vue 控制台、本机启动、接口与联调边界 |
|
||||
| [未来计划](docs/roadmap.md) | 产品化与明确暂缓的 VPN、软件白名单、品牌画面 |
|
||||
|
||||
## 当前流程与边界
|
||||
|
||||
```text
|
||||
盒子开机 → LightDM 独占 kiosk → 选择云桌面 → Moonlight 串流 → 返回选择页
|
||||
```
|
||||
|
||||
盒子使用私有 RKMPP 硬解/EGL,Windows 使用 NVENC,Linux 仍以软件编码为主。当前是 Xorg POC,Weston/Wayland 是后续方向;现场盒子已接入平台设备认证、授权列表和一次性连接票据,详见[真实接入说明](docs/cloud-live-integration.md)。正式边界为终端 → 自研平台 API → Proxmox,终端不直接管理 VM。
|
||||
|
||||
11-09 已修复退出露出绿色桌面和进入左上角小窗;三系统 X11 采样通过,尚无外置逐帧采集。详细版本与证据见当前状态,不将历史性能测试当作实时健康报告。
|
||||
|
||||
## 仓库结构
|
||||
|
||||
| 目录 | 职责 |
|
||||
| --- | --- |
|
||||
| `terminal/kiosk-shell/` | Qt 全屏入口、会话、看门狗和显示守护 |
|
||||
| `terminal/moonlight/`、`terminal/native-cursor/` | 私有硬解客户端补丁、Linux 原生光标 |
|
||||
| `terminal/usb-monitor/` | USB 存储设备透传 POC |
|
||||
| `terminal/meta-vdi/`、`terminal/vdt-agent/`、`terminal/ota-updater/` | 系统层、Agent 与 OTA 后续工作 |
|
||||
| `platform/`、`console/`、`deploy/` | Go API、Vue 管理台;演示部署与独立真实现场环境 |
|
||||
| `tools/` | 管理员构建、部署、诊断与测试工具 |
|
||||
| `docs/` | 主题说明、需求原件、历史归档与测试证据 |
|
||||
|
||||
运行监控由独立 [vdi-monitor 项目](../vdi-monitor/README.md) 维护;本仓库保存实现、验证与回退资料。监控最新快照和 7 天指标不能替代全部历史证据。
|
||||
|
||||
## 构建与配置
|
||||
|
||||
在具备 Qt5 开发依赖的 ARM64 环境:
|
||||
|
||||
```bash
|
||||
cd terminal/kiosk-shell
|
||||
cmake -G Ninja -B build -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON
|
||||
cmake --build build
|
||||
QT_QPA_PLATFORM=offscreen ctest --test-dir build --output-on-failure
|
||||
```
|
||||
|
||||
产物为 `kiosk-shell`、`vdi-kiosk-monitor`。产品连接配置在盒子 `~/.config/vdi-terminal/desktops.json`,基础配置为 `client.conf`;`moonlight.conf` 仅供旧独立调试入口使用。完整部署和客户端构建入口见[终端说明](docs/terminal-guide.md#build)。
|
||||
|
||||
## 开发约定
|
||||
|
||||
保留用户已有改动;事实、计划和待验收结论分开记录。正式需求来源保留于 `docs/` 的三份 Word,后续明确确认的实现与当前用户要求优先于旧历史描述。账号、密码、私钥和连接票据通过安全配置提供,不新增到文档或提交。
|
||||
|
||||
日常直接更新对应主题,计划统一维护在 `docs/roadmap.md`;测试输出放入 `docs/evidence/<专题-日期>/`。2026-11-09 以前的零散记录及本次整理前的三份根说明完整保留在[历史归档](docs/archive/README.md)。
|
||||
@@ -0,0 +1,2 @@
|
||||
# api: connect the Go backend; mock: browser-only demo, no real operations.
|
||||
VITE_API_MODE=api
|
||||
@@ -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,89 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { fail?: boolean; deny?: boolean; slow?: boolean } = {}) {
|
||||
const revoked: string[] = [], queries: string[] = []
|
||||
const now = new Date().toISOString(), expires = new Date(Date.now() + 3600000).toISOString()
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'session-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[], total = items.length) => route.fulfill({ json: { items, total, page: 1, pageSize: 20, requestId: 'sessions-ui' } })
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'owner', username: 'root', displayName: '管理员', role: 'super_admin' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', capabilities: ['administrator-sessions'], pveConfigured: true } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/administrators') { await list([{ id: 'owner', username: 'root', displayName: '管理员', role: 'super_admin', enabled: true }, { id: 'other', username: 'maintainer', displayName: '运维', role: 'operator', enabled: true }]); return }
|
||||
const match = path.match(/^\/administrators\/(owner|other)\/sessions(?:\/(.+))?$/)
|
||||
if (match) {
|
||||
const id = match[1]!, key = match[2]
|
||||
if (request.method() === 'DELETE') {
|
||||
revoked.push(`${id}/${key}`)
|
||||
if (options.deny) { await route.fulfill({ status: 403, json: { code: 'forbidden', message: '当前账号没有该操作权限' } }); return }
|
||||
await route.fulfill({ status: 204 }); return
|
||||
}
|
||||
queries.push(id)
|
||||
if (options.fail && id === 'other') { await route.fulfill({ status: 500, json: { code: 'database_error', message: '登录列表暂不可用' } }); return }
|
||||
if (options.slow && id === 'owner') await new Promise(resolve => setTimeout(resolve, 700))
|
||||
const p = Number(url.searchParams.get('page') || 1), size = 20, total = 21 - revoked.filter(r => r.startsWith(`${id}/`)).length
|
||||
await list(Array.from({ length: Math.max(0, Math.min(size, total - (p - 1) * size)) }, (_, i) => ({ key: `${id}-${(p - 1) * size + i}`, createdAt: i === 1 ? null : now, expiresAt: expires, clientIp: i === 1 ? '' : `192.0.2.${(p - 1) * size + i + 1}`, userAgent: 'Example browser <script>alert(1)</script>', current: id === 'owner' && p === 1 && i === 0 })), total); return
|
||||
}
|
||||
if (['/resources', '/desktops', '/users', '/terminals', '/tasks'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '测试接口未定义' } })
|
||||
})
|
||||
await page.goto('/settings'); await page.getByRole('button', { name: '管理员账号', exact: true }).click()
|
||||
await expect(page.getByRole('heading', { name: '管理员账号', exact: true })).toBeVisible()
|
||||
return { revoked, queries }
|
||||
}
|
||||
async function open(page: Page, name: string) {
|
||||
await page.getByRole('row').filter({ hasText: name }).getByRole('button', { name: '在线登录', exact: true }).click()
|
||||
return page.getByRole('dialog', { name: `在线登录 · ${name}`, exact: true })
|
||||
}
|
||||
|
||||
test('登录来源、旧登录未知信息、分页、当前登录保护及深浅窄屏', async ({ page }, info) => {
|
||||
const calls = await fixture(page), dialog = await open(page, 'root')
|
||||
await expect(dialog.getByText('当前登录', { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByRole('row').filter({ hasText: '当前登录' }).getByRole('button', { name: '撤销登录' })).toBeDisabled()
|
||||
await expect(dialog.getByText('升级前登录,时间未知', { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByText('升级前登录,来源未知', { exact: true })).toBeVisible()
|
||||
await page.screenshot({ path: info.outputPath('admin-sessions-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await dialog.locator('.el-pagination .btn-next').click(); await expect(dialog.getByText('192.0.2.21', { exact: true })).toBeVisible()
|
||||
await dialog.getByRole('button', { name: '关闭', exact: true }).click()
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click(); await page.setViewportSize({ width: 390, height: 844 })
|
||||
await open(page, 'root'); await expect(dialog.getByText('当前登录', { exact: true })).toBeVisible()
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: info.outputPath('admin-sessions-mobile.png'), fullPage: true, animations: 'disabled' })
|
||||
expect(calls.revoked).toEqual([])
|
||||
})
|
||||
|
||||
test('撤销指定登录需确认,取消不提交,成功刷新', async ({ page }) => {
|
||||
const calls = await fixture(page), dialog = await open(page, 'maintainer')
|
||||
await expect(dialog.getByText('共 21 次有效登录', { exact: true })).toBeVisible()
|
||||
await dialog.getByRole('button', { name: '撤销登录', exact: true }).first().click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '取消', exact: true }).click()
|
||||
expect(calls.revoked).toEqual([])
|
||||
await dialog.getByRole('button', { name: '撤销登录', exact: true }).first().click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认提交', exact: true }).click()
|
||||
await expect(dialog.getByText('共 20 次有效登录', { exact: true })).toBeVisible()
|
||||
expect(calls.revoked).toEqual(['other/other-0'])
|
||||
})
|
||||
|
||||
test('查询和撤销失败清除旧结果并显示错误,不误报成功', async ({ page }) => {
|
||||
const calls = await fixture(page, { deny: true }), dialog = await open(page, 'maintainer')
|
||||
await dialog.getByRole('button', { name: '撤销登录', exact: true }).first().click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认提交', exact: true }).click()
|
||||
await expect(dialog.getByText('当前账号没有该操作权限', { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByRole('button', { name: '撤销登录', exact: true })).toHaveCount(0)
|
||||
expect(calls.revoked).toHaveLength(1)
|
||||
await page.unrouteAll(); await fixture(page, { fail: true }); await open(page, 'maintainer')
|
||||
await expect(page.getByRole('dialog').getByText('登录列表暂不可用', { exact: true })).toBeVisible()
|
||||
await expect(page.getByRole('dialog').getByRole('button', { name: '撤销登录', exact: true })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('切换账号后旧请求不能覆盖新的登录列表', async ({ page }) => {
|
||||
const calls = await fixture(page, { slow: true }), old = await open(page, 'root')
|
||||
await expect.poll(() => calls.queries.includes('owner')).toBe(true)
|
||||
await old.getByRole('button', { name: '关闭', exact: true }).click()
|
||||
const current = await open(page, 'maintainer')
|
||||
await expect(current.getByText('共 21 次有效登录', { exact: true })).toBeVisible()
|
||||
await page.waitForTimeout(850)
|
||||
await expect(current.getByText('当前登录', { exact: true })).toHaveCount(0)
|
||||
expect(calls.revoked).toEqual([])
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
// Isolated browser fixtures; no live administrator passwords or roles are modified.
|
||||
async function fixture(page: Page, role = 'super_admin') {
|
||||
const calls: { method: string; path: string; body: Record<string, unknown> }[] = []
|
||||
const me = { id: 'self-admin', username: 'root', displayName: '平台管理员', role, enabled: true }
|
||||
const accounts = [me, { id: 'other-admin', username: 'operations', displayName: '运维人员', role: 'operator', enabled: true }]
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'admin-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const r = route.request(), path = new URL(r.url()).pathname.replace('/api/v1', ''), method = r.method()
|
||||
const list = (items: unknown[]) => route.fulfill({ json: { items, page: 1, pageSize: 100, total: items.length, requestId: 'admin-fixture' } })
|
||||
if (method !== 'GET') {
|
||||
const body = r.postData() ? r.postDataJSON() as Record<string, unknown> : {}; calls.push({ method, path, body })
|
||||
if (path === '/administrators') {
|
||||
if (accounts.some(a => a.username === body.username)) { await route.fulfill({ status: 409, json: { code: 'account_conflict', message: '管理员账号已存在', requestId: 'fixture' } }); return }
|
||||
const a = { id: 'new-admin', username: String(body.username), displayName: String(body.displayName), role: String(body.role), enabled: true };accounts.push(a)
|
||||
await route.fulfill({ status: 201, json: a }); return
|
||||
}
|
||||
if (path.startsWith('/administrators/') && method === 'PUT') { const a = accounts.find(a => path.endsWith(a.id)); if (a) Object.assign(a, body);await route.fulfill({ json: a }); return }
|
||||
if (path.endsWith('/password') && path.startsWith('/administrators/')) { await route.fulfill({ status: 204 }); return }
|
||||
if (path === '/auth/password') {
|
||||
if (body.currentPassword !== 'Correct-old-password') { await route.fulfill({ status: 400, json: { code: 'current_password_invalid', message: '原密码不正确', requestId: 'fixture' } }); return }
|
||||
await route.fulfill({ status: 204 }); return
|
||||
}
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: me }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', pveConfigured: true, computeProvider: 'proxmox', terminalTransport: 'https-poll', capabilities: ['administrators'] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/administrators') { await list(accounts); return }
|
||||
if (['/desktops', '/terminals', '/users', '/resources', '/tasks', '/audit-logs'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { code: 'fixture_missing', message: '测试接口未定义', requestId: 'fixture' } })
|
||||
})
|
||||
return calls
|
||||
}
|
||||
async function openAccounts(page: Page) { await page.goto('/settings'); await page.getByRole('button', { name: '管理员账号', exact: true }).click(); await expect(page.getByRole('heading', { name: '管理员账号', exact: true })).toBeVisible() }
|
||||
|
||||
test('新增管理员校验密码确认,账号持久化字段正确', async ({ page }, testInfo) => {
|
||||
const calls = await fixture(page)
|
||||
await page.setViewportSize({ width: 1440, height: 1000 })
|
||||
await openAccounts(page)
|
||||
await page.screenshot({ path: testInfo.outputPath('administrators-dark.png'), fullPage: true })
|
||||
await page.getByRole('button', { name: '新增管理员', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '新增管理员' })
|
||||
await dialog.getByRole('textbox', { name: '管理员账号', exact: true }).fill('finance')
|
||||
await dialog.getByRole('textbox', { name: '管理员显示名称' }).fill('财务只读人员')
|
||||
await dialog.getByLabel('管理员初始密码', { exact: true }).fill('Finance-test-2026')
|
||||
await expect(dialog.getByRole('button', { name: '保存管理员' })).toBeDisabled()
|
||||
await dialog.getByLabel('确认管理员初始密码', { exact: true }).fill('Finance-test-2026')
|
||||
await dialog.getByRole('button', { name: '保存管理员' }).click()
|
||||
await expect(dialog).not.toBeVisible()
|
||||
await expect(page.getByText('finance', { exact: true })).toBeVisible()
|
||||
expect(calls.find(c => c.path === '/administrators')?.body).toEqual({ username: 'finance', displayName: '财务只读人员', role: 'viewer', password: 'Finance-test-2026' })
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click()
|
||||
await page.screenshot({ path: testInfo.outputPath('administrators-light.png'), fullPage: true })
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: testInfo.outputPath('administrators-mobile.png'), fullPage: true })
|
||||
})
|
||||
|
||||
test('编辑本人禁止角色和停用,取消其他账号停用不提交', async ({ page }) => {
|
||||
const calls = await fixture(page)
|
||||
await openAccounts(page)
|
||||
await page.getByRole('row').filter({ hasText: 'root' }).getByRole('button', { name: '编辑', exact: true }).click()
|
||||
let dialog = page.getByRole('dialog', { name: '编辑管理员' })
|
||||
await expect(dialog.getByRole('combobox')).toBeDisabled()
|
||||
await expect(dialog.getByRole('switch')).toBeDisabled()
|
||||
await dialog.getByRole('button', { name: '取消', exact: true }).click()
|
||||
await page.getByRole('row').filter({ hasText: 'operations' }).getByRole('button', { name: '编辑', exact: true }).click()
|
||||
dialog = page.getByRole('dialog', { name: '编辑管理员' })
|
||||
await dialog.locator('.el-switch').click()
|
||||
await dialog.getByRole('button', { name: '保存管理员' }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '取消', exact: true }).click()
|
||||
expect(calls.filter(c => c.method === 'PUT')).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '保存管理员' }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认提交' }).click()
|
||||
await expect(dialog).not.toBeVisible()
|
||||
expect(calls.find(c => c.method === 'PUT')?.body.enabled).toBe(false)
|
||||
})
|
||||
|
||||
test('重置其他账号密码需要确认,取消不提交', async ({ page }) => {
|
||||
const calls = await fixture(page)
|
||||
await openAccounts(page)
|
||||
await page.getByRole('button', { name: '重置密码', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '重置密码 · operations' })
|
||||
await dialog.getByLabel('重置后的新密码', { exact: true }).fill('Reset-test-2026')
|
||||
await dialog.getByLabel('确认重置后的新密码', { exact: true }).fill('Reset-test-2026')
|
||||
await dialog.getByRole('button', { name: '重置密码', exact: true }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '取消', exact: true }).click()
|
||||
expect(calls.filter(c => c.path.endsWith('/password'))).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '重置密码', exact: true }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认提交' }).click()
|
||||
await expect(dialog).not.toBeVisible()
|
||||
expect(calls.find(c => c.path === '/administrators/other-admin/password')?.body).toEqual({ password: 'Reset-test-2026' })
|
||||
})
|
||||
|
||||
test('只读人员可修改本人密码,错误原密码不退出,成功后清理登录', async ({ page }) => {
|
||||
await fixture(page, 'viewer')
|
||||
await page.goto('/settings')
|
||||
await expect(page.getByText('无访问权限', { exact: true })).toBeVisible()
|
||||
await page.getByRole('button', { name: '修改密码', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '修改本人密码' })
|
||||
await dialog.getByLabel('原密码', { exact: true }).fill('Incorrect-old-password')
|
||||
await dialog.getByLabel('新密码', { exact: true }).fill('Updated-test-2026')
|
||||
await dialog.getByLabel('确认新密码', { exact: true }).fill('Updated-test-2026')
|
||||
await dialog.getByRole('button', { name: '保存并重新登录' }).click()
|
||||
await expect(dialog.getByText(/原密码不正确/)).toBeVisible()
|
||||
await dialog.getByLabel('原密码', { exact: true }).fill('Correct-old-password')
|
||||
await dialog.getByRole('button', { name: '保存并重新登录' }).click()
|
||||
await expect(page).toHaveURL(/\/login$/)
|
||||
await expect(page.getByRole('heading', { name: '登录管理控制台' })).toBeVisible()
|
||||
expect(await page.evaluate(() => sessionStorage.getItem('vdi.accessToken'))).toBeNull()
|
||||
})
|
||||
@@ -0,0 +1,92 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { fail?: boolean; oversized?: boolean; exportFail?: boolean } = {}) {
|
||||
const queries: URLSearchParams[] = [], exports: URLSearchParams[] = [], writes: string[] = []
|
||||
const now = new Date().toISOString()
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'audit-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[], extra = {}) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 100, requestId: 'audit-ui', ...extra } })
|
||||
if (request.method() !== 'GET') { writes.push(path); await route.fulfill({ status: 403, json: { message: '不应发送写请求' } }); return }
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'reader', username: 'reader', displayName: '只读人员', role: 'viewer' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', capabilities: ['audit'], pveConfigured: false } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/audit-logs/export') {
|
||||
exports.push(url.searchParams)
|
||||
if (options.exportFail) { await route.fulfill({ status: 413, json: { message: '匹配记录超过 10000 条,请缩小时间范围', code: 'export_too_large', requestId: 'audit-ui' } }); return }
|
||||
await route.fulfill({ contentType: 'text/csv; charset=utf-8', body: '\ufeff时间,操作者\r\n2026-11-11T00:00:00Z,root\r\n' }); return
|
||||
}
|
||||
if (path === '/audit-logs') {
|
||||
queries.push(url.searchParams)
|
||||
if (options.fail && url.searchParams.get('keyword')) { await route.fulfill({ status: 500, json: { message: '审计查询暂不可用', code: 'database_error', requestId: 'audit-ui' } }); return }
|
||||
const p = Number(url.searchParams.get('page') || 1), filtered = !!url.searchParams.get('actor'), total = options.oversized ? 10001 : filtered ? 1 : 45
|
||||
const items = Array.from({ length: Math.min(20, total - (p - 1) * 20) }, (_, i) => ({ id: `audit-${(p - 1) * 20 + i + 1}`, actor: filtered ? 'operator_%' : 'root', action: 'save_alert_rule', target: `node-${(p - 1) * 20 + i + 1}`, result: 'success', requestId: `req-${p}-${i}`, createdAt: now }))
|
||||
await list(items, { total, page: p, pageSize: 20 }); return
|
||||
}
|
||||
if (['/resources', '/desktops', '/users', '/terminals', '/tasks'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '未定义的测试接口' } })
|
||||
})
|
||||
return { queries, exports, writes }
|
||||
}
|
||||
|
||||
test('按需加载审计,真实分页参数和固定截止时间,浅色移动布局', async ({ page }, info) => {
|
||||
const calls = await fixture(page); await page.goto('/tasks')
|
||||
await expect(page.getByRole('tab', { name: '执行任务' })).toBeVisible()
|
||||
expect(calls.queries).toHaveLength(0)
|
||||
await page.getByRole('tab', { name: '操作审计' }).click()
|
||||
await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toBeVisible()
|
||||
await page.locator('.el-pagination .btn-next').click()
|
||||
await expect(page.getByRole('cell', { name: 'node-21', exact: true })).toBeVisible()
|
||||
expect(calls.queries[calls.queries.length - 1]?.get('page')).toBe('2')
|
||||
expect(calls.queries[calls.queries.length - 1]?.get('to')).toBe(calls.queries[0]?.get('to'))
|
||||
await page.screenshot({ path: info.outputPath('audit-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click(); await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.screenshot({ path: info.outputPath('audit-mobile-light.png'), fullPage: true, animations: 'disabled' })
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
expect(calls.writes).toEqual([])
|
||||
})
|
||||
|
||||
test('操作人、动作、结果与时间筛选传到后端,导出使用已查询条件而非未提交的输入', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/tasks'); await page.getByRole('tab', { name: '操作审计' }).click()
|
||||
await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '审计操作者', exact: true }).fill('operator_%')
|
||||
await page.getByRole('textbox', { name: '审计关键词' }).fill('req_trace')
|
||||
await page.getByRole('combobox', { name: '审计动作' }).click(); await page.getByRole('option', { name: '保存告警规则', exact: true }).click()
|
||||
await page.getByRole('combobox', { name: '审计结果' }).click(); await page.getByRole('option', { name: '成功', exact: true }).click()
|
||||
await page.getByRole('combobox', { name: '审计时间范围' }).first().click(); await page.getByRole('button', { name: '最近 7 天', exact: true }).click()
|
||||
await page.getByRole('button', { name: '查询审计', exact: true }).click()
|
||||
await expect(page.getByRole('cell', { name: 'operator_%', exact: true })).toBeVisible()
|
||||
const q = calls.queries[calls.queries.length - 1]!
|
||||
expect(Object.fromEntries(q)).toMatchObject({ actor: 'operator_%', keyword: 'req_trace', action: 'save_alert_rule', result: 'success', page: '1', pageSize: '20' })
|
||||
expect(q.get('from')).toBeTruthy(); expect(q.get('to')).toBeTruthy()
|
||||
await page.getByRole('textbox', { name: '审计关键词' }).fill('还未查询的输入')
|
||||
const downloaded = page.waitForEvent('download'); await page.getByRole('button', { name: '导出查询结果 CSV' }).click()
|
||||
expect((await downloaded).suggestedFilename()).toMatch(/操作审计.*\.csv$/)
|
||||
expect(Object.fromEntries(calls.exports[0]!)).toMatchObject({ actor: 'operator_%', keyword: 'req_trace', action: 'save_alert_rule', result: 'success', from: q.get('from'), to: q.get('to') })
|
||||
expect(calls.exports[0]?.get('page')).toBeNull()
|
||||
await page.getByRole('button', { name: '重置', exact: true }).click()
|
||||
await expect(page.getByRole('cell', { name: 'root', exact: true }).first()).toBeVisible()
|
||||
expect(calls.queries[calls.queries.length - 1]?.get('actor')).toBe('')
|
||||
expect(calls.writes).toEqual([])
|
||||
})
|
||||
|
||||
test('查询失败清除旧结果并禁用导出,允许重试', async ({ page }) => {
|
||||
const calls = await fixture(page, { fail: true }); await page.goto('/tasks'); await page.getByRole('tab', { name: '操作审计' }).click()
|
||||
await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '审计关键词' }).fill('failure'); await page.getByRole('button', { name: '查询审计', exact: true }).click()
|
||||
await expect(page.getByText(/审计查询暂不可用/)).toBeVisible(); await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toHaveCount(0)
|
||||
await expect(page.getByRole('button', { name: '导出查询结果 CSV' })).toBeDisabled()
|
||||
await page.getByRole('button', { name: '重置', exact: true }).click(); await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toBeVisible()
|
||||
expect(calls.exports).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('导出超量有明确提示,服务端导出错误保留查询结果', async ({ page }) => {
|
||||
await fixture(page, { oversized: true }); await page.goto('/tasks'); await page.getByRole('tab', { name: '操作审计' }).click()
|
||||
await expect(page.getByText(/匹配记录超过 10000 条/)).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: '导出查询结果 CSV' })).toBeDisabled()
|
||||
await page.unrouteAll(); await fixture(page, { exportFail: true }); await page.reload(); await page.getByRole('tab', { name: '操作审计' }).click()
|
||||
await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toBeVisible()
|
||||
await page.getByRole('button', { name: '导出查询结果 CSV' }).click()
|
||||
await expect(page.getByText(/匹配记录超过 10000 条/)).toBeVisible()
|
||||
await expect(page.getByRole('cell', { name: 'node-1', exact: true })).toBeVisible()
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
// Every API request is intercepted, including all power actions.
|
||||
async function fixture(page: Page, options: { role?: string; count?: number; blocked?: boolean; retry?: boolean; expired?: boolean } = {}) {
|
||||
const requests: { path: string; body: Record<string, unknown>; key?: string }[] = [], now = new Date().toISOString()
|
||||
const desktops = Array.from({ length: options.count || 3 }, (_, i) => ({ id: `desk-b${i + 1}`, name: `批量桌面 ${i + 1}`, vmid: 9000 + i, node: 'test', os: 'Ubuntu', pool: '', poolId: null, provider: 'proxmox', powerState: 'running', serviceState: 'unknown', setupRequired: false, endpoint: `192.0.2.${90 + i}`, app: 'Desktop', width: 1920, height: 1080, fps: 30, updatedAt: now }))
|
||||
let submitted = false, reconciled = false
|
||||
const batch = () => ({ id: 'batch-test', action: 'shutdown', actor: 'operator', createdAt: now, totalCount: 3, submittedCount: 2, skippedCount: 1, activeCount: submitted ? 2 : 0, successCount: reconciled ? 1 : 0, failedCount: submitted ? 0 : 1, uncertainCount: submitted || reconciled ? 0 : 1 })
|
||||
const detail = () => ({ batch: batch(), items: desktops.slice(0, 3).map((d, i) => ({ desktopId: d.id, name: d.name, vmid: d.vmid, taskId: i < 2 ? `task-b${i}` : '', status: i === 2 ? 'skipped' : submitted ? 'queued' : i === 0 ? reconciled ? 'success' : 'timeout' : 'failed', code: i === 2 ? 'active_session' : 'ready', message: i === 2 ? '有活动会话,已跳过' : submitted ? '已提交,等待执行' : i === 0 ? '原任务结果未确认,不会自动重发' : '权限变更,未执行' })) })
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'batch-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const r = route.request(), path = new URL(r.url()).pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[]) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 100, requestId: 'batch-ui' } })
|
||||
if (r.method() !== 'GET') {
|
||||
requests.push({ path, body: r.postData() ? r.postDataJSON() : {}, key: r.headers()['idempotency-key'] })
|
||||
if (path === '/desktop-batches/check') {
|
||||
const selected = (r.postDataJSON().desktopIds as string[]).map(id => desktops.find(d => d.id === id)!)
|
||||
const items = selected.map(d => ({ desktopId: d.id, name: d.name, vmid: d.vmid, powerState: d.powerState, available: !options.blocked && d.id !== 'desk-b3', code: options.blocked || d.id === 'desk-b3' ? 'active_session' : 'ready', message: options.blocked || d.id === 'desk-b3' ? '有活动会话,已跳过' : '可执行,提交前再次检查' }))
|
||||
const eligibleCount = items.filter(i => i.available).length
|
||||
await route.fulfill({ json: { items, eligibleCount, skippedCount: items.length - eligibleCount, previewToken: 'signed-preview', expiresAt: new Date(Date.now() + (options.expired ? -1000 : 300000)).toISOString() } }); return
|
||||
}
|
||||
if (path === '/desktop-batches') {
|
||||
if (options.retry && requests.filter(r => r.path === path).length === 1) { await route.fulfill({ status: 503, json: { code: 'network', message: '网络暂时不可用', requestId: 'batch-ui' } }); return }
|
||||
submitted = true; await route.fulfill({ status: 202, json: detail() }); return
|
||||
}
|
||||
if (path.endsWith('/batch-power-reconcile')) { reconciled = true; await route.fulfill({ json: { accepted: true } }); return }
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'admin-batch', username: 'operator', displayName: '批量验收员', role: options.role || 'operator' } }); return }
|
||||
if (path === '/desktop-batches') { await list([batch()]); return }
|
||||
if (path === '/desktop-batches/batch-test') { await route.fulfill({ json: detail() }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', computeProvider: 'proxmox', pveConfigured: true, terminalTransport: 'https-poll', capabilities: [] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: desktops.length, runningDesktops: desktops.length, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/desktops') { await list(desktops); return }
|
||||
if (['/terminals', '/users', '/resources', '/audit-logs'].includes(path)) { await list([]); return }
|
||||
if (path === '/tasks') { await list([{ id: 'task-b0', kind: 'batch-desktop', action: 'shutdown', targetId: 'desk-b1', targetName: '批量桌面 1', actor: 'operator', status: 'timeout', message: '批量电源结果未确认', providerRef: 'UPID:old', createdAt: now, updatedAt: now }]); return }
|
||||
await route.fulfill({ status: 404, json: { code: 'missing_fixture', message: '未定义测试接口', requestId: 'batch-ui' } })
|
||||
})
|
||||
return requests
|
||||
}
|
||||
async function selectCheckbox(page: Page, name: string) {
|
||||
await page.locator('label.el-checkbox').filter({ has: page.getByRole('checkbox', { name, exact: true }) }).click()
|
||||
}
|
||||
async function prepare(page: Page) {
|
||||
await page.goto('/desktops'); await selectCheckbox(page, '选择本页'); await page.getByRole('button', { name: '批量关机', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '批量正常关机', exact: true }); await dialog.getByRole('button', { name: '预检批量操作', exact: true }).click(); return dialog
|
||||
}
|
||||
test('批量关机逐台预检,取消不提交,确认后仅显示已提交', async ({ page }, info) => {
|
||||
const requests = await fixture(page), dialog = await prepare(page)
|
||||
await expect(dialog.getByText('有活动会话,已跳过', { exact: true })).toBeVisible(); await expect(dialog.getByText(/可执行/).first()).toBeVisible()
|
||||
await page.screenshot({ path: info.outputPath('batch-preview-dark.png'), fullPage: true })
|
||||
await dialog.getByRole('button', { name: '提交批量操作', exact: true }).click(); await page.getByRole('button', { name: '取消', exact: true }).click()
|
||||
expect(requests.filter(r => r.path === '/desktop-batches')).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '提交批量操作', exact: true }).click(); await page.getByRole('button', { name: '提交批量任务', exact: true }).click()
|
||||
const result = page.getByRole('dialog', { name: '批量操作结果', exact: true }); await expect(result.getByText('已提交,等待执行', { exact: true })).toHaveCount(2)
|
||||
const writes = requests.filter(r => r.path === '/desktop-batches'); expect(writes).toHaveLength(1); expect(writes[0]?.key).toBeTruthy(); expect(writes[0]?.body).toEqual({ action: 'shutdown', desktopIds: ['desk-b1', 'desk-b2', 'desk-b3'], previewToken: 'signed-preview' })
|
||||
await page.screenshot({ path: info.outputPath('batch-submitted-dark.png'), fullPage: true })
|
||||
})
|
||||
test('卡片与列表共享选择,跨页保留选择并可清空', async ({ page }) => {
|
||||
await fixture(page, { count: 13 }); await page.goto('/desktops')
|
||||
await selectCheckbox(page, '选择桌面 批量桌面 1'); await page.getByRole('button', { name: '列表视图', exact: true }).click()
|
||||
await expect(page.getByRole('checkbox', { name: '选择桌面 批量桌面 1', exact: true })).toBeChecked()
|
||||
await page.locator('.el-pagination .btn-next').click(); await selectCheckbox(page, '选择桌面 批量桌面 11')
|
||||
await expect(page.getByText('已选 2 / 50 台(可跨页)', { exact: true })).toBeVisible()
|
||||
await page.getByRole('button', { name: '批量重启', exact: true }).click(); const dialog = page.getByRole('dialog', { name: '批量重启', exact: true })
|
||||
await expect(dialog.getByText('批量桌面 1', { exact: true })).toBeVisible(); await expect(dialog.getByText('批量桌面 11', { exact: true })).toBeVisible()
|
||||
await dialog.getByRole('button', { name: '关闭', exact: true }).click(); await page.getByRole('button', { name: '清空选择', exact: true }).click(); await expect(page.getByRole('button', { name: '批量开机', exact: true })).toBeDisabled()
|
||||
})
|
||||
test('浅色窄屏预检与结果操作区域保持可见', async ({ page }, info) => {
|
||||
await fixture(page); await page.addInitScript(() => localStorage.setItem('vdi.theme', 'light')); await page.setViewportSize({ width: 390, height: 844 })
|
||||
const dialog = await prepare(page); await expect(dialog.locator('.el-dialog__header')).toBeInViewport(); await expect(dialog.getByRole('button', { name: '提交批量操作', exact: true })).toBeInViewport()
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: info.outputPath('batch-preview-light-mobile.png'), fullPage: true })
|
||||
})
|
||||
test('全部跳过或预检过期不能提交', async ({ page }) => {
|
||||
let requests = await fixture(page, { blocked: true }); let dialog = await prepare(page)
|
||||
await expect(dialog.getByRole('button', { name: '提交批量操作', exact: true })).toBeDisabled(); expect(requests.filter(r => r.path === '/desktop-batches')).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '关闭', exact: true }).click(); await page.unroute('**/api/v1/**'); requests = await fixture(page, { expired: true }); dialog = await prepare(page)
|
||||
await expect(dialog.getByRole('button', { name: '提交批量操作', exact: true })).toBeDisabled(); expect(requests.filter(r => r.path === '/desktop-batches')).toHaveLength(0)
|
||||
})
|
||||
test('提交网络失败保留相同幂等标识重试', async ({ page }) => {
|
||||
const requests = await fixture(page, { retry: true }), dialog = await prepare(page)
|
||||
for (let i = 0; i < 2; i++) { await dialog.getByRole('button', { name: '提交批量操作', exact: true }).click(); await page.getByRole('button', { name: '提交批量任务', exact: true }).click(); if (!i) await expect(dialog.getByText(/网络暂时不可用/)).toBeVisible() }
|
||||
await expect(page.getByRole('dialog', { name: '批量操作结果', exact: true })).toBeVisible(); const writes = requests.filter(r => r.path === '/desktop-batches'); expect(writes).toHaveLength(2); expect(writes[0]?.key).toBeTruthy(); expect(writes[0]?.key).toBe(writes[1]?.key)
|
||||
})
|
||||
test('批量记录保留失败和跳过原因,运维可只读核对原任务', async ({ page }) => {
|
||||
const requests = await fixture(page); await page.goto('/desktops'); await page.getByRole('button', { name: '批量记录', exact: true }).click()
|
||||
await page.getByRole('button', { name: '正常关机 · operator', exact: true }).click(); const dialog = page.getByRole('dialog', { name: '批量操作结果', exact: true })
|
||||
await expect(dialog.getByText('权限变更,未执行', { exact: true })).toBeVisible(); await dialog.getByRole('button', { name: '核对电源结果', exact: true }).click()
|
||||
await expect(dialog.getByRole('button', { name: '核对电源结果', exact: true })).toHaveCount(0); expect(requests).toHaveLength(1); expect(requests[0]?.path).toBe('/tasks/task-b0/batch-power-reconcile')
|
||||
})
|
||||
test('只读人员无批量选择与提交入口,可查看历史', async ({ page }) => {
|
||||
await fixture(page, { role: 'viewer' }); await page.goto('/desktops')
|
||||
await expect(page.getByRole('button', { name: '批量关机', exact: true })).toHaveCount(0); await expect(page.getByRole('checkbox', { name: '选择本页', exact: true })).toHaveCount(0)
|
||||
await page.getByRole('button', { name: '批量记录', exact: true }).click(); await page.getByRole('button', { name: '正常关机 · operator', exact: true }).click(); await expect(page.getByRole('button', { name: '核对电源结果', exact: true })).toHaveCount(0)
|
||||
})
|
||||
test('任务页支持运维只读核对批量电源结果', async ({ page }) => {
|
||||
const requests = await fixture(page); await page.goto('/tasks'); await page.getByRole('button', { name: '批量桌面 1', exact: true }).click(); await page.getByRole('button', { name: '核对电源结果', exact: true }).click(); await expect.poll(() => requests.length).toBe(1); expect(requests[0]?.path).toBe('/tasks/task-b0/batch-power-reconcile')
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
// All calls are intercepted: these tests cannot create a real VM or change live assignments.
|
||||
async function catalogFixture(page: Page, options: { role?: string; empty?: boolean; fail?: boolean } = {}) {
|
||||
const now = new Date().toISOString(), requests: { endpoint: string; body: Record<string, unknown>; key?: string }[] = []
|
||||
const templates = options.empty ? [] : [{ id: 'tpl-ui', name: 'Ubuntu 标准镜像', version: '1.0', os: 'Ubuntu', node: 'node-a', vmid: 8000, enabled: true, validatedAt: now }]
|
||||
const pools = [{ id: 'pool-ui', name: '研发专属池', type: 'dedicated', maxCount: 5, templateId: 'tpl-ui', enabled: true, createdAt: now, desktopCount: 0, reservedCount: 0, assignedCount: 0, activeCount: 0 }]
|
||||
const desktop = { id: 'desk-ui', name: '待初始化桌面', os: 'Ubuntu', node: 'node-a', vmid: 9000, pool: '', poolId: null, setupRequired: true, powerState: 'stopped', serviceState: 'unknown', provider: 'proxmox', endpoint: '', app: 'Desktop', width: 1920, height: 1080, fps: 30, updatedAt: now }
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'catalog-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const r = route.request(), endpoint = new URL(r.url()).pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[]) => route.fulfill({ json: { items, page: 1, pageSize: 100, total: items.length, requestId: 'catalog-ui' } })
|
||||
if (r.method() !== 'GET') {
|
||||
const body = r.postData() ? r.postDataJSON() as Record<string, unknown> : {}
|
||||
requests.push({ endpoint, body, key: r.headers()['idempotency-key'] })
|
||||
if (endpoint === '/templates') { const item = { ...templates[0], ...body, id: 'tpl-new', enabled: true, validatedAt: now } as typeof templates[number]; templates.push(item); await route.fulfill({ status: 201, json: item }); return }
|
||||
if (endpoint === '/pools') { const item = { ...pools[0], ...body, id: 'pool-new' } as typeof pools[number]; pools.push(item); await route.fulfill({ json: item }); return }
|
||||
if (endpoint === '/desktops/clone/check') { await route.fulfill({ json: { available: true, message: '预检通过;创建后需初始化' } }); return }
|
||||
if (endpoint === '/desktops/clone') { await route.fulfill({ status: 202, json: { id: 'task-ui-clone', kind: 'provision', action: 'clone', targetId: desktop.id, targetName: '测试克隆桌面', actor: 'root', status: 'queued', message: '等待 PVE', providerRef: '', createdAt: now, updatedAt: now } }); return }
|
||||
if (endpoint === '/desktops/desk-ui/connection') { Object.assign(desktop, body, { setupRequired: false }); await route.fulfill({ json: desktop }); return }
|
||||
if (endpoint.endsWith('/members')) { await route.fulfill({ json: { accepted: true } }); return }
|
||||
}
|
||||
if (endpoint === '/auth/me') { await route.fulfill({ json: { id: 'admin-ui', username: 'root', displayName: '测试管理员', role: options.role || 'super_admin' } }); return }
|
||||
if (endpoint === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: 1, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (endpoint === '/settings') { await route.fulfill({ json: { mode: 'production', computeProvider: 'proxmox', pveConfigured: true, terminalTransport: 'https-poll', capabilities: [] } }); return }
|
||||
if (endpoint === '/templates') { if (options.fail) { await route.fulfill({ status: 503, json: { code: 'unavailable', message: '模板读取失败,请重试', requestId: 'catalog-ui' } }); return }; await list(templates); return }
|
||||
if (endpoint === '/pools') { await list(pools); return }
|
||||
if (endpoint === '/resources/templates') { await list(options.empty ? [] : [{ name: 'Ubuntu 新模板', node: 'node-a', vmid: 8001, status: 'stopped' }]); return }
|
||||
if (endpoint === '/resources/storage') { await list([{ storage: 'local', avail: 100 * 1073741824, enabled: 1, active: 1, content: 'images' }]); return }
|
||||
if (endpoint === '/desktops') { await list([desktop]); return }
|
||||
if (['/terminals', '/users', '/resources', '/tasks', '/audit-logs'].includes(endpoint)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { code: 'fixture_missing', message: '测试接口未定义', requestId: 'catalog-ui' } })
|
||||
})
|
||||
return requests
|
||||
}
|
||||
|
||||
test('模板克隆向导先预检,再提交带去重标识的任务', async ({ page }, testInfo) => {
|
||||
const requests = await catalogFixture(page)
|
||||
await page.setViewportSize({ width: 1440, height: 1000 })
|
||||
await page.goto('/templates')
|
||||
await expect(page.getByText('Ubuntu 标准镜像', { exact: true })).toBeVisible()
|
||||
await page.screenshot({ path: testInfo.outputPath('templates-dark.png'), fullPage: true })
|
||||
await page.getByRole('button', { name: '创建桌面', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '从模板创建桌面' })
|
||||
await expect(dialog.getByRole('button', { name: '提交创建任务' })).toBeDisabled()
|
||||
await dialog.getByPlaceholder('例如:研发桌面 01').fill('测试克隆桌面')
|
||||
await dialog.locator('.el-select__wrapper').last().click()
|
||||
await page.getByRole('option', { name: /local · 可用/ }).click()
|
||||
await dialog.getByRole('button', { name: '检查创建条件' }).click()
|
||||
await expect(dialog.getByText('预检通过;创建后需初始化')).toBeVisible()
|
||||
await dialog.getByRole('button', { name: '提交创建任务' }).click()
|
||||
await expect(dialog.getByText('创建任务已提交', { exact: true })).toBeVisible()
|
||||
expect(requests.filter(r => r.endpoint === '/desktops/clone')).toHaveLength(1)
|
||||
expect(requests.find(r => r.endpoint === '/desktops/clone')?.body).toMatchObject({ templateId: 'tpl-ui', name: '测试克隆桌面', vmid: 9000, full: true, storage: 'local' })
|
||||
expect(requests.find(r => r.endpoint === '/desktops/clone')?.key).toBeTruthy()
|
||||
})
|
||||
|
||||
test('桌面池创建保存业务字段,窄屏与浅色主题可用', async ({ page }, testInfo) => {
|
||||
const requests = await catalogFixture(page)
|
||||
await page.goto('/pools')
|
||||
await expect(page.getByText('0 台桌面 + 0 台创建预留 / 5')).toBeVisible()
|
||||
await page.getByRole('button', { name: '新建桌面池' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '新建桌面池' })
|
||||
await dialog.getByRole('textbox').fill('财务专属池')
|
||||
await dialog.getByRole('button', { name: '保存桌面池' }).click()
|
||||
await expect(page.getByText('财务专属池', { exact: true })).toBeVisible()
|
||||
expect(requests.find(r => r.endpoint === '/pools')?.body).toEqual({ name: '财务专属池', type: 'dedicated', maxCount: 10, templateId: null, enabled: true })
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click()
|
||||
await page.screenshot({ path: testInfo.outputPath('pools-light.png'), fullPage: true })
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.reload()
|
||||
await expect(page.getByRole('heading', { name: '桌面池', exact: true })).toBeVisible()
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: testInfo.outputPath('pools-mobile.png'), fullPage: true })
|
||||
})
|
||||
|
||||
test('待初始化桌面必须勾选确认才能保存连接', async ({ page }) => {
|
||||
const requests = await catalogFixture(page)
|
||||
await page.goto('/desktops')
|
||||
await expect(page.getByText('待初始化', { exact: true }).first()).toBeVisible()
|
||||
await page.getByRole('button', { name: '查看详情' }).click()
|
||||
await page.getByRole('button', { name: '配置连接', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '配置桌面连接' })
|
||||
await dialog.getByPlaceholder('例如 192.168.1.200,不含协议和端口').fill('192.0.2.20')
|
||||
await expect(dialog.getByRole('button', { name: '保存连接配置' })).toBeDisabled()
|
||||
await dialog.getByText('已完成系统身份、IP、Sunshine 服务和终端配对', { exact: true }).click()
|
||||
await dialog.getByRole('button', { name: '保存连接配置' }).click()
|
||||
await expect(dialog).not.toBeVisible()
|
||||
expect(requests.find(r => r.endpoint.endsWith('/connection'))?.body).toMatchObject({ endpoint: '192.0.2.20', initialized: true, width: 1920, height: 1080, fps: 30 })
|
||||
})
|
||||
|
||||
test('空模板和接口错误显示明确原因,只读角色没有管理按钮', async ({ page }) => {
|
||||
await catalogFixture(page, { role: 'viewer', empty: true })
|
||||
await page.goto('/templates')
|
||||
await expect(page.getByText(/尚未登记模板。请先在 PVE/)).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: '登记模板' })).toHaveCount(0)
|
||||
await page.goto('/pools')
|
||||
await expect(page.getByRole('button', { name: '新建桌面池' })).toHaveCount(0)
|
||||
await expect(page.getByRole('button', { name: '成员', exact: true })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('模板读取失败提供错误反馈', async ({ page }) => {
|
||||
await catalogFixture(page, { fail: true })
|
||||
await page.goto('/templates')
|
||||
await expect(page.getByText(/模板读取失败,请重试/)).toBeVisible()
|
||||
})
|
||||
@@ -0,0 +1,127 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
// Every endpoint is intercepted; these tests cannot mutate a live PVE desktop.
|
||||
async function fixture(page: Page, options: { running?: boolean; role?: string; fail?: boolean } = {}) {
|
||||
const requests: { path: string; body: Record<string, unknown>; key?: string }[] = [], now = new Date().toISOString()
|
||||
const desktop = { id: 'desk-hw', name: '规格验收桌面', vmid: 9000, node: 'test', os: 'Windows', pool: '', poolId: null, provider: 'proxmox', powerState: options.running ? 'running' : 'stopped', serviceState: 'unknown', setupRequired: false, endpoint: '192.0.2.90', app: 'Desktop', width: 1920, height: 1080, fps: 30, updatedAt: now }
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'configuration-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const r = route.request(), path = new URL(r.url()).pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[]) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 100, requestId: 'config-ui' } })
|
||||
if (r.method() !== 'GET') {
|
||||
requests.push({ path, body: r.postData() ? r.postDataJSON() : {}, key: r.headers()['idempotency-key'] })
|
||||
if (path === '/settings/pve/check') { await route.fulfill(options.fail ? { status: 502, json: { code: 'pve_connection_failed', message: '连接检查失败,请检查证书与权限', requestId: 'config-ui' } } : { json: { available: true, nodes: 1, vms: 3, message: 'TLS、身份与资源读取检查通过' } }); return }
|
||||
if (path === '/desktops/desk-hw/hardware/check') { await route.fulfill({ json: { available: true, message: '规格预检通过' } }); return }
|
||||
if (path === '/desktops/desk-hw/hardware') { await route.fulfill({ status: 202, json: { id: 'task-hw', kind: 'hardware', action: 'configure-hardware', targetId: desktop.id, targetName: desktop.name, actor: 'root', status: 'queued', message: '等待执行', providerRef: '', createdAt: now, updatedAt: now } }); return }
|
||||
if (path === '/settings/pve' || path.endsWith('/hardware-reconcile')) { await route.fulfill({ json: { accepted: true } }); return }
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'admin-hw', username: 'root', displayName: '验收管理员', role: options.role || 'super_admin' } }); return }
|
||||
if (path === '/settings/pve') { await route.fulfill({ json: { url: 'https://pve.example:8006', tokenId: 'service@pve!vdi', tokenConfigured: true, caPem: '', revision: 'config-v1', source: 'environment' } }); return }
|
||||
if (path === '/desktops/desk-hw/hardware') { await route.fulfill({ json: { cores: 2, sockets: 1, memoryMiB: 2048, digest: 'hardware-v1', disks: [{ key: 'scsi0', storage: 'local', sizeGiB: 60 }], powerState: desktop.powerState, blockers: options.running ? ['请先正常关闭桌面,再修改规格'] : [] } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', computeProvider: 'proxmox', pveConfigured: true, terminalTransport: 'https-poll', capabilities: [] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: 1, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/desktops') { await list([desktop]); return }
|
||||
if (path === '/tasks') { await list([{ id: 'hw-timeout', kind: 'hardware', action: 'expand-disk', targetId: desktop.id, targetName: desktop.name, actor: 'root', status: 'timeout', message: '规格变更结果未确认,不会自动重发', providerRef: 'UPID:old', createdAt: now, updatedAt: now }]); return }
|
||||
if (['/terminals', '/users', '/resources', '/audit-logs'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { code: 'missing_fixture', message: '未定义测试接口', requestId: 'config-ui' } })
|
||||
})
|
||||
return requests
|
||||
}
|
||||
|
||||
test('接入配置不回显密钥,取消不写入,检查后保留原密钥保存', async ({ page }, info) => {
|
||||
const requests = await fixture(page)
|
||||
await page.goto('/settings')
|
||||
await page.getByRole('button', { name: '配置 Proxmox 接入' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: 'Proxmox 接入配置' })
|
||||
await expect(dialog.getByRole('textbox', { name: 'PVE Token 密钥' })).toHaveValue('')
|
||||
await dialog.getByRole('button', { name: '检查连接' }).click()
|
||||
await expect(dialog.getByText(/TLS、身份与资源读取检查通过/)).toBeVisible()
|
||||
await page.screenshot({ path: info.outputPath('pve-connection-dark.png'), fullPage: true })
|
||||
await dialog.getByRole('button', { name: '保存并生效' }).click()
|
||||
await page.getByRole('button', { name: '取消', exact: true }).last().click()
|
||||
expect(requests.filter(r => r.path === '/settings/pve')).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '保存并生效' }).click()
|
||||
await page.getByRole('button', { name: '确认保存', exact: true }).click()
|
||||
await expect(dialog).not.toBeVisible()
|
||||
expect(requests.find(r => r.path === '/settings/pve')?.body).toMatchObject({ tokenSecret: '', revision: 'config-v1' })
|
||||
})
|
||||
|
||||
test('接入检查失败保留输入并支持窄屏', async ({ page }, info) => {
|
||||
const requests = await fixture(page, { fail: true })
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.goto('/settings')
|
||||
await page.getByRole('button', { name: '配置 Proxmox 接入' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: 'Proxmox 接入配置' })
|
||||
await dialog.getByRole('button', { name: '检查连接' }).click()
|
||||
await expect(dialog.getByText(/连接检查失败,请检查证书与权限/)).toBeVisible()
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: info.outputPath('pve-connection-mobile.png'), fullPage: true })
|
||||
await dialog.getByRole('button', { name: '取消', exact: true }).click()
|
||||
expect(requests.filter(r => r.path === '/settings/pve')).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('CPU 内存调整先预检,修改参数使预检失效,确认后提交一次', async ({ page }, info) => {
|
||||
const requests = await fixture(page)
|
||||
await page.goto('/desktops')
|
||||
await page.getByRole('button', { name: '查看详情' }).click()
|
||||
await page.getByRole('button', { name: '规格管理' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '桌面规格管理' })
|
||||
await expect(dialog.getByText(/当前:1 插槽 × 2 核/)).toBeVisible()
|
||||
await dialog.getByRole('spinbutton', { name: '每插槽核心数' }).fill('4')
|
||||
await dialog.getByRole('button', { name: '预检规格' }).click()
|
||||
await expect(dialog.getByRole('button', { name: '提交变更' })).toBeEnabled()
|
||||
await dialog.getByRole('spinbutton', { name: '目标内存' }).fill('4096')
|
||||
await expect(dialog.getByRole('button', { name: '提交变更' })).toBeDisabled()
|
||||
await dialog.getByRole('button', { name: '预检规格' }).click()
|
||||
await page.screenshot({ path: info.outputPath('hardware-compute-dark.png'), fullPage: true })
|
||||
await dialog.getByRole('button', { name: '提交变更' }).click()
|
||||
await page.getByRole('button', { name: '提交规格任务', exact: true }).click()
|
||||
await expect(dialog).not.toBeVisible()
|
||||
const writes = requests.filter(r => r.path === '/desktops/desk-hw/hardware')
|
||||
expect(writes).toHaveLength(1)
|
||||
expect(writes[0]?.body).toEqual({ kind: 'compute', cores: 4, sockets: 1, memoryMiB: 4096, digest: 'hardware-v1' })
|
||||
expect(writes[0]?.key).toBeTruthy()
|
||||
})
|
||||
|
||||
test('磁盘输入总容量并提示客体扩展,取消确认不提交', async ({ page }, info) => {
|
||||
const requests = await fixture(page)
|
||||
await page.goto('/desktops')
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click()
|
||||
await page.getByRole('button', { name: '查看详情' }).click()
|
||||
await page.getByRole('button', { name: '规格管理' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '桌面规格管理' })
|
||||
await dialog.getByRole('tab', { name: '磁盘扩容' }).click()
|
||||
await dialog.getByRole('spinbutton', { name: '磁盘目标容量' }).fill('80')
|
||||
await dialog.getByRole('button', { name: '预检规格' }).click()
|
||||
await page.screenshot({ path: info.outputPath('hardware-disk-light.png'), fullPage: true })
|
||||
await dialog.getByRole('button', { name: '提交变更' }).click()
|
||||
await expect(page.getByText(/scsi0 扩容至 80 GiB;完成后需在客体内扩展/)).toBeVisible()
|
||||
await page.getByRole('button', { name: '取消', exact: true }).last().click()
|
||||
expect(requests.find(r => r.path.endsWith('/hardware/check'))?.body).toMatchObject({ kind: 'disk', disk: 'scsi0', sizeGiB: 80 })
|
||||
expect(requests.filter(r => r.path === '/desktops/desk-hw/hardware')).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('运行中的桌面阻止修改,结果未知任务只读核对', async ({ page }) => {
|
||||
const requests = await fixture(page, { running: true })
|
||||
await page.goto('/desktops')
|
||||
await page.getByRole('button', { name: '查看详情' }).click()
|
||||
await page.getByRole('button', { name: '规格管理' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '桌面规格管理' })
|
||||
await expect(dialog.getByText('请先正常关闭桌面,再修改规格')).toBeVisible()
|
||||
await expect(dialog.getByRole('button', { name: '预检规格' })).toBeDisabled()
|
||||
await dialog.getByRole('button', { name: '关闭', exact: true }).click()
|
||||
await page.goto('/tasks')
|
||||
await page.getByRole('button', { name: '规格验收桌面', exact: true }).click()
|
||||
await page.getByRole('button', { name: '核对规格结果' }).click()
|
||||
await expect.poll(() => requests.filter(r => r.path.endsWith('/hardware-reconcile')).length).toBe(1)
|
||||
expect(requests.filter(r => r.path === '/desktops/desk-hw/hardware')).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('只读角色不显示接入与规格管理入口', async ({ page }) => {
|
||||
await fixture(page, { role: 'viewer' })
|
||||
await page.goto('/settings')
|
||||
await expect(page.getByRole('button', { name: '配置 Proxmox 接入' })).toHaveCount(0)
|
||||
await page.goto('/desktops')
|
||||
await page.getByRole('button', { name: '查看详情' }).click()
|
||||
await expect(page.getByRole('button', { name: '规格管理' })).toHaveCount(0)
|
||||
})
|
||||
@@ -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,99 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { role?: string; queryError?: boolean; exportError?: boolean; slow?: boolean; offline?: boolean; pending?: boolean; collectError?: boolean } = {}) {
|
||||
const queries: URLSearchParams[] = [], exports: URLSearchParams[] = [], writes: { path: string; key: string | undefined; body: unknown }[] = []
|
||||
let collected = false, attempts = 0
|
||||
const now = new Date().toISOString()
|
||||
const task = () => ({ id: 'collect-1', kind: 'terminal', action: 'collect-logs', targetId: 't1', targetName: '同名盒子', actor: 'operator', status: collected ? 'success' : 'running', message: collected ? '日志已回传' : '等待设备回执', providerRef: '', createdAt: now, updatedAt: now })
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'diagnostics-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[]) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 100 } })
|
||||
if (request.method() !== 'GET') {
|
||||
writes.push({ path, key: request.headers()['idempotency-key'], body: request.postDataJSON() })
|
||||
if (path === '/terminals/t1/commands') {
|
||||
attempts++
|
||||
if (options.collectError && attempts === 1) { await route.fulfill({ status: 503, json: { message: '提交结果尚未确认', code: 'unavailable', requestId: 'diag-ui' } }); return }
|
||||
collected = true; await route.fulfill({ status: 202, json: { ...task(), status: 'queued', message: '采集命令已提交' } }); return
|
||||
}
|
||||
await route.abort(); return
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'operator', username: 'operator', displayName: '运维', role: options.role || 'operator' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', pveConfigured: true, capabilities: [] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { activeSessions: 1 } }); return }
|
||||
if (path === '/desktops') { await list([{ id: 'd1', name: '办公桌面', node: 'pve', vmid: 100, powerState: 'running', serviceState: 'unknown', os: 'Windows' }]); return }
|
||||
if (path === '/terminals') { await list(['t1', 't2'].map((id, i) => ({ id, name: '同名盒子', sn: `SN-${i + 1}`, status: options.offline ? 'offline' : 'online', enabled: true, lastSeen: now, sessionDesktopId: null }))); return }
|
||||
if (path === '/resources' || path === '/users') { await list([]); return }
|
||||
if (path === '/tasks') { await list(collected || options.pending ? [options.pending ? { ...task(), status: 'timeout' } : task()] : []); return }
|
||||
if (path === '/diagnostics/export') {
|
||||
exports.push(url.searchParams)
|
||||
if (options.exportError) { await route.fulfill({ status: 413, json: { code: 'export_too_large', message: '诊断事件超过 2000 条', requestId: 'diag-ui' } }); return }
|
||||
await route.fulfill({ contentType: 'application/zip', body: 'fixture-download' }); return
|
||||
}
|
||||
if (path === '/diagnostics') {
|
||||
queries.push(url.searchParams)
|
||||
if (options.queryError && url.searchParams.get('source')) { await route.fulfill({ status: 500, json: { message: '诊断查询暂不可用', requestId: 'diag-ui' } }); return }
|
||||
const target = url.searchParams.get('targetId') || 't1', kind = url.searchParams.get('targetType') || 'terminal', source = url.searchParams.get('source') || '', p = Number(url.searchParams.get('page') || 1)
|
||||
if (options.slow && target === 't1') await new Promise(resolve => setTimeout(resolve, 600))
|
||||
const items = [{ id: `event-${p}`, source: 'logs', time: now, action: 'collect-logs', status: 'success', targetId: target, targetName: target === 't2' ? '第二个同名盒子' : '同名盒子', actor: 'operator', message: target === 't2' ? '第二个设备独立记录' : '终端已回传的日志片段', details: JSON.stringify({ taskId: `task-${p}`, logTail: '<img src=x onerror="window.diagnosticInjected=true">\nnetwork error\n[REDACTED]', bootId: 'test' }) }]
|
||||
await route.fulfill({ json: { subject: { kind, id: target, name: kind === 'desktop' ? '办公桌面' : target === 't2' ? '第二个同名盒子' : '同名盒子', state: options.offline ? 'offline' : kind === 'desktop' ? 'running' : 'online', node: kind === 'desktop' ? 'pve' : '', vmid: kind === 'desktop' ? 100 : 0, lastSeen: now, agentVersion: 'test' }, from: url.searchParams.get('from') || now, to: url.searchParams.get('to') || now, observedAt: now, items, total: source ? 1 : 25, page: p, pageSize: 20, source, counts: { tasks: 10, sessions: 10, logs: 3, alerts: 1, audits: 1 }, notes: ['按唯一标识关联;无记录不代表设备无故障。', '日志为设备回传片段,当前快照独立于历史时间范围。'] } }); return
|
||||
}
|
||||
await route.fulfill({ status: 404, json: { message: '未定义的测试接口' } })
|
||||
})
|
||||
return { queries, exports, writes }
|
||||
}
|
||||
|
||||
test('按对象显式查询,关联来源与详情以纯文本展示,支持分页', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/diagnostics')
|
||||
await expect(page.getByText('选择需要排查的设备或桌面,再查询诊断记录')).toBeVisible(); expect(calls.queries).toHaveLength(0)
|
||||
await page.getByRole('combobox', { name: '诊断对象', exact: true }).click(); await page.getByRole('option', { name: '同名盒子 / SN-1', exact: true }).click(); await page.getByRole('button', { name: '查询诊断', exact: true }).click()
|
||||
await expect(page.getByRole('heading', { name: '关联事件', exact: true })).toBeVisible(); expect(calls.queries.slice(-1)[0]?.get('targetId')).toBe('t1')
|
||||
await page.getByText('查看关联标识与详情', { exact: true }).click(); await expect(page.locator('.diagnosis-log')).toContainText('<img src=x'); expect(await page.evaluate(() => (window as Window & { diagnosticInjected?: boolean }).diagnosticInjected)).toBeUndefined()
|
||||
await expect(page.locator('.diagnosis-event img')).toHaveCount(0)
|
||||
const cutoff = calls.queries.slice(-1)[0]?.get('to'); await page.locator('.el-pagination .btn-next').click(); await expect.poll(() => calls.queries.slice(-1)[0]?.get('page')).toBe('2'); expect(calls.queries.slice(-1)[0]?.get('to')).toBe(cutoff)
|
||||
expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('导出沿用已查询条件,修改筛选立即清除旧记录并禁用导出', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/diagnostics?targetType=terminal&targetId=t1'); await expect(page.getByRole('heading', { name: '关联事件' })).toBeVisible()
|
||||
const applied = calls.queries.slice(-1)[0]!, download = page.waitForEvent('download'); await page.getByRole('button', { name: '导出诊断包', exact: true }).click(); expect((await download).suggestedFilename()).toContain('.zip')
|
||||
expect(calls.exports[0]?.get('targetId')).toBe(applied.get('targetId')); expect(calls.exports[0]?.get('to')).toBe(applied.get('to')); expect(calls.exports[0]?.get('page')).toBeNull()
|
||||
await page.locator('.diagnosis-query > .el-select').last().click(); await page.getByRole('option', { name: '监控告警', exact: true }).click(); await expect(page.getByRole('heading', { name: '关联事件' })).toHaveCount(0); await expect(page.getByRole('button', { name: '导出诊断包' })).toBeDisabled()
|
||||
await page.getByRole('button', { name: '查询诊断', exact: true }).click(); await expect(page.getByRole('heading', { name: '关联事件' })).toBeVisible(); expect(calls.queries.slice(-1)[0]?.get('source')).toBe('alerts')
|
||||
})
|
||||
|
||||
test('查询失败清除结果,导出超量显示后台错误', async ({ page }) => {
|
||||
const calls = await fixture(page, { queryError: true, exportError: true }); await page.goto('/diagnostics?targetType=terminal&targetId=t1'); await expect(page.getByRole('heading', { name: '关联事件' })).toBeVisible()
|
||||
await page.getByRole('button', { name: '导出诊断包' }).click(); await expect(page.getByText(/诊断事件超过 2000 条/)).toBeVisible()
|
||||
await page.locator('.diagnosis-query > .el-select').last().click(); await page.getByRole('option', { name: '执行任务', exact: true }).click(); await page.getByRole('button', { name: '查询诊断', exact: true }).click(); await expect(page.getByText(/诊断查询暂不可用/)).toBeVisible(); await expect(page.getByRole('heading', { name: '关联事件' })).toHaveCount(0); await expect(page.getByRole('button', { name: '导出诊断包' })).toBeDisabled(); expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('切换对象后较晚返回的旧查询不能覆盖新对象', async ({ page }) => {
|
||||
await fixture(page, { slow: true }); await page.goto('/diagnostics?targetType=terminal&targetId=t1')
|
||||
await page.getByRole('combobox', { name: '诊断对象', exact: true }).click(); await page.getByRole('option', { name: '同名盒子 / SN-2', exact: true }).click(); await page.getByRole('button', { name: '查询诊断', exact: true }).click()
|
||||
await expect(page.getByRole('heading', { name: '第二个同名盒子', exact: true })).toBeVisible(); await expect(page.getByText('第二个设备独立记录')).toBeVisible(); await expect(page.getByRole('heading', { name: '同名盒子', exact: true })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('采集先确认,取消不提交,提交与回执分开,结果失败可复用原幂等标识', async ({ page }) => {
|
||||
const calls = await fixture(page, { collectError: true }); await page.goto('/diagnostics?targetType=terminal&targetId=t1'); await page.getByRole('button', { name: '收集此设备日志' }).click()
|
||||
const confirm = page.locator('.el-message-box'); await expect(confirm).toContainText('不会重启设备'); await confirm.getByRole('button', { name: '取消', exact: true }).click(); expect(calls.writes).toHaveLength(0)
|
||||
await page.getByRole('button', { name: '收集此设备日志' }).click(); await confirm.getByRole('button', { name: '确认提交' }).click(); await expect(page.getByText(/提交结果尚未确认/)).toBeVisible()
|
||||
await page.getByRole('button', { name: '收集此设备日志' }).click(); await confirm.getByRole('button', { name: '确认提交' }).click(); await expect(page.getByText('本次日志采集 · 同名盒子')).toBeVisible(); await expect(page.getByRole('button', { name: '查看本次采集' })).toBeVisible()
|
||||
expect(calls.writes).toHaveLength(2); expect(calls.writes[0]?.key).toBeTruthy(); expect(calls.writes[0]?.key).toBe(calls.writes[1]?.key); expect(calls.writes[1]?.body).toEqual({ action: 'collect-logs' })
|
||||
await page.getByRole('button', { name: '查看本次采集' }).click(); await expect.poll(() => calls.queries.slice(-1)[0]?.get('source')).toBe('logs')
|
||||
})
|
||||
|
||||
for (const options of [{ offline: true }, { pending: true }]) test(`离线或有未知任务时禁止发起新采集 ${JSON.stringify(options)}`, async ({ page }) => {
|
||||
const calls = await fixture(page, options); await page.goto('/diagnostics?targetType=terminal&targetId=t1'); await expect(page.getByRole('button', { name: '收集此设备日志' })).toBeDisabled(); expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('只读角色隐藏高级入口且直接访问被拦截', async ({ page }) => {
|
||||
const calls = await fixture(page, { role: 'viewer' }); await page.goto('/overview'); await expect(page.getByRole('navigation', { name: '主导航' }).getByRole('link', { name: '日志与诊断' })).toHaveCount(0)
|
||||
await page.goto('/diagnostics?targetType=terminal&targetId=t1'); await expect(page).toHaveURL(/\/forbidden$/); expect(calls.queries).toHaveLength(0); expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('桌面视角与深浅主题、390宽度布局可读', async ({ page }, info) => {
|
||||
const calls = await fixture(page); await page.goto('/diagnostics?targetType=desktop&targetId=d1'); await expect(page.getByRole('heading', { name: '办公桌面', exact: true })).toBeVisible(); await expect(page.getByRole('button', { name: '收集此设备日志' })).toHaveCount(0)
|
||||
await page.screenshot({ path: info.outputPath('diagnostics-dark.png'), fullPage: true, animations: 'disabled' }); await page.getByRole('button', { name: '切换浅色主题' }).click(); await page.screenshot({ path: info.outputPath('diagnostics-light.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.setViewportSize({ width: 390, height: 844 }); expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); await page.screenshot({ path: info.outputPath('diagnostics-mobile.png'), fullPage: true, animations: 'disabled' }); expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
@@ -0,0 +1,166 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { role?: string; empty?: boolean; ambiguous?: boolean; fail?: string; id?: string; saved?: string; timeout?: boolean } = {}) {
|
||||
const writes: { path: string; body: Record<string, unknown> }[] = [], reads: string[] = []
|
||||
let users = options.empty ? [] : [{ id: 'u1', username: 'zhang', displayName: '张三', enabled: true, terminalId: 't1', desktopIds: ['d1'] }, { id: 'u2', username: 'li', displayName: '李四', enabled: false, terminalId: null, desktopIds: [] as string[] }]
|
||||
const desktops = options.empty ? [] : ['d1', 'd2', ...(options.ambiguous ? ['d3'] : [])].map((id, i) => ({ id, name: options.ambiguous && i === 2 ? '备用桌面' : i ? '备用桌面' : '办公桌面', os: 'Windows', node: 'pve', vmid: 100 + i, powerState: i ? 'stopped' : 'running', serviceState: i ? 'unknown' : 'ready', setupRequired: false, updatedAt: new Date().toISOString() }))
|
||||
const terminals = options.empty ? [] : [{ id: 't1', sn: 'SN-01', name: '前台盒子', enabled: true, status: 'offline', sessionDesktopId: null, lastSeen: new Date().toISOString() }, { id: 't2', sn: 'SN-02', name: '新盒子', enabled: true, status: 'unregistered', sessionDesktopId: null, lastSeen: null }]
|
||||
const task = { id: 'k1', targetId: 'd2', targetName: '备用桌面', kind: 'desktop', action: 'start', status: options.timeout ? 'timeout' : 'success', message: '等待核对', actor: 'admin', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }
|
||||
await page.addInitScript(({ id, saved }) => { sessionStorage.setItem('vdi.accessToken', 'editions-fixture'); if (saved) localStorage.setItem(`vdi.console-mode:${id}`, saved) }, { id: options.id || 'admin', saved: options.saved })
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', ''), method = request.method(), body = request.postData() ? request.postDataJSON() : {}
|
||||
const list = (items: unknown[], total = items.length) => route.fulfill({ json: { items, total, page: Number(url.searchParams.get('page') || 1), pageSize: 10, requestId: 'edition-ui' } })
|
||||
if (method !== 'GET') writes.push({ path, body }); else reads.push(path + url.search)
|
||||
if (options.fail === path && method !== 'GET' || options.fail === 'reads' && path === '/desktops' || options.fail === 'alerts' && path === '/monitor/alerts') { await route.fulfill({ status: 503, json: { code: 'unavailable', message: '当前服务不可用', requestId: 'edition-ui' } }); return }
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: options.id || 'admin', username: 'admin', displayName: '管理员', role: options.role || 'super_admin' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', pveConfigured: true, capabilities: [] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { activeSessions: 1, desktopCount: desktops.length, onlineTerminals: 0, terminalCount: terminals.length, runningDesktops: 1, failedTasks: 0 } }); return }
|
||||
if (path === '/desktops') { await list(desktops); return }
|
||||
if (path === '/users' && method === 'POST') { const user = { ...body, id: 'new-user', terminalId: null, desktopIds: [], enabled: true }; users.push(user); await route.fulfill({ status: 201, json: user }); return }
|
||||
if (path === '/users') { await list(users); return }
|
||||
if (path === '/terminals' && method === 'POST') { await route.fulfill({ status: 201, json: { id: 'new-terminal', activationSecret: 'one-time-test-secret' } }); return }
|
||||
if (path === '/terminals') { await list(terminals); return }
|
||||
if (path === '/users/batch-bindings') {
|
||||
users = users.map(u => body.userIds.includes(u.id) ? { ...u, desktopIds: body.action === 'grant' ? [...new Set([...u.desktopIds, ...body.desktopIds])] : u.desktopIds.filter(id => !body.desktopIds.includes(id)) } : u)
|
||||
await route.fulfill({ json: { affectedUsers: 1 } }); return
|
||||
}
|
||||
if (path.startsWith('/desktops/') && path.endsWith('/actions')) { await route.fulfill({ status: 202, json: task }); return }
|
||||
if (path === '/tasks') { await list(url.searchParams.get('active') ? options.timeout ? [task] : [] : [task]); return }
|
||||
if (path === '/audit-logs') { await list([{ id: 'a1', target: '张三', action: 'batch_grant_bindings', result: 'success', actor: 'admin', createdAt: new Date().toISOString() }], 21); return }
|
||||
if (path === '/monitor/alerts') { await route.fulfill({ json: { items: [], total: 0, firingCount: 0, unacknowledgedCount: 0 } }); return }
|
||||
if (path === '/resources') { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '未定义的测试接口' } })
|
||||
})
|
||||
return { writes, reads }
|
||||
}
|
||||
|
||||
test('默认通用版五个入口,切换高级版保留专业深链和账号偏好', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/')
|
||||
await expect(page).toHaveURL(/\/workbench$/); await expect(page.getByRole('heading', { name: '工作台', exact: true })).toBeVisible(); await expect(page.locator('.simple-stats .panel').first()).toContainText('运行中的桌面1 / 2 台桌面')
|
||||
const nav = page.getByRole('navigation', { name: '主导航' }); await expect(nav.getByRole('link')).toHaveCount(5)
|
||||
await expect(nav.getByRole('link', { name: 'GPU 资源' })).toHaveCount(0)
|
||||
await page.getByRole('button', { name: '高级版', exact: true }).click(); await expect(page).toHaveURL(/\/overview$/)
|
||||
await expect(nav.getByRole('link', { name: 'GPU 资源' })).toBeVisible(); await expect(nav.getByRole('link', { name: '镜像模板' })).toBeVisible()
|
||||
await page.goto('/'); await expect(page).toHaveURL(/\/overview$/)
|
||||
await page.goto('/people'); await expect(page.getByRole('button', { name: '通用版', exact: true })).toHaveAttribute('aria-pressed', 'true')
|
||||
await page.goto('/users'); await expect(page.getByRole('heading', { name: '用户与授权' })).toBeVisible()
|
||||
expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('另一个账号默认通用版,存储不可用时仍可切换', async ({ page }) => {
|
||||
await fixture(page, { id: 'reader' }); await page.addInitScript(() => { localStorage.setItem('vdi.console-mode:another-account', 'advanced'); Storage.prototype.setItem = () => { throw new Error('storage disabled') } })
|
||||
await page.goto('/'); await expect(page).toHaveURL(/\/workbench$/)
|
||||
await page.getByRole('button', { name: '高级版', exact: true }).click(); await expect(page).toHaveURL(/\/overview$/)
|
||||
})
|
||||
|
||||
test('授权先展示固定对象方案,确认才提交,追加和撤销保留其余授权', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/people')
|
||||
const row = page.getByRole('row').filter({ hasText: '张三' }).first()
|
||||
await row.getByRole('button', { name: '分配桌面', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '分配已有桌面' }); await dialog.locator('.el-checkbox').filter({ hasText: '备用桌面' }).click()
|
||||
await dialog.getByRole('button', { name: '查看方案' }).click(); await expect(dialog.getByText('确认变更方案')).toBeVisible(); expect(calls.writes).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '确认并保存授权' }).dblclick(); await expect(dialog).not.toBeVisible()
|
||||
expect(calls.writes).toEqual([{ path: '/users/batch-bindings', body: { userIds: ['u1'], desktopIds: ['d2'], action: 'grant' } }])
|
||||
await expect(row).toContainText('备用桌面'); await expect(row).toContainText('办公桌面'); await expect(row).toContainText('前台盒子')
|
||||
await row.getByRole('button', { name: '撤销授权' }).click(); const revoke = page.getByRole('dialog', { name: '撤销指定授权' })
|
||||
await revoke.locator('.el-checkbox').filter({ hasText: '备用桌面' }).click(); await revoke.getByRole('button', { name: '查看方案' }).click(); await revoke.getByRole('button', { name: '确认并保存授权' }).click()
|
||||
await expect(revoke).not.toBeVisible(); await expect(row).not.toContainText('备用桌面'); await expect(row).toContainText('办公桌面')
|
||||
expect(calls.writes[1]?.body).toEqual({ userIds: ['u1'], desktopIds: ['d2'], action: 'revoke' })
|
||||
})
|
||||
|
||||
test('授权失败保留方案,不显示成功或自动重发', async ({ page }) => {
|
||||
const calls = await fixture(page, { fail: '/users/batch-bindings' }); await page.goto('/people')
|
||||
await page.getByRole('row').filter({ hasText: '张三' }).first().getByRole('button', { name: '分配桌面' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '分配已有桌面' }); await dialog.locator('.el-checkbox').filter({ hasText: '备用桌面' }).click(); await dialog.getByRole('button', { name: '查看方案' }).click(); await dialog.getByRole('button', { name: '确认并保存授权' }).click()
|
||||
await expect(page.getByText(/当前服务不可用/)).toBeVisible(); await expect(dialog).toBeVisible(); expect(calls.writes).toHaveLength(1)
|
||||
})
|
||||
|
||||
for (const role of ['viewer', 'operator']) test(`${role}切换版本不提升权限`, async ({ page }) => {
|
||||
const calls = await fixture(page, { role }); await page.goto('/people')
|
||||
await expect(page.getByRole('button', { name: '添加员工' })).toHaveCount(0); await expect(page.getByRole('button', { name: '分配桌面', exact: true })).toHaveCount(0)
|
||||
if (role === 'viewer') await expect(page.getByRole('button', { name: '正常关机', exact: true })).toHaveCount(0)
|
||||
await page.getByRole('button', { name: '高级版', exact: true }).click(); await page.goto('/settings'); await expect(page).toHaveURL(/\/forbidden$/)
|
||||
expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('设备诊断只读,区分离线、等待激活与缺少关联', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/help?terminal=t1')
|
||||
await expect(page.getByText('未收到在线心跳,请检查盒子电源、网络和平台地址。')).toBeVisible(); await expect(page.getByText('使用人:张三')).toBeVisible(); await expect(page.getByText('桌面运行且连接服务就绪', { exact: false })).toBeVisible()
|
||||
await page.goto('/help?terminal=t2'); await expect(page.getByText('设备尚未激活', { exact: false })).toBeVisible(); await expect(page.getByText('请在员工与桌面中关联此设备。')).toBeVisible()
|
||||
expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('设备登记返回真实接口激活信息,关闭后移除且不持久化', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/devices'); await page.getByRole('button', { name: '登记新设备' }).click()
|
||||
await page.getByLabel('新设备名称').fill('新设备'); await page.getByLabel('新设备 SN').fill('SN-NEW'); await page.getByRole('button', { name: '登记并获取激活信息' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '请保存设备激活信息' }); await expect(dialog.getByLabel('设备激活密钥')).toHaveValue('one-time-test-secret')
|
||||
await dialog.getByRole('button', { name: '已保存,关闭' }).click(); await expect(dialog).not.toBeVisible()
|
||||
expect(await page.evaluate(() => JSON.stringify({ ...localStorage, ...sessionStorage }))).not.toContain('one-time-test-secret')
|
||||
expect(calls.writes[0]).toEqual({ path: '/terminals', body: { name: '新设备', sn: 'SN-NEW', group: '' } })
|
||||
})
|
||||
|
||||
test('电源操作取消不提交,结果未知时阻止重复操作', async ({ page }) => {
|
||||
const calls = await fixture(page, { timeout: true }); await page.goto('/people')
|
||||
const backup = page.getByRole('row').filter({ hasText: '备用桌面' }).last(); await expect(backup.getByRole('button', { name: '开机', exact: true })).toBeDisabled()
|
||||
await page.getByRole('button', { name: '重启桌面', exact: true }).click(); const dialog = page.locator('.el-message-box')
|
||||
await expect(dialog).toContainText('保存文件'); await dialog.getByRole('button', { name: '取消', exact: true }).click(); expect(calls.writes).toHaveLength(0)
|
||||
await page.getByRole('button', { name: '重启桌面', exact: true }).click(); await dialog.getByRole('button', { name: '确认提交', exact: true }).click()
|
||||
await expect.poll(() => calls.writes.length).toBe(1); expect(calls.writes[0]).toEqual({ path: '/desktops/d1/actions', body: { action: 'reboot' } })
|
||||
})
|
||||
|
||||
test('通用记录查历史审计和任务,服务端分页', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/records'); await expect(page.getByRole('cell', { name: '批量分配桌面' })).toBeVisible()
|
||||
await page.locator('.el-pagination .btn-next').click(); await expect.poll(() => calls.reads.some(p => p.includes('/audit-logs?') && p.includes('page=2'))).toBe(true)
|
||||
await page.getByRole('tab', { name: '设备与桌面任务' }).click(); await expect(page.getByRole('cell', { name: '等待核对' })).toBeVisible()
|
||||
expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('空态、告警失败和平台数据失败有明确提示', async ({ page }) => {
|
||||
await fixture(page, { empty: true, fail: 'alerts' }); await page.goto('/people'); await expect(page.getByText('暂无员工,请先添加员工')).toBeVisible()
|
||||
await page.goto('/help'); await expect(page.getByText(/告警读取失败,不能判断是否正常/)).toBeVisible(); await expect(page.getByText('当前没有触发中的告警')).toHaveCount(0)
|
||||
await page.unroute('**/api/v1/**'); await fixture(page, { fail: 'reads' }); await page.goto('/workbench'); await expect(page.getByText('数据刷新失败,当前信息可能已过期')).toBeVisible()
|
||||
})
|
||||
|
||||
test('通用工作台深浅主题与窄屏导航无溢出', async ({ page }, info) => {
|
||||
await fixture(page); await page.goto('/workbench'); await expect(page.getByRole('heading', { name: '你想完成什么?' })).toBeVisible()
|
||||
await page.screenshot({ path: info.outputPath('workbench-dark.png'), fullPage: true })
|
||||
await page.getByRole('button', { name: /切换浅色主题/ }).click(); await page.screenshot({ path: info.outputPath('workbench-light.png'), fullPage: true })
|
||||
await page.setViewportSize({ width: 390, height: 844 }); await page.getByRole('button', { name: '打开导航', exact: true }).click(); await expect(page.getByRole('navigation', { name: '主导航' }).getByRole('link', { name: '员工与桌面' })).toBeVisible()
|
||||
await page.getByRole('button', { name: '关闭导航', exact: true }).click(); expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
|
||||
await page.screenshot({ path: info.outputPath('workbench-mobile.png'), fullPage: true })
|
||||
})
|
||||
|
||||
test('通用工作台固定场景助手生成方案,确认后复用真实授权接口', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/workbench')
|
||||
await page.getByRole('textbox', { name: '描述需求', exact: true }).fill('给张三分配备用桌面')
|
||||
await page.getByRole('button', { name: '生成方案', exact: true }).click()
|
||||
await expect(page.getByText('可执行方案', { exact: true })).toBeVisible()
|
||||
await expect(page.getByRole('heading', { name: '分配已有桌面', exact: true })).toBeVisible()
|
||||
await expect(page.locator('.assistant-plan').getByText('备用桌面', { exact: false }).first()).toBeVisible()
|
||||
await page.getByRole('button', { name: '执行方案', exact: true }).click()
|
||||
await page.getByRole('button', { name: '确认提交', exact: true }).click()
|
||||
await expect(page.getByRole('button', { name: '已执行', exact: true })).toBeVisible()
|
||||
expect(calls.writes.filter(w => w.path === '/users/batch-bindings')).toHaveLength(1)
|
||||
expect(calls.writes.find(w => w.path === '/users/batch-bindings')?.body).toEqual({ userIds: ['u1'], desktopIds: ['d2'], action: 'grant' })
|
||||
})
|
||||
|
||||
test('通用工作台助手对未知或重复授权给出阻止方案,不发写请求', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/workbench')
|
||||
await page.getByRole('textbox', { name: '描述需求', exact: true }).fill('给不存在的人分配一台桌面')
|
||||
await page.getByRole('button', { name: '生成方案', exact: true }).click()
|
||||
await expect(page.getByText('需要补充信息', { exact: true })).toBeVisible()
|
||||
await expect(page.getByText('没有匹配到员工', { exact: false })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '描述需求', exact: true }).fill('给张三分配办公桌面')
|
||||
await page.getByRole('button', { name: '生成方案', exact: true }).click()
|
||||
await expect(page.getByText('授权已存在', { exact: false })).toBeVisible()
|
||||
expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('通用工作台助手不会在多个同名桌面之间自动选择', async ({ page }) => {
|
||||
const calls = await fixture(page, { ambiguous: true }); await page.goto('/workbench')
|
||||
await page.getByRole('textbox', { name: '描述需求', exact: true }).fill('给张三分配备用桌面')
|
||||
await page.getByRole('button', { name: '生成方案', exact: true }).click()
|
||||
await expect(page.getByText('需要补充信息', { exact: true })).toBeVisible()
|
||||
await expect(page.getByText('匹配到多个桌面', { exact: false })).toBeVisible()
|
||||
expect(calls.writes).toHaveLength(0)
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
async function fixture(page: Page, options: { role?: string; fail?: boolean; status?: string } = {}) {
|
||||
const writes: string[] = []
|
||||
const task = { id: 'gpu-task', kind: 'gpu-prepare', action: 'prepare-desktop', targetId: 'desk', targetName: '显卡办公桌面', actor: 'device:box', status: options.status || 'timeout', message: '等待核对', providerRef: '{}', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'gpu-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[]) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 20 } })
|
||||
if (request.method() !== 'GET') {
|
||||
writes.push(path)
|
||||
if (path !== '/tasks/gpu-task/gpu-reconcile') { await route.abort(); return }
|
||||
if (options.fail) { await route.fulfill({ status: 409, json: { code: 'unknown_submission', message: '未记录原 PVE 任务编号,需要在 PVE 手工核对,不能自动重发', requestId: 'gpu-ui' } }); return }
|
||||
task.status = 'failed'; task.message = '管理员已核对原 PVE 任务及实际电源状态,可重新准备桌面'
|
||||
await route.fulfill({ json: { reconciled: true, vmid: '100' } }); return
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'admin', username: 'admin', displayName: '管理员', role: options.role || 'operator' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', pveConfigured: true, capabilities: [] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: {} }); return }
|
||||
if (path === '/tasks') { await list(url.searchParams.get('active') && task.status !== 'timeout' ? [] : [task]); return }
|
||||
if (['/desktops', '/users', '/terminals', '/resources'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '未定义接口' } })
|
||||
})
|
||||
return writes
|
||||
}
|
||||
|
||||
test('高级版运维先确认再核对,取消无变更,成功后不再提供核对按钮', async ({ page }) => {
|
||||
const writes = await fixture(page); await page.goto('/tasks'); await page.getByRole('button', { name: '显卡办公桌面', exact: true }).click()
|
||||
const drawer = page.getByRole('dialog', { name: '任务详情' }); await drawer.getByRole('button', { name: '核对显卡准备结果', exact: true }).click()
|
||||
const confirm = page.locator('.el-message-box'); await expect(confirm).toContainText('不重发电源操作'); await expect(confirm).toContainText('原任务标记为失败')
|
||||
await confirm.getByRole('button', { name: '取消', exact: true }).click(); expect(writes).toHaveLength(0)
|
||||
await drawer.getByRole('button', { name: '核对显卡准备结果', exact: true }).click(); await confirm.getByRole('button', { name: '确认提交' }).click()
|
||||
await expect(drawer).not.toBeVisible(); expect(writes).toEqual(['/tasks/gpu-task/gpu-reconcile'])
|
||||
await page.getByRole('button', { name: '显卡办公桌面', exact: true }).click(); await expect(drawer.getByRole('button', { name: '核对显卡准备结果' })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('缺少原任务编号显示后台拒绝,保留未知状态且不自动重发', async ({ page }) => {
|
||||
const writes = await fixture(page, { fail: true }); await page.goto('/tasks'); await page.getByRole('button', { name: '显卡办公桌面', exact: true }).click()
|
||||
const drawer = page.getByRole('dialog', { name: '任务详情' }); await drawer.getByRole('button', { name: '核对显卡准备结果' }).click(); await page.locator('.el-message-box').getByRole('button', { name: '确认提交' }).click()
|
||||
await expect(page.getByText(/未记录原 PVE 任务编号/)).toBeVisible(); await expect(drawer).toBeVisible(); expect(writes).toEqual(['/tasks/gpu-task/gpu-reconcile'])
|
||||
})
|
||||
|
||||
for (const options of [{ role: 'viewer' }, { role: 'operator', status: 'success' }]) test(`角色${options.role}与状态${options.status || 'timeout'}限制核对`, async ({ page }) => {
|
||||
const writes = await fixture(page, options); await page.goto('/tasks'); await page.getByRole('button', { name: '显卡办公桌面', exact: true }).click()
|
||||
await expect(page.getByRole('dialog', { name: '任务详情' }).getByRole('button', { name: '核对显卡准备结果' })).toHaveCount(0); expect(writes).toHaveLength(0)
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { role?: string; partial?: boolean; fail?: boolean; empty?: boolean; configured?: boolean; stale?: boolean } = {}) {
|
||||
const writes: string[] = [], reads: string[] = [], now = new Date().toISOString()
|
||||
let fail = !!options.fail
|
||||
const reference = { vmid: 9000, vmName: 'win-reference', vmStatus: 'stopped', template: false, desktopId: 'desk-gpu', desktopName: '测试 Windows', slot: 'hostpci0', phase: 'current', source: 'direct', mapping: '', mediated: false, pendingRemoval: true }
|
||||
const inventory = () => ({ node: 'node-gpu', observedAt: new Date(Date.now() - (options.stale ? 120000 : 0)).toISOString(), complete: !options.partial, visibleVmCount: 2, scannedVmCount: options.partial ? 1 : 2, issues: options.partial ? [{ code: 'vm_config_unavailable', vmid: 9001, message: '无法读取虚拟机当前及待应用配置' }] : [], items: options.empty ? [] : [
|
||||
{ id: 'node-gpu:0000:00:02.0', address: '0000:00:02.0', name: 'Intel Integrated Graphics', vendor: 'Intel', vendorId: '0x8086', deviceId: '0x0416', class: '0x030000', iommuGroup: 0, state: options.partial ? 'unknown' : 'unreferenced', references: [] },
|
||||
{ id: 'node-gpu:0000:01:00.0', address: '0000:01:00.0', name: 'GeForce GTX Test', vendor: 'NVIDIA', vendorId: '0x10de', deviceId: '0x1234', class: '0x030200', iommuGroup: 2, state: 'multiple', references: [reference, { ...reference, vmid: 9001, vmName: 'ubuntu-unmanaged', desktopId: '', desktopName: '', phase: 'pending', source: 'mapping', mapping: 'gpu-shared-map', mediated: true, template: true, pendingRemoval: false }] },
|
||||
] })
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'gpu-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const r = route.request(), path = new URL(r.url()).pathname.replace('/api/v1', '')
|
||||
if (r.method() !== 'GET') { writes.push(path); await route.fulfill({ status: 403, json: { code: 'readonly_fixture', message: 'GPU 查看不应发送写请求', requestId: 'gpu-ui' } }); return }
|
||||
const list = (items: unknown[]) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 100, requestId: 'gpu-ui' } })
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'gpu-admin', username: 'gpu-reader', displayName: 'GPU 查看人员', role: options.role || 'viewer' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', computeProvider: 'proxmox', pveConfigured: options.configured !== false, terminalTransport: 'https-poll', capabilities: ['gpu-inventory'] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/resources') { await list(options.configured === false ? [] : [{ id: 'node-gpu', name: 'node-gpu', status: 'online', cpu: 0.2, memory: 0.5, storage: 0.3, provider: 'proxmox', updatedAt: now }]); return }
|
||||
if (path === '/resources/gpus') {
|
||||
reads.push(new URL(r.url()).searchParams.get('node') || '')
|
||||
if (fail) { fail = false; await route.fulfill({ status: 502, json: { code: 'pci_unavailable', message: '无法读取节点 PCI 清单,请检查 Sys.Audit 权限', requestId: 'gpu-ui' } }); return }
|
||||
await route.fulfill({ json: inventory() }); return
|
||||
}
|
||||
if (['/desktops', '/terminals', '/users', '/tasks', '/audit-logs'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { code: 'fixture_missing', message: '测试接口未定义', requestId: 'gpu-ui' } })
|
||||
})
|
||||
return { writes, reads }
|
||||
}
|
||||
|
||||
test('只读角色可查显卡并筛选配置引用,IOMMU 0 保留', async ({ page }, info) => {
|
||||
const requests = await fixture(page); await page.goto('/gpus')
|
||||
await expect(page.getByRole('heading', { name: 'Intel Integrated Graphics', exact: true })).toBeVisible()
|
||||
const intel = page.locator('.gpu-card').filter({ has: page.getByRole('heading', { name: 'Intel Integrated Graphics', exact: true }) })
|
||||
await expect(intel.getByText('未发现配置引用', { exact: true })).toBeVisible(); await expect(intel.locator('dd').filter({ hasText: /^0$/ })).toBeVisible()
|
||||
await expect(page.locator('.gpu-card').getByText('多 VM 引用', { exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '搜索 GPU' }).fill('win-reference'); await expect(page.locator('.gpu-card')).toHaveCount(1)
|
||||
await page.getByRole('textbox', { name: '搜索 GPU' }).clear()
|
||||
await page.screenshot({ path: info.outputPath('gpu-inventory-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await expect(page.getByText('GPU 清单按需读取,请手动刷新', { exact: true })).toBeVisible()
|
||||
expect(requests.reads).toEqual(['node-gpu']); expect(requests.writes).toEqual([])
|
||||
await expect(page.getByRole('button', { name: '绑定 GPU', exact: true })).toHaveCount(0)
|
||||
})
|
||||
test('详情区分当前与待应用、待移除、模板及未纳管的映射引用', async ({ page }, info) => {
|
||||
const requests = await fixture(page); await page.goto('/gpus')
|
||||
await page.locator('.gpu-card').filter({ has: page.getByRole('heading', { name: 'GeForce GTX Test', exact: true }) }).getByRole('button', { name: '查看 GPU 详情' }).click()
|
||||
const drawer = page.getByRole('dialog', { name: 'GPU 资源详情', exact: true })
|
||||
for (const text of ['当前配置', '待应用配置', '待移除', '模板', '介导设备', '尚未纳管为平台桌面']) await expect(drawer.getByText(text, { exact: true })).toBeVisible()
|
||||
await expect(drawer.getByText('hostpci0 · PCI 映射 gpu-shared-map', { exact: true })).toBeVisible()
|
||||
await expect(drawer.getByText('已纳管桌面:测试 Windows', { exact: true })).toBeVisible()
|
||||
await page.screenshot({ path: info.outputPath('gpu-reference-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
expect(requests.writes).toEqual([])
|
||||
})
|
||||
test('配置读取不完整显示待核查,不宣称显卡可用', async ({ page }) => {
|
||||
const requests = await fixture(page, { partial: true }); await page.goto('/gpus')
|
||||
await expect(page.getByRole('heading', { name: '检查未完整' })).toBeVisible()
|
||||
await expect(page.getByText('VM 9001:无法读取虚拟机当前及待应用配置', { exact: true })).toBeVisible()
|
||||
const intel = page.locator('.gpu-card').filter({ hasText: 'Intel Integrated Graphics' }); await expect(intel.getByText('待核查', { exact: true })).toBeVisible()
|
||||
await intel.getByRole('button', { name: '查看 GPU 详情' }).click(); await expect(page.getByText('检查范围不完整,引用情况待核查', { exact: true })).toBeVisible()
|
||||
expect(requests.writes).toEqual([])
|
||||
})
|
||||
test('PCI 权限错误提供重试,数据过期有明确提示', async ({ page }) => {
|
||||
const requests = await fixture(page, { fail: true, stale: true }); await page.goto('/gpus')
|
||||
await expect(page.getByText(/无法读取节点 PCI 清单,请检查 Sys.Audit 权限/)).toBeVisible()
|
||||
await page.getByRole('button', { name: '重试读取', exact: true }).click()
|
||||
await expect(page.getByText('数据已过期,请刷新', { exact: true })).toBeVisible()
|
||||
await expect(page.locator('.gpu-card')).toHaveCount(2); expect(requests.reads).toHaveLength(2); expect(requests.writes).toEqual([])
|
||||
})
|
||||
test('浅色窄屏清单和详情可读且页面不横向溢出', async ({ page }, info) => {
|
||||
await fixture(page); await page.addInitScript(() => localStorage.setItem('vdi.theme', 'light')); await page.setViewportSize({ width: 390, height: 844 }); await page.goto('/gpus')
|
||||
await expect(page.locator('.gpu-card')).toHaveCount(2)
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: info.outputPath('gpu-inventory-light-mobile.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('button', { name: '查看 GPU 详情' }).last().click()
|
||||
const drawer = page.getByRole('dialog', { name: 'GPU 资源详情', exact: true }); await expect(drawer.getByRole('heading', { name: 'GeForce GTX Test', exact: true })).toBeVisible()
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await expect.poll(async () => { const box = await drawer.boundingBox(); return box ? box.x + box.width : 999 }).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: info.outputPath('gpu-detail-light-mobile.png'), animations: 'disabled' })
|
||||
})
|
||||
test('空节点清单与尚未接入显示真实空态', async ({ page }) => {
|
||||
let requests = await fixture(page, { empty: true }); await page.goto('/gpus')
|
||||
await expect(page.getByText('当前节点未发现显示控制器类 PCI 设备', { exact: true })).toBeVisible(); expect(requests.writes).toEqual([])
|
||||
await page.unroute('**/api/v1/**'); requests = await fixture(page, { configured: false }); await page.reload()
|
||||
await expect(page.getByText('尚未接入 Proxmox', { exact: true })).toBeVisible(); await expect(page.getByRole('button', { name: '刷新 GPU 清单', exact: true })).toBeDisabled(); expect(requests.reads).toEqual([])
|
||||
})
|
||||
@@ -0,0 +1,142 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, role = 'super_admin', active = false) {
|
||||
const calls: { path: string; method: string; body: Record<string, unknown> }[] = []
|
||||
const terminals = [
|
||||
{ id: 't1', sn: 'TEST-BOX-001', name: '设计工位', group: '设计部', enabled: true, status: 'online', agentVersion: 'qt-test', lastSeen: '2026-11-10T02:00:00Z', sessionDesktopId: active ? 'd1' : null, sessionState: active ? 'connected' : 'idle', configVersion: 1, fps: null, rtt: null },
|
||||
{ id: 't2', sn: 'TEST-BOX-002', name: '备用终端', group: '备用组', enabled: false, status: 'disabled', agentVersion: '', lastSeen: null, sessionDesktopId: null, sessionState: 'idle', configVersion: 1, fps: null, rtt: null },
|
||||
]
|
||||
const users = [
|
||||
{ id: 'u1', username: 'designer', displayName: '设计人员', enabled: true, terminalId: 't1', desktopIds: ['d1'] },
|
||||
{ id: 'u2', username: 'office', displayName: '办公人员', enabled: true, terminalId: null, desktopIds: ['d1'] },
|
||||
]
|
||||
const desktops = [{ id: 'd1', name: '设计桌面', os: 'Windows', powerState: 'running' }, { id: 'd2', name: '办公桌面', os: 'Ubuntu', powerState: 'running' }]
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'lifecycle-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const r = route.request(), path = new URL(r.url()).pathname.replace('/api/v1', ''), method = r.method()
|
||||
const list = (items: unknown[]) => route.fulfill({ json: { items, page: 1, pageSize: 100, total: items.length, requestId: 'lifecycle-fixture' } })
|
||||
if (method !== 'GET') {
|
||||
const body = r.postData() ? r.postDataJSON() as Record<string, unknown> : {}; calls.push({ path, method, body })
|
||||
if (path === '/terminals/t1' && method === 'PUT') { Object.assign(terminals[0]!, body); await route.fulfill({ json: { accepted: true } }); return }
|
||||
if (path.endsWith('/disable')) { Object.assign(terminals[0]!, { enabled: false, status: 'disabled', lastSeen: null }); await route.fulfill({ json: { accepted: true } }); return }
|
||||
if (path.endsWith('/reactivate')) { const t = terminals.find(t => path.includes(t.id))!; Object.assign(t, { enabled: true, status: 'unregistered' }); await route.fulfill({ json: { id: t.id, activationSecret: 'activate_fixture_one_time' } }); return }
|
||||
if (path === '/users/u1') { Object.assign(users[0]!, body); await route.fulfill({ json: users[0] }); return }
|
||||
if (path === '/users/batch-bindings') {
|
||||
for (const u of users.filter(u => (body.userIds as string[]).includes(u.id))) u.desktopIds = body.action === 'grant' ? [...new Set([...u.desktopIds, ...body.desktopIds as string[]])] : u.desktopIds.filter(id => !(body.desktopIds as string[]).includes(id))
|
||||
await route.fulfill({ json: { accepted: true, userCount: (body.userIds as string[]).length } }); return
|
||||
}
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'admin', username: 'root', displayName: '平台管理员', role } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', pveConfigured: true, capabilities: [] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 2, onlineTerminals: 1, desktopCount: 2, runningDesktops: 2, activeSessions: active ? 1 : 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/terminals') { await list(terminals); return }
|
||||
if (path === '/users') { await list(users); return }
|
||||
if (path === '/desktops') { await list(desktops); return }
|
||||
if (['/tasks', '/audit-logs', '/resources'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { code: 'fixture_missing', message: '测试接口未定义', requestId: 'fixture' } })
|
||||
})
|
||||
return calls
|
||||
}
|
||||
|
||||
test('终端资料保存名称和分组,深浅主题与窄屏可用', async ({ page }, testInfo) => {
|
||||
const calls = await fixture(page)
|
||||
await page.setViewportSize({ width: 1440, height: 1000 }); await page.goto('/terminals')
|
||||
const row = page.getByRole('row').filter({ hasText: 'TEST-BOX-001' })
|
||||
await row.getByRole('button', { name: '编辑资料' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '编辑终端资料' })
|
||||
await dialog.getByLabel('编辑终端名称').fill('设计工位 A')
|
||||
await dialog.getByLabel('编辑终端分组').fill('研发一组')
|
||||
await dialog.getByRole('button', { name: '保存终端资料' }).click()
|
||||
await expect(dialog).toBeHidden(); await expect(row).toContainText('研发一组')
|
||||
expect(calls[0]).toEqual({ path: '/terminals/t1', method: 'PUT', body: { name: '设计工位 A', group: '研发一组' } })
|
||||
await page.screenshot({ path: testInfo.outputPath('terminals-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click()
|
||||
await page.screenshot({ path: testInfo.outputPath('terminals-light.png'), fullPage: true, animations: 'disabled' })
|
||||
await row.getByRole('button', { name: '详情', exact: true }).click()
|
||||
await page.screenshot({ path: testInfo.outputPath('terminal-detail-light.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: testInfo.outputPath('terminal-detail-mobile.png'), fullPage: true, animations: 'disabled' })
|
||||
})
|
||||
|
||||
test('停用与重新激活需要确认,旧凭据撤销提示和一次性密钥可见', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/terminals')
|
||||
await page.getByRole('row').filter({ hasText: 'TEST-BOX-001' }).getByRole('button', { name: '详情', exact: true }).click()
|
||||
await page.getByRole('button', { name: '停用设备', exact: true }).click()
|
||||
const box = page.locator('.el-message-box')
|
||||
await box.getByRole('button', { name: '取消', exact: true }).click(); expect(calls).toHaveLength(0)
|
||||
await page.getByRole('button', { name: '停用设备', exact: true }).click()
|
||||
await box.getByRole('button', { name: '确认提交' }).click()
|
||||
await expect(page.getByRole('button', { name: '停用设备', exact: true })).toHaveCount(0)
|
||||
await expect(page.getByRole('button', { name: '收集日志', exact: true })).toHaveCount(0)
|
||||
await page.getByRole('button', { name: '重新激活', exact: true }).click()
|
||||
await box.getByRole('button', { name: '取消', exact: true }).click(); expect(calls).toHaveLength(1)
|
||||
await page.getByRole('button', { name: '重新激活', exact: true }).click()
|
||||
await box.getByRole('button', { name: '确认提交' }).click()
|
||||
const activation = page.getByRole('dialog', { name: '终端激活信息', exact: true })
|
||||
await expect(activation.getByTestId('activation-secret')).toHaveText('activate_fixture_one_time')
|
||||
await activation.getByRole('button', { name: '已保存,关闭' }).click()
|
||||
await expect(activation).toBeHidden(); await expect(page.getByText('activate_fixture_one_time')).toHaveCount(0)
|
||||
expect(calls.map(c => c.path)).toEqual(['/terminals/t1/disable', '/terminals/t1/reactivate'])
|
||||
})
|
||||
|
||||
test('活动会话保护设备身份,运维和只读人员无设备维护入口', async ({ page }) => {
|
||||
const calls = await fixture(page, 'super_admin', true); await page.goto('/terminals')
|
||||
await page.getByRole('row').filter({ hasText: 'TEST-BOX-001' }).getByRole('button', { name: '详情', exact: true }).click()
|
||||
await expect(page.getByRole('button', { name: '停用设备', exact: true })).toBeDisabled()
|
||||
await expect(page.getByRole('button', { name: '重新激活', exact: true })).toBeDisabled(); expect(calls).toHaveLength(0)
|
||||
await page.unroute('**/api/v1/**'); await fixture(page, 'operator'); await page.reload()
|
||||
await page.getByRole('row').filter({ hasText: 'TEST-BOX-001' }).getByRole('button', { name: '详情', exact: true }).click()
|
||||
await expect(page.getByRole('button', { name: '停用设备', exact: true })).toHaveCount(0)
|
||||
await expect(page.getByRole('button', { name: '编辑资料', exact: true })).toHaveCount(0)
|
||||
await page.unroute('**/api/v1/**'); await fixture(page, 'viewer'); await page.goto('/users')
|
||||
await expect(page.getByRole('button', { name: '批量授权', exact: true })).toHaveCount(0)
|
||||
await expect(page.getByRole('button', { name: '编辑资料', exact: true })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('用户改名与停用保持授权,取消状态变更不提交', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/users')
|
||||
const row = page.getByRole('row').filter({ hasText: 'designer' })
|
||||
await row.getByRole('button', { name: '编辑资料', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '编辑用户资料', exact: true })
|
||||
await dialog.getByLabel('编辑用户姓名').fill('新设计人员')
|
||||
await dialog.locator('.el-switch').click()
|
||||
await dialog.getByRole('button', { name: '保存用户资料' }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '取消', exact: true }).click(); expect(calls).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '保存用户资料' }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认提交' }).click()
|
||||
await expect(dialog).toBeHidden(); await expect(row).toContainText('新设计人员'); await expect(row).toContainText('设计桌面')
|
||||
expect(calls[0]).toEqual({ path: '/users/u1', method: 'PUT', body: { displayName: '新设计人员', enabled: false } })
|
||||
})
|
||||
|
||||
test('批量授权明确目标和追加撤销语义,取消不提交', async ({ page }, testInfo) => {
|
||||
const calls = await fixture(page); await page.setViewportSize({ width: 1440, height: 1000 }); await page.goto('/users')
|
||||
for (const username of ['designer', 'office']) await page.getByRole('row').filter({ hasText: username }).locator('label.el-checkbox').click()
|
||||
await page.getByRole('button', { name: /批量授权/ }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '批量桌面授权', exact: true })
|
||||
await expect(dialog).toContainText('目标用户(2 位)')
|
||||
await expect(dialog.getByRole('button', { name: '提交批量授权' })).toBeDisabled()
|
||||
await dialog.locator('label.el-checkbox').filter({ hasText: '办公桌面 · Ubuntu' }).click()
|
||||
await dialog.getByRole('button', { name: '提交批量授权' }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '取消', exact: true }).click(); expect(calls).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '提交批量授权' }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认提交' }).click()
|
||||
await expect(dialog).toBeHidden()
|
||||
const row = page.getByRole('row').filter({ hasText: 'designer' })
|
||||
await expect(row).toContainText('设计桌面'); await expect(row).toContainText('办公桌面')
|
||||
await page.screenshot({ path: testInfo.outputPath('users-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click()
|
||||
await page.screenshot({ path: testInfo.outputPath('users-light.png'), fullPage: true, animations: 'disabled' })
|
||||
// Refresh intentionally clears table selection; choose targets again if needed.
|
||||
if (await page.getByRole('button', { name: /批量授权/ }).isDisabled()) for (const username of ['designer', 'office']) await page.getByRole('row').filter({ hasText: username }).locator('label.el-checkbox').click()
|
||||
await page.getByRole('button', { name: /批量授权/ }).click()
|
||||
await dialog.locator('label.el-radio-button').filter({ hasText: '撤销指定' }).click()
|
||||
await dialog.locator('label.el-checkbox').filter({ hasText: '办公桌面 · Ubuntu' }).click()
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: testInfo.outputPath('batch-users-mobile.png'), fullPage: true, animations: 'disabled' })
|
||||
await dialog.getByRole('button', { name: '提交批量授权' }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认提交' }).click()
|
||||
await expect(dialog).toBeHidden(); await expect(row).toContainText('设计桌面'); await expect(row).not.toContainText('办公桌面')
|
||||
expect(calls.map(c => c.body)).toEqual([{ userIds: ['u1', 'u2'], desktopIds: ['d2'], action: 'grant' }, { userIds: ['u1', 'u2'], desktopIds: ['d2'], action: 'revoke' }])
|
||||
})
|
||||
@@ -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,98 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { enabled?: boolean; fail?: boolean; loggedOut?: boolean } = {}) {
|
||||
const writes: { path: string; body: Record<string, string> }[] = []
|
||||
let enabled = options.enabled ?? false
|
||||
const codes = Array.from({ length: 8 }, (_, i) => `AAAAAAAA-BBBBBBBB-CCCCCCCC-${String(i).padStart(8, '0')}`)
|
||||
if (!options.loggedOut) await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'mfa-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), path = new URL(request.url()).pathname.replace('/api/v1', ''), body = request.postData() ? request.postDataJSON() : {}
|
||||
if (request.method() !== 'GET') writes.push({ path, body })
|
||||
const fail = (code: string, message: string, status = 400) => route.fulfill({ status, json: { code, message, requestId: 'mfa-ui' } })
|
||||
if (path === '/auth/login') {
|
||||
if (body.password !== 'Correct-password-2026') { await fail('invalid_credentials', '用户名或密码错误', 401); return }
|
||||
if (!body.code) { await fail('mfa_required', '请输入身份验证器动态码或一次性恢复码', 401); return }
|
||||
if (body.code !== '123456' && body.code !== codes[0]) { await fail('mfa_invalid', '验证码错误、已使用或已过期', 401); return }
|
||||
await route.fulfill({ json: { accessToken: 'logged-in-after-mfa', expiresIn: 3600, user: { id: 'reader', username: 'reader', displayName: '查看员', role: 'viewer' } } }); return
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'reader', username: 'reader', displayName: '查看员', role: 'viewer' } }); return }
|
||||
if (path === '/auth/mfa' && request.method() === 'GET') { await route.fulfill({ json: { enabled, recoveryRemaining: enabled ? 8 : 0 } }); return }
|
||||
if (path === '/auth/mfa/setup') {
|
||||
if (body.password !== 'Correct-password-2026') { await fail('current_password_invalid', '当前密码不正确'); return }
|
||||
await route.fulfill({ json: { secret: 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP', provisioningUri: 'otpauth://totp/VDI%20Cloud:reader?secret=example', expiresAt: new Date(Date.now() + 600000).toISOString() } }); return
|
||||
}
|
||||
if (path === '/auth/mfa/confirm') {
|
||||
if (options.fail || body.code !== '123456') { await fail('mfa_invalid', '验证码错误或已过期'); return }
|
||||
enabled = true; await route.fulfill({ json: { recoveryCodes: codes } }); return
|
||||
}
|
||||
if (path === '/auth/mfa/recovery') { await route.fulfill({ json: { recoveryCodes: codes } }); return }
|
||||
if (path === '/auth/mfa' && request.method() === 'DELETE') { enabled = false; await route.fulfill({ status: 204 }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', capabilities: ['admin-mfa'], pveConfigured: true } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (['/resources', '/desktops', '/users', '/terminals', '/tasks'].includes(path)) { await route.fulfill({ json: { items: [], total: 0, page: 1, pageSize: 100, requestId: 'mfa-ui' } }); return }
|
||||
await route.fulfill({ status: 404, json: { message: '测试接口未定义' } })
|
||||
})
|
||||
return { writes, codes }
|
||||
}
|
||||
|
||||
test('只读人员也可绑定本人验证器,确认后才开启,恢复码下载和关闭后不再显示', async ({ page }, info) => {
|
||||
const calls = await fixture(page); await page.goto('/overview'); await page.getByRole('button', { name: '双重验证', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '本人双重验证', exact: true })
|
||||
await expect(dialog.getByText('未开启', { exact: true })).toBeVisible()
|
||||
await dialog.getByLabel('双重验证当前密码', { exact: true }).fill('Correct-password-2026')
|
||||
await dialog.getByRole('button', { name: '开始绑定身份验证器' }).click()
|
||||
await expect(dialog.getByLabel('身份验证器密钥')).toBeVisible()
|
||||
expect(calls.writes.map(x => x.path)).toEqual(['/auth/mfa/setup'])
|
||||
await dialog.getByRole('textbox', { name: '绑定动态码' }).fill('123456'); await dialog.getByRole('button', { name: '验证并开启' }).click()
|
||||
await expect(dialog.getByText('恢复码仅显示这一次,请先保存')).toBeVisible()
|
||||
await expect(dialog.getByText(calls.codes[0]!, { exact: true })).toBeVisible()
|
||||
const download = page.waitForEvent('download'); await dialog.getByRole('button', { name: '下载恢复码' }).click(); expect((await download).suggestedFilename()).toBe('vdi-cloud-recovery-codes.txt')
|
||||
await page.screenshot({ path: info.outputPath('mfa-recovery-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await dialog.getByRole('button', { name: '已保存,关闭' }).click(); await page.getByRole('button', { name: '双重验证', exact: true }).click()
|
||||
await expect(dialog.getByText('已开启', { exact: true })).toBeVisible(); await expect(dialog.getByText(calls.codes[0]!, { exact: true })).toHaveCount(0)
|
||||
expect(await page.evaluate(() => JSON.stringify({ ...localStorage, ...sessionStorage }))).not.toContain('JBSWY3')
|
||||
})
|
||||
|
||||
test('验证码错误保持未完成绑定,窄屏和浅色布局可用,关闭清除密钥', async ({ page }, info) => {
|
||||
await fixture(page, { fail: true }); await page.goto('/overview'); await page.getByRole('button', { name: '切换浅色主题' }).click(); await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.getByRole('button', { name: '双重验证', exact: true }).click(); const dialog = page.getByRole('dialog', { name: '本人双重验证' })
|
||||
await dialog.getByLabel('双重验证当前密码', { exact: true }).fill('Correct-password-2026'); await dialog.getByRole('button', { name: '开始绑定身份验证器' }).click()
|
||||
await dialog.getByRole('textbox', { name: '绑定动态码' }).fill('111111'); await dialog.getByRole('button', { name: '验证并开启' }).click()
|
||||
await expect(dialog.getByText(/验证码错误或已过期/)).toBeVisible(); await expect(dialog.getByText('恢复码仅显示这一次,请先保存')).toHaveCount(0)
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: info.outputPath('mfa-setup-mobile-light.png'), fullPage: true, animations: 'disabled' })
|
||||
await dialog.getByRole('button', { name: '关闭', exact: true }).click(); await page.getByRole('button', { name: '双重验证', exact: true }).click(); await expect(dialog.getByText('未开启', { exact: true })).toBeVisible(); await expect(dialog.getByLabel('身份验证器密钥')).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('更新恢复码和关闭需要密码及验证码,取消不提交', async ({ page }) => {
|
||||
const calls = await fixture(page, { enabled: true }); await page.goto('/overview'); await page.getByRole('button', { name: '双重验证', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '本人双重验证' })
|
||||
await dialog.getByRole('button', { name: '关闭双重验证', exact: true }).click()
|
||||
await dialog.getByLabel('双重验证当前密码', { exact: true }).fill('Correct-password-2026'); await dialog.getByRole('textbox', { name: '双重验证确认码' }).fill('123456')
|
||||
await dialog.getByRole('button', { name: '确认关闭双重验证' }).click(); await page.locator('.el-message-box').getByRole('button', { name: '取消', exact: true }).click(); expect(calls.writes).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '确认关闭双重验证' }).click(); await page.locator('.el-message-box').getByRole('button', { name: '确认提交' }).click()
|
||||
await expect(dialog.getByText('未开启', { exact: true })).toBeVisible(); expect(calls.writes[0]?.body).toEqual({ password: 'Correct-password-2026', code: '123456' })
|
||||
})
|
||||
|
||||
test('重新生成恢复码经过确认后显示新码并支持下载', async ({ page }) => {
|
||||
const calls = await fixture(page, { enabled: true }); await page.goto('/overview'); await page.getByRole('button', { name: '双重验证', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '本人双重验证' })
|
||||
await dialog.getByRole('button', { name: '重新生成恢复码', exact: true }).click()
|
||||
await dialog.getByLabel('双重验证当前密码', { exact: true }).fill('Correct-password-2026'); await dialog.getByRole('textbox', { name: '双重验证确认码' }).fill(calls.codes[0]!)
|
||||
await dialog.getByRole('button', { name: '生成新恢复码', exact: true }).click(); expect(calls.writes).toHaveLength(0)
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认提交', exact: true }).click()
|
||||
await expect(dialog.getByText('恢复码仅显示这一次,请先保存')).toBeVisible()
|
||||
expect(calls.writes[0]?.path).toBe('/auth/mfa/recovery'); expect(calls.writes[0]?.body.code).toBe(calls.codes[0])
|
||||
const download = page.waitForEvent('download'); await dialog.getByRole('button', { name: '下载恢复码' }).click(); expect((await download).suggestedFilename()).toBe('vdi-cloud-recovery-codes.txt')
|
||||
})
|
||||
|
||||
for (const recovery of [false, true]) test(`登录先验证密码,动态码${recovery ? '使用恢复码' : '错误后重试'}成功前不保存令牌`, async ({ page }) => {
|
||||
const calls = await fixture(page, { loggedOut: true }); await page.goto('/login')
|
||||
await page.getByRole('textbox', { name: '用户名', exact: true }).fill('reader'); await page.getByLabel('密码', { exact: true }).fill('incorrect'); await page.getByRole('button', { name: '登录', exact: true }).click()
|
||||
await expect(page.getByText(/用户名或密码错误/)).toBeVisible(); await expect(page.getByRole('textbox', { name: '登录动态码或恢复码' })).toHaveCount(0)
|
||||
await page.getByLabel('密码', { exact: true }).fill('Correct-password-2026'); await page.getByRole('button', { name: '登录', exact: true }).click()
|
||||
const input = page.getByRole('textbox', { name: '登录动态码或恢复码' }); await expect(input).toBeVisible(); expect(await page.evaluate(() => sessionStorage.getItem('vdi.accessToken'))).toBeNull()
|
||||
await input.fill('111111'); await page.getByRole('button', { name: '登录', exact: true }).click(); await expect(page.getByText(/验证码错误、已使用或已过期/)).toBeVisible(); await expect(input).toHaveValue('')
|
||||
await input.fill(recovery ? calls.codes[0]! : '123456'); await page.getByRole('button', { name: '登录', exact: true }).click(); await expect(page).toHaveURL(/\/workbench$/)
|
||||
expect(await page.evaluate(() => sessionStorage.getItem('vdi.accessToken'))).toBe('logged-in-after-mfa')
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, role = 'super_admin') {
|
||||
const calls: { path: string; body: Record<string, unknown> }[] = []
|
||||
const now = new Date(), earlier = new Date(now.getTime() - 180000).toISOString()
|
||||
let acknowledged = false
|
||||
const rules = [{ id: 'r1', name: '节点 CPU 高水位', metric: 'node_cpu', threshold: 90, holdSeconds: 120, enabled: true }]
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'operations-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), path = new URL(request.url()).pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[], extra = {}) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 20, ...extra } })
|
||||
if (request.method() !== 'GET') {
|
||||
const body = request.postData() ? request.postDataJSON() as Record<string, unknown> : {}; calls.push({ path, body })
|
||||
if (path === '/imports/preview') {
|
||||
const invalid = String(body.csv).includes('bad'), terminal = body.kind === 'terminals'
|
||||
await route.fulfill({ json: { kind: body.kind, totalRows: 1, validRows: invalid ? 0 : 1, errorRows: invalid ? 1 : 0, previewToken: invalid ? '' : 'preview-token', rows: [{ line: 2, key: terminal ? 'BULK-001' : 'imported', values: terminal ? { sn: 'BULK-001', name: '批量设备', group: '研发' } : { username: 'imported', displayName: '导入用户' }, errors: invalid ? ['该账号已存在'] : [] }] } }); return
|
||||
}
|
||||
if (path === '/imports/commit') { await route.fulfill({ json: { id: 'i1', kind: body.kind, count: 1, replayed: false, items: [{ line: 2, key: 'imported', id: 'new-id' }], activationSecrets: body.kind === 'terminals' ? [{ sn: 'BULK-001', activationSecret: 'activate_test_only' }] : [] } }); return }
|
||||
if (path.endsWith('/acknowledge')) { acknowledged = true; await route.fulfill({ json: { accepted: true } }); return }
|
||||
if (path === '/monitor/rules' || path === '/monitor/rules/r1') { Object.assign(rules[0]!, body); await route.fulfill({ json: rules[0] }); return }
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'admin', username: 'root', displayName: '平台管理员', role } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', pveConfigured: true, capabilities: [] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/resources') { await list([{ id: 'node1', name: '计算节点', provider: 'proxmox', status: 'online', cpu: .4, memory: .6, storage: .5 }]); return }
|
||||
if (path === '/sessions/history') { await list([{ id: 'h1', sessionId: 's1', terminalId: 't1', terminalName: '历史终端', desktopId: 'd1', desktopName: 'Windows 桌面', username: 'imported', displayName: '研发人员', state: 'interrupted', source: 'ticket', reservedAt: earlier, connectedAt: earlier, lastReportedAt: earlier, endedAt: now.toISOString(), endReason: 'heartbeat_timeout' }]); return }
|
||||
if (path === '/monitor/rules') { await list(rules); return }
|
||||
if (path === '/monitor/series') { await route.fulfill({ json: { bucketSeconds: 300, retentionDays: 30, items: [{ time: earlier, cpu: 94, memory: 60, storage: null, samples: 1 }, { time: now.toISOString(), cpu: 95, memory: 61, storage: null, samples: 1 }] } }); return }
|
||||
if (path === '/monitor/alerts') { await list([{ id: 'a1', ruleId: 'r1', ruleName: '节点 CPU 高水位', metric: 'node_cpu', targetId: 'node1', targetName: '计算节点', value: 95, threshold: 90, status: 'firing', startedAt: earlier, openedAt: earlier, resolvedAt: null, resolveReason: '', acknowledgedAt: acknowledged ? now.toISOString() : null, acknowledgedBy: acknowledged ? 'root' : '' }], { firingCount: 1, unacknowledgedCount: acknowledged ? 0 : 1 }); return }
|
||||
if (['/tasks', '/audit-logs', '/terminals', '/users', '/desktops'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { code: 'fixture_missing', message: path } })
|
||||
})
|
||||
return calls
|
||||
}
|
||||
|
||||
test('CSV 预检有错误不能提交,修改后重新预检并整批导入', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/users')
|
||||
await page.getByRole('button', { name: '导入用户', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '批量新增用户' })
|
||||
await dialog.getByLabel('CSV 内容').fill('username,displayName\nbad,重复\n')
|
||||
await dialog.getByRole('button', { name: '预检文件' }).click()
|
||||
await expect(dialog.getByText('该账号已存在', { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByRole('button', { name: '提交导入' })).toBeDisabled()
|
||||
const download = page.waitForEvent('download'); await dialog.getByRole('button', { name: '下载错误行' }).click(); expect((await download).suggestedFilename()).toBe('import-errors.csv')
|
||||
await dialog.getByLabel('CSV 内容').fill('username,displayName\nimported,导入用户\n')
|
||||
await dialog.getByRole('button', { name: '预检文件' }).click()
|
||||
await expect(dialog.getByRole('button', { name: '提交导入' })).toBeEnabled()
|
||||
await dialog.getByRole('button', { name: '提交导入' }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认导入' }).click()
|
||||
await expect(dialog.getByText('导入完成', { exact: true })).toBeVisible()
|
||||
expect(calls.filter(c => c.path.endsWith('/commit'))).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('批量终端激活信息支持下载,未下载关闭需要确认且密钥不残留', async ({ page }) => {
|
||||
await fixture(page); await page.goto('/terminals')
|
||||
await page.getByRole('button', { name: '批量导入', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '批量登记终端' })
|
||||
await dialog.getByLabel('CSV 内容').fill('sn,name,group\nBULK-001,批量设备,研发\n')
|
||||
await dialog.getByRole('button', { name: '预检文件' }).click(); await dialog.getByRole('button', { name: '提交导入' }).click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '确认导入' }).click()
|
||||
await expect(dialog.getByText('导入完成', { exact: true })).toBeVisible()
|
||||
await dialog.getByRole('button', { name: '关闭', exact: true }).last().click()
|
||||
await page.locator('.el-message-box').getByRole('button', { name: '返回保存' }).click()
|
||||
const downloaded = page.waitForEvent('download'); await dialog.getByRole('button', { name: '下载终端激活信息' }).click(); expect((await downloaded).suggestedFilename()).toBe('terminal-activation.csv')
|
||||
await dialog.getByRole('button', { name: '关闭', exact: true }).last().click(); await expect(dialog).toBeHidden()
|
||||
await page.getByRole('button', { name: '批量导入', exact: true }).click(); await expect(dialog.getByRole('button', { name: '下载终端激活信息' })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('会话历史按需查询,展示心跳超时和实际连接时长', async ({ page }, testInfo) => {
|
||||
await fixture(page); await page.goto('/sessions'); await page.getByRole('tab', { name: '历史记录' }).click()
|
||||
await expect(page.getByText('历史终端', { exact: true })).toBeVisible(); await expect(page.getByText('心跳超时', { exact: true })).toBeVisible()
|
||||
await expect(page.getByText('3 分 0 秒')).toBeVisible()
|
||||
await page.getByLabel('搜索历史会话').fill('历史终端'); await page.getByRole('button', { name: '查询历史' }).click()
|
||||
await page.screenshot({ path: testInfo.outputPath('session-history.png'), fullPage: true, animations: 'disabled' })
|
||||
})
|
||||
|
||||
test('告警确认保留正在告警状态,规则编辑和深浅窄屏可用', async ({ page }, testInfo) => {
|
||||
const calls = await fixture(page); await page.setViewportSize({ width: 1440, height: 1050 }); await page.goto('/monitor')
|
||||
await expect(page.getByRole('img', { name: 'CPU 使用率历史趋势' })).toBeVisible()
|
||||
await expect(page.getByText('此范围暂无有效采样')).toBeVisible()
|
||||
await page.getByRole('button', { name: '确认告警' }).click(); await expect(page.getByRole('button', { name: '确认告警' })).toHaveCount(0)
|
||||
await expect(page.getByRole('cell', { name: '正在告警', exact: true })).toBeVisible()
|
||||
await page.screenshot({ path: testInfo.outputPath('monitor-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click()
|
||||
await page.screenshot({ path: testInfo.outputPath('monitor-light.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('tab', { name: '告警规则' }).click(); await page.getByRole('button', { name: '编辑规则' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '编辑告警规则' })
|
||||
await dialog.getByLabel('规则名称', { exact: true }).fill('CPU 持续高水位')
|
||||
await dialog.getByRole('button', { name: '保存规则' }).click(); await expect(dialog).toBeHidden()
|
||||
expect(calls.find(c => c.path === '/monitor/rules/r1')?.body.name).toBe('CPU 持续高水位')
|
||||
await page.setViewportSize({ width: 390, height: 844 }); expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: testInfo.outputPath('monitor-mobile.png'), fullPage: true, animations: 'disabled' })
|
||||
})
|
||||
|
||||
test('只读人员可查监控及历史,无导入、确认或规则编辑入口', async ({ page }) => {
|
||||
await fixture(page, 'viewer'); await page.goto('/monitor')
|
||||
await expect(page.getByText('节点 CPU 高水位', { exact: true })).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: '确认告警' })).toHaveCount(0)
|
||||
await page.getByRole('tab', { name: '告警规则' }).click(); await expect(page.getByRole('button', { name: '编辑规则' })).toHaveCount(0)
|
||||
await expect(page.getByRole('button', { name: '新增规则' })).toHaveCount(0)
|
||||
await page.goto('/users'); await expect(page.getByRole('button', { name: '导入用户', exact: true })).toHaveCount(0)
|
||||
})
|
||||
@@ -0,0 +1,99 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, role = 'super_admin') {
|
||||
const calls: { path: string; body: Record<string, unknown>; key: string | undefined }[] = []
|
||||
const templates = [{ id: 'p1', name: '标准办公', version: '1.0', heartbeatInterval: 30, commandPollInterval: 3, desktopRefreshInterval: 15, createdAt: '2026-11-10T03:00:00Z' }]
|
||||
const states = [
|
||||
{ id: '', terminalId: 't1', terminalName: '设计工位', group: '设计组', protocol: 1, deploymentId: '', templateName: '', templateVersion: '', configVersion: 1, status: 'unconfigured', errorCode: '', acknowledgedAt: null, online: true, enabled: true, registered: true },
|
||||
{ id: 'r0', terminalId: 't2', terminalName: '备用终端', group: '设计组', protocol: 1, deploymentId: 'd0', templateName: '标准办公', templateVersion: '1.0', configVersion: 2, status: 'failed', errorCode: 'persist_failed', acknowledgedAt: '2026-11-10T03:10:00Z', online: false, enabled: true, registered: true },
|
||||
{ id: '', terminalId: 't3', terminalName: '旧客户端', group: '旧设备组', protocol: 0, deploymentId: '', templateName: '', templateVersion: '', configVersion: 1, status: 'unconfigured', errorCode: '', acknowledgedAt: null, online: true, enabled: true, registered: true },
|
||||
]
|
||||
const deployments = [{ id: 'd0', templateId: 'p1', templateName: '标准办公', templateVersion: '1.0', actor: 'root', targetCount: 1, createdAt: '2026-11-10T03:00:00Z' }]
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'policies-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const req = route.request(), path = new URL(req.url()).pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[]) => route.fulfill({ json: { items, page: 1, pageSize: 100, total: items.length, requestId: 'policy-fixture' } })
|
||||
if (req.method() === 'POST') {
|
||||
const body = req.postDataJSON() as Record<string, unknown>; calls.push({ path, body, key: req.headers()['idempotency-key'] })
|
||||
if (path === '/terminal-policy-templates') { const t = { ...templates[0]!, ...body, id: 'p2' }; templates.unshift(t); await route.fulfill({ status: 201, json: t }); return }
|
||||
if (path === '/terminal-policy-deployments') {
|
||||
const chosen = states.filter(s => body.targetMode === 'group' ? s.group === body.group : (body.terminalIds as string[]).includes(s.terminalId))
|
||||
const d = { ...deployments[0]!, id: 'd1', targetCount: chosen.length }; deployments.unshift(d)
|
||||
for (const s of chosen) Object.assign(s, { status: 'pending', deploymentId: 'd1', templateName: '标准办公', templateVersion: '1.0', configVersion: s.configVersion + 1, errorCode: '', acknowledgedAt: null })
|
||||
await route.fulfill({ status: 202, json: d }); return
|
||||
}
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'a', username: 'root', displayName: '管理员', role } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 3, onlineTerminals: 2, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', pveConfigured: true, capabilities: ['terminal-policies'] } }); return }
|
||||
if (path === '/terminal-policy-templates') { await list(templates); return }
|
||||
if (path === '/terminal-policy-states') { await list(states); return }
|
||||
if (path === '/terminal-policy-deployments') { await list(deployments); return }
|
||||
if (/\/terminal-policy-deployments\/.*\/results/.test(path)) { await list(states.filter(s => s.deploymentId === path.split('/')[2])); return }
|
||||
if (['/terminals', '/users', '/resources', '/tasks', '/desktops', '/audit-logs'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { code: 'fixture_missing', message: path, requestId: 'fixture' } })
|
||||
})
|
||||
return calls
|
||||
}
|
||||
|
||||
test('策略版本可保存和复制,深浅主题及手机表单可用', async ({ page }, info) => {
|
||||
const calls = await fixture(page); await page.setViewportSize({ width: 1440, height: 1000 }); await page.goto('/terminal-policies')
|
||||
await expect(page.getByRole('heading', { name: '终端策略', exact: true })).toBeVisible()
|
||||
await page.getByRole('button', { name: '新建策略', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '新建终端策略版本' })
|
||||
await dialog.getByLabel('策略名称', { exact: true }).fill('研发组')
|
||||
await dialog.getByLabel('策略版本', { exact: true }).fill('2.0')
|
||||
await dialog.getByLabel('命令检查间隔', { exact: true }).fill('5')
|
||||
await dialog.getByRole('button', { name: '保存策略版本' }).click(); await expect(dialog).toBeHidden()
|
||||
expect(calls[0]?.body).toEqual({ name: '研发组', version: '2.0', heartbeatInterval: 30, commandPollInterval: 5, desktopRefreshInterval: 15 })
|
||||
await page.screenshot({ path: info.outputPath('policies-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click()
|
||||
await page.screenshot({ path: info.outputPath('policies-light.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('row').filter({ hasText: '研发组' }).getByRole('button', { name: '复制新版本' }).click()
|
||||
await expect(dialog.getByLabel('策略版本', { exact: true })).toHaveValue('')
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: info.outputPath('policy-create-mobile.png'), fullPage: true, animations: 'disabled' })
|
||||
await dialog.getByRole('button', { name: '取消', exact: true }).click(); expect(calls).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('按分组下发先确认,提交后等待设备回执,不显示已应用', async ({ page }, info) => {
|
||||
const calls = await fixture(page); await page.goto('/terminal-policies')
|
||||
await page.getByRole('row').filter({ hasText: '标准办公' }).getByRole('button', { name: '下发', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '下发终端策略', exact: true })
|
||||
await dialog.getByText('指定分组', { exact: true }).click()
|
||||
await dialog.locator('.el-select').filter({ has: page.getByLabel('选择策略分组') }).click(); await page.getByRole('option', { name: '设计组', exact: true }).click()
|
||||
await expect(dialog).toContainText('本次 2 台')
|
||||
await dialog.getByRole('button', { name: '提交下发' }).click()
|
||||
const box = page.locator('.el-message-box'); await box.getByRole('button', { name: '取消', exact: true }).click(); expect(calls).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '提交下发' }).click(); await box.getByRole('button', { name: '确认下发', exact: true }).click()
|
||||
const drawer = page.getByRole('dialog', { name: '策略下发结果', exact: true })
|
||||
await expect(drawer.getByText('等待设备应用', { exact: true })).toHaveCount(2)
|
||||
await expect(drawer.getByText('已应用', { exact: true })).toHaveCount(0)
|
||||
await expect(drawer).toContainText('离线等待')
|
||||
expect(calls[0]?.body).toEqual({ templateId: 'p1', targetMode: 'group', group: '设计组' }); expect(calls[0]?.key).toBeTruthy()
|
||||
await page.screenshot({ path: info.outputPath('policy-results-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
})
|
||||
|
||||
test('旧客户端分组禁止下发,失败原因和重试入口可查看', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/terminal-policies')
|
||||
await page.getByRole('tab', { name: '设备结果', exact: true }).click()
|
||||
await expect(page.getByRole('row').filter({ hasText: '旧客户端' })).toContainText('需更新客户端')
|
||||
const failed = page.getByRole('row').filter({ hasText: '备用终端' }); await expect(failed).toContainText('设备无法安全保存配置')
|
||||
await failed.getByRole('button', { name: '重新下发' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '下发终端策略', exact: true }); await expect(dialog).toContainText('本次 1 台')
|
||||
await dialog.getByText('指定分组', { exact: true }).click(); await dialog.locator('.el-select').filter({ has: page.getByLabel('选择策略分组') }).click(); await page.getByRole('option', { name: '旧设备组', exact: true }).click()
|
||||
await expect(dialog.getByRole('button', { name: '提交下发' })).toBeDisabled(); await expect(dialog).toContainText('旧客户端设备')
|
||||
await dialog.getByRole('button', { name: '取消', exact: true }).click(); expect(calls).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('只读和运维角色只能查看策略与结果', async ({ page }) => {
|
||||
for (const role of ['viewer', 'operator']) {
|
||||
await page.unroute('**/api/v1/**'); const calls = await fixture(page, role); await page.goto('/terminal-policies'); await page.reload()
|
||||
await expect(page.getByRole('heading', { name: '终端策略', exact: true })).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: '新建策略', exact: true })).toHaveCount(0)
|
||||
await expect(page.getByRole('button', { name: '下发', exact: true })).toHaveCount(0)
|
||||
await page.getByRole('tab', { name: '设备结果', exact: true }).click()
|
||||
await expect(page.getByRole('button', { name: '重新下发', exact: true })).toHaveCount(0); expect(calls).toHaveLength(0)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,115 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
// All requests are intercepted. No live VM receives snapshot or power actions.
|
||||
async function fixture(page: Page, options: { running?: boolean; role?: string; deny?: boolean; empty?: boolean; fail?: boolean; retry?: boolean } = {}) {
|
||||
const requests: { path: string; body: Record<string, unknown>; key?: string }[] = [], now = new Date().toISOString()
|
||||
const desktop = { id: 'desk-snap', name: '快照验收桌面', vmid: 9000, node: 'test', os: 'Windows', pool: '', poolId: null, provider: 'proxmox', powerState: options.running ? 'running' : 'stopped', serviceState: 'unknown', setupRequired: false, endpoint: '192.0.2.90', app: 'Desktop', width: 1920, height: 1080, fps: 30, updatedAt: now }
|
||||
const items = options.empty ? [] : [{ name: 'baseline', description: '安装完成', createdAt: 1794268800, parent: '', includesMemory: false, state: '', revision: 'snap-v1' }, { name: 'with_memory', description: '保存内存', createdAt: 1794268801, parent: '', includesMemory: true, state: '', revision: 'memory-v1' }, { name: 'child', description: '后续版本', createdAt: 1794268802, parent: 'with_memory', includesMemory: false, state: '', revision: 'child-v1' }]
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'snapshot-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const r = route.request(), path = new URL(r.url()).pathname.replace('/api/v1', '')
|
||||
const list = (values: unknown[]) => route.fulfill({ json: { items: values, total: values.length, page: 1, pageSize: 100, requestId: 'snapshot-ui' } })
|
||||
if (r.method() !== 'GET') {
|
||||
requests.push({ path, body: r.postData() ? r.postDataJSON() : {}, key: r.headers()['idempotency-key'] })
|
||||
if (path.endsWith('/snapshots/check')) { await route.fulfill({ json: { available: true, message: '快照预检通过' } }); return }
|
||||
if (path.endsWith('/snapshots/actions')) {
|
||||
if (options.retry && requests.filter(x => x.path === path).length === 1) { await route.fulfill({ status: 503, json: { code: 'unavailable', message: '网络暂时不可用', requestId: 'snapshot-ui' } }); return }
|
||||
await route.fulfill({ status: 202, json: { id: 'task-snap', kind: 'snapshot', action: 'snapshot-create', targetId: desktop.id, targetName: desktop.name, actor: 'root', status: 'queued', message: '等待执行', providerRef: '', createdAt: now, updatedAt: now } }); return
|
||||
}
|
||||
if (path.endsWith('/snapshot-reconcile')) { await route.fulfill({ json: { accepted: true } }); return }
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'admin-snap', username: 'root', displayName: '验收管理员', role: options.role || 'super_admin' } }); return }
|
||||
if (path.endsWith('/snapshots')) { await route.fulfill(options.fail ? { status: 502, json: { code: 'snapshots_unavailable', message: '无法读取 PVE 快照', requestId: 'snapshot-ui' } } : { json: { items, digest: 'd1', powerState: desktop.powerState, blockers: options.running ? ['请先正常关闭桌面,再管理快照'] : [], disks: ['scsi0', 'efidisk0'], canCreate: !options.deny, canDelete: !options.deny, canRestore: !options.deny } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', computeProvider: 'proxmox', pveConfigured: true, terminalTransport: 'https-poll', capabilities: [] } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: 1, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/desktops') { await list([desktop]); return }
|
||||
if (path === '/tasks') { await list([{ id: 'snap-timeout', kind: 'snapshot', action: 'snapshot-rollback', targetId: desktop.id, targetName: desktop.name, actor: 'root', status: 'timeout', message: '快照结果未确认,不会自动重发', providerRef: 'UPID:old', createdAt: now, updatedAt: now }]); return }
|
||||
if (['/terminals', '/users', '/resources', '/audit-logs'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { code: 'missing_fixture', message: '未定义测试接口', requestId: 'snapshot-ui' } })
|
||||
})
|
||||
return requests
|
||||
}
|
||||
async function open(page: Page) {
|
||||
await page.goto('/desktops'); await page.getByRole('button', { name: '查看详情', exact: true }).click(); await page.getByRole('button', { name: '快照与还原', exact: true }).click()
|
||||
return page.getByRole('dialog', { name: '快照与还原', exact: true })
|
||||
}
|
||||
test('创建快照先预检,参数改变失效,取消不写,确认提交', async ({ page }, info) => {
|
||||
const requests = await fixture(page, { empty: true }), dialog = await open(page)
|
||||
await expect(dialog.getByText('尚无快照,可在关机后创建恢复点')).toBeVisible()
|
||||
await dialog.getByRole('textbox', { name: '快照名称', exact: true }).fill('before_update')
|
||||
await dialog.getByRole('button', { name: '预检快照操作', exact: true }).click()
|
||||
await expect(dialog.getByRole('button', { name: '提交创建快照', exact: true })).toBeEnabled()
|
||||
await dialog.getByRole('textbox', { name: '快照描述', exact: true }).fill('升级之前')
|
||||
await expect(dialog.getByRole('button', { name: '提交创建快照', exact: true })).toBeDisabled()
|
||||
await dialog.getByRole('button', { name: '预检快照操作', exact: true }).click()
|
||||
await page.screenshot({ path: info.outputPath('snapshot-create-dark.png'), fullPage: true })
|
||||
await dialog.getByRole('button', { name: '提交创建快照', exact: true }).click()
|
||||
await page.getByRole('button', { name: '取消', exact: true }).click()
|
||||
expect(requests.filter(r => r.path.endsWith('/actions'))).toHaveLength(0)
|
||||
await dialog.getByRole('button', { name: '提交创建快照', exact: true }).click()
|
||||
await page.getByRole('button', { name: '提交创建快照任务', exact: true }).click()
|
||||
await expect(dialog).not.toBeVisible()
|
||||
const writes = requests.filter(r => r.path.endsWith('/actions'))
|
||||
expect(writes).toHaveLength(1); expect(writes[0]?.body).toEqual({ action: 'create', name: 'before_update', description: '升级之前', digest: 'd1' }); expect(writes[0]?.key).toBeTruthy()
|
||||
})
|
||||
test('还原需输入当前 VMID,保留磁盘范围提示,支持浅色窄屏', async ({ page }, info) => {
|
||||
const requests = await fixture(page)
|
||||
await page.addInitScript(() => localStorage.setItem('vdi.theme', 'light'))
|
||||
await page.setViewportSize({ width: 390, height: 844 }); const dialog = await open(page)
|
||||
await dialog.locator('.snapshot-item').filter({ hasText: 'baseline' }).getByRole('button', { name: '还原', exact: true }).click()
|
||||
await expect(dialog.getByText(/包括快照中的数据盘/)).toBeVisible()
|
||||
await expect(dialog.getByRole('button', { name: '预检快照操作', exact: true })).toBeDisabled()
|
||||
await dialog.getByRole('textbox', { name: '还原确认 VMID', exact: true }).fill('100')
|
||||
await expect(dialog.getByRole('button', { name: '预检快照操作', exact: true })).toBeDisabled()
|
||||
await dialog.getByRole('textbox', { name: '还原确认 VMID', exact: true }).fill('9000')
|
||||
await dialog.getByRole('button', { name: '预检快照操作', exact: true }).click()
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await expect(dialog.locator('.el-dialog__header')).toBeInViewport()
|
||||
await expect(dialog.getByRole('button', { name: '提交还原快照', exact: true })).toBeInViewport()
|
||||
await page.screenshot({ path: info.outputPath('snapshot-restore-light-mobile.png'), fullPage: true })
|
||||
await dialog.getByRole('button', { name: '提交还原快照', exact: true }).click()
|
||||
await page.getByRole('button', { name: '提交还原快照任务', exact: true }).click()
|
||||
await expect(dialog).not.toBeVisible()
|
||||
expect(requests.find(r => r.path.endsWith('/actions'))?.body).toEqual({ action: 'rollback', name: 'baseline', revision: 'snap-v1', digest: 'd1', confirmVmid: 9000 })
|
||||
})
|
||||
test('删除叶快照先确认,内存还原和含子快照的删除禁用', async ({ page }) => {
|
||||
const requests = await fixture(page), dialog = await open(page)
|
||||
const memory = dialog.locator('.snapshot-item').filter({ hasText: 'with_memory' })
|
||||
await expect(memory.getByRole('button', { name: '还原', exact: true })).toBeDisabled(); await expect(memory.getByRole('button', { name: '删除', exact: true })).toBeDisabled()
|
||||
await dialog.locator('.snapshot-item').filter({ hasText: 'baseline' }).getByRole('button', { name: '删除', exact: true }).click()
|
||||
await dialog.getByRole('button', { name: '预检快照操作', exact: true }).click(); await dialog.getByRole('button', { name: '提交删除快照', exact: true }).click()
|
||||
await expect(page.getByText(/将永久删除此恢复点/)).toBeVisible(); await page.getByRole('button', { name: '提交删除快照任务', exact: true }).click()
|
||||
await expect(dialog).not.toBeVisible(); expect(requests.find(r => r.path.endsWith('/actions'))?.body).toEqual({ action: 'delete', name: 'baseline', digest: 'd1', revision: 'snap-v1' })
|
||||
})
|
||||
test('运行中或权限不足阻止操作', async ({ page }) => {
|
||||
const requests = await fixture(page, { running: true }), dialog = await open(page)
|
||||
await expect(dialog.getByText('请先正常关闭桌面,再管理快照')).toBeVisible()
|
||||
await expect(dialog.getByRole('button', { name: '预检快照操作', exact: true })).toBeDisabled(); await expect(dialog.getByRole('textbox', { name: '快照名称', exact: true })).toBeDisabled()
|
||||
await dialog.getByRole('button', { name: '关闭', exact: true }).click(); expect(requests).toHaveLength(0)
|
||||
})
|
||||
test('只读角色仅可查看列表', async ({ page }) => {
|
||||
const requests = await fixture(page, { role: 'viewer' }), dialog = await open(page)
|
||||
await expect(dialog.getByText(/当前角色可查看快照/)).toBeVisible()
|
||||
await expect(dialog.getByRole('button', { name: '新建快照' })).toHaveCount(0); await expect(dialog.getByRole('button', { name: '还原', exact: true })).toHaveCount(0); expect(requests).toHaveLength(0)
|
||||
})
|
||||
test('PVE 权限不足与读取失败明确显示', async ({ page }) => {
|
||||
await fixture(page, { deny: true }); const dialog = await open(page)
|
||||
await expect(dialog.getByText(/PVE Token 缺少当前操作的快照权限/)).toBeVisible()
|
||||
await expect(dialog.getByRole('button', { name: '新建快照' })).toBeDisabled()
|
||||
await page.unroute('**/api/v1/**'); await fixture(page, { fail: true }); await dialog.getByRole('button', { name: '重新读取', exact: true }).click()
|
||||
await expect(dialog.getByText(/无法读取 PVE 快照/)).toBeVisible(); await expect(dialog.getByRole('button', { name: '预检快照操作', exact: true })).toBeDisabled()
|
||||
})
|
||||
test('网络失败重试保留相同幂等标识', async ({ page }) => {
|
||||
const requests = await fixture(page, { retry: true }), dialog = await open(page)
|
||||
await dialog.getByRole('textbox', { name: '快照名称', exact: true }).fill('retry_point'); await dialog.getByRole('button', { name: '预检快照操作', exact: true }).click()
|
||||
for (let i = 0; i < 2; i++) {
|
||||
await dialog.getByRole('button', { name: '提交创建快照', exact: true }).click(); await page.getByRole('button', { name: '提交创建快照任务', exact: true }).click()
|
||||
if (i === 0) await expect(dialog.getByText(/网络暂时不可用/)).toBeVisible()
|
||||
}
|
||||
await expect(dialog).not.toBeVisible(); const writes = requests.filter(r => r.path.endsWith('/actions')); expect(writes).toHaveLength(2); expect(writes[0]?.key).toBeTruthy(); expect(writes[0]?.key).toBe(writes[1]?.key)
|
||||
})
|
||||
test('任务页只读核对快照结果', async ({ page }) => {
|
||||
const requests = await fixture(page); await page.goto('/tasks'); await page.getByRole('button', { name: '快照验收桌面', exact: true }).first().click()
|
||||
await page.getByRole('button', { name: '核对快照结果', exact: true }).click()
|
||||
await expect.poll(() => requests.length).toBe(1); expect(requests[0]?.path).toBe('/tasks/snap-timeout/snapshot-reconcile')
|
||||
})
|
||||
@@ -0,0 +1,90 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { fail?: boolean; pending?: boolean; slow?: boolean } = {}) {
|
||||
const queries: URLSearchParams[] = [], exports: URLSearchParams[] = [], writes: string[] = [], now = new Date().toISOString()
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'task-history-fixture'))
|
||||
const task = (i: number, extra = {}) => ({ id: `task-${i}`, kind: 'desktop', action: 'start', targetId: `desk-${i}`, targetName: `历史桌面 ${i}`, actor: 'root', status: 'success', message: '真实回执已保存', providerRef: '', createdAt: now, updatedAt: now, ...extra })
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[], extra = {}) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 100, requestId: 'task-ui', ...extra } })
|
||||
if (request.method() !== 'GET') { writes.push(path); await route.fulfill({ status: 403, json: { message: '不应发送业务写请求' } }); return }
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'reader', username: 'reader', displayName: '任务查看员', role: options.pending ? 'operator' : 'viewer' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', capabilities: ['task-history'], pveConfigured: false } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 0, onlineTerminals: 0, desktopCount: options.pending ? 1 : 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/tasks/export') { exports.push(url.searchParams); await route.fulfill({ contentType: 'text/csv; charset=utf-8', body: '\ufeff任务标识,状态\r\ntask-1,success\r\n' }); return }
|
||||
if (path === '/tasks') {
|
||||
queries.push(url.searchParams)
|
||||
const p = Number(url.searchParams.get('page') || 1), size = Number(url.searchParams.get('pageSize') || 20), active = url.searchParams.get('active') === 'true'
|
||||
if (active) {
|
||||
const total = options.pending ? 101 : 0
|
||||
await list(Array.from({ length: Math.max(0, Math.min(size, total - (p - 1) * size)) }, (_, i) => task(2000 + (p - 1) * size + i, { status: 'queued', targetId: (p - 1) * size + i === 100 ? 'desk-pending' : `pending-${i}` })), { total, page: p, pageSize: size }); return
|
||||
}
|
||||
const keyword = url.searchParams.get('keyword') || ''
|
||||
if (options.fail && keyword) { await route.fulfill({ status: 500, json: { code: 'database_error', message: '任务查询暂不可用', requestId: 'task-ui' } }); return }
|
||||
if (options.slow && keyword === 'slow') await new Promise(resolve => setTimeout(resolve, 700))
|
||||
const filtered = !!url.searchParams.get('actor') || !!keyword, total = options.pending ? 1500 : filtered ? 1 : 45
|
||||
await list(Array.from({ length: Math.max(0, Math.min(size, total - (p - 1) * size)) }, (_, i) => task((p - 1) * size + i + 1, filtered ? { targetName: keyword || '筛选桌面', actor: url.searchParams.get('actor') || 'root' } : {})), { total, page: p, pageSize: size }); return
|
||||
}
|
||||
if (path === '/desktops' && options.pending) { await list([{ id: 'desk-pending', name: '有旧任务的桌面', vmid: 9000, node: 'test', os: 'Ubuntu', pool: '', provider: 'proxmox', powerState: 'stopped', serviceState: 'unknown', setupRequired: false, endpoint: '192.0.2.1', width: 1920, height: 1080, fps: 30, updatedAt: now }]); return }
|
||||
if (['/resources', '/desktops', '/users', '/terminals', '/audit-logs'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '未定义的测试接口' } })
|
||||
})
|
||||
return { queries, exports, writes }
|
||||
}
|
||||
|
||||
test('任务历史分页、详情和深浅窄屏,历史读取不依赖全局近期任务', async ({ page }, info) => {
|
||||
const calls = await fixture(page); await page.goto('/tasks')
|
||||
await expect(page.getByRole('button', { name: '历史桌面 1', exact: true })).toBeVisible()
|
||||
const initialPages = calls.queries.filter(q => q.get('pageSize') === '20')
|
||||
const cutoffBeforePaging = initialPages[initialPages.length - 1]?.get('to')
|
||||
await page.locator('.el-pagination .btn-next').click(); await expect(page.getByRole('button', { name: '历史桌面 21', exact: true })).toBeVisible()
|
||||
await page.getByRole('button', { name: '历史桌面 21', exact: true }).click()
|
||||
const drawer = page.getByRole('dialog', { name: '任务详情' })
|
||||
await expect(drawer.getByText('task-21', { exact: true })).toBeVisible()
|
||||
await expect(drawer.getByRole('button', { name: /核对/ })).toHaveCount(0)
|
||||
await drawer.locator('.el-drawer__close-btn').click()
|
||||
await page.screenshot({ path: info.outputPath('task-history-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click(); await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.screenshot({ path: info.outputPath('task-history-mobile.png'), fullPage: true, animations: 'disabled' })
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
const pages = calls.queries.filter(q => q.get('pageSize') === '20')
|
||||
expect(pages[pages.length - 1]?.get('page')).toBe('2'); expect(pages[pages.length - 1]?.get('to')).toBe(cutoffBeforePaging)
|
||||
expect(calls.writes).toEqual([])
|
||||
})
|
||||
|
||||
test('任务筛选和导出沿用已应用条件,修改草稿后导出不混用', async ({ page }) => {
|
||||
const calls = await fixture(page); await page.goto('/tasks'); await expect(page.getByRole('button', { name: '历史桌面 1', exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '任务操作者' }).fill('root_%')
|
||||
await page.locator('.el-select').filter({ has: page.getByRole('combobox', { name: '任务状态筛选' }) }).click(); await page.getByRole('option', { name: '成功', exact: true }).click()
|
||||
await page.getByRole('combobox', { name: '任务动作' }).click(); await page.getByRole('option', { name: '开机', exact: true }).click()
|
||||
await page.getByRole('combobox', { name: '任务类型' }).click(); await page.getByRole('option', { name: '桌面电源', exact: true }).click()
|
||||
await page.getByRole('combobox', { name: '任务时间范围' }).first().click(); await page.getByRole('button', { name: '最近 7 天', exact: true }).click()
|
||||
await page.getByRole('button', { name: '查询任务', exact: true }).click(); await expect(page.getByRole('button', { name: '筛选桌面', exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '搜索任务' }).fill('尚未应用')
|
||||
const wait = page.waitForEvent('download'); await page.getByRole('button', { name: '导出任务 CSV' }).click()
|
||||
expect((await wait).suggestedFilename()).toMatch(/执行任务.*\.csv$/)
|
||||
expect(Object.fromEntries(calls.exports[0]!)).toMatchObject({ actor: 'root_%', status: 'success', action: 'start', kind: 'desktop', keyword: '' })
|
||||
expect(calls.exports[0]?.get('from')).toBeTruthy(); expect(calls.exports[0]?.get('page')).toBeNull()
|
||||
await page.getByRole('button', { name: '重置', exact: true }).click(); await expect(page.getByRole('button', { name: '历史桌面 1', exact: true })).toBeVisible()
|
||||
expect(calls.writes).toEqual([])
|
||||
})
|
||||
|
||||
test('查询失败清理旧结果并禁用导出,旧响应不能覆盖新条件', async ({ page }) => {
|
||||
await fixture(page, { fail: true }); await page.goto('/tasks'); await expect(page.getByRole('button', { name: '历史桌面 1', exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '搜索任务' }).fill('failure'); await page.getByRole('button', { name: '查询任务', exact: true }).click()
|
||||
await expect(page.getByText(/任务查询暂不可用/)).toBeVisible(); await expect(page.getByRole('button', { name: '导出任务 CSV' })).toBeDisabled()
|
||||
await expect(page.getByRole('button', { name: '历史桌面 1', exact: true })).toHaveCount(0)
|
||||
await page.unrouteAll(); await fixture(page, { slow: true }); await page.reload(); await expect(page.getByRole('button', { name: '历史桌面 1', exact: true })).toBeVisible()
|
||||
await page.getByRole('textbox', { name: '搜索任务' }).fill('slow'); await page.getByRole('textbox', { name: '搜索任务' }).press('Enter')
|
||||
await page.getByRole('textbox', { name: '搜索任务' }).fill('new'); await page.getByRole('textbox', { name: '搜索任务' }).press('Enter')
|
||||
await expect(page.getByRole('button', { name: 'new', exact: true })).toBeVisible()
|
||||
await expect.poll(async () => { await page.waitForTimeout(800); return page.getByRole('button', { name: 'slow', exact: true }).count() }).toBe(0)
|
||||
})
|
||||
|
||||
test('全局只取近期一页并分页拉全旧活动任务,旧任务仍阻止操作桌面', async ({ page }) => {
|
||||
const calls = await fixture(page, { pending: true }); await page.goto('/desktops')
|
||||
await expect(page.getByRole('button', { name: '任务执行中', exact: true })).toBeDisabled()
|
||||
expect(calls.queries.some(q => q.get('active') === 'true' && q.get('page') === '2')).toBe(true)
|
||||
expect(calls.queries.some(q => q.get('active') !== 'true' && q.get('page') === '2')).toBe(false)
|
||||
expect(calls.writes).toEqual([])
|
||||
})
|
||||
@@ -0,0 +1,94 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { role?: string; stale?: boolean; resolved?: boolean; fail?: boolean } = {}) {
|
||||
const writes: { path: string; body: Record<string, unknown> }[] = [], now = new Date().toISOString()
|
||||
let acknowledged = false
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'terminal-alert-fixture'))
|
||||
const rules: Record<string, unknown>[] = [{ id: 'temp-rule', name: '终端温度高水位', metric: 'terminal_temperature', threshold: 80, holdSeconds: 120, enabled: true }]
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), path = new URL(request.url()).pathname.replace('/api/v1', '')
|
||||
const list = (items: unknown[], extra = {}) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 100, requestId: 'alert-ui', ...extra } })
|
||||
if (request.method() !== 'GET') {
|
||||
const body = request.postDataJSON(); writes.push({ path, body })
|
||||
if (path.endsWith('/acknowledge')) { acknowledged = true; await route.fulfill({ json: { accepted: true } }); return }
|
||||
if (path.startsWith('/monitor/rules')) {
|
||||
if (options.fail) { await route.fulfill({ status: 400, json: { message: '温度阈值超出范围', code: 'invalid_request', requestId: 'alert-ui' } }); return }
|
||||
const rule = { ...body, id: path.endsWith('/temp-rule') ? 'temp-rule' : 'created-rule' }
|
||||
if (path.endsWith('/temp-rule')) rules[0] = rule; else rules.push(rule)
|
||||
await route.fulfill({ json: rule }); return
|
||||
}
|
||||
await route.fulfill({ status: 403, json: { message: '不应出现的写操作' } }); return
|
||||
}
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'alerts-reader', username: 'reader', displayName: '告警人员', role: options.role || 'super_admin' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', capabilities: ['terminal-metric-alerts'], pveConfigured: false } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 1, onlineTerminals: 1, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/monitor/rules') { await list(rules); return }
|
||||
if (path === '/monitor/alerts') {
|
||||
await list([{ id: 'temp-alert', ruleId: 'temp-rule', ruleName: '终端温度高水位', metric: 'terminal_temperature', targetId: 'box1', targetName: '测试盒子', value: 86.5, threshold: 80, status: options.resolved ? 'resolved' : 'firing', startedAt: now, openedAt: now, resolvedAt: options.resolved ? now : null, resolveReason: options.resolved ? 'condition_cleared' : '', acknowledgedAt: acknowledged ? now : null, acknowledgedBy: acknowledged ? 'reader' : '', dataFresh: !options.stale }], { firingCount: options.resolved ? 0 : 1, unacknowledgedCount: acknowledged || options.resolved ? 0 : 1 }); return
|
||||
}
|
||||
if (['/resources', '/desktops', '/users', '/terminals', '/tasks', '/audit-logs'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '测试接口未定义', requestId: 'alert-ui' } })
|
||||
})
|
||||
return writes
|
||||
}
|
||||
|
||||
test('新增 SoC 温度规则使用摄氏度和独立上限,切换内存使用百分比', async ({ page }, info) => {
|
||||
const writes = await fixture(page); await page.goto('/monitor')
|
||||
await expect(page.getByRole('cell', { name: '86.5 / 80 °C', exact: true })).toBeVisible()
|
||||
await page.getByRole('tab', { name: '告警规则' }).click()
|
||||
await expect(page.getByRole('cell', { name: '80°C / 120 秒', exact: true })).toBeVisible()
|
||||
await page.getByRole('button', { name: '新增规则', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '新增告警规则' })
|
||||
await dialog.locator('.el-select').click(); await page.getByRole('option', { name: '终端 SoC 温度', exact: true }).click()
|
||||
await expect(dialog.getByText('SoC 温度阈值(°C)', { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByRole('spinbutton', { name: '告警阈值' })).toHaveAttribute('aria-valuemax', '150')
|
||||
await expect(dialog.getByText(/重复读取不推进/)).toBeVisible()
|
||||
await dialog.getByRole('textbox', { name: '规则名称' }).fill('盒子过热')
|
||||
await page.screenshot({ path: info.outputPath('terminal-alert-create-dark.png'), fullPage: true, animations: 'disabled' })
|
||||
await dialog.getByRole('button', { name: '保存规则', exact: true }).click()
|
||||
await expect(dialog).toBeHidden()
|
||||
expect(writes[0]?.body).toMatchObject({ name: '盒子过热', metric: 'terminal_temperature', threshold: 80, holdSeconds: 120, enabled: true })
|
||||
await page.getByRole('button', { name: '新增规则', exact: true }).click()
|
||||
await dialog.locator('.el-select').click(); await page.getByRole('option', { name: '终端内存', exact: true }).click()
|
||||
await expect(dialog.getByText('使用率阈值(%)', { exact: true })).toBeVisible()
|
||||
await expect(dialog.getByRole('spinbutton', { name: '告警阈值' })).toHaveAttribute('aria-valuemax', '100')
|
||||
await dialog.getByRole('button', { name: '取消', exact: true }).click()
|
||||
expect(writes).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('过期数据保留告警和最近值,确认不表示恢复', async ({ page }, info) => {
|
||||
const writes = await fixture(page, { role: 'operator', stale: true }); await page.goto('/monitor')
|
||||
await expect(page.getByText('数据已过期或缺失;显示最近告警值,等待有效采样', { exact: true })).toBeVisible()
|
||||
await page.getByRole('button', { name: '确认告警' }).click()
|
||||
await expect(page.getByRole('cell', { name: '正在告警', exact: true })).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: '确认告警' })).toHaveCount(0)
|
||||
await page.getByRole('button', { name: '切换浅色主题' }).click()
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.screenshot({ path: info.outputPath('terminal-alert-stale-mobile-light.png'), fullPage: true, animations: 'disabled' })
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.getByRole('tab', { name: '告警规则' }).click()
|
||||
await expect(page.getByRole('button', { name: '新增规则' })).toHaveCount(0)
|
||||
expect(writes).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('只读人员可看恢复事件和摄氏度,无确认或规则写入口', async ({ page }) => {
|
||||
const writes = await fixture(page, { role: 'viewer', stale: true, resolved: true }); await page.goto('/monitor')
|
||||
await expect(page.getByRole('cell', { name: '已恢复', exact: true })).toBeVisible()
|
||||
await expect(page.getByText('指标恢复', { exact: true })).toBeVisible()
|
||||
await expect(page.getByText(/数据已过期或缺失/)).toHaveCount(0)
|
||||
await expect(page.getByRole('button', { name: '确认告警' })).toHaveCount(0)
|
||||
await page.getByRole('tab', { name: '告警规则' }).click()
|
||||
await expect(page.getByRole('button', { name: '编辑规则' })).toHaveCount(0)
|
||||
expect(writes).toEqual([])
|
||||
})
|
||||
|
||||
test('保存错误保留表单和数值,取消不改变规则', async ({ page }) => {
|
||||
const writes = await fixture(page, { fail: true }); await page.goto('/monitor')
|
||||
await page.getByRole('tab', { name: '告警规则' }).click(); await page.getByRole('button', { name: '编辑规则' }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '编辑告警规则' })
|
||||
await dialog.getByRole('button', { name: '保存规则', exact: true }).click()
|
||||
await expect(page.getByText(/温度阈值超出范围/)).toBeVisible()
|
||||
await expect(dialog).toBeVisible()
|
||||
await dialog.getByRole('button', { name: '取消', exact: true }).click(); await expect(dialog).toBeHidden()
|
||||
expect(writes).toHaveLength(1)
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
import { test, expect, type Page } from '@playwright/test'
|
||||
|
||||
async function fixture(page: Page, options: { stale?: boolean; legacy?: boolean; missing?: boolean; fail?: boolean; delayFirst?: boolean } = {}) {
|
||||
const now = new Date().toISOString(), writes: string[] = [], reads: URL[] = []
|
||||
let fail = options.fail, firstDelivered = false
|
||||
await page.addInitScript(() => sessionStorage.setItem('vdi.accessToken', 'metrics-fixture'))
|
||||
await page.route('**/api/v1/**', async route => {
|
||||
const request = route.request(), url = new URL(request.url()), path = url.pathname.replace('/api/v1', '')
|
||||
if (request.method() !== 'GET') { writes.push(path); await route.fulfill({ status: 403, json: { message: '只读页面出现写请求' } }); return }
|
||||
const list = (items: unknown[]) => route.fulfill({ json: { items, total: items.length, page: 1, pageSize: 100, requestId: 'metrics-fixture' } })
|
||||
if (path === '/auth/me') { await route.fulfill({ json: { id: 'metrics-viewer', username: 'viewer', displayName: '只读人员', role: 'viewer' } }); return }
|
||||
if (path === '/settings') { await route.fulfill({ json: { mode: 'production', capabilities: [], pveConfigured: true, computeProvider: 'proxmox' } }); return }
|
||||
if (path === '/overview') { await route.fulfill({ json: { terminalCount: 1, onlineTerminals: 1, desktopCount: 0, runningDesktops: 0, activeSessions: 0, failedTasks: 0, mode: 'production' } }); return }
|
||||
if (path === '/terminals') { await list([{ id: 'metrics-a', name: '指标测试盒子', sn: 'METRICS-001', group: '测试', status: options.stale ? 'offline' : 'online', agentVersion: 'qt-platform/0.4.0', lastSeen: now, sessionDesktopId: null, configVersion: 1, fps: null, rtt: null }]); return }
|
||||
if (path === '/terminals/metrics-a/metrics') {
|
||||
reads.push(url)
|
||||
const requestNumber = reads.length
|
||||
if (options.delayFirst && reads.length === 1) await new Promise(resolve => setTimeout(resolve, 2000))
|
||||
if (fail) { fail = false; await route.fulfill({ status: 503, json: { code: 'unavailable', message: '指标服务暂不可用', requestId: 'metrics-fixture' } }); return }
|
||||
const from = url.searchParams.get('from')!, to = url.searchParams.get('to')!, start = Date.parse(from)
|
||||
await route.fulfill({ json: { latest: { cpuPercent: options.missing ? null : options.delayFirst && requestNumber > 1 ? 25 : 0, memoryPercent: 30, socTemperatureC: 44.37, uptimeSeconds: 90120, sampledAt: now, supported: !options.legacy, fresh: !options.stale && !options.legacy, online: !options.stale }, from, to, bucketSeconds: 60, retentionDays: 30, items: [
|
||||
{ time: new Date(start + 60000).toISOString(), cpuPercent: 10, memoryPercent: 30, socTemperatureC: 44, uptimeSeconds: 90100, samples: 2 },
|
||||
{ time: new Date(start + 120000).toISOString(), cpuPercent: null, memoryPercent: null, socTemperatureC: null, uptimeSeconds: null, samples: 0 },
|
||||
{ time: new Date(start + 180000).toISOString(), cpuPercent: 20, memoryPercent: 30, socTemperatureC: 44.37, uptimeSeconds: 90120, samples: 2 },
|
||||
] } }); if (requestNumber === 1) firstDelivered = true; return
|
||||
}
|
||||
if (['/desktops', '/users', '/tasks', '/audit-logs', '/resources'].includes(path)) { await list([]); return }
|
||||
await route.fulfill({ status: 404, json: { message: '测试接口未定义' } })
|
||||
})
|
||||
return { writes, reads, firstDelivered: () => firstDelivered }
|
||||
}
|
||||
async function open(page: Page) {
|
||||
await page.goto('/terminals')
|
||||
await page.getByRole('button', { name: '详情', exact: true }).click()
|
||||
await page.getByRole('button', { name: '查看运行指标', exact: true }).click()
|
||||
return page.getByRole('region', { name: '终端运行指标' })
|
||||
}
|
||||
test('真实指标独立按需加载,零值、SoC 温度、运行时长与缺失断线显示', async ({ page }, info) => {
|
||||
const requests = await fixture(page)
|
||||
await page.goto('/terminals'); await page.getByRole('button', { name: '详情', exact: true }).click()
|
||||
expect(requests.reads).toHaveLength(0)
|
||||
await page.getByRole('button', { name: '查看运行指标', exact: true }).click()
|
||||
const panel = page.getByRole('region', { name: '终端运行指标' })
|
||||
await expect(panel.getByText('0.0 %', { exact: true })).toBeVisible()
|
||||
await expect(panel.getByText('44.4 °C', { exact: true })).toBeVisible()
|
||||
await expect(panel.getByText('1 天 1 小时 2 分钟', { exact: true })).toBeVisible()
|
||||
await expect(panel.getByRole('img', { name: /历史趋势/ })).toHaveCount(3)
|
||||
const path = await panel.getByRole('img', { name: 'CPU 使用率历史趋势' }).locator('path').getAttribute('d')
|
||||
expect(path?.match(/M/g)).toHaveLength(2); expect(path).not.toContain('L')
|
||||
await expect(panel.getByText(/串流 FPS\/RTT 尚未采集/)).toBeVisible()
|
||||
await page.screenshot({ path: info.outputPath('terminal-metrics-dark.png'), fullPage: true })
|
||||
expect(requests.writes).toEqual([])
|
||||
})
|
||||
test('离线隐藏当前数值并保留历史', async ({ page }) => {
|
||||
const requests = await fixture(page, { stale: true }); const panel = await open(page)
|
||||
await expect(panel.getByText(/设备离线或采样已过期/)).toBeVisible()
|
||||
await expect(panel.locator('.metric-values strong')).toHaveText(['未采集', '未采集', '未采集', '未采集'])
|
||||
await expect(panel.getByRole('img', { name: /历史趋势/ })).toHaveCount(3); expect(requests.writes).toEqual([])
|
||||
})
|
||||
test('旧 Agent 给出升级提示,不冒充零值', async ({ page }) => {
|
||||
await fixture(page, { legacy: true }); const panel = await open(page)
|
||||
await expect(panel.getByText('设备尚未上报系统指标,请更新 Agent', { exact: true })).toBeVisible()
|
||||
await expect(panel.locator('.metric-values strong')).toHaveText(['未采集', '未采集', '未采集', '未采集'])
|
||||
})
|
||||
test('单项缺失保持未采集,读取失败可重试', async ({ page }) => {
|
||||
await fixture(page, { missing: true, fail: true }); const panel = await open(page)
|
||||
await expect(panel.getByText('指标服务暂不可用', { exact: true })).toBeVisible()
|
||||
await expect(panel.locator('.metric-values')).toHaveCount(0)
|
||||
await panel.getByRole('button', { name: '刷新指标' }).click()
|
||||
await expect(panel.locator('.metric-values strong').first()).toHaveText('未采集')
|
||||
await expect(panel.getByText('30.0 %', { exact: true })).toBeVisible()
|
||||
})
|
||||
test('时间范围切换与窄屏浅色展示', async ({ page }, info) => {
|
||||
const requests = await fixture(page)
|
||||
await page.addInitScript(() => localStorage.setItem('vdi.theme', 'light'))
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
const panel = await open(page)
|
||||
await expect(panel.getByText('44.4 °C', { exact: true })).toBeVisible()
|
||||
await panel.locator('.el-select').click()
|
||||
await page.getByRole('option', { name: '最近 7 天' }).click()
|
||||
await expect.poll(() => requests.reads.length).toBe(2)
|
||||
const url = requests.reads[1]!
|
||||
expect(Date.parse(url.searchParams.get('to')!) - Date.parse(url.searchParams.get('from')!)).toBe(7 * 86400000)
|
||||
await expect(panel.getByText('44.4 °C', { exact: true })).toBeVisible()
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391)
|
||||
await page.screenshot({ path: info.outputPath('terminal-metrics-mobile-light.png'), fullPage: true })
|
||||
expect(requests.writes).toEqual([])
|
||||
})
|
||||
test('切换时间范围时旧响应不能覆盖新响应', async ({ page }) => {
|
||||
const requests = await fixture(page, { delayFirst: true }); const panel = await open(page)
|
||||
await expect.poll(() => requests.reads.length).toBe(1)
|
||||
await panel.locator('.el-select').click(); await page.getByRole('option', { name: '最近 24 小时' }).click()
|
||||
await expect.poll(() => requests.reads.length).toBe(2)
|
||||
await expect(panel.getByText('44.4 °C', { exact: true })).toBeVisible()
|
||||
await expect.poll(requests.firstDelivered).toBe(true)
|
||||
await expect(panel.getByText('25.0 %', { exact: true })).toBeVisible()
|
||||
await expect(panel.locator('.el-select')).toHaveText('最近 24 小时')
|
||||
})
|
||||
@@ -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 @@
|
||||
export const auditActionLabels: Record<string, string> = { export_diagnostics: '导出诊断包', assistant_grant_desktop: '助手分配桌面', assistant_revoke_desktop: '助手撤销桌面', read_diagnostics: '读取终端诊断', 'batch-start': '批量开机提交', 'batch-shutdown': '批量关机提交', 'batch-reboot': '批量重启提交', reconcile_batch_power: '核对批量电源', 'snapshot-create': '创建快照', 'snapshot-delete': '删除快照', 'snapshot-rollback': '还原快照', reconcile_snapshot: '核对快照', 'configure-hardware': '调整 CPU/内存', 'expand-disk': '磁盘扩容', reconcile_hardware: '核对规格', save_pve_connection: '保存 PVE 接入', create_terminal_policy: '创建终端策略', deploy_terminal_policy: '下发终端策略', terminal_policy_applied: '策略应用成功', terminal_policy_failed: '策略应用失败', update_terminal: '更新终端资料', disable_terminal: '停用终端', reactivate_terminal: '重新激活终端', update_user: '更新用户资料', batch_grant_bindings: '批量分配桌面', batch_revoke_bindings: '批量撤销桌面', create_administrator: '新增管理员', update_administrator: '更新管理员', reset_administrator_password: '重置管理员密码', change_own_password: '修改本人密码', reconcile_clone: '核对克隆', clone: '克隆桌面', register_template: '登记模板', update_template: '更新模板', validate_template: '验证模板', save_pool: '保存桌面池', update_pool_members: '更新池成员', configure_desktop: '配置连接', start: '开机', shutdown: '正常关机', reboot: '重启', 'reset-session': '重置会话', 'collect-logs': '收集日志', sync: '同步资源', login: '登录', logout: '退出登录', create_user: '创建用户', enroll_terminal: '登记终端', update_bindings: '更新授权', import_desktop: '纳管桌面', save_alert_rule: '保存告警规则', acknowledge_alert: '确认告警', export_audit_logs: '导出操作审计', export_tasks: '导出任务记录', revoke_administrator_session: '撤销管理员登录', enable_mfa: '开启双重验证', disable_mfa: '关闭双重验证', rotate_mfa_recovery: '更新恢复码', 'prepare-desktop': '准备独占显卡桌面', 'reconcile-gpu-switch': '核对显卡切换' }
|
||||
@@ -0,0 +1,208 @@
|
||||
import createClient from 'openapi-fetch'
|
||||
import type { paths, components } from './schema'
|
||||
|
||||
export type PveConnectionInput = components['schemas']['PveConnectionInput']
|
||||
export type DiagnosticReport = components['schemas']['DiagnosticReport']
|
||||
export type DiagnosticEvent = components['schemas']['DiagnosticEvent']
|
||||
export type DiagnosticQuery = NonNullable<paths['/diagnostics']['get']['parameters']['query']>
|
||||
export type PowerBatchInput = components['schemas']['PowerBatchInput']
|
||||
export type PowerBatch = components['schemas']['PowerBatch']
|
||||
export type PowerBatchDetail = components['schemas']['PowerBatchDetail']
|
||||
export type PowerBatchPreview = components['schemas']['PowerBatchPreview']
|
||||
export type SnapshotInput = components['schemas']['SnapshotInput']
|
||||
export type SnapshotView = components['schemas']['SnapshotView']
|
||||
export type SnapshotItem = components['schemas']['SnapshotItem']
|
||||
export type HardwareInput = components['schemas']['HardwareInput']
|
||||
export type VMHardware = components['schemas']['VMHardware']
|
||||
export type Admin = components['schemas']['Administrator']
|
||||
export type MFAStatus = components['schemas']['MFAStatus']
|
||||
export type MFASetup = components['schemas']['MFASetup']
|
||||
export type ImportPreview = components['schemas']['CsvImportPreview']
|
||||
export type ImportResult = components['schemas']['CsvImportResult']
|
||||
export type CsvImportInput = components['schemas']['CsvImportInput']
|
||||
export type SessionRecord = components['schemas']['SessionRecord']
|
||||
export type AlertRule = components['schemas']['AlertRule']
|
||||
export type AlertRuleInput = components['schemas']['AlertRuleInput']
|
||||
export type AlertRecord = components['schemas']['AlertRecord']
|
||||
export type ResourcePoint = components['schemas']['ResourcePoint']
|
||||
export type TerminalMetrics = components['schemas']['TerminalMetrics']
|
||||
export type TerminalMetricPoint = components['schemas']['TerminalMetricPoint']
|
||||
export type TerminalPolicy = components['schemas']['TerminalPolicy']
|
||||
export type TerminalPolicyInput = components['schemas']['TerminalPolicyInput']
|
||||
export type PolicyDeployment = components['schemas']['PolicyDeployment']
|
||||
export type PolicyDeploymentInput = components['schemas']['PolicyDeploymentInput']
|
||||
export type PolicyResult = components['schemas']['PolicyResult']
|
||||
export type AdministratorAccount = components['schemas']['AdministratorAccount']
|
||||
export type AdministratorSession = components['schemas']['AdministratorSession']
|
||||
export type CreateAdministrator = components['schemas']['CreateAdministrator']
|
||||
export type UpdateAdministrator = components['schemas']['UpdateAdministrator']
|
||||
export type Desktop = components['schemas']['Desktop']
|
||||
export type DesktopReadiness = components['schemas']['DesktopReadiness']
|
||||
export type ImageTemplate = components['schemas']['ImageTemplate']
|
||||
export type DesktopPool = components['schemas']['DesktopPool']
|
||||
export type PoolInput = components['schemas']['PoolInput']
|
||||
export type TemplateInput = components['schemas']['TemplateInput']
|
||||
export type TemplateUpdate = components['schemas']['TemplateUpdate']
|
||||
export type CloneInput = components['schemas']['CloneInput']
|
||||
export type Storage = components['schemas']['Storage']
|
||||
export type ConnectionInput = components['schemas']['ConnectionInput']
|
||||
export type TerminalUpdate = components['schemas']['TerminalUpdate']
|
||||
export type UserUpdate = components['schemas']['UserUpdate']
|
||||
export type BatchBindings = components['schemas']['BatchBindings']
|
||||
export type Terminal = components['schemas']['Terminal']
|
||||
export type User = components['schemas']['User']
|
||||
export type Resource = components['schemas']['Resource']
|
||||
export type GPUInventory = components['schemas']['GPUInventory']
|
||||
export type GPUItem = components['schemas']['GPUItem']
|
||||
export type GPUExclusiveStatus = components['schemas']['GPUExclusiveStatus']
|
||||
export type TerminalLogArchivePage = components['schemas']['TerminalLogArchivePage']
|
||||
export type Task = components['schemas']['Task']
|
||||
export type Audit = components['schemas']['Audit']
|
||||
export type AuditQuery = NonNullable<paths['/audit-logs']['get']['parameters']['query']>
|
||||
export type TaskQuery = NonNullable<paths['/tasks']['get']['parameters']['query']>
|
||||
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 AssistantPlanResult = components['schemas']['AssistantPlanResult']
|
||||
export type AssistantExecuteResult = components['schemas']['AssistantExecuteResult']
|
||||
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 = {
|
||||
diagnostics: (filters: DiagnosticQuery) => result(client.GET('/diagnostics', { params: { query: filters } })),
|
||||
assistantPlan: (text: string) => result(client.POST('/assistant/plan', { body: { text } })),
|
||||
assistantExecute: (runId: string, key = crypto.randomUUID()) => result(client.POST('/assistant/execute', { params: { header: { 'Idempotency-Key': key } }, body: { runId } })),
|
||||
assistantRun: (id: string) => result(client.GET('/assistant/runs/{id}', { params: { path: { id } } })),
|
||||
exportDiagnostics: (filters: DiagnosticQuery) => result(client.GET('/diagnostics/export', { params: { query: filters }, parseAs: 'blob' })),
|
||||
collectTerminalLogs: (id: string, key: string) => result(client.POST('/terminals/{id}/commands', { params: { path: { id }, header: { 'Idempotency-Key': key } }, body: { action: 'collect-logs' } })),
|
||||
gpuInventory: (node: string) => result(client.GET('/resources/gpus', { params: { query: { node } } })),
|
||||
gpuExclusiveStatus: (node: string) => result(client.GET('/resources/gpu-exclusive', { params: { query: { node } } })),
|
||||
terminalLogArchives: (filters: NonNullable<paths['/terminal-logs']['get']['parameters']['query']> = {}) => result(client.GET('/terminal-logs', { params: { query: filters } })),
|
||||
pveConnection: () => result(client.GET('/settings/pve')),
|
||||
checkPveConnection: (body: PveConnectionInput) => result(client.POST('/settings/pve/check', { body })),
|
||||
savePveConnection: (body: PveConnectionInput) => result(client.PUT('/settings/pve', { body })),
|
||||
desktopPowerBatches: (page = 1) => result(client.GET('/desktop-batches', { params: { query: { ...query, page } } })),
|
||||
desktopPowerBatch: (id: string) => result(client.GET('/desktop-batches/{id}', { params: { path: { id } } })),
|
||||
checkDesktopPowerBatch: (body: PowerBatchInput) => result(client.POST('/desktop-batches/check', { body })),
|
||||
submitDesktopPowerBatch: (body: PowerBatchInput, key: string) => result(client.POST('/desktop-batches', { params: { header: { 'Idempotency-Key': key } }, body })),
|
||||
reconcileBatchPower: (id: string) => result(client.POST('/tasks/{id}/batch-power-reconcile', { params: { path: { id } } })),
|
||||
reconcileGPUPrepare: (id: string) => result(client.POST('/tasks/{id}/gpu-reconcile', { params: { path: { id } } })),
|
||||
desktopSnapshots: (id: string) => result(client.GET('/desktops/{id}/snapshots', { params: { path: { id } } })),
|
||||
checkDesktopSnapshot: (id: string, body: SnapshotInput) => result(client.POST('/desktops/{id}/snapshots/check', { params: { path: { id } }, body })),
|
||||
changeDesktopSnapshot: (id: string, body: SnapshotInput, key: string) => result(client.POST('/desktops/{id}/snapshots/actions', { params: { path: { id }, header: { 'Idempotency-Key': key } }, body })),
|
||||
reconcileSnapshot: (id: string) => result(client.POST('/tasks/{id}/snapshot-reconcile', { params: { path: { id } } })),
|
||||
desktopHardware: (id: string) => result(client.GET('/desktops/{id}/hardware', { params: { path: { id } } })),
|
||||
checkDesktopHardware: (id: string, body: HardwareInput) => result(client.POST('/desktops/{id}/hardware/check', { params: { path: { id } }, body })),
|
||||
changeDesktopHardware: (id: string, body: HardwareInput, key: string) => result(client.POST('/desktops/{id}/hardware', { params: { path: { id }, header: { 'Idempotency-Key': key } }, body })),
|
||||
reconcileHardware: (id: string) => result(client.POST('/tasks/{id}/hardware-reconcile', { params: { path: { id } } })),
|
||||
previewImport: (body: CsvImportInput) => result(client.POST('/imports/preview', { body })),
|
||||
commitImport: (body: CsvImportInput, key: string) => result(client.POST('/imports/commit', { params: { header: { 'Idempotency-Key': key } }, body })),
|
||||
sessionHistory: (filters: { page?: number; keyword?: string; status?: string; from?: string; to?: string }) => result(client.GET('/sessions/history', { params: { query: { ...query, pageSize: 20, ...filters } } })),
|
||||
terminalMetrics: (id: string, from: string, to: string) => result(client.GET('/terminals/{id}/metrics', { params: { path: { id }, query: { from, to } } })),
|
||||
resourceSeries: (resourceId: string, from: string, to: string) => result(client.GET('/monitor/series', { params: { query: { resourceId, from, to } } })),
|
||||
alertRules: (page = 1) => result(client.GET('/monitor/rules', { params: { query: { ...query, page } } })),
|
||||
saveAlertRule: (id: string, body: AlertRuleInput) => id ? result(client.PUT('/monitor/rules/{id}', { params: { path: { id } }, body })) : result(client.POST('/monitor/rules', { body })),
|
||||
alerts: (page = 1, status = '', keyword = '') => result(client.GET('/monitor/alerts', { params: { query: { ...query, page, pageSize: 20, status, keyword } } })),
|
||||
acknowledgeAlert: (id: string) => result(client.POST('/monitor/alerts/{id}/acknowledge', { params: { path: { id } } })),
|
||||
terminalPolicies: (page = 1) => result(client.GET('/terminal-policy-templates', { params: { query: { ...query, page } } })),
|
||||
createTerminalPolicy: (body: TerminalPolicyInput) => result(client.POST('/terminal-policy-templates', { body })),
|
||||
policyStates: (page = 1) => result(client.GET('/terminal-policy-states', { params: { query: { ...query, page } } })),
|
||||
policyDeployments: (page = 1) => result(client.GET('/terminal-policy-deployments', { params: { query: { ...query, page } } })),
|
||||
deployPolicy: (body: PolicyDeploymentInput, key: string) => result(client.POST('/terminal-policy-deployments', { params: { header: { 'Idempotency-Key': key } }, body })),
|
||||
policyResults: (id: string, page = 1) => result(client.GET('/terminal-policy-deployments/{id}/results', { params: { path: { id }, query: { ...query, page } } })),
|
||||
login: (username: string, password: string, code?: string) => result(client.POST('/auth/login', { body: { username, password, ...(code ? { code } : {}) } })),
|
||||
mfaStatus: () => result(client.GET('/auth/mfa')),
|
||||
beginMFA: (password: string) => result(client.POST('/auth/mfa/setup', { body: { password } })),
|
||||
confirmMFA: (code: string) => result(client.POST('/auth/mfa/confirm', { body: { code } })),
|
||||
rotateMFARecovery: (password: string, code: string) => result(client.POST('/auth/mfa/recovery', { body: { password, code } })),
|
||||
disableMFA: (password: string, code: string) => result(client.DELETE('/auth/mfa', { body: { password, code } })),
|
||||
me: () => result(client.GET('/auth/me')),
|
||||
logout: () => result(client.POST('/auth/logout')),
|
||||
changeOwnPassword: (currentPassword: string, newPassword: string) => result(client.POST('/auth/password', { body: { currentPassword, newPassword } })),
|
||||
administrators: (page = 1) => result(client.GET('/administrators', { params: { query: { ...query, page } } })),
|
||||
administratorSessions: (id: string, page = 1) => result(client.GET('/administrators/{id}/sessions', { params: { path: { id }, query: { page, pageSize: 20 } } })),
|
||||
revokeAdministratorSession: (id: string, sessionKey: string) => result(client.DELETE('/administrators/{id}/sessions/{sessionKey}', { params: { path: { id, sessionKey } } })),
|
||||
createAdministrator: (body: CreateAdministrator) => result(client.POST('/administrators', { body })),
|
||||
updateAdministrator: (id: string, body: UpdateAdministrator) => result(client.PUT('/administrators/{id}', { params: { path: { id } }, body })),
|
||||
resetAdministratorPassword: (id: string, password: string) => result(client.POST('/administrators/{id}/password', { params: { path: { id } }, body: { password } })),
|
||||
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 } } })),
|
||||
activeTasks: (page = 1) => result(client.GET('/tasks', { params: { query: { ...query, page, active: true } } })),
|
||||
taskHistory: (filters: TaskQuery = {}) => result(client.GET('/tasks', { params: { query: filters } })),
|
||||
exportTasks: (filters: TaskQuery) => result(client.GET('/tasks/export', { params: { query: filters }, parseAs: 'blob' })),
|
||||
taskDiagnostics: (id: string) => result(client.GET('/tasks/{id}/diagnostics', { params: { path: { id } } })),
|
||||
reconcileProvision: (id: string) => result(client.POST('/tasks/{id}/reconcile', { params: { path: { id } } })),
|
||||
audits: (filters: AuditQuery = {}) => result(client.GET('/audit-logs', { params: { query: filters } })),
|
||||
exportAudits: (filters: AuditQuery) => result(client.GET('/audit-logs/export', { params: { query: filters }, parseAs: 'blob' })),
|
||||
discoverVMs: () => result(client.GET('/resources/vms', { params: { query } })),
|
||||
templates: (page = 1) => result(client.GET('/templates', { params: { query: { ...query, page } } })),
|
||||
discoverTemplates: (page = 1) => result(client.GET('/resources/templates', { params: { query: { ...query, page } } })),
|
||||
registerTemplate: (body: TemplateInput) => result(client.POST('/templates', { body })),
|
||||
updateTemplate: (id: string, body: TemplateUpdate) => result(client.PATCH('/templates/{id}', { params: { path: { id } }, body })),
|
||||
validateTemplate: (id: string) => result(client.POST('/templates/{id}/validate', { params: { path: { id } } })),
|
||||
pools: (page = 1) => result(client.GET('/pools', { params: { query: { ...query, page } } })),
|
||||
savePool: (id: string, body: PoolInput) => id ? result(client.PUT('/pools/{id}', { params: { path: { id } }, body })) : result(client.POST('/pools', { body })),
|
||||
poolMembers: (id: string, desktopIds: string[]) => result(client.PUT('/pools/{id}/members', { params: { path: { id } }, body: { desktopIds } })),
|
||||
storages: (node: string, page = 1) => result(client.GET('/resources/storage', { params: { query: { ...query, page, node } } })),
|
||||
checkClone: (body: CloneInput) => result(client.POST('/desktops/clone/check', { body })),
|
||||
cloneDesktop: (body: CloneInput, key: string) => result(client.POST('/desktops/clone', { params: { header: { 'Idempotency-Key': key } }, body })),
|
||||
configureDesktop: (id: string, body: ConnectionInput) => result(client.PUT('/desktops/{id}/connection', { params: { path: { id } }, body })),
|
||||
checkDesktopReadiness: (id: string) => result(client.POST('/desktops/{id}/readiness/check', { params: { path: { id } } })),
|
||||
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 })),
|
||||
updateTerminal: (id: string, body: TerminalUpdate) => result(client.PUT('/terminals/{id}', { params: { path: { id } }, body })),
|
||||
disableTerminal: (id: string) => result(client.POST('/terminals/{id}/disable', { params: { path: { id } } })),
|
||||
reactivateTerminal: (id: string) => result(client.POST('/terminals/{id}/reactivate', { params: { path: { id } } })),
|
||||
updateUser: (id: string, body: UserUpdate) => result(client.PUT('/users/{id}', { params: { path: { id } }, body })),
|
||||
batchBindings: (body: BatchBindings) => result(client.POST('/users/batch-bindings', { 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 async function recentAndActiveTasks(): Promise<Task[]> {
|
||||
const [recent, active] = await Promise.all([api.tasks(), allPages(api.activeTasks)])
|
||||
return [...new Map([...recent.items, ...active].map(task => [task.id, task])).values()]
|
||||
}
|
||||
export const errorMessage = (e: unknown) => e instanceof ApiError ? `${e.message}${e.requestId ? `(请求 ${e.requestId})` : ''}` : e instanceof Error ? e.message : '操作失败,请重试'
|
||||
Vendored
+14520
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 @@
|
||||
.simple-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:18px}.simple-stats .panel{padding:22px}.simple-stats span{color:var(--vdi-muted);font-size:13px}.simple-stats strong{display:block;font-size:32px;margin-top:14px}.simple-stats small{font-size:12px;color:var(--vdi-muted);font-weight:400}.simple-section{padding:24px;margin-top:22px}.simple-section h2{font-size:18px;margin-bottom:12px}.simple-shortcuts{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px;margin-top:22px}.simple-shortcuts a{padding:22px;border:1px solid var(--vdi-border);border-radius:12px;background:var(--vdi-panel-2)}.simple-shortcuts strong{display:block;color:var(--vdi-accent);font-size:15px}.simple-shortcuts span{display:block;margin-top:12px;font-size:12px;color:var(--vdi-muted);line-height:1.8}.simple-issues{display:grid;gap:18px;margin:22px 0}.simple-issues a{font-size:14px}.simple-check{display:flex;align-items:flex-start;gap:14px;border-top:1px solid var(--vdi-border);padding:18px 0}.simple-check:first-of-type{margin-top:20px}.simple-check p{color:var(--vdi-muted);line-height:1.8;margin:7px 0 0;font-size:13px}.simple-check strong{font-size:14px}.simple-check .el-tag{flex-shrink:0}.simple-checks{display:grid;margin:20px 0;max-height:45vh;overflow:auto}.simple-checks .el-checkbox{white-space:normal;height:auto;min-height:36px}.simple-checks .el-checkbox__label{white-space:normal}.simple-plan{line-height:1.9;padding:16px;border-radius:12px;background:var(--vdi-panel-2);margin-top:16px}.simple-plan ul{padding-left:20px}.simple-row{display:flex;align-items:center;justify-content:space-between;gap:12px}.simple-section>.el-select{max-width:450px;margin-bottom:18px}@media(max-width:1000px){.simple-shortcuts{grid-template-columns:1fr}.simple-stats{gap:10px}.simple-stats .panel{padding:16px}.simple-stats strong{font-size:24px}}@media(max-width:550px){.simple-stats{grid-template-columns:1fr}.simple-stats strong{margin-top:8px}.simple-section{padding:18px}.simple-check{gap:10px}.simple-section h2{font-size:17px}}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { diagnoseTerminal } from './diagnosis'
|
||||
import type { Desktop, Terminal, User } from '../api'
|
||||
const terminal = { id: 't', name: '盒子', status: 'online', enabled: true } as Terminal
|
||||
const user = { id: 'u', displayName: '员工', enabled: true, terminalId: 't', desktopIds: ['d'] } as User
|
||||
const desktop = { id: 'd', name: '桌面', powerState: 'running', serviceState: 'ready', setupRequired: false } as Desktop
|
||||
describe('终端诊断的连接前提', () => {
|
||||
test('运行但服务未检测时不能报告全部通过', () => {
|
||||
const result = diagnoseTerminal(terminal, [user], [{ ...desktop, serviceState: 'unknown' }])
|
||||
expect(result.slice(-1)[0]?.ok).toBe(false)
|
||||
expect(result.slice(-1)[0]?.detail).toContain('不代表一定不可用')
|
||||
})
|
||||
test('已停用设备、员工与待初始化桌面分别说明', () => {
|
||||
const result = diagnoseTerminal({ ...terminal, enabled: false }, [{ ...user, enabled: false }], [{ ...desktop, setupRequired: true }])
|
||||
expect(result.filter(c => !c.ok).map(c => c.title)).toEqual(['设备已启用', '员工已启用', '桌面'])
|
||||
})
|
||||
test('缺少关联时不猜测使用人;失效桌面授权不能报告已分配', () => {
|
||||
expect(diagnoseTerminal(terminal, [], [desktop])).toHaveLength(3)
|
||||
expect(diagnoseTerminal(terminal, [user], []).slice(-1)[0]?.ok).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { Desktop, Terminal, User } from '../api'
|
||||
|
||||
export interface Check { title: string; ok: boolean; detail: string }
|
||||
export function diagnoseTerminal(terminal: Terminal, users: User[], desktops: Desktop[]): Check[] {
|
||||
const user = users.find(u => u.terminalId === terminal.id)
|
||||
const assigned = desktops.filter(d => user?.desktopIds.includes(d.id))
|
||||
const checks: Check[] = [
|
||||
{ title: '设备已启用', ok: terminal.enabled !== false && terminal.status !== 'disabled', detail: terminal.enabled === false || terminal.status === 'disabled' ? '设备已停用,请联系管理员重新激活。' : '设备未被停用。' },
|
||||
{ title: '设备在线', ok: terminal.status === 'online', detail: terminal.status === 'online' ? '平台收到设备在线心跳。' : terminal.status === 'unregistered' ? '设备尚未激活,请在盒子上配置登记时的激活信息。' : '未收到在线心跳,请检查盒子电源、网络和平台地址。' },
|
||||
{ title: '已关联员工', ok: !!user, detail: user ? `使用人:${user.displayName}` : '请在员工与桌面中关联此设备。' },
|
||||
]
|
||||
if (!user) return checks
|
||||
checks.push({ title: '员工已启用', ok: user.enabled, detail: user.enabled ? '员工可申请桌面连接。' : '员工已停用,请由管理员核查。' })
|
||||
checks.push({ title: '已分配桌面', ok: assigned.length > 0, detail: assigned.length ? `已分配 ${assigned.length} 台桌面。` : '请为员工分配已有桌面;失效授权需由管理员清理。' })
|
||||
for (const desktop of assigned) {
|
||||
checks.push({ title: desktop.name, ok: desktop.powerState === 'running' && desktop.serviceState === 'ready' && !desktop.setupRequired,
|
||||
detail: desktop.setupRequired ? '桌面仍需完成初始化,请联系运维。' : desktop.powerState !== 'running' ? '桌面尚未运行,请先开机。' : desktop.serviceState !== 'ready' ? '桌面已运行,但平台尚未确认连接服务就绪;不代表一定不可用,请检查连接配置或联系运维。' : '桌面运行且连接服务就绪;实际网络和画面仍需连接后验证。' })
|
||||
}
|
||||
return checks
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
|
||||
import { Plus, Refresh } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, allPages, errorMessage, type AdministratorAccount, type UpdateAdministrator } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import AdministratorSessions from './AdministratorSessions.vue'
|
||||
const auth = useAuth(), { confirm } = useAction()
|
||||
const items = ref<AdministratorAccount[]>([]), loading = ref(false), busy = ref(false), error = ref(''), formError = ref(''), keyword = ref('')
|
||||
const sessionTarget = ref<AdministratorAccount>()
|
||||
const visible = ref(false), editing = ref<AdministratorAccount>(), resetTarget = ref<AdministratorAccount>()
|
||||
const form = reactive({ username: '', displayName: '', role: 'viewer' as AdministratorAccount['role'], enabled: true, password: '', confirmation: '' })
|
||||
const reset = reactive({ password: '', confirmation: '' })
|
||||
const roles = { super_admin: '超级管理员', operator: '运维人员', viewer: '只读人员' }
|
||||
const filtered = computed(() => items.value.filter(a => `${a.username} ${a.displayName}`.toLowerCase().includes(keyword.value.toLowerCase())))
|
||||
const passwordValid = (password: string, confirmation: string) => [...password].length >= 12 && new TextEncoder().encode(password).length <= 72 && password === confirmation
|
||||
const canSave = computed(() => !!form.displayName.trim() && (!!editing.value || (/^[a-zA-Z0-9][a-zA-Z0-9._-]{2,79}$/.test(form.username) && passwordValid(form.password, form.confirmation))))
|
||||
async function load(quiet = false) { if (!quiet) loading.value = true; try { items.value = await allPages(api.administrators); error.value = '' } catch (e) { error.value = errorMessage(e) } finally { loading.value = false } }
|
||||
let timer: ReturnType<typeof setInterval>
|
||||
onMounted(() => { void load(); timer = setInterval(() => { if (!document.hidden && !busy.value && !visible.value && !resetTarget.value && !sessionTarget.value) void load(true) }, 5000) })
|
||||
onUnmounted(() => clearInterval(timer))
|
||||
function edit(item?: AdministratorAccount) { editing.value = item; formError.value = ''; Object.assign(form, { username: item?.username || '', displayName: item?.displayName || '', role: item?.role || 'viewer', enabled: item?.enabled ?? true, password: '', confirmation: '' }); visible.value = true }
|
||||
watch(visible, open => { if (!open) { form.password = ''; form.confirmation = ''; formError.value = '' } })
|
||||
watch(resetTarget, () => { reset.password = ''; reset.confirmation = ''; formError.value = '' })
|
||||
async function save() {
|
||||
if (!canSave.value || busy.value) return
|
||||
if (editing.value && (editing.value.role !== form.role || editing.value.enabled !== form.enabled) && !await confirm('更新管理员权限', '修改角色或停用账号会使该账号的所有登录失效。')) return
|
||||
busy.value = true; formError.value = ''
|
||||
try {
|
||||
const update: UpdateAdministrator = { displayName: form.displayName, role: form.role, enabled: form.enabled }
|
||||
const item = editing.value ? await api.updateAdministrator(editing.value.id, update) : await api.createAdministrator({ username: form.username, displayName: form.displayName, role: form.role, password: form.password })
|
||||
if (item.id === auth.user?.id) auth.user = item
|
||||
visible.value = false; ElMessage.success('管理员账号已保存'); await load()
|
||||
} catch (e) { formError.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function resetPassword() {
|
||||
if (!resetTarget.value || busy.value || !passwordValid(reset.password, reset.confirmation)) return
|
||||
if (!await confirm(`重置密码 · ${resetTarget.value.username}`, '该账号需要使用新密码重新登录,现有登录会立即失效。')) return
|
||||
busy.value = true; formError.value = ''
|
||||
try { await api.resetAdministratorPassword(resetTarget.value.id, reset.password); resetTarget.value = undefined; ElMessage.success('密码已重置,旧登录已失效') }
|
||||
catch (e) { formError.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="account-heading"><div><div class="section-kicker">ADMINISTRATOR ACCOUNTS</div><h2>管理员账号</h2><p class="subtext">维护控制台账号、角色与启用状态</p></div><div class="actions"><el-button :icon="Refresh" :loading="loading" @click="load()">刷新</el-button><el-button type="primary" :icon="Plus" @click="edit()">新增管理员</el-button></div></div>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" show-icon style="margin:20px 0" />
|
||||
<div class="toolbar" style="margin-top:24px"><el-input v-model="keyword" placeholder="搜索账号 / 显示名称" aria-label="搜索管理员" clearable /></div>
|
||||
<el-table v-loading="loading" :data="filtered" empty-text="暂无符合条件的管理员"><el-table-column label="账号" min-width="150"><template #default="{ row }"><strong>{{ row.username }}</strong><el-tag v-if="row.id === auth.user?.id" size="small" type="info" style="margin-left:8px">本人</el-tag></template></el-table-column><el-table-column prop="displayName" label="显示名称" min-width="135" /><el-table-column label="角色" min-width="130"><template #default="{ row }">{{ roles[row.role as keyof typeof roles] }}</template></el-table-column><el-table-column label="状态" width="100"><template #default="{ row }"><el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '已启用' : '已停用' }}</el-tag></template></el-table-column><el-table-column label="操作" min-width="240"><template #default="{ row }"><el-button link type="primary" :disabled="busy" @click="edit(row)">编辑</el-button><el-button link type="primary" :disabled="busy" @click="sessionTarget = row">在线登录</el-button><el-button v-if="row.id !== auth.user?.id" link :disabled="busy" @click="resetTarget = row">重置密码</el-button></template></el-table-column></el-table>
|
||||
<p class="account-note">本人密码通过右上角钥匙按钮修改。不能停用自己或修改自己的角色;至少保留一个启用的超级管理员。停用账号会保留历史审计。</p>
|
||||
<el-dialog v-model="visible" :title="editing ? '编辑管理员' : '新增管理员'" width="520px" :close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy"><el-alert v-if="formError" type="error" :title="formError" :closable="false" show-icon /><el-form label-position="top" :disabled="busy"><el-form-item label="账号"><el-input v-model="form.username" :disabled="!!editing" maxlength="80" autocomplete="off" aria-label="管理员账号" placeholder="3~80 位字母、数字、点、下划线或短横线" /></el-form-item><el-form-item label="显示名称"><el-input v-model="form.displayName" maxlength="80" aria-label="管理员显示名称" /></el-form-item><el-form-item label="角色"><el-select v-model="form.role" :disabled="editing?.id === auth.user?.id" aria-label="管理员角色"><el-option v-for="(label, value) in roles" :key="value" :value="value" :label="label" /></el-select></el-form-item><el-form-item v-if="editing" label="启用"><el-switch v-model="form.enabled" :disabled="editing.id === auth.user?.id" aria-label="管理员启用状态" /></el-form-item><template v-else><el-form-item label="初始密码"><el-input v-model="form.password" type="password" show-password maxlength="72" autocomplete="new-password" aria-label="管理员初始密码" /></el-form-item><el-form-item label="确认初始密码"><el-input v-model="form.confirmation" type="password" show-password maxlength="72" autocomplete="new-password" aria-label="确认管理员初始密码" /></el-form-item><p class="subtext">密码至少 12 个字符,UTF-8 编码不超过 72 字节。</p></template></el-form><template #footer><el-button :disabled="busy" @click="visible = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!canSave" @click="save">保存管理员</el-button></template></el-dialog>
|
||||
<el-dialog :model-value="!!resetTarget" :title="`重置密码 · ${resetTarget?.username || ''}`" width="480px" :close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy" @close="resetTarget = undefined"><el-alert v-if="formError" type="error" :title="formError" :closable="false" /><el-form label-position="top" :disabled="busy"><el-form-item label="新密码"><el-input v-model="reset.password" type="password" show-password autocomplete="new-password" aria-label="重置后的新密码" maxlength="72" /></el-form-item><el-form-item label="确认新密码"><el-input v-model="reset.confirmation" type="password" show-password autocomplete="new-password" aria-label="确认重置后的新密码" maxlength="72" /></el-form-item><p class="subtext">至少 12 个字符,UTF-8 编码不超过 72 字节。保存后该账号所有登录失效。</p></el-form><template #footer><el-button :disabled="busy" @click="resetTarget = undefined">取消</el-button><el-button type="primary" :loading="busy" :disabled="!passwordValid(reset.password, reset.confirmation)" @click="resetPassword">重置密码</el-button></template></el-dialog>
|
||||
<AdministratorSessions :account="sessionTarget" @close="sessionTarget = undefined" />
|
||||
</template>
|
||||
<style scoped>
|
||||
.account-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;flex-wrap:wrap}.account-heading h2{margin-top:6px}.account-note{margin-top:22px;font-size:12px;line-height:1.8;color:var(--vdi-muted)}
|
||||
</style>
|
||||
@@ -0,0 +1,56 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, errorMessage, type AdministratorAccount, type AdministratorSession } from '../api'
|
||||
import { useAction } from '../composables/useAction'
|
||||
const props = defineProps<{ account?: AdministratorAccount }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
const { confirm } = useAction()
|
||||
const items = ref<AdministratorSession[]>([]), total = ref(0), page = ref(1), loading = ref(false), busy = ref(false), error = ref('')
|
||||
let generation = 0
|
||||
onBeforeUnmount(() => { generation++ })
|
||||
const time = (value: string | null) => value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '升级前登录,时间未知'
|
||||
async function load() {
|
||||
const account = props.account, request = ++generation
|
||||
if (!account) return
|
||||
loading.value = true; error.value = ''; items.value = []
|
||||
try {
|
||||
const result = await api.administratorSessions(account.id, page.value)
|
||||
if (request !== generation) return
|
||||
total.value = result.total
|
||||
if (page.value > 1 && !result.items.length && result.total <= (page.value - 1) * 20) { page.value = Math.max(1, Math.ceil(result.total / 20)); await load(); return }
|
||||
items.value = result.items
|
||||
} catch (e) { if (request === generation) { error.value = errorMessage(e); total.value = 0 } }
|
||||
finally { if (request === generation) loading.value = false }
|
||||
}
|
||||
watch(() => props.account, account => { generation++; items.value = []; total.value = 0; page.value = 1; error.value = ''; if (account) void load() }, { immediate: true })
|
||||
async function revoke(session: AdministratorSession) {
|
||||
const account = props.account
|
||||
if (!account || busy.value || session.current) return
|
||||
busy.value = true
|
||||
try {
|
||||
if (!await confirm(`撤销登录 · ${account.username}`, `撤销来自 ${session.clientIp || '未知来源'} 的这次登录?该登录将无法继续请求管理接口,需要重新登录。`)) return
|
||||
await api.revokeAdministratorSession(account.id, session.key)
|
||||
ElMessage.success('已撤销指定登录'); await load()
|
||||
} catch (e) { error.value = errorMessage(e); items.value = []; total.value = 0 }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog :model-value="!!account" :title="`在线登录 · ${account?.username || ''}`" width="920px" :close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy" @close="emit('close')">
|
||||
<p class="session-note">显示尚未退出、撤销或到期的登录凭据,不代表浏览器此刻仍在使用。当前登录请通过侧栏退出;撤销其他登录需要确认。来源信息仅供排查。</p>
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" show-icon />
|
||||
<div class="session-toolbar"><span>共 {{ total }} 次有效登录</span><el-button :disabled="busy" :loading="loading" @click="load">刷新登录列表</el-button></div>
|
||||
<el-table v-loading="loading" :data="items" empty-text="没有有效登录">
|
||||
<el-table-column label="来源地址" min-width="155"><template #default="{ row }"><span>{{ row.clientIp || '升级前登录,来源未知' }}</span><el-tag v-if="row.current" size="small" type="success" class="current-session">当前登录</el-tag></template></el-table-column>
|
||||
<el-table-column label="登录 / 到期时间" min-width="205"><template #default="{ row }"><div>{{ time(row.createdAt) }}</div><div class="secondary">到期 {{ time(row.expiresAt) }}</div></template></el-table-column>
|
||||
<el-table-column prop="userAgent" label="浏览器 / 客户端" min-width="220" show-overflow-tooltip><template #default="{ row }">{{ row.userAgent || '未知客户端' }}</template></el-table-column>
|
||||
<el-table-column label="操作" width="115" fixed="right"><template #default="{ row }"><el-button link type="danger" :disabled="row.current || busy || loading" @click="revoke(row)">撤销登录</el-button></template></el-table-column>
|
||||
</el-table>
|
||||
<el-pagination v-model:current-page="page" :disabled="busy || loading" :total="total" :page-size="20" layout="total, prev, pager, next" @current-change="load" />
|
||||
<template #footer><el-button :disabled="busy" @click="emit('close')">关闭</el-button></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<style scoped>
|
||||
.session-note{color:var(--vdi-muted);font-size:12px;line-height:1.8;margin-bottom:18px}.session-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:18px 0;font-size:12px;color:var(--vdi-muted)}.current-session{display:block;width:fit-content;margin-top:7px}.el-pagination{margin-top:20px;flex-wrap:wrap}.secondary{margin-top:5px;font-size:11px}
|
||||
</style>
|
||||
@@ -0,0 +1,70 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onBeforeUnmount, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, errorMessage, type Audit, type AuditQuery } from '../api'
|
||||
import { auditActionLabels } from '../api/audit-labels'
|
||||
import StatusTag from './StatusTag.vue'
|
||||
|
||||
const rows = ref<Audit[]>([]), total = ref(0), page = ref(1), busy = ref(false), exporting = ref(false), error = ref(''), loaded = ref(false)
|
||||
const keyword = ref(''), actor = ref(''), action = ref(''), result = ref(''), range = ref<[Date, Date] | null>(null)
|
||||
const applied = ref<AuditQuery>({})
|
||||
const shortcuts = [1, 7, 30, 90].map(days => ({ text: days === 1 ? '最近 24 小时' : `最近 ${days} 天`, value: () => { const end = new Date(); return [new Date(end.getTime() - days * 86400000), end] } }))
|
||||
const results: Record<string, string> = { success: '成功', submitted: '已提交', failed: '失败', timeout: '结果未确认', denied: '无权限' }
|
||||
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||||
let generation = 0
|
||||
onBeforeUnmount(() => { generation++ })
|
||||
async function load(reset = false) {
|
||||
if (reset) {
|
||||
if (range.value && range.value[1] <= range.value[0]) { ElMessage.warning('结束时间必须晚于开始时间'); return }
|
||||
applied.value = { keyword: keyword.value, actor: actor.value, action: action.value, result: result.value, from: range.value?.[0].toISOString(), to: range.value?.[1].toISOString() || new Date().toISOString() }
|
||||
page.value = 1
|
||||
}
|
||||
const request = ++generation
|
||||
busy.value = true; error.value = ''; loaded.value = false; rows.value = []
|
||||
try {
|
||||
const response = await api.audits({ ...applied.value, page: page.value, pageSize: 20 })
|
||||
if (request !== generation) return
|
||||
rows.value = response.items; total.value = response.total; loaded.value = true
|
||||
} catch (e) { if (request === generation) { error.value = errorMessage(e); total.value = 0 } }
|
||||
finally { if (request === generation) busy.value = false }
|
||||
}
|
||||
function clear() { keyword.value = ''; actor.value = ''; action.value = ''; result.value = ''; range.value = null; void load(true) }
|
||||
async function download() {
|
||||
exporting.value = true
|
||||
try {
|
||||
const blob = await api.exportAudits(applied.value)
|
||||
const url = URL.createObjectURL(blob), link = document.createElement('a')
|
||||
link.href = url; link.download = `操作审计-${new Date().toISOString().slice(0, 10)}.csv`; link.click()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
ElMessage.success('已生成筛选结果的 CSV 文件')
|
||||
} catch (e) { ElMessage.error(errorMessage(e)) } finally { exporting.value = false }
|
||||
}
|
||||
onMounted(() => { void load(true) })
|
||||
</script>
|
||||
<template>
|
||||
<div class="audit-filters">
|
||||
<el-input v-model="keyword" aria-label="审计关键词" placeholder="对象 / 请求标识 / 动作代码" maxlength="200" clearable @keyup.enter="load(true)" />
|
||||
<el-input v-model="actor" aria-label="审计操作者" placeholder="操作者包含" maxlength="200" clearable @keyup.enter="load(true)" />
|
||||
<el-select v-model="action" aria-label="审计动作" placeholder="全部动作" filterable allow-create clearable><el-option v-for="(label, value) in auditActionLabels" :key="value" :value="value" :label="label" /></el-select>
|
||||
<el-select v-model="result" aria-label="审计结果" placeholder="全部结果" filterable allow-create clearable><el-option v-for="(label, value) in results" :key="value" :value="value" :label="label" /></el-select>
|
||||
<el-date-picker v-model="range" type="datetimerange" aria-label="审计时间范围" start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts" format="YYYY-MM-DD HH:mm:ss" />
|
||||
<div class="audit-actions"><el-button type="primary" :loading="busy" @click="load(true)">查询审计</el-button><el-button :disabled="busy" @click="clear">重置</el-button><el-button :loading="exporting" :disabled="busy || !loaded || !total || total > 10000" @click="download">导出查询结果 CSV</el-button></div>
|
||||
</div>
|
||||
<p class="subtext audit-hint">不选时间可查询全部历史。导出按已查询条件,包含全部匹配页,单次最多 10000 条。CSV 时间为 UTC,动作与结果保留原始代码。</p>
|
||||
<p v-if="loaded && applied.to" class="subtext audit-hint">查询结果截至 {{ time(applied.to) }},更新条件后点击“查询审计”。</p>
|
||||
<el-alert v-if="loaded && total > 10000" title="匹配记录超过 10000 条,请缩小时间范围或增加筛选条件后导出。" type="warning" :closable="false" show-icon />
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" show-icon />
|
||||
<el-table v-loading="busy" :data="rows" empty-text="没有匹配的审计记录">
|
||||
<el-table-column prop="actor" label="操作者" min-width="110" />
|
||||
<el-table-column label="操作" min-width="150"><template #default="{ row }">{{ auditActionLabels[row.action] || row.action }}<div class="mono secondary">{{ row.action }}</div></template></el-table-column>
|
||||
<el-table-column prop="target" label="对象" min-width="180" show-overflow-tooltip />
|
||||
<el-table-column label="结果" width="125"><template #default="{ row }"><StatusTag :value="row.result" /></template></el-table-column>
|
||||
<el-table-column label="时间" min-width="180"><template #default="{ row }">{{ time(row.createdAt) }}</template></el-table-column>
|
||||
<el-table-column prop="requestId" label="请求标识" min-width="200" show-overflow-tooltip />
|
||||
</el-table>
|
||||
<el-pagination v-model:current-page="page" :disabled="busy" :total="total" :page-size="20" layout="total, prev, pager, next" @current-change="load()" />
|
||||
</template>
|
||||
<style scoped>
|
||||
.audit-filters{display:flex;flex-wrap:wrap;gap:12px;margin:18px 0}.audit-filters>.el-input{width:220px}.audit-filters>.el-select{width:180px}.audit-filters :deep(.el-date-editor){width:390px;flex-grow:0;max-width:100%;box-sizing:border-box}.audit-actions{display:flex;gap:10px;flex-wrap:wrap}.audit-actions .el-button{margin:0}.audit-hint{line-height:1.7;margin:10px 0}.el-alert{margin:12px 0}.el-pagination{margin-top:20px;flex-wrap:wrap}.mono{font-size:11px;margin-top:4px;overflow-wrap:anywhere}
|
||||
@media(max-width:600px){.audit-filters>.el-input,.audit-filters>.el-select{width:100%}.audit-filters :deep(.el-date-editor){width:100%;min-width:0}.audit-actions{width:100%}.audit-actions .el-button:last-child{width:100%}}
|
||||
</style>
|
||||
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, errorMessage } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
const props = defineProps<{ modelValue: boolean }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: boolean] }>()
|
||||
const auth = useAuth(), data = usePlatform(), router = useRouter(), busy = ref(false), error = ref('')
|
||||
const form = reactive({ currentPassword: '', newPassword: '', confirmation: '' })
|
||||
const valid = computed(() => !!form.currentPassword && [...form.newPassword].length >= 12 && new TextEncoder().encode(form.newPassword).length <= 72 && form.newPassword === form.confirmation)
|
||||
watch(() => props.modelValue, () => { Object.assign(form, { currentPassword: '', newPassword: '', confirmation: '' }); error.value = '' })
|
||||
async function save() {
|
||||
if (!valid.value || busy.value) return
|
||||
busy.value = true; error.value = ''
|
||||
try {
|
||||
await api.changeOwnPassword(form.currentPassword, form.newPassword)
|
||||
emit('update:modelValue', false); auth.clear(); data.clear()
|
||||
ElMessage.success('密码已更新,请使用新密码重新登录')
|
||||
await router.replace('/login')
|
||||
} catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog :model-value="modelValue" title="修改本人密码" width="480px" :close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy" @update:model-value="emit('update:modelValue', $event)">
|
||||
<p class="subtext">修改后,本账号的所有登录会失效。</p>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" show-icon style="margin-top:16px" />
|
||||
<el-form label-position="top" :disabled="busy" style="margin-top:20px" @submit.prevent="valid && save()"><el-form-item label="原密码"><el-input v-model="form.currentPassword" type="password" show-password autocomplete="current-password" aria-label="原密码" /></el-form-item><el-form-item label="新密码"><el-input v-model="form.newPassword" type="password" show-password autocomplete="new-password" aria-label="新密码" maxlength="72" /></el-form-item><el-form-item label="确认新密码"><el-input v-model="form.confirmation" type="password" show-password autocomplete="new-password" aria-label="确认新密码" maxlength="72" /></el-form-item><p class="subtext">新密码至少 12 个字符,UTF-8 编码不超过 72 字节。</p></el-form>
|
||||
<template #footer><el-button :disabled="busy" @click="emit('update:modelValue', false)">取消</el-button><el-button type="primary" :disabled="!valid" :loading="busy" @click="save">保存并重新登录</el-button></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,65 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, allPages, errorMessage, type ImageTemplate, type DesktopPool, type Storage, type CloneInput } from '../api'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
const props = defineProps<{ modelValue: boolean; templateId?: string; poolId?: string }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: boolean]; submitted: [] }>()
|
||||
const data = usePlatform(), templates = ref<ImageTemplate[]>([]), pools = ref<DesktopPool[]>([]), storages = ref<Storage[]>([])
|
||||
const busy = ref(false), loading = ref(false), loadError = ref(''), message = ref(''), available = ref(false), taskId = ref(''), key = ref('')
|
||||
const form = reactive<CloneInput>({ templateId: '', poolId: null, name: '', vmid: 9000, full: true, storage: '' })
|
||||
const selected = computed(() => templates.value.find(t => t.id === form.templateId))
|
||||
const choices = computed(() => pools.value.filter(p => p.enabled && (!p.templateId || p.templateId === form.templateId)))
|
||||
const eligibleStorages = computed(() => storages.value.filter(s => s.active && s.enabled && s.content.split(',').includes('images')))
|
||||
watch(() => props.modelValue, async open => {
|
||||
if (!open) return
|
||||
taskId.value = ''; message.value = ''; available.value = false; loadError.value = ''; key.value = crypto.randomUUID()
|
||||
Object.assign(form, { templateId: props.templateId || '', poolId: props.poolId || null, name: '', vmid: 9000, full: true, storage: '' })
|
||||
loading.value = true
|
||||
try { [templates.value, pools.value] = await Promise.all([allPages(api.templates), allPages(api.pools)]); await loadStorages() }
|
||||
catch (e) { loadError.value = errorMessage(e) }
|
||||
finally { loading.value = false }
|
||||
})
|
||||
let storageRequest = 0
|
||||
async function loadStorages() {
|
||||
const request = ++storageRequest, node = selected.value?.node
|
||||
storages.value = []; form.storage = ''
|
||||
if (!node) return
|
||||
try { const result = await allPages(page => api.storages(node, page)); if (request === storageRequest) storages.value = result }
|
||||
catch (e) { if (request === storageRequest) loadError.value = errorMessage(e) }
|
||||
}
|
||||
watch(() => form.templateId, () => { if (form.poolId && !choices.value.some(p => p.id === form.poolId)) form.poolId = null; void loadStorages() })
|
||||
watch(() => form.full, full => { if (!full) form.storage = '' })
|
||||
watch(form, () => { available.value = false; message.value = ''; key.value = crypto.randomUUID() })
|
||||
async function check() {
|
||||
busy.value = true
|
||||
try { const r = await api.checkClone({ ...form }); available.value = r.available; message.value = r.message }
|
||||
catch (e) { available.value = false; message.value = errorMessage(e) }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
async function submit() {
|
||||
busy.value = true
|
||||
try { const task = await api.cloneDesktop({ ...form }, key.value); taskId.value = task.id; ElMessage.success('创建任务已提交,请查看最终结果'); await data.refresh(); emit('submitted') }
|
||||
catch (e) { message.value = errorMessage(e); available.value = false }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog :model-value="modelValue" title="从模板创建桌面" width="620px" :close-on-click-modal="false" @update:model-value="emit('update:modelValue', $event)">
|
||||
<el-alert v-if="loadError" type="error" :title="loadError" :closable="false" show-icon />
|
||||
<template v-if="taskId"><el-result icon="success" title="创建任务已提交" sub-title="提交成功后仍需等待 PVE 克隆完成。请在任务页面查看结果。" /><p class="mono">{{ taskId }}</p><router-link to="/tasks" @click="emit('update:modelValue', false)">查看任务与审计 →</router-link></template>
|
||||
<el-form v-else v-loading="loading" label-position="top" :disabled="busy">
|
||||
<el-alert v-if="!loading && !templates.some(t => t.enabled)" title="尚无已启用模板,请先在镜像模板页面登记 PVE 专用模板。" type="info" :closable="false" />
|
||||
<el-form-item label="镜像模板"><el-select v-model="form.templateId" placeholder="选择模板" filterable><el-option v-for="t in templates.filter(t => t.enabled)" :key="t.id" :value="t.id" :label="`${t.name} · ${t.version} · ${t.os}`" /></el-select></el-form-item>
|
||||
<p v-if="selected" class="subtext">源节点 {{ selected.node }} · 模板 VMID {{ selected.vmid }} · 桌面将在同节点创建</p>
|
||||
<el-form-item label="桌面名称"><el-input v-model="form.name" maxlength="80" placeholder="例如:研发桌面 01" /></el-form-item>
|
||||
<el-form-item label="目标 VMID"><el-input-number v-model="form.vmid" :min="100" :max="999999999" :precision="0" /></el-form-item>
|
||||
<el-form-item label="桌面池(可选)"><el-select v-model="form.poolId" clearable placeholder="不加入桌面池"><el-option v-for="p in choices" :key="p.id" :label="`${p.name} · 已用 ${p.desktopCount + p.reservedCount}/${p.maxCount}`" :value="p.id" :disabled="p.desktopCount + p.reservedCount >= p.maxCount" /></el-select></el-form-item>
|
||||
<el-form-item label="克隆方式"><el-radio-group v-model="form.full"><el-radio :value="true">完整克隆</el-radio><el-radio :value="false">链接克隆</el-radio></el-radio-group></el-form-item>
|
||||
<el-form-item v-if="form.full" label="目标存储"><el-select v-model="form.storage" placeholder="选择存储"><el-option v-for="s in eligibleStorages" :key="s.storage" :value="s.storage" :label="`${s.storage} · 可用 ${(s.avail / 1073741824).toFixed(1)} GiB`" /></el-select></el-form-item>
|
||||
<p class="subtext">创建后需单独完成系统身份、IP、Sunshine 服务与终端配对,然后在桌面详情配置连接。公共池当前由管理员分配与回收。</p>
|
||||
<el-alert v-if="message" :title="message" :type="available ? 'success' : 'warning'" :closable="false" show-icon />
|
||||
</el-form>
|
||||
<template #footer><el-button :disabled="busy" @click="emit('update:modelValue', false)">关闭</el-button><template v-if="!taskId"><el-button :loading="busy" :disabled="loading || !form.templateId || !form.name.trim() || (form.full && !form.storage)" @click="check">检查创建条件</el-button><el-button type="primary" :loading="busy" :disabled="!available" @click="submit">提交创建任务</el-button></template></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,72 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { api, errorMessage, type ImportPreview, type ImportResult } from '../api'
|
||||
const visible = defineModel<boolean>({ required: true })
|
||||
const props = defineProps<{ kind: 'users' | 'terminals' | 'bindings' }>()
|
||||
const emit = defineEmits<{ completed: [] }>()
|
||||
const csv = ref(''), filename = ref(''), busy = ref(false), error = ref(''), preview = ref<ImportPreview>(), result = ref<ImportResult>(), saved = ref(false)
|
||||
const titles = { users: '批量新增用户', terminals: '批量登记终端', bindings: '批量导入授权' }
|
||||
const headers = { users: ['username', 'displayName'], terminals: ['sn', 'name', 'group'], bindings: ['username', 'terminalSn', 'desktopIds'] }
|
||||
const descriptions = { users: '只新增用户,不修改已有账号。姓名和账号必填。', terminals: '只登记新 SN,不修改现有设备。激活密钥在本次结果中下载,请妥善保存。', bindings: '用户和终端须已存在。空终端 SN 保持原绑定;桌面 ID 用英文分号分隔,仅追加授权。已有其他终端的用户需单独换绑。' }
|
||||
const columns = computed(() => headers[props.kind])
|
||||
let requestKey = '', readGeneration = 0
|
||||
watch(visible, open => { if (open) { csv.value = ''; filename.value = ''; preview.value = undefined; result.value = undefined; error.value = ''; saved.value = false; requestKey = crypto.randomUUID(); ++readGeneration } })
|
||||
watch(csv, () => { preview.value = undefined })
|
||||
function download(name: string, rows: string[][]) {
|
||||
// Neutralize spreadsheet formulas while preserving CSV quoting and Unicode.
|
||||
const cell = (s: string) => `"${(/^[\s]*[=+@-]/.test(s) ? `'${s}` : s).replace(/"/g, '""')}"`
|
||||
const data = '\ufeff' + rows.map(row => row.map(cell).join(',')).join('\r\n')
|
||||
const url = URL.createObjectURL(new Blob([data], { type: 'text/csv;charset=utf-8' })), a = document.createElement('a')
|
||||
a.href = url; a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
function template() { download(`${props.kind}-template.csv`, [columns.value]) }
|
||||
async function choose(event: Event) {
|
||||
const input = event.target as HTMLInputElement, file = input.files?.[0], generation = ++readGeneration
|
||||
input.value = ''; if (!file) return
|
||||
if (file.size > 524288) { ElMessage.error('文件不能超过 512 KiB'); return }
|
||||
try {
|
||||
const text = new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer())
|
||||
if (generation !== readGeneration) return
|
||||
csv.value = text; filename.value = file.name; error.value = ''; result.value = undefined
|
||||
} catch { ElMessage.error('请将 CSV 保存为 UTF-8 编码') }
|
||||
}
|
||||
async function check() {
|
||||
busy.value = true; error.value = ''; result.value = undefined
|
||||
try { preview.value = await api.previewImport({ kind: props.kind, csv: csv.value }) } catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function commit() {
|
||||
if (!preview.value?.previewToken || busy.value) return
|
||||
busy.value = true; error.value = ''
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认导入 ${preview.value.totalRows} 行?提交时会再次核对数据;有变化时整批取消。`, '确认批量导入', { type: 'warning', confirmButtonText: '确认导入', cancelButtonText: '取消' })
|
||||
result.value = await api.commitImport({ kind: props.kind, csv: csv.value, previewToken: preview.value.previewToken }, requestKey)
|
||||
emit('completed'); ElMessage.success(`已导入 ${result.value.count} 行`)
|
||||
} catch (e) { if (e !== 'cancel' && e !== 'close') error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
function exportErrors() { if (preview.value) download('import-errors.csv', [['line', ...columns.value, 'errors'], ...preview.value.rows.filter(r => r.errors.length).map(r => [String(r.line), ...columns.value.map(c => r.values[c] || ''), r.errors.join(';')])]) }
|
||||
function exportSecrets() { if (result.value) { download('terminal-activation.csv', [['sn', 'activationSecret'], ...result.value.activationSecrets.map(s => [s.sn, s.activationSecret])]); saved.value = true } }
|
||||
async function close(done: () => void) {
|
||||
if (busy.value) return
|
||||
if (result.value?.activationSecrets.length && !saved.value) {
|
||||
try { await ElMessageBox.confirm('本次激活密钥尚未下载。关闭后无法重新查看;需要在终端管理中重新激活。', '尚未保存激活信息', { confirmButtonText: '仍然关闭', cancelButtonText: '返回保存', type: 'warning' }) } catch { return }
|
||||
}
|
||||
++readGeneration; done()
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog v-model="visible" :title="titles[kind]" width="850px" :close-on-click-modal="false" :before-close="close" :show-close="!busy" @closed="csv = ''; result = undefined; preview = undefined">
|
||||
<p class="subtext">{{ descriptions[kind] }}每批最多 200 行,文件不超过 512 KiB。</p>
|
||||
<template v-if="!result">
|
||||
<div class="import-actions"><el-button :disabled="busy" @click="template">下载空白模板</el-button><label class="file-picker"><span>选择 CSV 文件</span><input type="file" accept=".csv,text/csv" aria-label="选择 CSV 文件" :disabled="busy" @change="choose" /></label><span class="subtext">{{ filename }}</span></div>
|
||||
<el-input v-model="csv" type="textarea" :rows="6" :disabled="busy" aria-label="CSV 内容" placeholder="也可粘贴 UTF-8 CSV 内容,第一行为表头" />
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" class="notice" />
|
||||
<div v-if="preview" class="preview"><p>共 {{ preview.totalRows }} 行 · 通过 {{ preview.validRows }} 行 · 错误 {{ preview.errorRows }} 行 <el-button v-if="preview.errorRows" link type="primary" @click="exportErrors">下载错误行</el-button></p><el-table :data="preview.rows" max-height="320" empty-text="没有数据"><el-table-column prop="line" label="行号" width="65" /><el-table-column v-for="col in columns" :key="col" :label="col" min-width="130"><template #default="{ row }">{{ row.values[col] }}</template></el-table-column><el-table-column label="预检结果" min-width="230"><template #default="{ row }"><span :class="row.errors.length ? 'tone-danger' : 'tone-ok'">{{ row.errors.length ? row.errors.join(';') : '通过' }}</span></template></el-table-column></el-table><p class="subtext">预检通过后才能提交;任何错误都会阻止整批导入。</p></div>
|
||||
</template>
|
||||
<template v-else><el-result icon="success" title="导入完成" :sub-title="`${result.count} 行已提交${result.replayed ? '(重复请求,未重复写入)' : ''}`" /><el-alert v-if="kind === 'terminals'" :closable="false" :type="result.activationSecrets.length ? 'warning' : 'info'" :title="result.activationSecrets.length ? '激活密钥仅在本次响应提供,请立即下载并妥善保管。' : '此次为重复请求,激活密钥不再返回;如未保存,请在终端管理中重新激活。'" /><el-button v-if="result.activationSecrets.length" type="primary" class="download-secret" @click="exportSecrets">下载终端激活信息</el-button><el-table :data="result.items" max-height="260"><el-table-column prop="line" label="行号" width="70" /><el-table-column prop="key" label="账号 / SN" min-width="180" /><el-table-column prop="id" label="平台标识" min-width="220" /></el-table></template>
|
||||
<template #footer><el-button :disabled="busy" @click="close(() => visible = false)">{{ result ? '关闭' : '取消' }}</el-button><template v-if="!result"><el-button :disabled="!csv.trim() || busy" :loading="busy" @click="check">预检文件</el-button><el-button type="primary" :disabled="!preview?.previewToken || !!preview?.errorRows || busy" :loading="busy" @click="commit">提交导入</el-button></template></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<style scoped>
|
||||
.import-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:18px 0}.file-picker{position:relative;padding:9px 14px;border:1px solid var(--vdi-border);border-radius:8px;font-size:12px;cursor:pointer}.file-picker input{position:absolute;inset:0;opacity:0;width:100%;cursor:pointer}.preview{margin-top:20px}.preview>p{margin:12px 0;font-size:12px}.download-secret{margin:18px 0}.subtext{line-height:1.8}
|
||||
</style>
|
||||
@@ -0,0 +1,86 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onUnmounted, ref, watch } from 'vue'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { api, errorMessage, allPages, type DesktopAction, type PowerBatch, type PowerBatchDetail, type PowerBatchPreview } from '../api'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import StatusTag from './StatusTag.vue'
|
||||
const mode = defineModel<DesktopAction | 'history' | undefined>({ required: true })
|
||||
const props = defineProps<{ desktopIds: string[] }>()
|
||||
const auth = useAuth(), platform = usePlatform(), busy = ref(false), error = ref(''), preview = ref<PowerBatchPreview>(), detail = ref<PowerBatchDetail>(), history = ref<PowerBatch[]>([])
|
||||
const labels = { start: '开机', shutdown: '正常关机', reboot: '重启' }
|
||||
const ids = ref<string[]>([]), now = ref(Date.now())
|
||||
const action = computed(() => mode.value && mode.value !== 'history' ? mode.value : undefined)
|
||||
const title = computed(() => detail.value ? '批量操作结果' : mode.value === 'history' ? '桌面批量记录' : `批量${labels[action.value || 'start']}`)
|
||||
const canSubmit = computed(() => !!action.value && !!preview.value?.eligibleCount && Date.parse(preview.value.expiresAt) > now.value)
|
||||
let key = '', timer: ReturnType<typeof setInterval> | undefined, generation = 0
|
||||
watch(mode, async value => {
|
||||
generation++; if (timer) clearInterval(timer); timer = undefined
|
||||
if (!value) return
|
||||
ids.value = [...props.desktopIds]; preview.value = undefined; detail.value = undefined; history.value = []; error.value = ''; key = crypto.randomUUID()
|
||||
if (value === 'history') await loadHistory()
|
||||
timer = setInterval(() => { now.value = Date.now(); if (detail.value?.batch.activeCount) void loadDetail(detail.value.batch.id); else if (mode.value === 'history' && !detail.value) void loadHistory() }, 5000)
|
||||
})
|
||||
onUnmounted(() => { generation++; if (timer) clearInterval(timer) })
|
||||
async function loadHistory() {
|
||||
if (busy.value) return
|
||||
const version = generation; busy.value = true; error.value = ''
|
||||
try { const items = await allPages(api.desktopPowerBatches); if (version === generation) history.value = items }
|
||||
catch (e) { if (version === generation) error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function loadDetail(id: string) {
|
||||
if (busy.value) return
|
||||
const version = generation; busy.value = true; error.value = ''
|
||||
try { const value = await api.desktopPowerBatch(id); if (version === generation) detail.value = value }
|
||||
catch (e) { if (version === generation) error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function check() {
|
||||
if (!action.value || busy.value) return
|
||||
busy.value = true; error.value = ''; preview.value = undefined; key = crypto.randomUUID()
|
||||
try { preview.value = await api.checkDesktopPowerBatch({ action: action.value, desktopIds: ids.value }) }
|
||||
catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function submit() {
|
||||
if (!action.value || !canSubmit.value || !preview.value || busy.value) return
|
||||
busy.value = true; error.value = ''
|
||||
try {
|
||||
const warning = action.value === 'start' ? '开机不代表桌面连接服务已经就绪。' : '会使所列桌面关机或重启,请确认使用者已保存工作。'
|
||||
await ElMessageBox.confirm(`本次仅向预检通过的 ${preview.value.eligibleCount} 台桌面提交${labels[action.value]},其余 ${preview.value.skippedCount} 台跳过。${warning} 提交和执行前会再次检查,结果逐台记录。`, '确认批量操作', { type: 'warning', confirmButtonText: '提交批量任务', cancelButtonText: '取消' })
|
||||
detail.value = await api.submitDesktopPowerBatch({ action: action.value, desktopIds: ids.value, previewToken: preview.value.previewToken }, key)
|
||||
await platform.refresh()
|
||||
} catch (e) { if (e !== 'cancel' && e !== 'close') error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function reconcile(id: string) {
|
||||
if (busy.value || !detail.value) return
|
||||
busy.value = true; error.value = ''
|
||||
try { await api.reconcileBatchPower(id); detail.value = await api.desktopPowerBatch(detail.value.batch.id); await platform.refresh() }
|
||||
catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
function close(done: () => void) { if (!busy.value) done() }
|
||||
function visibility(value: boolean) { if (!value) mode.value = undefined }
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog class="desktop-batch-dialog" :model-value="!!mode" :title="title" width="900px" :close-on-click-modal="false" :show-close="!busy" :before-close="close" @update:model-value="visibility">
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" class="notice" />
|
||||
<template v-if="detail">
|
||||
<p class="subtext">批次 {{ detail.batch.id }} · {{ labels[detail.batch.action] }} · {{ detail.batch.actor }}</p>
|
||||
<div class="batch-counts"><span>已提交 <b>{{ detail.batch.submittedCount }}</b></span><span>执行中 <b>{{ detail.batch.activeCount }}</b></span><span>成功 <b>{{ detail.batch.successCount }}</b></span><span>失败 <b>{{ detail.batch.failedCount }}</b></span><span>未确认 <b>{{ detail.batch.uncertainCount }}</b></span><span>跳过 <b>{{ detail.batch.skippedCount }}</b></span></div>
|
||||
<el-alert type="info" title="已提交不等于已成功;执行中的结果每 5 秒刷新。结果未确认的任务不会自动重发。" :closable="false" class="notice" />
|
||||
<el-table :data="detail.items" row-key="desktopId"><el-table-column label="桌面" min-width="145"><template #default="{ row }">{{ row.name || row.desktopId }}<div class="secondary">VM {{ row.vmid || '未知' }}</div></template></el-table-column><el-table-column label="状态" width="125"><template #default="{ row }"><StatusTag v-if="row.status !== 'skipped'" :value="row.status === 'running' ? '执行中' : row.status" /><el-tag v-else type="info">已跳过</el-tag></template></el-table-column><el-table-column prop="message" label="结果" min-width="230" /><el-table-column label="任务" min-width="130"><template #default="{ row }"><span v-if="row.taskId" class="mono secondary">{{ row.taskId.slice(0, 18) }}…</span><el-button v-if="auth.canOperate && row.status === 'timeout'" link type="primary" :disabled="busy" @click="reconcile(row.taskId)">核对电源结果</el-button></template></el-table-column></el-table>
|
||||
</template>
|
||||
<template v-else-if="mode === 'history'">
|
||||
<p class="subtext">最近 100 个批次,可查看逐台任务和跳过原因。历史失败批次不会自动重新执行。</p>
|
||||
<el-table :data="history" empty-text="暂无批量操作记录"><el-table-column label="操作 / 操作者" min-width="150"><template #default="{ row }"><el-button link type="primary" :disabled="busy" @click="loadDetail(row.id)">{{ labels[row.action as DesktopAction] }} · {{ row.actor }}</el-button><div class="secondary">{{ new Date(row.createdAt).toLocaleString('zh-CN') }}</div></template></el-table-column><el-table-column prop="totalCount" label="选择" width="65" /><el-table-column prop="successCount" label="成功" width="65" /><el-table-column prop="activeCount" label="执行中" width="80" /><el-table-column prop="failedCount" label="失败" width="65" /><el-table-column prop="uncertainCount" label="未确认" width="80" /><el-table-column prop="skippedCount" label="跳过" width="65" /></el-table>
|
||||
</template>
|
||||
<template v-else>
|
||||
<p class="subtext">已选择 {{ ids.length }} 台桌面,每批最多 50 台。批量操作会跳过活动会话、维护中、权限不足和状态不适用的桌面。</p>
|
||||
<template v-if="preview"><div class="batch-counts"><span>可执行 <b>{{ preview.eligibleCount }}</b></span><span>跳过 <b>{{ preview.skippedCount }}</b></span><span>预检有效至 {{ new Date(preview.expiresAt).toLocaleTimeString('zh-CN') }}</span></div><el-table :data="preview.items" row-key="desktopId"><el-table-column label="桌面 / VMID" min-width="150"><template #default="{ row }">{{ row.name || row.desktopId }}<div class="secondary">VM {{ row.vmid || '未知' }}</div></template></el-table-column><el-table-column label="预检" width="100"><template #default="{ row }"><el-tag :type="row.available ? 'success' : 'info'">{{ row.available ? '可执行' : '跳过' }}</el-tag></template></el-table-column><el-table-column prop="message" label="说明" min-width="230" /></el-table></template>
|
||||
<el-table v-else :data="ids.map(id => platform.desktops.find(d => d.id === id)).filter(Boolean)"><el-table-column prop="name" label="所选桌面" min-width="160" /><el-table-column prop="vmid" label="VMID" width="100" /><el-table-column label="当前状态" min-width="100"><template #default="{ row }"><StatusTag :value="row.powerState" /></template></el-table-column></el-table>
|
||||
</template>
|
||||
<template #footer><div class="batch-footer"><el-button :disabled="busy" @click="mode = undefined">关闭</el-button><template v-if="detail"><el-button v-if="mode === 'history'" :disabled="busy" @click="detail = undefined; loadHistory()">返回批次列表</el-button><el-button :loading="busy" @click="loadDetail(detail.batch.id)">刷新结果</el-button></template><el-button v-else-if="mode === 'history'" :loading="busy" @click="loadHistory">刷新批次</el-button><template v-else><el-button :loading="busy" :disabled="busy || !ids.length" @click="check">预检批量操作</el-button><el-button type="primary" :loading="busy" :disabled="busy || !canSubmit" @click="submit">提交批量操作</el-button></template></div></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<style scoped>
|
||||
.subtext{line-height:1.8;margin:10px 0 20px;overflow-wrap:anywhere}.batch-counts{display:flex;gap:12px;flex-wrap:wrap;margin:20px 0;color:var(--vdi-muted);font-size:12px}.batch-counts span{padding:9px 12px;background:var(--vdi-panel-2);border:1px solid var(--vdi-border);border-radius:9px}.batch-counts b{color:var(--vdi-text);margin-left:5px}.batch-footer{display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap}.batch-footer .el-button{margin:0}@media(max-width:600px){.batch-footer .el-button{flex:1;min-width:105px}}
|
||||
</style>
|
||||
<style>.desktop-batch-dialog{display:flex;flex-direction:column;max-height:90dvh;margin:5dvh auto!important}.desktop-batch-dialog .el-dialog__body{min-height:0;overflow-y:auto;overscroll-behavior:contain}.desktop-batch-dialog .el-dialog__header,.desktop-batch-dialog .el-dialog__footer{flex-shrink:0}</style>
|
||||
@@ -0,0 +1,46 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { api, errorMessage, type Desktop, type VMHardware, type HardwareInput } from '../api'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
const desktop = defineModel<Desktop | undefined>({ required: true })
|
||||
const snapshot = ref<VMHardware>(), busy = ref(false), error = ref(''), tab = ref('compute'), cores = ref(1), sockets = ref(1), memory = ref(2048), disk = ref(''), size = ref(1), checked = ref(false)
|
||||
let key = ''
|
||||
const diskInfo = computed(() => snapshot.value?.disks.find(d => d.key === disk.value))
|
||||
const input = computed<HardwareInput>(() => tab.value === 'compute' ? { kind: 'compute', cores: cores.value, sockets: sockets.value, memoryMiB: memory.value, digest: snapshot.value?.digest || '' } : { kind: 'disk', disk: disk.value, sizeGiB: size.value, digest: snapshot.value?.digest || '' })
|
||||
const valid = computed(() => !!snapshot.value && !snapshot.value.blockers.length && snapshot.value.powerState === 'stopped' && (tab.value === 'compute' ? (cores.value !== snapshot.value.cores || sockets.value !== snapshot.value.sockets || memory.value !== snapshot.value.memoryMiB) && cores.value * sockets.value <= 1024 && memory.value % 128 === 0 : !!diskInfo.value && size.value > diskInfo.value.sizeGiB))
|
||||
watch(input, () => { checked.value = false; key = crypto.randomUUID() })
|
||||
watch(disk, () => { size.value = Math.ceil(diskInfo.value?.sizeGiB || 0) + 1 })
|
||||
watch(desktop, async value => { if (value) { tab.value = 'compute'; snapshot.value = undefined; await load() } })
|
||||
async function load() {
|
||||
if (!desktop.value || busy.value) return
|
||||
busy.value = true; error.value = ''; checked.value = false
|
||||
try { snapshot.value = await api.desktopHardware(desktop.value.id); cores.value = snapshot.value.cores; sockets.value = snapshot.value.sockets; memory.value = snapshot.value.memoryMiB; disk.value = snapshot.value.disks[0]?.key || ''; size.value = Math.ceil(diskInfo.value?.sizeGiB || 0) + 1; key = crypto.randomUUID() }
|
||||
catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function check() {
|
||||
if (!desktop.value) return
|
||||
busy.value = true; error.value = ''; checked.value = false
|
||||
try { const result = await api.checkDesktopHardware(desktop.value.id, { ...input.value }); checked.value = result.available } catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function submit() {
|
||||
if (!desktop.value || !checked.value) return
|
||||
busy.value = true; error.value = ''
|
||||
try {
|
||||
const text = tab.value === 'compute' ? `CPU ${sockets.value} 插槽 × ${cores.value} 核,内存 ${memory.value} MiB` : `${disk.value} 扩容至 ${size.value} GiB;完成后需在客体内扩展分区和文件系统`
|
||||
await ElMessageBox.confirm(`${desktop.value.name}:${text}。执行前会重新检查关机状态和配置。`, '确认规格变更', { confirmButtonText: '提交规格任务', cancelButtonText: '取消', type: 'warning' })
|
||||
await api.changeDesktopHardware(desktop.value.id, { ...input.value }, key); ElMessage.success('规格任务已提交,请查看任务与审计中的最终结果'); desktop.value = undefined; await usePlatform().refresh()
|
||||
} catch (e) { if (e !== 'cancel' && e !== 'close') error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
function updateVisibility(value: boolean) { if (!value) desktop.value = undefined }
|
||||
function close(done: () => void) { if (!busy.value) done() }
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog :model-value="!!desktop" title="桌面规格管理" width="680px" :close-on-click-modal="false" :show-close="!busy" :before-close="close" @update:model-value="updateVisibility">
|
||||
<p class="subtext">{{ desktop?.name }} · VM {{ desktop?.vmid }} · 操作只在正常关机后执行。</p>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" class="notice" /><el-skeleton v-if="busy && !snapshot" :rows="6" animated />
|
||||
<template v-if="snapshot"><el-alert v-if="snapshot.blockers.length" type="warning" :title="snapshot.blockers.join(';')" :closable="false" class="notice" /><el-alert v-if="checked" type="success" title="预检通过,提交和执行时会再次核对" :closable="false" class="notice" /><el-tabs v-model="tab"><el-tab-pane label="CPU 与内存" name="compute" :disabled="busy" /><el-tab-pane label="磁盘扩容" name="disk" :disabled="busy" /></el-tabs><el-form label-position="top" :disabled="busy || !!snapshot.blockers.length"><template v-if="tab === 'compute'"><p class="subtext">当前:{{ snapshot.sockets }} 插槽 × {{ snapshot.cores }} 核 · {{ snapshot.memoryMiB }} MiB 内存</p><div class="compute-fields"><el-form-item label="每插槽核心数"><el-input-number v-model="cores" :min="1" :max="256" :precision="0" aria-label="每插槽核心数" /></el-form-item><el-form-item label="CPU 插槽数"><el-input-number v-model="sockets" :min="1" :max="8" :precision="0" aria-label="CPU 插槽数" /></el-form-item><el-form-item label="内存(MiB)"><el-input-number v-model="memory" :min="512" :max="1048576" :step="128" :precision="0" aria-label="目标内存" /></el-form-item></div><p class="subtext">目标共 {{ cores * sockets }} 个 vCPU。CPU 型号、GPU 和其他硬件保持现有配置。</p></template><template v-else><el-empty v-if="!snapshot.disks.length" description="没有可由平台扩容的虚拟磁盘" /><template v-else><el-form-item label="虚拟磁盘"><el-select v-model="disk" aria-label="扩容磁盘"><el-option v-for="d in snapshot.disks" :key="d.key" :value="d.key" :label="`${d.key} · ${d.storage} · ${d.sizeGiB} GiB`" /></el-select></el-form-item><el-form-item label="扩容后总容量(GiB)"><el-input-number v-model="size" :min="Math.floor(diskInfo?.sizeGiB || 0) + 1" :max="65536" :precision="0" aria-label="磁盘目标容量" /></el-form-item><el-alert title="仅扩容虚拟磁盘,不缩容;客体分区和文件系统需后续扩展。请确认已有可用备份。" type="warning" :closable="false" /></template></template></el-form></template>
|
||||
<template #footer><el-button :disabled="busy" @click="desktop = undefined">关闭</el-button><el-button :disabled="busy" @click="load">重新读取</el-button><el-button :loading="busy" :disabled="busy || !valid" @click="check">预检规格</el-button><el-button type="primary" :loading="busy" :disabled="busy || !valid || !checked" @click="submit">提交变更</el-button></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<style scoped>.subtext{line-height:1.8;margin:12px 0 20px}.compute-fields{display:flex;gap:18px;flex-wrap:wrap}.el-form-item{margin:18px 0}.compute-fields .el-input-number{width:170px}</style>
|
||||
@@ -0,0 +1,80 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { api, errorMessage, type Desktop, type SnapshotView, type SnapshotInput, type SnapshotItem } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
const desktop = defineModel<Desktop | undefined>({ required: true })
|
||||
const auth = useAuth(), view = ref<SnapshotView>(), busy = ref(false), error = ref(''), checked = ref(false)
|
||||
const action = ref<SnapshotInput['action']>('create'), name = ref(''), description = ref(''), confirm = ref('')
|
||||
let key = ''
|
||||
const selected = computed(() => view.value?.items.find(s => s.name === name.value))
|
||||
const input = computed<SnapshotInput>(() => ({ action: action.value, name: name.value, digest: view.value?.digest || '', ...(action.value === 'create' ? { description: description.value } : { revision: selected.value?.revision || '' }), ...(action.value === 'rollback' ? { confirmVmid: Number(confirm.value) || 0 } : {}) }))
|
||||
const hasChildren = (item: SnapshotItem) => !!view.value?.items.some(s => s.parent === item.name)
|
||||
const permitted = computed(() => action.value === 'create' ? view.value?.canCreate : action.value === 'delete' ? view.value?.canDelete : view.value?.canRestore)
|
||||
const valid = computed(() => auth.canAdmin && view.value && !view.value.blockers.length && permitted.value && (action.value === 'create' ? /^[A-Za-z][A-Za-z0-9_-]{0,39}$/.test(name.value) && !/^(current|pending)$/i.test(name.value) && !selected.value : !!selected.value && !selected.value.state && (action.value === 'delete' ? !hasChildren(selected.value) : !selected.value.includesMemory && confirm.value.trim() === String(desktop.value?.vmid))))
|
||||
const actionLabel = computed(() => ({ create: '创建快照', delete: '删除快照', rollback: '还原快照' })[action.value])
|
||||
watch(input, () => { checked.value = false; key = crypto.randomUUID() })
|
||||
watch(desktop, async value => { if (value) { view.value = undefined; action.value = 'create'; name.value = ''; description.value = ''; confirm.value = ''; await load() } })
|
||||
async function load() {
|
||||
if (!desktop.value || busy.value) return
|
||||
busy.value = true; error.value = ''; checked.value = false
|
||||
try { view.value = await api.desktopSnapshots(desktop.value.id); key = crypto.randomUUID() }
|
||||
catch (e) { view.value = undefined; error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
function choose(kind: SnapshotInput['action'], item?: SnapshotItem) { action.value = kind; name.value = item?.name || ''; description.value = ''; confirm.value = ''; error.value = '' }
|
||||
async function check() {
|
||||
if (!desktop.value || !valid.value) return
|
||||
busy.value = true; error.value = ''; checked.value = false
|
||||
try { checked.value = (await api.checkDesktopSnapshot(desktop.value.id, { ...input.value })).available }
|
||||
catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function submit() {
|
||||
if (!desktop.value || !valid.value || !checked.value) return
|
||||
busy.value = true; error.value = ''
|
||||
try {
|
||||
const detail = action.value === 'rollback' ? '将回退虚拟机配置以及快照内所有磁盘的数据(包括其中的数据盘),当前更改会丢失。完成后保持关机,需重新确认连接初始化、系统身份与配对。' : action.value === 'delete' ? '将永久删除此恢复点,无法通过它还原。' : '创建当前关机配置及磁盘的快照,不保存内存。'
|
||||
await ElMessageBox.confirm(`${desktop.value.name} / VM ${desktop.value.vmid} / ${name.value}:${detail}`, `确认${actionLabel.value}`, { type: 'warning', confirmButtonText: `提交${actionLabel.value}任务`, cancelButtonText: '取消' })
|
||||
await api.changeDesktopSnapshot(desktop.value.id, { ...input.value }, key)
|
||||
ElMessage.success('快照任务已提交,请在任务与审计查看最终结果'); desktop.value = undefined; await usePlatform().refresh()
|
||||
} catch (e) { if (e !== 'cancel' && e !== 'close') error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
function updateVisibility(value: boolean) { if (!value) desktop.value = undefined }
|
||||
function close(done: () => void) { if (!busy.value) done() }
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog class="snapshot-dialog" top="5vh" :model-value="!!desktop" title="快照与还原" width="780px" :close-on-click-modal="false" :show-close="!busy" :before-close="close" @update:model-value="updateVisibility">
|
||||
<p class="subtext">{{ desktop?.name }} · VM {{ desktop?.vmid }} · 快照操作须先正常关机。</p>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" class="notice" />
|
||||
<el-skeleton v-if="busy && !view" :rows="6" animated />
|
||||
<template v-if="view">
|
||||
<el-alert v-if="view.blockers.length" type="warning" :title="view.blockers.join(';')" :closable="false" class="notice" />
|
||||
<p class="subtext">磁盘范围:{{ view.disks.join('、') || '请先处理配置限制' }}。还原覆盖快照内磁盘及配置,系统盘与数据盘不会自动分开。</p>
|
||||
<div class="snapshot-heading"><h3>已有快照 <span class="subtext">{{ view.items.length }}</span></h3><el-button v-if="auth.canAdmin" :disabled="busy || !view.canCreate" @click="choose('create')">新建快照</el-button></div>
|
||||
<el-empty v-if="!view.items.length" description="尚无快照,可在关机后创建恢复点" :image-size="65" />
|
||||
<div v-for="item in view.items" :key="item.name" class="snapshot-item" :class="{ selected: action !== 'create' && name === item.name }">
|
||||
<div class="snapshot-info"><strong>{{ item.name }}</strong><p>{{ item.description || '无描述' }}</p><p>{{ item.createdAt ? new Date(item.createdAt * 1000).toLocaleString('zh-CN') : '时间未知' }} · {{ item.includesMemory ? '含内存状态,暂不能还原' : '无内存状态' }}{{ item.state ? ' · 状态未完成' : '' }}</p><p v-if="hasChildren(item)">含子快照,请先处理子快照再删除</p></div>
|
||||
<div v-if="auth.canAdmin" class="snapshot-actions"><el-button :disabled="busy || !!view.blockers.length || !view.canRestore || item.includesMemory || !!item.state" @click="choose('rollback', item)">还原</el-button><el-button type="danger" plain :disabled="busy || !!view.blockers.length || !view.canDelete || hasChildren(item) || !!item.state" @click="choose('delete', item)">删除</el-button></div>
|
||||
</div>
|
||||
<p v-if="!auth.canAdmin" class="subtext">当前角色可查看快照;管理快照需要超级管理员。</p>
|
||||
<template v-else>
|
||||
<p v-if="!permitted" class="subtext">PVE Token 缺少当前操作的快照权限,请联系 PVE 管理员配置。</p>
|
||||
<el-form label-position="top" :disabled="busy || !!view.blockers.length || !permitted" class="snapshot-form">
|
||||
<h3>{{ actionLabel }}</h3>
|
||||
<el-form-item label="快照名称"><el-input v-model="name" :readonly="action !== 'create'" maxlength="40" aria-label="快照名称" placeholder="字母开头,1~40 位字母、数字、下划线或短横线" /></el-form-item>
|
||||
<el-form-item v-if="action === 'create'" label="描述"><el-input v-model="description" type="textarea" :rows="2" maxlength="500" show-word-limit aria-label="快照描述" /></el-form-item>
|
||||
<template v-if="action === 'rollback'"><el-alert type="warning" title="还原将丢弃快照之后的磁盘及配置更改,包括快照中的数据盘。还原成功后需重新确认连接初始化。" :closable="false" /><el-form-item :label="`输入 VMID ${desktop?.vmid} 确认还原范围`"><el-input v-model="confirm" inputmode="numeric" aria-label="还原确认 VMID" /></el-form-item></template>
|
||||
</el-form>
|
||||
<el-alert v-if="checked" type="success" title="预检通过,提交和执行前会再次核对" :closable="false" class="notice" />
|
||||
</template>
|
||||
</template>
|
||||
<template #footer><div class="snapshot-footer"><el-button :disabled="busy" @click="desktop = undefined">关闭</el-button><el-button :disabled="busy" @click="load">重新读取</el-button><template v-if="auth.canAdmin"><el-button :loading="busy" :disabled="busy || !valid" @click="check">预检快照操作</el-button><el-button type="primary" :loading="busy" :disabled="busy || !valid || !checked" @click="submit">提交{{ actionLabel }}</el-button></template></div></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<style scoped>
|
||||
.subtext{line-height:1.8;margin:12px 0}.snapshot-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:22px 0 12px}.snapshot-item{display:flex;justify-content:space-between;gap:16px;padding:16px 0;border-bottom:1px solid var(--vdi-border)}.snapshot-info{min-width:0;overflow-wrap:anywhere}.snapshot-info p{color:var(--vdi-muted);font-size:12px;margin:8px 0;line-height:1.7;white-space:pre-wrap}.snapshot-actions{display:flex;align-items:center;flex-shrink:0}.snapshot-item.selected strong{color:var(--vdi-accent)}.snapshot-form{padding-top:22px}.snapshot-form h3{margin-bottom:18px}.snapshot-footer{display:flex;justify-content:flex-end;gap:8px;flex-wrap:wrap}.snapshot-footer .el-button{margin:0}@media(max-width:600px){.snapshot-item{flex-direction:column}.snapshot-actions{justify-content:flex-end}.snapshot-footer .el-button{flex:1;min-width:105px}}
|
||||
</style>
|
||||
|
||||
<style>
|
||||
.snapshot-dialog{display:flex;flex-direction:column;max-height:90dvh;margin:5dvh auto!important}.snapshot-dialog .el-dialog__body{min-height:0;overflow-y:auto;overscroll-behavior:contain}.snapshot-dialog .el-dialog__header,.snapshot-dialog .el-dialog__footer{flex-shrink:0}
|
||||
</style>
|
||||
@@ -0,0 +1,87 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, onBeforeUnmount } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, errorMessage, type MFAStatus, type MFASetup } from '../api'
|
||||
import { useAction } from '../composables/useAction'
|
||||
const props = defineProps<{ modelValue: boolean }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: boolean] }>()
|
||||
const { confirm } = useAction()
|
||||
const status = ref<MFAStatus>(), setup = ref<MFASetup>(), recovery = ref<string[]>([]), password = ref(''), code = ref(''), error = ref(''), loading = ref(false), busy = ref(false), action = ref<'disable' | 'rotate'>()
|
||||
let generation = 0
|
||||
onBeforeUnmount(() => { generation++ })
|
||||
watch(() => props.modelValue, open => {
|
||||
generation++; status.value = undefined; setup.value = undefined; recovery.value = []; password.value = ''; code.value = ''; error.value = ''; action.value = undefined
|
||||
if (open) void load()
|
||||
})
|
||||
async function load() {
|
||||
const request = ++generation; loading.value = true; error.value = ''
|
||||
try { const result = await api.mfaStatus(); if (request === generation) status.value = result }
|
||||
catch (e) { if (request === generation) error.value = errorMessage(e) }
|
||||
finally { if (request === generation) loading.value = false }
|
||||
}
|
||||
async function begin() {
|
||||
if (busy.value || !password.value) return
|
||||
busy.value = true; error.value = ''
|
||||
try { setup.value = await api.beginMFA(password.value); password.value = ''; code.value = '' }
|
||||
catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function enable() {
|
||||
if (busy.value || !/^\d{6}$/.test(code.value)) return
|
||||
busy.value = true; error.value = ''
|
||||
try { recovery.value = (await api.confirmMFA(code.value)).recoveryCodes; setup.value = undefined; code.value = ''; await load(); ElMessage.success('双重验证已开启,其他登录已失效') }
|
||||
catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function change() {
|
||||
if (busy.value || !action.value || !password.value || !code.value.trim()) return
|
||||
busy.value = true; error.value = ''
|
||||
try {
|
||||
const disable = action.value === 'disable'
|
||||
if (!await confirm(disable ? '关闭双重验证' : '重新生成恢复码', disable ? '关闭后登录只需密码,其他登录将失效。确认关闭?' : '现有恢复码将全部作废,其他登录将失效。确认重新生成?')) return
|
||||
if (disable) { await api.disableMFA(password.value, code.value.trim()); ElMessage.success('已关闭双重验证') }
|
||||
else { recovery.value = (await api.rotateMFARecovery(password.value, code.value.trim())).recoveryCodes; ElMessage.success('已更新恢复码,旧恢复码全部作废') }
|
||||
action.value = undefined; password.value = ''; code.value = ''; await load()
|
||||
} catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
function choose(value: 'disable' | 'rotate') { action.value = value; password.value = ''; code.value = ''; error.value = '' }
|
||||
function download() {
|
||||
const blob = new Blob([`VDI Cloud 一次性恢复码\n每条只能使用一次,请离线妥善保存。\n\n${recovery.value.join('\n')}\n`], { type: 'text/plain;charset=utf-8' }), url = URL.createObjectURL(blob), link = document.createElement('a')
|
||||
link.href = url; link.download = 'vdi-cloud-recovery-codes.txt'; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog :model-value="modelValue" title="本人双重验证" width="560px" :close-on-click-modal="false" :close-on-press-escape="!busy && !recovery.length" :show-close="!busy && !recovery.length" @update:model-value="emit('update:modelValue', $event)">
|
||||
<p class="mfa-note">使用身份验证器生成的 6 位动态码,或一次性恢复码完成登录。仅修改本人账号;开启、关闭或更新恢复码会撤销其他登录。</p>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" show-icon />
|
||||
<div v-loading="loading" class="mfa-body">
|
||||
<template v-if="recovery.length">
|
||||
<el-alert type="warning" title="恢复码仅显示这一次,请先保存" :closable="false" show-icon />
|
||||
<p class="mfa-note">身份验证器不可用时,可用密码和一条恢复码登录。每条只能使用一次;关闭此窗口后无法再次查看。</p>
|
||||
<div class="recovery-codes"><code v-for="value in recovery" :key="value">{{ value }}</code></div>
|
||||
<el-button @click="download">下载恢复码</el-button>
|
||||
</template>
|
||||
<template v-else-if="setup">
|
||||
<p class="mfa-note">在身份验证器中手动添加账号:名称为 VDI Cloud,密钥如下,使用基于时间的 6 位验证码(每 30 秒更新)。</p>
|
||||
<div class="mfa-secret" aria-label="身份验证器密钥">{{ setup.secret }}</div>
|
||||
<p class="mfa-note">绑定有效至 {{ new Date(setup.expiresAt).toLocaleTimeString('zh-CN') }}。输入动态码确认后才会启用。</p>
|
||||
<el-form label-position="top" :disabled="busy" @submit.prevent="enable"><el-form-item label="身份验证器动态码"><el-input v-model="code" aria-label="绑定动态码" autocomplete="one-time-code" inputmode="numeric" maxlength="6" /></el-form-item></el-form>
|
||||
<el-button type="primary" :disabled="!/^\d{6}$/.test(code)" :loading="busy" @click="enable">验证并开启</el-button>
|
||||
</template>
|
||||
<template v-else-if="status">
|
||||
<div class="mfa-state"><strong>当前状态</strong><el-tag :type="status.enabled ? 'success' : 'info'">{{ status.enabled ? '已开启' : '未开启' }}</el-tag></div>
|
||||
<p v-if="status.enabled" class="mfa-note">剩余 {{ status.recoveryRemaining }} 条恢复码。同一动态码只能成功使用一次,刚使用后请等待验证器刷新。</p>
|
||||
<div v-if="status.enabled && !action" class="mfa-actions"><el-button @click="choose('rotate')">重新生成恢复码</el-button><el-button type="danger" plain @click="choose('disable')">关闭双重验证</el-button></div>
|
||||
<el-form v-if="!status.enabled || action" label-position="top" :disabled="busy" @submit.prevent="status.enabled ? change() : begin()">
|
||||
<el-form-item label="当前密码"><el-input v-model="password" type="password" show-password autocomplete="current-password" aria-label="双重验证当前密码" maxlength="200" /></el-form-item>
|
||||
<el-form-item v-if="action" label="动态码或恢复码"><el-input v-model="code" autocomplete="one-time-code" aria-label="双重验证确认码" maxlength="80" /></el-form-item>
|
||||
<el-button v-if="!status.enabled" type="primary" :loading="busy" :disabled="!password" @click="begin">开始绑定身份验证器</el-button>
|
||||
<template v-else><el-button type="primary" :loading="busy" :disabled="!password || !code.trim()" @click="change">{{ action === 'disable' ? '确认关闭双重验证' : '生成新恢复码' }}</el-button><el-button :disabled="busy" @click="action = undefined; password = ''; code = ''">返回</el-button></template>
|
||||
</el-form>
|
||||
</template>
|
||||
<el-button v-else-if="error" @click="load">重新加载验证设置</el-button>
|
||||
</div>
|
||||
<template #footer><el-button :disabled="busy" @click="emit('update:modelValue', false)">{{ recovery.length ? '已保存,关闭' : '关闭' }}</el-button></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<style scoped>
|
||||
.mfa-note{font-size:12px;color:var(--vdi-muted);line-height:1.8;margin:14px 0}.mfa-body{min-height:80px;margin-top:18px}.mfa-state{display:flex;justify-content:space-between;align-items:center;margin:18px 0}.mfa-secret{padding:16px;background:var(--vdi-panel-2);border:1px solid var(--vdi-border);border-radius:10px;word-break:break-all;letter-spacing:2px;font-family:monospace;user-select:all}.mfa-actions{display:flex;flex-wrap:wrap;gap:10px;margin:20px 0}.mfa-actions .el-button{margin:0}.recovery-codes{display:grid;gap:10px;margin:18px 0;font-size:12px;overflow-wrap:anywhere}.recovery-codes code{padding:8px 10px;background:var(--vdi-panel-2);border-radius:6px;user-select:all}.mfa-body .el-form{margin-top:20px}
|
||||
</style>
|
||||
@@ -0,0 +1,38 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { api, errorMessage, type PveConnectionInput } from '../api'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
const visible = defineModel<boolean>({ required: true })
|
||||
const form = reactive<PveConnectionInput>({ url: '', tokenId: '', tokenSecret: '', caPem: '', revision: '' })
|
||||
const busy = ref(false), loaded = ref(false), error = ref(''), checked = ref(''), configured = ref(false), source = ref('')
|
||||
watch(visible, async open => {
|
||||
if (!open) return
|
||||
busy.value = true; loaded.value = false; error.value = ''; checked.value = ''
|
||||
try { const value = await api.pveConnection(); Object.assign(form, { url: value.url, tokenId: value.tokenId, caPem: value.caPem, tokenSecret: '', revision: value.revision }); configured.value = value.tokenConfigured; source.value = value.source; loaded.value = true }
|
||||
catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
})
|
||||
const canSubmit = computed(() => loaded.value && !busy.value && !!form.url && !!form.tokenId)
|
||||
watch(form, () => { checked.value = '' })
|
||||
async function check() {
|
||||
busy.value = true; error.value = ''; checked.value = ''
|
||||
try { const result = await api.checkPveConnection({ ...form }); checked.value = `${result.message}:${result.nodes} 个节点、${result.vms} 台 VM` } catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
async function save() {
|
||||
busy.value = true; error.value = ''
|
||||
try {
|
||||
await ElMessageBox.confirm('保存时会再次检查连接,通过后立即生效。首次接入后仅允许维护同一接入地址。', '保存计算平台接入', { confirmButtonText: '确认保存', cancelButtonText: '取消', type: 'warning' })
|
||||
await api.savePveConnection({ ...form }); ElMessage.success('接入配置已保存并生效'); visible.value = false; await usePlatform().refresh()
|
||||
} catch (e) { if (e !== 'cancel' && e !== 'close') error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
function close(done: () => void) { if (!busy.value) done() }
|
||||
</script>
|
||||
<template>
|
||||
<el-dialog v-model="visible" title="Proxmox 接入配置" width="660px" :close-on-click-modal="false" :show-close="!busy" :before-close="close" @closed="form.tokenSecret = ''; form.caPem = ''; loaded = false">
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" class="notice" /><el-alert v-if="checked" type="success" :title="checked" :closable="false" class="notice" />
|
||||
<el-skeleton v-if="busy && !loaded" :rows="6" animated />
|
||||
<el-form v-if="loaded" label-position="top" :disabled="busy"><p class="subtext">当前来源:{{ source === 'database' ? '控制台配置' : '服务端环境' }}。密钥只接收输入,留空可保留同一地址和 Token ID 的原密钥。</p><el-form-item label="HTTPS 接入地址"><el-input v-model="form.url" aria-label="PVE 接入地址" placeholder="https://pve.example.com:8006" maxlength="250" /></el-form-item><el-form-item label="API Token ID"><el-input v-model="form.tokenId" aria-label="PVE Token ID" placeholder="user@pve!token-name" maxlength="200" autocomplete="off" /></el-form-item><el-form-item label="API Token 密钥"><el-input v-model="form.tokenSecret" aria-label="PVE Token 密钥" type="password" :placeholder="configured ? '已配置,留空保留原密钥' : '请输入 Token 密钥'" autocomplete="new-password" maxlength="200" /></el-form-item><el-form-item label="CA 证书(PEM,可留空使用系统信任)"><el-input v-model="form.caPem" aria-label="PVE CA 证书" type="textarea" :rows="5" maxlength="32768" placeholder="-----BEGIN CERTIFICATE-----" /></el-form-item><p class="subtext">始终验证 TLS 证书。保存失败时原配置继续使用;本期更换集群地址需离线迁移。</p></el-form>
|
||||
<template #footer><el-button :disabled="busy" @click="visible = false">取消</el-button><el-button :disabled="!canSubmit" :loading="busy" @click="check">检查连接</el-button><el-button type="primary" :disabled="!canSubmit" :loading="busy" @click="save">保存并生效</el-button></template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<style scoped>.subtext{line-height:1.8;margin:8px 0 18px}.el-form-item{margin-top:20px}</style>
|
||||
@@ -0,0 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { ResourcePoint } from '../api'
|
||||
const props = defineProps<{ points: ResourcePoint[]; metric: 'cpu' | 'memory' | 'storage'; title: string; bucket: number; from: number; to: number }>()
|
||||
const valid = computed(() => props.points.filter(p => p[props.metric] != null))
|
||||
const x = (v: string) => 44 + (new Date(v).getTime() - props.from) / Math.max(1, props.to - props.from) * 590
|
||||
const y = (v: number) => 150 - Math.min(100, Math.max(0, v)) * 1.25
|
||||
const path = computed(() => {
|
||||
let last = 0
|
||||
return props.points.map(p => {
|
||||
const value = p[props.metric], current = new Date(p.time).getTime()
|
||||
if (value == null) { last = 0; return '' }
|
||||
const command = last && current - last <= props.bucket * 1800 ? 'L' : 'M'
|
||||
last = current
|
||||
return `${command}${x(p.time).toFixed(2)},${y(value).toFixed(2)}`
|
||||
}).join(' ')
|
||||
})
|
||||
const stamp = (v: number) => new Date(v).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false })
|
||||
</script>
|
||||
<template>
|
||||
<article class="trend">
|
||||
<div class="trend-heading"><h3>{{ title }}</h3><strong>{{ valid.length ? `${valid[valid.length - 1]![metric]!.toFixed(1)}%` : '暂无采样' }}</strong></div>
|
||||
<svg v-if="valid.length" viewBox="0 0 650 176" role="img" :aria-label="`${title}历史趋势`"><g v-for="v in [0, 50, 100]" :key="v"><line x1="44" x2="634" :y1="y(v)" :y2="y(v)" class="grid" /><text x="4" :y="y(v) + 4">{{ v }}%</text></g><path :d="path" class="series" /><circle v-for="p in valid" :key="p.time" :cx="x(p.time)" :cy="y(p[metric]!)" r="2" class="point"><title>{{ stamp(new Date(p.time).getTime()) }} · {{ p[metric]!.toFixed(1) }}%</title></circle></svg>
|
||||
<div v-else class="empty-trend">此范围暂无有效采样</div><div class="time-axis"><span>{{ stamp(from) }}</span><span>{{ stamp(to) }}</span></div>
|
||||
</article>
|
||||
</template>
|
||||
<style scoped>
|
||||
.trend{border:1px solid var(--vdi-border);border-radius:14px;padding:18px;min-width:0}.trend-heading{display:flex;align-items:center;justify-content:space-between;gap:10px}.trend h3{font-size:13px}.trend strong{font-size:16px;color:var(--vdi-accent)}svg{width:100%;display:block;margin-top:16px;overflow:visible}.grid{stroke:var(--vdi-border);stroke-dasharray:4 4}text{fill:var(--vdi-muted);font-size:10px}.series{stroke:var(--vdi-accent);stroke-width:2;fill:none}.point{fill:var(--vdi-accent)}.time-axis{display:flex;justify-content:space-between;gap:10px;color:var(--vdi-muted);font-size:10px}.empty-trend{height:156px;display:grid;place-items:center;color:var(--vdi-muted);font-size:12px}
|
||||
</style>
|
||||
@@ -0,0 +1,42 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { api, errorMessage, type SessionRecord } from '../api'
|
||||
const rows = ref<SessionRecord[]>([]), total = ref(0), page = ref(1), keyword = ref(''), status = ref(''), days = ref(1), busy = ref(false), error = ref('')
|
||||
const labels: Record<string, string> = { connecting: '连接中', connected: '已连接', ended: '正常结束', interrupted: '连接中断' }
|
||||
const reasons: Record<string, string> = { client_ended: '终端结束', replaced: '新连接替代', heartbeat_timeout: '心跳超时', identity_reset: '设备身份重置' }
|
||||
const time = (v?: string | null) => v ? new Date(v).toLocaleString('zh-CN', { hour12: false }) : '—'
|
||||
function duration(row: SessionRecord) {
|
||||
if (!row.connectedAt) return '未就绪'
|
||||
const seconds = Math.max(0, Math.floor((new Date(row.endedAt || row.lastReportedAt).getTime() - new Date(row.connectedAt).getTime()) / 1000))
|
||||
return `${Math.floor(seconds / 60)} 分 ${seconds % 60} 秒`
|
||||
}
|
||||
async function load(reset = false) {
|
||||
if (busy.value) return
|
||||
if (reset) page.value = 1
|
||||
busy.value = true; error.value = ''
|
||||
try {
|
||||
const to = new Date(), from = new Date(to.getTime() - days.value * 86400000)
|
||||
const result = await api.sessionHistory({ page: page.value, keyword: keyword.value, status: status.value, from: from.toISOString(), to: to.toISOString() })
|
||||
rows.value = result.items; total.value = result.total
|
||||
} catch (e) { error.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
onMounted(() => { void load() })
|
||||
</script>
|
||||
<template>
|
||||
<section class="panel">
|
||||
<div class="panel-heading"><div><h2>会话历史</h2><p class="subtext">保留 90 天。连接时长从画面就绪算起,活动会话统计到最近心跳。</p></div></div>
|
||||
<div class="history-filters"><el-input v-model="keyword" aria-label="搜索历史会话" placeholder="终端、桌面或用户" clearable @keyup.enter="load(true)" /><el-select v-model="status" aria-label="历史会话状态"><el-option label="全部状态" value="" /><el-option v-for="(label, value) in labels" :key="value" :label="label" :value="value" /></el-select><el-select v-model="days" aria-label="历史时间范围"><el-option :value="1" label="最近 24 小时" /><el-option :value="7" label="最近 7 天" /><el-option :value="30" label="最近 30 天" /><el-option :value="90" label="最近 90 天" /></el-select><el-button :loading="busy" @click="load(true)">查询历史</el-button></div>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" class="notice" />
|
||||
<el-table v-loading="busy" :data="rows" empty-text="所选时间范围内没有会话记录">
|
||||
<el-table-column label="终端 / 用户" min-width="170"><template #default="{ row }"><strong>{{ row.terminalName }}</strong><div class="subtext">{{ row.displayName || row.username || '未关联用户' }}</div></template></el-table-column>
|
||||
<el-table-column prop="desktopName" label="桌面" min-width="150" /><el-table-column label="状态" width="120"><template #default="{ row }"><el-tag :type="row.state === 'connected' ? 'success' : row.state === 'interrupted' ? 'danger' : 'info'">{{ labels[row.state] }}</el-tag></template></el-table-column>
|
||||
<el-table-column label="开始 / 就绪" min-width="185"><template #default="{ row }"><div>{{ time(row.reservedAt) }}</div><div class="subtext">就绪 {{ time(row.connectedAt) }}</div><div v-if="row.source === 'observed'" class="subtext">从首次观测开始记录</div></template></el-table-column>
|
||||
<el-table-column label="结束 / 原因" min-width="185"><template #default="{ row }"><div>{{ time(row.endedAt) }}</div><div class="subtext">{{ reasons[row.endReason] || (row.endedAt ? row.endReason : '会话进行中') }}</div></template></el-table-column>
|
||||
<el-table-column label="连接时长" min-width="125"><template #default="{ row }">{{ duration(row) }}</template></el-table-column>
|
||||
</el-table><el-pagination v-model:current-page="page" :page-size="20" :total="total" layout="prev, pager, next, total" @current-change="load()" />
|
||||
</section>
|
||||
</template>
|
||||
<style scoped>
|
||||
.history-filters{display:flex;gap:12px;flex-wrap:wrap;margin:20px 0}.history-filters .el-input{width:240px}.history-filters .el-select{width:160px}.el-pagination{margin-top:20px;flex-wrap:wrap}.subtext{line-height:1.7}
|
||||
@media(max-width:600px){.history-filters>*{flex:1;min-width:130px}.history-filters .el-input{width:100%;flex-basis:100%}}
|
||||
</style>
|
||||
@@ -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,94 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { api, errorMessage, type Task, type TaskQuery } from '../api'
|
||||
import { auditActionLabels as labels } from '../api/audit-labels'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import StatusTag from './StatusTag.vue'
|
||||
const data = usePlatform(), auth = useAuth(), { busy, run, confirm } = useAction()
|
||||
const confirmingGPU = ref(false)
|
||||
const rows = ref<Task[]>([]), total = ref(0), page = ref(1), loading = ref(false), loaded = ref(false), error = ref(''), exporting = ref(false), selected = ref<Task | null>(null)
|
||||
const keyword = ref(''), actor = ref(''), status = ref(''), action = ref(''), kind = ref(''), range = ref<[Date, Date] | null>(null), applied = ref<TaskQuery>({})
|
||||
const statuses: Record<string, string> = { queued: '排队中', running: '执行中', success: '成功', failed: '失败', timeout: '结果未确认' }
|
||||
const kinds: Record<string, string> = { desktop: '桌面电源', terminal: '终端命令', provision: '克隆发放', hardware: '规格调整', snapshot: '快照', 'batch-desktop': '批量电源子任务', 'gpu-prepare': '显卡桌面准备', resource: '资源同步' }
|
||||
const shortcuts = [1, 7, 30, 90].map(days => ({ text: days === 1 ? '最近 24 小时' : `最近 ${days} 天`, value: () => { const end = new Date(); return [new Date(end.getTime() - days * 86400000), end] } }))
|
||||
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||||
let generation = 0
|
||||
onBeforeUnmount(() => { generation++ })
|
||||
async function load(reset = false, background = false) {
|
||||
if (reset) {
|
||||
if (range.value && range.value[1] <= range.value[0]) { ElMessage.warning('结束时间必须晚于开始时间'); return }
|
||||
applied.value = { keyword: keyword.value, actor: actor.value, status: status.value, action: action.value, kind: kind.value, from: range.value?.[0].toISOString(), to: range.value?.[1].toISOString() || new Date().toISOString() }
|
||||
page.value = 1
|
||||
}
|
||||
const request = ++generation
|
||||
if (!background) { loading.value = true; rows.value = []; loaded.value = false }
|
||||
error.value = ''
|
||||
try {
|
||||
const response = await api.taskHistory({ ...applied.value, page: page.value, pageSize: 20 })
|
||||
if (request !== generation) return
|
||||
rows.value = response.items; total.value = response.total; loaded.value = true
|
||||
const current = rows.value.find(task => task.id === selected.value?.id)
|
||||
if (current) selected.value = current
|
||||
} catch (e) { if (request === generation) { error.value = errorMessage(e); rows.value = []; total.value = 0; loaded.value = false } }
|
||||
finally { if (request === generation) loading.value = false }
|
||||
}
|
||||
watch(() => data.updatedAt, () => { if (!loading.value) void load(false, true) })
|
||||
function clear() { keyword.value = ''; actor.value = ''; status.value = ''; action.value = ''; kind.value = ''; range.value = null; void load(true) }
|
||||
async function reconcile(work: () => Promise<unknown>, message: string) { if (await run(work, message)) { selected.value = null; await load() } }
|
||||
async function reconcileGPU() {
|
||||
const task = selected.value
|
||||
if (!task || task.kind !== 'gpu-prepare' || task.status !== 'timeout' || !auth.canOperate || busy.value || confirmingGPU.value) return
|
||||
confirmingGPU.value = true
|
||||
try {
|
||||
if (!await confirm(`核对显卡准备结果 · ${task.targetName}`, '只查询原 PVE 任务及组内桌面的实际电源状态,不重发电源操作。核对完成会结束此未确认流程并释放预留;原任务标记为失败,需要重新准备时请另行操作。')) return
|
||||
await reconcile(() => api.reconcileGPUPrepare(task.id), '已核对原任务并结束未确认流程,未重发电源操作')
|
||||
} finally { confirmingGPU.value = false }
|
||||
}
|
||||
async function downloadDiagnostics(id: string) {
|
||||
try {
|
||||
const diagnostic = await api.taskDiagnostics(id), 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(); setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
} catch (e) { ElMessage.error(errorMessage(e)) }
|
||||
}
|
||||
async function download() {
|
||||
exporting.value = true
|
||||
try {
|
||||
const blob = await api.exportTasks(applied.value), url = URL.createObjectURL(blob), link = document.createElement('a')
|
||||
link.href = url; link.download = `执行任务-${new Date().toISOString().slice(0, 10)}.csv`; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
ElMessage.success('已生成筛选任务的 CSV 文件')
|
||||
} catch (e) { ElMessage.error(errorMessage(e)) } finally { exporting.value = false }
|
||||
}
|
||||
onMounted(() => { void load(true) })
|
||||
</script>
|
||||
<template>
|
||||
<div class="task-filters">
|
||||
<el-input v-model="keyword" aria-label="搜索任务" placeholder="目标 / 任务标识 / 执行结果" maxlength="200" clearable @keyup.enter="load(true)" />
|
||||
<el-input v-model="actor" aria-label="任务操作者" placeholder="操作者包含" maxlength="200" clearable @keyup.enter="load(true)" />
|
||||
<el-select v-model="status" aria-label="任务状态筛选" placeholder="全部任务状态" clearable><el-option v-for="(label, value) in statuses" :key="value" :label="label" :value="value" /></el-select>
|
||||
<el-select v-model="action" aria-label="任务动作" placeholder="全部动作" filterable allow-create clearable><el-option v-for="(label, value) in labels" :key="value" :label="label" :value="value" /></el-select>
|
||||
<el-select v-model="kind" aria-label="任务类型" placeholder="全部类型" filterable allow-create clearable><el-option v-for="(label, value) in kinds" :key="value" :label="label" :value="value" /></el-select>
|
||||
<el-date-picker v-model="range" type="datetimerange" aria-label="任务时间范围" start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts" format="YYYY-MM-DD HH:mm:ss" />
|
||||
<div class="task-actions"><el-button type="primary" :loading="loading" @click="load(true)">查询任务</el-button><el-button :disabled="loading" @click="clear">重置</el-button><el-button :loading="exporting" :disabled="loading || !loaded || !total || total > 10000" @click="download">导出任务 CSV</el-button></div>
|
||||
</div>
|
||||
<p class="subtext task-hint">不选时间可查全部历史;按提交时间筛选。任务状态随平台刷新,新增任务请重新查询。导出包含全部匹配页,单次最多 10000 条,时间为 UTC。</p>
|
||||
<p v-if="loaded && applied.to" class="subtext task-hint">查询范围截至 {{ time(applied.to) }},修改条件后点击“查询任务”。</p>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" show-icon />
|
||||
<el-alert v-if="loaded && total > 10000" type="warning" title="匹配任务超过 10000 条,请缩小时间范围或增加筛选条件后导出。" :closable="false" show-icon />
|
||||
<el-table v-loading="loading" :data="rows" empty-text="没有匹配的执行任务">
|
||||
<el-table-column label="操作目标 / 任务" min-width="220"><template #default="{ row }"><el-button link type="primary" @click="selected = row">{{ row.targetName }}</el-button><div class="mono secondary">{{ row.id }}</div></template></el-table-column>
|
||||
<el-table-column label="操作 / 类型" min-width="150"><template #default="{ row }">{{ labels[row.action] || row.action }}<div class="secondary">{{ kinds[row.kind] || row.kind }}</div></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="120" />
|
||||
<el-table-column label="提交 / 更新时间" min-width="185"><template #default="{ row }">{{ time(row.createdAt) }}<div class="secondary">{{ time(row.updatedAt) }}</div></template></el-table-column>
|
||||
<el-table-column prop="message" label="执行结果" min-width="240" show-overflow-tooltip />
|
||||
</el-table>
|
||||
<el-pagination v-model:current-page="page" :disabled="loading" :total="total" :page-size="20" layout="total, prev, pager, next" @current-change="load()" />
|
||||
<el-drawer :model-value="!!selected" title="任务详情" size="580px" @close="selected = null"><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><el-button v-if="selected?.kind === 'provision' && selected.status === 'timeout' && selected.providerRef && auth.canAdmin" :loading="busy" style="margin-top:20px" @click="reconcile(() => api.reconcileProvision(selected!.id), '已提交核对,只查询原 PVE 任务')">核对克隆结果</el-button><el-button v-if="selected?.kind === 'hardware' && selected.status === 'timeout' && auth.canAdmin" :loading="busy" style="margin-top:20px" @click="reconcile(() => api.reconcileHardware(selected!.id), '已核对实际规格,未重发修改')">核对规格结果</el-button><el-button v-if="selected?.kind === 'snapshot' && selected.status === 'timeout' && auth.canAdmin" :loading="busy" style="margin-top:20px" @click="reconcile(() => api.reconcileSnapshot(selected!.id), '已核对原快照任务,未重发修改')">核对快照结果</el-button><el-button v-if="selected?.kind === 'batch-desktop' && selected.status === 'timeout' && auth.canOperate" :loading="busy" style="margin-top:20px" @click="reconcile(() => api.reconcileBatchPower(selected!.id), '已核对原电源任务,未重发操作')">核对电源结果</el-button><el-button v-if="selected?.kind === 'gpu-prepare' && selected.status === 'timeout' && auth.canOperate" :loading="busy" :disabled="confirmingGPU" style="margin-top:20px" @click="reconcileGPU">核对显卡准备结果</el-button><p v-if="selected && auth.canOperate && ['terminal', 'desktop', 'gpu-prepare', 'batch-desktop', 'hardware', 'snapshot', 'provision'].includes(selected.kind)" style="margin-top:20px"><router-link :to="{ path: '/diagnostics', query: { targetType: selected.kind === 'terminal' ? 'terminal' : 'desktop', targetId: selected.targetId } }">查看操作对象关联诊断 →</router-link></p><p class="subtext" style="margin-top:22px">结果未确认时先核对实际设备状态,再决定是否重新提交。系统不会自动重放操作。</p></el-drawer>
|
||||
</template>
|
||||
<style scoped>
|
||||
.task-filters{display:flex;flex-wrap:wrap;gap:12px;margin:18px 0}.task-filters>.el-input{width:220px}.task-filters>.el-select{width:180px}.task-filters :deep(.el-date-editor){width:390px;flex-grow:0;max-width:100%;box-sizing:border-box}.task-actions{display:flex;gap:10px;flex-wrap:wrap}.task-actions .el-button{margin:0}.task-hint{line-height:1.7;margin:10px 0}.el-alert{margin:12px 0}.el-pagination{margin-top:20px;flex-wrap:wrap}.mono{font-size:11px;overflow-wrap:anywhere;margin-top:4px}
|
||||
@media(max-width:600px){.task-filters>.el-input,.task-filters>.el-select{width:100%}.task-filters :deep(.el-date-editor){width:100%;min-width:0}.task-actions{width:100%}.task-actions .el-button:last-child{width:100%}}
|
||||
</style>
|
||||
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { TerminalMetricPoint } from '../api'
|
||||
const props = defineProps<{ points: TerminalMetricPoint[]; metric: 'cpuPercent' | 'memoryPercent' | 'socTemperatureC'; title: string; unit: string; bucket: number; from: number; to: number }>()
|
||||
const valid = computed(() => props.points.filter(p => p[props.metric] != null))
|
||||
const bounds = computed(() => props.metric === 'socTemperatureC' ? { min: -40, max: 150 } : { min: 0, max: 100 })
|
||||
const x = (v: string) => 44 + Math.max(0, Math.min(1, (new Date(v).getTime() - props.from) / Math.max(1, props.to - props.from))) * 590
|
||||
const y = (v: number) => 150 - (v - bounds.value.min) / (bounds.value.max - bounds.value.min) * 125
|
||||
const path = computed(() => {
|
||||
let last = 0
|
||||
return props.points.map(p => {
|
||||
const value = p[props.metric], current = new Date(p.time).getTime()
|
||||
if (value == null) { last = 0; return '' }
|
||||
const command = last && current - last <= props.bucket * 1500 ? 'L' : 'M'
|
||||
last = current
|
||||
return `${command}${x(p.time).toFixed(2)},${y(value).toFixed(2)}`
|
||||
}).join(' ')
|
||||
})
|
||||
const ticks = computed(() => [bounds.value.min, (bounds.value.min + bounds.value.max) / 2, bounds.value.max])
|
||||
const stamp = (v: number) => new Date(v).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false })
|
||||
</script>
|
||||
<template>
|
||||
<article class="metric-trend">
|
||||
<h4>{{ title }}</h4>
|
||||
<svg v-if="valid.length" viewBox="0 0 650 176" role="img" :aria-label="`${title}历史趋势`"><g v-for="v in ticks" :key="v"><line x1="44" x2="634" :y1="y(v)" :y2="y(v)" class="grid" /><text x="1" :y="y(v) + 4">{{ v }}{{ unit }}</text></g><path :d="path" class="series" /><circle v-for="p in valid" :key="p.time" :cx="x(p.time)" :cy="y(p[metric]!)" r="2" class="point"><title>{{ stamp(new Date(p.time).getTime()) }} · {{ p[metric]!.toFixed(1) }}{{ unit }}</title></circle></svg>
|
||||
<div v-else class="empty-trend">此范围暂无有效采样</div>
|
||||
<div class="time-axis"><span>{{ stamp(from) }}</span><span>{{ stamp(to) }}</span></div>
|
||||
</article>
|
||||
</template>
|
||||
<style scoped>
|
||||
.metric-trend{border:1px solid var(--vdi-border);border-radius:12px;padding:14px;min-width:0;margin-top:12px}h4{font-size:13px}svg{width:100%;display:block;margin-top:12px}.grid{stroke:var(--vdi-border);stroke-dasharray:4 4}text{fill:var(--vdi-muted);font-size:10px}.series{stroke:var(--vdi-accent);stroke-width:2;fill:none}.point{fill:var(--vdi-accent)}.time-axis{display:flex;justify-content:space-between;gap:10px;color:var(--vdi-muted);font-size:10px}.empty-trend{height:100px;display:grid;place-items:center;color:var(--vdi-muted);font-size:12px}
|
||||
</style>
|
||||
@@ -0,0 +1,55 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, onBeforeUnmount, computed } from 'vue'
|
||||
import { api, type TerminalMetrics } from '../api'
|
||||
import TerminalMetricTrend from './TerminalMetricTrend.vue'
|
||||
const props = defineProps<{ terminalId: string }>()
|
||||
const hours = ref(1), loading = ref(false), error = ref(''), result = ref<TerminalMetrics>()
|
||||
let generation = 0
|
||||
async function load() {
|
||||
const request = ++generation, id = props.terminalId, to = new Date(), from = new Date(to.getTime() - hours.value * 3600000)
|
||||
loading.value = true; error.value = ''; result.value = undefined
|
||||
try {
|
||||
const response = await api.terminalMetrics(id, from.toISOString(), to.toISOString())
|
||||
if (request === generation) result.value = response
|
||||
} catch (e) { if (request === generation) error.value = e instanceof Error ? e.message : '指标读取失败' }
|
||||
finally { if (request === generation) loading.value = false }
|
||||
}
|
||||
watch(() => [props.terminalId, hours.value], load, { immediate: true })
|
||||
const timer = window.setInterval(() => { if (!loading.value) void load() }, 30000)
|
||||
onBeforeUnmount(() => { generation++; window.clearInterval(timer) })
|
||||
const state = computed(() => {
|
||||
if (!result.value) return ''
|
||||
const latest = result.value.latest
|
||||
if (!latest.supported) return '设备尚未上报系统指标,请更新 Agent'
|
||||
if (!latest.fresh) return '设备离线或采样已过期,当前数值已隐藏;历史仍可查看'
|
||||
return '系统指标已接入 · 每 30 秒刷新'
|
||||
})
|
||||
const value = (n: number | null, unit: string) => n == null || !result.value?.latest.fresh ? '未采集' : `${n.toFixed(1)} ${unit}`
|
||||
const uptime = computed(() => {
|
||||
const n = result.value?.latest.uptimeSeconds
|
||||
if (n == null || !result.value?.latest.fresh) return '未采集'
|
||||
return `${Math.floor(n / 86400)} 天 ${Math.floor(n % 86400 / 3600)} 小时 ${Math.floor(n % 3600 / 60)} 分钟`
|
||||
})
|
||||
</script>
|
||||
<template>
|
||||
<section class="terminal-metrics" aria-label="终端运行指标">
|
||||
<div class="metric-toolbar"><h3>运行指标</h3><el-select v-model="hours" aria-label="终端指标时间范围" style="width:130px"><el-option label="最近 1 小时" :value="1" /><el-option label="最近 24 小时" :value="24" /><el-option label="最近 7 天" :value="168" /></el-select><el-button :loading="loading" @click="load">刷新指标</el-button></div>
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" show-icon />
|
||||
<p v-else-if="loading" class="subtext" role="status">正在读取终端指标…</p>
|
||||
<template v-else-if="result">
|
||||
<p class="subtext metric-state">{{ state }}</p>
|
||||
<div class="metric-values">
|
||||
<div><span>CPU 使用率</span><strong>{{ value(result.latest.cpuPercent, '%') }}</strong></div>
|
||||
<div><span>内存使用率</span><strong>{{ value(result.latest.memoryPercent, '%') }}</strong></div>
|
||||
<div><span>SoC 温度</span><strong>{{ value(result.latest.socTemperatureC, '°C') }}</strong></div>
|
||||
<div><span>设备运行时长</span><strong>{{ uptime }}</strong></div>
|
||||
</div>
|
||||
<p class="subtext metric-note">最近采样:{{ result.latest.sampledAt ? new Date(result.latest.sampledAt).toLocaleString('zh-CN') : '尚无采样' }}。历史保留 {{ result.retentionDays }} 天,曲线为 {{ result.bucketSeconds }} 秒聚合均值;缺失采样断线显示。</p>
|
||||
<TerminalMetricTrend v-for="m in ([{ metric: 'cpuPercent', title: 'CPU 使用率', unit: '%' }, { metric: 'memoryPercent', title: '内存使用率', unit: '%' }, { metric: 'socTemperatureC', title: 'SoC 温度', unit: '°C' }] as const)" :key="m.metric" :points="result.items" :metric="m.metric" :title="m.title" :unit="m.unit" :bucket="result.bucketSeconds" :from="Date.parse(result.from)" :to="Date.parse(result.to)" />
|
||||
</template>
|
||||
<p class="subtext metric-note">内存按 MemAvailable 计算;温度来自 soc-thermal,表示 SoC 温度。串流 FPS/RTT 尚未采集,桌面设置中的目标帧率不作为实测值。</p>
|
||||
</section>
|
||||
</template>
|
||||
<style scoped>
|
||||
.terminal-metrics{margin-top:24px;border-top:1px solid var(--vdi-border);padding-top:20px}.metric-toolbar{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}.metric-toolbar h3{font-size:14px;margin-right:auto}.metric-state{margin:12px 0;line-height:1.7}.metric-values{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.metric-values>div{padding:14px;background:var(--vdi-bg);border:1px solid var(--vdi-border);border-radius:10px;min-width:0}.metric-values span{display:block;font-size:12px;color:var(--vdi-muted);margin-bottom:8px}.metric-values strong{font-size:15px;overflow-wrap:anywhere}.metric-note{font-size:12px;line-height:1.8;margin:14px 0}
|
||||
</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,80 @@
|
||||
<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, Files, Collection, Key, Lock } from '@element-plus/icons-vue'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useEdition, type Edition } from '../stores/edition'
|
||||
import '../common/common.css'
|
||||
import ThemeToggle from '../components/ThemeToggle.vue'
|
||||
import ChangePasswordDialog from '../components/ChangePasswordDialog.vue'
|
||||
import MFADialog from '../components/MFADialog.vue'
|
||||
import brandMark from '../assets/brand-mark.svg'
|
||||
const auth = useAuth(), data = usePlatform(), route = useRoute(), router = useRouter()
|
||||
const edition = useEdition()
|
||||
const commonItems = [
|
||||
{ path: '/workbench', title: '工作台', icon: DataAnalysis, group: 'work' },
|
||||
{ path: '/people', title: '员工与桌面', icon: User, group: 'work' },
|
||||
{ path: '/devices', title: '终端设备', icon: Monitor, group: 'work' },
|
||||
{ path: '/help', title: '问题处理', icon: Connection, group: 'work' },
|
||||
{ path: '/records', title: '操作记录', icon: List, group: 'work' },
|
||||
]
|
||||
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: '/terminal-policies', title: '终端策略', icon: Setting, group: 'manage' },
|
||||
{ path: '/resources', title: '计算资源', icon: Cpu, group: 'manage' },
|
||||
{ path: '/gpus', title: 'GPU 资源', icon: Cpu, group: 'manage' },
|
||||
{ path: '/monitor', title: '监控告警', icon: DataAnalysis, group: 'manage' },
|
||||
{ path: '/templates', title: '镜像模板', icon: Files, group: 'manage' },
|
||||
{ path: '/pools', title: '桌面池', icon: Collection, group: 'manage' },
|
||||
{ path: '/users', title: '员工与授权', icon: User, group: 'work' },
|
||||
{ path: '/tasks', title: '任务与审计', icon: List, group: 'manage' },
|
||||
{ path: '/diagnostics', title: '日志与诊断', icon: Files, group: 'manage' },
|
||||
{ path: '/settings', title: '系统设置', icon: Setting, group: 'manage' },
|
||||
]
|
||||
const navigation = computed(() => edition.mode === 'common' ? commonItems : items)
|
||||
const groups = computed(() => edition.mode === 'common' ? [{ id: 'work', label: '日常管理' }] : [{ id: 'work', label: '云桌面工作台' }, { id: 'manage', label: '资源与管理' }])
|
||||
async function changeEdition(value: Edition) { edition.select(value); await router.push(edition.home) }
|
||||
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)
|
||||
const passwordVisible = ref(false), mfaVisible = 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="edition.home" 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>
|
||||
<div class="edition-switch" role="group" aria-label="控制台版本"><button :class="{ selected: edition.mode === 'common' }" :aria-pressed="edition.mode === 'common'" @click="changeEdition('common')">通用版</button><button :class="{ selected: edition.mode === 'advanced' }" :aria-pressed="edition.mode === 'advanced'" @click="changeEdition('advanced')">高级版</button></div>
|
||||
<nav aria-label="主导航"><template v-for="group in groups" :key="group.id"><div class="nav-label">{{ group.label }}</div><router-link v-for="item in navigation.filter(i => i.group === group.id && (i.path !== '/settings' || auth.canAdmin) && (i.path !== '/diagnostics' || auth.canOperate))" :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><el-button text aria-label="修改密码" title="修改本人密码" @click="passwordVisible = true"><el-icon :size="18"><Key /></el-icon></el-button><el-button text aria-label="双重验证" title="本人双重验证" @click="mfaVisible = true"><el-icon :size="18"><Lock /></el-icon></el-button><el-button v-if="auth.canAdmin && edition.mode === 'common'" text aria-label="系统设置" title="系统设置" @click="router.push('/settings')"><el-icon :size="18"><Setting /></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" /><template v-if="route.path === '/gpus'">GPU 清单按需读取,请手动刷新</template><template v-else>{{ data.updatedAt ? `最近刷新 ${data.updatedAt}` : '等待加载' }}<span class="refresh-note"> · 每 5 秒更新</span></template></span><router-link :to="edition.mode === 'common' ? '/records' : '/tasks'">{{ pending ? `${pending} 个任务等待回执` : (edition.mode === 'common' ? '查看操作记录' : '查看任务与审计') }} <el-icon><ArrowRight /></el-icon></router-link></footer>
|
||||
</div>
|
||||
<ChangePasswordDialog v-model="passwordVisible" />
|
||||
<MFADialog v-model="mfaVisible" />
|
||||
</div>
|
||||
</template>
|
||||
<style scoped>
|
||||
.edition-switch{display:flex;gap:4px;background:var(--vdi-panel-2);padding:4px;border:1px solid var(--vdi-border);border-radius:10px}.edition-switch button{flex:1;min-height:34px;border:0;border-radius:7px;color:var(--vdi-muted);background:transparent;cursor:pointer;font:inherit;font-size:12px}.edition-switch button.selected{color:var(--vdi-accent);background:var(--vdi-accent-soft);font-weight:650}
|
||||
|
||||
.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,42 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { useEdition } from '../stores/edition'
|
||||
|
||||
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: '', component: () => import('../views/CommonWorkbench.vue') },
|
||||
{ path: 'workbench', component: () => import('../views/CommonWorkbench.vue'), meta: { title: '工作台', edition: 'common' } },
|
||||
{ path: 'people', component: () => import('../views/CommonPeople.vue'), meta: { title: '员工与桌面', edition: 'common' } },
|
||||
{ path: 'devices', component: () => import('../views/CommonDevices.vue'), meta: { title: '终端设备', edition: 'common' } },
|
||||
{ path: 'help', component: () => import('../views/CommonHelp.vue'), meta: { title: '问题处理', edition: 'common' } },
|
||||
{ path: 'records', component: () => import('../views/CommonRecords.vue'), meta: { title: '操作记录', edition: 'common' } },
|
||||
{ path: 'overview', component: () => import('../views/Overview.vue'), meta: { title: '总览' } },
|
||||
{ path: 'resources', component: () => import('../views/Resources.vue'), meta: { title: '计算资源' } },
|
||||
{ path: 'gpus', component: () => import('../views/GPUs.vue'), meta: { title: 'GPU 资源' } },
|
||||
{ path: 'monitor', component: () => import('../views/Monitor.vue'), meta: { title: '监控告警' } },
|
||||
{ path: 'desktops', component: () => import('../views/Desktops.vue'), meta: { title: '桌面管理' } },
|
||||
{ path: 'templates', component: () => import('../views/Templates.vue'), meta: { title: '镜像模板' } },
|
||||
{ path: 'pools', component: () => import('../views/Pools.vue'), meta: { title: '桌面池' } },
|
||||
{ path: 'sessions', component: () => import('../views/Sessions.vue'), meta: { title: '远程会话' } },
|
||||
{ path: 'terminals', component: () => import('../views/Terminals.vue'), meta: { title: '终端管理' } },
|
||||
{ path: 'terminal-policies', component: () => import('../views/TerminalPolicies.vue'), meta: { title: '终端策略' } },
|
||||
{ path: 'users', component: () => import('../views/Users.vue'), meta: { title: '员工与授权' } },
|
||||
{ path: 'tasks', component: () => import('../views/Tasks.vue'), meta: { title: '任务与审计' } },
|
||||
{ path: 'diagnostics', component: () => import('../views/Diagnostics.vue'), meta: { title: '日志与诊断', operateOnly: true } },
|
||||
{ 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 === '/' && auth.user) return useEdition().home
|
||||
if (to.path === '/login' && auth.user) return useEdition().home
|
||||
if (to.meta.adminOnly && !auth.canAdmin) return '/forbidden'
|
||||
if (to.meta.operateOnly && !auth.canOperate) return '/forbidden'
|
||||
if (auth.user && !to.meta.public && !['/settings', '/forbidden'].includes(to.path) && to.matched.some(r => r.path === to.path && !r.path.includes(':'))) {
|
||||
useEdition().select(to.meta.edition === 'common' ? 'common' : 'advanced')
|
||||
}
|
||||
})
|
||||
@@ -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, code?: string) {
|
||||
const data = await api.login(username, password, code)
|
||||
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,19 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useAuth } from './auth'
|
||||
|
||||
export type Edition = 'common' | 'advanced'
|
||||
export const useEdition = defineStore('edition', () => {
|
||||
const auth = useAuth(), mode = ref<Edition>('common')
|
||||
const key = () => `vdi.console-mode:${auth.user?.id || ''}`
|
||||
watch(() => auth.user?.id, id => {
|
||||
mode.value = 'common'
|
||||
if (id) { try { if (localStorage.getItem(key()) === 'advanced') mode.value = 'advanced' } catch { /* Storage can be unavailable. */ } }
|
||||
}, { immediate: true, flush: 'sync' })
|
||||
function select(value: Edition) {
|
||||
mode.value = value
|
||||
if (auth.user) { try { localStorage.setItem(key(), value) } catch { /* Navigation still works without persistence. */ } }
|
||||
}
|
||||
const home = computed(() => mode.value === 'common' ? '/workbench' : '/overview')
|
||||
return { mode, home, select }
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { api, allPages, recentAndActiveTasks, errorMessage, type Desktop, type Terminal, type User, type Task, 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[]>([]), 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, r, s, o] = await Promise.all([allPages(api.desktops), allPages(api.terminals), allPages(api.users), recentAndActiveTasks(), api.resources(), api.settings(), api.overview()])
|
||||
if (startedGeneration !== generation) return
|
||||
desktops.value = d; terminals.value = t; users.value = u; tasks.value = k; 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 = []; resources.value = []; settings.value = null; overview.value = null; error.value = ''; updatedAt.value = '' }
|
||||
return { desktops, terminals, users, tasks, 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,24 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref } 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 search = ref(''), page = ref(1), creating = ref(false), secret = ref(''), activationSN = ref('')
|
||||
const form = reactive({ name: '', sn: '' })
|
||||
const filtered = computed(() => data.terminals.filter(t => `${t.name} ${t.sn}`.toLowerCase().includes(search.value.toLowerCase())))
|
||||
const rows = computed(() => filtered.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
async function enroll() {
|
||||
if (!auth.canAdmin || !form.name.trim() || !form.sn.trim()) return
|
||||
if (await run(async () => { const result = await api.enroll({ name: form.name.trim(), sn: form.sn.trim(), group: '' }); secret.value = result.activationSecret; activationSN.value = form.sn.trim() }, '设备已登记,请在盒子上完成激活')) { creating.value = false; form.name = ''; form.sn = '' }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>终端设备</h1><p class="subtext">查看盒子是否在线,以及当前使用人</p></div><el-button v-if="auth.canAdmin" type="primary" @click="creating = true">登记新设备</el-button></div>
|
||||
<section class="panel"><div class="toolbar"><el-input v-model="search" aria-label="查找设备" placeholder="设备名称或机身 SN" clearable @input="page = 1" /></div><el-table :data="rows" empty-text="暂无设备,请登记新设备"><el-table-column label="设备" min-width="180"><template #default="{ row }">{{ row.name }}<div class="secondary">{{ row.sn }}</div></template></el-table-column><el-table-column label="在线状态" min-width="105"><template #default="{ row }"><StatusTag :value="row.status" /></template></el-table-column><el-table-column label="使用人" min-width="135"><template #default="{ row }">{{ data.users.find(u => u.terminalId === row.id)?.displayName || '尚未关联' }}</template></el-table-column><el-table-column label="当前桌面" min-width="150"><template #default="{ row }">{{ data.desktops.find(d => d.id === row.sessionDesktopId)?.name || '无活动连接' }}</template></el-table-column><el-table-column label="操作" width="100"><template #default="{ row }"><router-link :to="{ path: '/help', query: { terminal: row.id } }">检查问题</router-link></template></el-table-column></el-table><el-pagination v-model:current-page="page" :total="filtered.length" :page-size="10" layout="prev, pager, next" /></section>
|
||||
<p class="subtext">登记后需要在设备上填写激活信息。设备关联、远程重启、收集日志和策略下发位于高级版。</p>
|
||||
<el-dialog v-model="creating" title="登记新设备" width="480px" :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy"><el-form label-position="top" :disabled="busy" @submit.prevent="enroll"><el-form-item label="设备名称" required><el-input v-model="form.name" aria-label="新设备名称" maxlength="80" /></el-form-item><el-form-item label="机身 SN" required><el-input v-model="form.sn" aria-label="新设备 SN" maxlength="100" /></el-form-item></el-form><template #footer><el-button :disabled="busy" @click="creating = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!form.name.trim() || !form.sn.trim()" @click="enroll">登记并获取激活信息</el-button></template></el-dialog>
|
||||
<el-dialog :model-value="!!secret" title="请保存设备激活信息" width="500px" :close-on-click-modal="false" @close="secret = ''"><p>设备 SN:{{ activationSN }}</p><p class="subtext">激活密钥仅显示这一次,请由设备管理员填入盒子配置。</p><el-input :model-value="secret" readonly type="password" show-password aria-label="设备激活密钥" /><template #footer><el-button type="primary" @click="secret = ''">已保存,关闭</el-button></template></el-dialog>
|
||||
</template>
|
||||
@@ -0,0 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { api, errorMessage, type AlertRecord } from '../api'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { diagnoseTerminal } from '../common/diagnosis'
|
||||
const data = usePlatform(), route = useRoute(), selected = ref(''), alerts = ref<AlertRecord[]>([]), total = ref(0), loading = ref(false), error = ref('')
|
||||
watch(() => route.query.terminal, id => { selected.value = typeof id === 'string' ? id : '' }, { immediate: true })
|
||||
const terminal = computed(() => data.terminals.find(t => t.id === selected.value))
|
||||
const checks = computed(() => terminal.value ? diagnoseTerminal(terminal.value, data.users, data.desktops) : [])
|
||||
async function load() {
|
||||
if (loading.value) return
|
||||
loading.value = true; error.value = ''
|
||||
try { const result = await api.alerts(1, 'firing'); alerts.value = result.items; total.value = result.total }
|
||||
catch (e) { error.value = errorMessage(e); alerts.value = [] }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
onMounted(load)
|
||||
watch(() => data.updatedAt, load)
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>问题处理</h1><p class="subtext">先找原因,再决定下一步;检查过程不会修改设备</p></div></div>
|
||||
<section class="panel simple-section"><h2>盒子为什么没有桌面?</h2><el-select v-model="selected" aria-label="选择要检查的设备" placeholder="选择设备" filterable clearable><el-option v-for="t in data.terminals" :key="t.id" :value="t.id" :label="`${t.name} / ${t.sn}`" /></el-select><p v-if="!selected" class="subtext">选择后检查在线状态、员工关联与桌面条件。</p><el-alert v-else-if="!terminal" title="该设备已不存在,请重新选择" type="warning" :closable="false" /><div v-for="(check, i) in checks" :key="i" class="simple-check"><el-tag :type="check.ok ? 'success' : 'warning'">{{ check.ok ? '已通过' : '需处理' }}</el-tag><div><strong>{{ check.title }}</strong><p>{{ check.detail }}</p></div></div><p v-if="terminal" class="subtext">检查依据为最近一次成功刷新;平台数据刷新失败时请先重新加载。全部通过仍不能替代实际连接验收。</p></section>
|
||||
<section class="panel simple-section"><div class="simple-row"><h2>当前告警</h2><el-button :loading="loading" @click="load">刷新告警</el-button></div><el-alert v-if="error" type="error" :closable="false" :title="error" /><el-empty v-else-if="!loading && !alerts.length" description="当前没有触发中的告警" :image-size="64" /><div v-for="alert in alerts" :key="alert.id" class="simple-check"><el-tag type="warning">需关注</el-tag><div><strong>{{ alert.targetName }} · {{ alert.ruleName }}</strong><p>{{ new Date(alert.openedAt).toLocaleString('zh-CN') }} 开始 · {{ alert.acknowledgedAt ? '已有人关注' : '尚未确认' }}</p></div></div><p class="subtext">{{ error ? '告警读取失败,不能判断是否正常。' : `当前 ${total} 条,展示前 20 条。` }}历史、阈值调整和确认操作请进入高级版的监控告警。</p></section>
|
||||
</template>
|
||||
@@ -0,0 +1,63 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
import { api, type User, type Desktop, type DesktopAction } from '../api'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
const data = usePlatform(), auth = useAuth(), { busy, run, confirm } = useAction()
|
||||
const search = ref(''), page = ref(1), creating = ref(false), editing = ref(false), reviewing = ref(false), person = ref<User | null>(null)
|
||||
const profileVisible = ref(false), profileId = ref(''), profileUsername = ref('')
|
||||
const profile = reactive({ displayName: '', enabled: true })
|
||||
const form = reactive({ username: '', displayName: '' }), selected = ref<string[]>([]), action = ref<'grant' | 'revoke'>('grant')
|
||||
const filtered = computed(() => data.users.filter(u => `${u.displayName} ${u.username}`.toLowerCase().includes(search.value.toLowerCase())))
|
||||
const rows = computed(() => filtered.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
const desktopName = (id: string) => data.desktops.find(d => d.id === id)?.name || '已失效的桌面'
|
||||
const choices = computed(() => data.desktops.filter(d => action.value === 'grant' ? !person.value?.desktopIds.includes(d.id) : person.value?.desktopIds.includes(d.id)))
|
||||
const desktopSearch = ref(''), desktopPage = ref(1)
|
||||
const desktops = computed(() => data.desktops.filter(d => d.name.toLowerCase().includes(desktopSearch.value.toLowerCase())))
|
||||
const desktopRows = computed(() => desktops.value.slice((desktopPage.value - 1) * 10, desktopPage.value * 10))
|
||||
const pending = (id: string) => data.tasks.some(t => t.targetId === id && ['queued', 'running', 'timeout'].includes(t.status))
|
||||
async function power(desktop: Desktop, operation: DesktopAction) {
|
||||
if (!auth.canOperate || pending(desktop.id) || busy.value || data.error) return
|
||||
const label = { start: '开机', shutdown: '正常关机', reboot: '重启桌面' }[operation]
|
||||
if (!await confirm(`${label} · ${desktop.name}`, operation === 'start' ? '将提交开机任务,连接服务仍需稍后就绪。' : '会中断该桌面上的使用,请先通知使用人保存文件。')) return
|
||||
if (pending(desktop.id) || data.error) return
|
||||
await run(() => api.desktopAction(desktop.id, operation), '操作已提交,请在操作记录中查看实际结果')
|
||||
}
|
||||
function open(user: User, operation: 'grant' | 'revoke') { person.value = { ...user, desktopIds: [...user.desktopIds] }; action.value = operation; selected.value = []; reviewing.value = false; editing.value = true }
|
||||
async function create() {
|
||||
if (!auth.canAdmin || !form.username.trim() || !form.displayName.trim()) return
|
||||
if (await run(() => api.createUser({ username: form.username.trim(), displayName: form.displayName.trim() }), '员工已添加,请继续分配桌面')) { creating.value = false; form.username = ''; form.displayName = '' }
|
||||
}
|
||||
function editProfile(user: User) {
|
||||
profileId.value = user.id
|
||||
profileUsername.value = user.username
|
||||
Object.assign(profile, { displayName: user.displayName, enabled: user.enabled })
|
||||
profileVisible.value = true
|
||||
}
|
||||
async function saveProfile() {
|
||||
if (!auth.canAdmin || !profile.displayName.trim() || busy.value) return
|
||||
const existing = data.users.find(user => user.id === profileId.value)
|
||||
if (existing?.enabled !== profile.enabled && !await confirm(profile.enabled ? '启用员工' : '停用员工', '状态变更会作废该员工未消费的连接票据。停用会阻止后续连接,但保留桌面授权和已有串流。')) return
|
||||
if (await run(() => api.updateUser(profileId.value, { displayName: profile.displayName.trim(), enabled: profile.enabled }), '员工资料已保存')) profileVisible.value = false
|
||||
}
|
||||
async function save() {
|
||||
if (!auth.canAdmin || !person.value || !selected.value.length || !reviewing.value || busy.value) return
|
||||
const userId = person.value.id, desktopIds = [...selected.value], operation = action.value
|
||||
if (await run(() => api.batchBindings({ userIds: [userId], desktopIds, action: operation }), operation === 'grant' ? '桌面授权已分配' : '指定桌面授权已撤销')) editing.value = false
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>员工与桌面</h1><p class="subtext">给员工分配已有桌面,其他授权自动保留</p></div><el-button v-if="auth.canAdmin" type="primary" @click="creating = true">添加员工</el-button></div>
|
||||
<section class="panel"><div class="toolbar"><el-input v-model="search" aria-label="查找员工" placeholder="输入姓名或账号" clearable @input="page = 1" /></div><el-table :data="rows" empty-text="暂无员工,请先添加员工"><el-table-column label="员工" min-width="150"><template #default="{ row }">{{ row.displayName }}<div class="secondary">{{ row.username }} · {{ row.enabled ? '已启用' : '已停用' }}</div></template></el-table-column><el-table-column label="已分配桌面" min-width="210"><template #default="{ row }"><div v-for="id in row.desktopIds" :key="id">{{ desktopName(id) }} <StatusTag v-if="data.desktops.find(d => d.id === id)" :value="data.desktops.find(d => d.id === id)!.powerState" /></div><span v-if="!row.desktopIds.length" class="secondary">尚未分配</span></template></el-table-column><el-table-column label="使用设备" min-width="145"><template #default="{ row }">{{ data.terminals.find(t => t.id === row.terminalId)?.name || '尚未关联设备' }}</template></el-table-column><el-table-column v-if="auth.canAdmin" label="操作" min-width="270"><template #default="{ row }"><div class="row-actions"><el-button link type="primary" @click="editProfile(row)">编辑资料</el-button><el-button link type="primary" @click="open(row, 'grant')">分配桌面</el-button><el-button link :disabled="!row.desktopIds.length" @click="open(row, 'revoke')">撤销授权</el-button></div></template></el-table-column></el-table><el-pagination v-model:current-page="page" :total="filtered.length" :page-size="10" layout="prev, pager, next" /></section>
|
||||
<section class="panel simple-section"><h2>桌面日常操作</h2><div class="toolbar"><el-input v-model="desktopSearch" aria-label="查找桌面" placeholder="桌面名称" clearable @input="desktopPage = 1" /></div><el-table :data="desktopRows" empty-text="暂无已有桌面,请由运维纳管"><el-table-column prop="name" label="桌面" min-width="150" /><el-table-column label="使用人" min-width="150"><template #default="{ row }">{{ data.users.filter(u => u.desktopIds.includes(row.id)).map(u => u.displayName).join('、') || '尚未分配' }}</template></el-table-column><el-table-column label="状态" min-width="180"><template #default="{ row }"><StatusTag :value="row.powerState" /><div class="secondary">{{ row.setupRequired ? '等待初始化' : row.serviceState === 'ready' ? '连接服务就绪' : '连接服务尚未确认就绪' }}</div><el-tag v-if="pending(row.id)" type="warning" size="small">任务未完成,请先核对</el-tag></template></el-table-column><el-table-column v-if="auth.canOperate" label="操作" min-width="200"><template #default="{ row }"><el-button v-if="row.powerState === 'stopped'" link type="primary" :disabled="busy || pending(row.id) || !!data.error" @click="power(row, 'start')">开机</el-button><template v-if="row.powerState === 'running'"><el-button link :disabled="busy || pending(row.id) || !!data.error" @click="power(row, 'shutdown')">正常关机</el-button><el-button link :disabled="busy || pending(row.id) || !!data.error" @click="power(row, 'reboot')">重启桌面</el-button></template></template></el-table-column></el-table><el-pagination v-model:current-page="desktopPage" :total="desktops.length" :page-size="10" layout="prev, pager, next" /></section>
|
||||
<p class="subtext">分配表示允许后续连接,不会新建桌面或自动开机。关联设备、批量导入和批量授权等集中管理功能可在高级版中完成。</p>
|
||||
<el-dialog v-model="creating" title="添加员工" width="460px" :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy"><el-form label-position="top" :disabled="busy" @submit.prevent="create"><el-form-item label="员工姓名" required><el-input v-model="form.displayName" aria-label="员工姓名" maxlength="80" /></el-form-item><el-form-item label="员工账号" required><el-input v-model="form.username" aria-label="员工账号" maxlength="80" /></el-form-item><p class="subtext">此账号用于关联盒子与桌面授权,桌面系统密码单独管理。</p></el-form><template #footer><el-button :disabled="busy" @click="creating = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!form.displayName.trim() || !form.username.trim()" @click="create">添加员工</el-button></template></el-dialog>
|
||||
<el-dialog v-model="profileVisible" title="编辑员工资料" width="480px" :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy"><el-form label-position="top" :disabled="busy" @submit.prevent="saveProfile"><el-form-item label="员工账号(固定)"><el-input :model-value="profileUsername" disabled readonly /></el-form-item><el-form-item label="姓名" required><el-input v-model="profile.displayName" aria-label="编辑员工姓名" maxlength="80" /></el-form-item><el-form-item label="员工状态"><el-switch v-model="profile.enabled" active-text="启用" inactive-text="停用" aria-label="编辑员工启用状态" /></el-form-item><p class="subtext">员工账号用于授权关系,创建后不能修改;停用会阻止后续连接,但保留已有桌面授权。</p></el-form><template #footer><el-button :disabled="busy" @click="profileVisible = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!profile.displayName.trim()" @click="saveProfile">保存员工资料</el-button></template></el-dialog>
|
||||
<el-dialog v-model="editing" :title="action === 'grant' ? '分配已有桌面' : '撤销指定授权'" width="560px" :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy"><template v-if="person"><h3>{{ person.displayName }} · {{ person.username }}</h3><p v-if="!person.enabled" class="subtext">员工目前已停用,保存授权后仍需管理员启用才能连接。</p><template v-if="!reviewing"><p class="subtext">选择要{{ action === 'grant' ? '分配' : '撤销' }}的桌面:</p><el-checkbox-group v-model="selected" class="simple-checks"><el-checkbox v-for="d in choices" :key="d.id" :value="d.id">{{ d.name }} · {{ d.os }}</el-checkbox></el-checkbox-group><el-empty v-if="!choices.length" description="没有符合条件的桌面" :image-size="64" /></template><div v-else class="simple-plan"><h3>确认变更方案</h3><p>为 {{ person.displayName }} {{ action === 'grant' ? '追加分配' : '撤销以下' }} {{ selected.length }} 台桌面的使用权限:</p><ul><li v-for="id in selected" :key="id">{{ desktopName(id) }}</li></ul><p>其他桌面授权、员工状态和设备关联保持原值。已有串流不会被强制断开。</p></div></template><template #footer><el-button :disabled="busy" @click="reviewing ? reviewing = false : editing = false">{{ reviewing ? '返回修改' : '取消' }}</el-button><el-button v-if="!reviewing" type="primary" :disabled="!selected.length" @click="reviewing = true">查看方案</el-button><el-button v-else type="primary" :loading="busy" @click="save">确认并保存授权</el-button></template></el-dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.row-actions{display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
|
||||
</style>
|
||||
@@ -0,0 +1,27 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { api, errorMessage, type Task, type Audit } from '../api'
|
||||
import { auditActionLabels } from '../api/audit-labels'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
const data = usePlatform(), rows = ref<Task[]>([]), page = ref(1), total = ref(0), loading = ref(false), error = ref(''), search = ref(''), keyword = ref('')
|
||||
const tab = ref('changes'), changes = ref<Audit[]>([])
|
||||
let generation = 0
|
||||
onBeforeUnmount(() => { generation++ })
|
||||
async function load(reset = false) {
|
||||
if (reset) { page.value = 1; keyword.value = search.value }
|
||||
const request = ++generation; loading.value = true; error.value = ''
|
||||
try {
|
||||
const filters = { page: page.value, pageSize: 10, keyword: keyword.value }
|
||||
if (tab.value === 'changes') { const result = await api.audits(filters); if (request === generation) { changes.value = result.items; total.value = result.total } }
|
||||
else { const result = await api.taskHistory(filters); if (request === generation) { rows.value = result.items; total.value = result.total } }
|
||||
}
|
||||
catch (e) { if (request === generation) { error.value = errorMessage(e); rows.value = []; changes.value = []; total.value = 0 } }
|
||||
finally { if (request === generation) loading.value = false }
|
||||
}
|
||||
onMounted(() => load())
|
||||
watch(() => data.updatedAt, () => { void load() })
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>操作记录</h1><p class="subtext">查看员工授权、配置变更与桌面任务结果</p></div></div><section class="panel"><el-tabs v-model="tab" @tab-change="load(true)"><el-tab-pane label="人员与配置变更" name="changes" /><el-tab-pane label="设备与桌面任务" name="tasks" /></el-tabs><div class="toolbar"><el-input v-model="search" aria-label="查找操作记录" placeholder="对象名称或结果" clearable @keyup.enter="load(true)" /><el-button type="primary" :loading="loading" @click="load(true)">查询记录</el-button></div><el-alert v-if="error" type="error" :title="error" :closable="false" /><el-table v-if="tab === 'changes'" v-loading="loading" :data="changes" empty-text="没有匹配的变更记录"><el-table-column prop="target" label="对象" min-width="180" /><el-table-column label="操作" min-width="140"><template #default="{ row }">{{ auditActionLabels[row.action] || row.action }}</template></el-table-column><el-table-column prop="result" label="记录结果" min-width="210" /><el-table-column prop="actor" label="操作人" min-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><el-table v-else v-loading="loading" :data="rows" empty-text="没有匹配的任务"><el-table-column prop="targetName" label="对象" min-width="150" /><el-table-column label="操作" min-width="120"><template #default="{ row }">{{ auditActionLabels[row.action] || row.action }}</template></el-table-column><el-table-column label="结果" min-width="110"><template #default="{ row }"><StatusTag :value="row.status" /></template></el-table-column><el-table-column prop="message" label="说明" min-width="240" /><el-table-column prop="actor" label="操作人" min-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><el-pagination v-model:current-page="page" :disabled="loading" :total="total" :page-size="10" layout="total, prev, pager, next" @current-change="load()" /></section><p class="subtext">结果未确认不代表失败或成功,应由运维核对。更详细的筛选、结果核对和 CSV 导出位于高级版“任务与审计”。</p>
|
||||
</template>
|
||||
@@ -0,0 +1,37 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { api, errorMessage, type AssistantPlanResult } from '../api'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useAction } from '../composables/useAction'
|
||||
const data = usePlatform(), auth = useAuth(), { busy, confirm } = useAction()
|
||||
const running = computed(() => data.desktops.filter(d => d.powerState === 'running').length)
|
||||
const unassigned = computed(() => data.users.filter(u => u.enabled && !u.desktopIds.length).length)
|
||||
const offline = computed(() => data.terminals.filter(t => t.enabled !== false && t.status !== 'disabled' && t.status !== 'online').length)
|
||||
const unresolved = computed(() => data.tasks.filter(t => t.status === 'timeout').length)
|
||||
const request = ref(''), plan = ref<AssistantPlanResult | null>(null), runningPlan = ref(false), executed = ref(false), assistantError = ref('')
|
||||
async function generatePlan() {
|
||||
const text = request.value.trim()
|
||||
if (!text || runningPlan.value) return
|
||||
runningPlan.value = true; assistantError.value = ''; executed.value = false
|
||||
try { plan.value = await api.assistantPlan(text) } catch (e) { assistantError.value = errorMessage(e) }
|
||||
finally { runningPlan.value = false }
|
||||
}
|
||||
function chooseCandidate(candidate: { label: string }) { request.value = `${request.value.trim()} ${candidate.label}`.trim(); void generatePlan() }
|
||||
async function executePlan() {
|
||||
if (!plan.value || plan.value.plan.kind !== 'action' || !auth.canAdmin || busy.value || executed.value) return
|
||||
if (!await confirm('确认执行方案', plan.value.plan.summary)) return
|
||||
try { await api.assistantExecute(plan.value.runId); await data.refresh(); executed.value = true; ElMessage.success('方案已执行,操作已保存') }
|
||||
catch (e) { ElMessage.error(errorMessage(e)); await generatePlan() }
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>工作台</h1><p class="subtext">{{ auth.user?.displayName }},在这里完成日常桌面管理</p></div><el-tag>通用版</el-tag></div>
|
||||
<div class="simple-stats"><section class="panel"><span>运行中的桌面</span><strong>{{ running }}<small> / {{ data.desktops.length }} 台桌面</small></strong></section><section class="panel"><span>在线设备</span><strong>{{ data.terminals.filter(t => t.status === 'online').length }}<small> / {{ data.terminals.length }} 台</small></strong></section><section class="panel"><span>正在使用</span><strong>{{ data.overview?.activeSessions ?? '—' }}<small> 个连接</small></strong></section></div>
|
||||
<section class="panel simple-section assistant-box"><h2>你想完成什么?</h2><p class="subtext">用一句话描述需求,平台会生成可核对的业务方案。执行前会再次检查权限和最新状态。</p><div class="assistant-input"><el-input v-model="request" aria-label="描述需求" placeholder="例如:给张三分配一台办公桌面" clearable @keyup.enter="generatePlan" /><el-button type="primary" :loading="runningPlan" :disabled="!request.trim()" @click="generatePlan">生成方案</el-button></div><el-alert v-if="assistantError" type="error" :title="assistantError" :closable="false" class="notice" /><article v-if="plan" class="assistant-plan" :class="`is-${plan.plan.kind}`"><div><el-tag :type="plan.plan.kind === 'action' ? 'success' : plan.plan.kind === 'blocked' ? 'warning' : 'info'">{{ plan.plan.kind === 'action' ? '可执行方案' : plan.plan.kind === 'route' ? '查询方案' : '需要补充信息' }}</el-tag><h3>{{ plan.plan.title }}</h3><p>{{ plan.plan.summary }}</p><p v-if="plan.plan.reason" class="secondary">原因:{{ plan.plan.reason }}</p></div><div v-if="plan.plan.candidates.length" class="assistant-candidates"><p class="secondary">请选择准确对象:</p><el-button v-for="candidate in plan.plan.candidates" :key="`${candidate.kind}-${candidate.id}`" size="small" @click="chooseCandidate(candidate)">{{ candidate.label }}</el-button></div><div class="assistant-plan-actions"><el-button v-if="plan.plan.kind === 'action'" type="primary" :loading="busy" :disabled="!auth.canAdmin || executed" @click="executePlan">{{ executed ? '已执行' : auth.canAdmin ? '确认并执行' : '当前角色无权执行' }}</el-button><router-link v-else-if="plan.plan.kind === 'route' && plan.plan.path" :to="plan.plan.path"><el-button>打开处理页面</el-button></router-link></div><dl v-if="plan.plan.kind === 'action'"><div><dt>员工</dt><dd>{{ plan.plan.userName }} · {{ plan.plan.userId }}</dd></div><div><dt>桌面</dt><dd>{{ plan.plan.desktopName }} · VM {{ plan.plan.desktopVmid }}</dd></div><div><dt>执行影响</dt><dd>{{ plan.plan.action === 'grant_desktop' ? '只追加授权,不开机、不建机、不终止已有连接' : '只撤销授权,不关机、不终止已有连接' }}</dd></div><div><dt>方案有效期</dt><dd>{{ new Date(plan.expiresAt).toLocaleTimeString('zh-CN') }}</dd></div></dl></article><div class="simple-shortcuts"><router-link to="/people"><strong>员工与桌面 →</strong><span>添加员工,分配或撤销已有桌面</span></router-link><router-link to="/devices"><strong>查看终端设备 →</strong><span>看在线状态,登记新盒子</span></router-link><router-link to="/help"><strong>桌面打不开 →</strong><span>检查设备、使用人和桌面连接条件</span></router-link></div></section>
|
||||
<section class="panel simple-section"><h2>需要关注</h2><div class="simple-issues"><router-link to="/people">{{ unassigned }} 位已启用员工尚未分配桌面 →</router-link><router-link to="/devices">{{ offline }} 台设备离线或等待激活 →</router-link><router-link to="/records">{{ unresolved }} 个任务结果尚未确认 →</router-link></div><p class="subtext">数据来自平台最近刷新。连接服务就绪后,仍需在终端验证实际连接和画面;告警详情见问题处理。</p></section>
|
||||
</template>
|
||||
<style scoped>
|
||||
.assistant-box{border-color:var(--vdi-accent)}.assistant-input{display:flex;gap:10px;margin:18px 0}.assistant-input .el-input{min-width:0}.assistant-plan{margin:18px 0;padding:18px;border:1px solid var(--vdi-border);border-radius:12px;background:var(--vdi-panel-2);display:grid;gap:16px}.assistant-plan.is-grant{border-color:var(--vdi-ok)}.assistant-plan.is-blocked{border-color:var(--vdi-warn)}.assistant-plan h3{font-size:16px;margin:12px 0 8px}.assistant-plan p{line-height:1.8;font-size:13px}.assistant-plan-actions{display:flex;justify-content:flex-end}.assistant-plan dl{display:grid;gap:8px;margin:0;padding-top:14px;border-top:1px solid var(--vdi-border);font-size:12px}.assistant-plan dl>div{display:flex;gap:18px}.assistant-plan dt{color:var(--vdi-muted);min-width:64px}.assistant-plan dd{margin:0}.assistant-box .simple-shortcuts{margin-top:18px}@media(max-width:600px){.assistant-input{align-items:stretch;flex-direction:column}.assistant-plan-actions{justify-content:stretch}.assistant-plan-actions .el-button,.assistant-plan-actions a{width:100%}.assistant-plan-actions .el-button{width:100%}.assistant-plan dl>div{display:block}.assistant-plan dd{margin-top:5px}}
|
||||
</style>
|
||||
@@ -0,0 +1,74 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { Grid, List, Search, Plus, ArrowRight, Monitor } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, errorMessage, type Desktop, type DesktopAction, type DesktopReadiness, type DiscoveredVM, type ImportInput, type ConnectionInput } 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'
|
||||
import DesktopBatchDialog from '../components/DesktopBatchDialog.vue'
|
||||
import DesktopSnapshotsDialog from '../components/DesktopSnapshotsDialog.vue'
|
||||
import DesktopHardwareDialog from '../components/DesktopHardwareDialog.vue'
|
||||
import CloneDesktopDialog from '../components/CloneDesktopDialog.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 batchIds = ref<string[]>([]), batchAction = ref<DesktopAction | 'history'>()
|
||||
watch(() => data.desktops, values => { batchIds.value = batchIds.value.filter(id => values.some(d => d.id === id)) })
|
||||
const hardwareDesktop = ref<Desktop>(), snapshotDesktop = ref<Desktop>()
|
||||
const cloneVisible = ref(false), connectionDesktop = ref<Desktop>()
|
||||
const readiness = ref<DesktopReadiness>(), readinessBusy = ref(false)
|
||||
const connection = reactive<ConnectionInput>({ endpoint: '', width: 2560, height: 1440, fps: 30, initialized: false })
|
||||
function openConnection(d: Desktop) { connectionDesktop.value = d; readiness.value = undefined; Object.assign(connection, { endpoint: d.endpoint, width: d.width, height: d.height, fps: d.fps, initialized: false }) }
|
||||
async function saveConnection() { if (connectionDesktop.value && await run(() => api.configureDesktop(connectionDesktop.value!.id, { ...connection }), '连接配置已保存')) connectionDesktop.value = undefined }
|
||||
async function checkReadiness(d: Desktop) {
|
||||
readinessBusy.value = true
|
||||
try { readiness.value = await api.checkDesktopReadiness(d.id); await data.refresh(); ElMessage.success(readiness.value.ready ? '桌面已满足连接条件' : '检查完成,请按结果处理未通过项') }
|
||||
catch (e) { ElMessage.error(errorMessage(e)) }
|
||||
finally { readinessBusy.value = false }
|
||||
}
|
||||
watch(selectedId, () => { readiness.value = undefined })
|
||||
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 pageSelected = computed(() => !!rows.value.length && rows.value.every(d => batchIds.value.includes(d.id)))
|
||||
function toggleDesktop(id: string) { batchIds.value = batchIds.value.includes(id) ? batchIds.value.filter(value => value !== id) : [...batchIds.value, id].slice(0, 50) }
|
||||
function selectPage() { const pageIds = rows.value.map(d => d.id); batchIds.value = pageSelected.value ? batchIds.value.filter(id => !pageIds.includes(id)) : [...new Set([...batchIds.value, ...pageIds])].slice(0, 50) }
|
||||
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><div v-if="auth.canAdmin"><el-button :disabled="!data.settings?.pveConfigured" @click="cloneVisible = true">从模板创建</el-button><el-button type="primary" :loading="busy" :disabled="!data.settings?.pveConfigured" @click="openImport"><el-icon style="margin-right:7px"><Plus /></el-icon>纳管已有 VM</el-button></div></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="desktop-batch-bar"><template v-if="auth.canOperate"><el-checkbox :model-value="pageSelected" :indeterminate="!pageSelected && rows.some(d => batchIds.includes(d.id))" :disabled="!rows.length || !!batchAction" @change="selectPage">选择本页</el-checkbox><span class="secondary">已选 {{ batchIds.length }} / 50 台(可跨页)</span><el-button :disabled="!batchIds.length" @click="batchIds = []">清空选择</el-button><el-button :disabled="!batchIds.length" @click="batchAction = 'start'">批量开机</el-button><el-button :disabled="!batchIds.length" @click="batchAction = 'shutdown'">批量关机</el-button><el-button :disabled="!batchIds.length" @click="batchAction = 'reboot'">批量重启</el-button></template><el-button @click="batchAction = 'history'">批量记录</el-button></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 === '麒麟' }"><el-checkbox v-if="auth.canOperate" :model-value="batchIds.includes(d.id)" @change="toggleDesktop(d.id)" :aria-label="`选择桌面 ${d.name}`" class="desktop-select" :disabled="batchIds.length >= 50 && !batchIds.includes(d.id)" /><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"><el-tag v-if="d.setupRequired" type="warning" size="small">待初始化</el-tag><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.setupRequired ? '待初始化' : 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 v-if="auth.canOperate" label="选择" width="60"><template #default="{ row }"><el-checkbox :model-value="batchIds.includes(row.id)" @change="toggleDesktop(row.id)" :aria-label="`选择桌面 ${row.name}`" :disabled="batchIds.length >= 50 && !batchIds.includes(row.id)" /></template></el-table-column><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.setupRequired ? '待初始化' : 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><router-link v-if="auth.canOperate" :to="{ path: '/diagnostics', query: { targetType: 'desktop', targetId: selected.id } }">查看此桌面关联诊断 →</router-link><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.setupRequired ? '待初始化,暂不能连接' : 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><div class="readiness-box"><div class="readiness-head"><strong>连接就绪检查</strong><el-tag v-if="readiness" :type="readiness.ready ? 'success' : 'warning'">{{ readiness.ready ? '可连接' : '未就绪' }}</el-tag></div><p v-if="!readiness" class="subtext">检查真实电源状态、桌面地址、初始化确认和 Sunshine serverinfo。</p><ul v-else class="readiness-list"><li v-for="check in readiness.checks" :key="check.name"><el-tag size="small" :type="check.status === 'pass' ? 'success' : check.status === 'unknown' ? 'info' : 'danger'">{{ check.status === 'pass' ? '通过' : check.status === 'unknown' ? '待确认' : '未通过' }}</el-tag><span>{{ check.message }}</span></li></ul><el-button v-if="auth.canOperate" :loading="readinessBusy" @click="checkReadiness(selected)">检测连接就绪</el-button></div><p class="subtext" style="margin:20px 0">从模板创建后需完成系统身份、硬件编码、Sunshine 服务与终端配对,再配置连接地址。关机后可管理快照;公共池自动还原待接入。</p><el-button v-if="auth.canAdmin" style="margin-bottom:18px" @click="openConnection(selected)">配置连接</el-button><el-button v-if="auth.canAdmin && selected.provider === 'proxmox'" style="margin-bottom:18px" :disabled="activeTask(selected)" @click="hardwareDesktop = selected">规格管理</el-button><el-button v-if="selected.provider === 'proxmox'" style="margin-bottom:18px" @click="snapshotDesktop = selected">快照与还原</el-button><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>
|
||||
<DesktopBatchDialog v-model="batchAction" :desktop-ids="batchIds" /><CloneDesktopDialog v-model="cloneVisible" /><DesktopHardwareDialog v-model="hardwareDesktop" /><DesktopSnapshotsDialog v-model="snapshotDesktop" />
|
||||
<el-dialog :model-value="!!connectionDesktop" title="配置桌面连接" width="560px" :close-on-click-modal="false" @close="connectionDesktop = undefined"><el-form label-position="top" :disabled="busy"><el-alert v-if="connectionDesktop?.setupRequired" title="新桌面尚未初始化,完成以下检查后才能向终端签发连接票据。" type="warning" :closable="false" /><el-form-item label="IP 或主机名"><el-input v-model="connection.endpoint" placeholder="例如 192.168.1.200,不含协议和端口" maxlength="253" /></el-form-item><el-form-item label="请求宽度"><el-input-number v-model="connection.width" :min="640" :max="7680" :precision="0" /></el-form-item><el-form-item label="请求高度"><el-input-number v-model="connection.height" :min="480" :max="4320" :precision="0" /></el-form-item><el-form-item label="请求帧率"><el-input-number v-model="connection.fps" :min="10" :max="120" :precision="0" /></el-form-item><el-checkbox v-if="connectionDesktop?.setupRequired" v-model="connection.initialized">已完成系统身份、IP、Sunshine 服务和终端配对</el-checkbox><p class="subtext" style="margin-top:16px">保存会使旧连接票据失效;有活动连接时请先结束会话。</p></el-form><template #footer><el-button :disabled="busy" @click="connectionDesktop = undefined">取消</el-button><el-button type="primary" :loading="busy" :disabled="!connection.endpoint.trim() || (!!connectionDesktop?.setupRequired && !connection.initialized)" @click="saveConnection">保存连接配置</el-button></template></el-dialog>
|
||||
</template>
|
||||
<style scoped>
|
||||
.readiness-box{margin:20px 0;padding:16px;border:1px solid var(--vdi-border);border-radius:12px;background:var(--vdi-panel-2)}.readiness-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.readiness-list{display:grid;gap:9px;margin:14px 0;padding:0;list-style:none}.readiness-list li{display:flex;align-items:flex-start;gap:8px;font-size:12px;color:var(--vdi-muted);line-height:1.5}.readiness-list .el-tag{flex-shrink:0}
|
||||
.desktop-batch-bar{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:0 0 20px;font-size:12px}.desktop-batch-bar .el-button{margin:0}.desktop-select{position:absolute;top:2px;right:8px;z-index:2}.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,102 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, errorMessage, type DiagnosticReport, type DiagnosticQuery, type DiagnosticEvent, type Task, type TerminalLogArchivePage } from '../api'
|
||||
import { auditActionLabels } from '../api/audit-labels'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
const data = usePlatform(), auth = useAuth(), route = useRoute(), { confirm } = useAction()
|
||||
const end = new Date()
|
||||
const form = reactive({ kind: 'terminal' as 'terminal' | 'desktop', id: '', source: '' as NonNullable<DiagnosticQuery['source']>, range: [new Date(end.getTime() - 86400000), end] as [Date, Date] | null })
|
||||
const sources = { tasks: '执行任务', sessions: '桌面会话', alerts: '监控告警', audits: '操作审计', logs: '终端日志' }
|
||||
const lifecycle: Record<string, string> = { 'session-reserved': '开始连接', 'session-connected': '连接已建立', 'session-ended': '连接结束', 'alert-opened': '告警触发', 'alert-resolved': '告警恢复' }
|
||||
const report = ref<DiagnosticReport | null>(null), archives = ref<TerminalLogArchivePage | null>(null), archiveKeyword = ref(''), archiveLoading = ref(false), applied = ref<DiagnosticQuery | null>(null), page = ref(1), loading = ref(false), error = ref(''), exporting = ref(false), collecting = ref(false)
|
||||
const collection = ref<Task | null>(null), collectionTarget = ref('')
|
||||
const currentCollection = computed(() => data.tasks.find(t => t.id === collection.value?.id) || collection.value)
|
||||
const objects = computed(() => form.kind === 'terminal' ? data.terminals.map(t => ({ id: t.id, label: `${t.name} / ${t.sn}` })) : data.desktops.map(d => ({ id: d.id, label: `${d.name} / VM ${d.vmid}` })))
|
||||
const terminal = computed(() => report.value?.subject.kind === 'terminal' ? data.terminals.find(t => t.id === report.value!.subject.id) : undefined)
|
||||
const pending = computed(() => !!terminal.value && data.tasks.some(t => t.kind === 'terminal' && t.targetId === terminal.value!.id && ['queued', 'running', 'timeout'].includes(t.status)))
|
||||
const canCollect = computed(() => auth.canOperate && report.value?.subject.kind === 'terminal' && report.value.subject.state === 'online' && terminal.value?.status === 'online' && terminal.value?.enabled !== false && !data.error && !pending.value)
|
||||
const shortcuts = [1, 24, 168].map(hours => ({ text: hours === 1 ? '最近 1 小时' : hours === 24 ? '最近 24 小时' : '最近 7 天', value: () => { const to = new Date(); return [new Date(to.getTime() - hours * 3600000), to] } }))
|
||||
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
|
||||
let generation = 0, exportGeneration = 0, collectionKey = '', collectionKeyTarget = ''
|
||||
onBeforeUnmount(() => { generation++; exportGeneration++ })
|
||||
watch(() => [form.kind, form.id, form.source, form.range], () => { generation++; exportGeneration++; report.value = null; applied.value = null; error.value = ''; loading.value = false }, { flush: 'sync', deep: true })
|
||||
function changeKind() { form.id = '' }
|
||||
async function load(reset = false) {
|
||||
if (reset) {
|
||||
if (!form.id || !form.range || form.range[1] <= form.range[0] || form.range[1].getTime() - form.range[0].getTime() > 7 * 86400000) { ElMessage.warning('请选择对象和有效时间范围,最长 7 天'); return }
|
||||
applied.value = { targetType: form.kind, targetId: form.id, source: form.source, from: form.range[0].toISOString(), to: form.range[1].toISOString() }; page.value = 1
|
||||
}
|
||||
if (!applied.value) return
|
||||
const version = ++generation, filters = { ...applied.value, page: page.value, pageSize: 20 }
|
||||
loading.value = true; error.value = ''; report.value = null
|
||||
try { const result = await api.diagnostics(filters); if (version === generation) { report.value = result; archives.value = result.subject.kind === 'terminal' ? await api.terminalLogArchives({ terminalId: result.subject.id, from: filters.from, to: filters.to, page: 1, pageSize: 20 }) : null } }
|
||||
catch (e) { if (version === generation) error.value = errorMessage(e) }
|
||||
finally { if (version === generation) loading.value = false }
|
||||
}
|
||||
async function searchArchives() {
|
||||
if (!report.value || report.value.subject.kind !== 'terminal') return
|
||||
archiveLoading.value = true
|
||||
try { archives.value = await api.terminalLogArchives({ terminalId: report.value.subject.id, keyword: archiveKeyword.value || undefined, from: applied.value?.from, to: applied.value?.to, page: 1, pageSize: 20 }) }
|
||||
catch (e) { ElMessage.error(errorMessage(e)) }
|
||||
finally { archiveLoading.value = false }
|
||||
}
|
||||
async function download() {
|
||||
if (!report.value || !applied.value || exporting.value || loading.value) return
|
||||
const filters = { ...applied.value }, version = exportGeneration
|
||||
exporting.value = true
|
||||
try {
|
||||
const blob = await api.exportDiagnostics(filters)
|
||||
if (version !== exportGeneration) return
|
||||
const url = URL.createObjectURL(blob), link = document.createElement('a'); link.href = url; link.download = `vdi-diagnostics-${filters.targetType}-${new Date().toISOString().slice(0, 10)}.zip`; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
ElMessage.success('诊断包已生成,包含当前筛选的全部匹配事件')
|
||||
} catch (e) { if (version === exportGeneration) ElMessage.error(errorMessage(e)) }
|
||||
finally { exporting.value = false }
|
||||
}
|
||||
async function collect() {
|
||||
if (!canCollect.value || collecting.value || !report.value) return
|
||||
const subject = { ...report.value.subject }; collecting.value = true
|
||||
try {
|
||||
if (!await confirm(`收集终端日志 · ${subject.name}`, '将向此设备提交日志采集命令并等待回执。不会重启设备、断开串流或操作桌面电源;提交成功不代表已取得日志。')) return
|
||||
if (!canCollect.value || report.value?.subject.id !== subject.id) return
|
||||
if (!collectionKey || collectionKeyTarget !== subject.id) { collectionKey = crypto.randomUUID(); collectionKeyTarget = subject.id }
|
||||
const task = await api.collectTerminalLogs(subject.id, collectionKey)
|
||||
collection.value = task; collectionTarget.value = subject.id; collectionKey = ''
|
||||
ElMessage.success('日志采集任务已提交,等待设备回执'); await data.refresh()
|
||||
} catch (e) { ElMessage.error(`${errorMessage(e)};请刷新任务核对,重试同一设备时复用本次请求标识。`) }
|
||||
finally { collecting.value = false }
|
||||
}
|
||||
function showCollection() {
|
||||
form.kind = 'terminal'; form.id = collectionTarget.value; form.source = 'logs'; const to = new Date(); form.range = [new Date(to.getTime() - 3600000), to]; void load(true)
|
||||
}
|
||||
function details(event: DiagnosticEvent): Record<string, unknown> { try { return JSON.parse(event.details) } catch { return {} } }
|
||||
function metadata(event: DiagnosticEvent) { const value = { ...details(event) }; delete value.logTail; return JSON.stringify(value, null, 2) }
|
||||
function applyRoute() {
|
||||
const kind = route.query.targetType, id = route.query.targetId
|
||||
if ((kind === 'terminal' || kind === 'desktop') && typeof id === 'string') { form.kind = kind; form.id = id; void load(true) }
|
||||
}
|
||||
onMounted(applyRoute)
|
||||
watch(() => [route.query.targetType, route.query.targetId], applyRoute)
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>日志与诊断</h1><p class="subtext">按设备或桌面关联日志、会话、告警与操作,追查故障经过</p></div><el-button :loading="exporting" :disabled="!report || loading || report.total > 2000" @click="download">导出诊断包</el-button></div>
|
||||
<section class="panel diagnosis-filters"><el-radio-group v-model="form.kind" aria-label="诊断对象类型" @change="changeKind"><el-radio-button value="terminal">终端设备</el-radio-button><el-radio-button value="desktop">云桌面</el-radio-button></el-radio-group><div class="diagnosis-query"><el-select v-model="form.id" aria-label="诊断对象" :placeholder="form.kind === 'terminal' ? '选择设备名称或 SN' : '选择桌面名称或 VMID'" filterable clearable><el-option v-for="object in objects" :key="object.id" :value="object.id" :label="object.label" /></el-select><el-date-picker v-model="form.range" type="datetimerange" aria-label="诊断时间范围" start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts" format="YYYY-MM-DD HH:mm:ss" /><el-select v-model="form.source" aria-label="诊断记录来源" placeholder="全部记录来源" clearable><el-option v-for="(label, key) in sources" :key="key" :value="key" :label="label" /></el-select><el-button type="primary" :loading="loading" :disabled="!form.id" @click="load(true)">查询诊断</el-button></div><p class="subtext">最长查询 7 天。查询和导出使用相同对象、时间及来源;查询不会自动采集日志或修改设备。</p></section>
|
||||
<section v-if="currentCollection" class="panel diagnosis-collection"><strong>本次日志采集 · {{ currentCollection.targetName }}</strong><StatusTag :value="currentCollection.status" /><p>{{ currentCollection.message }}</p><span class="mono secondary">{{ currentCollection.id }}</span><el-button v-if="currentCollection.status === 'success'" link type="primary" @click="showCollection">查看本次采集</el-button><router-link v-else to="/tasks">查看采集任务 →</router-link></section>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" show-icon class="notice" />
|
||||
<section v-if="loading" class="panel diagnosis-empty"><el-skeleton :rows="6" animated /></section>
|
||||
<template v-else-if="report">
|
||||
<section class="panel diagnosis-subject"><div><h2>{{ report.subject.name }}</h2><p class="mono secondary">{{ report.subject.id }}<span v-if="report.subject.node"> · {{ report.subject.node }} / VM {{ report.subject.vmid }}</span></p><p class="secondary">当前快照 {{ time(report.observedAt) }}<span v-if="report.subject.lastSeen"> · 最近心跳 {{ time(report.subject.lastSeen) }}</span></p></div><div class="diagnosis-subject-actions"><StatusTag :value="report.subject.state" /><el-button v-if="report.subject.kind === 'terminal' && auth.canOperate" :loading="collecting" :disabled="!canCollect" @click="collect">收集此设备日志</el-button></div><p v-if="report.subject.kind === 'terminal'" class="diagnosis-footnote">{{ pending ? '该设备有未完成或结果未知的命令,请先到任务中心核对。' : report.subject.state !== 'online' ? '设备当前不在线,恢复在线后再采集新日志。' : '采集需要设备回执;已存在的日志可在下方查看。' }}</p></section>
|
||||
<div class="diagnosis-counts"><div v-for="(label, key) in sources" :key="key" class="panel"><span>{{ label }}</span><strong>{{ report.counts[key] }}</strong></div></div>
|
||||
<section class="panel diagnosis-timeline"><div class="diagnosis-timeline-heading"><div><h2>关联事件</h2><p class="subtext">{{ time(report.from) }} — {{ time(report.to) }} · {{ report.source ? sources[report.source as keyof typeof sources] : '全部来源' }} · 共 {{ report.total }} 条</p></div><el-tag type="info">按事件时间倒序</el-tag></div><el-alert v-if="report.total > 2000" type="warning" title="事件超过 2000 条,请缩小时间范围或选择记录来源后导出" :closable="false" class="notice" /><el-empty v-if="!report.items.length" description="此范围内没有匹配记录;未采集或未上报不代表没有故障" :image-size="90" /><el-timeline v-else><el-timeline-item v-for="event in report.items" :key="event.id" :timestamp="time(event.time)" placement="top"><article class="diagnosis-event"><div class="diagnosis-event-heading"><el-tag size="small" type="info">{{ sources[event.source] }}</el-tag><strong>{{ lifecycle[event.action] || auditActionLabels[event.action] || event.action }}</strong><StatusTag :value="event.status" /></div><p>{{ event.message }}</p><p class="secondary">{{ event.targetName }}<span v-if="event.actor"> · {{ event.actor }}</span></p><el-collapse><el-collapse-item title="查看关联标识与详情" :name="event.id"><pre v-if="typeof details(event).logTail === 'string'" class="diagnosis-log">{{ details(event).logTail || '设备回传的日志片段为空' }}</pre><pre>{{ metadata(event) }}</pre></el-collapse-item></el-collapse></article></el-timeline-item></el-timeline><el-pagination v-model:current-page="page" :disabled="loading" :total="report.total" :page-size="20" layout="total, prev, pager, next" @current-change="load()" /></section>
|
||||
<section v-if="report.subject.kind === 'terminal'" class="panel diagnosis-archives"><div class="diagnosis-timeline-heading"><div><h2>持续日志归档</h2><p class="subtext">终端回传的每次日志快照独立归档,保留 {{ archives?.retentionDays || 30 }} 天,可按关键词检索</p></div><div class="archive-search"><el-input v-model="archiveKeyword" clearable placeholder="搜索日志关键词" @keyup.enter="searchArchives" /><el-button :loading="archiveLoading" @click="searchArchives">检索</el-button></div></div><el-empty v-if="!archives?.items.length" description="没有匹配的归档快照;持续归档从终端回传日志后开始" :image-size="80" /><div v-else class="archive-list"><article v-for="item in archives.items" :key="item.id" class="archive-item"><div class="archive-item-heading"><strong>{{ time(item.capturedAt) }}</strong><el-tag size="small" type="info">{{ item.kioskState || '未知状态' }}</el-tag><span class="secondary">Agent {{ item.agentVersion || '未报告' }} · boot {{ item.bootId || '未报告' }}</span></div><pre>{{ item.logText || '日志为空' }}</pre><p class="secondary mono">任务 {{ item.taskId }}</p></article></div></section>
|
||||
<section class="panel diagnosis-notes"><h3>查询范围说明</h3><p v-for="note in report.notes" :key="note" class="subtext">{{ note }}</p></section>
|
||||
</template>
|
||||
<section v-else-if="!error" class="panel diagnosis-empty"><el-empty description="选择需要排查的设备或桌面,再查询诊断记录" :image-size="110" /></section>
|
||||
</template>
|
||||
<style scoped>
|
||||
.diagnosis-filters{padding:22px}.diagnosis-query{display:grid;grid-template-columns:minmax(190px,1fr) minmax(320px,1.5fr) 160px auto;gap:12px;margin:18px 0}.diagnosis-query :deep(.el-date-editor){width:100%;min-width:0}.diagnosis-subject{display:flex;justify-content:space-between;align-items:center;gap:18px;flex-wrap:wrap;margin-top:20px}.diagnosis-subject h2{font-size:19px;margin-bottom:8px}.diagnosis-subject p{line-height:1.8;font-size:12px}.diagnosis-subject-actions{display:flex;align-items:center;gap:14px}.diagnosis-footnote{width:100%;color:var(--vdi-muted)}.diagnosis-counts{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;margin:20px 0}.diagnosis-counts .panel{padding:18px;margin:0}.diagnosis-counts span{font-size:12px;color:var(--vdi-muted)}.diagnosis-counts strong{display:block;font-size:26px;margin-top:12px}.diagnosis-timeline-heading{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-bottom:26px;flex-wrap:wrap}.diagnosis-timeline h2{font-size:18px}.diagnosis-timeline :deep(.el-timeline){padding-left:4px}.diagnosis-event{border:1px solid var(--vdi-border);border-radius:12px;padding:16px;background:var(--vdi-panel-2);overflow-wrap:anywhere}.diagnosis-event-heading{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.diagnosis-event-heading strong{font-size:14px}.diagnosis-event p{font-size:13px;line-height:1.9;margin-top:9px}.diagnosis-event pre{white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px;line-height:1.8;max-height:380px;overflow:auto}.diagnosis-log{padding:16px;background:var(--vdi-bg);border:1px solid var(--vdi-border);border-radius:8px;margin:10px 0}.diagnosis-event :deep(.el-collapse){margin-top:12px;--el-collapse-header-bg-color:transparent;--el-collapse-content-bg-color:transparent}.diagnosis-collection{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.diagnosis-collection p{width:100%;font-size:13px}.diagnosis-archives{margin-top:20px}.archive-search{display:flex;gap:8px;min-width:300px}.archive-list{display:grid;gap:12px}.archive-item{border:1px solid var(--vdi-border);border-radius:10px;padding:14px;background:var(--vdi-panel-2)}.archive-item-heading{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.archive-item pre{white-space:pre-wrap;overflow:auto;max-height:260px;margin:12px 0;padding:12px;background:var(--vdi-bg);border-radius:8px;font-size:12px;line-height:1.7}.diagnosis-notes{margin-top:20px}.diagnosis-notes h3{font-size:14px}.diagnosis-notes p{margin-top:12px}.diagnosis-empty{margin-top:20px}@media(max-width:1250px){.diagnosis-query{grid-template-columns:1fr 1fr}.diagnosis-query :deep(.el-date-editor){grid-column:1/-1;grid-row:2}.diagnosis-query>.el-button{grid-column:1/-1}}@media(max-width:600px){.diagnosis-query{grid-template-columns:minmax(0,1fr)}.diagnosis-query :deep(.el-date-editor){height:62px;flex-wrap:wrap;gap:4px}.diagnosis-filters{padding:18px}.diagnosis-counts{grid-template-columns:repeat(2,minmax(0,1fr))}.diagnosis-event{padding:12px}.diagnosis-subject-actions{flex-wrap:wrap}.diagnosis-counts strong{font-size:23px}}
|
||||
</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,54 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onUnmounted, ref, watch } from 'vue'
|
||||
import { Cpu, Refresh, Search } from '@element-plus/icons-vue'
|
||||
import { api, errorMessage, type GPUExclusiveStatus, type GPUInventory, type GPUItem } from '../api'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
|
||||
const platform = usePlatform(), node = ref(''), inventory = ref<GPUInventory>(), exclusive = ref<GPUExclusiveStatus>(), busy = ref(false), error = ref(''), keyword = ref(''), state = ref(''), selected = ref<GPUItem>()
|
||||
const nodes = computed(() => platform.resources.filter(r => r.provider === 'proxmox'))
|
||||
const labels = { referenced: '有配置引用', multiple: '多 VM 引用', unreferenced: '未发现配置引用', unknown: '待核查' }
|
||||
const tones = { referenced: 'info', multiple: 'warning', unreferenced: 'info', unknown: 'warning' } as const
|
||||
const items = computed(() => (inventory.value?.items || []).filter(g => (!state.value || g.state === state.value) && `${g.name} ${g.vendor} ${g.address} ${g.references.map(r => `${r.vmName} ${r.vmid} ${r.desktopName}`).join(' ')}`.toLowerCase().includes(keyword.value.toLowerCase())))
|
||||
const referencedCount = computed(() => inventory.value?.items.filter(g => g.references.length).length || 0)
|
||||
const uncertainCount = computed(() => inventory.value?.items.filter(g => g.state === 'unknown' || g.state === 'multiple').length || 0)
|
||||
const now = ref(Date.now()), stale = computed(() => !!inventory.value && now.value - Date.parse(inventory.value.observedAt) > 90000)
|
||||
const timer = setInterval(() => { now.value = Date.now() }, 5000)
|
||||
let generation = 0
|
||||
onUnmounted(() => { generation++; clearInterval(timer) })
|
||||
watch(nodes, values => { if (!values.some(r => r.id === node.value)) node.value = values[0]?.id || '' }, { immediate: true })
|
||||
watch(node, () => { selected.value = undefined; void load() }, { immediate: true })
|
||||
async function load() {
|
||||
const version = ++generation, target = node.value
|
||||
inventory.value = undefined; error.value = ''; busy.value = !!target
|
||||
if (!target) return
|
||||
try { const [value, group] = await Promise.all([api.gpuInventory(target), api.gpuExclusiveStatus(target)]); if (version === generation) { inventory.value = value; exclusive.value = group; now.value = Date.now() } }
|
||||
catch (e) { if (version === generation) error.value = errorMessage(e) }
|
||||
finally { if (version === generation) busy.value = false }
|
||||
}
|
||||
const owners = (gpu: GPUItem) => [...new Set(gpu.references.map(r => `${r.vmName || 'VM'} · ${r.vmid}`))].join('、')
|
||||
const exclusiveLabel = computed(() => !exclusive.value ? '' : exclusive.value.allocationReady ? '可分配' : exclusive.value.conflicts.length ? '需处理冲突' : '当前占用')
|
||||
const memberLabel = (member: GPUExclusiveStatus['members'][number]) => member.eligible ? '可用' : member.conflicts.some(item => item.includes('仍在运行')) ? '占用中' : '冲突'
|
||||
const memberTone = (member: GPUExclusiveStatus['members'][number]) => member.eligible ? 'success' : member.conflicts.some(item => item.includes('仍在运行')) ? 'info' : 'warning'
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>GPU 资源</h1><p class="subtext">节点显卡清单与虚拟机直通配置引用</p></div><el-button :icon="Refresh" :loading="busy" :disabled="!node" @click="load">刷新 GPU 清单</el-button></div>
|
||||
<el-alert v-if="!platform.settings?.pveConfigured" type="info" title="尚未接入 Proxmox" description="由管理员在系统设置配置接入后,读取节点的真实显卡清单。" :closable="false" class="notice" />
|
||||
<el-alert v-else-if="!nodes.length" type="warning" title="暂无可查询节点,请先在计算资源同步节点" :closable="false" class="notice" />
|
||||
<section class="panel gpu-controls"><div class="toolbar"><el-select v-model="node" aria-label="GPU 计算节点" placeholder="选择计算节点"><el-option v-for="n in nodes" :key="n.id" :value="n.id" :label="n.name" /></el-select><el-input v-model="keyword" :prefix-icon="Search" clearable placeholder="搜索显卡、PCI 或虚拟机" aria-label="搜索 GPU" /><el-select v-model="state" clearable placeholder="全部引用状态" aria-label="GPU 引用状态"><el-option v-for="(label, value) in labels" :key="value" :value="value" :label="label" /></el-select></div><p class="secondary">配置引用包含关机虚拟机、模板和待应用变更。健康数据来自 PVE PCI 清单;标准 PVE API 未提供温度、利用率和显存时显示“未采集”。</p></section>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" class="notice"><el-button link type="primary" @click="load">重试读取</el-button></el-alert>
|
||||
<template v-if="inventory">
|
||||
<section v-if="exclusive?.enabled" class="panel gpu-exclusive"><div class="gpu-exclusive-heading"><div><h2>独占资源状态</h2><p class="subtext">分配前检查与占用释放条件</p></div><el-tag :type="exclusive.allocationReady ? 'success' : exclusive.conflicts.length ? 'warning' : 'info'">{{ exclusiveLabel }}</el-tag></div><div class="gpu-exclusive-summary"><span>锁 {{ exclusive.lockAvailable ? '可用' : '占用' }}</span><span>成员 {{ exclusive.members.length }}/{{ exclusive.vmids.length }}</span><span>释放 {{ exclusive.releaseReady ? '可检查' : '不可释放' }}</span></div><el-alert v-if="exclusive.conflicts.length" type="warning" :closable="false" title="当前冲突"><ul class="gpu-conflicts"><li v-for="(item, index) in exclusive.conflicts" :key="index">{{ item }}</li></ul></el-alert><el-table :data="exclusive.members" size="small" style="margin-top:14px"><el-table-column prop="name" label="桌面" min-width="150" /><el-table-column prop="vmid" label="VMID" width="80" /><el-table-column label="实际电源" width="110"><template #default="scope"><el-tag :type="scope.row.powerObserved ? (scope.row.powerState === 'stopped' ? 'success' : 'warning') : 'info'">{{ scope.row.powerObserved ? scope.row.powerState : '未采集' }}</el-tag></template></el-table-column><el-table-column label="会话 / 任务" width="110"><template #default="scope">{{ scope.row.activeSessions }} / {{ scope.row.activeTasks }}</template></el-table-column><el-table-column label="分配" width="90"><template #default="scope"><el-tag :type="memberTone(scope.row)">{{ memberLabel(scope.row) }}</el-tag></template></el-table-column></el-table><p class="secondary gpu-release-note">释放仅表示当前无会话和未完成任务,平台不会自动关机或重放切换操作;需从终端准备或任务核对流程完成实际变更。</p></section>
|
||||
<div class="gpu-summary"><span>检测显卡 <b>{{ inventory.items.length }}</b></span><span>有配置引用 <b>{{ referencedCount }}</b></span><span>待核查 / 多 VM 引用 <b>{{ uncertainCount }}</b></span><span>已检查 {{ inventory.scannedVmCount }} / {{ inventory.visibleVmCount }} 台可见 VM</span><el-tag :type="stale ? 'warning' : 'info'">{{ stale ? '数据已过期,请刷新' : '读取于 ' + new Date(inventory.observedAt).toLocaleTimeString('zh-CN') }}</el-tag></div>
|
||||
<section v-if="inventory.issues.length" class="panel gpu-issues"><h2>检查未完整</h2><p class="subtext">以下情况影响引用检查范围,未发现引用的显卡仍需核查。</p><ul><li v-for="(issue, index) in inventory.issues" :key="index"><span v-if="issue.vmid">VM {{ issue.vmid }}:</span>{{ issue.message }}</li></ul></section>
|
||||
<div v-if="items.length" class="gpu-grid"><article v-for="gpu in items" :key="gpu.id" class="panel gpu-card"><div class="gpu-card-top"><div class="gpu-symbol"><el-icon :size="26"><Cpu /></el-icon></div><el-tag :type="tones[gpu.state]">{{ labels[gpu.state] }}</el-tag></div><p class="eyebrow">{{ gpu.vendor || gpu.vendorId }}</p><h2>{{ gpu.name || '显卡 ' + gpu.deviceId }}</h2><dl><div><dt>PCI 地址</dt><dd class="mono">{{ gpu.address }}</dd></div><div><dt>节点</dt><dd>{{ inventory.node }}</dd></div><div><dt>IOMMU 分组</dt><dd>{{ gpu.iommuGroup === null ? '未报告' : gpu.iommuGroup }}</dd></div><div><dt>驱动绑定</dt><dd><el-tag size="small" :type="gpu.health.driverBinding === 'bound' ? 'success' : 'info'">{{ gpu.health.driverBinding === 'bound' ? gpu.health.driver || '已绑定' : '未采集' }}</el-tag></dd></div><div><dt>配置引用</dt><dd>{{ owners(gpu) || (gpu.state === 'unknown' ? '检查范围不完整' : '未发现') }}</dd></div></dl><div class="gpu-card-footer"><span class="secondary">温度 / 利用率 / 显存:{{ gpu.health.status === 'not_collected' ? '未采集' : '部分采集' }}</span><el-button link type="primary" @click="selected = gpu">查看 GPU 详情</el-button></div></article></div>
|
||||
<section v-else class="panel"><el-empty :description="inventory.items.length ? '暂无符合筛选条件的显卡' : '当前节点未发现显示控制器类 PCI 设备'" /></section>
|
||||
</template>
|
||||
<section v-else-if="busy" class="panel empty-panel" aria-live="polite"><p class="subtext">正在读取显卡与虚拟机配置…</p></section>
|
||||
<el-drawer :model-value="!!selected" title="GPU 资源详情" size="600px" @closed="selected = undefined">
|
||||
<template v-if="selected && inventory"><h2 class="gpu-detail-name">{{ selected.name || selected.deviceId }}</h2><p class="subtext mono">{{ inventory.node }} · {{ selected.address }}</p><el-tag :type="tones[selected.state]" style="margin:16px 0">{{ labels[selected.state] }}</el-tag><el-descriptions :column="1" border><el-descriptions-item label="厂商">{{ selected.vendor || '未报告' }}</el-descriptions-item><el-descriptions-item label="厂商 / 设备 ID">{{ selected.vendorId }} / {{ selected.deviceId }}</el-descriptions-item><el-descriptions-item label="PCI 类别">{{ selected.class }}</el-descriptions-item><el-descriptions-item label="IOMMU 分组">{{ selected.iommuGroup === null ? '未报告' : selected.iommuGroup }}</el-descriptions-item><el-descriptions-item label="驱动绑定">{{ selected.health.driverBinding === 'bound' ? selected.health.driver : '未采集' }}</el-descriptions-item><el-descriptions-item label="温度 / 利用率 / 显存">未采集(标准 PVE PCI 接口不提供运行指标)</el-descriptions-item></el-descriptions><h3 class="gpu-ref-title">虚拟机配置引用</h3><p class="subtext">配置记录不代表设备实际已由虚拟机使用;待应用项在重启后可能生效。</p><article v-for="(owner, index) in selected.references" :key="index" class="gpu-reference"><div class="row"><strong>{{ owner.vmName || '虚拟机' }} · VM {{ owner.vmid }}</strong><StatusTag :value="owner.vmStatus" /></div><div class="gpu-ref-tags"><el-tag size="small">{{ owner.phase === 'current' ? '当前配置' : '待应用配置' }}</el-tag><el-tag v-if="owner.pendingRemoval" size="small" type="warning">待移除</el-tag><el-tag v-if="owner.template" size="small" type="info">模板</el-tag><el-tag size="small" type="info">{{ owner.mediated ? '介导设备' : 'PCI 直通' }}</el-tag></div><p class="secondary">{{ owner.slot }} · {{ owner.source === 'mapping' ? 'PCI 映射 ' + owner.mapping : '直接 PCI 地址' }}</p><p class="secondary">{{ owner.desktopId ? '已纳管桌面:' + owner.desktopName : '尚未纳管为平台桌面' }}</p></article><el-empty v-if="!selected.references.length" :description="selected.state === 'unknown' ? '检查范围不完整,引用情况待核查' : '未发现 QEMU 配置引用'" /><p class="subtext">驱动字段由 PVE PCI 清单提供;温度、利用率和显存需后续接入节点采集代理。</p></template>
|
||||
</el-drawer>
|
||||
</template>
|
||||
<style scoped>
|
||||
.gpu-controls .toolbar{margin-bottom:12px}.gpu-summary{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:20px;color:var(--vdi-muted);font-size:12px}.gpu-summary>span{background:var(--vdi-panel);border:1px solid var(--vdi-border);border-radius:9px;padding:12px}.gpu-summary b{color:var(--vdi-text);margin-left:8px}.gpu-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:20px}.gpu-card{margin:0;display:flex;flex-direction:column}.gpu-card-top{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:22px}.gpu-symbol{width:52px;height:52px;display:grid;place-items:center;background:var(--vdi-accent-soft);color:var(--vdi-accent);border-radius:13px}.gpu-card h2,.gpu-detail-name{overflow-wrap:anywhere;line-height:1.6}.gpu-card dl{margin:22px 0;display:grid;gap:16px;font-size:12px}.gpu-card dl>div{display:flex;justify-content:space-between;gap:20px}.gpu-card dt{color:var(--vdi-muted);flex-shrink:0}.gpu-card dd{margin:0;text-align:right;overflow-wrap:anywhere}.gpu-card-footer{margin-top:auto;padding-top:14px;border-top:1px solid var(--vdi-border);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px}.gpu-issues{border-color:var(--vdi-warn)}.gpu-issues h2{font-size:15px}.gpu-issues ul{padding-left:20px;margin-top:12px;color:var(--vdi-muted);font-size:12px;line-height:2;overflow-wrap:anywhere}.gpu-ref-title{margin:25px 0 8px;font-size:15px}.gpu-reference{margin-top:16px;padding:16px;border:1px solid var(--vdi-border);border-radius:12px;background:var(--vdi-panel-2);overflow-wrap:anywhere}.gpu-reference .row{margin:0 0 12px}.gpu-reference strong{font-size:13px}.gpu-ref-tags{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px}@media(min-width:1700px){.gpu-grid{grid-template-columns:repeat(3,minmax(0,1fr))}}@media(max-width:950px){.gpu-grid{grid-template-columns:1fr}}@media(max-width:600px){.gpu-controls .toolbar .el-select{width:100%}.gpu-summary{gap:8px}.gpu-summary>span{padding:9px}.gpu-card-footer{align-items:flex-start}}
|
||||
.gpu-exclusive{margin:20px 0}.gpu-exclusive-heading{display:flex;justify-content:space-between;align-items:center;gap:12px}.gpu-exclusive-heading h2{font-size:17px}.gpu-exclusive-summary{display:flex;gap:18px;flex-wrap:wrap;color:var(--vdi-muted);font-size:12px;margin:16px 0}.gpu-conflicts{padding-left:20px;line-height:1.8}.gpu-release-note{margin-top:14px}</style>
|
||||
@@ -0,0 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { Monitor, Connection, Lock, ArrowRight } from '@element-plus/icons-vue'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { ApiError, 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: '', code: '' }), busy = ref(false), error = ref(''), mfaRequired = ref(false)
|
||||
watch(() => form.username, () => { mfaRequired.value = false; form.code = ''; error.value = '' })
|
||||
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, form.code.trim()); form.password = ''; form.code = ''; const redirect = typeof route.query.redirect === 'string' && route.query.redirect.startsWith('/') && !route.query.redirect.startsWith('//') ? route.query.redirect : '/'; await router.replace(redirect) }
|
||||
catch (e) { if (e instanceof ApiError && (e.code === 'mfa_required' || e.code === 'mfa_invalid')) { mfaRequired.value = true; form.code = '' }; 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-form-item v-if="mfaRequired" label="动态码或恢复码"><el-input v-model="form.code" name="code" aria-label="登录动态码或恢复码" autocomplete="one-time-code" size="large" maxlength="80" 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,82 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
|
||||
import { api, errorMessage, type AlertRule, type AlertRuleInput, type AlertRecord, type ResourcePoint } from '../api'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { useAction } from '../composables/useAction'
|
||||
import ResourceTrend from '../components/ResourceTrend.vue'
|
||||
const data = usePlatform(), auth = useAuth(), { run, busy: saving } = useAction()
|
||||
const metricLabels: Record<string, string> = { node_cpu: '节点 CPU', node_memory: '节点内存', node_storage: '节点存储', node_unavailable: '节点不可用 / 采集异常', terminal_offline: '终端离线', terminal_cpu: '终端 CPU', terminal_memory: '终端内存', terminal_temperature: '终端 SoC 温度' }
|
||||
const rules = ref<AlertRule[]>([]), alerts = ref<AlertRecord[]>([]), points = ref<ResourcePoint[]>([])
|
||||
const resourceId = ref(''), hours = ref(24), bucket = ref(300), from = ref(Date.now() - 86400000), to = ref(Date.now())
|
||||
const status = ref(''), keyword = ref(''), page = ref(1), total = ref(0), firing = ref(0), unacknowledged = ref(0), loading = ref(false), error = ref(''), chartError = ref('')
|
||||
const nodes = computed(() => data.resources.filter(r => r.provider === 'proxmox'))
|
||||
const tab = ref('alerts'), dialog = ref(false), editId = ref('')
|
||||
const form = reactive<AlertRuleInput>({ name: '', metric: 'node_cpu', threshold: 90, holdSeconds: 120, enabled: true })
|
||||
const offline = computed(() => ['node_unavailable', 'terminal_offline'].includes(form.metric))
|
||||
const temperature = computed(() => form.metric === 'terminal_temperature')
|
||||
const terminalMetric = computed(() => ['terminal_cpu', 'terminal_memory', 'terminal_temperature'].includes(form.metric))
|
||||
const unit = (metric: string) => ['node_unavailable', 'terminal_offline'].includes(metric) ? '秒' : metric === 'terminal_temperature' ? '°C' : '%'
|
||||
const stamp = (v?: string | null) => v ? new Date(v).toLocaleString('zh-CN', { hour12: false }) : '—'
|
||||
const reasons: Record<string, string> = { condition_cleared: '指标恢复', rule_changed: '规则变更', target_unavailable: '目标移除或停用' }
|
||||
async function chart() {
|
||||
chartError.value = ''
|
||||
if (!resourceId.value) { points.value = []; return }
|
||||
const selected = resourceId.value, selectedHours = hours.value, end = Date.now(), start = end - selectedHours * 3600000
|
||||
try {
|
||||
const result = await api.resourceSeries(selected, new Date(start).toISOString(), new Date(end).toISOString())
|
||||
if (resourceId.value !== selected || hours.value !== selectedHours) return
|
||||
points.value = result.items; bucket.value = result.bucketSeconds; from.value = start; to.value = end
|
||||
} catch (e) { chartError.value = errorMessage(e); points.value = [] }
|
||||
}
|
||||
async function load(reset = false) {
|
||||
if (loading.value) return
|
||||
if (reset) page.value = 1
|
||||
loading.value = true; error.value = ''
|
||||
try {
|
||||
const [r, a] = await Promise.all([api.alertRules(), api.alerts(page.value, status.value, keyword.value)])
|
||||
rules.value = r.items; alerts.value = a.items; total.value = a.total; firing.value = a.firingCount; unacknowledged.value = a.unacknowledgedCount
|
||||
if (!resourceId.value) resourceId.value = nodes.value[0]?.id || ''
|
||||
await chart()
|
||||
} catch (e) { error.value = errorMessage(e) } finally { loading.value = false }
|
||||
}
|
||||
function edit(rule?: AlertRule) {
|
||||
editId.value = rule?.id || ''
|
||||
Object.assign(form, rule ? { name: rule.name, metric: rule.metric, threshold: rule.threshold, holdSeconds: rule.holdSeconds, enabled: rule.enabled } : { name: '', metric: 'node_cpu', threshold: 90, holdSeconds: 120, enabled: true })
|
||||
dialog.value = true
|
||||
}
|
||||
function metricChanged() { form.threshold = offline.value ? 180 : temperature.value ? 80 : 90; form.holdSeconds = offline.value ? 0 : 120 }
|
||||
async function save() {
|
||||
if (!form.name.trim()) return
|
||||
const ok = await run(() => api.saveAlertRule(editId.value, { ...form, name: form.name.trim() }), '告警规则已保存')
|
||||
if (ok) { dialog.value = false; await load() }
|
||||
}
|
||||
async function acknowledge(row: AlertRecord) { if (await run(() => api.acknowledgeAlert(row.id), '已确认,恢复状态仍由指标判断')) await load() }
|
||||
let timer: ReturnType<typeof setInterval>
|
||||
onMounted(() => { void load(); timer = setInterval(() => { if (!document.hidden && !dialog.value) void load() }, 15000) })
|
||||
onUnmounted(() => clearInterval(timer))
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>监控告警</h1><p class="subtext">节点与终端指标告警 · 每 15 秒刷新</p></div><el-button :loading="loading" @click="load()">刷新监控</el-button></div>
|
||||
<el-alert v-if="error" type="error" :title="error" :closable="false" class="notice" />
|
||||
<div class="monitor-summary"><article class="panel"><span>正在告警</span><strong :class="firing ? 'tone-danger' : 'tone-ok'">{{ firing }}</strong></article><article class="panel"><span>等待确认</span><strong>{{ unacknowledged }}</strong></article><article class="panel"><span>启用规则</span><strong>{{ rules.filter(r => r.enabled).length }}</strong></article></div>
|
||||
<section class="panel">
|
||||
<div class="panel-heading"><div><h2>节点资源趋势</h2><p class="subtext">采样保留 30 天,图表单次最多查看 7 天;空缺表示无有效数据。</p></div><div class="chart-filters"><el-select v-model="resourceId" aria-label="监控节点" placeholder="暂无节点" @change="chart"><el-option v-for="r in nodes" :key="r.id" :label="r.name" :value="r.id" /></el-select><el-select v-model="hours" aria-label="监控时间范围" @change="chart"><el-option :value="1" label="最近 1 小时" /><el-option :value="6" label="最近 6 小时" /><el-option :value="24" label="最近 24 小时" /><el-option :value="168" label="最近 7 天" /></el-select></div></div>
|
||||
<el-alert v-if="chartError" type="error" :title="chartError" :closable="false" class="notice" /><div class="trend-grid"><ResourceTrend v-for="m in ([{ key: 'cpu', label: 'CPU 使用率' }, { key: 'memory', label: '内存使用率' }, { key: 'storage', label: '存储使用率' }] as const)" :key="m.key" :points="points" :metric="m.key" :title="m.label" :bucket="bucket" :from="from" :to="to" /></div>
|
||||
</section>
|
||||
<section class="panel">
|
||||
<el-tabs v-model="tab"><el-tab-pane label="告警事件" name="alerts" /><el-tab-pane label="告警规则" name="rules" /></el-tabs>
|
||||
<template v-if="tab === 'alerts'">
|
||||
<div class="alert-filters"><el-input v-model="keyword" aria-label="搜索告警" placeholder="规则或目标名称" clearable @keyup.enter="load(true)" /><el-select v-model="status" aria-label="告警状态"><el-option value="" label="全部状态" /><el-option value="firing" label="正在告警" /><el-option value="resolved" label="已恢复" /></el-select><el-button :loading="loading" @click="load(true)">查询告警</el-button></div>
|
||||
<el-table :data="alerts" empty-text="暂无告警事件"><el-table-column label="规则 / 目标" min-width="190"><template #default="{ row }"><strong>{{ row.ruleName }}</strong><div class="subtext">{{ row.targetName }}</div></template></el-table-column><el-table-column label="状态" min-width="110"><template #default="{ row }"><el-tag :type="row.status === 'firing' ? 'danger' : 'success'">{{ row.status === 'firing' ? '正在告警' : '已恢复' }}</el-tag></template></el-table-column><el-table-column label="观测值 / 阈值" min-width="160"><template #default="{ row }">{{ row.value.toFixed(1) }} / {{ row.threshold }} {{ unit(row.metric) }}<div v-if="row.status === 'firing' && row.dataFresh === false" class="data-unknown" role="status">数据已过期或缺失;显示最近告警值,等待有效采样</div><div v-if="row.metric === 'node_unavailable'" class="subtext">含节点离线状态检测</div></template></el-table-column><el-table-column label="发生 / 恢复" min-width="185"><template #default="{ row }"><div>{{ stamp(row.openedAt) }}</div><div class="subtext">{{ row.resolvedAt ? stamp(row.resolvedAt) : '持续中' }}</div><div class="subtext">{{ reasons[row.resolveReason] }}</div></template></el-table-column><el-table-column label="确认" min-width="150"><template #default="{ row }"><span v-if="row.acknowledgedAt">{{ row.acknowledgedBy }}<div class="subtext">{{ stamp(row.acknowledgedAt) }}</div></span><el-button v-else-if="auth.canOperate && row.status === 'firing'" link type="primary" :disabled="saving" @click="acknowledge(row)">确认告警</el-button><span v-else class="secondary">未确认</span></template></el-table-column></el-table>
|
||||
<el-pagination v-model:current-page="page" :page-size="20" :total="total" layout="prev, pager, next, total" @current-change="load()" /><p class="subtext retention-note">确认表示已知悉,指标恢复后自动结束告警。已恢复事件保留 90 天。</p>
|
||||
</template>
|
||||
<template v-else><div class="panel-heading"><p class="subtext">水位按持续时间触发;离线按秒数触发。修改规则后重新计时。</p><el-button v-if="auth.canAdmin" type="primary" @click="edit()">新增规则</el-button></div><el-table :data="rules" empty-text="暂无规则"><el-table-column prop="name" label="规则名称" min-width="190" /><el-table-column label="指标" min-width="190"><template #default="{ row }">{{ metricLabels[row.metric] }}</template></el-table-column><el-table-column label="阈值 / 持续" min-width="155"><template #default="{ row }">{{ row.threshold }}{{ ['node_unavailable', 'terminal_offline'].includes(row.metric) ? ' 秒离线' : `${unit(row.metric)} / ${row.holdSeconds} 秒` }}</template></el-table-column><el-table-column label="状态" width="100"><template #default="{ row }"><el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '停用' }}</el-tag></template></el-table-column><el-table-column v-if="auth.canAdmin" label="操作" width="90"><template #default="{ row }"><el-button link type="primary" @click="edit(row)">编辑规则</el-button></template></el-table-column></el-table></template>
|
||||
</section>
|
||||
<el-dialog v-model="dialog" :title="editId ? '编辑告警规则' : '新增告警规则'" width="540px" :close-on-click-modal="false" :close-on-press-escape="!saving" :show-close="!saving"><el-form label-position="top"><el-form-item label="规则名称"><el-input v-model="form.name" maxlength="80" aria-label="规则名称" :disabled="saving" /></el-form-item><el-form-item label="监控指标"><el-select v-model="form.metric" aria-label="规则监控指标" :disabled="saving" @change="metricChanged"><el-option v-for="(label, value) in metricLabels" :key="value" :value="value" :label="label" /></el-select></el-form-item><el-form-item :label="offline ? '离线阈值(秒)' : temperature ? 'SoC 温度阈值(°C)' : '使用率阈值(%)'"><el-input-number v-model="form.threshold" :min="offline ? 90 : 1" :max="offline ? 86400 : temperature ? 150 : 100" :precision="offline ? 0 : 1" aria-label="告警阈值" :disabled="saving" /></el-form-item><el-form-item v-if="!offline" label="持续时间(秒)"><el-input-number v-model="form.holdSeconds" :min="0" :max="3600" :precision="0" aria-label="告警持续时间" :disabled="saving" /></el-form-item><el-form-item label="启用规则"><el-switch v-model="form.enabled" aria-label="启用告警规则" :disabled="saving" /></el-form-item></el-form><p v-if="terminalMetric" class="subtext terminal-alert-note">对已激活且启用的终端生效;SoC 温度只使用 soc-thermal 传感器。持续时间按新采样累计,重复读取不推进;采样超过 90 秒或缺失会重新计时,已有告警等待有效正常采样才恢复。此规则只在控制台告警,不发送外部通知。</p><el-alert v-if="editId" title="保存会结束本规则当前告警,并按新规则重新计时。" type="info" :closable="false" /><template #footer><el-button :disabled="saving" @click="dialog = false">取消</el-button><el-button type="primary" :loading="saving" :disabled="!form.name.trim()" @click="save">保存规则</el-button></template></el-dialog>
|
||||
</template>
|
||||
<style scoped>
|
||||
.monitor-summary{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:18px}.monitor-summary .panel{display:flex;justify-content:space-between;align-items:center;gap:12px}.monitor-summary span{font-size:12px;color:var(--vdi-muted)}.monitor-summary strong{font-size:28px}.trend-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px;margin-top:20px}.chart-filters,.alert-filters{display:flex;gap:12px;flex-wrap:wrap}.chart-filters .el-select{width:160px}.alert-filters{margin:18px 0}.alert-filters .el-input{width:230px}.alert-filters .el-select{width:150px}.el-pagination{margin-top:20px;flex-wrap:wrap}.retention-note{margin-top:15px}.subtext{line-height:1.7}.data-unknown{color:var(--el-color-warning);font-size:12px;line-height:1.7;margin-top:6px}.terminal-alert-note{margin:14px 0;font-size:12px}
|
||||
@media(max-width:1200px){.trend-grid{grid-template-columns:1fr}.panel-heading{flex-wrap:wrap;gap:16px}}
|
||||
@media(max-width:600px){.monitor-summary{gap:8px}.monitor-summary .panel{padding:14px;flex-direction:column;align-items:flex-start}.monitor-summary strong{font-size:24px}.chart-filters,.alert-filters{width:100%}.chart-filters .el-select,.alert-filters .el-select{flex:1;min-width:120px}.alert-filters .el-input{width:100%}}
|
||||
</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,39 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
|
||||
import { Plus, Refresh } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, allPages, errorMessage, type DesktopPool, type ImageTemplate, type PoolInput } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import { usePlatform } from '../stores/platform'
|
||||
import CloneDesktopDialog from '../components/CloneDesktopDialog.vue'
|
||||
const auth = useAuth(), data = usePlatform(), items = ref<DesktopPool[]>([]), templates = ref<ImageTemplate[]>([])
|
||||
const loading = ref(false), busy = ref(false), error = ref(''), visible = ref(false), editId = ref(''), memberPool = ref<DesktopPool>(), memberIds = ref<string[]>([]), cloneVisible = ref(false), clonePool = ref<DesktopPool>(), keyword = ref('')
|
||||
const form = reactive<PoolInput>({ name: '', type: 'dedicated', maxCount: 10, templateId: null, enabled: true })
|
||||
const filtered = computed(() => items.value.filter(p => p.name.toLowerCase().includes(keyword.value.toLowerCase())))
|
||||
const desktops = computed(() => data.desktops.filter(d => !d.poolId || d.poolId === memberPool.value?.id))
|
||||
async function load(quiet = false) { if (!quiet) loading.value = true; try { [items.value, templates.value] = await Promise.all([allPages(api.pools), allPages(api.templates)]); error.value = '' } catch (e) { error.value = errorMessage(e) } finally { loading.value = false } }
|
||||
let timer: ReturnType<typeof setInterval>
|
||||
onMounted(() => { void load(); timer = setInterval(() => { if (!document.hidden && !busy.value) void load(true) }, 5000) })
|
||||
onUnmounted(() => clearInterval(timer))
|
||||
function edit(pool?: DesktopPool) { editId.value = pool?.id || ''; Object.assign(form, pool ? { name: pool.name, type: pool.type, maxCount: pool.maxCount, templateId: pool.templateId, enabled: pool.enabled } : { name: '', type: 'dedicated', maxCount: 10, templateId: null, enabled: true }); visible.value = true }
|
||||
async function save() { busy.value = true; try { await api.savePool(editId.value, { ...form }); visible.value = false; ElMessage.success('桌面池已保存'); await Promise.all([load(), data.refresh()]) } catch (e) { ElMessage.error(errorMessage(e)) } finally { busy.value = false } }
|
||||
function members(pool: DesktopPool) { memberPool.value = pool; memberIds.value = data.desktops.filter(d => d.poolId === pool.id).map(d => d.id) }
|
||||
async function saveMembers() { if (!memberPool.value) return; busy.value = true; try { await api.poolMembers(memberPool.value.id, memberIds.value); memberPool.value = undefined; ElMessage.success('桌面池成员已更新'); await Promise.all([load(), data.refresh()]) } catch (e) { ElMessage.error(errorMessage(e)) } finally { busy.value = false } }
|
||||
function clone(pool: DesktopPool) { clonePool.value = pool; cloneVisible.value = true }
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>桌面池</h1><p class="subtext">按用途组织桌面,控制容量、模板与授权范围</p></div><div><el-button :icon="Refresh" :loading="loading" @click="load()">刷新</el-button><el-button v-if="auth.canAdmin" :icon="Plus" type="primary" @click="edit()">新建桌面池</el-button></div></div>
|
||||
<el-alert class="notice" type="info" :closable="false" show-icon title="当前采用管理员分配与回收。公共池的自动领取、退出还原和自动扩容尚未接入。" />
|
||||
<el-alert v-if="error" class="notice" type="error" :title="error" :closable="false" />
|
||||
<section class="panel" v-loading="loading">
|
||||
<div class="toolbar"><el-input v-model="keyword" placeholder="搜索桌面池" aria-label="搜索桌面池" clearable /></div>
|
||||
<el-table :data="filtered" empty-text="尚无桌面池,创建后可加入已有桌面或从模板创建。"><el-table-column prop="name" label="桌面池" min-width="170" /><el-table-column label="类型" width="110"><template #default="{ row }">{{ row.type === 'shared' ? '公共池' : '专属池' }}</template></el-table-column><el-table-column label="已用 / 容量" min-width="170"><template #default="{ row }"><el-progress :percentage="Math.min(100, Math.round((row.desktopCount + row.reservedCount) / row.maxCount * 100))" :show-text="false" /><div class="capacity">{{ row.desktopCount }} 台桌面 + {{ row.reservedCount }} 台创建预留 / {{ row.maxCount }}</div></template></el-table-column><el-table-column label="已授权 / 活动" min-width="120"><template #default="{ row }">{{ row.assignedCount }} / {{ row.activeCount }}</template></el-table-column><el-table-column label="默认模板" min-width="150"><template #default="{ row }">{{ templates.find(t => t.id === row.templateId)?.name || '不限定' }}</template></el-table-column><el-table-column label="状态" width="100"><template #default="{ row }"><el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '已启用' : '已停用' }}</el-tag></template></el-table-column><el-table-column v-if="auth.canAdmin" label="操作" min-width="235"><template #default="{ row }"><el-button link type="primary" :disabled="!row.enabled || row.desktopCount + row.reservedCount >= row.maxCount" @click="clone(row)">创建桌面</el-button><el-button link @click="members(row)">成员</el-button><el-button link @click="edit(row)">编辑</el-button></template></el-table-column></el-table>
|
||||
<p class="pool-note">创建中和结果待确认的任务均占用容量。加入桌面池不会自动修改用户授权,请在「用户与授权」分配桌面。停用池会阻止新建,不会中断现有桌面。</p>
|
||||
</section>
|
||||
<el-dialog v-model="visible" :title="editId ? '编辑桌面池' : '新建桌面池'" width="540px" :close-on-click-modal="false"><el-form label-position="top" :disabled="busy"><el-form-item label="名称"><el-input v-model="form.name" maxlength="80" /></el-form-item><el-form-item label="类型"><el-radio-group v-model="form.type"><el-radio value="dedicated">专属池</el-radio><el-radio value="shared">公共池</el-radio></el-radio-group></el-form-item><el-form-item label="容量上限"><el-input-number v-model="form.maxCount" :min="1" :max="10000" :precision="0" /></el-form-item><el-form-item label="创建模板(可选)"><el-select v-model="form.templateId" clearable placeholder="不限定模板"><el-option v-for="t in templates" :key="t.id" :label="`${t.name} · ${t.version}`" :value="t.id" :disabled="!t.enabled" /></el-select></el-form-item><el-form-item label="启用"><el-switch v-model="form.enabled" /></el-form-item></el-form><template #footer><el-button :disabled="busy" @click="visible = false">取消</el-button><el-button type="primary" :disabled="!form.name.trim()" :loading="busy" @click="save">保存桌面池</el-button></template></el-dialog>
|
||||
<el-dialog :model-value="!!memberPool" :title="`桌面池成员 · ${memberPool?.name || ''}`" width="620px" :close-on-click-modal="false" @close="memberPool = undefined"><p class="subtext">仅列出未加入其他池的桌面;移出池不会撤销已有用户授权。</p><el-select v-model="memberIds" multiple filterable placeholder="选择桌面" :disabled="busy" style="width:100%;margin:20px 0"><el-option v-for="d in desktops" :key="d.id" :label="`${d.name} · ${d.os} / ${d.vmid}`" :value="d.id" /></el-select><p class="subtext">已选 {{ memberIds.length }} 台 + 创建预留 {{ memberPool?.reservedCount || 0 }} 台 / 容量 {{ memberPool?.maxCount }}</p><template #footer><el-button :disabled="busy" @click="memberPool = undefined">取消</el-button><el-button type="primary" :loading="busy" :disabled="memberIds.length + (memberPool?.reservedCount || 0) > (memberPool?.maxCount || 0)" @click="saveMembers">保存成员</el-button></template></el-dialog>
|
||||
<CloneDesktopDialog v-model="cloneVisible" :pool-id="clonePool?.id" :template-id="clonePool?.templateId || undefined" @submitted="load" />
|
||||
</template>
|
||||
<style scoped>
|
||||
.capacity{font-size:11px;color:var(--vdi-muted);margin-top:7px}.pool-note{padding:20px;color:var(--vdi-muted);font-size:12px;line-height:1.8}
|
||||
</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,36 @@
|
||||
<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'
|
||||
import SessionHistory from '../components/SessionHistory.vue'
|
||||
const data = usePlatform(), auth = useAuth(), { busy, run, confirm } = useAction()
|
||||
const selectedId = ref('')
|
||||
const tab = ref('active')
|
||||
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>
|
||||
<el-tabs v-model="tab"><el-tab-pane label="当前会话" name="active" /><el-tab-pane label="历史记录" name="history" /></el-tabs>
|
||||
<SessionHistory v-if="tab === 'history'" />
|
||||
<template v-else>
|
||||
<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>
|
||||
</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,21 @@
|
||||
<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'
|
||||
import PveConnectionDialog from '../components/PveConnectionDialog.vue'
|
||||
import AdministratorAccounts from '../components/AdministratorAccounts.vue'
|
||||
const data = usePlatform(), auth = useAuth(), section = ref('platform'), pveVisible = ref(false)
|
||||
const sections = [{ id: 'platform', title: '平台接入', icon: Connection }, { id: 'accounts', title: '管理员账号', icon: Lock }, { id: 'permissions', title: '角色权限', icon: Lock }, { id: 'capabilities', title: '功能范围', icon: Setting }]
|
||||
const planned = ['公共池自动领取与退出还原', '新桌面自动初始化', 'GPU 资源绑定', '外部告警通知与串流 FPS/RTT 采集', '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><el-button v-if="auth.canAdmin" type="primary" style="margin-top:22px" @click="pveVisible = true">配置 Proxmox 接入</el-button><p class="settings-footnote">在控制台检查连接并保存;原密钥不回显,留空可保留。</p></section><section v-else-if="section === 'accounts'" class="panel settings-panel"><AdministratorAccounts /></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 ['登录限流与角色权限', '管理员账号维护与密码修改', '计算资源同步', 'GPU 清单与虚拟机配置引用', '已有桌面纳管与电源管理', '桌面批量开关机、重启与逐台结果', '镜像模板登记与 PVE 克隆', '桌面池容量与成员管理', '桌面连接与规格管理', '关机快照创建、删除与手动还原', '终端注册、分组、停用与重新激活', '用户资料、启停与批量桌面授权', '会话状态、历史与重置', 'CSV 批量导入', '节点趋势与告警', '终端系统指标、历史与阈值告警', '诊断日志采集', '日志诊断关联与诊断包', '终端策略版本、下发与应用回执', '任务跟踪与操作审计']" :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>
|
||||
<PveConnectionDialog v-model="pveVisible" />
|
||||
</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-content{min-width:0}.settings-panel{padding:28px;min-width:0}.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,14 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import AuditHistory from '../components/AuditHistory.vue'
|
||||
import TaskHistory from '../components/TaskHistory.vue'
|
||||
const tab = ref('tasks')
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>任务与审计</h1><p class="subtext">提交记录、执行回执和最终结果分开显示</p></div></div>
|
||||
<section class="panel">
|
||||
<el-tabs v-model="tab"><el-tab-pane label="执行任务" name="tasks" /><el-tab-pane label="操作审计" name="audit" /></el-tabs>
|
||||
<AuditHistory v-if="tab === 'audit'" />
|
||||
<TaskHistory v-else />
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,64 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
|
||||
import { Plus, Refresh } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { api, allPages, errorMessage, type ImageTemplate, type DiscoveredVM, type TemplateInput } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
import SystemIcon from '../components/SystemIcon.vue'
|
||||
import CloneDesktopDialog from '../components/CloneDesktopDialog.vue'
|
||||
const auth = useAuth(), items = ref<ImageTemplate[]>([]), discovered = ref<DiscoveredVM[]>([])
|
||||
const loading = ref(false), busy = ref(false), error = ref(''), discoverError = ref(''), visible = ref(false), cloneVisible = ref(false), templateId = ref(''), keyword = ref(''), vmKey = ref('')
|
||||
const form = reactive<TemplateInput>({ name: '', version: '1.0', os: 'Windows', node: '', vmid: 9000, hardwareEncodingVerified: false })
|
||||
const filtered = computed(() => items.value.filter(t => `${t.name} ${t.version} ${t.os} ${t.vmid}`.toLowerCase().includes(keyword.value.toLowerCase())))
|
||||
const candidates = computed(() => discovered.value.filter(v => !items.value.some(t => t.node === v.node && t.vmid === v.vmid)))
|
||||
async function load(quiet = false) { if (!quiet) loading.value = true; try { items.value = await allPages(api.templates); error.value = '' } catch (e) { error.value = errorMessage(e) } finally { loading.value = false } }
|
||||
let timer: ReturnType<typeof setInterval>
|
||||
onMounted(() => { void load(); timer = setInterval(() => { if (!document.hidden && !busy.value) void load(true) }, 5000) })
|
||||
onUnmounted(() => clearInterval(timer))
|
||||
async function openRegister() {
|
||||
visible.value = true; discoverError.value = ''; discovered.value = []; vmKey.value = ''; busy.value = true
|
||||
Object.assign(form, { name: '', version: '1.0', os: 'Windows', node: '', vmid: 9000, hardwareEncodingVerified: false })
|
||||
try { discovered.value = await allPages(api.discoverTemplates) } catch (e) { discoverError.value = errorMessage(e) } finally { busy.value = false }
|
||||
}
|
||||
function choose() { const vm = candidates.value.find(v => `${v.node}/${v.vmid}` === vmKey.value); if (vm) Object.assign(form, { node: vm.node, vmid: vm.vmid, name: vm.name }) }
|
||||
async function register() {
|
||||
busy.value = true
|
||||
try { await api.registerTemplate({ ...form }); visible.value = false; ElMessage.success('模板已登记并校验'); await load() }
|
||||
catch (e) { ElMessage.error(errorMessage(e)) } finally { busy.value = false }
|
||||
}
|
||||
async function update(item: ImageTemplate, validate = false) {
|
||||
busy.value = true
|
||||
try { if (validate) await api.validateTemplate(item.id); else await api.updateTemplate(item.id, { enabled: !item.enabled }); ElMessage.success(validate ? '模板配置已重新验证' : '模板状态已更新'); await load() }
|
||||
catch (e) { ElMessage.error(errorMessage(e)) } finally { busy.value = false }
|
||||
}
|
||||
async function toggleEncoding(item: ImageTemplate) {
|
||||
busy.value = true
|
||||
try { await api.updateTemplate(item.id, { hardwareEncodingVerified: !item.hardwareEncodingVerified }); ElMessage.success(item.hardwareEncodingVerified ? '已取消硬件编码验收' : '已确认硬件编码'); await load() }
|
||||
catch (e) { ElMessage.error(errorMessage(e)) } finally { busy.value = false }
|
||||
}
|
||||
function clone(item: ImageTemplate) { templateId.value = item.id; cloneVisible.value = true }
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>镜像模板</h1><p class="subtext">登记 PVE 专用模板,按版本创建新的云桌面</p></div><div><el-button :icon="Refresh" :loading="loading" @click="load()">刷新</el-button><el-button v-if="auth.canAdmin" type="primary" :icon="Plus" @click="openRegister">登记模板</el-button></div></div>
|
||||
<el-alert v-if="error" class="notice" type="error" :title="error" :closable="false" show-icon />
|
||||
<section class="panel" v-loading="loading">
|
||||
<div class="toolbar"><el-input v-model="keyword" placeholder="搜索模板名称 / 版本 / 系统 / VMID" aria-label="搜索模板" clearable /></div>
|
||||
<el-table :data="filtered" empty-text="尚未登记模板。请先在 PVE 制作专用模板,再点击登记模板。">
|
||||
<el-table-column label="模板 / 版本" min-width="200"><template #default="{ row }"><div class="template-title"><SystemIcon :os="row.os" :size="30" /><div><strong>{{ row.name }}</strong><div class="secondary">{{ row.version }} · {{ row.os }}</div></div></div></template></el-table-column>
|
||||
<el-table-column prop="node" label="源节点" min-width="120" /><el-table-column prop="vmid" label="模板 VMID" width="120" />
|
||||
<el-table-column label="状态" min-width="150"><template #default="{ row }"><el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '已启用' : '已停用' }}</el-tag><el-tag v-if="row.hardwareEncodingVerified" type="success" effect="plain" style="margin-left:6px">硬件编码已验收</el-tag><el-tag v-else type="warning" effect="plain" style="margin-left:6px">待验收</el-tag></template></el-table-column>
|
||||
<el-table-column label="最近校验" min-width="180"><template #default="{ row }">{{ new Date(row.validatedAt).toLocaleString('zh-CN') }}</template></el-table-column>
|
||||
<el-table-column v-if="auth.canAdmin" label="操作" min-width="330"><template #default="{ row }"><el-button link type="primary" :disabled="busy || !row.enabled || !row.hardwareEncodingVerified" @click="clone(row)">创建桌面</el-button><el-button link :disabled="busy" @click="update(row, true)">重新验证</el-button><el-button link :disabled="busy" @click="toggleEncoding(row)">{{ row.hardwareEncodingVerified ? '取消编码验收' : '确认硬件编码' }}</el-button><el-button link :disabled="busy" @click="update(row)">{{ row.enabled ? '停用' : '启用' }}</el-button></template></el-table-column>
|
||||
</el-table>
|
||||
<p class="catalog-note">模板登记会校验 PVE 模板标记、磁盘与直通配置。模板修改后需重新验证;停用会阻止新的创建请求。现有业务虚拟机不会自动转换为模板。</p>
|
||||
</section>
|
||||
<el-dialog v-model="visible" title="登记镜像模板" width="560px" :close-on-click-modal="false">
|
||||
<el-alert v-if="discoverError" type="error" :title="discoverError" :closable="false" /><el-alert v-else-if="!busy && !candidates.length" type="info" title="未发现可登记的模板,请先在 PVE 准备专用模板;现有运行桌面不能直接作为模板登记。" :closable="false" />
|
||||
<el-form label-position="top" :disabled="busy"><el-form-item label="PVE 模板"><el-select v-model="vmKey" placeholder="选择发现的模板" filterable @change="choose"><el-option v-for="v in candidates" :key="`${v.node}/${v.vmid}`" :label="`${v.name} · ${v.node} / ${v.vmid}`" :value="`${v.node}/${v.vmid}`" /></el-select></el-form-item><el-form-item label="模板名称"><el-input v-model="form.name" maxlength="80" /></el-form-item><el-form-item label="版本"><el-input v-model="form.version" maxlength="40" /></el-form-item><el-form-item label="操作系统"><el-select v-model="form.os"><el-option v-for="os in ['Windows', 'Ubuntu', '麒麟']" :key="os" :value="os" /></el-select></el-form-item><el-form-item label="模板能力验收"><el-checkbox v-model="form.hardwareEncodingVerified">已验证硬件编码可用(Sunshine 使用 GPU 硬件编码)</el-checkbox><p class="subtext">只有完成硬件编码验收的模板才允许创建新桌面。Windows、Ubuntu 和麒麟均按同一规则处理。</p></el-form-item></el-form>
|
||||
<template #footer><el-button :disabled="busy" @click="visible = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!vmKey || !form.name.trim() || !form.version.trim()" @click="register">校验并登记</el-button></template>
|
||||
</el-dialog>
|
||||
<CloneDesktopDialog v-model="cloneVisible" :template-id="templateId" />
|
||||
</template>
|
||||
<style scoped>
|
||||
.template-title{display:flex;align-items:center;gap:12px}.template-title strong{font-size:13px}.template-title .secondary{font-size:11px;margin-top:5px}.catalog-note{color:var(--vdi-muted);font-size:12px;line-height:1.8;padding:20px}
|
||||
</style>
|
||||
@@ -0,0 +1,88 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Plus, Refresh } from '@element-plus/icons-vue'
|
||||
import { api, allPages, errorMessage, type TerminalPolicy, type TerminalPolicyInput, type PolicyDeployment, type PolicyDeploymentInput, type PolicyResult } from '../api'
|
||||
import { useAuth } from '../stores/auth'
|
||||
const auth = useAuth()
|
||||
const templates = ref<TerminalPolicy[]>([]), deployments = ref<PolicyDeployment[]>([]), states = ref<PolicyResult[]>([]), results = ref<PolicyResult[]>([])
|
||||
const error = ref(''), loading = ref(false), busy = ref(false), tab = ref('templates'), keyword = ref(''), page = ref(1)
|
||||
const createVisible = ref(false), deployVisible = ref(false), selected = ref<PolicyDeployment>(), detailError = ref('')
|
||||
const form = reactive<TerminalPolicyInput>({ name: '', version: '1.0', heartbeatInterval: 30, commandPollInterval: 3, desktopRefreshInterval: 15 })
|
||||
const target = reactive<PolicyDeploymentInput>({ templateId: '', targetMode: 'devices', terminalIds: [], group: '' })
|
||||
const groups = computed(() => [...new Set(states.value.map(s => s.group).filter(Boolean))].sort())
|
||||
const eligible = (s: PolicyResult) => s.enabled && s.registered && s.protocol === 1
|
||||
const targets = computed(() => states.value.filter(s => target.targetMode === 'group' ? s.group === target.group : target.terminalIds?.includes(s.terminalId)))
|
||||
const invalidTargets = computed(() => targets.value.some(s => !eligible(s)))
|
||||
const template = computed(() => templates.value.find(t => t.id === target.templateId))
|
||||
const filtered = computed(() => states.value.filter(s => `${s.terminalName} ${s.group} ${s.templateName}`.toLowerCase().includes(keyword.value.toLowerCase())))
|
||||
const rows = computed(() => filtered.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
const deploymentRows = computed(() => deployments.value.slice((page.value - 1) * 10, page.value * 10))
|
||||
const labels: Record<string, string> = { unconfigured: '未配置', pending: '等待设备应用', applied: '已应用', failed: '应用失败', superseded: '已被新策略替代' }
|
||||
const errors: Record<string, string> = { invalid_policy: '客户端不接受该配置', persist_failed: '设备无法安全保存配置,请检查磁盘和权限', runtime_unavailable: '客户端运行组件未就绪' }
|
||||
const time = (s: string | null) => s ? new Date(s).toLocaleString('zh-CN') : '—'
|
||||
function stateLabel(s: PolicyResult) { return labels[s.status] || s.status }
|
||||
let running = false, detailGeneration = 0, timer: ReturnType<typeof setInterval> | undefined
|
||||
async function load(silent = false) {
|
||||
if (running) return
|
||||
running = true; if (!silent) loading.value = true
|
||||
try {
|
||||
const [t, d, s] = await Promise.all([allPages(api.terminalPolicies), allPages(api.policyDeployments), allPages(api.policyStates)])
|
||||
templates.value = t; deployments.value = d; states.value = s; error.value = ''
|
||||
if (selected.value) await loadResults(selected.value.id)
|
||||
} catch (e) { error.value = errorMessage(e) } finally { running = false; loading.value = false }
|
||||
}
|
||||
async function loadResults(id: string) {
|
||||
const generation = ++detailGeneration
|
||||
try { const data = await allPages(page => api.policyResults(id, page)); if (generation === detailGeneration && selected.value?.id === id) { results.value = data; detailError.value = '' } }
|
||||
catch (e) { if (generation === detailGeneration) detailError.value = errorMessage(e) }
|
||||
}
|
||||
function detail(d: PolicyDeployment) { selected.value = d; results.value = []; detailError.value = ''; void loadResults(d.id) }
|
||||
function create(t?: TerminalPolicy) {
|
||||
Object.assign(form, t ? { name: t.name, version: '', heartbeatInterval: t.heartbeatInterval, commandPollInterval: t.commandPollInterval, desktopRefreshInterval: t.desktopRefreshInterval } : { name: '', version: '1.0', heartbeatInterval: 30, commandPollInterval: 3, desktopRefreshInterval: 15 })
|
||||
createVisible.value = true
|
||||
}
|
||||
async function save() {
|
||||
busy.value = true
|
||||
try { await api.createTerminalPolicy({ ...form }); createVisible.value = false; ElMessage.success('策略版本已保存'); await load() } catch (e) { ElMessage.error(errorMessage(e)) } finally { busy.value = false }
|
||||
}
|
||||
function closeDeployment(done: () => void) { if (!busy.value) done() }
|
||||
let requestKey = '', submitted = ''
|
||||
function deploy(t: TerminalPolicy, ids: string[] = []) { Object.assign(target, { templateId: t.id, targetMode: 'devices', terminalIds: ids, group: '' }); requestKey = crypto.randomUUID(); submitted = ''; deployVisible.value = true }
|
||||
async function dispatch() {
|
||||
if (!template.value || !targets.value.length || invalidTargets.value || busy.value) return
|
||||
const body: PolicyDeploymentInput = target.targetMode === 'group' ? { templateId: target.templateId, targetMode: 'group', group: target.group } : { templateId: target.templateId, targetMode: 'devices', terminalIds: [...(target.terminalIds || [])].sort() }
|
||||
const fingerprint = JSON.stringify(body)
|
||||
busy.value = true
|
||||
try {
|
||||
await ElMessageBox.confirm(`将「${template.value.name} · ${template.value.version}」下发到${target.targetMode === 'group' ? `「${target.group}」分组当前的` : ''} ${targets.value.length} 台终端。离线设备将在恢复联网后应用,最终以设备回执为准。`, '确认下发策略', { type: 'warning', confirmButtonText: '确认下发', cancelButtonText: '取消' })
|
||||
if (submitted && submitted !== fingerprint) requestKey = crypto.randomUUID()
|
||||
submitted = fingerprint
|
||||
const d = await api.deployPolicy(body, requestKey)
|
||||
deployVisible.value = false; tab.value = 'deployments'; page.value = 1; ElMessage.success('下发已登记,等待设备应用'); await load(); detail(d)
|
||||
} catch (e) { if (e !== 'cancel' && e !== 'close') ElMessage.error(errorMessage(e)) } finally { busy.value = false }
|
||||
}
|
||||
function retry(s: PolicyResult) { const t = templates.value.find(t => t.name === s.templateName && t.version === s.templateVersion); if (t) deploy(t, [s.terminalId]) }
|
||||
onMounted(() => { void load(); timer = setInterval(() => { if (!document.hidden) void load(true) }, 5000) })
|
||||
onUnmounted(() => { if (timer) clearInterval(timer); ++detailGeneration })
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>终端策略</h1><p class="subtext">配置有版本,下发有记录,生效以设备回执为准</p></div><div><el-button :icon="Refresh" :loading="loading" @click="load()">刷新</el-button><el-button v-if="auth.canAdmin" type="primary" :icon="Plus" @click="create()">新建策略</el-button></div></div>
|
||||
<el-alert v-if="error" class="notice" type="error" :title="error" :closable="false" />
|
||||
<div class="policy-summary"><section class="panel"><span>策略版本</span><strong>{{ templates.length }}</strong></section><section class="panel"><span>当前已应用</span><strong>{{ states.filter(s => s.status === 'applied').length }}</strong></section><section class="panel"><span>等待设备</span><strong>{{ states.filter(s => s.status === 'pending').length }}</strong></section><section class="panel"><span>应用失败</span><strong>{{ states.filter(s => s.status === 'failed').length }}</strong></section></div>
|
||||
<section class="panel" v-loading="loading">
|
||||
<el-tabs v-model="tab" @tab-change="page = 1"><el-tab-pane label="配置模板" name="templates" /><el-tab-pane label="下发记录" name="deployments" /><el-tab-pane label="设备结果" name="states" /></el-tabs>
|
||||
<template v-if="tab === 'templates'">
|
||||
<p class="policy-note">每个版本保存后固定。调整配置可复制为新版本;恢复旧配置时,重新下发对应版本。</p>
|
||||
<el-table :data="templates" empty-text="尚无策略,创建模板后可下发到设备或分组"><el-table-column label="策略 / 版本" min-width="180"><template #default="{ row }"><strong>{{ row.name }}</strong><div class="secondary">{{ row.version }}</div></template></el-table-column><el-table-column label="心跳间隔" min-width="115"><template #default="{ row }">{{ row.heartbeatInterval }} 秒</template></el-table-column><el-table-column label="命令检查" min-width="115"><template #default="{ row }">{{ row.commandPollInterval }} 秒</template></el-table-column><el-table-column label="桌面列表刷新" min-width="140"><template #default="{ row }">{{ row.desktopRefreshInterval }} 秒</template></el-table-column><el-table-column label="创建时间" min-width="175"><template #default="{ row }">{{ time(row.createdAt) }}</template></el-table-column><el-table-column v-if="auth.canAdmin" label="操作" min-width="180"><template #default="{ row }"><el-button link type="primary" @click="deploy(row)">下发</el-button><el-button link @click="create(row)">复制新版本</el-button></template></el-table-column></el-table>
|
||||
</template>
|
||||
<template v-else-if="tab === 'deployments'"><el-table :data="deploymentRows" empty-text="尚无下发记录"><el-table-column label="策略版本" min-width="190"><template #default="{ row }">{{ row.templateName }} · {{ row.templateVersion }}</template></el-table-column><el-table-column label="设备数" prop="targetCount" width="100" /><el-table-column label="操作者" prop="actor" min-width="110" /><el-table-column label="提交时间" min-width="180"><template #default="{ row }">{{ time(row.createdAt) }}</template></el-table-column><el-table-column label="操作" width="130"><template #default="{ row }"><el-button link type="primary" @click="detail(row)">查看结果</el-button></template></el-table-column></el-table><el-pagination v-model:current-page="page" :total="deployments.length" :page-size="10" layout="total, prev, pager, next" /></template>
|
||||
<template v-else><div class="toolbar"><el-input v-model="keyword" aria-label="搜索策略设备" placeholder="搜索设备 / 分组 / 策略" clearable @input="page = 1" /></div><el-table :data="rows" empty-text="没有符合条件的终端"><el-table-column label="终端 / 分组" min-width="160"><template #default="{ row }"><strong>{{ row.terminalName }}</strong><div class="secondary">{{ row.group || '未分组' }} · {{ row.online && row.enabled ? '在线' : '离线' }}</div></template></el-table-column><el-table-column label="策略能力" min-width="130"><template #default="{ row }">{{ !row.enabled ? '设备已停用' : !row.registered ? '等待激活' : row.protocol === 1 ? '支持策略' : '需更新客户端' }}</template></el-table-column><el-table-column label="期望策略" min-width="170"><template #default="{ row }">{{ row.templateName ? `${row.templateName} · ${row.templateVersion}` : '默认配置' }}<div class="secondary">配置版本 {{ row.configVersion }}</div></template></el-table-column><el-table-column label="应用结果" min-width="155"><template #default="{ row }"><el-tag :type="row.status === 'applied' ? 'success' : row.status === 'failed' ? 'danger' : 'info'">{{ stateLabel(row) }}</el-tag><div v-if="row.status === 'pending' && !row.online" class="secondary">等待设备恢复联网</div></template></el-table-column><el-table-column label="最近回执 / 原因" min-width="215"><template #default="{ row }">{{ time(row.acknowledgedAt) }}<div v-if="row.errorCode" class="secondary">{{ errors[row.errorCode] || row.errorCode }}</div></template></el-table-column><el-table-column v-if="auth.canAdmin" label="操作" width="120"><template #default="{ row }"><el-button v-if="row.deploymentId" link type="primary" :disabled="!eligible(row)" @click="retry(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" /></template>
|
||||
</section>
|
||||
<el-dialog v-model="createVisible" title="新建终端策略版本" width="550px" :close-on-click-modal="false"><el-form label-position="top" :disabled="busy"><el-form-item label="策略名称"><el-input v-model="form.name" aria-label="策略名称" maxlength="80" /></el-form-item><el-form-item label="版本标记"><el-input v-model="form.version" aria-label="策略版本" maxlength="40" placeholder="例如 1.0" /></el-form-item><el-form-item label="心跳间隔(15~60 秒)"><el-input-number v-model="form.heartbeatInterval" aria-label="心跳间隔" :min="15" :max="60" :precision="0" /></el-form-item><el-form-item label="远程命令检查间隔(3~30 秒)"><el-input-number v-model="form.commandPollInterval" aria-label="命令检查间隔" :min="3" :max="30" :precision="0" /></el-form-item><el-form-item label="桌面列表刷新间隔(5~120 秒)"><el-input-number v-model="form.desktopRefreshInterval" aria-label="桌面列表刷新间隔" :min="5" :max="120" :precision="0" /></el-form-item></el-form><p class="subtext">间隔越短,状态更新和命令响应越快。桌面列表仅在选择页刷新。</p><template #footer><el-button :disabled="busy" @click="createVisible = false">取消</el-button><el-button type="primary" :disabled="!form.name.trim() || !form.version.trim()" :loading="busy" @click="save">保存策略版本</el-button></template></el-dialog>
|
||||
<el-dialog v-model="deployVisible" title="下发终端策略" width="600px" :close-on-click-modal="false" :before-close="closeDeployment"><el-form label-position="top" :disabled="busy"><el-form-item label="策略版本"><el-select v-model="target.templateId" aria-label="下发策略版本"><el-option v-for="t in templates" :key="t.id" :value="t.id" :label="`${t.name} · ${t.version}`" /></el-select></el-form-item><div v-if="template" class="policy-preview">心跳 {{ template.heartbeatInterval }} 秒 · 命令检查 {{ template.commandPollInterval }} 秒 · 列表刷新 {{ template.desktopRefreshInterval }} 秒</div><el-form-item label="下发范围"><el-radio-group v-model="target.targetMode"><el-radio value="devices">指定设备</el-radio><el-radio value="group">指定分组</el-radio></el-radio-group></el-form-item><el-form-item v-if="target.targetMode === 'devices'" label="选择终端"><el-select v-model="target.terminalIds" multiple filterable aria-label="选择策略终端"><el-option v-for="s in states" :key="s.terminalId" :value="s.terminalId" :disabled="!eligible(s)" :label="`${s.terminalName} · ${s.group || '未分组'}${!eligible(s) ? '(暂不支持)' : !s.online ? '(离线)' : ''}`" /></el-select></el-form-item><el-form-item v-else label="选择分组"><el-select v-model="target.group" aria-label="选择策略分组"><el-option v-for="g in groups" :key="g" :value="g" :label="g" /></el-select></el-form-item></el-form><el-alert v-if="invalidTargets" type="warning" :closable="false" title="所选范围包含停用、未激活或旧客户端设备,请先处理或改为指定设备。" /><p class="subtext">本次 {{ targets.length }} 台。按提交时的分组成员创建下发记录,新加入分组的设备需另行下发。设备每 15 秒检查策略,离线时等待恢复联网。</p><template #footer><el-button :disabled="busy" @click="deployVisible = false">取消</el-button><el-button type="primary" :disabled="!template || !targets.length || targets.length > 200 || invalidTargets" :loading="busy" @click="dispatch">提交下发</el-button></template></el-dialog>
|
||||
<el-drawer :model-value="!!selected" title="策略下发结果" size="650px" @close="selected = undefined; ++detailGeneration"><template v-if="selected"><h2>{{ selected.templateName }} · {{ selected.templateVersion }}</h2><p class="subtext">{{ selected.actor }} · {{ time(selected.createdAt) }} · {{ selected.targetCount }} 台</p><p class="mono secondary">{{ selected.id }}</p><el-alert v-if="detailError" type="error" :closable="false" :title="detailError" /><el-table :data="results" empty-text="暂无结果"><el-table-column label="终端" prop="terminalName" min-width="130" /><el-table-column label="配置版本" prop="configVersion" width="95" /><el-table-column label="应用状态" min-width="160"><template #default="{ row }"><el-tag :type="row.status === 'applied' ? 'success' : row.status === 'failed' ? 'danger' : 'info'">{{ stateLabel(row) }}</el-tag><div v-if="row.status === 'pending' && !row.online" class="secondary">离线等待</div><div v-if="row.errorCode" class="secondary">{{ errors[row.errorCode] || row.errorCode }}</div></template></el-table-column><el-table-column label="设备回执" min-width="170"><template #default="{ row }">{{ time(row.acknowledgedAt) }}</template></el-table-column></el-table><p class="subtext">本页保留当次下发结果。当前期望版本请到「设备结果」查看。应用失败的设备每次检查策略时会尝试恢复,也可以重新下发。</p></template></el-drawer>
|
||||
</template>
|
||||
<style scoped>
|
||||
.policy-summary{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;margin-bottom:20px}.policy-summary section{padding:20px}.policy-summary span{display:block;color:var(--vdi-muted);font-size:12px}.policy-summary strong{display:block;font-size:28px;margin-top:10px}.policy-note{padding:4px 20px 12px;color:var(--vdi-muted);font-size:12px}.secondary{font-size:11px;color:var(--vdi-muted);margin-top:6px;overflow-wrap:anywhere}.policy-preview{padding:14px;border-radius:10px;background:var(--vdi-panel-2);font-size:12px;color:var(--vdi-muted);margin-bottom:20px}.el-dialog .subtext,.el-drawer .subtext{margin:18px 0;line-height:1.8}h2{font-size:19px}.el-select{width:100%}@media(max-width:600px){.policy-summary{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.policy-summary section{padding:15px}.policy-summary strong{font-size:24px}}
|
||||
</style>
|
||||
@@ -0,0 +1,53 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } 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 CsvImportDialog from '../components/CsvImportDialog.vue'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
import TerminalMetrics from '../components/TerminalMetrics.vue'
|
||||
const auth = useAuth(), data = usePlatform(), { busy, run, confirm } = useAction()
|
||||
const csvVisible = ref(false), metricsVisible = ref(false)
|
||||
const keyword = ref(''), status = ref(''), page = ref(1), selectedId = ref(''), createVisible = ref(false), secret = ref(''), activationVisible = ref(false)
|
||||
const editVisible = ref(false), editingId = ref(''), activationSN = ref('')
|
||||
const editForm = reactive({ name: '', group: '' })
|
||||
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))
|
||||
watch(selectedId, () => { metricsVisible.value = false })
|
||||
const disabled = (t: Terminal) => t.enabled === false || t.status === 'disabled'
|
||||
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; activationSN.value = form.sn }, '终端已登记')) { createVisible.value = false; activationVisible.value = true; form.sn = ''; form.name = ''; form.group = '' } }
|
||||
function edit(t: Terminal) { editingId.value = t.id; Object.assign(editForm, { name: t.name, group: t.group }); editVisible.value = true }
|
||||
async function saveTerminal() { if (!editForm.name.trim() || busy.value) return; if (await run(() => api.updateTerminal(editingId.value, editForm), '终端资料已保存')) editVisible.value = false }
|
||||
async function disable(t: Terminal) {
|
||||
if (!await confirm(`停用终端 · ${t.name}`, '旧设备令牌和激活密钥将失效,不能再访问平台。重新使用需生成并配置新的激活信息。')) return
|
||||
await run(() => api.disableTerminal(t.id), '终端已停用,旧凭据已撤销')
|
||||
}
|
||||
async function reactivate(t: Terminal) {
|
||||
if (!await confirm(`重新激活 · ${t.name}`, '旧令牌、激活密钥和连接票据将失效。新激活密钥只显示一次,需要由设备管理员更新设备配置,不能自动恢复旧身份。')) return
|
||||
if (await run(async () => { const r = await api.reactivateTerminal(t.id); secret.value = r.activationSecret; activationSN.value = t.sn }, '已生成新的激活信息')) activationVisible.value = true
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>终端管理</h1><p class="subtext">设备身份、在线心跳与远程命令</p></div><div v-if="auth.canAdmin" class="heading-actions"><el-button @click="csvVisible = true">批量导入</el-button><el-button type="primary" @click="createVisible = true">登记终端</el-button></div></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-option label="停用" value="disabled" /></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="280"><template #default="{ row }"><div class="actions"><el-button link type="primary" @click="selectedId = row.id">详情</el-button><el-button v-if="auth.canOperate && !disabled(row)" link type="primary" :disabled="busy || pending(row.id)" @click="command(row, 'reboot')">重启盒子</el-button><el-button v-if="auth.canAdmin" link type="primary" :disabled="busy" @click="edit(row)">编辑资料</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><router-link v-if="auth.canOperate" :to="{ path: '/diagnostics', query: { targetType: 'terminal', targetId: selected.id } }">查看此设备日志与诊断 →</router-link><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><el-button style="margin-top:18px" @click="metricsVisible = !metricsVisible">{{ metricsVisible ? '收起运行指标' : '查看运行指标' }}</el-button><TerminalMetrics v-if="metricsVisible" :terminal-id="selected.id" /><p class="subtext" style="margin:20px 0">重置会话只结束终端连接,不会还原或关机云桌面。网络 RTT 不等于整体输入延迟。</p><div class="actions" v-if="auth.canOperate && !disabled(selected)"><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><div v-if="auth.canAdmin" class="lifecycle-actions"><h3>设备管理</h3><p class="subtext">停用或重新激活会撤销旧凭据。请先结束活动会话并处理未完成命令;重新激活后需在设备上配置新密钥。</p><div class="actions"><el-button :disabled="busy" @click="edit(selected)">编辑资料</el-button><el-button v-if="!disabled(selected)" type="danger" plain :disabled="busy || pending(selected.id) || !!selected.sessionDesktopId" @click="disable(selected)">停用设备</el-button><el-button :disabled="busy || pending(selected.id) || !!selected.sessionDesktopId" @click="reactivate(selected)">重新激活</el-button></div></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="editVisible" title="编辑终端资料" width="480px" :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy"><el-form label-position="top" :disabled="busy" @submit.prevent="saveTerminal"><el-form-item label="终端名称"><el-input v-model="editForm.name" maxlength="80" aria-label="编辑终端名称" /></el-form-item><el-form-item label="分组"><el-input v-model="editForm.group" maxlength="80" aria-label="编辑终端分组" /></el-form-item></el-form><template #footer><el-button :disabled="busy" @click="editVisible = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!editForm.name.trim()" @click="saveTerminal">保存终端资料</el-button></template></el-dialog>
|
||||
<el-dialog v-model="activationVisible" title="终端激活信息" width="530px" @closed="secret = ''"><p class="subtext" style="margin-bottom:16px">激活密钥只在此处显示一次,交给设备管理员配置。设备注册后即失效。</p><p class="subtext" style="margin-bottom:12px">设备 SN:{{ activationSN }}</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>
|
||||
<CsvImportDialog v-model="csvVisible" kind="terminals" @completed="data.refresh" />
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.heading-actions{display:flex;gap:10px;flex-wrap:wrap}.heading-actions .el-button{margin-left:0}
|
||||
.lifecycle-actions{margin-top:28px;padding-top:24px;border-top:1px solid var(--vdi-border)}.lifecycle-actions h3{font-size:14px}.lifecycle-actions p{margin:12px 0 18px;line-height:1.8}
|
||||
</style>
|
||||
@@ -0,0 +1,55 @@
|
||||
<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 CsvImportDialog from '../components/CsvImportDialog.vue'
|
||||
import StatusTag from '../components/StatusTag.vue'
|
||||
const auth = useAuth(), data = usePlatform(), { busy, run, confirm } = useAction()
|
||||
const csvVisible = ref(false), csvKind = ref<'users' | 'bindings'>('users')
|
||||
const keyword = ref(''), page = ref(1), createVisible = ref(false), bindingVisible = ref(false), selectedId = ref('')
|
||||
const profileVisible = ref(false), profileId = ref(''), profileUsername = ref(''), checked = ref<User[]>([])
|
||||
const profile = reactive({ displayName: '', enabled: true })
|
||||
const batchVisible = ref(false), batchUsers = ref<User[]>([])
|
||||
const batch = reactive({ action: 'grant' as 'grant' | 'revoke', desktopIds: [] as string[] })
|
||||
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 (busy.value) return; if (!await confirm('保存员工授权', '更新关联终端、员工状态和所选桌面。未消费的旧连接票据将失效;已有串流不会被强制中断。')) return; 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)
|
||||
function editProfile(u: User) { profileId.value = u.id; profileUsername.value = u.username; Object.assign(profile, { displayName: u.displayName, enabled: u.enabled }); profileVisible.value = true }
|
||||
async function saveProfile() {
|
||||
if (!profile.displayName.trim() || busy.value) return
|
||||
const existing = data.users.find(u => u.id === profileId.value)
|
||||
if (existing?.enabled !== profile.enabled && !await confirm(profile.enabled ? '启用员工' : '停用员工', '状态变更将作废该员工未消费的连接票据。停用阻止后续连接,保留授权关系和已有串流。')) return
|
||||
if (await run(() => api.updateUser(profileId.value, profile), '员工资料已保存')) profileVisible.value = false
|
||||
}
|
||||
function selectUsers(users: User[]) { checked.value = users }
|
||||
function openBatch() { batchUsers.value = [...checked.value]; batch.action = 'grant'; batch.desktopIds = []; batchVisible.value = true }
|
||||
async function saveBatch() {
|
||||
if (!batchUsers.value.length || !batch.desktopIds.length || busy.value) return
|
||||
const action = batch.action === 'grant' ? '分配' : '撤销'
|
||||
if (!await confirm(`批量${action}桌面`, `将为 ${batchUsers.value.length} 位员工${action}所选 ${batch.desktopIds.length} 台桌面的授权。其他授权保留,已有串流不会被强制中断。`)) return
|
||||
if (await run(() => api.batchBindings({ userIds: batchUsers.value.map(u => u.id), desktopIds: batch.desktopIds, action: batch.action }), `已批量${action}桌面授权`)) batchVisible.value = false
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="page-heading"><div><h1>员工与授权</h1><p class="subtext">管理员工资料、终端关联和桌面使用授权</p></div><div v-if="auth.canAdmin" class="actions"><el-button @click="csvKind = 'users'; csvVisible = true">导入员工</el-button><el-button @click="csvKind = 'bindings'; csvVisible = true">导入授权</el-button><el-button :disabled="!checked.length || busy" @click="openBatch">批量授权<span v-if="checked.length">({{ checked.length }})</span></el-button><el-button type="primary" @click="createVisible = true">新建员工</el-button></div></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" row-key="id" empty-text="暂无员工" @selection-change="selectUsers"><el-table-column v-if="auth.canAdmin" type="selection" width="44" /><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="220"><template #default="{ row }"><div class="row-actions"><el-button link type="primary" :disabled="busy" @click="editProfile(row)">编辑资料</el-button><el-button link type="primary" :disabled="busy" @click="edit(row)">编辑授权</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><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="profileVisible" title="编辑员工资料" width="480px" :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy"><el-form label-position="top" :disabled="busy" @submit.prevent="saveProfile"><el-form-item label="员工账号(固定)"><el-input :model-value="profileUsername" disabled readonly /></el-form-item><el-form-item label="姓名"><el-input v-model="profile.displayName" maxlength="80" aria-label="编辑员工姓名" /></el-form-item><el-form-item label="员工状态"><el-switch v-model="profile.enabled" active-text="启用" inactive-text="停用" aria-label="编辑员工启用状态" /></el-form-item><p class="subtext">员工账号用于授权关系,创建后不能修改;停用保留桌面授权,阻止后续连接。</p></el-form><template #footer><el-button :disabled="busy" @click="profileVisible = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!profile.displayName.trim()" @click="saveProfile">保存员工资料</el-button></template></el-dialog>
|
||||
<el-dialog v-model="batchVisible" title="批量桌面授权" width="560px" :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy"><el-form label-position="top" :disabled="busy"><el-form-item label="操作方式"><el-radio-group v-model="batch.action" aria-label="批量授权操作"><el-radio-button value="grant">追加分配</el-radio-button><el-radio-button value="revoke">撤销指定</el-radio-button></el-radio-group></el-form-item><el-form-item :label="`目标员工(${batchUsers.length} 位)`"><div class="batch-users"><el-tag v-for="u in batchUsers" :key="u.id" type="info">{{ u.displayName }} / {{ u.username }}</el-tag></div></el-form-item><el-form-item label="所选桌面"><el-checkbox-group v-model="batch.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><p class="subtext">只追加或撤销所选桌面,保留其他授权;停用员工仍需启用后才能连接。每次最多 100 位员工和 100 台桌面。</p></el-form><template #footer><el-button :disabled="busy" @click="batchVisible = false">取消</el-button><el-button type="primary" :loading="busy" :disabled="!batchUsers.length || !batch.desktopIds.length || batchUsers.length > 100" @click="saveBatch">提交批量授权</el-button></template></el-dialog>
|
||||
<el-dialog v-model="bindingVisible" title="编辑桌面授权" width="540px" :close-on-click-modal="false" :show-close="!busy" :close-on-press-escape="!busy"><el-form label-position="top" @submit.prevent="save" :disabled="busy"><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) || (t.enabled === false && t.id !== binding.terminalId)" /></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>
|
||||
<CsvImportDialog v-model="csvVisible" :kind="csvKind" @completed="data.refresh" />
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.row-actions{display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
|
||||
.batch-users{display:flex;flex-wrap:wrap;gap:8px;max-height:140px;overflow:auto}
|
||||
</style>
|
||||
Loaded 100 of 1168 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user