Compare commits

...

28 Commits

Author SHA1 Message Date
zhanxi d5677b5109 merge(chat): 增加对白与叙述排版预览 2026-10-27 14:21:15 +00:00
湛兮 5dc709865a feat(content): 增加对白与叙述排版预览
- DigitalMessageText.vue: 为角色预览与聊天记录提供统一的受限文本展示
- content.vue: 增加首次问候、备用开场、示例对白的实时预览与格式说明
- users.vue: 按相同规则展示角色聊天记录,保留用户纯文本
- digital-message-format.ts、tests、README.md: 同步前台格式实现、兼容用例与目录说明
2026-10-27 22:19:16 +08:00
zhanxi 9b10b6b4c2 merge(nsfw): 发布登录账号成人内容偏好
合入已验证的 NSFW 账号偏好改动,游客登录限制保持不变。
2026-10-27 12:39:18 +00:00
湛兮 98ddd137e0 feat(nsfw): 支持管理 C 端账号成人内容偏好
- src/api/access.ts: 补充 C 端账号 NSFW 偏好字段与中文注释
- src/views/digital/users.vue: 展示开关状态,创建默认开启,编辑可保存账号选择
- README.md: 说明前后台共用偏好及配套发布要求
2026-10-27 20:18:16 +08:00
zhanxi 48aac171dd Merge pull request 'feat(users): 独立 C 端账号并提供聊天记录管理' (#18) from feature/env-pipeline-split into master 2026-10-27 10:56:50 +00:00
湛兮 0b7c1cba24 feat(users): 新增独立用户与聊天记录管理
- users.vue: 支持开户、停用、重置密码和按会话查看原始消息
- digital 路由与接口: 区分用户管理和实验用户分组,同步教程与文档
2026-10-27 18:56:11 +08:00
zhanxi 643f1b76b8 Merge pull request 'fix(guide): 固定目录并同步阅读章节高亮' (#16) from feature/env-pipeline-split into master 2026-10-27 10:15:52 +00:00
湛兮 4c35e50270 fix(guide): 固定目录并同步阅读章节高亮
- 目录与正文独立滚动,滚轮和目录定位均同步当前章节高亮

- 按截图真实比例预留空间,避免懒加载后定位偏移,补充使用说明
2026-10-27 18:15:31 +08:00
zhanxi 3e78e79971 Merge pull request 'feat(experiments): 优化用户分组管理与指定说明' (#14) from feature/env-pipeline-split into master 2026-10-27 09:15:22 +00:00
湛兮 41bf7d8bae feat(experiments): 优化用户分组管理与指定说明
- experiment-users.vue: 分离预计分组与实际入组,新增查找指定入口并明确人群限制及有效期状态

- docs/experiments 与 public/guides: 同步用户分组教程、原始截图和编号标注

- README.md: 更新用户分组入口与真实接入边界说明
2026-10-27 17:14:51 +08:00
zhanxi c93acad3d9 Merge pull request 'feat(experiments): 发布完整截图教程与分组规则说明' (#12) from feature/env-pipeline-split into master 2026-10-27 08:14:35 +00:00
湛兮 c406f8c127 feat(experiments): 发布完整截图教程与分组规则说明
- 操作指南改为带目录和图片放大的二级教程页面,完整覆盖实验生命周期
- 用隔离演示数据拍摄14张实际组件截图,生成编号箭头标注与共享内容README
- 标明稳定分组算法与比例区间,修正比例输入提交时的回显同步
- 同步路由、项目目录和教程资源一致性校验脚本
2026-10-27 16:13:49 +08:00
zhanxi 0cd7ed078e Merge pull request 'feat(experiments): 发布多组方案配置界面' (#10) from feature/env-pipeline-split into master 2026-10-27 07:15:53 +00:00
湛兮 df7b9a0cb3 feat(experiments): 重设计多组比例与返回值配置
- 方案使用动态分组表,支持添加删除、互补比例、平均分配与合计校验
- 移除默认方案,用户管理与结束实验按实际分组展示
- 固定弹窗标题和操作区并同步多组说明
2026-10-27 15:15:21 +08:00
zhanxi c9dcfa1975 Merge pull request 'fix(experiments): 移除预置实验提示和 UI 默认选择' (#8) from feature/env-pipeline-split into master 2026-10-27 06:43:16 +00:00
湛兮 afad5507a6 fix(experiments): 移除预置类型提示与默认选择
- 实验类型统一展示真实接入状态
- 创建方案不预选 UI 类型,操作指南改为通用手动验收流程
2026-10-27 14:42:07 +08:00
zhanxi 9d9794848b fix(admin): 隐藏内部滚动条并同步预设编排规则
已完成三端构建、规则与真实浏览器链路验收,统一按同一版本发布。
2026-10-27 05:08:32 +00:00
湛兮 703237469e fix(admin): 统一隐藏滚动条并同步预设编辑规则
- 后台滚动:隐藏原生和Element Plus自绘轨道,表格弹窗与下拉框保留滚动

- Grok业务改动:预设预算下限同步6000,说明统一方案快照和下架回退行为

- 文档与验证:同步交互约束,类型检查样式检查和生产构建通过
2026-10-27 12:54:52 +08:00
zhanxi f9abc12853 feat(experiments): 发布实验类型与用户管理拆分
已完成双轮review与测试环境验证,沿用现有部署链路。
2026-10-27 03:47:08 +00:00
湛兮 db3fd9bee1 feat(experiments): 拆分实验类型测试方案与用户管理入口
- 实验类型:新增独立创建、数据格式、默认值、调用示例和接入验收页

- 测试方案:按类型编辑 A/B 返回值,统一百分比并保留生命周期和效果审计

- 用户管理:新增分页查人、方案分组预览、人工指定和恢复自动分组

- 文档:同步菜单与组件职责,移除固定业务接入点场景弹窗
2026-10-27 11:40:28 +08:00
zhanxi 043e6d0e36 feat(experiments): 发布场景管理与百分比配置
已完成双轮review与测试环境验证,沿用现有部署链路。
2026-10-27 03:08:59 +00:00
湛兮 a49101b790 feat(experiments): 增加仅自己验收的全流程操作指引
提供从建场景、启动、指定账号对照到正式实验和结论推广的说明;示例预填100%流量,要求选择入组账号并明确草稿不生效。
2026-10-27 11:05:46 +08:00
湛兮 9aa57d0b80 fix(experiments): 使用百分比输入并补齐场景管理入口
输入50表示50%,保留0.01%精度且不改变既有分组配置;独立管理场景并标注预置或后台创建来源,创建实验使用动态场景列表。
2026-10-27 11:02:00 +08:00
zhanxi 5c167f5ed3 fix(ui): 发布星港图标更新
已完成双轮review与测试环境验证,沿用现有部署链路。
2026-10-27 02:46:43 +00:00
湛兮 18921a039d fix(ui): 重设计星港标签页图标与品牌标识
采用对话气泡与星芒图形,替换模板favicon并补齐多尺寸图标;版本化资源路径刷新浏览器缓存。
2026-10-27 10:44:43 +08:00
zhanxi 9ae40866e4 feat: 发布星港数字人项目
已完成双轮review与测试环境验证,沿用现有部署链路。
2026-10-27 02:28:17 +00:00
湛兮 44c4bb706b fix(ci): 补齐pnpm工作区根包声明 2026-10-27 10:26:41 +08:00
湛兮 a611045db2 feat(digital): 新增数字人内容库和实验运营后台
数字人内容库支持角色、世界书和预设管理;账号实验中心覆盖生命周期、指定用户、分组解释、漏斗和审计;更新星港品牌与默认导航,保留原兼容路由。
2026-10-27 10:25:51 +08:00
59 changed files with 5926 additions and 75 deletions
+59 -4
View File
@@ -1,6 +1,6 @@
# role-admin
门店员工权限管理后台,基于 `pure-admin-thin` 精简模板二次开发。当前业务聚焦门店、角色、员工三类基础数据管理,并通过 Vite 代理对接本地 `access-manage` 后端服务。
星港数字人运营后台,基于现有 Vue 3 / Element Plus 管理端改造,角色、世界书、预设和账号实验统一由 `access-manage` 提供服务。原门店功能保留为兼容路由,默认进入数字人内容库。
## 技术栈
@@ -46,7 +46,11 @@ http://localhost:8848/
## 目录说明
```text
.
├── docs/experiments/ # 教程README、共享内容、原始截图与标注坐标
├── public/guides/experiments/ # 可放大的编号箭头SVG截图
├── scripts/build-experiment-guide.mjs # 生成与核对图文教程
├── .agents/ # 当前项目 Agent skill 索引与中文提交、注释同步规则
├── .codex/skills/ # 旧版仓库内协作 skill,保留 README 同步规则
├── .husky/ # Git hooks,提交前执行 lint-staged,提交信息走 commitlint
@@ -58,7 +62,7 @@ http://localhost:8848/
├── src/ # 前端源码
│ ├── api/ # HTTP API 封装,业务接口集中在 access.ts
│ ├── assets/ # 图片、SVG、iconfont 等静态资源
│ ├── components/ # 模板沉淀的通用组件
│ ├── components/ # 通用组件,DigitalMessageText.vue 提供对白/叙述预览与聊天记录展示
│ ├── config/ # 读取 public/platform-config.json 的运行时配置
│ ├── directives/ # 自定义指令,如权限、复制、长按、波纹
│ ├── layout/ # 后台布局、菜单、标签页、导航栏与布局 hooks
@@ -66,9 +70,12 @@ http://localhost:8848/
│ ├── router/ # 静态路由、剩余路由、路由实例与守卫
│ ├── store/ # Pinia store,含用户、权限、标签页、主题等模块
│ ├── style/ # 全局样式、主题、暗色模式、侧边栏和过渡样式
│ ├── utils/ # 鉴权、HTTP、缓存、消息、进度条、树处理等工具
│ └── views/ # 页面视图,当前业务页在 employees、roles、stores、permissions 和员工工作台运营模块
│ ├── utils/ # 鉴权、HTTP、缓存及 digital-message-format.ts 受限文本解析
│ └── views/
│ ├── digital/ # 内容库、实验类型、测试方案和用户分组
│ └── ... # 原门店与员工业务兼容页面
├── types/ # 全局类型声明、组件声明、路由声明和 Vue shim
├── tests/ # 数字人对白/叙述格式回归,与 role-user 使用相同用例
├── AGENTS.md # Codex/Agent 入口规则,转到 RTK.md 并登记本地 skill
├── RTK.md # 本仓库协作规则与 README 同步要求
├── Dockerfile # 容器构建入口
@@ -205,3 +212,51 @@ http://localhost:8848/
pnpm typecheck
pnpm build
```
## 数字人运营
角色「人格与开场」提供对白/叙述格式说明和首次问候、示例对白、其他开场的实时预览,预览替换角色/用户占位符但不修改原文。生成预设始终遵守系统统一排版:`*叙述*` 与 `“对白”`,切换时空一行。用户管理的聊天记录也使用 `DigitalMessageText.vue`,用户原文保持纯文本,角色消息兼容旧括号与引号。
`src/utils/digital-message-format.ts` 与 `role-user/src/lib/digital-message-format.ts` 保持同一实现和用例,两仓独立构建。所有内容通过文本节点展示,不使用 HTML 注入。执行 `node --experimental-strip-types --test tests/*.test.mjs` 验证协议兼容。
- `src/views/digital/content.vue`:角色卡、世界书、预设,草稿/发布/下架,JSON 导入导出。
- `src/views/digital/experiments.vue`:测试方案的类型选择、A/B 返回值、百分比、人群、生命周期、效果和审计。
- `src/views/digital/experiment-types.vue`:类型创建、默认值契约、来源、调用示例与接入验收。
- `src/views/digital/experiment-users.vue`:按方案搜索真实账号,区分预计分组、实际入组和手动指定,保留有效期并解释目标人群限制。
- `src/views/digital/experiment-value.vue`:开关/数字/字符串/JSON 类型编辑器。
- `src/router/modules/digital.ts`:数字人菜单,只有超级管理员可见;接口仍集中在 `src/api/access.ts`,后端独立验证权限。
- 保留既有员工管理模块和数据。沿用原 Vite 构建、域名与 Jenkins 发布。
管理端站内封面从 H5/Web 域名读取,可通过 `VITE_ROLE_USER_BASE_URL` 覆盖;默认按本地、develop、production 环境分别选择 localhost:3210、dev.mrzhan.top、mrzhan.top。
标签页图标采用 `public/stellar-icon-v2.svg`,同时提供多尺寸 `favicon.ico`、180/192/512 PNG,覆盖浏览器、Apple 主屏幕和 PWA。版本化资源路径用于刷新旧图标缓存。
「实验类型」「测试方案」「实验用户分组」是独立菜单。新类型填写自己的稳定标识与数据契约,先接入应用、收到实际调用并人工确认验收,再启动方案;未接入类型可存草稿。系统不预置 UI/对话类型;自建类型需要真实前台接入,不再使用固定业务功能的场景下拉框。方案行可直接跳转该方案的用户管理,用户预览不写分组、不记曝光,人工指定有原因、时效和审计。前台只消费决策。
比例统一按百分比输入,50代表50%,保留0.01%精度;既有用户分组保持不变。
后台统一隐藏原生及 Element Plus 自绘内部滚动条;表格、弹窗、抽屉和下拉选项仍支持触摸、鼠标和键盘滚动。叙事预设编辑与后端预算、下架回退及方案快照行为保持一致。
实验方案分组支持 A~Z(最多26组),每组自行设置返回值和比例,合计必须100%。两组比例自动互补,多组显示总和并支持平均分配、补足剩余;0%组保留配置供人工验收。不再提供默认方案选择,未入组及暂停时使用类型默认返回值。用户管理按当前方案动态展示可指定的组,结束实验也可选择任意已配置组。
## 实验图文操作指南
测试方案页的「操作指南」进入二级页面 `/digital/experiments/guide`(`src/views/digital/experiment-guide.vue`),不再弹出简短说明。页面有章节目录、14张可放大的编号箭头截图和返回业务入口,覆盖类型创建、应用接入验收、仅自己验收、分组算法、启动、人工指定、正式分流、效果审计、暂停恢复及结束保留组。
项目内教程见 [完整实验教程](docs/experiments/README.md)。内容源为 `docs/experiments/guide.json`,网页直接读取同一文件;`screenshots.json` 保存标注坐标,原图只含隔离演示账号与状态。图中演示调用和统计不代表真实生产验收。
- 更新图文内容或截图后:`node scripts/build-experiment-guide.mjs`。
- 发布前验证文档、标注与源码一致:`node scripts/build-experiment-guide.mjs --check`。
- 原始截图及标注后的SVG都纳入版本管理,维护时保留“隔离演示”说明,不能用伪造回执替代真实接入。
用户分组管理提供独立的方案概况、用户查找和指定入口。列表覆盖全部真实账号,不把只读预计结果称为实际入组;手动指定明确显示草稿待生效、人群不符、已过期等状态。不符合目标人群的账号须明确选择“作为测试账号加入”,不修改其他用户的人群范围。取消指定或到期后沿用原自动分组,否则按当前方案规则计算。
教程目录固定在阅读区左侧,右侧正文独立滚动并自动高亮当前章节;点击目录平滑定位,目录过长时会自动滚动到当前项。窄屏将目录置于正文上方,保留正文滚动与章节同步。
### C 端用户管理
`src/views/digital/users.vue` 对应 `/digital/users`,用于创建独立 C 端账号、搜索用户、修改昵称/状态、重置密码,以及按用户查看数字人会话和原始消息。账号由后台开通,无公开注册;与管理员/员工账号分别鉴权,重置 C 端密码不影响后台。停用保留聊天记录。
`src/api/access.ts` 定义 C 端用户、会话和消息响应类型。消息记录第1页为最新内容,每页按发送顺序展示,支持刷新、分页和生成状态查看。原实验账号页面 `/digital/experiment-users` 更名为「实验用户分组」,只针对 C 端用户配置实验。
用户列表展示账号的 NSFW 开关;创建用户默认开启,编辑用户可单独开启或关闭。与前台「我的」读取和修改同一份服务端账号偏好,不覆盖收藏、称呼或身份背景。已有账号未保存该字段时默认开启,游客的登录限制不变;需与 `access-manage` 配套发布。
+230
View File
@@ -0,0 +1,230 @@
# 实验完整操作教程
从创建类型到结束实验,按顺序走一遍。建议第一次先只选自己的测试账号,验证真实应用效果后再扩大流量。
更新时间:2026-10-27
> 截图由仓库实际页面组件在隔离演示环境拍摄。红色箭头和编号为操作标注;演示调用、账号和统计不是生产验收证据。
## 目录
- 先分清三个概念
- 1. 创建自己的实验类型
- 2. 接入应用并完成业务验收
- 3. 先建“仅自己验收”的测试方案
- 4. 用户究竟如何被分组
- 5. 启动验收方案
- 6. 查看账号分组,指定 A/B 做对照
- 7. 验收完成后,另建正式分流方案
- 8. 查看效果与审计
- 9. 暂停与恢复
- 10. 结束并保留最终结果
- 完成前再核对一次
## 先分清三个概念
类型定义测什么,测试方案定义怎么测,分组定义每种返回结果。
- 实验类型:例如“新老 UI(教程)”,稳定标识 tutorial_ui,返回格式为开关,默认值 false。名称不会自动接入任何功能。
- 测试方案:一次有明确目标、人群、流量和生命周期的实验。相同类型可以先做仅自己验收,再结束验收方案、另建正式实验。
- 分组:方案内的 A~Z 组。每组有比例和返回值,合计100%;false / true 只是教程示例,实际含义由应用代码决定。
- 本文使用隔离演示数据拍摄实际页面组件,标注编号对应下方操作;演示调用与统计不代表你的类型已经接入或线上实验已验收。
## 1. 创建自己的实验类型
进入“实验类型”,点击“创建实验类型”。
![1. 创建自己的实验类型:编号操作截图](../../public/guides/experiments/01-create-type.svg)
1. 填写稳定标识;名称用于辨认,标识才是应用读取决策的依据。
2. 选择返回值格式,本例为开关;下面的默认值使用 false。
3. 启用类型后保存;保存成功仍须完成真实应用接入。
- 填写名称与稳定标识。本例 tutorial_ui 只是演示,不要照抄成已有业务的标识;标识创建后不可改。
- 选择“开关(是/否)”,默认返回值设为关闭 false;在应用中约定 false 为旧 UI、true 为新 UI。
- 保持“启用类型”开启并保存。启用只表示允许这一类型参与决策,不会直接开启新 UI。
- 保存后应看到“待应用调用”。这是正常状态;此时可以保存草稿,不能启动实验。
## 2. 接入应用并完成业务验收
在类型所在行点击“接入与验收”,先让真实功能读取并使用返回值。
![2. 接入应用并完成业务验收:编号操作截图](../../public/guides/experiments/02-integration.svg)
1. 核对要接入的稳定标识,避免读错类型。
2. 按调用说明接入,让真实功能使用接口返回的 value。
3. 收到调用并验证实际功能后,勾选确认、填写记录,再确认接入验收。
- 将类型标识、数据格式、默认值和目标功能交给负责应用接入的人。后台只能配置,不能替客户端实现界面切换。
- 应用以当前用户的已登录身份调用决策接口,读取 value,并将 false / true 实际用于切换旧 / 新 UI。只请求接口并不等于功能已经消费返回值。
- 在实际页面检查结果,返回后台点击“刷新调用状态”;收到当前契约的调用后,勾选真实验证并填写至少8字的验收记录,再点“确认接入验收”。
- 应看到“已确认接入”。没有调用时按钮不可用,不应伪造回执。截图中的状态来自隔离演示,不是对线上接入的证明。
```text
GET /api/digital/decisions/tutorial_ui
Authorization: Bearer <当前用户的访问令牌>
// 应用接入示意:使用自己的请求封装和实际界面切换方法。
const decision = await readDecision("tutorial_ui");
applyUiVersion(decision.value === true ? "new" : "old");
```
## 3. 先建“仅自己验收”的测试方案
回到“测试方案”,创建草稿,先用自己的真实测试账号验证。
![3. 先建“仅自己验收”的测试方案:编号操作截图](../../public/guides/experiments/03-trial.svg)
1. 命名本次“仅自己验收”的方案,并选择正确类型。
2. 入组范围选指定名单,只选择自己的测试账号。
3. 分组配置完成后保存草稿;保存不会启动实验。
![3. 先建“仅自己验收”的测试方案:编号操作截图](../../public/guides/experiments/03b-trial-groups.svg)
1. A设0%,保留 false;没有自动流量进入A。
2. B设100%,返回 true;自动入组的验收账号读取B值。
3. 核对目标、人群和返回值后保存草稿。
- 填方案名称、选择刚才的类型,写清目标与验收指标。方案名称用于辨认本次实验,不负责绑定功能。
- 入组范围选“指定名单”,只选自己的测试账号;进入实验的流量设为100%。请确认页面选择的是你自己的账号。
- A 组设0%、返回 false;B 组设100%、返回 true。A仍保留另一种返回值,可通过人工指定进行对照;没有自动流量进入A。
- 点击“保存草稿”。保存不会改变应用行为;比例必须合计100%,0%组也必须填写合法返回值。
## 4. 用户究竟如何被分组
分组规则会直接标注在配置页,并随着比例显示当前区间。
![4. 用户究竟如何被分组:编号操作截图](../../public/guides/experiments/04-allocation.svg)
1. 分组方式固定标注在页面:按账号稳定随机分配。
2. 当前区间随比例联动,A/B各50%时按0~4999与5000~9999划分。
3. 展开查看具体算法,以及人工指定、稳定分组、流量筛选的优先顺序。
- “所有用户”只表示所有账号有资格参加,不按性别、年龄或账号尾号区分。首次自动分配先判断人群及实验流量。
- 系统用账号标识、本次测试方案ID及用途做SHA-256,取摘要前4字节的无符号大端整数,对10000取余,得到0~9999。流量和组别使用两个独立的用途值。
- A/B各50%时,按配置顺序A为0~4999,B为5000~9999。A为100%时,A覆盖0~9999,B为0%不自动分配。
- 首次实际入组后保存稳定分组,刷新和重新登录不重抽;有效人工指定优先。新建方案的ID不同,同一账号可能分到不同组。
- 比例是分配概率,不保证小样本恰好一半。未入组、草稿或暂停时使用类型默认返回值,不属于任何组。
## 5. 启动验收方案
接入已确认、草稿配置无误后,点击方案行中的“启动”。
![5. 启动验收方案:编号操作截图](../../public/guides/experiments/05-start.svg)
1. 确认目标方案,并注意启动后配置冻结。
2. 核对无误再确认;之后到应用中验收实际效果。
- 核对方案名称、人群与比例,再确认启动。启动后应显示“运行中”。
- 启动后组别、比例、人群和返回值冻结;需要新规则时创建下一条方案,不能直接改正在运行的配置。
- 在应用中重新读取决策并检查新 UI。人工指定用户也需要刷新或等待应用读取新决策;决策请求、实际展示和曝光记录是不同的事情。
- 如果仍看旧 UI,先检查类型标识与接入代码、账号是否在名单、返回值是否被使用,而不是仅看后台状态。
## 6. 查看账号分组,指定 A/B 做对照
从方案行进入“实验用户分组”,确认当前方案,再搜索测试账号。
![6. 查看账号分组,指定 A/B 做对照:编号操作截图](../../public/guides/experiments/06-users.svg)
1. 先选择本次测试方案,并在方案详情中核对目标人群与比例。
2. 当前分组和值与分配方式分列展示,明确区分预计自动分组和手动指定。
3. 查找用户或指定用户分组;已有指定可修改,也可取消,原有效期限单独展示。
![6. 查看账号分组,指定 A/B 做对照:编号操作截图](../../public/guides/experiments/06b-override.svg)
1. 指定分组直接展示返回值与自动分流比例;A 为 0% 也可手动指定。
2. 账号不在目标人群时,须明确作为测试账号加入;设置未来30天内的有效期。
3. 填写原因后确认指定;方案运行且前台已接入时,应用下次读取才会使用指定值。
- 先选择本次方案,再按账号、姓名或用户名查询;用户列表包含未参与实验的账号。“预计自动分组”只读,首次实际调用后才保存入组,查询不会计曝光。
- 点击“指定用户分组”查找账号,或在用户行点击“指定分组/修改指定”。每组直接展示返回值和自动分流比例,0% 组也可手动指定。有效期须在未来30天内,操作原因至少2字。
- 账号不符合目标人群时,页面会说明具体原因。例如仅新用户的实验中指定老账号,须勾选“将此账号作为测试账号加入,仍使用上面指定的组”;仅对此账号放开限制,不修改其他用户。符合人群时无需此选项。
- 有效期内不一定正在生效:草稿/暂停要等方案运行,人群不符且未允许测试账号加入时不生效。前台仍须真实接入并读取返回值,才能验证功能变化。
- 点击“取消手动指定”,或等待到期后恢复方案规则:符合目标人群时沿用原自动分组,否则重新判断。取消指定不保证会换到另一组;修改指定会保留原有效期限,不自动延长。
## 7. 验收完成后,另建正式分流方案
先结束验收方案并保留需要的组,再为同一类型创建新的正式方案。
![7. 验收完成后,另建正式分流方案:编号操作截图](../../public/guides/experiments/07-formal.svg)
1. 正式分流示例A/B各50%,C为0%;合计须为100%。
2. 返回值与比例独立配置,不要根据组名猜业务含义。
3. 添加更多组或平均分配,最多A到Z共26组。
- 同一类型消费标识只允许一个运行中或暂停中的方案,可以先保存多份草稿;请先结束验收方案,再启动正式方案。
- 本例选择“所有用户”,进入实验流量100%,A/B各50%,分别返回 false / true。也可选择新用户、老用户,并设置明确的注册时间分界。
- 可添加到Z组。新增组初始0%,各组返回值独立配置;三组及以上需要自行调整合计100%,或点击“平均分配”“补足剩余”。
- 如要扩大实验流量,已启动方案不能直接调规则,需要结束后另建方案。组内比例与实验流量不同:实验流量20%、A/B各50%时,目标人群约10%进入A、10%进入B,其余使用类型默认值。
- 截图为另一份演示草稿,比例与返回值请按实际目标设置;不要把教程示例直接当作上线决策。
## 8. 查看效果与审计
在方案行点击“效果与审计”,同时核对配置、效果和操作记录。
![8. 查看效果与审计:编号操作截图](../../public/guides/experiments/08-metrics.svg)
1. 先核对当前组配置,确认所分析的值与比例。
2. 区分决策和曝光;曝光须由实际展示后的回报产生。
3. 切换“操作审计”,追溯创建、状态流转和人工指定。
![8. 查看效果与审计:编号操作截图](../../public/guides/experiments/08b-audit.svg)
1. 进入操作审计页签。
2. 查看动作、操作人、详情与时间;图中为隔离演示记录。
- 上方显示实际组别、比例与返回值,下方按组展示决策、曝光和漏斗;人工指定与规则分组分开统计。
- 决策次数是读取结果的次数,曝光是应用实际展示后的回报;不能将请求接口的数量当成用户已看到界面的数量。
- 根据事先写好的指标比较体验、留存等业务结果;当前页面的漏斗统计不等于完整留存报表,也不会自动给出显著性结论。
- “操作审计”保留创建、状态变更和人工指定等操作。没有数据时先检查是否有真实入组、是否完成曝光接入;后台预览不会制造统计。
- 截图统计为演示样例,用于解释字段,不能作为生产结果或发布验收凭据。
## 9. 暂停与恢复
运行中可以暂停;暂停用于停止实验效果,并不释放同类型的未结束方案。
![9. 暂停与恢复:编号操作截图](../../public/guides/experiments/09-pause.svg)
1. 已暂停表示使用类型默认返回值,不属于某个默认组。
2. 需要继续时点击恢复;已有稳定分组保持不变。
- 点击“暂停”并确认后,用户使用实验类型的默认返回值,而不是某个默认组。
- 已保存分组保留;点击“恢复”后沿用分组。暂停期间的人工指定也不会让方案重新生效。
- 需要彻底换一套人群或分组比例时,结束当前方案,再创建下一条方案。
## 10. 结束并保留最终结果
点击“结束实验”,从当前方案已有组中选择最终保留哪一组。
![10. 结束并保留最终结果:编号操作截图](../../public/guides/experiments/10a-choose-winner.svg)
1. 打开结束实验菜单。
2. 明确选定最终保留的组,本例是返回 true 的B组。
![10. 结束并保留最终结果:编号操作截图](../../public/guides/experiments/10-finish.svg)
1. 确认影响范围:结束后所有用户采用所选组返回值,且不能重新启动。
2. 确认无误后提交;若希望回旧版,请先核对所选组是否真的返回旧版值。
- 本例选择“保留 B 组”,确认文案会明确说明:结束后所有用户采用该组的返回值。
- 结束是最终状态,不能恢复运行;它不是“停止并自动回旧版”。如果希望回旧版,应选择实际返回旧版值的组。
- 结束后该组返回值会持续生效,直到有新的有效方案接管,或类型被停用;停用类型后回类型默认返回值。
- 结束后核对应用效果和审计,再规划下一次实验。不要仅因B叫“B”就认为它一定是新版;含义取决于该组配置的值和消费代码。
## 完成前再核对一次
每次实验都按这份清单自查。
- 类型标识、格式、默认值与应用实现一致,真实功能已经使用返回值,并完成当前契约的接入验收。
- 先用自己的账号验收,再正式分流;所有组比例合计100%,零比例组的值同样正确。
- 确认人工指定是否仍有效,区分规则分组与人工指定的统计。
- 真实调用、真实展示、曝光回报和业务指标分别核实;截图教程与构建成功都不是业务效果验收。
- 暂停使用类型默认值;结束保留所选组。按需要的结果操作,不凭组名猜测功能。
## 维护教程
- 内容源:`guide.json`;二级教程页直接读取同一内容源。
- 原始截图:`screenshots/*.jpg`;标注坐标:`screenshots.json`。截图必须使用隔离演示数据。
- 执行 `node scripts/build-experiment-guide.mjs` 重新生成本README和带箭头、编号的SVG。
- 执行 `node scripts/build-experiment-guide.mjs --check` 检查派生文件与内容源一致。
- 二级页面:`/digital/experiments/guide`;点击“操作指南”进入。
+221
View File
@@ -0,0 +1,221 @@
{
"title": "实验完整操作教程",
"updated": "2026-10-27",
"intro": "从创建类型到结束实验,按顺序走一遍。建议第一次先只选自己的测试账号,验证真实应用效果后再扩大流量。",
"steps": [
{
"id": "concepts",
"title": "先分清三个概念",
"lead": "类型定义测什么,测试方案定义怎么测,分组定义每种返回结果。",
"bullets": [
"实验类型:例如“新老 UI(教程)”,稳定标识 tutorial_ui,返回格式为开关,默认值 false。名称不会自动接入任何功能。",
"测试方案:一次有明确目标、人群、流量和生命周期的实验。相同类型可以先做仅自己验收,再结束验收方案、另建正式实验。",
"分组:方案内的 A~Z 组。每组有比例和返回值,合计100%;false / true 只是教程示例,实际含义由应用代码决定。",
"本文使用隔离演示数据拍摄实际页面组件,标注编号对应下方操作;演示调用与统计不代表你的类型已经接入或线上实验已验收。"
]
},
{
"id": "create-type",
"title": "1. 创建自己的实验类型",
"lead": "进入“实验类型”,点击“创建实验类型”。",
"bullets": [
"填写名称与稳定标识。本例 tutorial_ui 只是演示,不要照抄成已有业务的标识;标识创建后不可改。",
"选择“开关(是/否)”,默认返回值设为关闭 false;在应用中约定 false 为旧 UI、true 为新 UI。",
"保持“启用类型”开启并保存。启用只表示允许这一类型参与决策,不会直接开启新 UI。",
"保存后应看到“待应用调用”。这是正常状态;此时可以保存草稿,不能启动实验。"
],
"images": ["01-create-type"]
},
{
"id": "integrate",
"title": "2. 接入应用并完成业务验收",
"lead": "在类型所在行点击“接入与验收”,先让真实功能读取并使用返回值。",
"bullets": [
"将类型标识、数据格式、默认值和目标功能交给负责应用接入的人。后台只能配置,不能替客户端实现界面切换。",
"应用以当前用户的已登录身份调用决策接口,读取 value,并将 false / true 实际用于切换旧 / 新 UI。只请求接口并不等于功能已经消费返回值。",
"在实际页面检查结果,返回后台点击“刷新调用状态”;收到当前契约的调用后,勾选真实验证并填写至少8字的验收记录,再点“确认接入验收”。",
"应看到“已确认接入”。没有调用时按钮不可用,不应伪造回执。截图中的状态来自隔离演示,不是对线上接入的证明。"
],
"code": "GET /api/digital/decisions/tutorial_ui\nAuthorization: Bearer <当前用户的访问令牌>\n\n// 应用接入示意:使用自己的请求封装和实际界面切换方法。\nconst decision = await readDecision(\"tutorial_ui\");\napplyUiVersion(decision.value === true ? \"new\" : \"old\");",
"images": ["02-integration"]
},
{
"id": "trial",
"title": "3. 先建“仅自己验收”的测试方案",
"lead": "回到“测试方案”,创建草稿,先用自己的真实测试账号验证。",
"bullets": [
"填方案名称、选择刚才的类型,写清目标与验收指标。方案名称用于辨认本次实验,不负责绑定功能。",
"入组范围选“指定名单”,只选自己的测试账号;进入实验的流量设为100%。请确认页面选择的是你自己的账号。",
"A 组设0%、返回 false;B 组设100%、返回 true。A仍保留另一种返回值,可通过人工指定进行对照;没有自动流量进入A。",
"点击“保存草稿”。保存不会改变应用行为;比例必须合计100%,0%组也必须填写合法返回值。"
],
"images": ["03-trial", "03b-trial-groups"]
},
{
"id": "allocation",
"title": "4. 用户究竟如何被分组",
"lead": "分组规则会直接标注在配置页,并随着比例显示当前区间。",
"bullets": [
"“所有用户”只表示所有账号有资格参加,不按性别、年龄或账号尾号区分。首次自动分配先判断人群及实验流量。",
"系统用账号标识、本次测试方案ID及用途做SHA-256,取摘要前4字节的无符号大端整数,对10000取余,得到0~9999。流量和组别使用两个独立的用途值。",
"A/B各50%时,按配置顺序A为0~4999,B为5000~9999。A为100%时,A覆盖0~9999,B为0%不自动分配。",
"首次实际入组后保存稳定分组,刷新和重新登录不重抽;有效人工指定优先。新建方案的ID不同,同一账号可能分到不同组。",
"比例是分配概率,不保证小样本恰好一半。未入组、草稿或暂停时使用类型默认返回值,不属于任何组。"
],
"images": ["04-allocation"]
},
{
"id": "start",
"title": "5. 启动验收方案",
"lead": "接入已确认、草稿配置无误后,点击方案行中的“启动”。",
"bullets": [
"核对方案名称、人群与比例,再确认启动。启动后应显示“运行中”。",
"启动后组别、比例、人群和返回值冻结;需要新规则时创建下一条方案,不能直接改正在运行的配置。",
"在应用中重新读取决策并检查新 UI。人工指定用户也需要刷新或等待应用读取新决策;决策请求、实际展示和曝光记录是不同的事情。",
"如果仍看旧 UI,先检查类型标识与接入代码、账号是否在名单、返回值是否被使用,而不是仅看后台状态。"
],
"images": ["05-start"]
},
{
"id": "users",
"title": "6. 查看账号分组,指定 A/B 做对照",
"lead": "从方案行进入“实验用户分组”,确认当前方案,再搜索测试账号。",
"bullets": [
"先选择本次方案,再按账号、姓名或用户名查询;用户列表包含未参与实验的账号。“预计自动分组”只读,首次实际调用后才保存入组,查询不会计曝光。",
"点击“指定用户分组”查找账号,或在用户行点击“指定分组/修改指定”。每组直接展示返回值和自动分流比例,0% 组也可手动指定。有效期须在未来30天内,操作原因至少2字。",
"账号不符合目标人群时,页面会说明具体原因。例如仅新用户的实验中指定老账号,须勾选“将此账号作为测试账号加入,仍使用上面指定的组”;仅对此账号放开限制,不修改其他用户。符合人群时无需此选项。",
"有效期内不一定正在生效:草稿/暂停要等方案运行,人群不符且未允许测试账号加入时不生效。前台仍须真实接入并读取返回值,才能验证功能变化。",
"点击“取消手动指定”,或等待到期后恢复方案规则:符合目标人群时沿用原自动分组,否则重新判断。取消指定不保证会换到另一组;修改指定会保留原有效期限,不自动延长。"
],
"images": ["06-users", "06b-override"]
},
{
"id": "formal",
"title": "7. 验收完成后,另建正式分流方案",
"lead": "先结束验收方案并保留需要的组,再为同一类型创建新的正式方案。",
"bullets": [
"同一类型消费标识只允许一个运行中或暂停中的方案,可以先保存多份草稿;请先结束验收方案,再启动正式方案。",
"本例选择“所有用户”,进入实验流量100%,A/B各50%,分别返回 false / true。也可选择新用户、老用户,并设置明确的注册时间分界。",
"可添加到Z组。新增组初始0%,各组返回值独立配置;三组及以上需要自行调整合计100%,或点击“平均分配”“补足剩余”。",
"如要扩大实验流量,已启动方案不能直接调规则,需要结束后另建方案。组内比例与实验流量不同:实验流量20%、A/B各50%时,目标人群约10%进入A、10%进入B,其余使用类型默认值。",
"截图为另一份演示草稿,比例与返回值请按实际目标设置;不要把教程示例直接当作上线决策。"
],
"images": ["07-formal"]
},
{
"id": "metrics",
"title": "8. 查看效果与审计",
"lead": "在方案行点击“效果与审计”,同时核对配置、效果和操作记录。",
"bullets": [
"上方显示实际组别、比例与返回值,下方按组展示决策、曝光和漏斗;人工指定与规则分组分开统计。",
"决策次数是读取结果的次数,曝光是应用实际展示后的回报;不能将请求接口的数量当成用户已看到界面的数量。",
"根据事先写好的指标比较体验、留存等业务结果;当前页面的漏斗统计不等于完整留存报表,也不会自动给出显著性结论。",
"“操作审计”保留创建、状态变更和人工指定等操作。没有数据时先检查是否有真实入组、是否完成曝光接入;后台预览不会制造统计。",
"截图统计为演示样例,用于解释字段,不能作为生产结果或发布验收凭据。"
],
"images": ["08-metrics", "08b-audit"]
},
{
"id": "pause",
"title": "9. 暂停与恢复",
"lead": "运行中可以暂停;暂停用于停止实验效果,并不释放同类型的未结束方案。",
"bullets": [
"点击“暂停”并确认后,用户使用实验类型的默认返回值,而不是某个默认组。",
"已保存分组保留;点击“恢复”后沿用分组。暂停期间的人工指定也不会让方案重新生效。",
"需要彻底换一套人群或分组比例时,结束当前方案,再创建下一条方案。"
],
"images": ["09-pause"]
},
{
"id": "finish",
"title": "10. 结束并保留最终结果",
"lead": "点击“结束实验”,从当前方案已有组中选择最终保留哪一组。",
"bullets": [
"本例选择“保留 B 组”,确认文案会明确说明:结束后所有用户采用该组的返回值。",
"结束是最终状态,不能恢复运行;它不是“停止并自动回旧版”。如果希望回旧版,应选择实际返回旧版值的组。",
"结束后该组返回值会持续生效,直到有新的有效方案接管,或类型被停用;停用类型后回类型默认返回值。",
"结束后核对应用效果和审计,再规划下一次实验。不要仅因B叫“B”就认为它一定是新版;含义取决于该组配置的值和消费代码。"
],
"images": ["10a-choose-winner", "10-finish"]
},
{
"id": "checklist",
"title": "完成前再核对一次",
"lead": "每次实验都按这份清单自查。",
"bullets": [
"类型标识、格式、默认值与应用实现一致,真实功能已经使用返回值,并完成当前契约的接入验收。",
"先用自己的账号验收,再正式分流;所有组比例合计100%,零比例组的值同样正确。",
"确认人工指定是否仍有效,区分规则分组与人工指定的统计。",
"真实调用、真实展示、曝光回报和业务指标分别核实;截图教程与构建成功都不是业务效果验收。",
"暂停使用类型默认值;结束保留所选组。按需要的结果操作,不凭组名猜测功能。"
]
}
],
"captions": {
"01-create-type": [
"填写稳定标识;名称用于辨认,标识才是应用读取决策的依据。",
"选择返回值格式,本例为开关;下面的默认值使用 false。",
"启用类型后保存;保存成功仍须完成真实应用接入。"
],
"02-integration": [
"核对要接入的稳定标识,避免读错类型。",
"按调用说明接入,让真实功能使用接口返回的 value。",
"收到调用并验证实际功能后,勾选确认、填写记录,再确认接入验收。"
],
"03-trial": [
"命名本次“仅自己验收”的方案,并选择正确类型。",
"入组范围选指定名单,只选择自己的测试账号。",
"分组配置完成后保存草稿;保存不会启动实验。"
],
"03b-trial-groups": [
"A设0%,保留 false;没有自动流量进入A。",
"B设100%,返回 true;自动入组的验收账号读取B值。",
"核对目标、人群和返回值后保存草稿。"
],
"04-allocation": [
"分组方式固定标注在页面:按账号稳定随机分配。",
"当前区间随比例联动,A/B各50%时按0~4999与5000~9999划分。",
"展开查看具体算法,以及人工指定、稳定分组、流量筛选的优先顺序。"
],
"05-start": [
"确认目标方案,并注意启动后配置冻结。",
"核对无误再确认;之后到应用中验收实际效果。"
],
"06-users": [
"先选择本次测试方案,并在方案详情中核对目标人群与比例。",
"当前分组和值与分配方式分列展示,明确区分预计自动分组和手动指定。",
"查找用户或指定用户分组;已有指定可修改,也可取消,原有效期限单独展示。"
],
"06b-override": [
"指定分组直接展示返回值与自动分流比例;A 为 0% 也可手动指定。",
"账号不在目标人群时,须明确作为测试账号加入;设置未来30天内的有效期。",
"填写原因后确认指定;方案运行且前台已接入时,应用下次读取才会使用指定值。"
],
"07-formal": [
"正式分流示例A/B各50%,C为0%;合计须为100%。",
"返回值与比例独立配置,不要根据组名猜业务含义。",
"添加更多组或平均分配,最多A到Z共26组。"
],
"08-metrics": [
"先核对当前组配置,确认所分析的值与比例。",
"区分决策和曝光;曝光须由实际展示后的回报产生。",
"切换“操作审计”,追溯创建、状态流转和人工指定。"
],
"08b-audit": [
"进入操作审计页签。",
"查看动作、操作人、详情与时间;图中为隔离演示记录。"
],
"09-pause": [
"已暂停表示使用类型默认返回值,不属于某个默认组。",
"需要继续时点击恢复;已有稳定分组保持不变。"
],
"10a-choose-winner": [
"打开结束实验菜单。",
"明确选定最终保留的组,本例是返回 true 的B组。"
],
"10-finish": [
"确认影响范围:结束后所有用户采用所选组返回值,且不能重新启动。",
"确认无误后提交;若希望回旧版,请先核对所选组是否真的返回旧版值。"
]
}
}
+567
View File
@@ -0,0 +1,567 @@
{
"01-create-type": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 649.5,
"y": 273.796875,
"width": 606,
"height": 30
},
"badge": {
"x": 573.5,
"y": 288.796875
}
},
{
"number": 2,
"rect": {
"x": 650.5,
"y": 396.796875,
"width": 156,
"height": 24
},
"badge": {
"x": 574.5,
"y": 408.796875
}
},
{
"number": 3,
"rect": {
"x": 1178.5,
"y": 803.796875,
"width": 88,
"height": 32
},
"badge": {
"x": 1336.5,
"y": 819.796875
}
}
]
},
"02-integration": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 1455.3515625,
"y": 95,
"width": 429.1484375,
"height": 40
},
"badge": {
"x": 1379.3515625,
"y": 115
}
},
{
"number": 2,
"rect": {
"x": 1160,
"y": 319.5,
"width": 725,
"height": 26.5
},
"badge": {
"x": 1084,
"y": 332.75
}
},
{
"number": 3,
"rect": {
"x": 1160,
"y": 868.875,
"width": 116,
"height": 32
},
"badge": {
"x": 1346,
"y": 872
}
}
]
},
"03-trial": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 547,
"y": 132.09375,
"width": 384.5,
"height": 30
},
"badge": {
"x": 471,
"y": 147.09375
}
},
{
"number": 2,
"rect": {
"x": 823.578125,
"y": 427.09375,
"width": 513.421875,
"height": 24
},
"badge": {
"x": 747.578125,
"y": 439.09375
}
},
{
"number": 3,
"rect": {
"x": 1296,
"y": 808.890625,
"width": 88,
"height": 32
},
"badge": {
"x": 1454,
"y": 824.890625
}
}
]
},
"05-start": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 798,
"y": 423,
"width": 360,
"height": 48
},
"badge": {
"x": 722,
"y": 447
}
},
{
"number": 2,
"rect": {
"x": 1098,
"y": 483,
"width": 60,
"height": 32
},
"badge": {
"x": 1228,
"y": 499.0
}
}
]
},
"06-users": {
"width": 1920,
"height": 958,
"annotations": [
{
"number": 1,
"rect": {
"x": 470,
"y": 225,
"width": 305,
"height": 38
},
"badge": {
"x": 520,
"y": 170
}
},
{
"number": 2,
"rect": {
"x": 625,
"y": 425,
"width": 560,
"height": 187
},
"badge": {
"x": 580,
"y": 447
}
},
{
"number": 3,
"rect": {
"x": 1200,
"y": 355,
"width": 675,
"height": 255
},
"badge": {
"x": 1795,
"y": 708
}
}
]
},
"06b-override": {
"width": 1920,
"height": 958,
"annotations": [
{
"number": 1,
"rect": {
"x": 655,
"y": 225,
"width": 595,
"height": 135
},
"badge": {
"x": 1390,
"y": 270
}
},
{
"number": 2,
"rect": {
"x": 655,
"y": 418,
"width": 595,
"height": 223
},
"badge": {
"x": 520,
"y": 470
}
},
{
"number": 3,
"rect": {
"x": 655,
"y": 665,
"width": 595,
"height": 157
},
"badge": {
"x": 1390,
"y": 720
}
}
]
},
"03b-trial-groups": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 660,
"y": 575.46875,
"width": 66,
"height": 30
},
"badge": {
"x": 480,
"y": 543.46875
}
},
{
"number": 2,
"rect": {
"x": 660,
"y": 624.46875,
"width": 66,
"height": 30
},
"badge": {
"x": 480,
"y": 592.46875
}
},
{
"number": 3,
"rect": {
"x": 1296,
"y": 808.890625,
"width": 88,
"height": 32
},
"badge": {
"x": 1454,
"y": 824.890625
}
}
]
},
"04-allocation": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 551,
"y": 342.09375,
"width": 182,
"height": 16
},
"badge": {
"x": 475,
"y": 350.09375
}
},
{
"number": 2,
"rect": {
"x": 551,
"y": 395.28125,
"width": 803,
"height": 22.09375
},
"badge": {
"x": 475,
"y": 406.328125
}
},
{
"number": 3,
"rect": {
"x": 551,
"y": 452.46875,
"width": 811,
"height": 49
},
"badge": {
"x": 475,
"y": 476.46875
}
}
]
},
"07-formal": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 660,
"y": 575.46875,
"width": 66,
"height": 30
},
"badge": {
"x": 480,
"y": 543.46875
}
},
{
"number": 2,
"rect": {
"x": 818,
"y": 623.46875,
"width": 116,
"height": 32
},
"badge": {
"x": 999,
"y": 639.46875
}
},
{
"number": 3,
"rect": {
"x": 536,
"y": 729.46875,
"width": 88,
"height": 32
},
"badge": {
"x": 460,
"y": 745.46875
}
}
]
},
"08-metrics": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 1180,
"y": 260.28125,
"width": 720,
"height": 40
},
"badge": {
"x": 1104,
"y": 280.28125
}
},
{
"number": 2,
"rect": {
"x": 1594,
"y": 537.28125,
"width": 153,
"height": 40
},
"badge": {
"x": 1518,
"y": 557.28125
}
},
{
"number": 3,
"rect": {
"x": 1056,
"y": 443.28125,
"width": 76,
"height": 40
},
"badge": {
"x": 980,
"y": 463.28125
}
}
]
},
"08b-audit": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 1056,
"y": 443.28125,
"width": 76,
"height": 40
},
"badge": {
"x": 980,
"y": 463.28125
}
},
{
"number": 2,
"rect": {
"x": 1048,
"y": 494.28125,
"width": 149.40625,
"height": 17
},
"badge": {
"x": 972,
"y": 502.78125
}
}
]
},
"09-pause": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 983,
"y": 659.65625,
"width": 36,
"height": 12
},
"badge": {
"x": 907,
"y": 665.65625
}
},
{
"number": 2,
"rect": {
"x": 1404,
"y": 656.65625,
"width": 34,
"height": 20
},
"badge": {
"x": 1328,
"y": 666.65625
}
}
]
},
"10a-choose-winner": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 1448,
"y": 656.65625,
"width": 62,
"height": 20
},
"badge": {
"x": 1372,
"y": 666.65625
}
},
{
"number": 2,
"rect": {
"x": 1433,
"y": 727,
"width": 91.453125,
"height": 32
},
"badge": {
"x": 1357,
"y": 743
}
}
]
},
"10-finish": {
"width": 1920,
"height": 902,
"annotations": [
{
"number": 1,
"rect": {
"x": 798,
"y": 435,
"width": 338.625,
"height": 24
},
"badge": {
"x": 722,
"y": 447
}
},
{
"number": 2,
"rect": {
"x": 1098,
"y": 471,
"width": 60,
"height": 32
},
"badge": {
"x": 1228,
"y": 487.0
}
}
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

+5 -3
View File
@@ -1,5 +1,5 @@
<!doctype html>
<html lang="en">
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
@@ -8,8 +8,10 @@
name="viewport"
content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0"
/>
<title>pure-admin-thin</title>
<link rel="icon" href="/favicon.ico" />
<title>星港 · 数字人运营</title>
<link rel="icon" type="image/svg+xml" href="/stellar-icon-v2.svg" />
<link rel="alternate icon" href="/favicon.ico?v=stellar-2" />
<link rel="apple-touch-icon" href="/stellar-icon-180-v2.png" />
</head>
<body>
+3
View File
@@ -1,3 +1,6 @@
packages:
- '.'
allowedDeprecatedVersions:
are-we-there-yet: "*"
sourcemap-codec: "*"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 5.3 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 93 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 127 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 143 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 148 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 140 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 96 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 110 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 121 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 144 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 141 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 112 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 130 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 107 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 131 KiB

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" class="icon" viewBox="0 0 1024 1024"><path fill="#386BF3" d="M410.558.109c0 210.974-300.876 361.752-300.876 633.548 0 174.943 134.704 316.787 300.876 316.787s300.877-141.817 300.877-316.787C711.408 361.752 410.558 210.974 410.558.109"/><path fill="#C3D2FB" d="M613.469 73.665c0 211.055-300.877 361.914-300.877 633.547C312.592 882.156 447.296 1024 613.47 1024s300.876-141.817 300.876-316.788C914.29 435.58 613.469 284.72 613.469 73.665"/><path fill="#303F5B" d="M312.592 707.212c0-183.713 137.636-312.171 226.723-441.39 81.702 106.112 172.12 218.74 172.12 367.726A309.755 309.755 0 0 1 420.36 950.064a323.1 323.1 0 0 1-107.769-242.852z"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="stellar" x1="12" y1="13" x2="49" y2="49" gradientUnits="userSpaceOnUse"><stop stop-color="#F4D5A3"/><stop offset="1" stop-color="#F5A8D9"/></linearGradient></defs><rect x="2" y="2" width="60" height="60" rx="18" fill="#211628"/><path d="M24 14h16c9 0 15 6 15 15v4c0 9-6 15-15 15H27L14 54l3-13c-4-3-6-7-6-12 0-9 5-15 13-15Z" fill="url(#stellar)"/><path d="M33 20c2.2 6.5 4.5 8.8 11 11-6.5 2.2-8.8 4.5-11 11-2.2-6.5-4.5-8.8-11-11 6.5-2.2 8.8-4.5 11-11Z" fill="#211628"/><circle cx="51" cy="13" r="5" fill="#F7B7DD" stroke="#211628" stroke-width="3"/></svg>

Before

Width:  |  Height:  |  Size: 706 B

After

Width:  |  Height:  |  Size: 640 B

+2 -2
View File
@@ -1,6 +1,6 @@
{
"Version": "6.2.0",
"Title": "门店权限后台",
"Title": "星港 · 数字人运营",
"FixedHeader": true,
"HiddenSideBar": false,
"MultiTagsCache": false,
@@ -15,7 +15,7 @@
"HideFooter": true,
"Stretch": false,
"SidebarStatus": true,
"EpThemeColor": "#2563EB",
"EpThemeColor": "#8b5d91",
"ShowLogo": true,
"ShowModel": "smart",
"MenuArrowIconNoTransition": false,
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="stellar" x1="12" y1="13" x2="49" y2="49" gradientUnits="userSpaceOnUse"><stop stop-color="#F4D5A3"/><stop offset="1" stop-color="#F5A8D9"/></linearGradient></defs><rect x="2" y="2" width="60" height="60" rx="18" fill="#211628"/><path d="M24 14h16c9 0 15 6 15 15v4c0 9-6 15-15 15H27L14 54l3-13c-4-3-6-7-6-12 0-9 5-15 13-15Z" fill="url(#stellar)"/><path d="M33 20c2.2 6.5 4.5 8.8 11 11-6.5 2.2-8.8 4.5-11 11-2.2-6.5-4.5-8.8-11-11 6.5-2.2 8.8-4.5 11-11Z" fill="#211628"/><circle cx="51" cy="13" r="5" fill="#F7B7DD" stroke="#211628" stroke-width="3"/></svg>

After

Width:  |  Height:  |  Size: 640 B

+98
View File
@@ -0,0 +1,98 @@
/** 从同一教程内容源生成仓库README和带编号箭头的SVG截图;--check只验证,不修改文件。 */
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const docRoot = path.join(root, "docs/experiments");
const guide = JSON.parse(
await readFile(path.join(docRoot, "guide.json"), "utf8")
);
const shots = JSON.parse(
await readFile(path.join(docRoot, "screenshots.json"), "utf8")
);
const check = process.argv.includes("--check");
const escape = value =>
String(value).replace(
/[&<>"']/g,
c =>
({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&apos;"
})[c]
);
/** 派生文件必须与共享源一致,防止网页教程、标注和README各自漂移。 */
async function output(file, content) {
if (check) {
if ((await readFile(file, "utf8")) !== content)
throw new Error(`派生文档需要重新生成:${path.relative(root, file)}`);
} else await writeFile(file, content);
}
let readme = `# ${guide.title}\n\n${guide.intro}\n\n更新时间:${guide.updated}\n\n> 截图由仓库实际页面组件在隔离演示环境拍摄。红色箭头和编号为操作标注;演示调用、账号和统计不是生产验收证据。\n\n## 目录\n\n`;
for (const step of guide.steps) readme += `- ${step.title}\n`;
for (const step of guide.steps) {
readme += `\n## ${step.title}\n\n${step.lead}\n`;
for (const image of step.images ?? []) {
const shot = shots[image];
if (!shot || shot.annotations.length < 1)
throw new Error(`缺少截图标注:${image}`);
if (guide.captions[image]?.length !== shot.annotations.length)
throw new Error(`标注编号与说明不匹配:${image}`);
const raw = await readFile(
path.join(docRoot, "screenshots", `${image}.jpg`)
);
if (raw[0] !== 255 || raw[1] !== 216)
throw new Error(`截图不是JPEG:${image}`);
const { width, height } = shot;
if (
!Number.isInteger(width) ||
!Number.isInteger(height) ||
width < 1 ||
height < 1
)
throw new Error("截图尺寸无效");
const annotations = shot.annotations
.map(a => {
const { x, y, width: w, height: h } = a.rect,
{ x: bx, y: by } = a.badge;
for (const n of [x, y, w, h, bx, by])
if (!Number.isFinite(n)) throw new Error("标注坐标无效");
if (
w <= 0 ||
h <= 0 ||
x < 0 ||
y < 0 ||
x + w > width + 1 ||
y + h > height + 1 ||
bx < 20 ||
bx > width - 20 ||
by < 20 ||
by > height - 20
)
throw new Error(`标注超出截图:${image}`);
const targetX = Math.max(x, Math.min(x + w, bx)),
targetY = Math.max(y, Math.min(y + h, by));
return `<g><rect x="${x - 4}" y="${y - 4}" width="${w + 8}" height="${h + 8}" rx="7" fill="none" stroke="#ff3b30" stroke-width="4"/><path d="M ${bx} ${by} L ${targetX} ${targetY}" fill="none" stroke="#ff3b30" stroke-width="5" marker-end="url(#arrow)"/><circle cx="${bx}" cy="${by}" r="22" fill="#ff3b30" stroke="white" stroke-width="3"/><text x="${bx}" y="${by + 8}" text-anchor="middle" fill="white" font-family="Arial,sans-serif" font-size="24" font-weight="700">${a.number}</text></g>`;
})
.join("");
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-labelledby="title desc"><title id="title">${escape(step.title)}</title><desc id="desc">隔离演示界面截图,红色箭头和编号对应教程操作步骤。</desc><defs><marker id="arrow" markerWidth="10" markerHeight="10" refX="9" refY="5" orient="auto" markerUnits="userSpaceOnUse"><path d="M0,0 L10,5 L0,10Z" fill="#ff3b30"/></marker></defs><image width="${width}" height="${height}" href="data:image/jpeg;base64,${raw.toString("base64")}"/>${annotations}</svg>\n`;
await output(
path.join(root, "public/guides/experiments", `${image}.svg`),
svg
);
readme +=
`\n![${step.title}:编号操作截图](../../public/guides/experiments/${image}.svg)\n\n` +
guide.captions[image].map((note, i) => `${i + 1}. ${note}`).join("\n") +
"\n";
}
readme += "\n" + step.bullets.map(line => `- ${line}`).join("\n") + "\n";
if (step.code) readme += `\n\`\`\`text\n${step.code}\n\`\`\`\n`;
}
readme +=
"\n## 维护教程\n\n- 内容源:`guide.json`;二级教程页直接读取同一内容源。\n- 原始截图:`screenshots/*.jpg`;标注坐标:`screenshots.json`。截图必须使用隔离演示数据。\n- 执行 `node scripts/build-experiment-guide.mjs` 重新生成本README和带箭头、编号的SVG。\n- 执行 `node scripts/build-experiment-guide.mjs --check` 检查派生文件与内容源一致。\n- 二级页面:`/digital/experiments/guide`;点击“操作指南”进入。\n";
await output(path.join(docRoot, "README.md"), readme);
console.log(
check ? "图文教程与标注一致性检查通过" : "已生成图文README与标注截图"
);
+177
View File
@@ -1,3 +1,4 @@
/** 既有权限业务与数字人运营的统一后台接口。 */
import { http } from "@/utils/http";
/**
@@ -1082,3 +1083,179 @@ export const listCredentialAudits = (params: CredentialAuditListParams) => {
)
);
};
/** 数字人运营接口,管理配置不进入前台 BFF。 */
/** 统一响应结构。 */
export type Result<T> = { success: boolean; data: T };
/** 数字人后台 API,复用已有 JWT 拦截器。 */
export async function digital<T>(
path: string,
method: "get" | "post" | "put" | "patch" | "delete" = "get",
data?: unknown
): Promise<T> {
try {
const result = await http.request<Result<T>>(
method,
`/api/digital-admin/${path}`,
data === undefined ? undefined : { data }
);
return result.data;
} catch (error) {
const response = (
error as { response?: { data?: { error?: { message?: string } } } }
).response;
throw new Error(
response?.data?.error?.message ??
(error instanceof Error ? error.message : "请求失败")
);
}
}
/** 内容编辑表单,保留完整协议字段。 */
export type Content = {
id: string;
kind: "character" | "worldbook" | "preset";
name: string;
status: string;
version?: number;
body: {
description: string;
personality: string;
scenario: string;
greeting: string;
alternateGreetings: string[];
examples: string;
systemPrompt: string;
gender: string;
age: number;
cover: string;
tags: string[];
bookIds: string[];
presetId?: string;
entries: Entry[];
temperature: number;
maxTokens: number;
contextBudget: number;
worldBudget: number;
source: string;
};
};
/** 世界书条目。 */
export type Entry = {
id: string;
name: string;
keys: string[];
secondaryKeys: string[];
content: string;
constant: boolean;
enabled: boolean;
priority: number;
position: string;
caseSensitive: boolean;
scanDepth: number;
};
/** 组比例以万分比保存,key使用A至Z,0%组仍可用于人工指定。 */
export type ExperimentGroup = { key: string; weight: number; value: unknown };
/** 测试方案:动态分组的返回值遵循已注册类型的数据契约。 */
export type Experiment = {
id: string;
name: string;
scope: string;
runtime?: string | null;
sceneName?: string;
state: "draft" | "running" | "paused" | "finished";
revision?: number;
config: {
audience: "all" | "new" | "existing" | "specified";
cutoff?: string;
accounts: string[];
traffic: number;
groups: ExperimentGroup[];
winner?: string;
description: string;
typeRevision?: number;
};
};
/** 动态注册的业务实验类型,接入状态由调用证据与人工验收共同决定。 */
export type ExperimentType = {
id: string;
name: string;
description: string;
consumerKey: string;
valueType: "string" | "number" | "boolean" | "json";
defaultValue: unknown;
contract: {
fixedValues?: { A: unknown; B: unknown };
labels?: { A: string; B: string };
optionsSource?: string;
};
enabled: number;
builtin: number;
runtime: string | null;
revision: number;
contractRevision: number;
integrationState: "pending" | "confirmed";
lastSeenAt: string | null;
lastSeenRevision: number | null;
confirmedAt: string | null;
confirmedBy: string | null;
integrationNotes: string;
hasPlans: number;
};
/** 用户分组页面的账号与只读判定。 */
export type ExperimentUser = {
account: string;
username: string;
name: string;
status: string;
createdAt: string;
decision: null | {
variant: string | null;
reason: string;
value: unknown;
revision: number;
};
override: null | {
variant: string;
reason: string;
expiresAt: string;
bypassAudience: number;
};
assignment: null | { variant: string; createdAt: string };
};
/** 独立 C 端用户的后台公开资料,不含密码/令牌或员工权限。 */
export type DigitalUser = {
id: number;
account: string;
username: string;
displayName: string;
status: "ACTIVE" | "INACTIVE";
/** 账号未保存内容偏好时默认开启,后端在生成时读取实际值。 */
nsfwEnabled?: boolean;
createdAt: string;
lastLoginAt: string | null;
conversations: number;
messages: number;
};
/** 用户所属会话的只读摘要。 */
export type UserConversation = {
id: string;
title: string;
characterId: string;
characterName: string;
messages: number;
createdAt: string;
updatedAt: string;
};
/** 持久化聊天消息;包括已停止、失败和被替换的历史版本。 */
export type UserChatMessage = {
id: string;
role: "user" | "assistant";
content: string;
status: string;
pinned: number;
sequenceId: number;
createdAt: string;
};
+79
View File
@@ -0,0 +1,79 @@
<script setup lang="ts">
/** 角色编辑预览与聊天记录共用的受限文本展示,用户消息和 HTML 字面量均不作为标签解释。 */
import { computed } from "vue";
import { parseDigitalMessage } from "@/utils/digital-message-format";
const props = withDefaults(
defineProps<{
text: string;
role?: "assistant" | "user";
incomplete?: boolean;
}>(),
{ role: "assistant", incomplete: false }
);
const blocks = computed(() =>
parseDigitalMessage(props.text, props.incomplete)
);
</script>
<template>
<div
class="digital-message-text"
:class="{ 'is-prose': role === 'assistant' }"
>
<template v-if="role === 'assistant' && blocks.length">
<p
v-for="(block, index) in blocks"
:key="index"
:class="[
block.kind,
{
'is-latin':
/[A-Za-z]/.test(block.text) && !/[\u3400-\u9fff]/.test(block.text)
}
]"
>
<strong v-if="block.kind === 'dialogue'">{{ block.text }}</strong>
<template v-else>{{ block.text }}</template>
</p>
</template>
<template v-else>{{ text || "(未生成正文)" }}</template>
</div>
</template>
<style scoped>
.digital-message-text {
line-height: 1.9;
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.is-prose {
white-space: normal;
}
.is-prose > p {
margin: 0;
white-space: pre-wrap;
}
.is-prose > p + p {
margin-top: 12px;
}
.dialogue {
color: var(--digital-dialogue-ink, var(--el-text-color-primary));
}
.dialogue strong {
font-weight: 600;
}
.narration {
color: var(--digital-narration-ink, var(--el-text-color-regular));
}
.narration.is-latin {
font-style: italic;
}
</style>
+8 -61
View File
@@ -3,73 +3,20 @@ import type { FunctionalComponent } from "vue";
/**
* 登录后默认打开的标签页。
*
* 这里要和 `src/router/modules/employees.ts` 的业务页面保持一致,
* 这里要和 `src/router/modules/digital.ts` 的业务页面保持一致,
* 否则登出重置标签页或首次进入后台时会出现空标签/错入口。
*/
/** 数字人后台默认标签,旧业务路由保留但不自动打开。 */
export const routerArrays: Array<RouteConfigs> = [
{
path: "/stores",
name: "StoreManagement",
meta: {
title: "门店管理",
icon: "ep/shop"
}
path: "/digital/content",
name: "DigitalContent",
meta: { title: "角色与内容库", icon: "ep/collection" }
},
{
path: "/roles",
name: "RoleManagement",
meta: {
title: "角色管理",
icon: "ep/key"
}
},
{
path: "/employees",
name: "EmployeeManagement",
meta: {
title: "员工管理",
icon: "ep/user-filled"
}
},
{
path: "/permissions",
name: "PermissionPolicies",
meta: {
title: "权限策略",
icon: "ep/key"
}
},
{
path: "/announcements",
name: "AnnouncementManagement",
meta: {
title: "公告管理",
icon: "ep/bell"
}
},
{
path: "/tasks",
name: "TaskManagement",
meta: {
title: "任务管理",
icon: "ep/tickets"
}
},
{
path: "/shifts",
name: "ShiftManagement",
meta: {
title: "排班管理",
icon: "ep/calendar"
}
},
{
path: "/credential-audits",
name: "CredentialAuditManagement",
meta: {
title: "凭据审计",
icon: "ep/document-checked"
}
path: "/digital/experiments",
name: "DigitalExperiments",
meta: { title: "测试方案", icon: "ep/data-analysis" }
}
];
+53
View File
@@ -0,0 +1,53 @@
/** 数字人运营菜单,只授予现有超级管理员,业务后端再次执行鉴权。 */
const Layout = () => import("@/layout/index.vue");
/** 内容库、实验类型、测试方案和用户分组复用原有后台壳。 */
export default {
path: "/digital",
name: "DigitalOperations",
component: Layout,
redirect: "/digital/content",
meta: { title: "数字人运营", icon: "ep/chat-dot-round", rank: 0 },
children: [
{
path: "/digital/users",
name: "DigitalUsers",
component: () => import("@/views/digital/users.vue"),
meta: { title: "用户管理", permission: "*" }
},
{
path: "/digital/content",
name: "DigitalContent",
component: () => import("@/views/digital/content.vue"),
meta: { title: "角色与内容库", permission: "*" }
},
{
path: "/digital/experiment-types",
name: "DigitalExperimentTypes",
component: () => import("@/views/digital/experiment-types.vue"),
meta: { title: "实验类型", permission: "*" }
},
{
path: "/digital/experiments",
name: "DigitalExperiments",
component: () => import("@/views/digital/experiments.vue"),
meta: { title: "测试方案", permission: "*" }
},
{
path: "/digital/experiments/guide",
name: "DigitalExperimentGuide",
component: () => import("@/views/digital/experiment-guide.vue"),
meta: {
title: "实验操作指南",
permission: "*",
showLink: false,
activePath: "/digital/experiments"
}
},
{
path: "/digital/experiment-users",
name: "DigitalExperimentUsers",
component: () => import("@/views/digital/experiment-users.vue"),
meta: { title: "实验用户分组", permission: "*" }
}
]
} satisfies RouteConfigsTable;
+3
View File
@@ -1,3 +1,4 @@
/** 保留原门店业务路由,数字人改造后不占用主要导航。 */
const Layout = () => import("@/layout/index.vue");
/**
@@ -15,6 +16,7 @@ export default [
meta: {
icon: "ep/user-filled",
title: "权限管理",
showLink: false,
rank: 1
},
children: [
@@ -72,6 +74,7 @@ export default [
meta: {
icon: "ep/operation",
title: "员工工作台运营",
showLink: false,
rank: 2
},
children: [
+2 -2
View File
@@ -3,14 +3,14 @@ const Layout = () => import("@/layout/index.vue");
/**
* pure-admin 模板要求保留 Home 根路由。
*
* 当前业务首页是员工管理,所以根路径直接重定向到 `/employees`;
* 当前业务首页是数字人内容库,所以根路径直接重定向到 `/digital/content`;
* `/welcome` 只作为隐藏工作台占位页保留。
*/
export default {
path: "/",
name: "Home",
component: Layout,
redirect: "/employees",
redirect: "/digital/content",
meta: {
icon: "ep/home-filled",
title: "工作台",
+37
View File
@@ -35,3 +35,40 @@
.html-weakness {
filter: invert(80%);
}
/* 后台原生与 Element Plus 内部轨道统一隐藏,表格、抽屉和下拉框仍可滚动。 */
:root,
:root * {
scrollbar-width: none !important;
}
:root::-webkit-scrollbar,
:root *::-webkit-scrollbar {
display: none !important;
width: 0 !important;
height: 0 !important;
}
.el-scrollbar__bar {
display: none !important;
}
body {
overflow-x: hidden;
}
.el-dialog,
.el-drawer {
max-width: 100vw;
}
.el-dialog__body,
.el-drawer__body {
min-width: 0;
}
.el-textarea__inner {
max-width: 100%;
overflow-x: hidden;
overflow-wrap: anywhere;
}
+151
View File
@@ -0,0 +1,151 @@
/** 数字人消息的受限文本格式:对白、故事叙述与旧版括号;始终返回文本,不解释 HTML。 */
/** 有序展示片段;原始 content 继续用于存储、复制、记忆和上下文。 */
export type DigitalMessageBlock = {
kind: "dialogue" | "narration" | "plain";
text: string;
};
const quotePairs: Record<string, string> = {
'"': '"',
"“": "”",
"「": "」",
"『": "』",
"«": "»",
""": """
};
/** 跳过转义字符;引号不跨行,括号按同类型嵌套匹配,避免误吞后续内容。 */
function closingIndex(
text: string,
from: number,
open: string,
close: string,
nested = false
) {
let depth = 1;
for (let i = from; i < text.length; i++) {
if (text[i] === "\\") {
i++;
continue;
}
if (!nested && quotePairs[open] && text[i] === "\n") return -1;
if (nested && text.startsWith(open, i)) depth++;
if (text.startsWith(close, i)) {
depth--;
if (depth === 0) return i;
}
}
return -1;
}
/** 星号需要处于词边界,避免把乘法、文件名或普通单词里的星号视为排版。 */
function markerBoundary(text: string, index: number) {
return (
index === 0 || /[\s。!?!?,,;;::))\]”"」』»]/u.test(text[index - 1])
);
}
/**
* 解析累计正文而非单个 SSE delta。未闭合标记仅在流式/中断展示时延续当前样式;
* 旧版括号外文本按对白处理,有引号的旧开场白将引号外文字作为叙述,其他纯文本保留。
* 与 role-user/src/lib/digital-message-format.ts 保持同一实现和用例,独立构建时无需跨仓引用。
*/
export function parseDigitalMessage(
source: string,
streaming = false
): DigitalMessageBlock[] {
const blocks: DigitalMessageBlock[] = [];
for (const paragraph of source.replace(/\r\n?/g, "\n").split(/\n\s*\n/)) {
const parts: DigitalMessageBlock[] = [];
let legacyNarration = false;
const push = (kind: DigitalMessageBlock["kind"], text: string) => {
if (!text) return;
const last = parts[parts.length - 1];
if (last?.kind === kind) last.text += text;
else parts.push({ kind, text });
};
for (let i = 0; i < paragraph.length; ) {
const char = paragraph[i];
if (
char === "\\" &&
/[*"\\()()“”「」『』]/u.test(paragraph[i + 1] ?? "")
) {
push("plain", paragraph[i + 1]);
i += 2;
continue;
}
const quoteEnd = quotePairs[char];
if (quoteEnd) {
const close = closingIndex(paragraph, i + 1, char, quoteEnd);
const lineEnd = paragraph.indexOf("\n", i + 1);
const end =
close >= 0 ? close + 1 : lineEnd >= 0 ? lineEnd : paragraph.length;
push("dialogue", paragraph.slice(i, end));
i = end;
continue;
}
if (
char === "*" &&
markerBoundary(paragraph, i) &&
!/\s/u.test(paragraph[i + 1] ?? "")
) {
const marker = paragraph.startsWith("**", i) ? "**" : "*";
const close = closingIndex(
paragraph,
i + marker.length,
marker,
marker
);
if (close >= 0 || streaming) {
push(
marker === "**" ? "dialogue" : "narration",
paragraph.slice(i + marker.length, close >= 0 ? close : undefined)
);
i = close >= 0 ? close + marker.length : paragraph.length;
continue;
}
// 格式不完整的历史正文原样保留,不猜测后面的哪些字符属于标记。
push("plain", paragraph.slice(i));
break;
}
if ((char === "(" || char === "(") && markerBoundary(paragraph, i)) {
const close = closingIndex(
paragraph,
i + 1,
char,
char === "(" ? ")" : ")",
true
);
if (close >= 0 || streaming) {
legacyNarration = true;
push(
"narration",
paragraph.slice(i + 1, close >= 0 ? close : undefined)
);
i = close >= 0 ? close + 1 : paragraph.length;
continue;
}
push("plain", paragraph.slice(i));
break;
}
push("plain", char);
i++;
}
const hasDialogue = parts.some(part => part.kind === "dialogue");
for (const part of parts) {
const kind =
part.kind !== "plain"
? part.kind
: legacyNarration
? "dialogue"
: hasDialogue
? "narration"
: "plain";
for (const line of part.text.split(/\n+/)) {
if (line.trim()) blocks.push({ kind, text: line.trim() });
}
}
}
return blocks;
}
+687
View File
@@ -0,0 +1,687 @@
<script setup lang="ts">
/** 数字人内容库:角色、世界书、预设分别编辑,开场与示例使用聊天格式实时预览。 */
import { computed, onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { digital, type Content, type Entry } from "@/api/access";
import DigitalMessageText from "@/components/DigitalMessageText.vue";
const contents = ref<Content[]>([]),
kind = ref("character"),
query = ref(""),
loading = ref(false),
saving = ref(false),
visible = ref(false),
activeTab = ref("basic"),
edit = ref<Content | null>(null);
const overview = ref<{ modelConfigured: boolean } | null>(null);
const filtered = computed(() =>
contents.value.filter(
c =>
c.kind === kind.value &&
(!query.value || `${c.name} ${c.body.description}`.includes(query.value))
)
);
const kindNames: Record<string, string> = {
character: "角色卡",
worldbook: "世界书",
preset: "叙事预设"
};
const statusNames: Record<string, string> = {
draft: "草稿",
published: "已发布",
archived: "已下架"
};
/** 占位符仅用于当前预览,不改写编辑内容或数据库中的角色模板。 */
function previewText(value: string) {
return value
.replaceAll("{{char}}", edit.value?.name || "角色")
.replaceAll("{{user}}", "旅人");
}
const books = computed(() =>
contents.value.filter(c => c.kind === "worldbook" && c.status === "published")
);
const presets = computed(() =>
contents.value.filter(c => c.kind === "preset" && c.status === "published")
);
/** 站内封面由 H5/Web 提供,管理端域名不保存第二份素材。 */
function coverUrl(value: string) {
if (!value.startsWith("/")) return value;
const base =
import.meta.env.VITE_ROLE_USER_BASE_URL ||
(import.meta.env.VITE_APP_ENV === "production"
? "https://mrzhan.top"
: import.meta.env.VITE_APP_ENV === "develop"
? "https://dev.mrzhan.top"
: "http://localhost:3210");
return `${base}${value}`;
}
async function load() {
loading.value = true;
try {
const [list, stats] = await Promise.all([
digital<Content[]>("content"),
digital<{ modelConfigured: boolean }>("overview")
]);
contents.value = list;
overview.value = stats;
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "读取失败");
} finally {
loading.value = false;
}
}
function open(item?: Content) {
edit.value = item
? JSON.parse(JSON.stringify(item))
: {
id: crypto.randomUUID(),
kind: kind.value as Content["kind"],
name: "",
status: "draft",
body: {
description: "",
personality: "",
scenario: "",
greeting: "",
alternateGreetings: [],
examples: "",
systemPrompt: "",
gender: "female",
age: 25,
cover: "",
tags: [],
bookIds: [],
entries: [],
temperature: 0.9,
maxTokens: 700,
contextBudget: 12000,
worldBudget: 3500,
source: "项目原创"
}
};
activeTab.value = "basic";
visible.value = true;
}
function addEntry() {
if (!edit.value) return;
const entry: Entry = {
id: crypto.randomUUID(),
name: "新条目",
keys: [],
secondaryKeys: [],
content: "",
constant: false,
enabled: true,
priority: 100,
position: "after",
caseSensitive: false,
scanDepth: 6
};
edit.value.body.entries.push(entry);
}
async function save() {
if (!edit.value?.name.trim()) {
ElMessage.warning("请输入名称");
return;
}
saving.value = true;
try {
await digital(`content/${edit.value.id}`, "put", edit.value);
visible.value = false;
ElMessage.success("已保存");
await load();
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "保存失败");
} finally {
saving.value = false;
}
}
async function importJson(event: Event) {
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) return;
try {
if (file.size > 500000) throw new Error("文件不能超过500KB");
const data = JSON.parse(await file.text());
if (data.spec === "chara_card_v2" || data.spec === "chara_card_v3") {
const c = data.data;
open();
Object.assign(edit.value!, {
kind: "character",
name: String(c.name ?? "导入角色").slice(0, 120)
});
Object.assign(edit.value!.body, {
description: c.description ?? "",
personality: c.personality ?? "",
scenario: c.scenario ?? "",
greeting: c.first_mes ?? "",
examples: c.mes_example ?? "",
systemPrompt: c.system_prompt ?? "",
alternateGreetings: c.alternate_greetings ?? [],
tags: c.tags ?? [],
source: "手动导入角色卡 JSON"
});
if (c.character_book?.entries) {
edit.value!.body.bookIds = [];
ElMessage.info("角色已载入,内嵌世界书请单独导入内容库后关联");
}
} else if (data.kind && data.body) {
open();
edit.value = {
...data,
id: crypto.randomUUID(),
version: undefined,
status: "draft"
};
} else throw new Error("支持本项目导出格式或 Character Card V2/V3 JSON");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "导入失败");
}
(event.target as HTMLInputElement).value = "";
}
function exportJson(c: Content) {
const url = URL.createObjectURL(
new Blob([JSON.stringify(c, null, 2)], { type: "application/json" })
);
const a = document.createElement("a");
a.href = url;
a.download = `${c.id}.json`;
a.click();
URL.revokeObjectURL(url);
}
onMounted(load);
</script>
<template>
<div class="digital-content">
<div class="heading">
<div>
<h2>角色与内容库</h2>
<p>
角色定义人格,世界书补充背景,预设组织生成方式。发布后在前台使用。
</p>
</div>
<el-tag :type="overview?.modelConfigured ? 'success' : 'warning'">{{
overview?.modelConfigured ? "DeepSeek 已配置" : "模型待配置"
}}</el-tag>
</div>
<el-card shadow="never"
><div class="toolbar">
<el-radio-group v-model="kind"
><el-radio-button value="character">角色卡</el-radio-button
><el-radio-button value="worldbook">世界书</el-radio-button
><el-radio-button value="preset"
>叙事预设</el-radio-button
></el-radio-group
><el-input
v-model="query"
placeholder="搜索名称和描述"
clearable
style="max-width: 240px"
/><span class="grow" /><label class="import-button"
>导入 JSON<input
type="file"
accept="application/json,.json"
hidden
@change="importJson" /></label
><el-button type="primary" @click="open()"
>创建{{ kindNames[kind] }}</el-button
>
</div>
<el-table v-loading="loading" :data="filtered" stripe
><el-table-column label="内容" min-width="260"
><template #default="{ row }"
><div class="content-title">
<img
v-if="row.body.cover"
:src="coverUrl(row.body.cover)"
alt=""
/>
<div>
<strong>{{ row.name }}</strong>
<p>{{ row.body.description?.slice(0, 90) }}</p>
</div>
</div></template
></el-table-column
><el-table-column label="状态" width="100"
><template #default="{ row }"
><el-tag
:type="
row.status === 'published'
? 'success'
: row.status === 'draft'
? 'info'
: 'warning'
"
>{{ statusNames[row.status] }}</el-tag
></template
></el-table-column
><el-table-column label="设定" min-width="130"
><template #default="{ row }"
><span v-if="row.kind === 'character'"
>{{ row.body.age }}岁 ·
{{ row.body.gender === "male" ? "男性" : "女性" }}</span
><span v-else-if="row.kind === 'worldbook'"
>{{ row.body.entries?.length ?? 0 }}条背景</span
><span v-else>{{ row.body.maxTokens }}输出上限</span></template
></el-table-column
><el-table-column
prop="version"
label="版本"
width="70"
/><el-table-column label="操作" width="150" fixed="right"
><template #default="{ row }"
><el-button link type="primary" @click="open(row)">编辑</el-button
><el-button link @click="exportJson(row)">导出</el-button></template
></el-table-column
></el-table
>
</el-card>
<el-dialog
v-model="visible"
:title="edit?.name || `创建${kindNames[kind]}`"
width="min(940px, 95vw)"
destroy-on-close
:close-on-click-modal="false"
><el-form v-if="edit" label-position="top">
<el-tabs v-model="activeTab"
><el-tab-pane label="基本信息" name="basic"
><div class="form-grid">
<el-form-item label="名称" required
><el-input v-model="edit.name" maxlength="120" /></el-form-item
><el-form-item label="发布状态"
><el-select v-model="edit.status"
><el-option label="草稿" value="draft" /><el-option
label="发布"
value="published" /><el-option
label="下架"
value="archived" /></el-select
></el-form-item>
</div>
<el-form-item label="公开简介"
><el-input
v-model="edit.body.description"
type="textarea"
:rows="3"
/></el-form-item>
<div v-if="edit.kind === 'character'" class="form-grid">
<el-form-item label="性别"
><el-select v-model="edit.body.gender"
><el-option label="成年女性" value="female" /><el-option
label="成年男性"
value="male" /><el-option
label="其他"
value="other" /></el-select></el-form-item
><el-form-item label="年龄(必须成年)"
><el-input-number v-model="edit.body.age" :min="18" :max="1000"
/></el-form-item>
</div>
<el-form-item label="封面 URL(站内路径或 HTTPS)"
><el-input v-model="edit.body.cover" /></el-form-item
><el-form-item label="标签"
><el-select
v-model="edit.body.tags"
multiple
filterable
allow-create
default-first-option
placeholder="输入后回车添加标签" /></el-form-item
><el-form-item label="来源与署名"
><el-input v-model="edit.body.source" /></el-form-item
></el-tab-pane>
<el-tab-pane
v-if="edit.kind === 'character'"
label="人格与开场"
name="persona"
><el-alert
class="format-guide"
title="对白与叙述分段书写"
description="对白使用成对引号,如:“你来了。”;动作、神态、心理和环境用单星号包裹,如:*她合上书,抬头微笑。*。切换时空一行,下方预览与聊天使用相同的格式规则。"
:closable="false"
/><el-form-item label="性格、背景和关系"
><el-input
v-model="edit.body.personality"
type="textarea"
:rows="5" /></el-form-item
><el-form-item label="当前场景"
><el-input
v-model="edit.body.scenario"
type="textarea"
:rows="3" /></el-form-item
><el-form-item label="首次问候(支持 {{char}} / {{user}} 占位符)"
><div class="format-editor">
<el-input
v-model="edit.body.greeting"
type="textarea"
:rows="4"
placeholder="*她合上书,抬头看向你。*&#10;&#10;“你来了。”"
/>
<div
v-if="edit.body.greeting.trim()"
class="format-preview"
aria-label="首次问候展示预览"
>
<small>首次问候 · 展示效果</small>
<DigitalMessageText :text="previewText(edit.body.greeting)" />
</div></div></el-form-item
><el-form-item label="示例对白"
><div class="format-editor">
<el-input
v-model="edit.body.examples"
type="textarea"
:rows="4"
/>
<div
v-if="edit.body.examples.trim()"
class="format-preview"
aria-label="示例对白展示预览"
>
<small>示例对白 · 展示效果</small>
<DigitalMessageText :text="previewText(edit.body.examples)" />
</div></div></el-form-item
><el-form-item label="角色系统指令"
><el-input
v-model="edit.body.systemPrompt"
type="textarea"
:rows="3" /></el-form-item
><el-form-item label="其他开场"
><div style="width: 100%">
<div
v-for="(_, i) in edit.body.alternateGreetings"
:key="i"
class="entry-row"
>
<div class="format-editor">
<el-input
v-model="edit.body.alternateGreetings[i]"
type="textarea"
:rows="2"
/>
<div
v-if="edit.body.alternateGreetings[i].trim()"
class="format-preview"
:aria-label="`其他开场 ${i + 1} 展示预览`"
>
<small>其他开场 {{ i + 1 }} · 展示效果</small>
<DigitalMessageText
:text="previewText(edit.body.alternateGreetings[i])"
/>
</div>
</div>
<el-button @click="edit.body.alternateGreetings.splice(i, 1)"
>移除</el-button
>
</div>
<el-button @click="edit.body.alternateGreetings.push('')"
>增加开场</el-button
>
</div></el-form-item
></el-tab-pane
>
<el-tab-pane
v-if="edit.kind === 'character'"
label="关联内容"
name="links"
><el-form-item label="角色默认预设"
><el-select v-model="edit.body.presetId" clearable
><el-option
v-for="p in presets"
:key="p.id"
:label="p.name"
:value="p.id" /></el-select></el-form-item
><el-form-item label="世界书"
><el-select v-model="edit.body.bookIds" multiple
><el-option
v-for="b in books"
:key="b.id"
:label="b.name"
:value="b.id" /></el-select></el-form-item
></el-tab-pane>
<el-tab-pane
v-if="edit.kind === 'worldbook'"
label="背景条目"
name="entries"
><el-alert
title="高优先级条目先占预算。次关键词非空时,主关键词与至少一个次关键词须同时命中。常驻条目仍受预算限制。"
type="info"
:closable="false"
/><el-collapse
><el-collapse-item
v-for="(entry, i) in edit.body.entries"
:key="entry.id"
:title="`${i + 1}. ${entry.name}`"
:name="entry.id"
><div class="form-grid">
<el-form-item label="条目名"
><el-input v-model="entry.name" /></el-form-item
><el-form-item label="启用"
><el-switch v-model="entry.enabled"
/></el-form-item>
</div>
<el-form-item label="主关键词"
><el-select
v-model="entry.keys"
multiple
allow-create
filterable
default-first-option /></el-form-item
><el-form-item label="次关键词(可选)"
><el-select
v-model="entry.secondaryKeys"
multiple
allow-create
filterable
default-first-option /></el-form-item
><el-form-item label="注入内容"
><el-input v-model="entry.content" type="textarea" :rows="4"
/></el-form-item>
<div class="form-grid">
<el-form-item label="优先级"
><el-input-number
v-model="entry.priority"
:min="0"
:max="1000" /></el-form-item
><el-form-item label="扫描最近消息数"
><el-input-number
v-model="entry.scanDepth"
:min="1"
:max="30" /></el-form-item
><el-form-item label="注入位置"
><el-select v-model="entry.position"
><el-option label="角色设定前" value="before" /><el-option
label="角色设定后"
value="after" /></el-select></el-form-item
><el-form-item label="匹配方式"
><el-checkbox v-model="entry.constant">常驻</el-checkbox
><el-checkbox v-model="entry.caseSensitive"
>区分大小写</el-checkbox
></el-form-item
>
</div>
<el-button
type="danger"
plain
@click="edit.body.entries.splice(i, 1)"
>移除此条目</el-button
></el-collapse-item
></el-collapse
><el-button style="margin-top: 16px" @click="addEntry"
>增加条目</el-button
></el-tab-pane
>
<el-tab-pane
v-if="edit.kind === 'preset'"
label="生成编排"
name="generation"
><el-alert
class="format-guide"
title="系统统一区分对白和叙述"
description="本页设置叙事风格;对白使用引号、叙述使用单星号并分段的排版规则始终生效,发送、继续与重新生成共用。"
:closable="false" /><el-form-item label="系统指令"
><el-input
v-model="edit.body.systemPrompt"
type="textarea"
:rows="8"
/></el-form-item>
<div class="form-grid">
<el-form-item label="温度"
><el-input-number
v-model="edit.body.temperature"
:min="0"
:max="1.5"
:step="0.1" /></el-form-item
><el-form-item label="最大输出 tokens"
><el-input-number
v-model="edit.body.maxTokens"
:min="100"
:max="1500"
:step="100" /></el-form-item
><el-form-item label="上下文字符预算"
><el-input-number
v-model="edit.body.contextBudget"
:min="6000"
:max="24000"
:step="1000" /></el-form-item
><el-form-item label="世界书字符预算"
><el-input-number
v-model="edit.body.worldBudget"
:min="0"
:max="8000"
:step="500"
/></el-form-item>
</div>
<el-alert
title="云端 DeepSeek Flash,禁用思考模式以减少等待;温度效果取决于模型支持。共用前言保持中性并尊重边界;具体叙事由预设决定。后台对话方案优先于用户选择,方案快照不会随本页编辑或下架而改变。普通会话遇到下架预设会回退到角色默认或内置风格,下架世界书则跳过。上下文字符预算最少 6000。"
:closable="false"
/></el-tab-pane> </el-tabs></el-form
><template #footer
><el-button @click="visible = false">取消</el-button
><el-button type="primary" :loading="saving" @click="save"
>保存内容</el-button
></template
></el-dialog
>
</div>
</template>
<style scoped>
.format-guide {
margin-bottom: 18px;
}
.format-editor {
width: 100%;
min-width: 0;
}
.format-preview {
--digital-dialogue-ink: #fff5fc;
--digital-narration-ink: #c2b6c4;
max-height: 300px;
padding: 14px 18px;
margin-top: 10px;
overflow: auto;
font-size: 14px;
color: #e6dfe7;
background: #211c23;
border: 1px solid #ffffff12;
border-radius: 10px;
}
.format-preview > small {
display: block;
margin-bottom: 10px;
font-size: 11px;
color: #b5a6b8;
}
.heading {
display: flex;
gap: 16px;
align-items: center;
justify-content: space-between;
margin-bottom: 22px;
}
.heading h2 {
margin: 0 0 8px;
font-size: 24px;
font-weight: 600;
}
.heading p {
margin: 0;
font-size: 13px;
color: var(--el-text-color-secondary);
}
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
margin-bottom: 20px;
}
.grow {
flex: 1;
}
.content-title {
display: flex;
gap: 13px;
align-items: center;
padding: 10px 0;
}
.content-title img {
width: 48px;
height: 66px;
object-fit: cover;
border-radius: 6px;
}
.content-title strong {
font-weight: 500;
}
.content-title p {
max-width: 520px;
margin: 4px 0;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0 20px;
}
.el-select {
width: 100%;
}
.entry-row {
display: flex;
gap: 10px;
margin-bottom: 10px;
}
.import-button {
padding: 7px 12px;
font-size: 13px;
white-space: nowrap;
cursor: pointer;
border: 1px solid var(--el-border-color);
border-radius: 4px;
}
@media (width <= 650px) {
.heading {
flex-direction: column;
align-items: flex-start;
}
.form-grid {
grid-template-columns: 1fr;
}
}
</style>
+414
View File
@@ -0,0 +1,414 @@
<script setup lang="ts">
/** 实验图文教程二级页:固定目录与独立正文滚动,按实际阅读位置同步当前章节。 */
import {
nextTick,
onActivated,
onBeforeUnmount,
onMounted,
ref,
watch
} from "vue";
import { useRouter } from "vue-router";
import guide from "../../../docs/experiments/guide.json";
import screenshotSizes from "../../../docs/experiments/screenshots.json";
// 为懒加载截图预留真实比例,避免图片出现后章节位置发生跳动。
const sizes = screenshotSizes as Record<
string,
{ width: number; height: number }
>;
const router = useRouter();
const page = ref<HTMLElement>(),
body = ref<HTMLElement>(),
toc = ref<HTMLElement>();
const activeId = ref(guide.steps[0].id);
let frame = 0,
observer: ResizeObserver | undefined;
/** 正文是唯一阅读滚动容器,懒加载图片改变章节高度后也重新判定位置。 */
function updateReadingPosition() {
frame = 0;
if (!page.value?.offsetWidth || !body.value) return;
const available =
window.innerHeight - page.value.getBoundingClientRect().top - 24;
page.value.style.setProperty(
"--guide-height",
`${Math.max(360, available)}px`
);
const sections = Array.from(
body.value.querySelectorAll<HTMLElement>(".guide-section")
);
const top = body.value.getBoundingClientRect().top + 24;
let current = sections[0]?.id;
for (const section of sections) {
if (section.getBoundingClientRect().top <= top) current = section.id;
else break;
}
// 最后一章可能不足一屏;滚到底部时仍须选中它。
if (
body.value.scrollTop + body.value.clientHeight >=
body.value.scrollHeight - 2
)
current = sections.at(-1)?.id;
if (current) activeId.value = current.replace(/^guide-/, "");
}
function scheduleUpdate() {
if (!frame) frame = requestAnimationFrame(updateReadingPosition);
}
onMounted(() => {
window.addEventListener("resize", scheduleUpdate);
observer = new ResizeObserver(scheduleUpdate);
if (page.value) observer.observe(page.value);
if (body.value) {
observer.observe(body.value);
body.value
.querySelectorAll(".guide-section")
.forEach(section => observer!.observe(section));
}
scheduleUpdate();
});
onActivated(scheduleUpdate);
onBeforeUnmount(() => {
window.removeEventListener("resize", scheduleUpdate);
observer?.disconnect();
cancelAnimationFrame(frame);
});
watch(activeId, async id => {
await nextTick();
const button = toc.value?.querySelector<HTMLElement>(
`[data-section="${id}"]`
);
if (!button || !toc.value) return;
const item = button.getBoundingClientRect(),
menu = toc.value.getBoundingClientRect();
// 仅移动目录内部,避免 scrollIntoView 带动后台外层容器。
if (item.top < menu.top || item.bottom > menu.bottom)
toc.value.scrollTop +=
item.top - menu.top - toc.value.clientHeight / 2 + item.height / 2;
});
const images = guide.steps.flatMap(step =>
(step.images ?? []).map(image => `/guides/experiments/${image}.svg`)
);
/** 在当前二级页内滚动,不修改hash路由,也不触发任何实验写操作。 */
function jump(id: string) {
const section = body.value?.querySelector<HTMLElement>(`#guide-${id}`);
if (!section || !body.value) return;
body.value.scrollTo({
top:
body.value.scrollTop +
section.getBoundingClientRect().top -
body.value.getBoundingClientRect().top,
behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches
? "instant"
: "smooth"
});
}
</script>
<template>
<div ref="page" class="experiment-guide">
<header class="guide-heading">
<div>
<el-tag type="info">从零开始 · 图文教程</el-tag>
<h1>{{ guide.title }}</h1>
<p>{{ guide.intro }}</p>
</div>
<el-button @click="router.push('/digital/experiments')"
>返回测试方案</el-button
>
</header>
<el-alert
title="截图使用实际页面组件与隔离演示数据。红色编号对应下方操作;演示接入与统计状态不代表你的线上类型已经验收。点击图片可放大查看。"
type="info"
:closable="false"
/>
<div class="guide-layout">
<nav class="guide-toc" aria-label="教程目录">
<strong>本页目录</strong>
<div ref="toc" class="guide-links">
<button
v-for="step in guide.steps"
:key="step.id"
type="button"
:data-section="step.id"
:class="{ active: activeId === step.id }"
:aria-current="activeId === step.id ? 'location' : undefined"
@click="jump(step.id)"
>
{{ step.title }}
</button>
</div>
</nav>
<article
ref="body"
class="guide-body"
tabindex="0"
aria-label="教程正文"
@scroll="scheduleUpdate"
>
<section
v-for="step in guide.steps"
:id="`guide-${step.id}`"
:key="step.id"
class="guide-section"
>
<h2>{{ step.title }}</h2>
<p class="guide-lead">{{ step.lead }}</p>
<figure v-for="image in step.images ?? []" :key="image">
<el-image
:src="`/guides/experiments/${image}.svg`"
:style="{
aspectRatio: `${sizes[image].width} / ${sizes[image].height}`
}"
:alt="`${step.title},带红色箭头与编号的演示截图`"
:preview-src-list="images"
:initial-index="
images.indexOf(`/guides/experiments/${image}.svg`)
"
preview-teleported
lazy
fit="contain"
><template #error
><div class="image-error">
教程图片加载失败,请刷新重试。
</div></template
></el-image
>
<figcaption>隔离演示截图 · 点击放大 · 编号对应下方操作</figcaption>
<ol class="guide-callouts">
<li v-for="note in guide.captions[image]" :key="note">
{{ note }}
</li>
</ol>
</figure>
<ul>
<li v-for="line in step.bullets" :key="line">{{ line }}</li>
</ul>
<pre v-if="'code' in step"><code>{{ step.code }}</code></pre>
</section>
<footer class="guide-footer">
<p>
教程更新:{{
guide.updated
}}。开始操作前,请确认当前环境与目标账号。
</p>
<el-button @click="router.push('/digital/experiment-types')"
>去实验类型</el-button
><el-button
type="primary"
@click="router.push('/digital/experiments')"
>去测试方案</el-button
><el-button @click="router.push('/digital/experiment-users')"
>去实验用户分组</el-button
>
</footer>
</article>
</div>
</div>
</template>
<style scoped>
.experiment-guide {
display: flex;
flex-direction: column;
max-width: 1440px;
height: var(--guide-height, calc(100dvh - 134px));
min-height: 360px;
margin: 0 auto;
overflow: hidden;
}
.guide-heading {
display: flex;
gap: 24px;
align-items: flex-start;
justify-content: space-between;
margin-bottom: 24px;
}
.guide-heading h1 {
margin: 12px 0;
font-size: 28px;
}
.guide-heading p {
max-width: 800px;
line-height: 1.8;
color: var(--el-text-color-secondary);
}
.guide-layout {
display: grid;
flex: 1;
grid-template-columns: 220px minmax(0, 1fr);
gap: 32px;
min-height: 0;
margin-top: 24px;
}
.guide-toc {
display: flex;
flex-direction: column;
gap: 6px;
min-height: 0;
max-height: 100%;
padding: 16px;
overflow: hidden;
background: var(--el-bg-color);
border: 1px solid var(--el-border-color-lighter);
border-radius: 8px;
}
.guide-links {
display: flex;
flex-direction: column;
gap: 6px;
min-height: 0;
overflow-y: auto;
}
.guide-toc strong {
flex-shrink: 0;
padding: 4px 8px 12px;
}
.guide-toc button {
padding: 8px;
font: inherit;
font-size: 13px;
color: var(--el-text-color-regular);
text-align: left;
cursor: pointer;
background: transparent;
border: 0;
border-radius: 4px;
}
.guide-toc button.active {
font-weight: 600;
color: var(--el-color-primary);
background: var(--el-color-primary-light-9);
box-shadow: inset 3px 0 var(--el-color-primary);
}
.guide-body {
min-width: 0;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
}
.guide-body:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: -2px;
}
.guide-toc button:hover {
color: var(--el-color-primary);
background: var(--el-fill-color-light);
}
.guide-toc button:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: 2px;
}
.guide-section {
padding: 24px;
margin-bottom: 24px;
scroll-margin-top: 0;
background: var(--el-bg-color);
border: 1px solid var(--el-border-color-lighter);
border-radius: 8px;
}
.guide-section h2 {
margin: 0 0 12px;
font-size: 21px;
}
.guide-lead {
line-height: 1.8;
}
.guide-section figure {
margin: 20px 0;
}
.guide-section .el-image {
display: block;
width: 100%;
min-height: 100px;
border: 1px solid var(--el-border-color-lighter);
border-radius: 6px;
}
.guide-section figcaption {
margin-top: 8px;
font-size: 12px;
color: var(--el-text-color-secondary);
text-align: center;
}
.guide-section ul {
padding-left: 22px;
line-height: 1.9;
}
.guide-section li {
margin-bottom: 12px;
overflow-wrap: anywhere;
}
.guide-section pre {
padding: 16px;
overflow-x: auto;
font-size: 12px;
line-height: 1.8;
white-space: pre-wrap;
background: var(--el-fill-color-light);
border-radius: 6px;
}
.image-error {
padding: 24px;
color: var(--el-text-color-secondary);
text-align: center;
}
.guide-footer {
padding: 20px 0 32px;
line-height: 1.8;
}
.guide-footer p {
color: var(--el-text-color-secondary);
}
@media (width <= 900px) {
.guide-layout {
grid-template-rows: auto minmax(0, 1fr);
grid-template-columns: 1fr;
gap: 16px;
}
.guide-toc {
max-height: 140px;
}
.guide-heading {
flex-direction: column;
gap: 8px;
margin-bottom: 12px;
}
.guide-heading h1 {
font-size: 22px;
}
.guide-heading p {
margin: 0;
font-size: 12px;
}
.guide-section {
padding: 16px;
}
}
</style>
+391
View File
@@ -0,0 +1,391 @@
<script setup lang="ts">
/** 实验类型独立管理:注册契约、查看调用说明、按真实证据确认接入。 */
import { computed, onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { digital, type ExperimentType } from "@/api/access";
import ExperimentValue from "./experiment-value.vue";
const types = ref<ExperimentType[]>([]),
loading = ref(false),
saving = ref(false),
editing = ref(false),
integration = ref(false),
selected = ref<ExperimentType | null>(null),
valid = ref(true),
query = ref("");
const kinds: Record<string, string> = {
boolean: "开关(是/否)",
string: "字符串",
number: "数字",
json: "JSON 配置"
};
const draft = ref({
id: "",
name: "",
description: "",
valueType: "boolean" as ExperimentType["valueType"],
defaultValue: false as unknown,
enabled: true,
revision: undefined as number | undefined
});
const confirmation = ref({ verified: false, notes: "" });
const filtered = computed(() =>
types.value.filter(
t =>
!query.value ||
`${t.id} ${t.name}`.toLowerCase().includes(query.value.toLowerCase())
)
);
const contractLocked = computed(() => {
const old = types.value.find(t => t.id === draft.value.id);
return !!old && (!!old.builtin || !!old.runtime || !!old.hasPlans);
});
async function load() {
loading.value = true;
try {
types.value = await digital<ExperimentType[]>("experiment-types");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "加载失败");
} finally {
loading.value = false;
}
}
function open(t?: ExperimentType) {
draft.value = t
? {
id: t.id,
name: t.name,
description: t.description,
valueType: t.valueType,
defaultValue: JSON.parse(JSON.stringify(t.defaultValue)),
enabled: !!t.enabled,
revision: t.revision
}
: {
id: "",
name: "",
description: "",
valueType: "boolean",
defaultValue: false,
enabled: true,
revision: undefined
};
valid.value = true;
editing.value = true;
}
function changeKind(kind: ExperimentType["valueType"]) {
draft.value.defaultValue =
kind === "boolean"
? false
: kind === "number"
? 0
: kind === "json"
? {}
: "";
valid.value = true;
}
async function save() {
if (!draft.value.id || !draft.value.name.trim() || !valid.value)
return ElMessage.warning("请填写类型标识、名称和合法默认值");
saving.value = true;
try {
await digital(`experiment-types/${draft.value.id}`, "put", draft.value);
editing.value = false;
await load();
ElMessage.success("类型已保存;新类型需要接入应用并验收后才能发布方案");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "保存失败");
} finally {
saving.value = false;
}
}
function status(t: ExperimentType) {
if (t.integrationState === "confirmed") return "已确认接入";
return t.lastSeenAt && t.lastSeenRevision === t.contractRevision
? "待业务验收"
: "待应用调用";
}
function integrationInfo(t: ExperimentType) {
selected.value = t;
confirmation.value = { verified: false, notes: "" };
integration.value = true;
}
const example = computed(() =>
selected.value
? `const response = await fetch('/api/digital/decisions/${selected.value.id}');\nconst { data } = await response.json();\n// 将 data.value 应用于这个功能;只请求接口不会自动改变界面。\napplyYourFeature(data.value);`
: ""
);
async function confirm() {
if (!selected.value) return;
saving.value = true;
try {
await digital(`experiment-types/${selected.value.id}/integration`, "post", {
revision: selected.value.revision,
contractRevision: selected.value.contractRevision,
...confirmation.value
});
await load();
selected.value = types.value.find(t => t.id === selected.value?.id) ?? null;
ElMessage.success("接入验收已记录,可以发布该类型的测试方案");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "验收确认失败");
} finally {
saving.value = false;
}
}
async function refreshSelected() {
const id = selected.value?.id;
await load();
selected.value = types.value.find(t => t.id === id) ?? null;
}
function summary(value: unknown) {
const s = JSON.stringify(value) ?? "null";
return s.length > 100 ? s.slice(0, 100) + "…" : s;
}
onMounted(load);
</script>
<template>
<div class="types-page">
<div class="heading">
<div>
<h2>实验类型</h2>
<p>
先定义要测试的业务与返回值,再配置测试方案;所有类型由你创建,系统不预置实验类型。
</p>
</div>
<el-button type="primary" @click="open()">创建实验类型</el-button>
</div>
<el-alert
title="新类型不会凭名称自动影响应用。创建后先完成消费者接入、收到实际调用,再由你确认业务验收;未验收的类型只能保存草稿,不能启动方案。"
type="info"
:closable="false"
/>
<el-card shadow="never" class="content"
><div class="toolbar">
<el-input
v-model="query"
placeholder="搜索类型名称或标识"
clearable
style="max-width: 320px"
/><el-button @click="load">刷新</el-button>
</div>
<el-table v-loading="loading" :data="filtered"
><el-table-column label="类型 / 稳定标识" min-width="230"
><template #default="{ row }"
><strong>{{ row.name }}</strong>
<p class="secondary">{{ row.id }}</p></template
></el-table-column
><el-table-column label="数据格式" width="120"
><template #default="{ row }">{{
kinds[row.valueType]
}}</template></el-table-column
><el-table-column label="默认返回值" min-width="140"
><template #default="{ row }"
><code>{{ summary(row.defaultValue) }}</code></template
></el-table-column
><el-table-column label="接入状态" min-width="150"
><template #default="{ row }"
><el-tag
:type="
row.integrationState === 'confirmed' ? 'success' : 'warning'
"
>{{ status(row) }}</el-tag
>
</template></el-table-column
><el-table-column label="启用" width="80"
><template #default="{ row }">{{
row.enabled ? "是" : "否"
}}</template></el-table-column
><el-table-column label="操作" width="180" fixed="right"
><template #default="{ row }"
><el-button link type="primary" @click="open(row)">设置</el-button
><el-button link type="primary" @click="integrationInfo(row)"
>接入与验收</el-button
></template
></el-table-column
></el-table
></el-card
>
<el-dialog
v-model="editing"
:title="draft.revision ? '设置实验类型' : '创建实验类型'"
width="min(660px,95vw)"
:close-on-click-modal="false"
destroy-on-close
><el-form label-position="top"
><el-form-item label="类型名称" required
><el-input
v-model="draft.name"
maxlength="120"
placeholder="例如:推荐卡片数量" /></el-form-item
><el-form-item label="稳定标识" required
><el-input
v-model="draft.id"
:disabled="!!draft.revision"
placeholder="例如:recommendation_card_count"
maxlength="64"
/><small class="secondary"
>由你创建,应用通过这个标识读取决策。创建后不可改名。</small
></el-form-item
><el-form-item label="返回值的数据格式" required
><el-select
v-model="draft.valueType"
:disabled="contractLocked"
@change="changeKind"
><el-option
v-for="(label, key) in kinds"
:key="key"
:label="label"
:value="key" /></el-select></el-form-item
><el-form-item label="没有有效方案时的默认值" required
><ExperimentValue
:key="draft.valueType"
v-model="draft.defaultValue"
:kind="draft.valueType"
:disabled="contractLocked"
@valid="v => (valid = v)" /></el-form-item
><el-form-item label="业务说明"
><el-input
v-model="draft.description"
type="textarea"
:rows="3"
maxlength="2000" /></el-form-item
><el-form-item label="启用类型"
><el-switch v-model="draft.enabled" /></el-form-item
><el-alert
title="格式是数据契约,不是业务功能。已有测试方案的类型不能更改契约;未接入的新类型修改契约后需要重新验收。"
:closable="false" /></el-form
><template #footer
><el-button @click="editing = false">取消</el-button
><el-button type="primary" :loading="saving" @click="save"
>保存类型</el-button
></template
></el-dialog
>
<el-drawer
v-model="integration"
:title="`${selected?.name ?? ''} · 接入与验收`"
size="min(780px,96vw)"
><template v-if="selected"
><el-descriptions :column="1" border
><el-descriptions-item label="类型标识">{{
selected.id
}}</el-descriptions-item
><el-descriptions-item label="状态">{{
status(selected)
}}</el-descriptions-item
><el-descriptions-item label="数据契约版本">{{
selected.contractRevision
}}</el-descriptions-item
><el-descriptions-item label="最近应用调用">{{
selected.lastSeenAt
? new Date(selected.lastSeenAt).toLocaleString()
: "尚未收到调用"
}}</el-descriptions-item
><el-descriptions-item label="验收记录">{{
selected.integrationNotes || "尚未验收"
}}</el-descriptions-item></el-descriptions
>
<h3>应用调用方式</h3>
<p class="secondary">
H5/Web 使用已登录会话。服务端可调用 GET /api/digital/decisions/{{
selected.id
}},附带对应用户的 Bearer token。接口返回该用户的分组和值。
</p>
<pre>{{ example }}</pre>
<el-alert
title="此处展示接入说明,不会替应用调用接口或伪造接入成功。接口被调用后,也需要你确认真实功能已消费返回值。"
type="info"
:closable="false"
/><el-button class="refresh" @click="refreshSelected"
>刷新调用状态</el-button
><template v-if="selected.integrationState !== 'confirmed'"
><h3>确认业务验收</h3>
<el-checkbox v-model="confirmation.verified"
>我已在实际应用验证,功能确实使用了该类型返回值</el-checkbox
><el-input
v-model="confirmation.notes"
type="textarea"
:rows="3"
maxlength="2000"
placeholder="记录验收页面、功能及结果,至少8个字"
class="notes"
/><el-button
type="primary"
:loading="saving"
:disabled="
!selected.lastSeenAt ||
selected.lastSeenRevision !== selected.contractRevision ||
!confirmation.verified
"
@click="confirm"
>确认接入验收</el-button
></template
></template
></el-drawer
>
</div>
</template>
<style scoped>
.heading {
display: flex;
gap: 18px;
align-items: center;
justify-content: space-between;
margin-bottom: 22px;
}
.heading h2 {
margin: 0 0 8px;
font-size: 24px;
}
.heading p,
.secondary {
margin: 4px 0;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.content {
margin-top: 20px;
}
.toolbar {
display: flex;
gap: 12px;
margin-bottom: 18px;
}
.el-select {
width: 100%;
}
pre {
padding: 18px;
font-size: 12px;
line-height: 1.8;
white-space: pre-wrap;
background: var(--el-fill-color-light);
border-radius: 8px;
}
h3 {
margin: 24px 0 14px;
}
.refresh,
.notes {
margin: 16px 0;
}
code {
overflow-wrap: anywhere;
}
@media (width <= 700px) {
.heading {
flex-direction: column;
align-items: flex-start;
}
}
</style>
+882
View File
@@ -0,0 +1,882 @@
<script setup lang="ts">
/** 用户分组管理:区分实际入组与只读预估,按目标人群解释人工指定的生效条件。 */
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
digital,
type Experiment,
type ExperimentType,
type ExperimentUser
} from "@/api/access";
const route = useRoute(),
router = useRouter();
const plans = ref<Experiment[]>([]),
types = ref<ExperimentType[]>([]),
selectedId = ref(
typeof route.query.experiment === "string" ? route.query.experiment : ""
),
typeFilter = ref(""),
q = ref(""),
page = ref(1),
size = 20,
total = ref(0),
items = ref<ExperimentUser[]>([]),
loading = ref(false),
saving = ref(false),
editor = ref(false),
detail = ref<ExperimentUser | null>(null),
explanation = ref(false),
planDetail = ref(false),
candidates = ref<ExperimentUser[]>([]),
finding = ref(false);
const selected = computed(() =>
plans.value.find(p => p.id === selectedId.value)
);
const availablePlans = computed(() =>
plans.value.filter(p => !typeFilter.value || p.scope === typeFilter.value)
);
const form = ref({
account: "",
variant: "",
reason: "",
bypassAudience: false,
expiresAt: new Date(Date.now() + 86400000).toISOString()
});
const reasons: Record<string, string> = {
default: "无运行方案",
finished: "最终方案",
override: "人工指定",
outside_audience: "不在目标人群",
sticky: "已保存的稳定分组",
outside_traffic: "未进入实验流量",
allocated: "按规则预计分组(未写入)",
paused: "方案暂停,使用类型默认值",
draft: "草稿,使用类型默认值"
};
const states: Record<string, string> = {
draft: "草稿",
running: "运行中",
paused: "已暂停",
finished: "已结束"
};
let requestVersion = 0;
/** 请求序号保护快速切换方案时的分页结果,防止给旧上下文的账号误操作。 */
async function load() {
const version = ++requestVersion;
loading.value = true;
items.value = [];
try {
const params = new URLSearchParams({
q: q.value,
page: String(page.value),
size: String(size)
});
if (selectedId.value) params.set("experiment", selectedId.value);
const result = await digital<{ items: ExperimentUser[]; total: number }>(
`experiment-users?${params}`
);
if (version !== requestVersion) return;
items.value = result.items;
total.value = result.total;
} catch (e) {
if (version === requestVersion)
ElMessage.error(e instanceof Error ? e.message : "用户加载失败");
} finally {
if (version === requestVersion) loading.value = false;
}
}
function search() {
page.value = 1;
load();
}
function typeName(id: string) {
return types.value.find(t => t.id === id)?.name ?? id;
}
function summary(value: unknown) {
const text = JSON.stringify(value) ?? "null";
return text.length > 150 ? text.slice(0, 150) + "…" : text;
}
function overrideActive(row: ExperimentUser) {
return !!row.override && Date.parse(row.override.expiresAt) > Date.now();
}
function formatTime(value?: string) {
return value ? new Date(value).toLocaleString() : "—";
}
const audienceName = computed(() => {
const cfg = selected.value?.config;
if (!cfg) return "";
return {
all: "所有用户",
new: "新用户",
existing: "老用户",
specified: "指定名单"
}[cfg.audience];
});
/** 与服务端人群边界一致:新用户包含分界时刻,人工指定不自动改变名单。 */
function inAudience(row: ExperimentUser) {
const cfg = selected.value?.config;
if (!cfg) return false;
if (cfg.audience === "all") return true;
if (cfg.audience === "specified") return cfg.accounts.includes(row.account);
const date = Date.parse(row.createdAt),
cutoff = Date.parse(cfg.cutoff ?? "");
if (!Number.isFinite(date) || !Number.isFinite(cutoff)) return false;
return cfg.audience === "new" ? date >= cutoff : date < cutoff;
}
const outsideSelectedAudience = computed(
() => !!detail.value && !inAudience(detail.value)
);
const audienceExplanation = computed(() => {
if (!selected.value || !detail.value) return "请先选择用户";
const cfg = selected.value.config;
if (inAudience(detail.value))
return `此账号符合“${audienceName.value}”范围。`;
if (cfg.audience === "specified") return "此账号不在方案的指定名单中。";
return `此账号注册于 ${formatTime(detail.value.createdAt)},方案仅面向${audienceName.value}(以 ${formatTime(cfg.cutoff)} 为界)。`;
});
function overrideStatus(row: ExperimentUser) {
if (!overrideActive(row)) return "已过期";
if (selected.value?.state === "finished") return "方案已结束,不再生效";
if (selected.value?.state !== "running") return "待方案运行后生效";
if (!selected.value.config.groups.some(g => g.key === row.override?.variant))
return "原分组已移除";
if (!inAudience(row) && !row.override?.bypassAudience)
return "不符合目标人群,未生效";
return "生效中";
}
function allocationLabel(row: ExperimentUser) {
if (!row.decision) return "未选择方案";
return (
{
override: "手动指定",
sticky: "自动分组",
allocated: "预计自动分组",
finished: "最终统一分组"
}[row.decision.reason] ?? "未参与实验"
);
}
let candidateVersion = 0;
/** 独立查找账号,避免将指定用户限定为当前表格页;过期响应不能覆盖新的搜索。 */
async function findCandidates(query: string) {
const version = ++candidateVersion;
finding.value = true;
try {
const params = new URLSearchParams({ q: query, page: "1", size: "20" });
if (selectedId.value) params.set("experiment", selectedId.value);
const result = await digital<{ items: ExperimentUser[] }>(
`experiment-users?${params}`
);
if (version === candidateVersion)
candidates.value = result.items.filter(row => row.status === "ACTIVE");
} catch (e) {
if (version === candidateVersion)
ElMessage.error(e instanceof Error ? e.message : "查找账号失败");
} finally {
if (version === candidateVersion) finding.value = false;
}
}
function chooseAccount(account: string) {
const row = candidates.value.find(item => item.account === account);
if (row) {
detail.value = row;
form.value.variant =
row.override?.variant ??
row.decision?.variant ??
selected.value?.config.groups[0]?.key ??
"";
form.value.bypassAudience = !!row.override?.bypassAudience;
form.value.expiresAt = overrideActive(row)
? row.override!.expiresAt
: new Date(Date.now() + 86400000).toISOString();
}
}
function startAssign() {
detail.value = null;
form.value = {
account: "",
variant: selected.value?.config.groups[0]?.key ?? "",
reason: "",
bypassAudience: false,
expiresAt: new Date(Date.now() + 86400000).toISOString()
};
candidates.value = [];
editor.value = true;
findCandidates("");
}
function open(row: ExperimentUser) {
if (!selected.value) return;
detail.value = row;
form.value = {
account: row.account,
variant:
row.override?.variant ??
row.decision?.variant ??
selected.value.config.groups[0]?.key ??
"",
reason: "",
bypassAudience: !!row.override?.bypassAudience,
expiresAt: overrideActive(row)
? row.override!.expiresAt
: new Date(Date.now() + 86400000).toISOString()
};
candidates.value = [row];
editor.value = true;
}
async function save() {
const id = selectedId.value;
if (!id || !selected.value || selected.value.state === "finished") return;
if (!detail.value || !form.value.account)
return ElMessage.warning("请先查找并选择用户");
if (!selected.value.config.groups.some(g => g.key === form.value.variant))
return ElMessage.warning("请选择方案中有效的分组");
const expiry = Date.parse(form.value.expiresAt);
if (
!Number.isFinite(expiry) ||
expiry <= Date.now() ||
expiry > Date.now() + 30 * 86400000
)
return ElMessage.warning("有效期须在未来 30 天内");
if (outsideSelectedAudience.value && !form.value.bypassAudience)
return ElMessage.warning(
"此账号不符合目标人群,请确认是否作为测试账号加入"
);
if (form.value.reason.trim().length < 2)
return ElMessage.warning("请填写至少两个字的操作原因");
const wasRunning = selected.value.state === "running";
saving.value = true;
try {
await digital(`experiments/${id}/override`, "put", {
...form.value,
bypassAudience: outsideSelectedAudience.value && form.value.bypassAudience
});
editor.value = false;
await load();
ElMessage.success(
wasRunning
? "手动指定已保存,应用下次读取方案时生效"
: "手动指定已保存,方案运行后才会生效"
);
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "指定失败");
} finally {
saving.value = false;
}
}
async function restore(row: ExperimentUser) {
const id = selectedId.value;
if (!id) return;
try {
await ElMessageBox.confirm(
`取消 ${row.name} 的人工指定?已有稳定分组保留,没有稳定分组时按方案规则判定。`,
"取消手动指定",
{
confirmButtonText: "确认取消指定",
cancelButtonText: "取消",
type: "warning"
}
);
await digital(
`experiments/${id}/override/${encodeURIComponent(row.account)}`,
"delete"
);
await load();
ElMessage.success("已恢复自动分组");
} catch (e) {
if (e !== "cancel" && e !== "close")
ElMessage.error(e instanceof Error ? e.message : "恢复失败");
}
}
watch(selectedId, () => {
editor.value = false;
explanation.value = false;
planDetail.value = false;
++candidateVersion;
router.replace({
query: { ...route.query, experiment: selectedId.value || undefined }
});
search();
});
watch(
() => route.query.experiment,
value => {
selectedId.value = typeof value === "string" ? value : "";
}
);
watch(typeFilter, () => {
if (
selected.value &&
selected.value.scope !== typeFilter.value &&
typeFilter.value
)
selectedId.value = "";
});
onMounted(async () => {
try {
[plans.value, types.value] = await Promise.all([
digital<Experiment[]>("experiments"),
digital<ExperimentType[]>("experiment-types")
]);
if (selectedId.value && !selected.value) {
selectedId.value = "";
ElMessage.warning("原方案已不存在,请重新选择");
}
await load();
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "加载失败");
}
});
</script>
<template>
<div class="users-page">
<div class="heading">
<div>
<h2>实验用户分组</h2>
<p>选择测试方案,查看独立 C 端用户的分组,或为测试账号指定分组。</p>
</div>
<el-button :loading="loading" @click="load">刷新</el-button>
</div>
<el-card shadow="never">
<div class="plan-filters">
<el-form-item label="实验类型"
><el-select v-model="typeFilter" clearable placeholder="全部类型"
><el-option
v-for="t in types"
:key="t.id"
:value="t.id"
:label="t.name" /></el-select
></el-form-item>
<el-form-item label="当前测试方案"
><el-select
v-model="selectedId"
clearable
filterable
placeholder="请选择测试方案"
><el-option
v-for="p in availablePlans"
:key="p.id"
:value="p.id"
:label="p.name + ' · ' + states[p.state]" /></el-select
></el-form-item>
<el-tag
v-if="selected"
:type="selected.state === 'running' ? 'success' : 'info'"
>{{ states[selected.state] }}</el-tag
>
<el-button
v-if="selected"
link
type="primary"
@click="planDetail = true"
>方案详情</el-button
>
<el-button
link
type="primary"
@click="router.push('/digital/experiments')"
>查看测试方案</el-button
>
</div>
<div v-if="selected" class="plan-summary">
{{ typeName(selected.scope) }} · 目标人群:{{ audienceName }} ·
参与流量:{{ selected.config.traffic / 100 }}% ·
{{
selected.config.groups
.map(g => `${g.key} 组 ${g.weight / 100}%`)
.join(" / ")
}}
</div>
</el-card>
<el-alert
v-if="selected && selected.state !== 'running'"
class="content"
:title="
selected.state === 'finished'
? '方案已结束:所有用户使用最终分组,原手动指定不再生效。'
: `方案${states[selected.state]}:用户当前使用类型默认值。手动指定可提前保存,方案运行后才会生效。`
"
:closable="false"
type="warning"
/>
<el-card shadow="never" class="content">
<div class="table-toolbar">
<div>
<strong>用户列表</strong
><span class="secondary"> 共 {{ total }} 个账号</span>
<p class="secondary">
包含尚未参与实验的账号;“预计分组”仅供查看,实际调用后才会入组。
</p>
</div>
<div class="search-actions">
<el-input
v-model="q"
clearable
placeholder="用户名、姓名或账号 ID"
@keyup.enter="search"
@clear="search"
/><el-button :loading="loading" @click="search">查找用户</el-button
><el-button
type="primary"
:disabled="!selected || selected.state === 'finished' || loading"
@click="startAssign"
>指定用户分组</el-button
>
</div>
</div>
<el-table v-loading="loading" :data="items" empty-text="没有匹配的账号">
<el-table-column label="用户" min-width="230"
><template #default="{ row }"
><div class="user-cell">
<el-avatar :size="36">{{
(row.name || row.username).slice(0, 1)
}}</el-avatar>
<div>
<strong>{{ row.name }}</strong>
<p class="secondary">{{ row.username }} · {{ row.account }}</p>
<el-tag v-if="row.status !== 'ACTIVE'" type="info" size="small"
>账号已停用</el-tag
>
</div>
</div></template
></el-table-column
>
<el-table-column label="当前分组 / 返回值" min-width="210"
><template #default="{ row }"
><template v-if="row.decision"
><div class="group-value">
<el-tag v-if="row.decision.variant"
>{{ row.decision.variant }} 组</el-tag
><strong v-else>未参与实验</strong
><code>{{ summary(row.decision.value) }}</code>
</div>
<p class="secondary">
{{ reasons[row.decision.reason] ?? row.decision.reason }}
</p></template
><span v-else class="secondary">选择方案后查看</span></template
></el-table-column
>
<el-table-column label="分配方式" min-width="160"
><template #default="{ row }"
><el-tag
:type="row.decision?.reason === 'override' ? 'success' : 'info'"
>{{ allocationLabel(row) }}</el-tag
>
<p
v-if="row.override && row.decision?.reason !== 'override'"
class="secondary"
>
有手动指定 · {{ overrideStatus(row) }}
</p></template
></el-table-column
>
<el-table-column label="手动指定有效期" min-width="190"
><template #default="{ row }"
><template v-if="row.override"
><div>
{{ row.override.variant }} 组 · {{ overrideStatus(row) }}
</div>
<p class="secondary">
至 {{ formatTime(row.override.expiresAt) }}
</p></template
><span v-else class="secondary">—</span></template
></el-table-column
>
<el-table-column label="操作" min-width="240" fixed="right"
><template #default="{ row }"
><el-button
link
type="primary"
:disabled="!selected || loading"
@click="
detail = row;
explanation = true;
"
>详情</el-button
><el-button
link
type="primary"
:disabled="
!selected ||
selected.state === 'finished' ||
row.status !== 'ACTIVE' ||
loading
"
@click="open(row)"
>{{ row.override ? "修改指定" : "指定分组" }}</el-button
><el-button
v-if="row.override"
link
type="warning"
:disabled="loading || selected?.state === 'finished'"
@click="restore(row)"
>取消手动指定</el-button
></template
></el-table-column
>
</el-table>
<el-pagination
v-model:current-page="page"
:page-size="size"
:total="total"
layout="total, prev, pager, next"
class="pagination"
@current-change="load"
/>
</el-card>
<el-dialog
v-model="editor"
:title="detail?.override ? '修改用户指定分组' : '指定用户分组'"
width="min(640px,95vw)"
class="assignment-dialog"
:close-on-click-modal="false"
destroy-on-close
>
<el-form label-position="top">
<el-form-item label="当前测试方案"
><strong>{{ selected?.name }}</strong
><el-tag class="state-tag">{{
selected ? states[selected.state] : ""
}}</el-tag></el-form-item
>
<el-form-item label="用户" required
><el-select
v-model="form.account"
filterable
remote
:remote-method="findCandidates"
:loading="finding"
placeholder="输入用户名、姓名或账号 ID 查找"
@change="chooseAccount"
><el-option
v-for="row in candidates"
:key="row.account"
:value="row.account"
:label="`${row.name} · ${row.username} · ${row.account}`" /></el-select
></el-form-item>
<el-form-item label="指定分组" required
><el-radio-group v-model="form.variant" class="group-options"
><el-radio
v-for="group in selected?.config.groups ?? []"
:key="group.key"
:value="group.key"
border
><span>{{ group.key }} 组 · 返回 {{ summary(group.value) }}</span
><span class="secondary">
自动分流 {{ group.weight / 100 }}%</span
></el-radio
></el-radio-group
>
<p class="secondary">
手动指定不受分流比例限制,0% 的组也可以选择。
</p></el-form-item
>
<div v-if="detail" class="audience-note">
<strong>目标人群:{{ audienceName }}</strong>
<p>{{ audienceExplanation }}</p>
<template v-if="outsideSelectedAudience"
><el-checkbox v-model="form.bypassAudience"
>将此账号作为测试账号加入,仍使用上面指定的组</el-checkbox
>
<p class="secondary">
只对这个账号放开人群限制,不修改方案人群和其他用户的分组。
</p></template
>
</div>
<el-form-item label="有效期(最多 30 天)" required
><el-date-picker
:model-value="new Date(form.expiresAt)"
type="datetime"
:clearable="false"
@update:model-value="
v => {
if (v) form.expiresAt = new Date(v).toISOString();
}
"
/>
<p class="secondary">
到期后按方案规则恢复:符合目标人群时沿用原自动分组,否则重新判断。
</p></el-form-item
>
<el-form-item label="指定原因" required
><el-input
v-model="form.reason"
type="textarea"
:rows="2"
maxlength="500"
show-word-limit
placeholder="例如:测试账号验证新版界面(至少 2 个字)"
/></el-form-item>
<el-alert
:title="
selected?.state === 'running'
? '保存后,应用下次读取此方案时使用指定组的返回值。请在已接入该实验类型的前台验证效果。'
: '当前方案未运行,保存只记录指定关系,不会切换前台。方案运行且指定未过期后才会生效。'
"
:closable="false"
type="info"
/>
</el-form>
<template #footer
><el-button @click="editor = false">取消</el-button
><el-button
type="primary"
:loading="saving"
:disabled="
!detail || (outsideSelectedAudience && !form.bypassAudience)
"
@click="save"
>确认指定</el-button
></template
>
</el-dialog>
<el-dialog
v-model="explanation"
title="用户分组详情"
width="min(640px,95vw)"
>
<el-descriptions v-if="detail" :column="1" border>
<el-descriptions-item label="用户"
>{{ detail.name }} · {{ detail.account }}</el-descriptions-item
>
<el-descriptions-item label="注册时间">{{
formatTime(detail.createdAt)
}}</el-descriptions-item>
<el-descriptions-item label="当前结果"
>{{
detail.decision?.variant
? detail.decision.variant + " 组"
: "未参与实验"
}}
· {{ reasons[detail.decision?.reason ?? ""] }}
<pre>{{ JSON.stringify(detail.decision?.value, null, 2) }}</pre>
</el-descriptions-item>
<el-descriptions-item label="实际入组记录"
>{{
detail.assignment
? detail.assignment.variant +
" 组 · " +
formatTime(detail.assignment.createdAt)
: "尚无自动入组记录"
}}
<p class="secondary">
手动指定单独记录,不覆盖原自动分组。
</p></el-descriptions-item
>
<el-descriptions-item label="手动指定"
><template v-if="detail.override"
>{{ detail.override.variant }} 组 · {{ overrideStatus(detail) }}
<p>有效期至 {{ formatTime(detail.override.expiresAt) }}</p>
<p>原因:{{ detail.override.reason }}</p>
<p>
{{
detail.override.bypassAudience
? "已允许此测试账号不受目标人群限制"
: "仅在此账号符合目标人群时生效"
}}
</p></template
><span v-else>无</span></el-descriptions-item
>
<el-descriptions-item label="目标人群">{{
audienceExplanation
}}</el-descriptions-item> </el-descriptions
><el-alert
title="页面查询不会让用户入组或记录曝光;前台需实际接入并读取实验结果,才能验证功能变化。"
type="info"
:closable="false"
class="content"
/>
</el-dialog>
<el-dialog v-model="planDetail" title="当前方案详情" width="min(640px,95vw)"
><el-descriptions v-if="selected" :column="1" border
><el-descriptions-item label="测试方案"
>{{ selected.name }} ·
{{ states[selected.state] }}</el-descriptions-item
><el-descriptions-item label="实验类型">{{
typeName(selected.scope)
}}</el-descriptions-item
><el-descriptions-item label="目标人群"
>{{ audienceName
}}<span v-if="selected.config.cutoff"
>(注册时间分界:{{ formatTime(selected.config.cutoff) }})</span
><span v-if="selected.config.audience === 'specified'">
· {{ selected.config.accounts.length }} 个账号</span
></el-descriptions-item
><el-descriptions-item label="参与流量"
>{{ selected.config.traffic / 100 }}%</el-descriptions-item
><el-descriptions-item
v-for="group in selected.config.groups"
:key="group.key"
:label="group.key + ' 组'"
>{{ group.weight / 100 }}% · 返回
{{ summary(group.value) }}</el-descriptions-item
></el-descriptions
></el-dialog
>
</div>
</template>
<style scoped>
.heading,
.table-toolbar,
.plan-filters,
.search-actions,
.user-cell,
.group-value {
display: flex;
gap: 12px;
align-items: center;
}
.heading,
.table-toolbar {
justify-content: space-between;
margin-bottom: 20px;
}
.heading h2 {
margin: 0 0 8px;
font-size: 24px;
}
.heading p,
.secondary {
margin: 5px 0;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.content {
margin-top: 18px;
}
.plan-filters {
flex-wrap: wrap;
}
.plan-filters :deep(.el-form-item) {
display: block;
margin-bottom: 0;
}
.plan-filters :deep(.el-select) {
width: 300px;
}
.plan-filters :deep(.el-form-item:first-child .el-select) {
width: 200px;
}
.plan-summary {
margin-top: 18px;
font-size: 13px;
color: var(--el-text-color-secondary);
}
.search-actions {
flex-wrap: wrap;
}
.search-actions :deep(.el-input) {
width: 260px;
}
.search-actions :deep(.el-button + .el-button) {
margin-left: 0;
}
.pagination {
justify-content: flex-end;
margin-top: 20px;
}
.group-options {
display: flex;
gap: 10px;
width: 100%;
}
.group-options :deep(.el-radio) {
width: 100%;
height: auto;
min-height: 42px;
padding: 12px;
margin: 0;
}
.group-options :deep(.el-radio__label) {
overflow-wrap: anywhere;
white-space: normal;
}
.audience-note {
padding: 14px;
margin-bottom: 18px;
background: var(--el-fill-color-light);
border-radius: 6px;
}
.audience-note p {
margin: 8px 0;
}
.audience-note :deep(.el-checkbox) {
height: auto;
white-space: normal;
}
.audience-note :deep(.el-checkbox__label) {
white-space: normal;
}
.assignment-dialog :deep(.el-form-item__content > p) {
flex-basis: 100%;
}
.state-tag {
margin-left: 12px;
}
code,
pre {
overflow-wrap: anywhere;
white-space: pre-wrap;
}
code {
font-size: 12px;
}
.users-page :deep(.assignment-dialog .el-dialog__body) {
max-height: 65vh;
overflow-y: auto;
}
@media (width <= 1000px) {
.table-toolbar {
flex-direction: column;
align-items: flex-start;
}
}
@media (width <= 760px) {
.heading {
flex-direction: column;
align-items: flex-start;
}
.plan-filters {
flex-direction: column;
align-items: flex-start;
}
.plan-filters :deep(.el-form-item),
.plan-filters :deep(.el-select),
.search-actions,
.search-actions :deep(.el-input) {
width: 100%;
}
.pagination {
justify-content: flex-start;
}
}
</style>
+97
View File
@@ -0,0 +1,97 @@
<script setup lang="ts">
/** 类型化返回值编辑器,不执行输入内容,JSON语法错误显式阻止保存。 */
import { ref, watch } from "vue";
const props = withDefaults(
defineProps<{
modelValue: unknown;
kind: "string" | "number" | "boolean" | "json";
disabled?: boolean;
options?: Array<{ label: string; value: string }>;
}>(),
{ disabled: false, options: undefined }
);
const emit = defineEmits<{
"update:modelValue": [value: unknown];
valid: [value: boolean];
}>();
const raw = ref(JSON.stringify(props.modelValue, null, 2) ?? "null"),
error = ref("");
watch(
() => props.modelValue,
value => {
let current: unknown;
try {
current = JSON.parse(raw.value);
} catch {
current = undefined;
}
if (JSON.stringify(value) !== JSON.stringify(current))
raw.value = JSON.stringify(value, null, 2) ?? "null";
}
);
function jsonInput(value: string) {
raw.value = value;
try {
const parsed = JSON.parse(value);
error.value = "";
emit("update:modelValue", parsed);
emit("valid", true);
} catch {
error.value = "请输入有效 JSON,字符串需加双引号";
emit("valid", false);
}
}
</script>
<template>
<el-select
v-if="options"
:model-value="modelValue as string"
:disabled="disabled"
@update:model-value="v => emit('update:modelValue', v)"
><el-option
v-for="o in options"
:key="o.value"
:label="o.label"
:value="o.value"
/></el-select>
<el-switch
v-else-if="kind === 'boolean'"
:model-value="Boolean(modelValue)"
:disabled="disabled"
active-text="开启"
inactive-text="关闭"
@update:model-value="v => emit('update:modelValue', v)"
/>
<el-input-number
v-else-if="kind === 'number'"
:model-value="typeof modelValue === 'number' ? modelValue : 0"
:disabled="disabled"
@update:model-value="v => emit('update:modelValue', v ?? 0)"
/>
<el-input
v-else-if="kind === 'string'"
:model-value="String(modelValue ?? '')"
maxlength="12000"
:disabled="disabled"
@update:model-value="v => emit('update:modelValue', v)"
/>
<div v-else class="json-value">
<el-input
:model-value="raw"
type="textarea"
:rows="5"
:disabled="disabled"
@update:model-value="jsonInput"
/><small v-if="error" role="alert">{{ error }}</small>
</div>
</template>
<style scoped>
.el-select,
.json-value {
width: 100%;
}
.json-value small {
color: var(--el-color-danger);
}
</style>
+975
View File
@@ -0,0 +1,975 @@
<script setup lang="ts">
/** 测试方案管理:类型契约、百分比、人群与生命周期;用户分组使用独立页面。 */
import { computed, onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ExperimentValue from "./experiment-value.vue";
import { useRouter } from "vue-router";
import {
digital,
type Content,
type Experiment,
type ExperimentGroup,
type ExperimentType
} from "@/api/access";
type Account = { account: string; name: string; createdAt: string };
type Details = {
assignments: Array<{
account: string;
variant: string;
reason: string;
createdAt: string;
}>;
overrides: Array<{
account: string;
variant: string;
reason: string;
bypassAudience: boolean;
expiresAt: string;
}>;
metrics: Array<{
variant: string;
cohort: string;
decisions: number;
assignedUsers: number;
exposures: number;
exposedUsers: number;
}>;
funnel: Array<{
variant: string;
cohort: string;
eventName: string;
events: number;
users: number;
}>;
audits: Array<{
actor: string;
action: string;
detail: unknown;
createdAt: string;
}>;
};
const router = useRouter();
const scenes = ref<ExperimentType[]>([]);
const groupValid = ref<Record<string, boolean>>({});
const filterType = ref("");
const filtered = computed(() =>
list.value.filter(e => !filterType.value || e.scope === filterType.value)
);
const list = ref<Experiment[]>([]),
accounts = ref<Account[]>([]),
presets = ref<Content[]>([]),
loading = ref(false),
saving = ref(false),
edit = ref<Experiment | null>(null),
editor = ref(false),
selected = ref<Experiment | null>(null),
drawer = ref(false),
details = ref<Details | null>(null),
detailTab = ref("metrics");
const eventNames: Record<string, string> = {
conversation_started: "开启会话",
message_sent: "发送消息",
reply_complete: "回复完成",
reply_stopped: "主动停止",
reply_failed: "生成失败"
};
const stateNames: Record<string, string> = {
draft: "草稿",
running: "运行中",
paused: "已暂停",
finished: "已结束"
};
const audienceNames: Record<string, string> = {
all: "所有用户",
new: "新用户",
existing: "老用户",
specified: "指定名单"
};
const stats = computed(() => ({
running: list.value.filter(e => e.state === "running").length,
draft: list.value.filter(e => e.state === "draft").length,
finished: list.value.filter(e => e.state === "finished").length
}));
/** 页面以百分比编辑,接口保留整数精度,50%对应5000。 */
const trafficPercent = computed({
get: () => (edit.value?.config.traffic ?? 0) / 100,
set: (value: number | undefined) => {
if (edit.value) edit.value.config.traffic = Math.round((value ?? 0) * 100);
}
});
const groupTotal = computed(
() => edit.value?.config.groups.reduce((sum, g) => sum + g.weight, 0) ?? 0
);
const groupKeys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
/** 展示服务端按配置顺序累计的半开区间;仅解释首次自动分组,不覆盖稳定分组或人工指定。 */
function groupRanges(groups: ExperimentGroup[]) {
if (groups.reduce((sum, group) => sum + group.weight, 0) !== 10000)
return "分组比例合计达到 100% 后显示区间";
let start = 0;
return groups
.map(group => {
const text =
group.weight === 0
? `${group.key}:0%,不参与自动分流`
: `${group.key}:${start}~${start + group.weight - 1}`;
start += group.weight;
return text;
})
.join(";");
}
/** 数字提交后更新万分比并联动两组,避免输入中间值导致控件回显与区间不同步。 */
function setWeight(group: ExperimentGroup, percentage: number | undefined) {
if (!edit.value) return;
group.weight = Math.round((percentage ?? 0) * 100);
if (edit.value.config.groups.length === 2) {
const other = edit.value.config.groups.find(g => g.key !== group.key)!;
other.weight = 10000 - group.weight;
}
}
function addGroup() {
if (!edit.value || !editingType.value) return;
const key = groupKeys.find(
k => !edit.value!.config.groups.some(g => g.key === k)
);
if (key)
edit.value.config.groups.push({
key,
weight: 0,
value: JSON.parse(JSON.stringify(editingType.value.defaultValue))
});
}
function removeGroup(key: string) {
if (!edit.value || edit.value.config.groups.length <= 1) return;
edit.value.config.groups = edit.value.config.groups.filter(
g => g.key !== key
);
delete groupValid.value[key];
}
function distributeEvenly() {
if (!edit.value) return;
const groups = edit.value.config.groups;
const each = Math.floor(10000 / groups.length),
extra = 10000 % groups.length;
groups.forEach((g, i) => {
g.weight = each + (i < extra ? 1 : 0);
});
}
function fillRemaining(group: ExperimentGroup) {
group.weight = Math.max(0, 10000 - (groupTotal.value - group.weight));
}
function groupSummary(item: Experiment) {
return item.config.groups.map(g => `${g.key} ${g.weight / 100}%`).join(" · ");
}
const editingType = computed(() =>
scenes.value.find(s => s.id === edit.value?.scope)
);
const presetOptions = computed(() =>
editingType.value?.contract.optionsSource === "presets"
? presets.value.map(p => ({ label: p.name, value: p.id }))
: undefined
);
/** 类型切换只重置返回值,不改变用户已经配置的组别和比例。 */
function initializeValues(reset = false) {
if (!edit.value || !editingType.value) return;
const type = editingType.value;
for (const group of edit.value.config.groups) {
if (reset || group.value === undefined)
group.value = JSON.parse(
JSON.stringify(
type.valueType === "boolean" && group.key === "B"
? !type.defaultValue
: type.defaultValue
)
);
}
groupValid.value = {};
}
function users(item: Experiment) {
router.push({
path: "/digital/experiment-users",
query: { experiment: item.id }
});
}
function sceneName(id: string) {
return scenes.value.find(s => s.id === id)?.name ?? id;
}
async function load() {
loading.value = true;
try {
const [experiments, users, content, registered] = await Promise.all([
digital<Experiment[]>("experiments"),
digital<Account[]>("accounts"),
digital<Content[]>("content"),
digital<ExperimentType[]>("experiment-types")
]);
scenes.value = registered;
list.value = experiments;
accounts.value = users;
presets.value = content.filter(
c => c.kind === "preset" && c.status === "published"
);
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "加载失败");
} finally {
loading.value = false;
}
}
function open(item?: Experiment) {
edit.value = item
? JSON.parse(JSON.stringify(item))
: {
id: crypto.randomUUID(),
name: "",
scope: "",
state: "draft",
config: {
audience: "all",
accounts: [],
traffic: 10000,
groups: [
{ key: "A", weight: 5000, value: undefined },
{ key: "B", weight: 5000, value: undefined }
],
description: ""
}
};
edit.value.config.groups.sort((a, b) => a.key.localeCompare(b.key));
initializeValues();
editor.value = true;
}
async function save() {
if (!edit.value?.scope) return ElMessage.warning("请先创建或选择实验类型");
if (!edit.value?.name.trim()) return ElMessage.warning("请输入方案名称");
if (
["new", "existing"].includes(edit.value.config.audience) &&
!edit.value.config.cutoff
)
return ElMessage.warning("请选择注册时间分界");
if (
edit.value.config.audience === "specified" &&
!edit.value.config.accounts.length
)
return ElMessage.warning("请选择至少一个入组账号,验收时先选择自己");
if (groupTotal.value !== 10000)
return ElMessage.warning("所有分组比例合计必须为 100%");
if (Object.values(groupValid.value).some(valid => !valid))
return ElMessage.warning("请修正分组返回值的 JSON 格式");
saving.value = true;
try {
await digital(`experiments/${edit.value.id}`, "put", edit.value);
editor.value = false;
await load();
ElMessage.success("实验草稿已保存");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "保存失败");
} finally {
saving.value = false;
}
}
async function move(
item: Experiment,
state: "running" | "paused" | "finished",
winner?: string
) {
try {
await ElMessageBox.confirm(
state === "running"
? `启动「${item.name}」?启动后人群、比例和方案将冻结。`
: state === "paused"
? "暂停后用户使用类型默认返回值,已有分组保留。"
: `结束后所有用户采用 ${winner} 组返回值,实验不能重新启动。`,
state === "finished" ? "结束实验" : "确认状态变更",
{ type: "warning", confirmButtonText: "确认", cancelButtonText: "取消" }
);
await digital(`experiments/${item.id}/transition`, "post", {
state,
revision: item.revision,
winner
});
await load();
if (selected.value?.id === item.id) {
selected.value = list.value.find(v => v.id === item.id) ?? null;
await loadDetails();
}
ElMessage.success("状态已更新");
} catch (e) {
if (e === "cancel" || e === "close") return;
ElMessage.error(e instanceof Error ? e.message : "状态变更失败");
}
}
async function inspect(item: Experiment) {
selected.value = item;
details.value = null;
detailTab.value = "metrics";
drawer.value = true;
await loadDetails();
}
async function loadDetails() {
if (!selected.value) return;
try {
details.value = await digital<Details>(
`experiments/${selected.value.id}/details`
);
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "明细读取失败");
}
}
function accountLabel(account: string) {
const a = accounts.value.find(a => a.account === account);
return a ? `${a.name} (${account})` : account;
}
onMounted(load);
</script>
<template>
<div class="experiment-page">
<div class="heading">
<div>
<h2>测试方案</h2>
<p>
配置测什么、给谁看、分配多少流量;账号查询与人工分组在「实验用户分组」。
</p>
</div>
<div>
<el-button @click="router.push('/digital/experiments/guide')"
>操作指南</el-button
><el-button @click="router.push('/digital/experiment-types')"
>实验类型</el-button
><el-button @click="router.push('/digital/experiment-users')"
>实验用户分组</el-button
><el-button type="primary" @click="open()">创建测试方案</el-button>
</div>
</div>
<el-alert
title="第一次使用:点击「操作指南」查看完整图文教程,按“仅自己验收 → 正式实验 → 保留最终结果”走一遍。保存草稿不会改变前台,启动后才生效。"
type="info"
:closable="false"
style="margin-bottom: 16px"
/>
<div class="stats">
<el-card shadow="never"
><strong>{{ stats.running }}</strong
><span>运行中</span></el-card
><el-card shadow="never"
><strong>{{ stats.draft }}</strong
><span>待启动</span></el-card
><el-card shadow="never"
><strong>{{ stats.finished }}</strong
><span>已完成</span></el-card
>
</div>
<el-alert
title="同一类型消费标识只允许一个未结束方案。新老用户以账号创建时间与显式分界判定;暂停使用类型默认返回值,结束后保留所选组的返回值。"
type="info"
:closable="false"
style="margin-bottom: 20px"
/>
<el-card shadow="never"
><div class="toolbar">
<el-select
v-model="filterType"
clearable
placeholder="筛选实验类型"
style="max-width: 320px"
><el-option
v-for="t in scenes"
:key="t.id"
:label="t.name"
:value="t.id" /></el-select
><el-button @click="load">刷新</el-button>
</div>
<el-table v-loading="loading" :data="filtered"
><el-table-column label="实验" min-width="240"
><template #default="{ row }"
><strong>{{ row.name }}</strong>
<p class="secondary">{{ row.config.description }}</p>
<small class="secondary">{{ row.id }}</small></template
></el-table-column
><el-table-column label="实验类型" min-width="140"
><template #default="{ row }"
>{{ sceneName(row.scope) }}
<p
v-if="
scenes.find(t => t.id === row.scope)?.integrationState !==
'confirmed'
"
class="secondary"
>
待接入验收,暂不可启动
</p></template
></el-table-column
><el-table-column label="状态" width="100"
><template #default="{ row }"
><el-tag
:type="
row.state === 'running'
? 'success'
: row.state === 'paused'
? 'warning'
: 'info'
"
>{{ stateNames[row.state] }}</el-tag
></template
></el-table-column
><el-table-column label="人群 / 比例" min-width="180"
><template #default="{ row }"
><div>{{ audienceNames[row.config.audience] }}</div>
<small class="secondary"
>实验流量 {{ row.config.traffic / 100 }}%<br />{{
groupSummary(row)
}}</small
></template
></el-table-column
><el-table-column label="操作" min-width="260" fixed="right"
><template #default="{ row }"
><el-button
v-if="row.state === 'draft'"
link
type="primary"
@click="open(row)"
>编辑</el-button
><el-button
v-if="row.state === 'draft' || row.state === 'paused'"
link
type="success"
:disabled="
scenes.find(t => t.id === row.scope)?.integrationState !==
'confirmed'
"
@click="move(row, 'running')"
>{{ row.state === "draft" ? "启动" : "恢复" }}</el-button
><el-button
v-if="row.state === 'running'"
link
type="warning"
@click="move(row, 'paused')"
>暂停</el-button
><el-dropdown
v-if="row.state === 'running' || row.state === 'paused'"
@command="v => move(row, 'finished', v)"
><el-button link type="danger">结束实验</el-button
><template #dropdown
><el-dropdown-menu
><el-dropdown-item
v-for="group in row.config.groups"
:key="group.key"
:command="group.key"
>保留 {{ group.key }} 组</el-dropdown-item
></el-dropdown-menu
></template
></el-dropdown
><el-button link type="primary" @click="inspect(row)"
>效果与审计</el-button
><el-button link type="primary" @click="users(row)"
>实验用户分组</el-button
></template
></el-table-column
></el-table
><el-empty
v-if="!filtered.length && !loading"
description="从一条可解释的实验开始"
/></el-card>
<el-dialog
v-model="editor"
title="测试方案草稿"
class="experiment-dialog"
top="5vh"
width="min(880px,95vw)"
:close-on-click-modal="false"
destroy-on-close
><el-form v-if="edit" label-position="top">
<div class="form-grid">
<el-form-item label="名称" required
><el-input v-model="edit.name" maxlength="120"
/></el-form-item>
<el-form-item label="实验类型"
><el-select
v-model="edit.scope"
placeholder="选择实验类型"
@change="initializeValues(true)"
><el-option
v-for="s in scenes"
:key="s.id"
:value="s.id"
:label="s.name"
:disabled="!s.enabled" /></el-select
></el-form-item>
</div>
<el-form-item label="实验目标与验收指标"
><el-input
v-model="edit.config.description"
type="textarea"
:rows="2"
placeholder="例如:观察首次聊天转化和用户反馈,确认新版交互是否改善体验。" /></el-form-item
><el-divider content-position="left">实验人群</el-divider
><el-form-item label="入组范围"
><el-radio-group v-model="edit.config.audience"
><el-radio value="all">所有用户</el-radio
><el-radio value="new">新用户</el-radio
><el-radio value="existing">老用户</el-radio
><el-radio value="specified">指定名单</el-radio></el-radio-group
></el-form-item
><el-form-item
v-if="
edit.config.audience === 'new' ||
edit.config.audience === 'existing'
"
label="注册时间分界(新用户 ≥ 分界,老用户 < 分界)"
><el-date-picker
:model-value="
edit.config.cutoff ? new Date(edit.config.cutoff) : undefined
"
type="datetime"
placeholder="选择本地时间"
@update:model-value="
v => {
if (edit)
edit.config.cutoff = v
? new Date(v).toISOString()
: undefined;
}
"
/>
<p class="secondary">
按本地时区显示,服务端以 UTC 保存;创建时间取账号表。
</p></el-form-item
><el-form-item
v-if="edit.config.audience === 'specified'"
label="指定入组账号"
><el-select v-model="edit.config.accounts" multiple filterable
><el-option
v-for="a in accounts"
:key="a.account"
:label="`${a.name} (${a.account})`"
:value="a.account" /></el-select
></el-form-item>
<el-form-item label="进入实验的流量(%)">
<el-input-number
v-model="trafficPercent"
:min="0"
:max="100"
:precision="2"
:step="1"
/>
<p class="secondary">
目标人群中有多少人参与实验;未参与的用户使用类型默认返回值。
</p>
</el-form-item>
<section class="group-config" aria-label="分组配置">
<div class="group-heading">
<strong>分组配置</strong>
<el-tag
:type="groupTotal === 10000 ? 'success' : 'danger'"
role="status"
>合计 {{ (groupTotal / 100).toFixed(2) }}% / 100%</el-tag
>
</div>
<p class="secondary">
默认 A、B 两组,可添加到 Z。0%
组不会自动分流,仍可人工指定;返回值不因比例改变。
</p>
<div class="allocation-rule">
<strong>分组方式:按账号稳定随机分配</strong>
<p>
账号标识与本次测试方案 ID 共同算出固定的 0~9999
数字,落在哪个区间就进入哪组。
</p>
<p class="allocation-ranges">
当前自动分组区间:{{ groupRanges(edit.config.groups) }}
</p>
<p>
首次实际入组后保存分组,刷新、重新登录仍保持同组;有效的人工指定优先。比例是分配概率,不保证小样本人数恰好相等。
</p>
<el-collapse>
<el-collapse-item
title="查看具体计算步骤与优先顺序"
name="algorithm"
>
<ol class="allocation-steps">
<li>
先检查入组范围。“所有用户”表示所有账号都有资格参与,不按性别、年龄或账号尾号分组。
</li>
<li>
符合人群或获准越过人群限制的有效人工指定,直接使用指定组;否则已保存的稳定分组优先。
</li>
<li>
首次自动分配先计算流量桶,数字小于“进入实验的流量 ×
100”才入组;未入组使用类型默认返回值。
</li>
<li>
入组后另算分组桶,按上方各组比例的累计区间分配。流量桶和分组桶独立,0%组不接收自动流量。
</li>
</ol>
<p>
技术算法:SHA-256
处理下方字符串,取摘要前4字节的无符号大端整数,再对10000取余。
</p>
<code>dh-v1\0{用途}\0{测试方案ID}\0{账号标识}</code>
<p>
用途分别为 traffic(流量)和 variant(分组);\0
为分隔符。账号标识包含账号类型与ID。新建方案的ID不同,同一账号可能分到不同组。
</p>
</el-collapse-item>
</el-collapse>
</div>
<el-table :data="edit.config.groups" row-key="key">
<el-table-column label="组别" width="70"
><template #default="{ row }"
><el-tag type="info">{{ row.key }}</el-tag></template
></el-table-column
>
<el-table-column label="分流比例(%)" width="200"
><template #default="{ row }">
<el-input-number
:model-value="row.weight / 100"
:aria-label="`${row.key}组分流比例`"
:min="0"
:max="100"
:precision="2"
:step="1"
@change="v => setWeight(row, v)"
/>
<el-button
v-if="groupTotal < 10000"
link
type="primary"
@click="fillRemaining(row)"
>补足剩余</el-button
>
</template></el-table-column
>
<el-table-column label="返回值" min-width="220"
><template #default="{ row }">
<ExperimentValue
v-if="editingType"
:key="editingType.id + row.key"
v-model="row.value"
:kind="editingType.valueType"
:options="presetOptions"
@valid="v => (groupValid[row.key] = v)"
/>
<span v-else class="secondary">请先选择实验类型</span>
</template></el-table-column
>
<el-table-column label="操作" width="85"
><template #default="{ row }"
><el-button
link
type="danger"
:disabled="edit.config.groups.length <= 1"
:aria-label="`删除${row.key}组`"
@click="removeGroup(row.key)"
>删除</el-button
></template
></el-table-column
>
</el-table>
<div class="group-actions">
<el-button
:disabled="!editingType || edit.config.groups.length >= 26"
@click="addGroup"
>添加分组</el-button
><el-button @click="distributeEvenly">平均分配</el-button
><span class="secondary"
>{{ edit.config.groups.length }} / 26 组</span
>
</div>
<el-alert
v-if="groupTotal !== 10000"
type="error"
:closable="false"
title="请调整各组比例,合计达到 100% 后才能保存。"
/>
</section>
<el-alert
v-if="editingType && editingType.integrationState !== 'confirmed'"
type="warning"
title="该类型尚未完成应用接入验收,可以保存草稿;完成接入与验收后才能启动。"
:closable="false" />
<p v-if="editingType" class="secondary">
未参与实验或实验暂停时,返回类型默认值:{{
JSON.stringify(editingType.defaultValue)
}},不属于任何实验组。
</p>
<el-alert
title="启动前请核对人群和比例。启动后规则冻结,需要新规则时创建下一条实验。"
:closable="false" /></el-form
><template #footer
><el-button @click="editor = false">取消</el-button
><el-button
type="primary"
:loading="saving"
:disabled="
groupTotal !== 10000 || Object.values(groupValid).some(v => !v)
"
@click="save"
>保存草稿</el-button
></template
></el-dialog
>
<el-drawer
v-model="drawer"
:title="selected?.name"
size="min(960px,96vw)"
destroy-on-close
><template v-if="selected"
><div class="detail-summary">
<el-tag>{{ stateNames[selected.state] }}</el-tag
><span>{{ sceneName(selected.scope) }}</span
><small>版本 {{ selected.revision }}</small>
</div>
<div class="allocation-rule">
<strong>分组方式:按账号稳定随机分配</strong>
<p>
账号标识与本次方案 ID 计算固定的 0~9999
数字,按累计比例区间首次分组;已保存的稳定分组保留,有效人工指定优先。
</p>
<p class="allocation-ranges">
当前自动分组区间:{{ groupRanges(selected.config.groups) }}
</p>
</div>
<el-table :data="selected.config.groups" class="group-details">
<el-table-column prop="key" label="组别" width="80" />
<el-table-column label="分流比例" width="120"
><template #default="{ row }"
>{{ row.weight / 100 }}%</template
></el-table-column
>
<el-table-column label="返回值"
><template #default="{ row }"
><code>{{ JSON.stringify(row.value) }}</code></template
></el-table-column
>
</el-table>
<el-tabs v-model="detailTab"
><el-tab-pane label="效果概览" name="metrics"
><el-alert
title="只统计实际入组流量,人工指定单列。曝光在可见页面渲染后记录,漏斗按服务端决策归因;仅作描述性统计。"
type="info"
:closable="false" /><el-table :data="details?.metrics ?? []"
><el-table-column prop="variant" label="组别" /><el-table-column
label="人群"
><template #default="{ row }">{{
row.cohort === "manual" ? "人工指定" : "规则分组"
}}</template></el-table-column
><el-table-column
prop="decisions"
label="决策次数" /><el-table-column
prop="assignedUsers"
label="决策人数" /><el-table-column
prop="exposures"
label="曝光次数" /><el-table-column
prop="exposedUsers"
label="曝光人数" /></el-table
><el-empty
v-if="!details?.metrics.length"
description="尚无决策记录" />
<h3 style="margin: 24px 0 12px">使用漏斗</h3>
<el-table :data="details?.funnel ?? []"
><el-table-column prop="variant" label="组别" /><el-table-column
label="人群"
><template #default="{ row }">{{
row.cohort === "manual" ? "人工指定" : "规则分组"
}}</template></el-table-column
><el-table-column label="行为"
><template #default="{ row }">{{
eventNames[row.eventName]
}}</template></el-table-column
><el-table-column prop="events" label="次数" /><el-table-column
prop="users"
label="人数" /></el-table
></el-tab-pane>
<el-tab-pane label="操作审计" name="audits"
><el-timeline
><el-timeline-item
v-for="(a, i) in details?.audits ?? []"
:key="i"
:timestamp="new Date(a.createdAt).toLocaleString()"
><strong>{{ a.action }}</strong>
<p>{{ accountLabel(a.actor) }}</p>
<pre>{{
typeof a.detail === "string"
? a.detail
: JSON.stringify(a.detail, null, 2)
}}</pre>
</el-timeline-item></el-timeline
></el-tab-pane
></el-tabs
></template
></el-drawer
>
</div>
</template>
<style scoped>
.allocation-rule {
padding: 12px 14px;
margin: 12px 0;
font-size: 13px;
line-height: 1.7;
background: var(--el-fill-color-light);
border: 1px solid var(--el-border-color-lighter);
border-radius: 6px;
}
.allocation-rule p {
margin: 6px 0;
}
.allocation-ranges {
font-variant-numeric: tabular-nums;
}
.allocation-rule code {
overflow-wrap: anywhere;
}
.allocation-steps {
padding-left: 20px;
margin: 8px 0;
}
:global(.experiment-dialog) {
display: flex;
flex-direction: column;
max-height: 90vh;
margin-bottom: 0;
}
:global(.experiment-dialog .el-dialog__body) {
min-height: 0;
overflow-y: auto;
}
.group-details {
margin-bottom: 20px;
}
.group-config {
margin: 8px 0 20px;
}
.group-heading,
.group-actions {
display: flex;
gap: 12px;
align-items: center;
}
.group-heading {
justify-content: space-between;
margin-bottom: 12px;
}
.group-actions {
margin: 16px 0;
}
.heading {
display: flex;
gap: 15px;
align-items: center;
justify-content: space-between;
margin-bottom: 24px;
}
.heading h2 {
margin: 0 0 8px;
font-size: 24px;
font-weight: 600;
}
.heading p,
.secondary {
margin: 4px 0;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
margin-bottom: 20px;
}
.stats strong {
display: block;
font-size: 30px;
font-weight: 500;
}
.stats span {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0 20px;
}
.el-select {
width: 100%;
}
.toolbar {
display: flex;
gap: 15px;
align-items: center;
justify-content: space-between;
margin-bottom: 20px;
}
.detail-summary {
display: flex;
gap: 15px;
align-items: center;
margin-bottom: 20px;
}
.detail-summary span {
font-size: 13px;
}
.detail-summary small {
margin-left: auto;
color: var(--el-text-color-secondary);
}
pre {
max-height: 260px;
padding: 12px;
overflow: auto;
font-size: 11px;
word-break: break-word;
white-space: pre-wrap;
background: var(--el-fill-color-light);
border-radius: 6px;
}
.el-dropdown {
margin: 0 10px;
vertical-align: middle;
}
@media (width <= 650px) {
.form-grid {
grid-template-columns: 1fr;
}
.heading {
flex-direction: column;
align-items: flex-start;
}
.stats {
gap: 8px;
}
.toolbar {
flex-wrap: wrap;
}
}
</style>
+659
View File
@@ -0,0 +1,659 @@
<script setup lang="ts">
/** 独立 C 端用户管理:开户、内容偏好、停用、改密与区分对白/叙述的持久化聊天记录。 */
import { onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import DigitalMessageText from "@/components/DigitalMessageText.vue";
import {
digital,
type DigitalUser,
type UserConversation,
type UserChatMessage
} from "@/api/access";
const q = ref(""),
status = ref(""),
page = ref(1),
total = ref(0),
loading = ref(false),
users = ref<DigitalUser[]>([]);
const creating = ref(false),
saving = ref(false),
createForm = ref({
username: "",
displayName: "",
password: "",
nsfwEnabled: true
});
const editing = ref<DigitalUser | null>(null),
editForm = ref({ displayName: "", status: "ACTIVE", nsfwEnabled: true });
const resetTarget = ref<DigitalUser | null>(null),
newPassword = ref("");
const selected = ref<DigitalUser | null>(null),
history = ref(false),
conversations = ref<UserConversation[]>([]),
conversationPage = ref(1),
conversationTotal = ref(0),
conversationLoading = ref(false);
const active = ref<UserConversation | null>(null),
messages = ref<UserChatMessage[]>([]),
messagePage = ref(1),
messageTotal = ref(0),
messageLoading = ref(false);
let listVersion = 0,
chatVersion = 0,
messageVersion = 0;
const time = (value: string | null) =>
value ? new Date(value).toLocaleString() : "—";
const states: Record<string, string> = {
complete: "已完成",
stopped: "已停止",
failed: "生成失败",
generating: "生成中",
superseded: "旧版本"
};
/** 请求编号避免快速切换用户时把旧请求结果写进新用户的聊天面板。 */
async function load() {
const version = ++listVersion;
loading.value = true;
try {
const params = new URLSearchParams({
q: q.value,
page: String(page.value),
size: "20"
});
if (status.value) params.set("status", status.value);
const r = await digital<{ items: DigitalUser[]; total: number }>(
`users?${params}`
);
if (version === listVersion) {
users.value = r.items;
total.value = r.total;
}
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "加载失败");
} finally {
if (version === listVersion) loading.value = false;
}
}
function search() {
page.value = 1;
load();
}
async function create() {
if (
!createForm.value.username.trim() ||
!createForm.value.displayName.trim() ||
createForm.value.password.length < 8
)
return ElMessage.warning("请填写账号、昵称及至少8位密码");
saving.value = true;
try {
await digital("users", "post", createForm.value);
creating.value = false;
createForm.value = {
username: "",
displayName: "",
password: "",
nsfwEnabled: true
};
search();
ElMessage.success("C 端账号已创建,可在星港前台登录");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "创建失败");
} finally {
saving.value = false;
}
}
function edit(user: DigitalUser) {
editing.value = user;
editForm.value = {
displayName: user.displayName,
status: user.status,
nsfwEnabled: user.nsfwEnabled ?? true
};
}
async function saveEdit() {
if (!editing.value) return;
saving.value = true;
try {
await digital(`users/${editing.value.id}`, "patch", editForm.value);
editing.value = null;
await load();
ElMessage.success("用户资料已保存");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "保存失败");
} finally {
saving.value = false;
}
}
async function resetPassword() {
if (!resetTarget.value) return;
if (newPassword.value.length < 8) return ElMessage.warning("密码至少8位");
saving.value = true;
try {
await digital(`users/${resetTarget.value.id}/password`, "post", {
password: newPassword.value
});
newPassword.value = "";
resetTarget.value = null;
ElMessage.success("密码已重置,该用户需要重新登录");
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : "重置失败");
} finally {
saving.value = false;
}
}
async function openHistory(user: DigitalUser) {
selected.value = user;
history.value = true;
conversationPage.value = 1;
active.value = null;
messages.value = [];
++messageVersion;
await loadConversations();
}
async function loadConversations() {
if (!selected.value) return;
const version = ++chatVersion;
conversationLoading.value = true;
conversations.value = [];
try {
const r = await digital<{ items: UserConversation[]; total: number }>(
`users/${selected.value.id}/conversations?page=${conversationPage.value}&size=20`
);
if (version === chatVersion) {
conversations.value = r.items;
conversationTotal.value = r.total;
}
} catch (e) {
if (version === chatVersion)
ElMessage.error(e instanceof Error ? e.message : "会话加载失败");
} finally {
if (version === chatVersion) conversationLoading.value = false;
}
}
async function chooseConversation(c: UserConversation) {
active.value = c;
messagePage.value = 1;
await loadMessages();
}
async function loadMessages() {
if (!selected.value || !active.value) return;
const version = ++messageVersion;
messageLoading.value = true;
messages.value = [];
try {
const r = await digital<{ items: UserChatMessage[]; total: number }>(
`users/${selected.value.id}/conversations/${active.value.id}/messages?page=${messagePage.value}&size=30`
);
if (version === messageVersion) {
messages.value = r.items;
messageTotal.value = r.total;
}
} catch (e) {
if (version === messageVersion)
ElMessage.error(e instanceof Error ? e.message : "聊天记录加载失败");
} finally {
if (version === messageVersion) messageLoading.value = false;
}
}
function closeHistory() {
++chatVersion;
++messageVersion;
selected.value = null;
active.value = null;
messages.value = [];
}
onMounted(load);
</script>
<template>
<div class="customer-page">
<div class="heading">
<div>
<h2>用户管理</h2>
<p>C 端账号独立于后台管理员,由后台开通。聊天记录按用户和会话查看。</p>
</div>
<el-button
type="primary"
@click="
createForm = {
username: '',
displayName: '',
password: '',
nsfwEnabled: true
};
creating = true;
"
>创建 C 端用户</el-button
>
</div>
<el-card shadow="never"
><div class="filters">
<el-input
v-model="q"
clearable
placeholder="搜索账号、昵称或用户 ID"
@keyup.enter="search"
@clear="search"
/><el-select
v-model="status"
clearable
placeholder="全部状态"
@change="search"
><el-option value="ACTIVE" label="正常" /><el-option
value="INACTIVE"
label="已停用" /></el-select
><el-button :loading="loading" @click="search">查询</el-button>
</div>
<el-table
v-loading="loading"
:data="users"
empty-text="暂无 C 端用户,可点击上方创建"
><el-table-column label="用户" min-width="220"
><template #default="{ row }"
><strong>{{ row.displayName }}</strong>
<p class="secondary">
{{ row.username }} · UID {{ row.id }}
</p></template
></el-table-column
><el-table-column label="状态" width="100"
><template #default="{ row }"
><el-tag :type="row.status === 'ACTIVE' ? 'success' : 'info'">{{
row.status === "ACTIVE" ? "正常" : "已停用"
}}</el-tag></template
></el-table-column
><el-table-column label="NSFW" width="100"
><template #default="{ row }"
><el-tag :type="row.nsfwEnabled === false ? 'info' : 'success'">{{
row.nsfwEnabled === false ? "已关闭" : "已开启"
}}</el-tag></template
></el-table-column
><el-table-column
prop="conversations"
label="会话数"
width="90"
/><el-table-column
prop="messages"
label="消息数"
width="90"
/><el-table-column label="创建时间" min-width="175"
><template #default="{ row }">{{
time(row.createdAt)
}}</template></el-table-column
><el-table-column label="最近登录" min-width="175"
><template #default="{ row }">{{
time(row.lastLoginAt)
}}</template></el-table-column
><el-table-column label="操作" min-width="235" fixed="right"
><template #default="{ row }"
><el-button link type="primary" @click="openHistory(row)"
>聊天记录</el-button
><el-button link type="primary" @click="edit(row)">编辑</el-button
><el-button
link
type="warning"
@click="
resetTarget = row;
newPassword = '';
"
>重置密码</el-button
></template
></el-table-column
></el-table
>
<el-pagination
v-model:current-page="page"
:page-size="20"
:total="total"
layout="total, prev, pager, next"
@current-change="load"
/>
</el-card>
<el-dialog
v-model="creating"
title="创建 C 端用户"
width="min(520px,95vw)"
:close-on-click-modal="false"
><el-form label-position="top"
><el-form-item label="登录账号" required
><el-input
v-model="createForm.username"
maxlength="120"
placeholder="字母、数字、手机号或邮箱"
autocomplete="off" /></el-form-item
><el-form-item label="用户昵称" required
><el-input
v-model="createForm.displayName"
maxlength="120" /></el-form-item
><el-form-item label="初始密码" required
><el-input
v-model="createForm.password"
type="password"
show-password
maxlength="128"
placeholder="至少8位"
autocomplete="new-password" /></el-form-item
><el-form-item label="NSFW 成人内容"
><el-switch
v-model="createForm.nsfwEnabled"
active-text="开启"
inactive-text="关闭"
/>
<p class="secondary">
登录账号默认开启,用户可在前台保存自己的选择。
</p>
</el-form-item></el-form
><template #footer
><el-button @click="creating = false">取消</el-button
><el-button type="primary" :loading="saving" @click="create"
>创建用户</el-button
></template
></el-dialog
>
<el-dialog
:model-value="!!editing"
title="编辑 C 端用户"
width="min(520px,95vw)"
@close="editing = null"
><el-form label-position="top"
><el-form-item label="登录账号">{{ editing?.username }}</el-form-item
><el-form-item label="用户昵称"
><el-input
v-model="editForm.displayName"
maxlength="120" /></el-form-item
><el-form-item label="账号状态"
><el-radio-group v-model="editForm.status"
><el-radio value="ACTIVE">正常</el-radio
><el-radio value="INACTIVE">停用</el-radio></el-radio-group
></el-form-item
><el-form-item label="NSFW 成人内容"
><el-switch
v-model="editForm.nsfwEnabled"
active-text="开启"
inactive-text="关闭"
/>
<p class="secondary">保存后用于该账号的后续回复。</p>
</el-form-item></el-form
><el-alert
title="停用后用户无法登录,已有会话记录仍保留。"
:closable="false"
/><template #footer
><el-button @click="editing = null">取消</el-button
><el-button type="primary" :loading="saving" @click="saveEdit"
>保存</el-button
></template
></el-dialog
>
<el-dialog
:model-value="!!resetTarget"
title="重置 C 端用户密码"
width="min(520px,95vw)"
@close="
resetTarget = null;
newPassword = '';
"
><p>{{ resetTarget?.displayName }} · {{ resetTarget?.username }}</p>
<el-input
v-model="newPassword"
type="password"
show-password
maxlength="128"
autocomplete="new-password"
placeholder="设置至少8位新密码"
/>
<p class="secondary">
重置后该 C 端账号的旧登录状态失效,不影响同名后台账号。
</p>
<template #footer
><el-button @click="resetTarget = null">取消</el-button
><el-button type="primary" :loading="saving" @click="resetPassword"
>确认重置</el-button
></template
></el-dialog
>
<el-dialog
v-model="history"
:title="`${selected?.displayName ?? ''} · 聊天记录`"
width="min(1280px,96vw)"
top="4vh"
@closed="closeHistory"
>
<div class="history-layout">
<aside v-loading="conversationLoading" class="conversation-list">
<p class="secondary">
{{ selected?.username }} · {{ conversationTotal }} 个会话
</p>
<el-empty
v-if="!conversations.length && !conversationLoading"
description="暂无聊天记录"
/><button
v-for="c in conversations"
:key="c.id"
class="conversation"
:class="{ active: active?.id === c.id }"
@click="chooseConversation(c)"
>
<strong>{{ c.characterName }}</strong
><span>{{ c.title }}</span
><small
>{{ c.messages }} 条消息 · {{ time(c.updatedAt) }}</small
></button
><el-pagination
v-model:current-page="conversationPage"
small
:page-size="20"
:total="conversationTotal"
layout="prev, pager, next"
@current-change="loadConversations"
/>
</aside>
<section v-loading="messageLoading" class="message-pane">
<template v-if="active"
><header>
<strong>{{ active.characterName }} · {{ active.title }}</strong
><el-button size="small" @click="loadMessages"
>刷新记录</el-button
>
</header>
<p class="secondary">
第1页为最新记录,每页按发送顺序展示;较早内容可翻页查看。共
{{ messageTotal }} 条。
</p>
<div class="messages">
<el-empty
v-if="!messages.length && !messageLoading"
description="此会话尚无消息"
/>
<article v-for="m in messages" :key="m.id" :class="m.role">
<div class="message-meta">
<strong>{{
m.role === "user"
? selected?.displayName
: active.characterName
}}</strong
><time>{{ time(m.createdAt) }}</time
><el-tag
v-if="m.status !== 'complete'"
size="small"
type="info"
>{{ states[m.status] ?? m.status }}</el-tag
><el-tag v-if="m.pinned" size="small">已固定</el-tag>
</div>
<DigitalMessageText
class="history-message-body"
:text="m.content"
:role="m.role"
:incomplete="
['generating', 'stopped', 'failed'].includes(m.status)
"
/>
</article>
</div>
<el-pagination
v-model:current-page="messagePage"
:page-size="30"
:total="messageTotal"
layout="total, prev, pager, next"
@current-change="loadMessages" /></template
><el-empty v-else description="选择左侧会话查看聊天内容" />
</section>
</div>
</el-dialog>
</div>
</template>
<style scoped>
.heading,
.filters,
.message-pane header {
display: flex;
gap: 12px;
align-items: center;
justify-content: space-between;
margin-bottom: 18px;
}
h2 {
margin: 0 0 8px;
font-size: 24px;
}
.secondary,
.heading p {
margin: 6px 0;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.filters .el-input {
max-width: 420px;
}
.filters .el-select {
width: 160px;
}
.filters {
justify-content: flex-start;
}
.el-pagination {
justify-content: flex-end;
margin-top: 16px;
}
.history-layout {
display: grid;
grid-template-columns: 280px minmax(0, 1fr);
gap: 20px;
height: 72vh;
}
.conversation-list,
.message-pane {
min-height: 0;
overflow: auto;
}
.conversation-list {
padding-right: 12px;
border-right: 1px solid var(--el-border-color-light);
}
.conversation {
display: flex;
flex-direction: column;
gap: 6px;
width: 100%;
padding: 14px 10px;
color: var(--el-text-color-primary);
text-align: left;
cursor: pointer;
background: transparent;
border: 0;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.conversation.active {
color: var(--el-color-primary);
background: var(--el-color-primary-light-9);
}
.conversation small {
font-size: 11px;
color: var(--el-text-color-secondary);
}
.message-pane {
display: flex;
flex-direction: column;
}
.message-pane header {
margin-bottom: 8px;
}
.messages {
flex: 1;
min-height: 0;
padding: 8px;
overflow: auto;
}
.messages article {
margin-bottom: 18px;
}
.message-meta {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
font-size: 12px;
}
.message-meta time {
color: var(--el-text-color-secondary);
}
.messages article .history-message-body {
padding: 12px 14px;
margin: 6px 0;
overflow-wrap: anywhere;
white-space: pre-wrap;
background: var(--el-fill-color-light);
border-radius: 6px;
}
.messages article.user .history-message-body {
background: var(--el-color-primary-light-9);
}
.conversation:focus-visible {
outline: 2px solid var(--el-color-primary);
outline-offset: -2px;
}
@media (width<=760px) {
.heading,
.filters {
flex-direction: column;
align-items: stretch;
}
.filters .el-input,
.filters .el-select {
width: 100%;
max-width: none;
}
.history-layout {
grid-template-rows: 180px minmax(0, 1fr);
grid-template-columns: 1fr;
}
.conversation-list {
padding-right: 0;
border-right: 0;
border-bottom: 1px solid var(--el-border-color-light);
}
}
</style>
+3 -2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
/** 星港管理端登录,凭据由用户输入,不内置默认账号密码。 */
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
@@ -37,8 +38,8 @@ dataThemeChange(overallStyle.value);
const { title } = useNav();
const ruleForm = reactive({
username: "admin",
password: "Admin@123456"
username: "",
password: ""
});
function getErrorMessage(error: unknown, fallback: string) {
+107
View File
@@ -0,0 +1,107 @@
/** 对白、叙述、旧消息与累计流式文本的格式回归,不依赖浏览器或真实模型。 */
import test from "node:test";
import assert from "node:assert/strict";
import { parseDigitalMessage as parse } from "../src/utils/digital-message-format.ts";
test("标准消息按剧情顺序拆分叙述、对白与心理,隐藏星号并保留引号", () => {
assert.deepEqual(parse("*她合上书。*\n\n“你来了。”\n\n*她终于放松下来。*"), [
{ kind: "narration", text: "她合上书。" },
{ kind: "dialogue", text: "“你来了。”" },
{ kind: "narration", text: "她终于放松下来。" }
]);
});
test("旧消息的成对括号与括号外对白兼容,内层括号不会提前关闭叙述", () => {
assert.deepEqual(
parse(
"(她抱起书(封面有些旧),笑了笑)你来了。\n(她心里有些高兴)坐吧。"
),
[
{ kind: "narration", text: "她抱起书(封面有些旧),笑了笑" },
{ kind: "dialogue", text: "你来了。" },
{ kind: "narration", text: "她心里有些高兴" },
{ kind: "dialogue", text: "坐吧。" }
]
);
});
test("旧开场白的无标记叙述与引号对白分别展示,英文撇号不作为对白", () => {
assert.deepEqual(
parse('She picked up her book.\n"You’re early. Don\'t wait outside."'),
[
{ kind: "narration", text: "She picked up her book." },
{ kind: "dialogue", text: '"You’re early. Don\'t wait outside."' }
]
);
for (const [open, close] of [
["“", "”"],
["「", "」"],
["『", "』"],
["«", "»"],
[""", """]
]) {
assert.deepEqual(parse(`${open}你好${close}`), [
{ kind: "dialogue", text: `${open}你好${close}` }
]);
}
});
test("纯文本、普通备注、乘法与不完整的历史标记保留原文", () => {
for (const text of [
"普通文本",
"说明(选填)",
"3 * 4 = 12",
"file*name.txt",
"*未闭合",
"(未闭合"
]) {
assert.deepEqual(parse(text), [{ kind: "plain", text }]);
}
assert.deepEqual(parse(" \n\r\n"), []);
assert.deepEqual(parse("第一段\r\n\r\n第二段"), [
{ kind: "plain", text: "第一段" },
{ kind: "plain", text: "第二段" }
]);
});
test("显式叙述里的引号保持为故事文本,不再二次推断", () => {
assert.deepEqual(parse("*她想到“明天”这个词,轻轻笑了。*"), [
{ kind: "narration", text: "她想到“明天”这个词,轻轻笑了。" }
]);
assert.deepEqual(parse("**“你好。”**"), [
{ kind: "dialogue", text: "“你好。”" }
]);
assert.deepEqual(parse("\\*字面星号\\*"), [
{ kind: "plain", text: "*字面星号*" }
]);
});
test("累计流式输入的每个字符前缀都隐藏未闭合星号,完成态排版相同", () => {
const source = "*她推开门。*\n\n“你来了。”\n\n*她松了口气。*";
for (let end = 1; end <= source.length; end++) {
const blocks = parse(source.slice(0, end), true);
assert.equal(
blocks.some(block => block.text.includes("*")),
false,
`前缀 ${end}`
);
}
assert.deepEqual(parse(source, true), parse(source));
assert.deepEqual(parse("*她推开门", true), [
{ kind: "narration", text: "她推开门" }
]);
assert.deepEqual(parse("(她推开门", true), [
{ kind: "narration", text: "她推开门" }
]);
assert.deepEqual(parse("“你来了", true), [
{ kind: "dialogue", text: "“你来了" }
]);
assert.deepEqual(parse("**Hello", true), [
{ kind: "dialogue", text: "Hello" }
]);
});
test("HTML 与脚本内容只作为文本保留,格式解析不会生成任何标签", () => {
const text = "<script>globalThis.injected = true</script>";
assert.deepEqual(parse(text), [{ kind: "plain", text }]);
});