Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c1d49adb62 | |||
| 9a8a3e7795 | |||
| 2c7265efc4 | |||
| 64b32c2da6 | |||
| b7f7e4f121 | |||
| 4cb5110845 | |||
| 90db243a68 | |||
| 062a3b3cb6 | |||
| 4d43a9386a |
@@ -35,5 +35,8 @@ TEST_ACCEPTANCE_POLICY_VERSION=structural-v1
|
||||
VERSION_HISTORY_GITEA_BASE_URL=
|
||||
VERSION_HISTORY_REPO=Weknora/knowledge-governance
|
||||
VERSION_HISTORY_ALLOWED_ORIGINS=
|
||||
# 页面上的「查看提交 / 查看 tag」链接用哪个 origin —— 抓取可以走内网,但链接必须能被
|
||||
# **点它的人**打开(否则点开是空白)。留空 = 与上面的抓取地址相同。
|
||||
VERSION_HISTORY_LINK_ORIGIN=https://gitea.zheromiku.top
|
||||
VERSION_HISTORY_HTTP_TIMEOUT=15s
|
||||
VERSION_HISTORY_MAX_PAGES=200
|
||||
|
||||
@@ -43,3 +43,5 @@ backups/
|
||||
.ci-remote-tags
|
||||
.ci-commits-count
|
||||
.ci-preview-url
|
||||
# 上一版构建的静态资源(部署脚本落盘、只读挂载的运行时目录,不进 git)
|
||||
deploy/legacy-assets/
|
||||
|
||||
@@ -9,6 +9,24 @@
|
||||
- 新增迁移 `000046_version_history`(提交记录 + 同步状态):`commit_sha` 是唯一身份,**版本号不是唯一键** —— 两个提交算出同一个开发号时各占一行,用 SHA 区分。
|
||||
- 「当前运行」只认运行产物注入的**完整 SHA 精确匹配**:匹配到就标该条;开发构建显式标注"开发构建";拿不到标识就显示"当前运行版本未知",**不拿最新 main 或最新 tag 顶替**;CI 成功不等于已部署。
|
||||
|
||||
### Changed
|
||||
|
||||
- 「系统设置 → 数据源配置」**收敛成两个入口**:**dws 导入**(按当前钉钉账号列出可访问的知识库与钉盘空间)与 **PP 导入**。AList(已由钉盘文件替代)、静态登记的钉钉知识库、本地手工导入与 PP legacy 都**不再出现在这一页**;已接入的这类来源用**归档**下架(`POST /api/v1/source-connections/{id}/archive`,管理员、幂等,带写意图头与幂等键):从列表、来源与目录、计划刷新与手动扫描里消失,**目录快照、发布记录与审计数据一行不删**。恢复用 `…/restore`(保持停用、不自动带回调度),或让 dws 重新登记同一来源 —— 钉钉空间登记是确定性 ID + `ON CONFLICT`,**原地复活同一行、不产生重复**。卡片上新增「去掉来源」按钮(管理员,带确认弹窗)。
|
||||
- 迁移 `000047_source_connection_archive`:新增 `archived_at` / `archived_by` 与只覆盖未归档行的部分索引;列表、目录、计划刷新、手动扫描四类查询一律排除归档行(漏一条就等于入口没去掉)。
|
||||
|
||||
- 「系统设置 → 数据源配置」默认只列 PP 资料与「可加入的来源」:AList 来源(已由钉盘文件替代)与静态登记的钉钉知识库来源(改为按当前钉钉账号发现)**不再默认列出**,收进「显示 AList/钉钉知识库来源(N)」折叠开关 —— **来源一个都没删**,展开后照旧可改刷新周期与启停,「来源与目录」里的内容不变。手动导入来源(本地手工验收)不在这次范围内,照旧显示。
|
||||
|
||||
### Fixed
|
||||
|
||||
- **登记钉钉知识库失败(HTTP 409 `space_registration_conflict`)的真实原因与修复**:`source_connections.name` 有唯一约束,而早期路径登记的钉钉来源(`base_url` 为空、id 与 dws 现在推导的确定性 id 不同)被**归档后仍占着名字槽位** ⇒ 重新登记时 INSERT 撞唯一约束;处理器又把**所有**存储层错误都翻译成同一个 409,真实原因被吞掉(线上只能看到一个无细节的错误码)。现在:① 同名来源**已归档**时,把它改名腾位(`…(已下架 · <短ID>)`,归档行不显示、数据与审计一行不动);② 同名来源**仍在使用**时返回 `space_name_conflict` + 可行动提示(先「去掉来源」);③ 同一登记键指向别的空间且该行仍在用时返回 `space_identity_conflict`(已归档的行则允许就地改写 —— 这就是"去掉后再用 dws 重新获取");④ 其余内部故障改回 **500** `space_registration_failed`,不再伪装成冲突;前端优先显示后端 `hint`,并为这两个新码补了中文说明。
|
||||
|
||||
- 前端入口与静态资源的缓存语义("新功能看起来没上线"与"页面偶尔裸奔/空白"的根因):
|
||||
- `index.html` 此前**没有缓存头**,CDN/浏览器按启发式缓存它 ⇒ 页面会一直停在旧构建上(实测被腾讯云 EdgeOne 卡住:源站已是新包,公网入口仍发旧包)。现在 `index.html` 每次回源校验(`no-cache, must-revalidate`);
|
||||
- 带内容哈希的 `/assets/` 长缓存(`immutable`),但**未命中时先回退到"上一版构建的资源"目录、再 404**(`deploy/legacy-assets` 由部署脚本在每次重建前落盘并只读挂载):CDN/浏览器仍持有旧 `index.html` 时,它引用的旧 JS/CSS 依旧能取到 ⇒ 不会出现"JS 404 白屏"或"CSS 404 只有文字没样式";
|
||||
- 明确 404 时不再回退成 `index.html`(否则浏览器把 HTML 当 JS 执行,报一堆语法错误)。
|
||||
- **上线前护栏 + 事故复盘**:`scripts/deploy-api-web.sh` 现在先校验 `.env` 的键值形状(值里再出现 `KEY=` 或键名不合法 ⇒ **拒绝上线**),配置校验失败时也会给出"两行粘成一行"的线索。事故:`.env` 最后一行没有结尾换行、又被追加新键 ⇒ 两行粘成一行 ⇒ `VERSION_HISTORY_GITEA_BASE_URL` 变成非法值 ⇒ api/worker 按设计拒绝启动、崩溃重启(平台整体不可用)。已修数据、加护栏、加回归用例。
|
||||
- 「版本记录」页的链接改为**抓取与链接分离**:抓取仍走配置的(内网)地址,页面上的「查看提交 / 查看 tag」用 `VERSION_HISTORY_LINK_ORIGIN`(公网 origin)拼 —— 原先两者共用内网地址,内网外的浏览器点开是空白;另外 tag 记录原先不带链接(空 `href` 点下去没反应),现在补上链接、没有链接就不渲染该按钮。
|
||||
|
||||
### Security
|
||||
|
||||
- 版本记录同步**匿名只读**远端仓库(**不使用任何凭据**),来源限配置里批准的 origin 与固定仓库:拒绝任意 URL、拒绝跨主机重定向,单个响应设大小上限与超时、5xx/429 才有退避重试。
|
||||
|
||||
@@ -944,6 +944,108 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/source-connections/{id}/archive": {
|
||||
"parameters": [
|
||||
{
|
||||
"$ref": "#/components/parameters/ID"
|
||||
}
|
||||
],
|
||||
"post": {
|
||||
"operationId": "archiveSourceConnection",
|
||||
"summary": "归档下架来源(去掉入口;不物理删除)",
|
||||
"description": "把来源从数据源配置、来源与目录、计划刷新与手动扫描里摘掉:目录快照、发布记录与审计数据原样保留;恢复只需再次登记同一来源(钉钉空间登记是确定性 ID,原地复活同一行)。幂等:重复归档不改归档时间与归档人。仅管理员可写。",
|
||||
"tags": [
|
||||
"governance"
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"$ref": "#/components/parameters/IdempotencyKey"
|
||||
},
|
||||
{
|
||||
"in": "header",
|
||||
"name": "X-Governance-Action",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"source-archive"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"403": {
|
||||
"$ref": "#/components/responses/Forbidden"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/NotFound"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"503": {
|
||||
"$ref": "#/components/responses/ServiceUnavailable"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/source-connections/{id}/restore": {
|
||||
"parameters": [
|
||||
{
|
||||
"$ref": "#/components/parameters/ID"
|
||||
}
|
||||
],
|
||||
"post": {
|
||||
"operationId": "restoreSourceConnection",
|
||||
"summary": "撤销来源归档(保持停用,调度不自动恢复)",
|
||||
"description": "归档的反向操作:来源重新出现在列表里,但保持停用且不带调度,需要管理员再显式启用。幂等:未归档时视为成功;连接不存在返回 404。仅管理员可写。",
|
||||
"tags": [
|
||||
"governance"
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"$ref": "#/components/parameters/IdempotencyKey"
|
||||
},
|
||||
{
|
||||
"in": "header",
|
||||
"name": "X-Governance-Action",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"source-restore"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"403": {
|
||||
"$ref": "#/components/responses/Forbidden"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/NotFound"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"503": {
|
||||
"$ref": "#/components/responses/ServiceUnavailable"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/source-connections/{id}/scan": {
|
||||
"parameters": [
|
||||
{
|
||||
|
||||
@@ -118,6 +118,7 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
client, err := versionhistory.NewGiteaClient(versionhistory.GiteaConfig{
|
||||
BaseURL: config.VersionHistoryGiteaBaseURL,
|
||||
AllowedBaseURLs: config.VersionHistoryAllowedOrigins,
|
||||
LinkOrigin: config.VersionHistoryLinkOrigin,
|
||||
Repo: config.VersionHistoryRepo,
|
||||
Timeout: config.VersionHistoryHTTPTimeout,
|
||||
})
|
||||
|
||||
@@ -40,6 +40,15 @@ services:
|
||||
MINERU_BASE_URL: "${MINERU_BASE_URL:-}"
|
||||
TEST_INTERNAL_WEKNORA_KB_ID: "${TEST_INTERNAL_WEKNORA_KB_ID:-1b52c140-2e18-4676-afc5-4c7d8d190a8c}"
|
||||
TEST_EXTERNAL_WEKNORA_KB_ID: "${TEST_EXTERNAL_WEKNORA_KB_ID:-fd7db6aa-763a-46f1-84d2-ecc7c952a5ea}"
|
||||
# 「版本记录」页:**匿名只读**远端仓库的提交与 tag(不使用任何凭据)。
|
||||
# 留空 = 未接线(页面降级、同步入口不可用);来源只允许下面批准的 origin 与固定仓库。
|
||||
VERSION_HISTORY_GITEA_BASE_URL: "${VERSION_HISTORY_GITEA_BASE_URL:-}"
|
||||
VERSION_HISTORY_REPO: "${VERSION_HISTORY_REPO:-Weknora/knowledge-governance}"
|
||||
VERSION_HISTORY_ALLOWED_ORIGINS: "${VERSION_HISTORY_ALLOWED_ORIGINS:-}"
|
||||
# 页面链接用的 origin(给内网外的浏览器点开);留空 = 与抓取 origin 相同。
|
||||
VERSION_HISTORY_LINK_ORIGIN: "${VERSION_HISTORY_LINK_ORIGIN:-}"
|
||||
VERSION_HISTORY_HTTP_TIMEOUT: "${VERSION_HISTORY_HTTP_TIMEOUT:-15s}"
|
||||
VERSION_HISTORY_MAX_PAGES: "${VERSION_HISTORY_MAX_PAGES:-200}"
|
||||
# P10 readiness probe reads the routing KB with the same scoped key.
|
||||
TEST_WEKNORA_API_KEY_FILE: /run/secrets/test_weknora_api_key
|
||||
TEST_WEKNORA_ALLOW_DOCKER_HTTP: "${TEST_WEKNORA_ALLOW_DOCKER_HTTP:-false}"
|
||||
@@ -204,6 +213,10 @@ services:
|
||||
api:
|
||||
condition: service_healthy
|
||||
read_only: true
|
||||
volumes:
|
||||
# 上一版构建的静态资源(只读,由部署脚本落盘):CDN/浏览器可能还持有旧 index.html,
|
||||
# 让它的旧哈希引用不至于 404 —— 否则页面会空白或"只有文字没样式"。
|
||||
- ./deploy/legacy-assets:/usr/share/nginx/legacy:ro
|
||||
tmpfs:
|
||||
- /tmp
|
||||
- /var/cache/nginx
|
||||
|
||||
@@ -25,7 +25,32 @@ server {
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
# 带内容哈希的构建产物:可以长期缓存(换版本必然换文件名);旧哈希文件已被新构建替换
|
||||
# ⇒ 明确 404,不要回退成 index.html(否则浏览器把 HTML 当 JS 执行,报一堆语法错误)。
|
||||
location /assets/ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
# 当前构建里没有再找**上一版构建**的资源:CDN/浏览器可能还持有旧 index.html,
|
||||
# 它引用的旧哈希文件若直接 404,页面就会空白或"裸奔"(只有文字没样式)。
|
||||
# 旧目录由部署脚本在每次重建前落盘(deploy/legacy-assets,只读挂载)。
|
||||
try_files $uri @legacy;
|
||||
}
|
||||
|
||||
location @legacy {
|
||||
root /usr/share/nginx/legacy;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# ⚠️ index.html(含 SPA 深链回退)**必须每次回源校验**:它引用的是带哈希的 JS 文件名,
|
||||
# 一旦被 CDN/浏览器缓存住,页面就一直停在旧构建上(看着像"新功能没上线")。
|
||||
# 2026-10-14 实测被腾讯云 EdgeOne 缓存卡住过一次:源站已是新包,公网入口仍发旧包。
|
||||
location = /index.html {
|
||||
# 只发一条 Cache-Control(`expires -1` 会再发一条,CDN 读到哪条说不准)。
|
||||
add_header Cache-Control "no-cache, must-revalidate" always;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
add_header Cache-Control "no-cache, must-revalidate" always;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
# DobotAI 2.0 知识运营报表数据链路分析
|
||||
|
||||
> 调查日期:2026-10-14(Asia/Shanghai)
|
||||
> 阶段:只读现状调查与架构建议,未实施开发。
|
||||
> 结论等级:**线上已核实**=本轮 DWS 真实响应;**源码已核实**=本地实现/迁移证据;**待确认**=生产部署或数据不可访问,不能用源码代替线上事实。
|
||||
> 本文不含员工原始记录、问答原文、密码或 Token。
|
||||
|
||||
## 0. 摘要与调查边界
|
||||
|
||||
### 0.1 核心结论
|
||||
|
||||
1. **现有数据不是一条统一链路。** 至少有 DobotAI Go 后端问答/规则覆盖判定、钉钉 AI 表格标签、Python 离线统计三套实现;目前不能把它们的“覆盖/正确”视为同一指标。
|
||||
2. DWS 核实 `w0nYx0a` 为 **问题流水表 (2.0)**,`jQ6oevs` 为 **问题流水表**。截至本轮聚合,分别为 **2,121 / 13,275 条**;两表日期重叠,不能简单拼接后当作去重后的总使用量。
|
||||
3. **2.0 表覆盖、正确性、产品、部门、区域填值数均为 0。** 因而仅依赖这张表,当前不能生成可信的质量与维度周报。后端源码另有 `coverage_decisions`,但生产数据完整率尚未核实。
|
||||
4. 后端覆盖器是**确定性规则**,不是 LLM 正确性评测;引用存在不等于回答正确。源码未发现对应的 AI 正确性评估存储/服务。
|
||||
5. 现有流水统计脚本正确率为“正确=是 /(正确=是+否)”,**不要求该行已覆盖**;与用户本轮期望口径不同。
|
||||
6. 推荐先确认生产源、评估来源与分母,再新增一个轻量统计模块;报表 API 和邮件均复用它。**不重建问答日志,不把监控任务成功率当作回答正确率。**
|
||||
|
||||
### 0.2 已检查范围与限制
|
||||
|
||||
| 范围 | 检查方式 | 证据级别 / 限制 |
|
||||
|---|---|---|
|
||||
| 两张指定 AI 表格 | DWS `table get`、`field get`、`record stats`、`record group-stats` | 线上已核实;不全量读取问答,不导出员工记录 |
|
||||
| `/home/zheromiku/dobotai-platform` | Go 源码、数据库迁移、HTTP 路由、导出流程 | 源码已核实;HEAD `0fc73c415245073a7a94aa9afb1fe35ca9c1fb3e`,工作区有已有未提交改动,HEAD 不代表线上版本 |
|
||||
| `/home/zheromiku/knowledge-governance` | API、监控、工作流及目录结构 | 源码已核实;HEAD `b7f7e4f12101569db5bb76af9d836043eefc342b`,工作区有已有未提交改动 |
|
||||
| `/home/zheromiku/knowledge-adapter-service` | 检索模型、API、日志实现 | 源码已核实;未检查 live 检索/问答系统 |
|
||||
| `/home/zheromiku/DOBOTAI/{weekly_report,kb_ops,knowledge_ai_report}` | 现有 Python 统计、清洗和映射代码 | 源码已核实;没有运行会写 Excel/日志的流水线 |
|
||||
| 后端 live PostgreSQL | 尝试使用本地既有连接配置,只读连接 | **连接失败,未能执行任何查询**;不能确认 live 表、迁移、行数及版本 |
|
||||
| 运行服务版本 | 本地候选服务 `/version` 只读探测 | 未成功取得 DobotAI 版本响应;生产地址、部署 SHA 待确认 |
|
||||
| 表格重复事件 | DWS PostgreSQL 聚合探测 | 返回 `Invalid PostgreSQL query`;**未得到重复率,不能宣称已完成去重核验** |
|
||||
|
||||
DWS 大请求曾出现下游 `code: 800`,拆成单字段聚合后成功。覆盖分组响应没有提供可解释的选项值,改按 `field get` 取得的稳定 option ID 分别计数,避免猜测分组对应关系。所有下述主要计数的响应数据版本均为 **23215**;这是表格数据版本,**不是评估器版本**。
|
||||
|
||||
## 1. 当前系统架构与数据流
|
||||
|
||||
### 1.1 问答后端:源码链路
|
||||
|
||||
```text
|
||||
钉钉消息(群聊须 @) / POST /v1/qa
|
||||
→ 身份与会话解析、Agent 绑定
|
||||
→ BeginTurn:channel_actors / channel_conversations / messages / turns
|
||||
→ WeKnora Agent Chat:生成答案与引用
|
||||
→ FinishTurn:更新 turns,保存出站 messages
|
||||
├→ 成功轮次 observer:coverage.Service
|
||||
│ → coverage_decisions
|
||||
│ → 若未覆盖,同时创建 support_cases
|
||||
├→ 钉钉实际送达:单独记录 messages 送达状态
|
||||
└→ 可选 question_table_exports outbox
|
||||
→ 异步写入 AI 表格基础问答和人员快照
|
||||
→ 本地记录 external_record_id
|
||||
```
|
||||
|
||||
证据:`DP/internal/store/postgres/store.go:50–129,196–283`;`DP/internal/qa/service.go:166–177,285–298`;`DP/cmd/dobotai/main.go:84–95,188–203`。
|
||||
|
||||
**边界:**`turns.status=succeeded` 表示答案生成成功,不等同于用户成功收到答案。覆盖评估保存失败不会把成功问答改为失败,故成功轮次可能没有覆盖记录;成功请求重放提前返回,不自动补评估。
|
||||
|
||||
### 1.2 表格和离线报表:已核实链路与断点
|
||||
|
||||
```text
|
||||
AI 表格:问题、答案、人员、时间 + 覆盖/正确/产品等标签
|
||||
→ 本地 Excel / 离线流水与问题主表
|
||||
→ 人员部门映射(08) → 部门区域映射(09)
|
||||
→ 月区域使用统计(10) / 知识指标统计(12)
|
||||
→ Excel 汇总
|
||||
```
|
||||
|
||||
- 后端 `internal/questiontable/row.go:40–41` 明确**省略** `是否覆盖/是否正确/产品分类/问题类型/根因分析` 五个 select 字段;导出 SQL 也未读取 `coverage_decisions`。
|
||||
- 两张表有评估字段,不代表已查明谁填写、何时填写、是否由 AI 自动评估;完整字段读取未返回 AI 配置证据。
|
||||
- Base 工作流列表返回 3 个工作流、`runningCount=0`。这只说明本次列表中没有运行中的 Base 工作流,**不能排除外部自动化、定时脚本或人工评估**。
|
||||
- 本轮未核实“线上 AI 表格 → 本地 Excel”的自动同步和执行调度,也未核实当前正式周报调用哪份脚本。
|
||||
|
||||
### 1.3 知识治理和检索适配的边界
|
||||
|
||||
知识治理当前负责知识源、解析、发布及监控;Adapter 提供检索,不生成最终答案。现有监控 API 的 `success_rate` 来源是 `jobs` 的 completed/failed,**不是回答正确率**。
|
||||
|
||||
证据:`KG/internal/monitoring/metrics.go:25–44,73–86`;`KG/internal/monitoring/real.go:109–181`;`KA/src/knowledge_adapter/app.py:131–160`、`models.py:27–33`。
|
||||
|
||||
## 2. 实际数据表、字段及关联关系
|
||||
|
||||
### 2.1 线上 AI 表格
|
||||
|
||||
共同 Base:`KGZLxjv9VG37o9N6IYvYGBl9V6EDybno`。
|
||||
|
||||
| 表 | tableId | viewId | 本轮记录数 | 提问时间最小值 — 最大值 |
|
||||
|---|---|---|---:|---|
|
||||
| 问题流水表 (2.0) | `w0nYx0a` | `Qr19nXJ` | 2,121 | 2026-09-12 19:43:30 — 2026-10-14 11:45:30 +08:00 |
|
||||
| 问题流水表(旧表) | `jQ6oevs` | `TE2xi1m` | 13,275 | 2026-04-01 03:02:00 — 2026-10-14 11:44:23 +08:00 |
|
||||
|
||||
以上是 `COUNT` 聚合的记录数,**不是有效提问数或去重问题数**。两个 URL 的版本归属以真实表名为证据,不根据链接排列顺序推断。
|
||||
|
||||
| 字段名 | fieldId | 类型 | 用途 / 关联 |
|
||||
|---|---|---|---|
|
||||
| 中文问题 | `ZaMZF6j` | text | 中文文本,不能拿其非空作为所有语言的有效问题条件 |
|
||||
| 原始问题 | `bETcL3r` | text | 原始提问 |
|
||||
| AI答案 | `Y4cpmxU` | text | 答案正文 |
|
||||
| 提问时间 | `SCug9My` | date | 时间筛选;字段 formatter 为 `YYYY-MM-DD HH:mm:ss` |
|
||||
| 提问人 | `S2XA1uZ` | user | 人员实体;跨系统 ID 关系待确认 |
|
||||
| 流程触发人员信息 | `JgY2f1z` | text | 触发身份,文本格式不可假定始终为结构化 JSON |
|
||||
| 语言 | `DNIV3mQ` | text | 后端导出以 Han/Latin 字符启发式判断,不是语言模型识别 |
|
||||
| 部门 | `eBc6a6b` | text | 部门名称,不是部门外键 |
|
||||
| 区域 | `fPNLeVW` | text | 区域名称 |
|
||||
| 是否覆盖 | `QMn9UoU` | singleSelect | `是 / 否 / 否但不计入` |
|
||||
| 是否正确 | `H3gtTuv` | singleSelect | `是 / 否 / 待确认` |
|
||||
| 产品分类 | `nFvv8OR` | singleSelect | 产品标签;其中 DobotStudio Pro 是产品选项,不是渠道证据 |
|
||||
| 问题类型 | `UMqUPAG` | singleSelect | 问题业务分类 |
|
||||
| 根因分析 | `lnF7gF9` | singleSelect | 知识缺失/过期/检索不到等标签 |
|
||||
| 父记录 | 2.0:`C7kZIHz`;旧表:`qgyb5Df` | unidirectionalLink | 两字段 config 都指向 `w0nYx0a`,且允许 multiple;不能当作已建立的 1.0→2.0 迁移去重关系 |
|
||||
|
||||
**同一行存问答和评估标签**,没有本轮可见的独立评估表外键,也没有 `turn_id`、渠道、评估状态、评估时间、评估器版本业务列。DWS 有记录历史读取能力,但“单元格变更历史”不能直接等价于有状态、有版本的评估执行流水。
|
||||
|
||||
#### 线上标签和维度填值情况
|
||||
|
||||
| 计数项 | 2.0 | 旧表 | 解释 |
|
||||
|---|---:|---:|---|
|
||||
| 记录数 | 2,121 | 13,275 | 原始行数 |
|
||||
| 提问时间有值 | 2,121 | 13,275 | 已可做日期筛选 |
|
||||
| AI答案有值 | 2,121 | 13,256 | 有值不等于正确或成功送达 |
|
||||
| 覆盖标签有值 | 0 | 13,205 | 有值不等于评估完成 |
|
||||
| 覆盖=是 | 0 | 8,627 | 按 option ID 筛选 |
|
||||
| 覆盖=否 | 0 | 4,481 | 按 option ID 筛选 |
|
||||
| 覆盖=否但不计入 | 0 | 97 | 不计入的实际原因/标准待确认 |
|
||||
| 覆盖为空 | 2,121 | 70 | 用记录数减已知三个选项数量计算 |
|
||||
| 正确性有值 | 0 | 13,035 | 包括“待确认” |
|
||||
| 正确性=待确认 | 0 | 4,791 | 不能当作正确性评估已完成 |
|
||||
| 覆盖与正确性同时有值 | 0 | 12,965 | 仅为标签填值交集,不是正式完成量 |
|
||||
| 覆盖=是且正确=是 | 0 | 7,887 | 未排除测试人员、去重或筛有效问题 |
|
||||
| 部门有值 | 0 | 10,814 | 缺失会影响部门分析 |
|
||||
| 区域有值 | 0 | 8,556 | 缺失会影响区域分析 |
|
||||
| 产品分类有值 | 0 | 12,969 | 缺失或“未知”仍需区分 |
|
||||
|
||||
DWS 对提问人字段的 `DISTINCT` 返回 2.0 为 153、旧表为 418;这是**该人员字段的不同值计数**,尚未确认一行单人约束、ID 域及跨渠道合并,不发布为正式活跃人数。
|
||||
|
||||
日期过滤实测:`2026-10-05 ≤ 提问时间 < 2026-10-12`,2.0 为 **465 行**,旧表为 **80 行**。这证明已有时间范围查询能力,但不是“每周有效提问量”。
|
||||
|
||||
### 2.2 后端关系模型:迁移与写入代码证据,live 待确认
|
||||
|
||||
以下是真实源码中的表/列,不是猜测表名;但本轮 live DB 未连通,**不能宣称已核实生产表结构**。
|
||||
|
||||
| 实际表名 | 关键字段 | 用途 / 关联 | 证据 |
|
||||
|---|---|---|---|
|
||||
| `turns` | `id, tenant_key, channel, external_message_id, session_key, weknora_session_id, weknora_request_id, question, answer, references_json, status, created_at, updated_at, request_message_id, answer_message_id, agent_id, media_json` | 一个问答轮次;唯一 `(tenant_key,channel,external_message_id)` | DP 迁移 000001:16–35;000002;000003:77–84 |
|
||||
| `messages` | `id, tenant_key, channel, conversation_id, actor_id, correlation_id, direction, role, message_type, text_content, status, provider_created_at, created_at` | 入站/出站/内部消息;不要混合计为问题 | DP 迁移 000003:39–64 |
|
||||
| `messages` 人员/送达扩展 | `actor_name_snapshot, department_snapshot, region_snapshot, trigger_person_snapshot, actor_union_id_snapshot, delivered_at, delivery_method, provider_message_id, failure_code` | 提问时人员维度与独立送达状态 | DP 迁移 000003/000004/000009/000010 |
|
||||
| `coverage_decisions` | `id,tenant_key,channel,turn_id,evaluator_version,verdict,reason_code,reference_count,top_score,created_at,updated_at` | 覆盖决策;`turn_id → turns.id`,唯一 `(tenant_key,channel,turn_id)` | DP 迁移 000007:4–27 |
|
||||
| `support_cases` | `id,tenant_key,channel,turn_id,coverage_decision_id,status`;通知及 FAQ 导出字段 | 未覆盖支持单;不是正确性评估结果 | DP 迁移 000007:29–49;000011 |
|
||||
| `channel_actors` | `id,tenant_key,channel,external_actor_id,actor_type,display_name` | 渠道内人员;唯一 `(tenant_key,channel,external_actor_id)` | DP 迁移 000003:8–18 |
|
||||
| `channel_conversations` | `id,tenant_key,channel,external_conversation_id,conversation_type` | 对话;群聊对话不等于个人 | DP 迁移 000003:23–34 |
|
||||
| `session_mappings` | `session_key,tenant_key,channel,agent_id,conversation_type,external_subject_id,weknora_session_id` | 外部会话与 WeKnora 会话映射 | DP 迁移 000001:1–14;000008 |
|
||||
| `directory_profiles` | `tenant_key,staff_id,union_id,name,nickname,job_title,department_ids,department_name,main_department_name,region,employment_status,source,synced_at,updated_at` | 当前通讯录,主键 `(tenant_key,staff_id)` | DP 迁移 000009:1–20 |
|
||||
| `question_table_exports` | `id,tenant_key,channel,turn_id,status,attempts,last_attempt_at,next_attempt_at,exported_at,failure_code,external_record_id` | 表格同步 outbox;远端记录 ID 可用于对照,但当前表没有可见反向 turn ID | DP 迁移 000010:11–40 |
|
||||
| `answer_feedback` | `answer_message_id,turn_id,actor_id,value,reason_code,source,created_at,updated_at` | 用户点赞/点踩当前状态,不能等价为 AI 正确性评估 | DP 迁移 000005:6–19 |
|
||||
|
||||
建议调查/聚合连接顺序:`turns → request_message_id → messages → actor_id → channel_actors`;覆盖决策按 `turn_id` 加租户/渠道校验关联,避免跨租户。目录按渠道身份与 `staff_id/union_id` 解析,**不能统一按姓名 JOIN**。来自回调的 `external_actor_id` 可能有回退 ID,不应假定总是 staff ID。
|
||||
|
||||
### 2.3 评估状态、时间、版本与重新评估
|
||||
|
||||
| 问题 | 已有实现 | 边界 |
|
||||
|---|---|---|
|
||||
| 是否有评估状态 | `turns.status` 是问答状态;`coverage_decisions` 有最终 verdict,但没有独立 pending/running/failed 评估状态列 | 无决策只能视为缺评估,无法区分等待/失败/未接入 |
|
||||
| 是否有评估时间 | 覆盖决策 `created_at/updated_at` 为 DB 写入时间 | 不是独立的 AI 评估任务开始/完成时间;表格没有对应业务列 |
|
||||
| 是否有评估器版本 | 源码 `EvaluatorVersion="v3"`,写入 `evaluator_version` | 迁移默认 `v1`;线上版本分布待确认;版本不是 LLM 型号 |
|
||||
| 是否保存多次评估 | 覆盖唯一键不含版本;冲突仅 `DO UPDATE SET id=coverage_decisions.id` | 保留原有决策,不取“最新一次”;没有多版本历史 |
|
||||
| AI 正确性版本/时间 | 表格只见标签;后端未找到该评估模型 | 实际 AI 批处理/人工标注系统待定位 |
|
||||
|
||||
证据:`DP/internal/coverage/types.go:33–50`;`DP/internal/store/postgres/coverage.go:33–55`。
|
||||
|
||||
### 2.4 已有 API 与服务
|
||||
|
||||
| 实际 API / 服务 | 当前用途 | 是否可直接提供目标周报 |
|
||||
|---|---|---|
|
||||
| `POST /v1/qa` | 发起问答,接收 channel 等基础参数;不接收部门/区域/union ID,也未调用目录补全 | 否,且本轮未调用该写接口 |
|
||||
| `GET /v1/admin/audit/turns`;`GET /v1/admin/audit/turns/{id}` | 可选管理审计;列表筛选只允许 limit/cursor/channel/status | 否,无日期区间聚合、coverage JOIN 或质量统计 |
|
||||
| `coverage.Service.EvaluateAndPersist` | 成功轮次覆盖评估和保存 | 可复用已有决策,不是统计服务 |
|
||||
| `questiontable.Dispatcher` | outbox 异步表格插入 | 是同步服务,不是评估和统计服务 |
|
||||
| DWS `record stats/group-stats` | 表格服务端计数、筛选、分组、去重聚合 | 可复用数据读取能力;仍需统一业务口径 |
|
||||
| `GET /api/v1/monitor/overview`;`GET /api/v1/monitor/metrics` | 知识治理资源/入库/任务监控 | 不可替代问答运营指标 |
|
||||
| `POST /retrieval` | Adapter 外部知识检索,返回片段/score/元数据 | 不保存此处所需最终答案正确性 |
|
||||
|
||||
证据:DP `internal/httpapi/server.go:86–92,130–165`;KG `internal/httpapi/server.go:322–342`;KA `src/knowledge_adapter/app.py:131–160`。
|
||||
|
||||
### 2.5 钉钉、Studio Pro、Wiki 入口如何区分
|
||||
|
||||
- 后端已有 `turns.channel`、`messages.channel`、`channel_actors.channel`,可作为现有入口维度基础。
|
||||
- 钉钉 handler 已实现;HTTP `/v1/qa` 允许调用方传 channel。**未查明线上 Studio Pro/Wiki 是否经过该接口、传入什么 channel,不能编造渠道枚举。**
|
||||
- 表格没有显式入口字段;旧/新表名表达版本,不表达全部业务入口。
|
||||
- “产品分类=DobotStudio Pro”描述问题涉及产品,不表示用户从 Studio Pro 发起。
|
||||
- 知识治理的 `internal/external` 是知识可见范围,文档中 PG/ES/OSS 是发布运输通道,不能替代问答业务入口。
|
||||
- Wiki 资料检索/页面访问与 Wiki 问答必须分开定义,不能把知识访问数直接加入提问量。
|
||||
|
||||
## 3. 现有覆盖率、正确率计算逻辑
|
||||
|
||||
### 3.1 后端单次覆盖判断:不是统计覆盖率
|
||||
|
||||
当前 `coverage.Evaluator` 只接受 `succeeded`:
|
||||
|
||||
1. 答案命中明确无答案措辞,或同时出现“检索缺口+联系人工”措辞 → `uncovered_explicit_no_answer`。
|
||||
2. 未命中上述规则,且引用数量为 0 → `uncovered_no_references`。
|
||||
3. 有引用 → `covered_has_references`。
|
||||
|
||||
记录最高引用 score,但**没有分数阈值**,也不核对答案事实是否正确。该规则无法等价于表格 AI 对知识覆盖与回答正确性的评估。
|
||||
|
||||
证据:`DP/internal/coverage/evaluator.go:12–38,62–119,131–138`。
|
||||
|
||||
### 3.2 离线脚本实际口径
|
||||
|
||||
| 代码入口 | 实际公式 / 样本 | 与本轮目标差异 |
|
||||
|---|---|---|
|
||||
| `WR/scripts/12_calc_kb_metrics.py:153–179`;KB 同名脚本 | 严格覆盖率=覆盖“是” /(覆盖“是”+“否”);另算含部分覆盖率 | 空值、待确认、不计入、非法标签不进分母;没有统一有效问题判定 |
|
||||
| 同上正确率 | 正确“是” /(正确“是”+“否”),独立统计正确列 | **没有先限定覆盖=是**;待确认不进分母 |
|
||||
| `KB/scripts/06_calc_metrics.py:139–159` | 主表覆盖=(是+部分覆盖)/全部输入行;正确率=是/(是+否) | 主表是归并问题,非事件频次;空值等仍进覆盖分母 |
|
||||
| `KR/backup/calculate_metrics.py:182–211` | 先筛 `is_real_question=True`,覆盖总和 / 非空 question 数 | 另一套“真实问题”口径;实际正式入口待确认 |
|
||||
|
||||
`12_calc_kb_metrics.py` 先排除代码内置的测试/指定人员名单,再算指标;人员列缺失则不排除。本文不公开名单。它没有时间过滤、事件去重、非空问题检查;分母为 0 时返回 `0.0`,容易把“没有评估样本”显示成“表现为零”。
|
||||
|
||||
证据:`WR/scripts/12_calc_kb_metrics.py:128–146,282–308`。
|
||||
|
||||
### 3.3 有效问题、未评估、多次评估与历史变化
|
||||
|
||||
| 调查点 | 真实现状 |
|
||||
|---|---|
|
||||
| 有效问题如何判定 | 没有一套所有入口共用定义;主表、流水脚本、旧清洗分别采用不同过滤。`KB/scripts/01_import_raw.py:82–110,180–193` 按说明类关键词过滤,规则可能误排业务问题;旧清洗还按答案排除词过滤 |
|
||||
| 未完成评估 | 流水指标脚本不把空值/待确认计入对应分母;正确性“待确认”不是完成。后端成功但无决策的轮次无专门评估状态 |
|
||||
| 多次评估取哪一次 | 后端保留首次成功持久化决策,不覆盖原判定;表格/Excel 统计读取当前单元格,不查询历史最新完成任务 |
|
||||
| 历史是否变化 | 离线重跑使用当前标签、映射和人员名单;修改标签/通讯录/区域规则或文件会改变过去统计。后端规则决策不会仅因升级版本自动改写,但后续补评估或统计过滤调整仍会影响历史结果 |
|
||||
| 时间范围 | AI 表格已实测可以;后端审计列表没有时间参数;12脚本本身没有时间过滤,10脚本支持自然月 |
|
||||
| 产品/部门/区域 | 字段基础存在;当前10脚本有区域月使用统计,未发现目标产品×部门×区域质量聚合服务。2.0 的这些字段实际为空 |
|
||||
|
||||
**流水线时间错位:**`WR/scripts/12_run_08_09_10_pipeline.py:154–180` 把 `--month` 传给区域统计,知识指标读取完整输入,故同次产物可能混合“某月使用”与“全量质量”。
|
||||
|
||||
### 3.4 月使用与技术人员至少5次
|
||||
|
||||
- 当前 `WR/scripts/10_calc_region_usage_metrics.py:286–342,418–448` 按指定自然月;未指定时取数据中最大可解析日期所在月。区域总次数是流水行数,使用人数是人员文本 `nunique()`,不是统一稳定 ID。
|
||||
- 通讯录人员分母按 ID/姓名回退去重,再按区域展开;并未严格筛选技术人员、纳入范围和在职状态。多区域可能重复计数,汇总与人员明细身份口径也不同。
|
||||
- 旧 `KR/backup/calculate_metrics.py:214–290` 有“真实问题+内部技术支持+纳入范围+在职+周期≥5”的实现;`KR/backup/usage/region_usage.py:135–195` 则按 user ID,但在职/有效问题筛选不同。
|
||||
- **可以复用旧算法思路,不能称为当前已上线的统一≥5次指标。** 技术人员范围、人员 ID 唯一性、计次单位与离职处理均待确认。
|
||||
|
||||
### 3.5 重复计数风险
|
||||
|
||||
| 风险来源 | 已有保护 | 仍存在的风险 |
|
||||
|---|---|---|
|
||||
| 回调重复 | 后端 external_message_id 复合唯一键;成功请求返回原结果 | 新 ID 重发同内容是不同事件,不应按相同文本盲目去重 |
|
||||
| 多轮对话 | 后端一个 turn 一个问答轮次 | 一个会话多个 turn;若把会话、message、turn混合汇总会重复;默认群聊共享会话不是一个用户 |
|
||||
| 覆盖重评 | 一个 turn 一份持久化覆盖决策 | 不是多版本评估历史;新的 uncovered 输入可能创建支持单,但指向原有 covered 决策,需单独处理重评一致性 |
|
||||
| 表格同步重试 | 本地 outbox 一个 turn 唯一 | 远端插入后本地 MarkExported 失败可重试插入,未证明远端 exactly-once |
|
||||
| 旧数据导入 | 01脚本 SHA1(对话人\|规范时间\|原始问题),保留首条/跳过历史 ID | 不是官方消息 ID;时间缺失或规范化冲突会错误合并;12统计入口自身不去重 |
|
||||
| 1.0 / 2.0 合并 | 有两张表和父记录字段 | 日期重叠但无可证实迁移键;本轮 SQL 重复探测失败,重复量待确认 |
|
||||
| 通讯录及区域映射 | 已有离线别名/区域规则 | 重名保留首条、多区域 explode、目录规则分叉,可能放大或错归属 |
|
||||
|
||||
证据:DP `internal/store/postgres/coverage.go:33–55`;`internal/questiontable/dispatcher.go:168–185`;KB `scripts/01_import_raw.py:180–230`;WR `scripts/10_calc_region_usage_metrics.py:336–375`。
|
||||
|
||||
## 4. 报表指标可用性清单
|
||||
|
||||
分级针对**当前完整业务指标**,不把“有字段”当作“已有可信接口”。原始计数已支持的部分单独注明;所有后端数据实际填值仍待 live 核实。
|
||||
|
||||
| 目标指标 | 分级 | 现有可复用基础 | 必须补齐 / 验证 |
|
||||
|---|---|---|---|
|
||||
| 每周有效提问数量 | **部分支持,需要补充字段或逻辑** | 表格日期计数已支持,可直接查原始周行数;后端 turn 唯一键 | 有效问题、测试排除、失败是否纳入、双表去重和入口范围 |
|
||||
| 知识覆盖率 | **部分支持,需要补充字段或逻辑** | 后端规则决策;旧表覆盖标签;离线覆盖公式 | 选择权威覆盖源、统一分母;2.0表标签为空,不能出质量结论 |
|
||||
| 回答正确率 | **部分支持,需要补充字段或逻辑** | 旧表正确性标签、脚本 | 核实 AI 评估写入源及版本;限定已覆盖交集;2.0无正确性标签 |
|
||||
| 有效解答率 | **部分支持,需要补充字段或逻辑** | 旧表可筛覆盖=是且正确=是,已实测交集计数 | 没有找到正式有效解答率实现;需同一有效样本分母与缺评估处理 |
|
||||
| 与上周对比 | **部分支持,需要补充字段或逻辑** | 日期范围已支持,两期可查原始计数 | 统一两期口径与 as-of;没有核实不可变历史统计快照 |
|
||||
| 活跃用户数量 | **部分支持,需要补充字段或逻辑** | 人员字段 DISTINCT、后端 actors/union ID | 稳定 ID、单人行、跨入口合并、机器人/测试排除;字段不同值不是可靠人数 |
|
||||
| 按部门、区域、产品统计 | **部分支持,需要补充字段或逻辑** | 旧表标签、人员快照、目录和区域脚本 | 2.0全部为空;补关联与未知桶;产品分类不是渠道 |
|
||||
| 月使用次数≥5的技术人员数量 | **部分支持,需要补充字段或逻辑** | 历史 backup 有≥5次逻辑;目录有职位/任职字段 | 当前入口未实现该指标;统一技术人员名单、有效事件与稳定ID、自然月 |
|
||||
| 未覆盖问题 Top N | **部分支持,需要补充字段或逻辑** | 旧表覆盖=否,后端 uncovered/support_cases | 选择按事件还是归并问题;归并键、排序、授权与脱敏;未找到正式排名API |
|
||||
| AI 评估完成率 | **部分支持,需要补充字段或逻辑** | 当前标签非空/待确认可统计;后端决策存在性 | 非空不等于完成,规则覆盖不等于AI评估;执行状态、应评样本、正确性终态定义待补 |
|
||||
| 自动邮件周报(交付能力) | **暂不支持,需要开发** | 可复用统一统计结果;DWS 有 mail 服务但不代表项目已有邮件周报 | 本轮未找到项目邮件周报任务、投递去重、失败重试与发送审计实现 |
|
||||
|
||||
**当前可以直接查询的内容:**原始记录量、时间范围行数、标签分布、字段填值量和字段 DISTINCT。这些查询能力已经实测,不等价于完整目标指标已验收。
|
||||
|
||||
## 5. 当前的数据缺口和技术风险
|
||||
|
||||
### 5.1 P0:先澄清,避免做出“看起来正确”的错误周报
|
||||
|
||||
1. **生产证据缺口:**live DB 不可达,部署 SHA 未取得;需提供只读访问或由运维导出脱敏 schema/聚合。不能拿本地迁移证明生产已具备全部字段。
|
||||
2. **评估来源不明:**用户描述的“AI 自动覆盖与正确性评估”尚未定位到实际执行代码;表格字段配置未证明其自动化机制,后端现有覆盖器不是 AI 评测。
|
||||
3. **2.0标签断点:**质量、产品、部门和区域字段无填值。先查真实数据是否在别处,避免重新建设已有评估器。
|
||||
4. **无统一分母:**归并问题主表、流水事件、规则成功问答、旧真实问题过滤不一致。
|
||||
5. **双表版本不是入口:**同时写入/迁移关系未知,直接相加有重复风险。
|
||||
|
||||
### 5.2 P1:实现前要纳入验收
|
||||
|
||||
- 状态缺失:后端成功问答可缺覆盖评估,表格“待确认”无法区分进行中/人工待审/失败。
|
||||
- 评估更新:后端首次决策幂等与“取最新评估”目标不兼容;不能静默变更现有策略。
|
||||
- 用户反馈不等于正确性:点踩理由 incorrect 是用户反馈,不是统一 AI 评估标注。
|
||||
- 维度漂移:提问时快照与当前目录应分开;按当前部门重算历史会变动。
|
||||
- 人员去重:不同渠道 external ID、staff ID、union ID 不等价;姓名只能作低可信回退。
|
||||
- 产品归类:后端未见相应字段,旧脚本同名问题回退可能跨产品误配。
|
||||
- 区域规则分叉:weekly_report 与 kb_ops 的09/10已有不同别名规则,不应复制两套继续演化。
|
||||
- 时间口径:提问时间、系统入站时间、评估写入时间不同;周窗口必须选定一种,评估完成作为另一个 as-of。
|
||||
- 分母为零:现有脚本输出零,新的正式报表宜输出 null/not_available,并给缺失原因,不能暗示正确率为0%。
|
||||
- 性能与权限:避免每周全量读入问答正文;服务端聚合、固定窗口、只读凭据、超时及租户校验优先。
|
||||
- 邮件数据泄露:默认仅汇总;Top N需脱敏、权限和明确授权,不嵌入员工个人明细。
|
||||
|
||||
## 6. 最小改造方案及预估工作量(建议,未实施)
|
||||
|
||||
### 6.1 推荐方案 / 备选方案 / 不推荐
|
||||
|
||||
| 方案 | 内容 | 评价 |
|
||||
|---|---|---|
|
||||
| **推荐** | 在现有知识治理后端增加一个轻量运营统计模块;读现有问答/目录/评估源,统一归一化与计算;API及邮件共享结果 | 一个开发者可维护,不增微服务,不重建日志;先以 live 权威源核实为前提 |
|
||||
| **备选** | 表格作为权威源时,先用 DWS 聚合/窄字段读取生成可复核统计,再接入同一模块 | 出数快,但目前2.0标签缺失,评估追踪/远端去重仍弱;不能据此承诺全指标可用 |
|
||||
| **不推荐** | 新建问答日志系统、另做邮件专用公式、长期全量导出大表、拿检索score/监控成功率冒充正确率 | 重复建设、口径漂移、隐私与维护成本高 |
|
||||
|
||||
若生产问答库不可安全跨库读取,可将同一统计模块部署到已有 DobotAI 服务并通过只读聚合接口供治理平台消费。**二选一落地,不先创建两个同义统计实现。**
|
||||
|
||||
### 6.2 模块边界与复用点
|
||||
|
||||
| 模块(建议) | 输入 / 输出 | 边界与复用 |
|
||||
|---|---|---|
|
||||
| 只读来源适配 | 原问答记录、当前评估、人员快照 → 归一化事件 | 复用 turns/messages/coverage_decisions;正确性先定位原系统,禁止新增替代评测器;旧表仅作明确授权历史源 |
|
||||
| 口径与统计 | 同一范围内事件+已批准规则 → 总量、分子分母、维度、两期对比、缺失诊断 | 复用12脚本标签规范化/异常计数和10脚本区域规则;**不直接沿用有冲突的分母/姓名去重** |
|
||||
| V1只读API | 授权过滤 → 统一统计结果 | 复用治理HTTP、鉴权、日志;不复用 monitor 的任务成功率 |
|
||||
| 周报快照/渲染 | 同一统计结果 → 报表摘要/邮件内容 | 复用现有持久任务设施(jobs),但先核实扩展点;快照持久化位置需批准后设计 |
|
||||
| 邮件投递 | 已批准收件范围+快照 → 发送/失败审计 | 不在发送环节重新计算;定时、重试、投递幂等单独处理 |
|
||||
|
||||
后续涉及页面/UI时,**先移交 prototype Agent** 做数据缺失、口径说明、筛选及对比状态原型;原型确认后才进入正式开发。本轮没有启动 prototype、coder、tester或CI/CD任务。
|
||||
|
||||
### 6.3 归一化数据模型草案(DTO,不是新增数据库表)
|
||||
|
||||
| 建议字段 | 来源与规则 |
|
||||
|---|---|
|
||||
| `source / source_record_id` | 后端 turn ID 或表格record ID+表ID,保持来源命名空间 |
|
||||
| `tenant / channel / occurred_at` | 优先现有租户/渠道/选定提问时间;未知渠道不得伪造 |
|
||||
| `person_key / identity_quality` | 来源稳定ID及映射置信等级;报告不返回原始人员ID |
|
||||
| `department / region / product` | 快照/标签,缺失进入unknown;产品由现有分类来源提供 |
|
||||
| `is_valid / exclusion_reason` | 用户确认的统一规则;与是否已评估分开 |
|
||||
| `coverage_value / coverage_source / coverage_version` | 后端规则和表格AI标签必须标注来源,不能无说明混合 |
|
||||
| `correctness_value / correctness_source` | 原正确性评估;unknown/pending与incorrect分开 |
|
||||
| `evaluation_state / evaluated_at` | 有证据才填写;不能把问答成功时间当评估完成时间 |
|
||||
|
||||
没有证据的状态/版本保持 unknown,报表附质量诊断。若需要正式评估历史,优先评估已有原系统能力,再决定是否加小型关联/快照存储;**本轮不提供DDL,不变更数据库**。
|
||||
|
||||
### 6.4 指标口径草案(待用户确认,不是现状)
|
||||
|
||||
设同一范围内:`V`=有效事件数;`C`=有效且已覆盖事件数;`R`=有效且已覆盖且回答正确事件数。
|
||||
|
||||
- 期望覆盖率=`C/V`;正确率=`R/C`;有效解答率=`R/V`。
|
||||
- 同时返回未评估、正确性待确认、评估失败/未知、测试排除等数量;是否将未评估有效事件保留在V和已覆盖待正确性评估事件保留在C,**须明确确认**。不能把暂缺标签暗中视为“否”。
|
||||
- 若另提供“已评估样本表现”,必须使用不同指标名与分母说明,不冒充上述业务覆盖率。
|
||||
- 周范围推荐 Asia/Shanghai 周一00:00起、下周一00:00止,半开区间;月≥5按自然月及有效事件数计算。
|
||||
- 计次单位推荐问答turn;会话、答案消息和重复回调不额外计次。正常多轮各turn是否算一次由业务确认。
|
||||
- 比较两周时同一rule_version与as-of策略;可冻结已发布结果并提供明确重算版本,不能悄然修改已发送邮件的历史值。
|
||||
|
||||
### 6.5 V1 API草案(新建议,尚不存在)
|
||||
|
||||
建议仅新增一个端点:`GET /api/v1/operations/report`,参数 `start/end/timezone`、可选 `channel/department/region/product`、`compare=previous_period`、`top_n`。最终路由名称待仓库规范确认。
|
||||
|
||||
响应逻辑字段:
|
||||
|
||||
- `period, timezone, generated_at, as_of, rule_version, sources, source_versions`。
|
||||
- `counts`:原始量、有效量、已覆盖量、已覆盖且正确量、各类未评估/排除量。
|
||||
- `metrics`:每项 value/numerator/denominator/status,缺证据时not_available,不用假零。
|
||||
- `comparison`:上期计数及指标;率差用百分点,量变化可用百分比;上期分母为零时显式不可比。
|
||||
- `dimensions`:已授权维度聚合与unknown桶;避免多区域展开使总计膨胀。
|
||||
- `top_uncovered`:脱敏题目/归并标识/次数;默认不输出员工信息,权限不足不返回明细。
|
||||
- `data_quality`:缺标签、身份未匹配、维度缺失、重复待查、来源/评估版本差异。
|
||||
|
||||
自动邮件调用**同一内部统计入口**,使用其结果快照渲染,不另外写SQL或复刻公式。发送幂等建议由“周期+规则/快照版本+收件组”组成;未知投递结果不能盲目重发。
|
||||
|
||||
### 6.6 安全、日志、部署与CI/CD影响
|
||||
|
||||
- 数据源使用只读身份,设置查询超时,禁止写入、DDL或将秘密放入Git;报告和邮件仅输出授权范围聚合。
|
||||
- 复用治理鉴权与租户边界;报表访问、导出和邮件投递留审计,日志只含周期、规则版、计数、耗时、稳定失败码。
|
||||
- 默认不引入新微服务、消息队列或独立运行栈;新增统计模块随现有API部署,邮件复用已核实后的任务框架。
|
||||
- 后续CI增加纯统计契约测试:空样本、待确认、重复事件、多轮、双表来源、跨租户、跨区域、零分母、两期版本一致性。
|
||||
- 本轮未改变工作流、Runner、生产部署和数据库。后续数据库/索引/调度变更均需单独批准与回滚方案。
|
||||
|
||||
### 6.7 工作量估计
|
||||
|
||||
以下为架构估算,不是实测工时或已批准开发排期;单位为单人工作日,不含UI正式实现、重新建设AI评估器及历史数据大规模回填。
|
||||
|
||||
| 后续工作 | 预估 | 前提 / 验收 |
|
||||
|---|---:|---|
|
||||
| 生产只读核验与口径确认 | 1天 | 取得真实schema、部署SHA、渠道枚举、评估来源和填值聚合 |
|
||||
| 只读来源适配+统一统计核心 | 2–3天 | 对拍固定范围的分子分母、异常/未知桶、去重规则 |
|
||||
| V1接口+对比+基础维度/Top N | 1–2天 | API和独立核对结果一致,无未授权个人明细 |
|
||||
| 周报快照/调度/邮件复用 | 1–2天 | 同一快照与API数值一致;批准测试收件人;失败重试不重复发送 |
|
||||
| 回归与验收证据整理 | 1–2天 | 边界测试、固定范围对拍、性能和权限记录完整 |
|
||||
|
||||
**基础范围估计合计6–10工作日**。若正确性原系统不可接入、缺turn↔record映射或要回填2.0维度/历史评估,需调查后另估,不能承诺上述时间覆盖所有缺口。
|
||||
|
||||
### 6.8 Gitea Issue规划(草案,未创建,不建DEV任务)
|
||||
|
||||
| 标题 / 类型 | 交付与验收标准 | 依赖 |
|
||||
|---|---|---|
|
||||
| `[ARCH] 核实生产问答与评估数据源` | 脱敏live schema、部署SHA、实际渠道值、成功turn与缺决策量、评估版本分布;明确AI正确性来源;全部只读 | 只读访问/运维证据 |
|
||||
| `[DECISION] 确认有效问题和三个质量指标口径` | 批准V/C/R、测试排除、未评估处理、turn计次、时区窗口、技术人员范围与历史重算规则 | 来源核验 |
|
||||
| `[ARCH] 运营统计模块与V1接口契约` | 单一计算入口、来源映射、API草案、unknown/不可用状态、对拍及权限验收标准 | 口径确认 |
|
||||
| `[ARCH] 邮件周报复用与投递幂等设计` | 同一快照供API/邮件使用;收件权限、重试、未知投递处理与审计方案 | V1契约 |
|
||||
| `[UI] 运营报表V1原型交接prototype` | 筛选、两期对比、缺失数据提示、指标分母/来源说明;用户批准原型,不写正式UI业务代码 | 口径和契约 |
|
||||
|
||||
## 7. 需要用户确认的问题
|
||||
|
||||
1. **生产部署在哪里?** 本地 DobotAI 连接配置对应DB不可达,请提供生产项目路径/只读访问方式,或让运维输出无个人信息的schema与聚合;不要在聊天发送密码或Token。
|
||||
2. **AI自动评估由什么执行?** 是钉钉AI字段、外部工作流、离线批处理还是另一系统?请给执行代码/配置所在位置及其结果目标表;现有后端v3规则不是该正确性评估。
|
||||
3. **哪份评估是权威?** 表格覆盖标签与后端规则决策是否刻意分别保留?若不一致,以哪份为正式周报口径?
|
||||
4. **两个流水表的关系?** 为什么时间同时延伸到本轮当天?是否双写、试点/正式用户分流或历史迁移?是否有现有消息ID/turn ID映射文件或表?
|
||||
5. **有效提问范围?** 是否排除测试人员、无效/范围外问题、纯寒暄、失败问答、图片问题和设置指令?内置排除名单是否仍有效?
|
||||
6. **未评估与待确认如何进入分母?** 正式业务率与已评估样本率是否同时展示?零样本是否显示“暂无可用评估”,而不是0%?
|
||||
7. **入口范围和人员定义?** Studio Pro/Wiki是否问答入口、实际渠道值是什么?“技术人员”是技术支持岗位还是更大名单?≥5次是否按有效turn和自然月?
|
||||
8. **历史归属与发布策略?** 按提问时部门/区域还是当前通讯录?周报冻结还是自动随评估更新重算?周窗口是否采用周一至周一、北京时间?
|
||||
9. **Top N语义与邮件权限?** 排名按重复提问频次还是每条未覆盖事件?哪些人员能看脱敏问题?收件人范围、发送日/时间和重发策略是什么?
|
||||
10. **正式离线报表入口是哪份?** weekly_report、kb_ops还是knowledge_ai_report旧流程?确认后保留一套权威规则,避免三份实现互相冲突。
|
||||
|
||||
## 附录:证据定位与复核方式
|
||||
|
||||
路径缩写:DP=`/home/zheromiku/dobotai-platform`;KG=`/home/zheromiku/knowledge-governance`;KA=`/home/zheromiku/knowledge-adapter-service`;WR=`/home/zheromiku/DOBOTAI/weekly_report`;KB=`/home/zheromiku/DOBOTAI/kb_ops`;KR=`/home/zheromiku/DOBOTAI/knowledge_ai_report`。迁移简称均在DP `db/migrations/`,例如000007对应 `000007_coverage_decisions.up.sql`。
|
||||
|
||||
### A. DWS只读命令示例
|
||||
|
||||
```sh
|
||||
# 明确限定两表,读取字段/视图目录
|
||||
dws aitable table get --base-id KGZLxjv9VG37o9N6IYvYGBl9V6EDybno --table-ids w0nYx0a,jQ6oevs
|
||||
# 完整表头;按字段展开配置前先确认ID
|
||||
dws aitable field get --base-id KGZLxjv9VG37o9N6IYvYGBl9V6EDybno --table-id w0nYx0a
|
||||
# COUNT统计匹配记录,不加limit避免仅统计子集
|
||||
dws aitable record stats --base-id KGZLxjv9VG37o9N6IYvYGBl9V6EDybno --table-id w0nYx0a --stats '[{"fieldId":"ZaMZF6j","statsType":"COUNT"}]'
|
||||
```
|
||||
|
||||
实际标签筛选使用field get取得的option ID:覆盖“是”=`MPfK0hpGNX`,“否”=`rZT6tj41Je`,“否但不计入”=`1IJOik1qP8`;正确“是”=`p1jnsxEU3R`,“待确认”=`VGER9DlTkn`。日期范围使用 `not_before` 与 `before`,而非通用数值比较运算符。
|
||||
|
||||
本轮字段/聚合JSON保存在调查用scratch目录下 `dobotai-investigation/`;其中 `sanitized-summary.json` 含聚合摘要,不含原始问答或人员记录。失败响应未伪造成结果。
|
||||
|
||||
### B. 关键源码索引
|
||||
|
||||
| 文件 | 用途 |
|
||||
|---|---|
|
||||
| DP `internal/core/types.go:39–56,91–122` | 请求和turn模型 |
|
||||
| DP `internal/store/postgres/store.go:50–129,196–283` | 问答/消息事务写入,送达分离 |
|
||||
| DP `internal/qa/service.go:166–177,285–298` | 重放、成功评估observer、错误边界 |
|
||||
| DP `internal/coverage/{types,evaluator,service}.go` | 覆盖版本、规则及持久化服务 |
|
||||
| DP `internal/store/postgres/coverage.go:33–55` | 决策幂等和支持单关联 |
|
||||
| DP `internal/questiontable/row.go:36–87` | 实际表格字段映射、select省略 |
|
||||
| DP `internal/store/postgres/question_table_exports.go:80–98` | 导出数据来源,未关联评估 |
|
||||
| DP `internal/questiontable/dispatcher.go:168–185` | 远端写入后标记本地,重复窗口 |
|
||||
| DP `internal/httpapi/server.go:86–92,130–188` | 现有问答/审计API契约 |
|
||||
| DP `internal/channels/dingtalk/handler.go:189–265` | 入口、人员补全和请求 |
|
||||
| DP `internal/directory/resolver.go:35–64` | 通讯录缓存与故障回退 |
|
||||
| WR `scripts/12_calc_kb_metrics.py:128–179,282–308` | 当前流水统计样本与真实公式 |
|
||||
| WR `scripts/12_run_08_09_10_pipeline.py:154–180` | 月份只传区域统计的时间错位 |
|
||||
| WR `scripts/10_calc_region_usage_metrics.py:286–342,345–448` | 自然月、区域展开、人数与次数统计 |
|
||||
| KB `scripts/06_calc_metrics.py:139–159` | 问题主表不同分母 |
|
||||
| KB `scripts/01_import_raw.py:82–110,180–230` | 清洗/事件哈希去重 |
|
||||
| KR `backup/calculate_metrics.py:182–290` | 旧真实问题与技术人员≥5逻辑 |
|
||||
| KR `backup/usage/region_usage.py:135–195` | 另一份按ID的月≥5逻辑 |
|
||||
| KG `internal/monitoring/{real,metrics}.go` | 知识运行监控,不是问答质量统计 |
|
||||
| KA `src/knowledge_adapter/{app,models,observability}.py` | 外部检索、请求边界及脱敏日志 |
|
||||
|
||||
**下一步门槛:先确认数据源与口径,再批准实现;本报告不代表已批准开发、数据回填、结构变更或邮件发送。**
|
||||
@@ -0,0 +1,160 @@
|
||||
# 三 Agent 交接闭环工作流(架构 / 开发 / 验收)
|
||||
|
||||
> 适用仓库:`Weknora/knowledge-governance`(默认分支 `main`)。
|
||||
> 本文件是**交接契约**,不是介绍:它规定角色边界、状态机、版本口径与交接证据格式,
|
||||
> 供三个独立会话(架构 / 开发 / 验收)在同一仓库上串行协作时逐条核对。
|
||||
> 依据:工单 `#6` 的「文档内容合同」8 条(正文=目标与范围,评论=证据,commit/tag=版本)。
|
||||
|
||||
## 0. 与工单合同条目的对应(便于独立验收逐条核对)
|
||||
|
||||
| 合同条目 | 本文位置 |
|
||||
|---|---|
|
||||
| 1 三角色职责 | §1 |
|
||||
| 2 main 单线、串行修改 | §2 |
|
||||
| 3 六个状态名、标签互斥、blocked 要素 | §3 |
|
||||
| 4 每轮可交接的修改链路(自测→commit→快照 tag→推送→核实→review) | §4、§5 |
|
||||
| 5 不可变与回退规则 | §5 |
|
||||
| 6 开发/验收交接模板 | §6 |
|
||||
| 7 关单条件 | §7 |
|
||||
| 8 安全与边界 | §8 |
|
||||
|
||||
## 1. 三角色职责
|
||||
|
||||
| 角色 | 能做 | 不能做 |
|
||||
|---|---|---|
|
||||
| **架构** | 需求、设计、把目标/范围/验收标准写成工单;维护工单正文与验收矩阵;写设计文档 | 不写业务代码、不改测试/依赖/构建配置、不推送、不启动其他 Agent |
|
||||
| **开发** | **唯一**可以改业务代码、测试、依赖、迁移、构建配置与项目文档的角色;自测、commit、打快照 tag、推送 main 与 tag | 不设置 `accepted`、不关单、不改验收标准、不部署 |
|
||||
| **验收** | 独立复核差异与版本信息,逐项判定 PASS/FAIL/BLOCKED;通过后置 `accepted` 并关单 | 不修复代码(发现问题置 `rework` 并把问题列清)、不自行 `checkout`/`reset` |
|
||||
| **prototype(UI)** | **仅**当工单涉及 UI 原型时介入,产出可打开的原型与交互证据 | 不参与非 UI 任务,不代替开发提交业务代码 |
|
||||
|
||||
角色约束是**流程约束**,不是技术 ACL 隔离:本机共用 Gitea 管理员凭据,谁也拦不住谁越权,
|
||||
所以每个角色都要靠"读回核实"而非"相信对方自述"来交付。
|
||||
|
||||
## 2. main 单线、单仓库串行
|
||||
|
||||
- 只使用 `main` 一条线:**不创建分支、不建 worktree、不走 PR、不做合并**(通用引擎规范里 PR 是可选姿态,
|
||||
本仓沿用"以直推为主"的口径)。
|
||||
- 同一仓库的代码修改**串行**:一个工单在主开发阶段只由一个开发会话持有。
|
||||
- **review 期间开发停止修改代码**:工单进入 `status:review` 后,除按 `rework` 要求修复外不再改动。
|
||||
- 切换现场前先取证:`git status --short --branch`、`git worktree list`、`git rev-parse origin/main`。
|
||||
工作区不干净、或存在不属于本工单的改动时**不得混入**,安全处理不了就置 `status:blocked`。
|
||||
- 别人的 feature 分支与成果原样保留:不 `reset`、不 `stash`、不 cherry-pick、不清理旧分支/worktree/tag。
|
||||
|
||||
## 3. 工单状态机
|
||||
|
||||
六个完整状态名,**互斥**,同一工单最多一个状态标签:
|
||||
|
||||
```
|
||||
status:ready → status:developing → status:review → status:accepted
|
||||
↑ │
|
||||
└── status:rework ─┘ status:blocked(可从中途进入,解除后回原状态)
|
||||
```
|
||||
|
||||
| 标签 | 含义 | 进入条件(缺一不可) |
|
||||
|---|---|---|
|
||||
| `status:ready` | 设计完成、用户已批准开发 | 用户明确批准;范围与验收标准写明 |
|
||||
| `status:developing` | 开发已领取并在实施 | 评论记录工单号、起始 SHA |
|
||||
| `status:review` | 已交付待独立验收 | commit/tag/推送/远端核实/交接证据齐全 |
|
||||
| `status:rework` | 验收失败 | 验收列出明确不通过项(不授权扩范围) |
|
||||
| `status:accepted` | 指定版本通过验收待核实交付 | 验收矩阵逐项通过,结论绑定 tag + 完整 SHA |
|
||||
| `status:blocked` | 受阻停手 | 有原因、处理人、解除条件、原状态;解除后**恢复原状态** |
|
||||
|
||||
- `Closed` 是 **Issue 状态**,不是标签:通过验收后由验收移除状态标签并关闭。
|
||||
- 未批准的工单保持 Open 且**不打** `status:ready`。
|
||||
- 标签 ID **按仓库实时读取**(`GET /api/v1/repos/{owner}/{repo}/labels`),不跨仓库复用 ID。
|
||||
- ⚠️ Gitea 1.26.2 实测:`PATCH /issues/{n}` 带 `labels` 返回 201 **却不改任何标签**(静默无效);
|
||||
替换标签必须用 `PUT /issues/{n}/labels`,且每次写完 `GET /issues/{n}` **读回核验**。
|
||||
- ⚠️ 本仓历史遗留标签 `status/working`(`/` 而非 `:`)不符合本约定,遇到时应归一为 `status:developing`。
|
||||
|
||||
## 4. 快照 tag 与正式版本分线
|
||||
|
||||
**两种版本语义必须分开**,混用会让 CI 变红或让快照被误当发布。
|
||||
|
||||
| | 快照(开发交付用) | 正式版本(发布用) |
|
||||
|---|---|---|
|
||||
| 命名 | `snapshot/vX.Y.Z` | `vX.Y.Z` |
|
||||
| 类型 | **注释 tag**(`git tag -a`) | **注释 tag**(`git tag -a`) |
|
||||
| 批准 | 开发按工单直接创建,序号递增 | **用户单独批准** |
|
||||
| 与 CHANGELOG 的关系 | 无要求;快照序号独立于构建显示版本,**不要求二者相等** | 必须同步写 `CHANGELOG.md` 顶部该版本段 |
|
||||
| CI 门禁 | 不被当作正式版本 | 受版本一致性门禁约束 |
|
||||
| 含义 | 代码快照,**不代表验收、不代表发布** | 发布事实,需 Release 等后续动作 |
|
||||
|
||||
**为什么不能用 `vX.Y.Z` 当快照(实测结论,勿凭直觉改回)**
|
||||
|
||||
- `make verify` → `scripts/check_changelog.py --tags`(`Makefile:27`、`scripts/ci_checks.py:254`)对每个
|
||||
`vX.Y.Z` tag 断言:tag 指到的提交里 `CHANGELOG.md` 顶部正式版本 == tag 版本,且必须是注释 tag
|
||||
(`scripts/check_changelog.py:44-45,257-278`)。
|
||||
- CI 检出会把 `git ls-remote --tags origin` 落成 `.ci-remote-tags` 并 `fetch --tags`(`.gitea/scripts/ci_checkout.sh:122,127`);
|
||||
`CI=true` 时拿不到清单直接判红 ⇒ **不带 CHANGELOG 段的正式 tag 会让 main 从此每次推送都红**。
|
||||
- 正式 tag 的匹配是 `^v(\d+\.\d+\.\d+)$`(`scripts/check_changelog.py:45`),`snapshot/v0.1.1` **不匹配**,
|
||||
因此不参与版本一致性判定;`scripts/version.py:119-151` 的发布证据也只认 `refs/tags/v<版本号>` 的注释 tag
|
||||
与 CHANGELOG 顶部一致 ⇒ 快照 tag 不会把构建身份变成 release。
|
||||
- 结论:快照一律用 `snapshot/vX.Y.Z`;要发正式版就单独走批准 + CHANGELOG 流程。
|
||||
- 修复后的下一快照序号递增(`snapshot/v0.1.2`),**不得移动已交付的快照 tag**。
|
||||
|
||||
## 5. 每轮可交接的完整链路 + 不可变性
|
||||
|
||||
一轮可交付的修改必须走完整条链,任何一步失败都要如实报告**实际状态**,不能假装完整交付:
|
||||
|
||||
```
|
||||
自测(真实命令 + 真实结果)
|
||||
→ commit(信息含工单号;不用 Closes/Fixes/Resolves 等自动关单关键词)
|
||||
→ 创建递增的不可变快照 tag(注释 tag)
|
||||
→ 正常推送 main 与该 tag
|
||||
→ 远端核实(main 含结束 SHA;tag 解引用后指向结束 SHA)
|
||||
→ 工单评论完整交接证据 → status:review
|
||||
```
|
||||
|
||||
- 开发的**正常 main 与快照 tag 推送无需逐次确认**;但**部署与正式发布不在授权内**。
|
||||
- 推送前必须先核查:目标名未被占用、推送是否会触发生产部署(`.gitea/workflows/` 里是否有 deploy 作业)。
|
||||
本仓唯一工作流 `build.yml` 头部明确"只做 CI,不做 CD"(`on: push: branches: "**"`)⇒ 普通 CI 允许放行。
|
||||
- **保留旧提交与旧 tag**:不强推、不覆盖、不删除旧 tag、不改写历史。
|
||||
- 回退只能由开发执行 `git revert` 并创建**新的**版本(`revert` + 递增快照),旧提交与旧 tag 原样留着。
|
||||
- CI 绿 ≠ 已部署;`main` 不是自动可发布版本。
|
||||
|
||||
## 6. 交接与验收模板
|
||||
|
||||
### 6.1 开发交接(写进工单评论)
|
||||
|
||||
| 字段 | 内容 |
|
||||
|---|---|
|
||||
| 工单 | 编号 + 标题 |
|
||||
| 起始 SHA | 动手前的 `origin/main` 完整 SHA |
|
||||
| 结束 SHA | 本次提交的完整 SHA |
|
||||
| tag | 快照 tag 名 + 类型(注释)+ 解引用后的 SHA |
|
||||
| 实现摘要 | 改了什么、为什么这么改 |
|
||||
| 文件清单 | `git diff --stat` 的范围,逐条列出 |
|
||||
| 测试命令与结果 | **真实执行的命令 + 真实输出**(不可只写"已测试") |
|
||||
| 已知问题 | 未验证项、环境限制、待批事项 |
|
||||
| 剩余完成项 | 明确列表;没有就写"无" |
|
||||
|
||||
### 6.2 验收结论(写进工单评论)
|
||||
|
||||
| 字段 | 内容 |
|
||||
|---|---|
|
||||
| 版本锚点 | tag + 完整 SHA(结论必须绑在这上面) |
|
||||
| 逐项判定 | 合同/矩阵每项 `PASS` / `FAIL` / `BLOCKED`,FAIL 必须列明确问题 |
|
||||
| 复验命令与结果 | 独立跑过的只读检查(如 `git diff --check`、远端 tag 读回)与真实输出 |
|
||||
| 问题与结论 | 通过 ⇒ 下一步;不通过 ⇒ 置 `rework` 并把问题列清;无法验证 ⇒ 置 `blocked` |
|
||||
|
||||
验收不得凭开发总结宣告通过;也不得自行 `checkout`/`reset` 去凑现场 —— 现场不对就要求开发准备。
|
||||
|
||||
## 7. 关单条件
|
||||
|
||||
同时满足才可关单:
|
||||
|
||||
1. 验收矩阵全部通过;
|
||||
2. 目标版本可追溯(tag + 完整 SHA 可读回);
|
||||
3. 远端交付已核实(远端 main 含结束 SHA,tag 解引用一致);
|
||||
4. 交接与验收文档齐全(含真实执行证据);
|
||||
5. 无未解除的阻塞项。
|
||||
|
||||
**不需要** PR、不需要合并、**不默认需要部署**。
|
||||
|
||||
## 8. 安全与边界
|
||||
|
||||
- 不提交任何密钥/隐私:决定只用 secret 文件(仓库外、0600),日志与评论不出现秘密与正文原文。
|
||||
- 每个外部写操作(标签、评论、tag、推送)都**读回核实**;结果不明确时不得宣布成功。
|
||||
- 不使用自动关单关键词,不绕过独立验收。
|
||||
- 角色约束不是技术隔离;`main` 也不是自动可发布版本。
|
||||
- 每次执行开始先确认:仓库、路径、工单、当前状态、最新评论、授权;缺一项且无法查询就先问,不猜。
|
||||
@@ -67,8 +67,11 @@ type Config struct {
|
||||
VersionHistoryGiteaBaseURL string
|
||||
VersionHistoryRepo string
|
||||
VersionHistoryAllowedOrigins []string
|
||||
VersionHistoryHTTPTimeout time.Duration
|
||||
VersionHistoryMaxPages int
|
||||
// VersionHistoryLinkOrigin 是**页面链接**用的 origin(给内网外的浏览器点开),
|
||||
// 留空即与抓取 origin 相同。只用于拼展示链接,不参与任何请求。
|
||||
VersionHistoryLinkOrigin string
|
||||
VersionHistoryHTTPTimeout time.Duration
|
||||
VersionHistoryMaxPages int
|
||||
}
|
||||
|
||||
func Load(getenv func(string) string) (Config, error) {
|
||||
@@ -113,6 +116,7 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
|
||||
VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"),
|
||||
VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")),
|
||||
VersionHistoryLinkOrigin: strings.TrimSpace(getenv("VERSION_HISTORY_LINK_ORIGIN")),
|
||||
VersionHistoryHTTPTimeout: 15 * time.Second,
|
||||
VersionHistoryMaxPages: valueOrDefaultInt(getenv("VERSION_HISTORY_MAX_PAGES"), 200),
|
||||
}
|
||||
@@ -202,7 +206,8 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
// 版本记录来源:给了 origin 就必须是干净的 http(s) origin;白名单留空则默认只许自己。
|
||||
if config.VersionHistoryGiteaBaseURL != "" {
|
||||
if err := validateHTTPBaseURL(config.VersionHistoryGiteaBaseURL); err != nil {
|
||||
return Config{}, fmt.Errorf("VERSION_HISTORY_GITEA_BASE_URL: %w", err)
|
||||
return Config{}, fmt.Errorf("VERSION_HISTORY_GITEA_BASE_URL: %w%s", err,
|
||||
envHint(config.VersionHistoryGiteaBaseURL))
|
||||
}
|
||||
if len(config.VersionHistoryAllowedOrigins) == 0 {
|
||||
config.VersionHistoryAllowedOrigins = []string{config.VersionHistoryGiteaBaseURL}
|
||||
@@ -215,6 +220,11 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
if strings.Count(config.VersionHistoryRepo, "/") != 1 {
|
||||
return Config{}, errors.New("VERSION_HISTORY_REPO 必须是 owner/name 形式")
|
||||
}
|
||||
if config.VersionHistoryLinkOrigin != "" {
|
||||
if err := validateHTTPBaseURL(config.VersionHistoryLinkOrigin); err != nil {
|
||||
return Config{}, fmt.Errorf("VERSION_HISTORY_LINK_ORIGIN: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if config.TestWeKnoraHTTPTimeout, err = durationOrDefault(getenv("TEST_WEKNORA_HTTP_TIMEOUT"), config.TestWeKnoraHTTPTimeout); err != nil {
|
||||
return Config{}, fmt.Errorf("TEST_WEKNORA_HTTP_TIMEOUT: %w", err)
|
||||
@@ -312,6 +322,15 @@ func validateHTTPBaseURL(value string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// envHint 给"值明显不像一个地址"的情况补一句线索:最常见的成因是 `.env` 里两行粘在一起
|
||||
// (新键被追加到没有结尾换行的上一行后面)—— 值里就会出现第二个 `KEY=`。
|
||||
func envHint(value string) string {
|
||||
if strings.Contains(value, "=") {
|
||||
return "(值里出现了 `=`:`.env` 里两行可能粘成了一行,改成一行一值再上线)"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// splitOrigins 解析逗号分隔的 origin 白名单(空项丢弃)。
|
||||
func splitOrigins(value string) []string {
|
||||
parts := strings.Split(value, ",")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package appconfig
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -290,3 +291,34 @@ func TestProductionWeKnoraEndpointIsConfigurableAndFailsClosed(t *testing.T) {
|
||||
t.Fatalf("production endpoint must default to unconfigured: %#v", unset)
|
||||
}
|
||||
}
|
||||
|
||||
// 回归用例(2026-10-14 线上事故):`.env` 两行粘成一行时,base URL 会变成
|
||||
// "http://host:3000VERSION_HISTORY_LINK_ORIGIN=…" —— 必须被拒,并给出线索文案,
|
||||
// 而不是让 api/worker 带着坏值崩溃重启(或者更糟:静默按坏值跑起来)。
|
||||
func TestLoadRejectsMergedVersionHistoryEnvValue(t *testing.T) {
|
||||
values := map[string]string{
|
||||
"DATABASE_URL": "postgres://example",
|
||||
"VERSION_HISTORY_GITEA_BASE_URL": "http://192.168.50.223:3000VERSION_HISTORY_LINK_ORIGIN=https://gitea.example",
|
||||
}
|
||||
_, err := Load(func(key string) string { return values[key] })
|
||||
if err == nil {
|
||||
t.Fatal("粘在一起的值必须被拒绝")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "粘成了一行") {
|
||||
t.Fatalf("错误里应给出线索(.env 粘行):%v", err)
|
||||
}
|
||||
|
||||
// 正常值仍然放行,且链接 origin 可为空(退回抓取 origin)
|
||||
good := map[string]string{
|
||||
"DATABASE_URL": "postgres://example",
|
||||
"VERSION_HISTORY_GITEA_BASE_URL": "http://192.168.50.223:3000",
|
||||
"VERSION_HISTORY_LINK_ORIGIN": "https://gitea.example",
|
||||
}
|
||||
config, err := Load(func(key string) string { return good[key] })
|
||||
if err != nil {
|
||||
t.Fatalf("合法配置不该被拒:%v", err)
|
||||
}
|
||||
if config.VersionHistoryLinkOrigin != "https://gitea.example" || len(config.VersionHistoryAllowedOrigins) != 1 {
|
||||
t.Fatalf("配置解析不对:%+v", config)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,9 @@ const (
|
||||
ReasonNoBaseline = "no_baseline"
|
||||
// ReasonIncompleteGraph:提交图不完整(检出被截断)⇒ 提交数算不准 ⇒ 宁可不给号。
|
||||
ReasonIncompleteGraph = "shallow_or_incomplete_graph"
|
||||
// ReasonTagCreatedLater:该版本号对应的 tag 是在**更晚的提交**上打的(不在这个提交的历史里)
|
||||
// ⇒ 这个提交当时还没有发布基线,不能拿"后来才有的 tag"给它编号。
|
||||
ReasonTagCreatedLater = "release_tag_created_later"
|
||||
)
|
||||
|
||||
// versionHistorySemver 只认三段十进制、无前导零(与 scripts/check_changelog.py 同口径)。
|
||||
|
||||
@@ -117,6 +117,12 @@ func classifyRole(method, path string) string {
|
||||
if strings.Contains(path, "/settings/revisions") {
|
||||
return roleAdmin
|
||||
}
|
||||
// 「去掉来源」(归档下架 / 恢复)会把一个来源从目录、计划刷新与扫描里摘掉,
|
||||
// 并改变后续可见与可发布的来源集合:与改设置修订同级,写只能管理员。
|
||||
if strings.HasPrefix(path, "/api/v1/source-connections/") &&
|
||||
(strings.HasSuffix(path, "/archive") || strings.HasSuffix(path, "/restore")) {
|
||||
return roleAdmin
|
||||
}
|
||||
// The DingTalk scan session replaces the shared browser credentials:
|
||||
// admin-only, like every other credential surface. The QR image is a
|
||||
// login artifact, so even polling it stays admin-only. Space
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
@@ -137,8 +138,22 @@ func registerDingtalkSpace(w http.ResponseWriter, r *http.Request, config Config
|
||||
connectionID, err := store.RegisterDingtalkSpace(r.Context(), postgresstore.RegisterDingtalkSpaceInput{
|
||||
RootKey: resolved.Key, Name: resolved.Name, SpaceID: spaceID, RootID: resolved.Root, Now: config.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "space_registration_conflict"})
|
||||
switch {
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceNameTaken):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_name_conflict",
|
||||
"hint": "已有同名来源仍在使用(未下架):请先在该来源卡片上「去掉来源」,或确认选的是同一个知识库空间。",
|
||||
})
|
||||
return
|
||||
case errors.Is(err, postgresstore.ErrDingtalkSpaceIdentityConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "space_identity_conflict",
|
||||
"hint": "这个登记键已指向另一个知识库空间:请刷新列表后重试;若仍失败,把该来源「去掉来源」后再登记。",
|
||||
})
|
||||
return
|
||||
case err != nil:
|
||||
// 真正的数据库/内部故障不能伪装成"冲突":换个 500 才有人去查日志。
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "space_registration_failed"})
|
||||
return
|
||||
}
|
||||
// First scan is enqueued right away: the new connection has no catalog
|
||||
|
||||
@@ -3,10 +3,13 @@ package httpapi
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
func TestDingtalkSessionProxyRelaysSidecarStates(t *testing.T) {
|
||||
@@ -92,3 +95,62 @@ func TestDingtalkSessionUnavailableWithoutSidecar(t *testing.T) {
|
||||
t.Fatalf("sidecar down status = %d, want 503", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// 登记失败必须能被分类:同名来源仍在用 / 同键换空间 是两种不同的冲突,
|
||||
// 数据库内部故障不能伪装成"冲突"(否则线上只能看到一个无细节的 409)。
|
||||
type fakeDingtalkRegistrar struct {
|
||||
*fakeJobStore
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeDingtalkRegistrar) RegisterDingtalkSpace(ctx context.Context, in postgresstore.RegisterDingtalkSpaceInput) (string, error) {
|
||||
if f.err != nil {
|
||||
return "", f.err
|
||||
}
|
||||
return in.ConnectionID(), nil
|
||||
}
|
||||
|
||||
func TestDingtalkSpaceRegistrationErrorClassification(t *testing.T) {
|
||||
sidecar := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost && r.URL.Path == "/spaces/add" {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"key": "support-kb", "name": "公司级技术支持知识库", "root": "root-support"})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
defer sidecar.Close()
|
||||
t.Setenv("DINGTALK_LOGIN_SIDECAR_URL", sidecar.URL)
|
||||
|
||||
call := func(storeErr error) (int, string) {
|
||||
store := &fakeDingtalkRegistrar{fakeJobStore: &fakeJobStore{}, err: storeErr}
|
||||
handler, err := NewHandler(Config{Store: store})
|
||||
if err != nil {
|
||||
t.Fatalf("NewHandler() error = %v", err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/dingtalk-spaces", strings.NewReader(`{"url":"https://alidocs.dingtalk.com/i/spaces/9JOK9EEOMLMWX4Q"}`))
|
||||
request.Header.Set("X-Governance-Action", "dingtalk-space")
|
||||
request.Header.Set("Idempotency-Key", "op-dingtalk-register")
|
||||
request = request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "yaozhanghao", Role: roleAdmin}))
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, request)
|
||||
return recorder.Code, recorder.Body.String()
|
||||
}
|
||||
|
||||
status, body := call(postgresstore.ErrDingtalkSpaceNameTaken)
|
||||
if status != http.StatusConflict || !strings.Contains(body, "space_name_conflict") || !strings.Contains(body, "去掉来源") {
|
||||
t.Fatalf("同名冲突 = %d %s", status, body)
|
||||
}
|
||||
status, body = call(postgresstore.ErrDingtalkSpaceIdentityConflict)
|
||||
if status != http.StatusConflict || !strings.Contains(body, "space_identity_conflict") {
|
||||
t.Fatalf("同键冲突 = %d %s", status, body)
|
||||
}
|
||||
status, body = call(errors.New("connection refused: password=hunter2"))
|
||||
if status != http.StatusInternalServerError || !strings.Contains(body, "space_registration_failed") || strings.Contains(body, "hunter2") {
|
||||
t.Fatalf("内部故障 = %d %s(且不得回显细节)", status, body)
|
||||
}
|
||||
// 正常路径仍然成功(别把好的也拦掉)。
|
||||
status, body = call(nil)
|
||||
if status != http.StatusCreated || !strings.Contains(body, "connection_id") {
|
||||
t.Fatalf("正常登记 = %d %s", status, body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,6 +394,12 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("POST /api/v1/source-connections/{id}/settings/revisions/{revision_id}/activate", func(w http.ResponseWriter, r *http.Request) {
|
||||
activateSourceSettingsRevision(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/source-connections/{id}/archive", func(w http.ResponseWriter, r *http.Request) {
|
||||
archiveSourceConnection(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("POST /api/v1/source-connections/{id}/restore", func(w http.ResponseWriter, r *http.Request) {
|
||||
restoreSourceConnection(w, r, config)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/review-candidates", func(w http.ResponseWriter, r *http.Request) {
|
||||
listReviewCandidates(w, r, config.Store)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// 「去掉来源」= 归档下架(不是物理删除)。管理员专用、幂等。
|
||||
//
|
||||
// 归档后来源从数据源配置、来源与目录、计划刷新与手动扫描里全部消失,但目录快照、
|
||||
// 发布记录与审计数据原样保留 —— 恢复用 /restore,或让 dws 重新登记同一空间
|
||||
// (钉钉空间登记是确定性 id + ON CONFLICT,会原地复活同一行,不产生重复)。
|
||||
//
|
||||
// 为什么不给物理删除:source_items / source_catalog_snapshots / test_publications /
|
||||
// release_executions 都以 ON DELETE RESTRICT 引用来源连接。硬删要么失败,要么
|
||||
// 连带毁掉发布与审计记录。
|
||||
func archiveSourceConnection(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
mutateSourceConnectionArchive(w, r, config, true)
|
||||
}
|
||||
|
||||
func restoreSourceConnection(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
mutateSourceConnectionArchive(w, r, config, false)
|
||||
}
|
||||
|
||||
// sourceConnectionArchiver 是本路由需要的最小能力面:归档与恢复各一个写操作。
|
||||
type sourceConnectionArchiver interface {
|
||||
ArchiveSourceConnection(ctx context.Context, connectionID, actor string, now time.Time) error
|
||||
RestoreSourceConnection(ctx context.Context, connectionID, actor string, now time.Time) error
|
||||
}
|
||||
|
||||
func mutateSourceConnectionArchive(w http.ResponseWriter, r *http.Request, config Config, archive bool) {
|
||||
if _, ok := requireSessionIdentity(w, r); !ok {
|
||||
return
|
||||
}
|
||||
// 写意图与幂等键与其它来源设置写操作同规格:没有意图头就不写。
|
||||
wantIntent := "source-archive"
|
||||
if !archive {
|
||||
wantIntent = "source-restore"
|
||||
}
|
||||
if r.Header.Get("X-Governance-Action") != wantIntent {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "source archive write intent is required"})
|
||||
return
|
||||
}
|
||||
operationID, ok := requireOperationID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
connectionID := r.PathValue("id")
|
||||
if !validCatalogID(connectionID) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid source connection"})
|
||||
return
|
||||
}
|
||||
store, ok := config.Store.(sourceConnectionArchiver)
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "source archive is not wired"})
|
||||
return
|
||||
}
|
||||
var err error
|
||||
if archive {
|
||||
err = store.ArchiveSourceConnection(r.Context(), connectionID, actorFor(r), config.Now().UTC())
|
||||
} else {
|
||||
err = store.RestoreSourceConnection(r.Context(), connectionID, actorFor(r), config.Now().UTC())
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, postgres.ErrSourceConnectionNotFound):
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "source connection not found"})
|
||||
return
|
||||
case err != nil:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not change source archive state"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"id": connectionID, "archived": archive, "operation_id": operationID,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
// 复用既有 fakeJobStore 提供 Store 接口的其余方法;这里只关心归档两个写操作。
|
||||
type fakeSourceArchiver struct {
|
||||
*fakeJobStore
|
||||
archivedID string
|
||||
archivedActor string
|
||||
restoredID string
|
||||
restoredActor string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeSourceArchiver) ArchiveSourceConnection(ctx context.Context, connectionID, actor string, now time.Time) error {
|
||||
f.archivedID, f.archivedActor = connectionID, actor
|
||||
return f.err
|
||||
}
|
||||
|
||||
func (f *fakeSourceArchiver) RestoreSourceConnection(ctx context.Context, connectionID, actor string, now time.Time) error {
|
||||
f.restoredID, f.restoredActor = connectionID, actor
|
||||
return f.err
|
||||
}
|
||||
|
||||
func archiveRequest(t *testing.T, path, intent, key string) *http.Request {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(http.MethodPost, path, nil)
|
||||
if intent != "" {
|
||||
request.Header.Set("X-Governance-Action", intent)
|
||||
}
|
||||
if key != "" {
|
||||
request.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
return request.WithContext(context.WithValue(request.Context(), sessionKey{}, sessionIdentity{Username: "yaozhanghao", Role: roleAdmin}))
|
||||
}
|
||||
|
||||
func TestSourceConnectionArchiveHandler(t *testing.T) {
|
||||
store := &fakeSourceArchiver{fakeJobStore: &fakeJobStore{}}
|
||||
handler, err := NewHandler(Config{Store: store, Now: func() time.Time { return time.Date(2026, 10, 14, 4, 0, 0, 0, time.UTC) }})
|
||||
if err != nil {
|
||||
t.Fatalf("NewHandler() error = %v", err)
|
||||
}
|
||||
|
||||
// 写意图头缺失 ⇒ 拒绝(与其它来源设置写操作同规格)。
|
||||
noIntent := httptest.NewRecorder()
|
||||
handler.ServeHTTP(noIntent, archiveRequest(t, "/api/v1/source-connections/conn-1/archive", "", "op-1"))
|
||||
if noIntent.Code != http.StatusForbidden {
|
||||
t.Fatalf("intent gate = %d, want 403", noIntent.Code)
|
||||
}
|
||||
// 幂等键缺失 ⇒ 400(不允许"没键的重试")。
|
||||
noKey := httptest.NewRecorder()
|
||||
handler.ServeHTTP(noKey, archiveRequest(t, "/api/v1/source-connections/conn-1/archive", "source-archive", ""))
|
||||
if noKey.Code != http.StatusBadRequest {
|
||||
t.Fatalf("idempotency gate = %d, want 400", noKey.Code)
|
||||
}
|
||||
// 归档成功:把连接 ID 与操作人交给存储层。
|
||||
ok := httptest.NewRecorder()
|
||||
handler.ServeHTTP(ok, archiveRequest(t, "/api/v1/source-connections/conn-1/archive", "source-archive", "op-archive-1"))
|
||||
if ok.Code != http.StatusOK || store.archivedID != "conn-1" || store.archivedActor != "yaozhanghao" {
|
||||
t.Fatalf("archive = %d id=%s actor=%s body=%s", ok.Code, store.archivedID, store.archivedActor, ok.Body.String())
|
||||
}
|
||||
if !strings.Contains(ok.Body.String(), `"archived":true`) || strings.Contains(ok.Body.String(), "secret") {
|
||||
t.Fatalf("archive body = %s", ok.Body.String())
|
||||
}
|
||||
|
||||
// 恢复走另一条意图头。
|
||||
unknownIntent := httptest.NewRecorder()
|
||||
handler.ServeHTTP(unknownIntent, archiveRequest(t, "/api/v1/source-connections/conn-1/restore", "source-archive", "op-restore-1"))
|
||||
if unknownIntent.Code != http.StatusForbidden {
|
||||
t.Fatalf("restore intent gate = %d, want 403", unknownIntent.Code)
|
||||
}
|
||||
restored := httptest.NewRecorder()
|
||||
handler.ServeHTTP(restored, archiveRequest(t, "/api/v1/source-connections/conn-1/restore", "source-restore", "op-restore-1"))
|
||||
if restored.Code != http.StatusOK || store.restoredID != "conn-1" || store.restoredActor != "yaozhanghao" {
|
||||
t.Fatalf("restore = %d id=%s actor=%s", restored.Code, store.restoredID, store.restoredActor)
|
||||
}
|
||||
|
||||
// 未知连接 ⇒ 404(与"已经处于目标状态"区分开)。
|
||||
store.err = postgresstore.ErrSourceConnectionNotFound
|
||||
missing := httptest.NewRecorder()
|
||||
handler.ServeHTTP(missing, archiveRequest(t, "/api/v1/source-connections/conn-missing/archive", "source-archive", "op-2"))
|
||||
if missing.Code != http.StatusNotFound {
|
||||
t.Fatalf("unknown connection = %d, want 404", missing.Code)
|
||||
}
|
||||
|
||||
// 存储层故障 ⇒ 500,且不得回显内部细节。
|
||||
store.err = errors.New("boom: password=hunter2")
|
||||
failure := httptest.NewRecorder()
|
||||
handler.ServeHTTP(failure, archiveRequest(t, "/api/v1/source-connections/conn-1/archive", "source-archive", "op-3"))
|
||||
if failure.Code != http.StatusInternalServerError || strings.Contains(failure.Body.String(), "hunter2") {
|
||||
t.Fatalf("store failure = %d body=%s", failure.Code, failure.Body.String())
|
||||
}
|
||||
|
||||
// 非法 ID ⇒ 400(超长 ID;带路径分隔符的会被 mux 规范化,不在这里测)。
|
||||
badID := httptest.NewRecorder()
|
||||
handler.ServeHTTP(badID, archiveRequest(t, "/api/v1/source-connections/"+strings.Repeat("a", 300)+"/archive", "source-archive", "op-4"))
|
||||
if badID.Code != http.StatusBadRequest {
|
||||
t.Fatalf("invalid id = %d, want 400", badID.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// 「去掉来源」是管理员动作:工程号与只读号都不行。
|
||||
func TestSourceConnectionArchiveRolePolicy(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
method, path, want string
|
||||
}{
|
||||
{http.MethodPost, "/api/v1/source-connections/conn-1/archive", roleAdmin},
|
||||
{http.MethodPost, "/api/v1/source-connections/conn-1/restore", roleAdmin},
|
||||
{http.MethodGet, "/api/v1/source-connections", roleViewer},
|
||||
{http.MethodPost, "/api/v1/source-connections/conn-1/scan", roleEngineer},
|
||||
} {
|
||||
if got := classifyRole(tt.method, tt.path); got != tt.want {
|
||||
t.Fatalf("classifyRole(%s %s) = %s, want %s", tt.method, tt.path, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,14 @@ import (
|
||||
// begin only after an admin sets an interval — same posture as the existing
|
||||
// imported DingTalk sources.
|
||||
|
||||
// 登记失败的可行动分类(处理器据此返回不同错误码,前端才能说清"该怎么办"):
|
||||
// - 同名来源**仍在使用**(未归档):不能悄悄改名,也不能出现两个同名来源;
|
||||
// - 同一个登记键已指向另一个 root,而那个来源仍在使用。
|
||||
var (
|
||||
ErrDingtalkSpaceNameTaken = errors.New("dingtalk space name is already used by a live connection")
|
||||
ErrDingtalkSpaceIdentityConflict = errors.New("dingtalk space registration: live connection already serves another root")
|
||||
)
|
||||
|
||||
// RegisterDingtalkSpaceInput describes one space resolved by the sidecar.
|
||||
type RegisterDingtalkSpaceInput struct {
|
||||
RootKey string // sidecar inventory key, e.g. "atom" or "space-1f2e3d4c5b"
|
||||
@@ -56,17 +64,42 @@ func (s *Store) RegisterDingtalkSpace(ctx context.Context, in RegisterDingtalkSp
|
||||
}
|
||||
connectionID := in.ConnectionID()
|
||||
var existingName, existingRoot string
|
||||
err := s.db.QueryRow(ctx, `SELECT name, base_url FROM source_connections WHERE id = $1`, connectionID).Scan(&existingName, &existingRoot)
|
||||
var existingArchived bool
|
||||
err := s.db.QueryRow(ctx, `SELECT name, base_url, archived_at IS NOT NULL FROM source_connections WHERE id = $1`, connectionID).
|
||||
Scan(&existingName, &existingRoot, &existingArchived)
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
// fresh registration below
|
||||
case err != nil:
|
||||
return "", fmt.Errorf("load dingtalk connection: %w", err)
|
||||
default:
|
||||
// A different space resolved under the same key must not silently
|
||||
// rewrite the existing connection.
|
||||
if !strings.HasPrefix(existingRoot, "spaces/"+in.RootID+"?") {
|
||||
return "", fmt.Errorf("dingtalk space registration: connection %s already serves another root", connectionID)
|
||||
// 同一个键解析到了另一个 root:**在用中**的行不能悄悄改写(可能是两个不同空间
|
||||
// 撞了同一个键);已经归档的行可以就地改写 —— 这正是"去掉来源之后再用 dws
|
||||
// 重新获取"的语义。
|
||||
if !strings.HasPrefix(existingRoot, "spaces/"+in.RootID+"?") && !existingArchived {
|
||||
return "", ErrDingtalkSpaceIdentityConflict
|
||||
}
|
||||
}
|
||||
// 名字有 UNIQUE 约束,而**旧路径登记**的来源(例如早期直接建的钉钉知识库连接,
|
||||
// base_url 为空、id 与 dws 现在推导出的确定性 id 不同)会一直占着这个名字。
|
||||
// 归档行已经不显示在任何页面,就把它改名腾出位置(数据与审计一行不动);
|
||||
// 仍在使用的同名来源则直接报可行动错误,绝不悄悄改名。
|
||||
var nameHolderID string
|
||||
var nameHolderArchived bool
|
||||
err = s.db.QueryRow(ctx, `SELECT id, archived_at IS NOT NULL FROM source_connections WHERE name = $1 AND id <> $2`, in.Name, connectionID).
|
||||
Scan(&nameHolderID, &nameHolderArchived)
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
case err != nil:
|
||||
return "", fmt.Errorf("lookup dingtalk connection name: %w", err)
|
||||
default:
|
||||
if !nameHolderArchived {
|
||||
return "", ErrDingtalkSpaceNameTaken
|
||||
}
|
||||
if _, err := s.db.Exec(ctx, `
|
||||
UPDATE source_connections SET name = $2, updated_at = $3, updated_by = $4 WHERE id = $1`,
|
||||
nameHolderID, archivedConnectionName(in.Name, nameHolderID), in.Now.UTC(), "dingtalk-registration"); err != nil {
|
||||
return "", fmt.Errorf("free archived dingtalk name: %w", err)
|
||||
}
|
||||
}
|
||||
// base_url stores a stable, non-secret locator (the root dentry uuid plus
|
||||
@@ -80,6 +113,9 @@ INSERT INTO source_connections (
|
||||
) VALUES ($1, 'dingtalk', $2, $3, '', TRUE, '{}'::jsonb, '{}'::jsonb, $4, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET name = EXCLUDED.name, base_url = EXCLUDED.base_url,
|
||||
-- 归档过的来源被重新登记(dws 重新获取)时原地复活:清掉归档标记,不建重复行 ——
|
||||
-- 目录快照与历史仍属于同一行。
|
||||
archived_at = NULL, archived_by = '',
|
||||
updated_at = EXCLUDED.updated_at, updated_by = EXCLUDED.updated_by`,
|
||||
connectionID, in.Name, locator, in.Now.UTC(), "dingtalk-registration")
|
||||
if err != nil {
|
||||
@@ -90,3 +126,25 @@ SET name = EXCLUDED.name, base_url = EXCLUDED.base_url,
|
||||
}
|
||||
return connectionID, nil
|
||||
}
|
||||
|
||||
// archivedConnectionName 给"已归档但名字仍占着唯一槽位"的行一个确定性新名字:
|
||||
// 内建短 ID 后缀保证唯一,并按 name 列(255)截断原名。
|
||||
func archivedConnectionName(name, connectionID string) string {
|
||||
suffix := "(已下架 · " + shortConnectionIDSuffix(connectionID) + ")"
|
||||
runes := []rune(name)
|
||||
if limit := 255 - len([]rune(suffix)); len(runes) > limit && limit > 0 {
|
||||
runes = runes[:limit]
|
||||
}
|
||||
return string(runes) + suffix
|
||||
}
|
||||
|
||||
func shortConnectionIDSuffix(connectionID string) string {
|
||||
trimmed := strings.TrimPrefix(connectionID, "sc-")
|
||||
if len(trimmed) > 8 {
|
||||
trimmed = trimmed[:8]
|
||||
}
|
||||
if trimmed == "" {
|
||||
trimmed = "unknown"
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
DROP INDEX IF EXISTS idx_source_connections_active;
|
||||
|
||||
ALTER TABLE source_connections
|
||||
DROP COLUMN IF EXISTS archived_by;
|
||||
|
||||
ALTER TABLE source_connections
|
||||
DROP COLUMN IF EXISTS archived_at;
|
||||
@@ -0,0 +1,20 @@
|
||||
-- 「去掉来源」= 归档下架,而不是物理删除。
|
||||
--
|
||||
-- 归档后这个来源会从所有列表与调度里消失:数据源配置不再列它、来源与目录不再出现
|
||||
-- 它的快照、计划刷新不会再拉它、手动扫描会被拒。目录快照、发布记录与审计数据
|
||||
-- **原样保留**;恢复只需把 archived_at 置空,或让 dws 重新获取同一个空间
|
||||
-- (钉钉空间登记用确定性 id + ON CONFLICT,会原地复活同一行,不会产生重复)。
|
||||
--
|
||||
-- 为什么不物理删除:source_items / source_catalog_snapshots / test_publications /
|
||||
-- release_* 都以 ON DELETE RESTRICT 引用它,硬删要么失败,要么连带毁掉发布与审计
|
||||
-- 记录 —— 而这两样正是治理平台存在的理由。
|
||||
ALTER TABLE source_connections
|
||||
ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;
|
||||
|
||||
ALTER TABLE source_connections
|
||||
ADD COLUMN IF NOT EXISTS archived_by VARCHAR(255) NOT NULL DEFAULT '';
|
||||
|
||||
-- 列表、调度、目录都只关心未归档的行:部分索引让这些查询继续走索引。
|
||||
CREATE INDEX IF NOT EXISTS idx_source_connections_active
|
||||
ON source_connections (source_type, name)
|
||||
WHERE archived_at IS NULL;
|
||||
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 46 {
|
||||
t.Fatalf("migration count = %d, want 46", len(migrations))
|
||||
if len(migrations) != 47 {
|
||||
t.Fatalf("migration count = %d, want 47", len(migrations))
|
||||
}
|
||||
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
|
||||
t.Fatalf("migration 1 = %#v", migrations[0])
|
||||
@@ -125,6 +125,27 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if !strings.Contains(migrations[45].DownSQL, "DROP TABLE IF EXISTS version_history_commits") {
|
||||
t.Fatalf("migration 46 down = %#v", migrations[45].DownSQL)
|
||||
}
|
||||
// 000047:「去掉来源」= 归档下架而不是物理删除(内容、发布与审计都靠 ON DELETE
|
||||
// RESTRICT 引用来源连接,硬删要么失败要么毁证据)。归档标记 + 只覆盖未归档行的部分索引。
|
||||
if migrations[46].Version != 47 || !strings.Contains(migrations[46].UpSQL, "ADD COLUMN IF NOT EXISTS archived_at") ||
|
||||
!strings.Contains(migrations[46].UpSQL, "ADD COLUMN IF NOT EXISTS archived_by") ||
|
||||
!strings.Contains(migrations[46].UpSQL, "WHERE archived_at IS NULL") {
|
||||
t.Fatalf("migration 47 = %#v", migrations[46])
|
||||
}
|
||||
if !strings.Contains(migrations[46].DownSQL, "DROP COLUMN IF EXISTS archived_at") {
|
||||
t.Fatalf("migration 47 down = %#v", migrations[46].DownSQL)
|
||||
}
|
||||
// 归档行必须在每一条「来源可见 / 可调度」的 SQL 里被排除;漏一条就等于入口没去掉。
|
||||
for name, query := range map[string]string{
|
||||
"listSourceConnectionsSQL": listSourceConnectionsSQL,
|
||||
"claimDueSourceRefreshesSQL": claimDueSourceRefreshesSQL,
|
||||
"triggerPPSourceScanSQL": triggerPPSourceScanSQL,
|
||||
"inspectPPSourceScanBlockSQL": inspectPPSourceScanBlockSQL,
|
||||
} {
|
||||
if !strings.Contains(strings.ToLower(query), "archived_at is null") {
|
||||
t.Errorf("%s must exclude archived connections", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessingConfirmationMigrationSeparatesPlanningFromUpload(t *testing.T) {
|
||||
|
||||
@@ -35,7 +35,7 @@ JOIN LATERAL (
|
||||
LIMIT 1
|
||||
) job ON TRUE
|
||||
LEFT JOIN source_catalog_heads head ON head.source_connection_id=connection.id
|
||||
WHERE connection.enabled AND head.source_connection_id IS NULL
|
||||
WHERE connection.enabled AND connection.archived_at IS NULL AND head.source_connection_id IS NULL
|
||||
ORDER BY job.created_at DESC, connection.id`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list catalog scan progress: %w", err)
|
||||
@@ -90,6 +90,7 @@ LEFT JOIN LATERAL (
|
||||
ORDER BY job.completed_at DESC
|
||||
LIMIT 1
|
||||
) refresh ON TRUE
|
||||
WHERE connection.archived_at IS NULL
|
||||
ORDER BY CASE connection.source_type WHEN 'dingtalk' THEN 1 WHEN 'pp' THEN 2 WHEN 'alist' THEN 3 ELSE 4 END,
|
||||
snapshot.source_label, connection.id`)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// 「去掉来源」的语义护栏:归档之后来源从列表里消失、不能再被手动扫描,
|
||||
// 但**内容与审计数据一行都不少**;恢复/重新登记都能原地复活,且不产生重复行。
|
||||
// 这些性质就是"可以不物理删除"的全部理由,所以逐条钉死。
|
||||
func TestSourceConnectionArchiveHidesFromListsAndKeepsData(t *testing.T) {
|
||||
databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if databaseURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatalf("ApplyMigrations() error = %v", err)
|
||||
}
|
||||
store := NewStore(pool)
|
||||
now := time.Date(2026, 10, 14, 4, 0, 0, 0, time.UTC)
|
||||
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO source_connections (id, source_type, name, enabled, created_at, updated_at)
|
||||
VALUES ('conn-keep-pp', 'pp', 'PP资料下载中心', TRUE, $1, $1),
|
||||
('conn-drop-alist', 'alist', '国内工业', TRUE, $1, $1),
|
||||
('conn-drop-pp', 'pp', 'PP legacy', TRUE, $1, $1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO source_items (id, source_connection_id, stable_external_id, canonical_uri_hash,
|
||||
title, item_type, visibility, visibility_origin, source_change, created_at, updated_at)
|
||||
VALUES ('item-drop-1', 'conn-drop-alist', 'ext-1', repeat('a', 64), '要被归档的文档',
|
||||
'file', 'internal', 'configured_scope', 'unchanged', $1, $1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
page, err := store.ListSourceConnections(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSourceConnections() error = %v", err)
|
||||
}
|
||||
if len(page.Items) != 3 {
|
||||
t.Fatalf("前置状态:want 3 sources, got %d", len(page.Items))
|
||||
}
|
||||
|
||||
if err := store.ArchiveSourceConnection(ctx, "conn-drop-alist", "yaozhanghao", now); err != nil {
|
||||
t.Fatalf("ArchiveSourceConnection() error = %v", err)
|
||||
}
|
||||
page, err = store.ListSourceConnections(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 2 {
|
||||
t.Fatalf("归档后仍列出:%#v", page.Items)
|
||||
}
|
||||
for _, item := range page.Items {
|
||||
if item.ID == "conn-drop-alist" {
|
||||
t.Fatalf("归档的来源不该出现在列表里:%#v", item)
|
||||
}
|
||||
}
|
||||
// 内容数据必须原样保留:这是"归档而不是删除"的核心承诺。
|
||||
var keptItems int
|
||||
var archivedAt *time.Time
|
||||
var archivedBy string
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*)::int FROM source_items WHERE source_connection_id='conn-drop-alist'`).Scan(&keptItems); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if keptItems != 1 {
|
||||
t.Fatalf("归档不该动内容数据:source_items=%d, want 1", keptItems)
|
||||
}
|
||||
if err := pool.QueryRow(ctx, `SELECT archived_at, archived_by FROM source_connections WHERE id='conn-drop-alist'`).Scan(&archivedAt, &archivedBy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if archivedAt == nil || !archivedAt.Equal(now) || archivedBy != "yaozhanghao" {
|
||||
t.Fatalf("归档证据 = %v / %q", archivedAt, archivedBy)
|
||||
}
|
||||
|
||||
// 幂等:重复归档不改归档时间与归档人(谁先归档就以谁为准)。
|
||||
if err := store.ArchiveSourceConnection(ctx, "conn-drop-alist", "someone-else", now.Add(time.Hour)); err != nil {
|
||||
t.Fatalf("重复归档该幂等成功:%v", err)
|
||||
}
|
||||
var again *time.Time
|
||||
var againBy string
|
||||
if err := pool.QueryRow(ctx, `SELECT archived_at, archived_by FROM source_connections WHERE id='conn-drop-alist'`).Scan(&again, &againBy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if again == nil || !again.Equal(now) || againBy != "yaozhanghao" {
|
||||
t.Fatalf("重复归档漂移了归档证据 = %v / %q", again, againBy)
|
||||
}
|
||||
|
||||
// 未知连接要能和"已经是目标状态"区分开。
|
||||
if err := store.ArchiveSourceConnection(ctx, "conn-missing", "yaozhanghao", now); !errors.Is(err, ErrSourceConnectionNotFound) {
|
||||
t.Fatalf("未知连接归档 = %v, want ErrSourceConnectionNotFound", err)
|
||||
}
|
||||
if err := store.RestoreSourceConnection(ctx, "conn-missing", "yaozhanghao", now); !errors.Is(err, ErrSourceConnectionNotFound) {
|
||||
t.Fatalf("未知连接恢复 = %v, want ErrSourceConnectionNotFound", err)
|
||||
}
|
||||
|
||||
// 归档来源不能再被手动扫描(否则"去掉入口"只是界面假象)。
|
||||
if _, err := store.TriggerPPSourceScan(ctx, "conn-drop-alist", now); !errors.Is(err, ErrSourceConnectionNotScannable) {
|
||||
t.Fatalf("归档来源扫描 = %v, want ErrSourceConnectionNotScannable", err)
|
||||
}
|
||||
if err := store.ArchiveSourceConnection(ctx, "conn-drop-pp", "yaozhanghao", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.TriggerPPSourceScan(ctx, "conn-drop-pp", now); !errors.Is(err, ErrSourceConnectionNotScannable) {
|
||||
t.Fatalf("归档的 PP 来源扫描 = %v, want ErrSourceConnectionNotScannable", err)
|
||||
}
|
||||
|
||||
// 恢复:回到列表,但保持停用、调度为空 —— 归档时清掉的调度不悄悄回来。
|
||||
if err := store.RestoreSourceConnection(ctx, "conn-drop-alist", "yaozhanghao", now); err != nil {
|
||||
t.Fatalf("RestoreSourceConnection() error = %v", err)
|
||||
}
|
||||
page, err = store.ListSourceConnections(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// conn-drop-pp 仍然归档中,只有 conn-drop-alist 回来了:2 = 3 - 仍归档的 1。
|
||||
if len(page.Items) != 2 {
|
||||
t.Fatalf("恢复后 want 2 sources, got %d", len(page.Items))
|
||||
}
|
||||
var restoredSeen bool
|
||||
for _, item := range page.Items {
|
||||
if item.ID == "conn-drop-pp" {
|
||||
t.Fatalf("仍在归档中的来源不该出现:%#v", item)
|
||||
}
|
||||
if item.ID == "conn-drop-alist" {
|
||||
restoredSeen = true
|
||||
}
|
||||
}
|
||||
if !restoredSeen {
|
||||
t.Fatalf("恢复的来源没有回到列表:%#v", page.Items)
|
||||
}
|
||||
var enabled bool
|
||||
var nextRefresh *time.Time
|
||||
var restoredArchived *time.Time
|
||||
if err := pool.QueryRow(ctx, `SELECT enabled, next_refresh_at, archived_at FROM source_connections WHERE id='conn-drop-alist'`).
|
||||
Scan(&enabled, &nextRefresh, &restoredArchived); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if enabled || nextRefresh != nil || restoredArchived != nil {
|
||||
t.Fatalf("恢复状态 = enabled:%v next:%v archived:%v", enabled, nextRefresh, restoredArchived)
|
||||
}
|
||||
// 未归档时恢复幂等成功(不是错误)。
|
||||
if err := store.RestoreSourceConnection(ctx, "conn-drop-alist", "yaozhanghao", now); err != nil {
|
||||
t.Fatalf("重复恢复该幂等成功:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 「等下用 dws 重新获取」必须原地复活同一个来源,而不是留下一堆重复行:
|
||||
// 钉钉空间登记用确定性 id + ON CONFLICT,归档标记要在登记时被清掉。
|
||||
func TestRegisterDingtalkSpaceRevivesArchivedConnection(t *testing.T) {
|
||||
databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if databaseURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatalf("ApplyMigrations() error = %v", err)
|
||||
}
|
||||
store := NewStore(pool)
|
||||
now := time.Date(2026, 10, 14, 4, 0, 0, 0, time.UTC)
|
||||
input := RegisterDingtalkSpaceInput{
|
||||
RootKey: "revive-key", Name: "ATOM知识库", SpaceID: "space-revive", RootID: "root-revive", Now: now,
|
||||
}
|
||||
|
||||
first, err := store.RegisterDingtalkSpace(ctx, input)
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterDingtalkSpace() error = %v", err)
|
||||
}
|
||||
if err := store.ArchiveSourceConnection(ctx, first, "yaozhanghao", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, err := store.ListSourceConnections(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 0 {
|
||||
t.Fatalf("归档后不该列出:%#v", page.Items)
|
||||
}
|
||||
|
||||
second, err := store.RegisterDingtalkSpace(ctx, input)
|
||||
if err != nil {
|
||||
t.Fatalf("重新登记失败:%v", err)
|
||||
}
|
||||
if second != first {
|
||||
t.Fatalf("重新登记产生了新行:%s → %s", first, second)
|
||||
}
|
||||
page, err = store.ListSourceConnections(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 1 || page.Items[0].ID != first {
|
||||
t.Fatalf("重新获取后应当原地复活且不重复:%#v", page.Items)
|
||||
}
|
||||
var archivedAt *time.Time
|
||||
var archivedBy string
|
||||
var rows int
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*)::int FROM source_connections WHERE id = $1`, first).Scan(&rows); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := pool.QueryRow(ctx, `SELECT archived_at, archived_by FROM source_connections WHERE id = $1`, first).Scan(&archivedAt, &archivedBy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rows != 1 || archivedAt != nil || archivedBy != "" {
|
||||
t.Fatalf("复活状态 = rows:%d archived:%v by:%q", rows, archivedAt, archivedBy)
|
||||
}
|
||||
}
|
||||
|
||||
// 场景复刻(2026-10-14 线上 409 事故):早期路径登记的同名来源被归档后仍占着
|
||||
// UNIQUE(name) 槽位,而它的 id 与 dws 现在推导出的确定性 id 不同 ⇒ 重新登记撞唯一约束。
|
||||
// 期望:归档行被改名腾位(数据与审计不动),新来源按新 id 正常登记。
|
||||
func TestRegisterDingtalkSpaceFreesNameHeldByArchivedLegacyConnection(t *testing.T) {
|
||||
databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
|
||||
if databaseURL == "" {
|
||||
t.Skip("TEST_DATABASE_URL is not set")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, databaseURL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatalf("ApplyMigrations() error = %v", err)
|
||||
}
|
||||
store := NewStore(pool)
|
||||
now := time.Date(2026, 10, 14, 5, 0, 0, 0, time.UTC)
|
||||
|
||||
// 旧路径登记的来源:id 与 dws 推导不同、base_url 为空、已归档、名字仍占槽位。
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO source_connections (id, source_type, name, base_url, enabled, archived_at, archived_by, created_at, updated_at)
|
||||
VALUES ('sc-18d10ca094c6071d44a32e531359e3b2', 'dingtalk', '公司级技术支持知识库', '', FALSE, $1, 'yaozhanghao', $1, $1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO source_items (id, source_connection_id, stable_external_id, canonical_uri_hash,
|
||||
title, item_type, visibility, visibility_origin, source_change, created_at, updated_at)
|
||||
VALUES ('item-legacy', 'sc-18d10ca094c6071d44a32e531359e3b2', 'ext-legacy', repeat('b', 64), '旧行留下的文档',
|
||||
'file', 'internal', 'configured_scope', 'unchanged', $1, $1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
input := RegisterDingtalkSpaceInput{
|
||||
RootKey: "support-kb", Name: "公司级技术支持知识库", SpaceID: "space-support", RootID: "root-support", Now: now,
|
||||
}
|
||||
connectionID, err := store.RegisterDingtalkSpace(ctx, input)
|
||||
if err != nil {
|
||||
t.Fatalf("登记被旧归档行挡住:%v", err)
|
||||
}
|
||||
if connectionID == "sc-18d10ca094c6071d44a32e531359e3b2" {
|
||||
t.Fatalf("不该复用没有身份证据的旧行:%s", connectionID)
|
||||
}
|
||||
page, err := store.ListSourceConnections(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) != 1 || page.Items[0].ID != connectionID || page.Items[0].Name != "公司级技术支持知识库" {
|
||||
t.Fatalf("列表 = %#v", page.Items)
|
||||
}
|
||||
// 旧行:改名腾位、保持归档、内容一行不丢。
|
||||
var legacyName string
|
||||
var legacyArchivedAt *time.Time
|
||||
var legacyItems int
|
||||
if err := pool.QueryRow(ctx, `SELECT name, archived_at, (SELECT COUNT(*)::int FROM source_items WHERE source_connection_id = 'sc-18d10ca094c6071d44a32e531359e3b2') FROM source_connections WHERE id = 'sc-18d10ca094c6071d44a32e531359e3b2'`).
|
||||
Scan(&legacyName, &legacyArchivedAt, &legacyItems); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if legacyName == "公司级技术支持知识库" || !strings.Contains(legacyName, "(已下架 · 18d10ca0)") {
|
||||
t.Fatalf("旧归档行没有被改名腾位:%q", legacyName)
|
||||
}
|
||||
if legacyArchivedAt == nil || legacyItems != 1 {
|
||||
t.Fatalf("旧归档行被破坏:archived=%v items=%d", legacyArchivedAt, legacyItems)
|
||||
}
|
||||
|
||||
// 同名来源仍在使用(未归档)时:拒绝并给出可行动错误,且不写任何东西。
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO source_connections (id, source_type, name, enabled, created_at, updated_at)
|
||||
VALUES ('sc-live-other', 'dingtalk', '在用中的同名来源', TRUE, $1, $1)`, now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = store.RegisterDingtalkSpace(ctx, RegisterDingtalkSpaceInput{
|
||||
RootKey: "other-key", Name: "在用中的同名来源", SpaceID: "space-other", RootID: "root-other", Now: now,
|
||||
})
|
||||
if !errors.Is(err, ErrDingtalkSpaceNameTaken) {
|
||||
t.Fatalf("同名在用来源 = %v, want ErrDingtalkSpaceNameTaken", err)
|
||||
}
|
||||
|
||||
// 同一个登记键解析到另一个 root:在用中 ⇒ 拒绝;已归档 ⇒ 就地改写。
|
||||
held := RegisterDingtalkSpaceInput{RootKey: "held-key", Name: "同键来源", SpaceID: "space-a", RootID: "root-a", Now: now}
|
||||
heldID, err := store.RegisterDingtalkSpace(ctx, held)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = store.RegisterDingtalkSpace(ctx, RegisterDingtalkSpaceInput{
|
||||
RootKey: "held-key", Name: "同键来源", SpaceID: "space-b", RootID: "root-b", Now: now,
|
||||
})
|
||||
if !errors.Is(err, ErrDingtalkSpaceIdentityConflict) {
|
||||
t.Fatalf("同键换 root(在用)= %v, want ErrDingtalkSpaceIdentityConflict", err)
|
||||
}
|
||||
if err := store.ArchiveSourceConnection(ctx, heldID, "yaozhanghao", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.RegisterDingtalkSpace(ctx, RegisterDingtalkSpaceInput{
|
||||
RootKey: "held-key", Name: "同键来源", SpaceID: "space-b", RootID: "root-b", Now: now,
|
||||
}); err != nil {
|
||||
t.Fatalf("归档后同键换 root 应就地改写:%v", err)
|
||||
}
|
||||
var rootAfter string
|
||||
if err := pool.QueryRow(ctx, `SELECT base_url FROM source_connections WHERE id = $1`, heldID).Scan(&rootAfter); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(rootAfter, "spaces/root-b?") {
|
||||
t.Fatalf("归档行没有被就地改写:%q", rootAfter)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
@@ -47,6 +48,7 @@ LEFT JOIN LATERAL (
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1
|
||||
) scan ON TRUE
|
||||
WHERE c.archived_at IS NULL
|
||||
GROUP BY c.id, c.source_type, c.name, c.enabled, c.schedule, c.last_health, c.updated_at, c.next_refresh_at,
|
||||
scan.id, scan.state, scan.observed_items, scan.unchanged_items,
|
||||
scan.added_items, scan.updated_items, scan.over_limit_items,
|
||||
@@ -158,7 +160,7 @@ WITH due AS (
|
||||
FROM source_connections AS c
|
||||
LEFT JOIN source_connection_revisions AS r
|
||||
ON r.id = c.current_revision_id AND r.state = 'active'
|
||||
WHERE c.enabled AND c.source_type <> 'manual'
|
||||
WHERE c.enabled AND c.source_type <> 'manual' AND c.archived_at IS NULL
|
||||
AND c.next_refresh_at IS NOT NULL AND c.next_refresh_at <= $1
|
||||
ORDER BY c.next_refresh_at, c.id
|
||||
FOR UPDATE OF c SKIP LOCKED
|
||||
@@ -225,3 +227,64 @@ func NextRefreshAtFor(enabled bool, scheduleRaw []byte, from time.Time) (*time.T
|
||||
next := from.UTC().Add(interval)
|
||||
return &next, nil
|
||||
}
|
||||
|
||||
// ArchiveSourceConnection 把来源连接从平台上「去掉入口」:置 archived_at 之后它会
|
||||
// 从数据源配置、来源与目录、计划刷新与扫描里全部消失,但行、目录快照、发布记录与
|
||||
// 审计原样保留 —— 恢复(RestoreSourceConnection 或重新登记同一来源)即可原地复活。
|
||||
//
|
||||
// 幂等:已归档时不改写归档时间与归档人,只返回成功(重复点击不漂移语义)。同时停用并
|
||||
// 清空 next_refresh_at:即使有人手工把 archived_at 改回来,也不会带着旧调度立刻跑起来。
|
||||
func (s *Store) ArchiveSourceConnection(ctx context.Context, connectionID, actor string, now time.Time) error {
|
||||
if strings.TrimSpace(connectionID) == "" || now.IsZero() {
|
||||
return errors.New("archive source connection: id and time are required")
|
||||
}
|
||||
if strings.TrimSpace(actor) == "" {
|
||||
return errors.New("archive source connection: actor is required")
|
||||
}
|
||||
tag, err := s.db.Exec(ctx, `
|
||||
UPDATE source_connections
|
||||
SET archived_at = COALESCE(archived_at, $2),
|
||||
archived_by = CASE WHEN archived_at IS NULL THEN $3 ELSE archived_by END,
|
||||
enabled = FALSE,
|
||||
next_refresh_at = NULL,
|
||||
updated_at = $2,
|
||||
updated_by = $3
|
||||
WHERE id = $1`, connectionID, now.UTC(), actor)
|
||||
if err != nil {
|
||||
return fmt.Errorf("archive source connection: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrSourceConnectionNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RestoreSourceConnection 撤销归档:来源重新出现在列表里,但**保持停用**,需要管理员
|
||||
// 再显式启用(归档时被清掉的调度不会悄悄回来)。幂等:未归档时视为成功;只有连接真的
|
||||
// 不存在才报 ErrSourceConnectionNotFound。
|
||||
func (s *Store) RestoreSourceConnection(ctx context.Context, connectionID, actor string, now time.Time) error {
|
||||
if strings.TrimSpace(connectionID) == "" || now.IsZero() {
|
||||
return errors.New("restore source connection: id and time are required")
|
||||
}
|
||||
if strings.TrimSpace(actor) == "" {
|
||||
return errors.New("restore source connection: actor is required")
|
||||
}
|
||||
tag, err := s.db.Exec(ctx, `
|
||||
UPDATE source_connections
|
||||
SET archived_at = NULL, archived_by = '', updated_at = $2, updated_by = $3
|
||||
WHERE id = $1 AND archived_at IS NOT NULL`, connectionID, now.UTC(), actor)
|
||||
if err != nil {
|
||||
return fmt.Errorf("restore source connection: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() > 0 {
|
||||
return nil
|
||||
}
|
||||
var exists bool
|
||||
if err := s.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM source_connections WHERE id = $1)`, connectionID).Scan(&exists); err != nil {
|
||||
return fmt.Errorf("restore source connection: %w", err)
|
||||
}
|
||||
if !exists {
|
||||
return ErrSourceConnectionNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ const triggerPPSourceScanSQL = `
|
||||
WITH target AS (
|
||||
SELECT id, source_type
|
||||
FROM source_connections
|
||||
WHERE id = $1 AND source_type = 'pp'
|
||||
WHERE id = $1 AND source_type = 'pp' AND archived_at IS NULL
|
||||
), active AS (
|
||||
SELECT 1
|
||||
FROM source_scans
|
||||
@@ -65,7 +65,7 @@ SELECT connection.source_type,
|
||||
AND scan.state IN ('pending', 'running')
|
||||
)
|
||||
FROM source_connections AS connection
|
||||
WHERE connection.id = $1
|
||||
WHERE connection.id = $1 AND connection.archived_at IS NULL
|
||||
`
|
||||
|
||||
const startSourceScanSQL = `
|
||||
|
||||
@@ -15,8 +15,12 @@ import (
|
||||
// GiteaConfig 是只读客户端的配置。**只用匿名请求**:本客户端不会携带任何凭据,
|
||||
// 也不接受调用方传入任意 URL —— base 必须在白名单里,仓库只允许配置的那一个。
|
||||
type GiteaConfig struct {
|
||||
BaseURL string
|
||||
AllowedBaseURLs []string
|
||||
BaseURL string
|
||||
AllowedBaseURLs []string
|
||||
// LinkOrigin 是**给人看的链接**用的 origin(例如公网 https://gitea.example)。
|
||||
// 抓取用内网地址、点链接的人在内网外 —— 两者必须能分开,否则页面上的链接打不开。
|
||||
// 留空则与 BaseURL 相同。它只用于拼展示链接,不参与任何请求。
|
||||
LinkOrigin string
|
||||
Repo string
|
||||
HTTPClient *http.Client
|
||||
Timeout time.Duration
|
||||
@@ -29,6 +33,7 @@ type GiteaConfig struct {
|
||||
// GiteaClient 只读地访问 Gitea 的提交、tag 与仓库内文件。
|
||||
type GiteaClient struct {
|
||||
baseURL *url.URL
|
||||
linkOrigin string
|
||||
repo string
|
||||
client *http.Client
|
||||
maxBytes int64
|
||||
@@ -98,16 +103,29 @@ func NewGiteaClient(config GiteaConfig) (*GiteaClient, error) {
|
||||
if sleep == nil {
|
||||
sleep = time.Sleep
|
||||
}
|
||||
return &GiteaClient{baseURL: base, repo: repo, client: &sameHost, maxBytes: maxBytes,
|
||||
maxRetries: retries, sleep: sleep, pageSize: pageSize}, nil
|
||||
linkOrigin := strings.TrimRight(strings.TrimSpace(config.LinkOrigin), "/")
|
||||
if linkOrigin == "" {
|
||||
linkOrigin = strings.TrimRight(base.String(), "/")
|
||||
} else if parsed, perr := url.Parse(linkOrigin); perr != nil || parsed.Host == "" ||
|
||||
(parsed.Scheme != "http" && parsed.Scheme != "https") {
|
||||
return nil, fmt.Errorf("版本记录:链接 origin %q 非法(必须是 http(s) 绝对地址)", config.LinkOrigin)
|
||||
}
|
||||
return &GiteaClient{baseURL: base, linkOrigin: linkOrigin, repo: repo, client: &sameHost,
|
||||
maxBytes: maxBytes, maxRetries: retries, sleep: sleep, pageSize: pageSize}, nil
|
||||
}
|
||||
|
||||
// PageSize 是抓取页大小(外层据此做完整性对账)。
|
||||
func (c *GiteaClient) PageSize() int { return c.pageSize }
|
||||
|
||||
// CommitURLBase 给记录页拼提交链接用(白名单 origin + 固定仓库,不接受外部传入)。
|
||||
// CommitURLBase 给记录页拼提交链接用(**给人看的** origin + 固定仓库,不接受外部传入)。
|
||||
// 抓取走内网、链接走公网 —— 两者分开,页面上的链接才点得开。
|
||||
func (c *GiteaClient) CommitURLBase() string {
|
||||
return strings.TrimRight(c.baseURL.String(), "/") + "/" + c.repo + giteaCommitURLSuffix
|
||||
return c.linkOrigin + "/" + c.repo + giteaCommitURLSuffix
|
||||
}
|
||||
|
||||
// TagURLBase 给记录页拼 tag 链接用(`<link origin>/<repo>/src/tag/`)。
|
||||
func (c *GiteaClient) TagURLBase() string {
|
||||
return c.linkOrigin + "/" + c.repo + "/src/tag/"
|
||||
}
|
||||
|
||||
func (c *GiteaClient) apiURL(path string, query url.Values) string {
|
||||
|
||||
@@ -28,6 +28,35 @@ func validConfig(base string) GiteaConfig {
|
||||
Sleep: func(time.Duration) {}, MaxRetries: 2, PageSize: 50}
|
||||
}
|
||||
|
||||
func TestGiteaClientUsesSeparateLinkOriginForHumanLinks(t *testing.T) {
|
||||
// 抓取走内网、链接走公网:页面上的链接必须用公网 origin,否则点开是空白。
|
||||
config := validConfig("http://192.168.50.223:3000")
|
||||
config.LinkOrigin = "https://gitea.zheromiku.top/"
|
||||
client, err := NewGiteaClient(config)
|
||||
if err != nil {
|
||||
t.Fatalf("构造客户端失败:%v", err)
|
||||
}
|
||||
if got := client.CommitURLBase(); got != "https://gitea.zheromiku.top/Weknora/knowledge-governance/commit/" {
|
||||
t.Fatalf("提交链接基址 = %q(必须用公网 origin)", got)
|
||||
}
|
||||
if got := client.TagURLBase(); got != "https://gitea.zheromiku.top/Weknora/knowledge-governance/src/tag/" {
|
||||
t.Fatalf("tag 链接基址 = %q", got)
|
||||
}
|
||||
// 不配 LinkOrigin ⇒ 退回抓取 origin(内网场景仍然一致)
|
||||
fallback, err := NewGiteaClient(validConfig("http://192.168.50.223:3000"))
|
||||
if err != nil {
|
||||
t.Fatalf("构造客户端失败:%v", err)
|
||||
}
|
||||
if !strings.HasPrefix(fallback.CommitURLBase(), "http://192.168.50.223:3000/") {
|
||||
t.Fatalf("未配 LinkOrigin 时应退回抓取 origin:%q", fallback.CommitURLBase())
|
||||
}
|
||||
bad := validConfig("http://192.168.50.223:3000")
|
||||
bad.LinkOrigin = "ftp://nope"
|
||||
if _, err := NewGiteaClient(bad); err == nil {
|
||||
t.Fatal("非 http(s) 的链接 origin 必须拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaClientRejectsNonWhitelistedOriginAndBadRepo(t *testing.T) {
|
||||
if _, err := NewGiteaClient(GiteaConfig{BaseURL: "http://evil.example.com",
|
||||
AllowedBaseURLs: []string{"http://192.168.50.223:3000"}, Repo: "a/b"}); err == nil {
|
||||
|
||||
@@ -38,6 +38,7 @@ type ChangelogSource func(sha string) (string, error)
|
||||
type DeriveInput struct {
|
||||
RepoKey string
|
||||
CommitURLBase string // 形如 "<origin>/<owner>/<repo>/commit/",由配置拼好,不接受外部传入
|
||||
TagURLBase string // 形如 "<origin>/<owner>/<repo>/src/tag/";空则不下发 tag 链接
|
||||
Commits []RawCommit
|
||||
Tags []RawTag
|
||||
Changelog ChangelogSource
|
||||
@@ -124,37 +125,54 @@ func DeriveVersions(in DeriveInput) DeriveResult {
|
||||
|
||||
baseTagName := ""
|
||||
var sinceBase *int
|
||||
tagCreatedLater := false
|
||||
if governance.SemverValid(top) {
|
||||
candidate := "v" + top
|
||||
if base, exists := tagByName[candidate]; exists {
|
||||
if !graphComplete {
|
||||
own, ownKnown := ancestors[commit.SHA]
|
||||
_, tagIsAncestor := own[base.TargetSHA]
|
||||
switch {
|
||||
case !graphComplete:
|
||||
// tag 存在但图不完整 ⇒ 不给号(宁可没号,也不报错号)
|
||||
baseTagName = candidate
|
||||
} else if baseSet, ok := ancestors[base.TargetSHA]; ok {
|
||||
if own, ok2 := ancestors[commit.SHA]; ok2 {
|
||||
count := 0
|
||||
for item := range own {
|
||||
if _, inBase := baseSet[item]; !inBase {
|
||||
count++
|
||||
}
|
||||
case !ownKnown:
|
||||
// 连自己的祖先都给不出 ⇒ 不给号
|
||||
case !tagIsAncestor:
|
||||
// **该 tag 是更晚才打在这个提交之后的**:这个提交当时还没有发布基线。
|
||||
// (提交数在这里算会得到 0 —— 因为它的祖先全被那个更晚的 tag 覆盖 —— 拿它编号是错的。)
|
||||
tagCreatedLater = true
|
||||
default:
|
||||
baseSet := ancestors[base.TargetSHA]
|
||||
count := 0
|
||||
for item := range own {
|
||||
if _, inBase := baseSet[item]; !inBase {
|
||||
count++
|
||||
}
|
||||
baseTagName = candidate
|
||||
sinceBase = &count
|
||||
}
|
||||
baseTagName = candidate
|
||||
sinceBase = &count
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
evidenceTags := make([]governance.VersionTagEvidence, 0, len(tagsByTarget[commit.SHA]))
|
||||
for _, tag := range tagsByTarget[commit.SHA] {
|
||||
url := ""
|
||||
if in.TagURLBase != "" {
|
||||
url = in.TagURLBase + tag.Name
|
||||
}
|
||||
evidenceTags = append(evidenceTags, governance.VersionTagEvidence{
|
||||
Name: tag.Name, TagSHA: tag.TagSHA, Annotated: tag.Annotated})
|
||||
Name: tag.Name, TagSHA: tag.TagSHA, Annotated: tag.Annotated, URL: url})
|
||||
}
|
||||
sort.Slice(evidenceTags, func(i, j int) bool { return evidenceTags[i].Name < evidenceTags[j].Name })
|
||||
|
||||
label, state, kind, evidence := governance.DecideVersion(top, evidenceTags, baseTagName, sinceBase)
|
||||
if label == "" && !graphComplete {
|
||||
switch {
|
||||
case label != "":
|
||||
case !graphComplete:
|
||||
evidence.Reason = governance.ReasonIncompleteGraph
|
||||
case tagCreatedLater:
|
||||
evidence.Reason = governance.ReasonTagCreatedLater
|
||||
}
|
||||
record := governance.VersionHistoryCommit{
|
||||
RepoKey: in.RepoKey,
|
||||
|
||||
@@ -177,6 +177,25 @@ func TestDeriveVersionsPicksUpTagAddedAfterwards(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeriveVersionsFillsTagLinksForHumans(t *testing.T) {
|
||||
commits := []RawCommit{commit("A", nil, 1)}
|
||||
tags := []RawTag{{Name: "v0.1.0", TargetSHA: "A", Annotated: true}}
|
||||
derived := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags,
|
||||
CommitURLBase: "https://gitea.example/o/r/commit/",
|
||||
TagURLBase: "https://gitea.example/o/r/src/tag/",
|
||||
Changelog: readerFor(map[string]string{"A": "0.1.0"})})
|
||||
record := find(t, derived.Records, "A")
|
||||
if len(record.ReleaseTags) != 1 || record.ReleaseTags[0].URL != "https://gitea.example/o/r/src/tag/v0.1.0" {
|
||||
t.Fatalf("tag 必须带可点的链接:%+v", record.ReleaseTags)
|
||||
}
|
||||
// 不给 TagURLBase ⇒ 不下发链接(页面据此不渲染空的 tag 链接)
|
||||
bare := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags,
|
||||
Changelog: readerFor(map[string]string{"A": "0.1.0"})})
|
||||
if url := find(t, bare.Records, "A").ReleaseTags[0].URL; url != "" {
|
||||
t.Fatalf("没有基址时不该编链接:%q", url)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeriveVersionsSortsDeterministicallyForPaging(t *testing.T) {
|
||||
sameTime := at(9)
|
||||
commits := []RawCommit{
|
||||
@@ -193,3 +212,51 @@ func TestDeriveVersionsSortsDeterministicallyForPaging(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 回归用例(真实数据发现):tag **更晚**才在链尾打上时,tag 之前那些「提交内 CHANGELOG 顶部
|
||||
// 已经写着 0.1.0」的提交**不能**被算成 0.1.0 开发版 —— 它们的祖先集合全被那个更晚的 tag 覆盖,
|
||||
// 按提交数会得到 0。正确结果:历史提交 + 原因 release_tag_created_later。
|
||||
func TestDeriveVersionsDoesNotNumberCommitsThatPredateTheTag(t *testing.T) {
|
||||
commits := []RawCommit{
|
||||
commit("A", nil, 1), commit("B", []string{"A"}, 2),
|
||||
commit("C", []string{"B"}, 3), commit("D", []string{"C"}, 4),
|
||||
}
|
||||
// tag 打在 C 上;A、B 的 CHANGELOG 顶部**也已经**是 0.1.0(旧分支遗留的条目)
|
||||
tags := []RawTag{{Name: "v0.1.0", TargetSHA: "C", Annotated: true}}
|
||||
top := map[string]string{"A": "0.1.0", "B": "0.1.0", "C": "0.1.0", "D": "0.1.0"}
|
||||
|
||||
result := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags, Changelog: readerFor(top)})
|
||||
for _, sha := range []string{"A", "B"} {
|
||||
record := find(t, result.Records, sha)
|
||||
if record.VersionLabel != "" || record.RecordKind != governance.RecordKindHistorical {
|
||||
t.Fatalf("tag 之前的提交 %s 不许编号:%+v", sha, record)
|
||||
}
|
||||
if record.VersionEvidence.Reason != governance.ReasonTagCreatedLater {
|
||||
t.Fatalf("提交 %s 的原因码 = %q,期望 %q", sha, record.VersionEvidence.Reason, governance.ReasonTagCreatedLater)
|
||||
}
|
||||
}
|
||||
if release := find(t, result.Records, "C"); release.RecordKind != governance.RecordKindRelease || release.VersionLabel != "0.1.0" {
|
||||
t.Fatalf("tag 指向的提交才是正式版本:%+v", release)
|
||||
}
|
||||
if after := find(t, result.Records, "D"); after.VersionLabel != "0.1.1" {
|
||||
t.Fatalf("tag 之后的提交才是开发号:%+v", after)
|
||||
}
|
||||
}
|
||||
|
||||
// 侧分支(不含 tag 的那条线)同样不给号。
|
||||
func TestDeriveVersionsSideBranchWithoutTagStaysHistorical(t *testing.T) {
|
||||
commits := []RawCommit{
|
||||
commit("A", nil, 1), commit("B", []string{"A"}, 2), commit("T", []string{"B"}, 3),
|
||||
commit("S", []string{"A"}, 4), // 从 A 分出去、不含 tag 的侧分支
|
||||
commit("M", []string{"T", "S"}, 5), // 合并回主干
|
||||
}
|
||||
tags := []RawTag{{Name: "v0.1.0", TargetSHA: "T", Annotated: true}}
|
||||
top := map[string]string{"A": "0.1.0", "B": "0.1.0", "T": "0.1.0", "S": "0.1.0", "M": "0.1.0"}
|
||||
result := DeriveVersions(DeriveInput{RepoKey: "repo", Commits: commits, Tags: tags, Changelog: readerFor(top)})
|
||||
if side := find(t, result.Records, "S"); side.VersionLabel != "" {
|
||||
t.Fatalf("不含 tag 的侧分支提交不许编号:%+v", side)
|
||||
}
|
||||
if merge := find(t, result.Records, "M"); merge.VersionLabel != "0.1.2" {
|
||||
t.Fatalf("合并提交含 tag 祖先 ⇒ 按图算号:%+v", merge)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +104,8 @@ type Source interface {
|
||||
CommitURLBase() string
|
||||
ListCommits(ctx context.Context, page, limit int) ([]RawCommit, int, error)
|
||||
ListTags(ctx context.Context) ([]RawTag, error)
|
||||
// TagURLBase 是 tag 链接的基址(给人看的 origin,可能与抓取 origin 不同)。
|
||||
TagURLBase() string
|
||||
ReadFile(ctx context.Context, sha, path string) (string, error)
|
||||
// BranchHeadSHA 读分支 HEAD;读不到不算致命(退回"提交列表里最新的那条")。
|
||||
BranchHeadSHA(ctx context.Context, branch string) (string, error)
|
||||
@@ -203,7 +205,8 @@ func (s *Syncer) Sync(ctx context.Context, jobID, triggeredBy string) (governanc
|
||||
}
|
||||
|
||||
derived := DeriveVersions(DeriveInput{RepoKey: s.repoKey, CommitURLBase: s.source.CommitURLBase(),
|
||||
Commits: commits, Tags: tags, SnapshotID: runID,
|
||||
TagURLBase: s.source.TagURLBase(),
|
||||
Commits: commits, Tags: tags, SnapshotID: runID,
|
||||
Changelog: func(sha string) (string, error) {
|
||||
return s.source.ReadFile(ctx, sha, s.changelog)
|
||||
}})
|
||||
|
||||
@@ -27,6 +27,10 @@ func (f *fakeSource) CommitURLBase() string {
|
||||
return "http://gitea.test/Weknora/knowledge-governance/commit/"
|
||||
}
|
||||
|
||||
func (f *fakeSource) TagURLBase() string {
|
||||
return "http://gitea.test/Weknora/knowledge-governance/src/tag/"
|
||||
}
|
||||
|
||||
func (f *fakeSource) ListCommits(_ context.Context, page, limit int) ([]RawCommit, int, error) {
|
||||
f.listCalls++
|
||||
if f.commitsErr != nil {
|
||||
|
||||
@@ -9,8 +9,77 @@ echo "=== 1. 打回滚标签 ($TS)"
|
||||
docker tag knowledge-governance-p1-api:latest "knowledge-governance-p1-api:rollback-$TS" || exit 1
|
||||
docker tag knowledge-governance-p1-web:latest "knowledge-governance-p1-web:rollback-$TS" || exit 1
|
||||
|
||||
echo "=== 1a. 上线前校验 .env 的键值形状(一行一值)"
|
||||
# 2026-10-14 实测事故:`.env` 最后一行没有结尾换行、又被追加新键 ⇒ 两行粘成一行
|
||||
# ⇒ VERSION_HISTORY_GITEA_BASE_URL 变成 "http://host:3000VERSION_HISTORY_LINK_ORIGIN=…"
|
||||
# ⇒ 配置校验按设计拒绝启动 ⇒ api/worker 崩溃重启(平台整体不可用)。
|
||||
# 这里在**上线前**用形状判定拦住:值里再出现 `KEY=` 或键名不合法,直接拒绝部署。
|
||||
if [ -f .env ]; then
|
||||
python3 - <<'ENVCHECK' || exit 1
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
problems = []
|
||||
for number, raw in enumerate(pathlib.Path(".env").read_text(encoding="utf-8").splitlines(), 1):
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key.strip()):
|
||||
problems.append((number, line, "键名不合法"))
|
||||
elif re.search(r"[A-Z][A-Z0-9_]{3,}=", value):
|
||||
# 不能用 \b:粘行处是 "…:3000VERSION_HISTORY_…",数字紧邻字母,没有词边界。
|
||||
problems.append((number, line, "值里又出现 KEY=(两行粘在一起)"))
|
||||
if problems:
|
||||
print("ENV_VALUE_LOOKS_MERGED(.env 有坏值,拒绝上线)")
|
||||
for number, line, why in problems:
|
||||
print(f" line {number}: {why}: {line[:120]}")
|
||||
sys.exit(1)
|
||||
print(" .env 键值形状 OK")
|
||||
ENVCHECK
|
||||
fi
|
||||
|
||||
echo "=== 1b. 构建身份(构建期注入:页面「当前运行」只认产物里的完整 SHA 精确匹配)"
|
||||
# 唯一来源是 scripts/version.py --identity(与 Makefile、CI 同一份规则):不注入 ⇒ 页面只能显示"未知"。
|
||||
IDENTITY_ARGS=()
|
||||
while IFS= read -r line; do IDENTITY_ARGS+=("$line"); done < <(python3 scripts/version.py --identity 2>/dev/null | python3 -c '
|
||||
import json, sys
|
||||
try:
|
||||
d = json.load(sys.stdin)
|
||||
except Exception:
|
||||
sys.exit(0)
|
||||
release = d.get("release_version") or ""
|
||||
count = d.get("commits_since_release")
|
||||
print("--build-arg=VERSION=" + (release or "dev"))
|
||||
print("--build-arg=RELEASE_VERSION=" + release)
|
||||
print("--build-arg=BUILD_KIND=" + (d.get("build_kind") or "development"))
|
||||
print("--build-arg=COMMITS_SINCE_RELEASE=" + ("" if count is None else str(count)))
|
||||
print("--build-arg=COMMIT_SHA=" + (d.get("commit_sha") or "unknown"))
|
||||
print("--build-arg=BUILD_TIME=" + (d.get("built_at") or "unknown"))
|
||||
')
|
||||
if [ "${#IDENTITY_ARGS[@]}" -lt 6 ]; then
|
||||
echo "IDENTITY_UNAVAILABLE"
|
||||
echo " 取不到构建身份(scripts/version.py --identity 失败)⇒ 拒绝继续:"
|
||||
echo " 否则构建出来的产物无法被「版本记录」页识别成「当前运行」,只会显示未知。"
|
||||
exit 1
|
||||
fi
|
||||
printf ' %s\n' "${IDENTITY_ARGS[@]}"
|
||||
|
||||
echo "=== 1c. 保留上一版构建的静态资源(CDN/浏览器可能还持有旧 index.html)"
|
||||
# 只保留**当前正在跑的那一版**:旧 index.html 的旧哈希引用仍能取到文件,
|
||||
# 页面不会因为某个 JS/CSS 404 而空白或"裸奔"。目录只读挂载进 web 容器。
|
||||
LEGACY_DIR="deploy/legacy-assets"
|
||||
PREV_WEB_IMAGE=$(docker inspect -f '{{.Image}}' knowledge-governance-p1-web-1 2>/dev/null || true)
|
||||
mkdir -p "$LEGACY_DIR/assets" && chmod 777 "$LEGACY_DIR" "$LEGACY_DIR/assets"
|
||||
if [ -n "$PREV_WEB_IMAGE" ]; then
|
||||
docker run --rm --user 0 --entrypoint sh -v "$PWD/$LEGACY_DIR:/out" "$PREV_WEB_IMAGE" \
|
||||
-c 'cp -a /usr/share/nginx/html/assets/. /out/assets/ 2>/dev/null || true' >/dev/null 2>&1 || true
|
||||
echo " LEGACY_ASSETS=$(ls -1 "$LEGACY_DIR/assets" 2>/dev/null | tr '\n' ' ')"
|
||||
fi
|
||||
|
||||
echo "=== 2. 构建 api"
|
||||
docker build --network host "${PROXY_ARGS[@]}" -f Dockerfile -t knowledge-governance-p1-api:latest . || { echo "API_BUILD_FAILED"; exit 1; }
|
||||
docker build --network host "${PROXY_ARGS[@]}" "${IDENTITY_ARGS[@]}" -f Dockerfile -t knowledge-governance-p1-api:latest . || { echo "API_BUILD_FAILED"; exit 1; }
|
||||
|
||||
echo "=== 3. 构建 web"
|
||||
docker build --network host "${PROXY_ARGS[@]}" -f Dockerfile.web -t knowledge-governance-p1-web:latest . || { echo "WEB_BUILD_FAILED"; exit 1; }
|
||||
@@ -47,4 +116,11 @@ echo "=== 7b. 生产门禁状态(重建后必须与预期一致)"
|
||||
docker exec knowledge-governance-p1-api-1 sh -lc 'for v in PRODUCTION_RELEASE_REQUESTS_ENABLED PRODUCTION_BACKUP_RESTORE_VERIFIED; do eval "val=\$$v"; echo "$v=${val:-<empty>}"; done'
|
||||
echo "=== 8. 新包"
|
||||
docker exec knowledge-governance-p1-web-1 sh -lc 'grep -o "index-[A-Za-z0-9_-]*\.js" /usr/share/nginx/html/index.html | head -1'
|
||||
echo "=== 9. 构建身份是否真的进了产物(页面据此判「当前运行」)"
|
||||
INJECTED=$(printf '%s\n' "${IDENTITY_ARGS[@]}" | sed -n 's/^--build-arg=COMMIT_SHA=//p')
|
||||
if docker exec knowledge-governance-p1-api-1 sh -lc "strings /app/api | grep -q '$INJECTED'"; then
|
||||
echo "INJECTED_COMMIT_SHA=$INJECTED(已进 api 产物)"
|
||||
else
|
||||
echo "INJECTION_MISSING(产物里没有 $INJECTED —— 页面会显示当前运行未知)"
|
||||
fi
|
||||
echo "DONE"
|
||||
@@ -5,8 +5,10 @@ import { DingtalkSourceDiscovery } from './DingtalkSourceDiscovery'
|
||||
|
||||
describe('DingtalkSourceDiscovery', () => {
|
||||
it('renders the discovery shell without any file-format filter', () => {
|
||||
const html = renderToStaticMarkup(<DingtalkSourceDiscovery registeredNames={['ATOM知识库']} onRegistered={vi.fn()} />)
|
||||
for (const text of ['可加入的来源', '刷新列表', '加入为来源(选中 0)', '已是来源']) {
|
||||
const html = renderToStaticMarkup(
|
||||
<DingtalkSourceDiscovery registeredNames={['ATOM知识库']} onRegistered={vi.fn()} />
|
||||
)
|
||||
for (const text of ['dws 导入(钉钉)', '刷新列表', '加入为来源(选中 0)', '已是来源']) {
|
||||
expect(html).toContain(text)
|
||||
}
|
||||
// 需求(2026-10-10):数据源配置这里不再做文件格式筛选——格式归目录级标注决定。
|
||||
@@ -14,4 +16,4 @@ describe('DingtalkSourceDiscovery', () => {
|
||||
expect(html).not.toContain(removed)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,7 +2,12 @@ import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { DingtalkRequestError, registerDingtalkSpace } from './dingtalkSession'
|
||||
import { DingtalkSessionControl } from './DingtalkSessionControl'
|
||||
import { discoveryCandidates, fetchAvailableDingtalkSources, type AvailableDingtalkSources, type DiscoveryCandidate } from './dingtalkSources'
|
||||
import {
|
||||
discoveryCandidates,
|
||||
fetchAvailableDingtalkSources,
|
||||
type AvailableDingtalkSources,
|
||||
type DiscoveryCandidate,
|
||||
} from './dingtalkSources'
|
||||
|
||||
// 「系统设置 → 数据源配置」里的数据源发现面板(管理员):
|
||||
// ① 列出当前钉钉账号(dws)能看到的钉钉知识库;
|
||||
@@ -11,7 +16,13 @@ import { discoveryCandidates, fetchAvailableDingtalkSources, type AvailableDingt
|
||||
// ④ 登记需要有效的钉钉扫码会话:会话失效时直接弹二维码,扫完自动重试本次登记。
|
||||
// 这里不显示文件格式筛选:格式由目录级标注决定,不在这张卡上做。
|
||||
|
||||
export function DingtalkSourceDiscovery({ registeredNames, onRegistered }: { registeredNames: string[]; onRegistered: () => void }) {
|
||||
export function DingtalkSourceDiscovery({
|
||||
registeredNames,
|
||||
onRegistered,
|
||||
}: {
|
||||
registeredNames: string[]
|
||||
onRegistered: () => void
|
||||
}) {
|
||||
const [list, setList] = useState<AvailableDingtalkSources | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
@@ -22,7 +33,8 @@ export function DingtalkSourceDiscovery({ registeredNames, onRegistered }: { reg
|
||||
const [loginRequired, setLoginRequired] = useState(false)
|
||||
|
||||
const load = useCallback(async (signal?: AbortSignal) => {
|
||||
setLoading(true); setLoadError(null)
|
||||
setLoading(true)
|
||||
setLoadError(null)
|
||||
try {
|
||||
const next = await fetchAvailableDingtalkSources(signal)
|
||||
setList(next)
|
||||
@@ -47,10 +59,13 @@ export function DingtalkSourceDiscovery({ registeredNames, onRegistered }: { reg
|
||||
const knowledgeBases = candidates.filter((item) => item.kind === 'knowledge_base')
|
||||
const driveSpaces = candidates.filter((item) => item.kind === 'drive_space')
|
||||
const selected = candidates.filter((item) => checked.includes(item.key))
|
||||
const toggle = (key: string) => setChecked((current) => current.includes(key) ? current.filter((item) => item !== key) : [...current, key])
|
||||
const toggle = (key: string) =>
|
||||
setChecked((current) => (current.includes(key) ? current.filter((item) => item !== key) : [...current, key]))
|
||||
|
||||
const submit = async (retryAfterLogin = false) => {
|
||||
setBusy(true); setFailure(null); setMessage(null)
|
||||
setBusy(true)
|
||||
setFailure(null)
|
||||
setMessage(null)
|
||||
const added: string[] = []
|
||||
const failed: string[] = []
|
||||
let needLogin = false
|
||||
@@ -89,49 +104,90 @@ export function DingtalkSourceDiscovery({ registeredNames, onRegistered }: { reg
|
||||
|
||||
const renderRow = (candidate: DiscoveryCandidate) => {
|
||||
const already = candidate.alreadyRegistered
|
||||
return <li key={candidate.key} className={already ? 'discovery-row registered' : 'discovery-row'}>
|
||||
<label>
|
||||
<input type="checkbox" aria-label={`选择${candidate.name}`} checked={checked.includes(candidate.key)} disabled={already || busy} onChange={() => toggle(candidate.key)} />
|
||||
<span><strong>{candidate.name}</strong><small>{candidate.detail}</small></span>
|
||||
</label>
|
||||
{already ? <span className="safe-badge">已是来源</span> : null}
|
||||
</li>
|
||||
return (
|
||||
<li key={candidate.key} className={already ? 'discovery-row registered' : 'discovery-row'}>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`选择${candidate.name}`}
|
||||
checked={checked.includes(candidate.key)}
|
||||
disabled={already || busy}
|
||||
onChange={() => toggle(candidate.key)}
|
||||
/>
|
||||
<span>
|
||||
<strong>{candidate.name}</strong>
|
||||
<small>{candidate.detail}</small>
|
||||
</span>
|
||||
</label>
|
||||
{already ? <span className="safe-badge">已是来源</span> : null}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
return <section className="dingtalk-discovery" aria-label="可加入的数据源">
|
||||
<div className="dingtalk-discovery-heading">
|
||||
<div>
|
||||
<strong>可加入的来源</strong>
|
||||
<small>按当前钉钉账号列出能访问的知识库与钉盘空间;勾选后加入为来源,首次目录扫描自动排队。</small>
|
||||
return (
|
||||
<section className="dingtalk-discovery" aria-label="可加入的数据源">
|
||||
<div className="dingtalk-discovery-heading">
|
||||
<div>
|
||||
<strong>dws 导入(钉钉)</strong>
|
||||
<small>按当前钉钉账号列出能访问的知识库与钉盘空间;勾选后加入为来源,首次目录扫描自动排队。</small>
|
||||
</div>
|
||||
<button type="button" className="secondary" onClick={() => void load()} disabled={loading}>
|
||||
{loading ? '正在列举…' : '刷新列表'}
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" className="secondary" onClick={() => void load()} disabled={loading}>{loading ? '正在列举…' : '刷新列表'}</button>
|
||||
</div>
|
||||
{loadError ? <p className="error-message" role="alert">{loadError}</p> : null}
|
||||
{list ? <div className="dingtalk-discovery-groups">
|
||||
<div className="discovery-group">
|
||||
<h4>知识库({knowledgeBases.length})</h4>
|
||||
{list.knowledge_notice ? <small className="empty-inline">知识库列表可能不全:{list.knowledge_notice}</small> : null}
|
||||
{knowledgeBases.length ? <ul>{knowledgeBases.map(renderRow)}</ul> : <small className="empty-inline">当前账号下没有可访问的知识库。</small>}
|
||||
{loadError ? (
|
||||
<p className="error-message" role="alert">
|
||||
{loadError}
|
||||
</p>
|
||||
) : null}
|
||||
{list ? (
|
||||
<div className="dingtalk-discovery-groups">
|
||||
<div className="discovery-group">
|
||||
<h4>知识库({knowledgeBases.length})</h4>
|
||||
{list.knowledge_notice ? (
|
||||
<small className="empty-inline">知识库列表可能不全:{list.knowledge_notice}</small>
|
||||
) : null}
|
||||
{knowledgeBases.length ? (
|
||||
<ul>{knowledgeBases.map(renderRow)}</ul>
|
||||
) : (
|
||||
<small className="empty-inline">当前账号下没有可访问的知识库。</small>
|
||||
)}
|
||||
</div>
|
||||
<div className="discovery-group">
|
||||
<h4>钉盘({driveSpaces.length})</h4>
|
||||
{list.drive_notice ? <small className="empty-inline">钉盘这次列不出来:{list.drive_notice}</small> : null}
|
||||
{!list.drive_notice && !driveSpaces.length ? (
|
||||
<small className="empty-inline">当前账号下没有可见的钉盘空间。</small>
|
||||
) : null}
|
||||
{driveSpaces.length ? <ul>{driveSpaces.map(renderRow)}</ul> : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="dingtalk-discovery-actions">
|
||||
<button type="button" disabled={!selected.length || busy} onClick={() => void submit()}>
|
||||
{busy ? '正在加入…' : `加入为来源(选中 ${selected.length})`}
|
||||
</button>
|
||||
<small>勾选的知识库会登记为来源连接;已登记的条目标为「已是来源」,不会重复登记。</small>
|
||||
</div>
|
||||
<div className="discovery-group">
|
||||
<h4>钉盘({driveSpaces.length})</h4>
|
||||
{list.drive_notice ? <small className="empty-inline">钉盘这次列不出来:{list.drive_notice}</small> : null}
|
||||
{!list.drive_notice && !driveSpaces.length ? <small className="empty-inline">当前账号下没有可见的钉盘空间。</small> : null}
|
||||
{driveSpaces.length ? <ul>{driveSpaces.map(renderRow)}</ul> : null}
|
||||
</div>
|
||||
</div> : null}
|
||||
<div className="dingtalk-discovery-actions">
|
||||
<button type="button" disabled={!selected.length || busy} onClick={() => void submit()}>{busy ? '正在加入…' : `加入为来源(选中 ${selected.length})`}</button>
|
||||
<small>勾选的知识库会登记为来源连接;已登记的条目标为「已是来源」,不会重复登记。</small>
|
||||
</div>
|
||||
{message ? <p className="success-message" role="status">{message}</p> : null}
|
||||
{failure ? <p className="error-message" role="alert">{failure}</p> : null}
|
||||
{loginRequired ? <DingtalkSessionControl
|
||||
autoStart
|
||||
hideTrigger
|
||||
space={selected[0]?.url}
|
||||
onSuccess={resumeAfterLogin}
|
||||
onClose={() => setLoginRequired(false)}
|
||||
/> : null}
|
||||
</section>
|
||||
}
|
||||
{message ? (
|
||||
<p className="success-message" role="status">
|
||||
{message}
|
||||
</p>
|
||||
) : null}
|
||||
{failure ? (
|
||||
<p className="error-message" role="alert">
|
||||
{failure}
|
||||
</p>
|
||||
) : null}
|
||||
{loginRequired ? (
|
||||
<DingtalkSessionControl
|
||||
autoStart
|
||||
hideTrigger
|
||||
space={selected[0]?.url}
|
||||
onSuccess={resumeAfterLogin}
|
||||
onClose={() => setLoginRequired(false)}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
+629
-98
@@ -1,108 +1,639 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe,expect,it,vi } from 'vitest'
|
||||
import { SystemSettingsView, visibleSaveMessage } from './SystemSettings'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { SystemSettingsView, ppSourceConnections, visibleSaveMessage } from './SystemSettings'
|
||||
import { AuthContext } from './auth'
|
||||
import type { MonitorOverview } from './monitor'
|
||||
import type { CatalogSource } from './sourceCatalog'
|
||||
import type { UISettings } from './uiSettings'
|
||||
import type { SourceConnectionListItem } from './sourceConnections'
|
||||
const monitor:MonitorOverview={mode:'simulation',simulated:true,observed_at:'2026-09-08T12:00:00Z',host:{cpu_percent:42,memory_used_bytes:1,memory_total_bytes:2,disk_used_bytes:1,disk_total_bytes:2,gpu_state:'unknown',gpu_detail:'未接入真实GPU监控',simulated:true},services:[{key:'mineru',name:'MinerU',state:'healthy',detail:'模拟',latency_ms:1,observed_at:'2026-09-08T12:00:00Z',simulated:true}],knowledge_bases:[],health:[{key:'mineru',name:'MinerU',liveness:'up',readiness:'blocked',reason:'服务可达但容量已满(429),暂时不可接单',latency_ms:30,observed_at:'2026-09-08T12:00:00Z',last_success_at:'2026-09-08T11:59:00Z',consecutive_failures:2,configured:true,applicable:true}]}
|
||||
const sources:CatalogSource[]=[{connection_id:'ding-1',source_type:'dingtalk',name:'公司级技术支持知识库',root_node_id:'root-1',folder_count:1079,file_count:3444,observed_at:'2026-09-09T09:30:32Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:0}]
|
||||
const connections:SourceConnectionListItem[]=[{id:'conn-ding',source_type:'dingtalk',name:'公司级技术支持知识库',enabled:true,schedule_configured:true,health_status:'healthy',item_count:3444,updated_at:'2026-09-09T09:30:32Z',next_refresh_at:'2026-09-12T10:00:00Z'},{id:'conn-man',source_type:'manual',name:'本地手工验收',enabled:false,schedule_configured:false,health_status:'unknown',item_count:5,updated_at:'2026-09-09T09:30:32Z',next_refresh_at:null}]
|
||||
const settings:UISettings={id:'settings-default',state:'active',document_refresh_seconds:15,resource_refresh_seconds:30,stalled_after_seconds:1800,finalizing_after_seconds:7200,ingestion_concurrency:2,test_weknora_base_url:'',production_weknora_base_url:'',production_tenant_id:'',production_knowledge_base_id:'',updated_by:'system:migration',created_at:'2026-09-10T08:00:00Z',activated_at:'2026-09-10T08:00:00Z',retired_at:null,error_code:''}
|
||||
const authValue=(role:'admin'|'engineer')=>({identity:{id:`${role}-1`,username:role,display_name:role,role,must_change_password:false},ready:true,login:async()=>null,logout:async()=>{},changePassword:async()=>null,signedOut:0,notifySignedOut:()=>{}})
|
||||
describe('SystemSettingsView service configuration',()=>{
|
||||
it('lets an administrator edit exactly the four service fields in the web console',()=>{
|
||||
const configured:UISettings={...settings,test_weknora_base_url:'https://weknora.test.example',production_weknora_base_url:'https://weknora.prod.example',production_tenant_id:'10000',production_knowledge_base_id:'kb-abc123'}
|
||||
const view=(role:'admin'|'engineer')=>renderToStaticMarkup(<AuthContext.Provider value={authValue(role)}><SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={configured} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" /></AuthContext.Provider>)
|
||||
const adminHtml=view('admin')
|
||||
for(const text of ['测试地址','生产地址','生产 ID','知识库 ID','保存并启用服务配置','https://weknora.test.example','https://weknora.prod.example','10000','kb-abc123','四项留空即表示未配置'])expect(adminHtml).toContain(text)
|
||||
expect(adminHtml).not.toContain('仅管理员可修改')
|
||||
// 界面只剩这四项:依赖探活矩阵与对内/对外绑定下拉不再出现在服务配置页。
|
||||
for(const removed of ['MinerU','Embedding','Redis / MQ','PostgreSQL','测试知识库映射'])expect(adminHtml).not.toContain(removed)
|
||||
const engineerHtml=view('engineer')
|
||||
expect(engineerHtml).toContain('仅管理员可修改')
|
||||
expect(engineerHtml).not.toContain('保存并启用服务配置')
|
||||
})
|
||||
const monitor: MonitorOverview = {
|
||||
mode: 'simulation',
|
||||
simulated: true,
|
||||
observed_at: '2026-09-08T12:00:00Z',
|
||||
host: {
|
||||
cpu_percent: 42,
|
||||
memory_used_bytes: 1,
|
||||
memory_total_bytes: 2,
|
||||
disk_used_bytes: 1,
|
||||
disk_total_bytes: 2,
|
||||
gpu_state: 'unknown',
|
||||
gpu_detail: '未接入真实GPU监控',
|
||||
simulated: true,
|
||||
},
|
||||
services: [
|
||||
{
|
||||
key: 'mineru',
|
||||
name: 'MinerU',
|
||||
state: 'healthy',
|
||||
detail: '模拟',
|
||||
latency_ms: 1,
|
||||
observed_at: '2026-09-08T12:00:00Z',
|
||||
simulated: true,
|
||||
},
|
||||
],
|
||||
knowledge_bases: [],
|
||||
health: [
|
||||
{
|
||||
key: 'mineru',
|
||||
name: 'MinerU',
|
||||
liveness: 'up',
|
||||
readiness: 'blocked',
|
||||
reason: '服务可达但容量已满(429),暂时不可接单',
|
||||
latency_ms: 30,
|
||||
observed_at: '2026-09-08T12:00:00Z',
|
||||
last_success_at: '2026-09-08T11:59:00Z',
|
||||
consecutive_failures: 2,
|
||||
configured: true,
|
||||
applicable: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
const sources: CatalogSource[] = [
|
||||
{
|
||||
connection_id: 'ding-1',
|
||||
source_type: 'dingtalk',
|
||||
name: '公司级技术支持知识库',
|
||||
root_node_id: 'root-1',
|
||||
folder_count: 1079,
|
||||
file_count: 3444,
|
||||
observed_at: '2026-09-09T09:30:32Z',
|
||||
snapshot_only: true,
|
||||
snapshot_status: 'ready',
|
||||
last_refresh_duration_ms: 0,
|
||||
},
|
||||
]
|
||||
const connections: SourceConnectionListItem[] = [
|
||||
{
|
||||
id: 'conn-ding',
|
||||
source_type: 'dingtalk',
|
||||
name: '公司级技术支持知识库',
|
||||
enabled: true,
|
||||
schedule_configured: true,
|
||||
health_status: 'healthy',
|
||||
item_count: 3444,
|
||||
updated_at: '2026-09-09T09:30:32Z',
|
||||
next_refresh_at: '2026-09-12T10:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'conn-man',
|
||||
source_type: 'manual',
|
||||
name: '本地手工验收',
|
||||
enabled: false,
|
||||
schedule_configured: false,
|
||||
health_status: 'unknown',
|
||||
item_count: 5,
|
||||
updated_at: '2026-09-09T09:30:32Z',
|
||||
next_refresh_at: null,
|
||||
},
|
||||
]
|
||||
const settings: UISettings = {
|
||||
id: 'settings-default',
|
||||
state: 'active',
|
||||
document_refresh_seconds: 15,
|
||||
resource_refresh_seconds: 30,
|
||||
stalled_after_seconds: 1800,
|
||||
finalizing_after_seconds: 7200,
|
||||
ingestion_concurrency: 2,
|
||||
test_weknora_base_url: '',
|
||||
production_weknora_base_url: '',
|
||||
production_tenant_id: '',
|
||||
production_knowledge_base_id: '',
|
||||
updated_by: 'system:migration',
|
||||
created_at: '2026-09-10T08:00:00Z',
|
||||
activated_at: '2026-09-10T08:00:00Z',
|
||||
retired_at: null,
|
||||
error_code: '',
|
||||
}
|
||||
const authValue = (role: 'admin' | 'engineer') => ({
|
||||
identity: { id: `${role}-1`, username: role, display_name: role, role, must_change_password: false },
|
||||
ready: true,
|
||||
login: async () => null,
|
||||
logout: async () => {},
|
||||
changePassword: async () => null,
|
||||
signedOut: 0,
|
||||
notifySignedOut: () => {},
|
||||
})
|
||||
describe('SystemSettingsView',()=>{
|
||||
it('separates document-engineer settings from locked administrator and production controls',()=>{
|
||||
const html=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时" onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} />)
|
||||
for(const text of ['系统设置','数据源配置','服务配置','存储与备份','刷新策略','设置服务已启用','当前活动版本','公司级技术支持知识库','钉钉知识库','认证方式','端点与凭据','文档工程师可调整','管理员设置已锁定'])expect(html).toContain(text)
|
||||
// 需求(2026-10-10):数据源配置不再做文件格式筛选(格式由目录级标注决定)。
|
||||
for(const removed of ['文件格式筛选','未勾选的一律不取件','保存保留格式','恢复继承上级规则'])expect(html).not.toContain(removed)
|
||||
// 需求(2026-10-10):新增入口只剩「可加入的来源」勾选,粘贴链接的按钮已下线。
|
||||
for(const removed of ['+ 新增钉钉知识库','新增钉钉知识库'])expect(html).not.toContain(removed)
|
||||
const servicesHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" />)
|
||||
for(const text of ['测试 WeKnora','生产 WeKnora','测试地址','生产地址','生产 ID','知识库 ID'])expect(servicesHtml).toContain(text)
|
||||
const storageHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="storage" />)
|
||||
// 存储与备份分区已换成真实功能(整库逻辑备份的定时计划),静态占位文案不再存在。
|
||||
expect(storageHtml).toContain('存储与备份')
|
||||
expect(storageHtml).toContain('正在读取备份计划…')
|
||||
expect(storageHtml).not.toContain('仅保存凭据引用,不可回读')
|
||||
const refreshHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时" onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="refresh" />)
|
||||
for(const text of ['刷新与告警参数已验证并启用','停滞30分钟','finalizing 2小时','文档状态刷新间隔','15秒','解析停滞判定','30分钟','保存并应用刷新与告警参数'])expect(refreshHtml).toContain(text)
|
||||
expect(visibleSaveMessage('已保存',true)).toBeNull();expect(visibleSaveMessage('已保存',false)).toBe('已保存')
|
||||
expect(html).not.toContain('本地模拟');expect(html).not.toContain('保存模拟设置')
|
||||
for(const forbidden of ['DATABASE_URL','RELEASE_CONFIG_FILE','API Key明文','secret_ref'])expect(html).not.toContain(forbidden)
|
||||
// 两个环境卡仍由真实探测驱动(依赖矩阵搬到总览页,本页不再渲染)。
|
||||
expect(servicesHtml).toContain('解析队列 对内 已配置 · 对外 已配置')
|
||||
expect(servicesHtml).not.toContain('PostgreSQL')
|
||||
expect(servicesHtml).toContain('端点探测:暂无真实探测结果')
|
||||
// V1: left-nav section controls, per-source schedule editing, danger modal & history affordances.
|
||||
expect(html).toContain('settings-nav')
|
||||
expect(html).toContain('下次自动刷新')
|
||||
expect(html).toContain('仅手动刷新')
|
||||
expect(html).toContain('查看修订历史')
|
||||
expect(html).toContain('保存并启用调度')
|
||||
expect(html).toContain('停用来源')
|
||||
expect(html).toContain('本地手工导入来源不支持定时刷新')
|
||||
// dead buttons removed
|
||||
expect(html).not.toContain('添加内容源')
|
||||
expect(html).not.toContain('管理员编辑')
|
||||
})
|
||||
it('lets an administrator bind the internal/external import knowledge bases from 系统设置',()=>{
|
||||
// 组件一直在(RoutingBindingsSection),但从未挂到任何页面 —— 导入目标库只能靠
|
||||
// 部署 env 钉死,换库必须重建容器。
|
||||
const view=(section:'sources'|'bindings'|'production-bindings')=>renderToStaticMarkup(<AuthContext.Provider value={authValue('admin')}><SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection={section} /></AuthContext.Provider>)
|
||||
expect(view('sources')).toContain('测试知识库绑定')
|
||||
expect(view('sources')).toContain('生产知识库绑定')
|
||||
const bound=view('bindings')
|
||||
expect(bound).toContain('id="settings-routing-bindings"')
|
||||
expect(bound).toContain('分发到对应的测试 WeKnora 知识库')
|
||||
// 未读到绑定数据时(SSR 不跑 effect)面板也要如实存在,而不是空白。
|
||||
expect(bound).toContain('读取中…')
|
||||
// 发布目标(源库 → 目标库)是独立分区,与测试端收件库分开。
|
||||
const target=view('production-bindings')
|
||||
expect(target).toContain('id="settings-production-bindings"')
|
||||
expect(target).toContain('新发布的对内 / 对外内容按这里的绑定写入生产 WeKnora 的对应知识库')
|
||||
describe('SystemSettingsView service configuration', () => {
|
||||
it('lets an administrator edit exactly the four service fields in the web console', () => {
|
||||
const configured: UISettings = {
|
||||
...settings,
|
||||
test_weknora_base_url: 'https://weknora.test.example',
|
||||
production_weknora_base_url: 'https://weknora.prod.example',
|
||||
production_tenant_id: '10000',
|
||||
production_knowledge_base_id: 'kb-abc123',
|
||||
}
|
||||
const view = (role: 'admin' | 'engineer') =>
|
||||
renderToStaticMarkup(
|
||||
<AuthContext.Provider value={authValue(role)}>
|
||||
<SystemSettingsView
|
||||
sources={sources}
|
||||
connections={connections}
|
||||
monitor={monitor}
|
||||
settings={configured}
|
||||
productionEnabled={false}
|
||||
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage={null}
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
initialSection="services"
|
||||
/>
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
const adminHtml = view('admin')
|
||||
for (const text of [
|
||||
'测试地址',
|
||||
'生产地址',
|
||||
'生产 ID',
|
||||
'知识库 ID',
|
||||
'保存并启用服务配置',
|
||||
'https://weknora.test.example',
|
||||
'https://weknora.prod.example',
|
||||
'10000',
|
||||
'kb-abc123',
|
||||
'四项留空即表示未配置',
|
||||
])
|
||||
expect(adminHtml).toContain(text)
|
||||
expect(adminHtml).not.toContain('仅管理员可修改')
|
||||
// 界面只剩这四项:依赖探活矩阵与对内/对外绑定下拉不再出现在服务配置页。
|
||||
for (const removed of ['MinerU', 'Embedding', 'Redis / MQ', 'PostgreSQL', '测试知识库映射'])
|
||||
expect(adminHtml).not.toContain(removed)
|
||||
const engineerHtml = view('engineer')
|
||||
expect(engineerHtml).toContain('仅管理员可修改')
|
||||
expect(engineerHtml).not.toContain('保存并启用服务配置')
|
||||
})
|
||||
})
|
||||
it('does not show healthy simulation when the settings data failed to load',()=>{
|
||||
const html=renderToStaticMarkup(<SystemSettingsView sources={[]} connections={[]} monitor={null} settings={null} productionEnabled={false} routingCapabilities={{internal_enabled:false,external_enabled:false}} loading={false} saving={false} error="加载失败" saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} />)
|
||||
expect(html).toContain('加载失败');expect(html).not.toContain('模拟运行中')
|
||||
})
|
||||
it('renders the WeKnora cards and production channel from live probe and the real production gate',()=>{
|
||||
const probed:MonitorOverview={...monitor,health:[
|
||||
{key:'weknora',name:'WeKnora API',liveness:'up',readiness:'ready',reason:'',latency_ms:86,observed_at:'2026-09-08T12:00:00Z',last_success_at:'2026-09-08T11:59:00Z',consecutive_failures:0,configured:true,applicable:true},
|
||||
{key:'weknora-production',name:'生产 WeKnora',liveness:'up',readiness:'ready',reason:'',latency_ms:41,observed_at:'2026-09-08T12:00:00Z',last_success_at:'2026-09-08T11:59:00Z',consecutive_failures:0,configured:true,applicable:true},
|
||||
{key:'embedding',name:'Embedding',liveness:'up',readiness:'not_applicable',reason:'未部署:本平台不使用该依赖',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',last_success_at:null,consecutive_failures:0,configured:false,applicable:false}]}
|
||||
const view=(enabled:boolean,verified:boolean)=>renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={probed} settings={settings} productionEnabled={enabled} productionBackupRestoreVerified={verified} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" />)
|
||||
const on=view(true,true)
|
||||
expect(on).toContain('测试 WeKnora')
|
||||
expect(on).toContain('可达 · 可接单');expect(on).toContain('延迟 86ms')
|
||||
expect(on).toContain('已启用 · 可提交生产请求');expect(on).toContain('生产写入:开启');expect(on).toContain('发布目标与凭据:管理员受限配置')
|
||||
const off=view(false,false)
|
||||
expect(off).toContain('未启用');expect(off).toContain('生产写入:关闭')
|
||||
// 卡片状态由真实探测/门禁驱动,写死的“已连接 / 未连接 / 生产映射:未配置”必须消失。
|
||||
for(const removed of ['本地真实连接','生产映射:未配置'])expect(off).not.toContain(removed)
|
||||
// 生产端点可达性来自真实探活,且只说真话:探活不等于验证过接单能力。
|
||||
expect(on).toContain('端点探测:端点可达 · 未做接单验证')
|
||||
const blocked=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={true} productionBackupRestoreVerified={false} routingCapabilities={{internal_enabled:false,external_enabled:false}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" />)
|
||||
expect(blocked).toContain('已启用 · 被阻断')
|
||||
// 未配置生产端点时必须显式说「未配置」,不得靠文案含糊过去。
|
||||
expect(blocked).toContain('端点探测:暂无真实探测结果')
|
||||
const unconfigured=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={{...monitor,health:[{key:'weknora-production',name:'生产 WeKnora',liveness:'unknown',readiness:'not_configured',reason:'已部署但未配置探测参数',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',last_success_at:null,consecutive_failures:0,configured:false,applicable:false}]}} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:false,external_enabled:false}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" />)
|
||||
expect(unconfigured).toContain('端点探测:未配置')
|
||||
expect(unconfigured).not.toContain('端点可达')
|
||||
describe('SystemSettingsView', () => {
|
||||
it('separates document-engineer settings from locked administrator and production controls', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SystemSettingsView
|
||||
sources={sources}
|
||||
connections={connections}
|
||||
monitor={monitor}
|
||||
settings={settings}
|
||||
productionEnabled={false}
|
||||
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时"
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
)
|
||||
for (const text of [
|
||||
'系统设置',
|
||||
'数据源配置',
|
||||
'服务配置',
|
||||
'存储与备份',
|
||||
'刷新策略',
|
||||
'设置服务已启用',
|
||||
'当前活动版本',
|
||||
'文档工程师可调整',
|
||||
'管理员设置已锁定',
|
||||
])
|
||||
expect(html).toContain(text)
|
||||
// 需求(2026-10-14 收敛):数据源配置只剩两个入口 —— dws 导入(按当前钉钉账号发现)
|
||||
// 与 PP 导入;AList/静态钉钉知识库等来源类型不再出现在这里(也没有折叠开关兜着)。
|
||||
for (const hidden of ['公司级技术支持知识库', '专用浏览器扫码会话', '显示 AList/钉钉知识库来源'])
|
||||
expect(html).not.toContain(hidden)
|
||||
expect(html).toContain('dws 导入')
|
||||
expect(html).toContain('PP 导入')
|
||||
// 需求(2026-10-10):数据源配置不再做文件格式筛选(格式由目录级标注决定)。
|
||||
for (const removed of ['文件格式筛选', '未勾选的一律不取件', '保存保留格式', '恢复继承上级规则'])
|
||||
expect(html).not.toContain(removed)
|
||||
// 需求(2026-10-10):新增入口只剩「可加入的来源」勾选,粘贴链接的按钮已下线。
|
||||
for (const removed of ['+ 新增钉钉知识库', '新增钉钉知识库']) expect(html).not.toContain(removed)
|
||||
const servicesHtml = renderToStaticMarkup(
|
||||
<SystemSettingsView
|
||||
sources={sources}
|
||||
connections={connections}
|
||||
monitor={monitor}
|
||||
settings={settings}
|
||||
productionEnabled={false}
|
||||
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage={null}
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
initialSection="services"
|
||||
/>
|
||||
)
|
||||
for (const text of ['测试 WeKnora', '生产 WeKnora', '测试地址', '生产地址', '生产 ID', '知识库 ID'])
|
||||
expect(servicesHtml).toContain(text)
|
||||
const storageHtml = renderToStaticMarkup(
|
||||
<SystemSettingsView
|
||||
sources={sources}
|
||||
connections={connections}
|
||||
monitor={monitor}
|
||||
settings={settings}
|
||||
productionEnabled={false}
|
||||
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage={null}
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
initialSection="storage"
|
||||
/>
|
||||
)
|
||||
// 存储与备份分区已换成真实功能(整库逻辑备份的定时计划),静态占位文案不再存在。
|
||||
expect(storageHtml).toContain('存储与备份')
|
||||
expect(storageHtml).toContain('正在读取备份计划…')
|
||||
expect(storageHtml).not.toContain('仅保存凭据引用,不可回读')
|
||||
const refreshHtml = renderToStaticMarkup(
|
||||
<SystemSettingsView
|
||||
sources={sources}
|
||||
connections={connections}
|
||||
monitor={monitor}
|
||||
settings={settings}
|
||||
productionEnabled={false}
|
||||
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时"
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
initialSection="refresh"
|
||||
/>
|
||||
)
|
||||
for (const text of [
|
||||
'刷新与告警参数已验证并启用',
|
||||
'停滞30分钟',
|
||||
'finalizing 2小时',
|
||||
'文档状态刷新间隔',
|
||||
'15秒',
|
||||
'解析停滞判定',
|
||||
'30分钟',
|
||||
'保存并应用刷新与告警参数',
|
||||
])
|
||||
expect(refreshHtml).toContain(text)
|
||||
expect(visibleSaveMessage('已保存', true)).toBeNull()
|
||||
expect(visibleSaveMessage('已保存', false)).toBe('已保存')
|
||||
expect(html).not.toContain('本地模拟')
|
||||
expect(html).not.toContain('保存模拟设置')
|
||||
for (const forbidden of ['DATABASE_URL', 'RELEASE_CONFIG_FILE', 'API Key明文', 'secret_ref'])
|
||||
expect(html).not.toContain(forbidden)
|
||||
// 两个环境卡仍由真实探测驱动(依赖矩阵搬到总览页,本页不再渲染)。
|
||||
expect(servicesHtml).toContain('解析队列 对内 已配置 · 对外 已配置')
|
||||
expect(servicesHtml).not.toContain('PostgreSQL')
|
||||
expect(servicesHtml).toContain('端点探测:暂无真实探测结果')
|
||||
// V1: left-nav section controls, per-source schedule editing, danger modal & history affordances.
|
||||
expect(html).toContain('settings-nav')
|
||||
// 非 PP 来源在这里根本不渲染卡片:连它们卡片上的调度、停用、修订入口一起消失。
|
||||
for (const gone of ['查看修订历史', '保存并启用调度', '停用来源', '下次自动刷新']) expect(html).not.toContain(gone)
|
||||
expect(html).toContain('本页只列 PP 来源')
|
||||
// 手工来源(本地手工验收)也不再列在这里,它的专属提示自然不出现。
|
||||
expect(html).not.toContain('本地手工导入来源不支持定时刷新')
|
||||
// dead buttons removed
|
||||
expect(html).not.toContain('添加内容源')
|
||||
expect(html).not.toContain('管理员编辑')
|
||||
})
|
||||
it('lets an administrator bind the internal/external import knowledge bases from 系统设置', () => {
|
||||
// 组件一直在(RoutingBindingsSection),但从未挂到任何页面 —— 导入目标库只能靠
|
||||
// 部署 env 钉死,换库必须重建容器。
|
||||
const view = (section: 'sources' | 'bindings' | 'production-bindings') =>
|
||||
renderToStaticMarkup(
|
||||
<AuthContext.Provider value={authValue('admin')}>
|
||||
<SystemSettingsView
|
||||
sources={sources}
|
||||
connections={connections}
|
||||
monitor={monitor}
|
||||
settings={settings}
|
||||
productionEnabled={false}
|
||||
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage={null}
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
initialSection={section}
|
||||
/>
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
expect(view('sources')).toContain('测试知识库绑定')
|
||||
expect(view('sources')).toContain('生产知识库绑定')
|
||||
const bound = view('bindings')
|
||||
expect(bound).toContain('id="settings-routing-bindings"')
|
||||
expect(bound).toContain('分发到对应的测试 WeKnora 知识库')
|
||||
// 未读到绑定数据时(SSR 不跑 effect)面板也要如实存在,而不是空白。
|
||||
expect(bound).toContain('读取中…')
|
||||
// 发布目标(源库 → 目标库)是独立分区,与测试端收件库分开。
|
||||
const target = view('production-bindings')
|
||||
expect(target).toContain('id="settings-production-bindings"')
|
||||
expect(target).toContain('新发布的对内 / 对外内容按这里的绑定写入生产 WeKnora 的对应知识库')
|
||||
})
|
||||
it('does not show healthy simulation when the settings data failed to load', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SystemSettingsView
|
||||
sources={[]}
|
||||
connections={[]}
|
||||
monitor={null}
|
||||
settings={null}
|
||||
productionEnabled={false}
|
||||
routingCapabilities={{ internal_enabled: false, external_enabled: false }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error="加载失败"
|
||||
saveMessage={null}
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
)
|
||||
expect(html).toContain('加载失败')
|
||||
expect(html).not.toContain('模拟运行中')
|
||||
})
|
||||
it('renders the WeKnora cards and production channel from live probe and the real production gate', () => {
|
||||
const probed: MonitorOverview = {
|
||||
...monitor,
|
||||
health: [
|
||||
{
|
||||
key: 'weknora',
|
||||
name: 'WeKnora API',
|
||||
liveness: 'up',
|
||||
readiness: 'ready',
|
||||
reason: '',
|
||||
latency_ms: 86,
|
||||
observed_at: '2026-09-08T12:00:00Z',
|
||||
last_success_at: '2026-09-08T11:59:00Z',
|
||||
consecutive_failures: 0,
|
||||
configured: true,
|
||||
applicable: true,
|
||||
},
|
||||
{
|
||||
key: 'weknora-production',
|
||||
name: '生产 WeKnora',
|
||||
liveness: 'up',
|
||||
readiness: 'ready',
|
||||
reason: '',
|
||||
latency_ms: 41,
|
||||
observed_at: '2026-09-08T12:00:00Z',
|
||||
last_success_at: '2026-09-08T11:59:00Z',
|
||||
consecutive_failures: 0,
|
||||
configured: true,
|
||||
applicable: true,
|
||||
},
|
||||
{
|
||||
key: 'embedding',
|
||||
name: 'Embedding',
|
||||
liveness: 'up',
|
||||
readiness: 'not_applicable',
|
||||
reason: '未部署:本平台不使用该依赖',
|
||||
latency_ms: 0,
|
||||
observed_at: '2026-09-08T12:00:00Z',
|
||||
last_success_at: null,
|
||||
consecutive_failures: 0,
|
||||
configured: false,
|
||||
applicable: false,
|
||||
},
|
||||
],
|
||||
}
|
||||
const view = (enabled: boolean, verified: boolean) =>
|
||||
renderToStaticMarkup(
|
||||
<SystemSettingsView
|
||||
sources={sources}
|
||||
connections={connections}
|
||||
monitor={probed}
|
||||
settings={settings}
|
||||
productionEnabled={enabled}
|
||||
productionBackupRestoreVerified={verified}
|
||||
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage={null}
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
initialSection="services"
|
||||
/>
|
||||
)
|
||||
const on = view(true, true)
|
||||
expect(on).toContain('测试 WeKnora')
|
||||
expect(on).toContain('可达 · 可接单')
|
||||
expect(on).toContain('延迟 86ms')
|
||||
expect(on).toContain('已启用 · 可提交生产请求')
|
||||
expect(on).toContain('生产写入:开启')
|
||||
expect(on).toContain('发布目标与凭据:管理员受限配置')
|
||||
const off = view(false, false)
|
||||
expect(off).toContain('未启用')
|
||||
expect(off).toContain('生产写入:关闭')
|
||||
// 卡片状态由真实探测/门禁驱动,写死的“已连接 / 未连接 / 生产映射:未配置”必须消失。
|
||||
for (const removed of ['本地真实连接', '生产映射:未配置']) expect(off).not.toContain(removed)
|
||||
// 生产端点可达性来自真实探活,且只说真话:探活不等于验证过接单能力。
|
||||
expect(on).toContain('端点探测:端点可达 · 未做接单验证')
|
||||
const blocked = renderToStaticMarkup(
|
||||
<SystemSettingsView
|
||||
sources={sources}
|
||||
connections={connections}
|
||||
monitor={monitor}
|
||||
settings={settings}
|
||||
productionEnabled={true}
|
||||
productionBackupRestoreVerified={false}
|
||||
routingCapabilities={{ internal_enabled: false, external_enabled: false }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage={null}
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
initialSection="services"
|
||||
/>
|
||||
)
|
||||
expect(blocked).toContain('已启用 · 被阻断')
|
||||
// 未配置生产端点时必须显式说「未配置」,不得靠文案含糊过去。
|
||||
expect(blocked).toContain('端点探测:暂无真实探测结果')
|
||||
const unconfigured = renderToStaticMarkup(
|
||||
<SystemSettingsView
|
||||
sources={sources}
|
||||
connections={connections}
|
||||
monitor={{
|
||||
...monitor,
|
||||
health: [
|
||||
{
|
||||
key: 'weknora-production',
|
||||
name: '生产 WeKnora',
|
||||
liveness: 'unknown',
|
||||
readiness: 'not_configured',
|
||||
reason: '已部署但未配置探测参数',
|
||||
latency_ms: 0,
|
||||
observed_at: '2026-09-08T12:00:00Z',
|
||||
last_success_at: null,
|
||||
consecutive_failures: 0,
|
||||
configured: false,
|
||||
applicable: false,
|
||||
},
|
||||
],
|
||||
}}
|
||||
settings={settings}
|
||||
productionEnabled={false}
|
||||
routingCapabilities={{ internal_enabled: false, external_enabled: false }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage={null}
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
initialSection="services"
|
||||
/>
|
||||
)
|
||||
expect(unconfigured).toContain('端点探测:未配置')
|
||||
expect(unconfigured).not.toContain('端点可达')
|
||||
})
|
||||
})
|
||||
describe('SystemSettingsView 数据源配置的默认清单', () => {
|
||||
const withPP: SourceConnectionListItem[] = [
|
||||
{
|
||||
id: 'conn-pp',
|
||||
source_type: 'pp',
|
||||
name: 'PP资料下载中心',
|
||||
enabled: true,
|
||||
schedule_configured: true,
|
||||
health_status: 'healthy',
|
||||
item_count: 613,
|
||||
updated_at: '2026-09-09T09:30:32Z',
|
||||
next_refresh_at: null,
|
||||
},
|
||||
{
|
||||
id: 'conn-alist',
|
||||
source_type: 'alist',
|
||||
name: '国内工业',
|
||||
enabled: false,
|
||||
schedule_configured: false,
|
||||
health_status: 'unknown',
|
||||
item_count: 3027,
|
||||
updated_at: '2026-09-09T09:30:32Z',
|
||||
next_refresh_at: null,
|
||||
},
|
||||
{
|
||||
id: 'conn-ding2',
|
||||
source_type: 'dingtalk',
|
||||
name: 'ATOM知识库',
|
||||
enabled: false,
|
||||
schedule_configured: false,
|
||||
health_status: 'unknown',
|
||||
item_count: 109,
|
||||
updated_at: '2026-09-09T09:30:32Z',
|
||||
next_refresh_at: null,
|
||||
},
|
||||
]
|
||||
const view = (role: 'admin' | 'engineer' = 'admin') =>
|
||||
renderToStaticMarkup(
|
||||
<AuthContext.Provider value={authValue(role)}>
|
||||
<SystemSettingsView
|
||||
sources={[]}
|
||||
connections={withPP}
|
||||
monitor={monitor}
|
||||
settings={settings}
|
||||
productionEnabled={false}
|
||||
routingCapabilities={{ internal_enabled: true, external_enabled: true }}
|
||||
loading={false}
|
||||
saving={false}
|
||||
error={null}
|
||||
saveMessage={null}
|
||||
onSave={vi.fn()}
|
||||
onSourcesChanged={vi.fn()}
|
||||
onRefresh={vi.fn()}
|
||||
/>
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
it('只有两个入口:PP 来源列在 PP 导入下,AList/钉钉知识库/手工都不出现', () => {
|
||||
const html = view()
|
||||
expect(html).toContain('PP资料下载中心')
|
||||
expect(html).toContain('PP 资料下载中心')
|
||||
// 三个非 PP 来源一个都不该渲染,也没有任何折叠开关。
|
||||
for (const hidden of ['国内工业', 'ATOM知识库', '本地手工验收', '显示 AList', '折叠'])
|
||||
expect(html).not.toContain(hidden)
|
||||
expect(html).toContain('dws 导入(钉钉)')
|
||||
expect(html).toContain('PP 导入')
|
||||
expect(html).toContain('去掉来源</button>')
|
||||
expect(html).toContain('端点与凭据')
|
||||
// PP 来源的卡片操作照旧:改刷新周期、启停、看修订历史。
|
||||
for (const kept of ['查看修订历史', '保存并启用调度', '停用来源', '自动刷新周期']) expect(html).toContain(kept)
|
||||
for (const removed of ['+ 新增钉钉知识库', '文件格式筛选']) expect(html).not.toContain(removed)
|
||||
// 文档工程师看不到 dws 导入面板与「去掉来源」:两者都是管理员动作。
|
||||
const engineer = view('engineer')
|
||||
expect(engineer).not.toContain('dws 导入(钉钉)')
|
||||
expect(engineer).not.toContain('去掉来源</button>')
|
||||
expect(engineer).toContain('PP 导入')
|
||||
})
|
||||
})
|
||||
describe('ppSourceConnections(数据源配置的清单规则)', () => {
|
||||
const rows: SourceConnectionListItem[] = [
|
||||
{
|
||||
id: 'a',
|
||||
source_type: 'pp',
|
||||
name: 'PP资料下载中心',
|
||||
enabled: true,
|
||||
schedule_configured: true,
|
||||
health_status: 'healthy',
|
||||
item_count: 1,
|
||||
updated_at: '2026-09-09T09:30:32Z',
|
||||
next_refresh_at: null,
|
||||
},
|
||||
{
|
||||
id: 'b',
|
||||
source_type: 'alist',
|
||||
name: '国内工业',
|
||||
enabled: false,
|
||||
schedule_configured: false,
|
||||
health_status: 'unknown',
|
||||
item_count: 2,
|
||||
updated_at: '2026-09-09T09:30:32Z',
|
||||
next_refresh_at: null,
|
||||
},
|
||||
{
|
||||
id: 'c',
|
||||
source_type: 'dingtalk',
|
||||
name: 'ATOM知识库',
|
||||
enabled: false,
|
||||
schedule_configured: false,
|
||||
health_status: 'unknown',
|
||||
item_count: 3,
|
||||
updated_at: '2026-09-09T09:30:32Z',
|
||||
next_refresh_at: null,
|
||||
},
|
||||
{
|
||||
id: 'd',
|
||||
source_type: 'manual',
|
||||
name: '本地手工验收',
|
||||
enabled: false,
|
||||
schedule_configured: false,
|
||||
health_status: 'unknown',
|
||||
item_count: 4,
|
||||
updated_at: '2026-09-09T09:30:32Z',
|
||||
next_refresh_at: null,
|
||||
},
|
||||
{
|
||||
id: 'e',
|
||||
source_type: 'pp',
|
||||
name: 'PP legacy',
|
||||
enabled: false,
|
||||
schedule_configured: false,
|
||||
health_status: 'unknown',
|
||||
item_count: 5,
|
||||
updated_at: '2026-09-09T09:30:32Z',
|
||||
next_refresh_at: null,
|
||||
},
|
||||
]
|
||||
it('只放行 PP 来源,顺序不变,其余类型一条都不放行', () => {
|
||||
expect(ppSourceConnections(rows).map((item) => item.id)).toEqual(['a', 'e'])
|
||||
expect(ppSourceConnections([])).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
+680
-121
@@ -12,9 +12,22 @@ import type { MonitorOverview } from './monitor'
|
||||
import { fetchReleaseCapabilities } from './reviewRelease'
|
||||
import { fetchCatalogRoutingCapabilities, fetchCatalogSources } from './sourceCatalog'
|
||||
import type { CatalogRoutingCapabilities, CatalogSource } from './sourceCatalog'
|
||||
import { activateSourceSettingsRevision, createSourceSettingsRevision, fetchSourceConnectionList, fetchSourceSettingsRevisions } from './sourceConnections'
|
||||
import {
|
||||
activateSourceSettingsRevision,
|
||||
archiveSourceConnection,
|
||||
createSourceSettingsRevision,
|
||||
fetchSourceConnectionList,
|
||||
fetchSourceSettingsRevisions,
|
||||
} from './sourceConnections'
|
||||
import type { SourceConnectionListItem, SourceSettingsRevision } from './sourceConnections'
|
||||
import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings, validKnowledgeBaseID, validProductionTenantID, validServiceEndpoint } from './uiSettings'
|
||||
import {
|
||||
activateUISettings,
|
||||
createUISettingsCandidate,
|
||||
fetchActiveUISettings,
|
||||
validKnowledgeBaseID,
|
||||
validProductionTenantID,
|
||||
validServiceEndpoint,
|
||||
} from './uiSettings'
|
||||
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
|
||||
import './systemSettings.css'
|
||||
|
||||
@@ -48,17 +61,37 @@ const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [
|
||||
{ key: 'members', label: '成员与角色', adminOnly: true },
|
||||
] as { key: SectionKey; label: string; adminOnly?: boolean }[]
|
||||
|
||||
const sourceTypeLabels: Record<string, string> = { dingtalk: '钉钉知识库', pp: 'PP 资料下载中心', alist: 'AList 文件源', manual: '本地手工导入' }
|
||||
const sourceAuthLabels: Record<string, string> = { dingtalk: '专用浏览器扫码会话', pp: '公开只读访问', alist: '直连 API Token', manual: '离线导入,无在线认证' }
|
||||
const secondsLabel = (value: number) => value < 60 ? `${value}秒` : value < 3600 ? `${value / 60}分钟` : `${value / 3600}小时`
|
||||
export const visibleSaveMessage = (message: string | null, dirty: boolean) => dirty ? null : message
|
||||
const sourceTypeLabels: Record<string, string> = {
|
||||
dingtalk: '钉钉知识库',
|
||||
pp: 'PP 资料下载中心',
|
||||
alist: 'AList 文件源',
|
||||
manual: '本地手工导入',
|
||||
}
|
||||
|
||||
// 「数据源配置」只保留两个入口:**dws 导入**(按当前钉钉账号发现知识库与钉盘空间)
|
||||
// 与 **PP 导入**。AList 已由钉盘文件替代、钉钉知识库一律走当前账号发现、本地手工与
|
||||
// PP legacy 也下架了:本页只列 PP 来源。下架用归档(archived_at)实现,不删数据 ——
|
||||
// 需要时用 dws 重新登记同名来源即原地复活(见 postgres.RegisterDingtalkSpace)。
|
||||
export const ppSourceConnections = (connections: SourceConnectionListItem[]) =>
|
||||
connections.filter((item) => item.source_type === 'pp')
|
||||
|
||||
const sourceAuthLabels: Record<string, string> = {
|
||||
dingtalk: '专用浏览器扫码会话',
|
||||
pp: '公开只读访问',
|
||||
alist: '直连 API Token',
|
||||
manual: '离线导入,无在线认证',
|
||||
}
|
||||
const secondsLabel = (value: number) =>
|
||||
value < 60 ? `${value}秒` : value < 3600 ? `${value / 60}分钟` : `${value / 3600}小时`
|
||||
export const visibleSaveMessage = (message: string | null, dirty: boolean) => (dirty ? null : message)
|
||||
|
||||
type ServiceHealthView = MonitorOverview['health'][number]
|
||||
type ServiceView = MonitorOverview['services'][number]
|
||||
|
||||
// 服务配置只保留四项可写值(测试地址、生产地址、生产 ID、知识库 ID),
|
||||
// 依赖与解析队列的状态仍按真实探测呈现,不写死。
|
||||
const findHealth = (monitor: MonitorOverview | null, name: string): ServiceHealthView | undefined => (monitor?.health || []).find((item) => item.name === name || item.name.startsWith(name))
|
||||
const findHealth = (monitor: MonitorOverview | null, name: string): ServiceHealthView | undefined =>
|
||||
(monitor?.health || []).find((item) => item.name === name || item.name.startsWith(name))
|
||||
export const healthStateLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
|
||||
if (!health) {
|
||||
if (!service) return '待配置'
|
||||
@@ -71,7 +104,9 @@ export const healthStateLabel = (health: ServiceHealthView | undefined, service:
|
||||
}
|
||||
export const healthStateDetail = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => {
|
||||
if (!health) return service?.detail || '真实 Provider 未接入'
|
||||
const success = health.last_success_at ? `最近成功 ${new Date(health.last_success_at).toLocaleTimeString('zh-CN', { hour12: false })}` : ''
|
||||
const success = health.last_success_at
|
||||
? `最近成功 ${new Date(health.last_success_at).toLocaleTimeString('zh-CN', { hour12: false })}`
|
||||
: ''
|
||||
if (health.readiness === 'ready') return [`延迟 ${health.latency_ms}ms`, success].filter(Boolean).join(';')
|
||||
const failures = health.consecutive_failures ? `连续失败${health.consecutive_failures}次` : ''
|
||||
return [health.reason, success, failures].filter(Boolean).join(';')
|
||||
@@ -84,7 +119,12 @@ export const productionWeKnoraProbe = (monitor: MonitorOverview | null): string
|
||||
const health = findHealth(monitor, '生产 WeKnora')
|
||||
if (!health) return '端点探测:暂无真实探测结果'
|
||||
if (!health.configured) return '端点探测:未配置'
|
||||
const label = health.liveness === 'up' ? (health.readiness === 'ready' ? '端点可达 · 未做接单验证' : '端点可达 · 不可接单') : '端点不可达'
|
||||
const label =
|
||||
health.liveness === 'up'
|
||||
? health.readiness === 'ready'
|
||||
? '端点可达 · 未做接单验证'
|
||||
: '端点可达 · 不可接单'
|
||||
: '端点不可达'
|
||||
const detail = healthStateDetail(health, undefined)
|
||||
return `端点探测:${label}${detail ? `(${detail})` : ''}`
|
||||
}
|
||||
@@ -103,7 +143,13 @@ function formatHorizon(value: string | null): string {
|
||||
return `下次自动刷新 ${at.toLocaleString('zh-CN', { hour12: false })}`
|
||||
}
|
||||
|
||||
function SourceSettingsCard({ connection, onSourcesChanged }: { connection: SourceConnectionListItem; onSourcesChanged: () => void }) {
|
||||
function SourceSettingsCard({
|
||||
connection,
|
||||
onSourcesChanged,
|
||||
}: {
|
||||
connection: SourceConnectionListItem
|
||||
onSourcesChanged: () => void
|
||||
}) {
|
||||
const auth = useOptionalAuth()
|
||||
const isAdmin = auth?.identity?.role === 'admin'
|
||||
const [interval, setInterval] = useState<number>(() => {
|
||||
@@ -118,18 +164,45 @@ function SourceSettingsCard({ connection, onSourcesChanged }: { connection: Sour
|
||||
const [showHistory, setShowHistory] = useState(false)
|
||||
const [history, setHistory] = useState<SourceSettingsRevision[] | null>(null)
|
||||
const [pendingDisable, setPendingDisable] = useState(false)
|
||||
// 「去掉来源」= 归档下架:先弹确认,再调后端(后端会再校验一次管理员权限)。
|
||||
const [pendingArchive, setPendingArchive] = useState(false)
|
||||
const scheduled = connection.source_type !== 'manual'
|
||||
|
||||
// 归档下架:来源从列表、目录、调度与扫描里消失,但数据不删;重新登记同一来源即复活。
|
||||
const archive = async () => {
|
||||
setBusy(true)
|
||||
setFailure(null)
|
||||
setMessage(null)
|
||||
try {
|
||||
await archiveSourceConnection(connection.id)
|
||||
setMessage(`「${connection.name}」已归档下架:列表、来源与目录、计划刷新里都不再出现,数据保留可恢复。`)
|
||||
setPendingArchive(false)
|
||||
onSourcesChanged()
|
||||
} catch (cause) {
|
||||
setFailure(cause instanceof Error ? cause.message : '去掉来源失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const submit = async (nextEnabled: boolean) => {
|
||||
setBusy(true); setMessage(null); setFailure(null)
|
||||
setBusy(true)
|
||||
setMessage(null)
|
||||
setFailure(null)
|
||||
try {
|
||||
const draft = {
|
||||
source_type: connection.source_type, name: connection.name, endpoint: '', credential_ref: '',
|
||||
enabled: nextEnabled, schedule: { refresh_interval_seconds: nextEnabled && interval > 0 ? interval : null },
|
||||
source_type: connection.source_type,
|
||||
name: connection.name,
|
||||
endpoint: '',
|
||||
credential_ref: '',
|
||||
enabled: nextEnabled,
|
||||
schedule: { refresh_interval_seconds: nextEnabled && interval > 0 ? interval : null },
|
||||
}
|
||||
const created = await createSourceSettingsRevision(connection.id, draft)
|
||||
const activated = await activateSourceSettingsRevision(connection.id, created.id)
|
||||
setMessage(`${connection.name}:调度设置已验证并启用${activated.operation === 'replayed' ? '(沿用上次结果)' : ''};${nextEnabled ? formatHorizon(new Date(Date.now() + interval * 1000).toISOString()) : '已停用,新的自动扫描与刷新任务不再入队,历史记录全部保留'}。`)
|
||||
setMessage(
|
||||
`${connection.name}:调度设置已验证并启用${activated.operation === 'replayed' ? '(沿用上次结果)' : ''};${nextEnabled ? formatHorizon(new Date(Date.now() + interval * 1000).toISOString()) : '已停用,新的自动扫描与刷新任务不再入队,历史记录全部保留'}。`
|
||||
)
|
||||
onSourcesChanged()
|
||||
} catch (cause) {
|
||||
setFailure(cause instanceof Error ? cause.message : '保存来源设置失败')
|
||||
@@ -142,42 +215,177 @@ function SourceSettingsCard({ connection, onSourcesChanged }: { connection: Sour
|
||||
const loadHistory = async () => {
|
||||
setShowHistory(true)
|
||||
if (history) return
|
||||
try { setHistory(await fetchSourceSettingsRevisions(connection.id)) }
|
||||
catch (cause) { setFailure(cause instanceof Error ? cause.message : '加载修订历史失败') }
|
||||
try {
|
||||
setHistory(await fetchSourceSettingsRevisions(connection.id))
|
||||
} catch (cause) {
|
||||
setFailure(cause instanceof Error ? cause.message : '加载修订历史失败')
|
||||
}
|
||||
}
|
||||
|
||||
const canApply = !busy
|
||||
|
||||
return <article className="settings-source-row">
|
||||
<div className="settings-source-name"><strong>{connection.name}</strong><span>{sourceTypeLabels[connection.source_type] ?? connection.source_type}{connection.enabled ? '' : ' · 已停用'}</span></div>
|
||||
<dl>
|
||||
<div><dt>认证方式</dt><dd>{sourceAuthLabels[connection.source_type] ?? '按连接配置'}</dd></div>
|
||||
<div><dt>端点与凭据</dt><dd>已保存,不可回读(草稿留空即沿用现值)</dd></div>
|
||||
<div><dt>当前调度</dt><dd>{connection.enabled ? formatHorizon(connection.next_refresh_at) : '停用中(不入队)'}</dd></div>
|
||||
</dl>
|
||||
<div className="source-schedule-form">
|
||||
{scheduled ? <label>自动刷新周期<select value={interval} onChange={(event) => setInterval(Number(event.target.value))}>{intervalChoices.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}</select></label>
|
||||
: <small className="manual-source-note">本地手工导入来源不支持定时刷新,只能手动触发扫描。</small>}
|
||||
{connection.enabled
|
||||
? <div className="source-schedule-actions"><button className="secondary" disabled={!canApply || (scheduled && interval === 0 && !connection.schedule_configured)} onClick={() => void submit(true)}>{busy ? '正在验证并启用…' : '保存并启用调度'}</button>
|
||||
<button className="danger" disabled={!canApply} onClick={() => setPendingDisable(true)}>停用来源</button></div>
|
||||
: <div className="source-schedule-actions"><button className="secondary" disabled={!canApply} onClick={() => void submit(true)}>保存并启用</button></div>}
|
||||
{connection.source_type === "dingtalk" && isAdmin ? <DingtalkSessionControl /> : null}
|
||||
<button className="link" onClick={() => void loadHistory()}>{showHistory ? '收起修订历史' : '查看修订历史'}</button>
|
||||
</div>
|
||||
{message ? <p className="success-message" role="status">{message}</p> : null}
|
||||
{failure ? <p className="error-message" role="alert">{failure}</p> : null}
|
||||
{showHistory && history ? <ul className="revision-list">{history.map((item) => <li key={item.id}><b>修订 {item.revision_number}</b><span>{item.state === 'active' ? '当前启用' : item.state === 'validated' ? '待启用' : item.state === 'retired' ? '已退休' : '失败'}</span><small>{item.created_by} · {new Date(item.created_at).toLocaleString('zh-CN', { hour12: false })} · {item.refresh_interval_seconds ? `每${secondsLabel(Number(item.refresh_interval_seconds))}` : '仅手动'}</small></li>)}</ul> : null}
|
||||
{showHistory && !history ? <small>正在加载修订历史…</small> : null}
|
||||
{pendingDisable ? <div className="modal-backdrop" role="dialog" aria-modal="true"><div className="modal-card">
|
||||
<h3>停用「{connection.name}」?</h3>
|
||||
<p>停用会立即停止该来源的自动扫描与新刷新任务入队;历史快照、标注和审计全部保留,随时可以重新启用。此操作会先由后端再次校验权限。</p>
|
||||
<div className="modal-actions"><button className="danger" disabled={busy} onClick={() => void submit(false)}>{busy ? '正在停用…' : '确认停用'}</button><button className="secondary" disabled={busy} onClick={() => setPendingDisable(false)}>取消</button></div>
|
||||
</div></div> : null}
|
||||
</article>
|
||||
return (
|
||||
<article className="settings-source-row">
|
||||
<div className="settings-source-name">
|
||||
<strong>{connection.name}</strong>
|
||||
<span>
|
||||
{sourceTypeLabels[connection.source_type] ?? connection.source_type}
|
||||
{connection.enabled ? '' : ' · 已停用'}
|
||||
</span>
|
||||
</div>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>认证方式</dt>
|
||||
<dd>{sourceAuthLabels[connection.source_type] ?? '按连接配置'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>端点与凭据</dt>
|
||||
<dd>已保存,不可回读(草稿留空即沿用现值)</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>当前调度</dt>
|
||||
<dd>{connection.enabled ? formatHorizon(connection.next_refresh_at) : '停用中(不入队)'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div className="source-schedule-form">
|
||||
{scheduled ? (
|
||||
<label>
|
||||
自动刷新周期
|
||||
<select value={interval} onChange={(event) => setInterval(Number(event.target.value))}>
|
||||
{intervalChoices.map((choice) => (
|
||||
<option key={choice.value} value={choice.value}>
|
||||
{choice.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
) : (
|
||||
<small className="manual-source-note">本地手工导入来源不支持定时刷新,只能手动触发扫描。</small>
|
||||
)}
|
||||
{connection.enabled ? (
|
||||
<div className="source-schedule-actions">
|
||||
<button
|
||||
className="secondary"
|
||||
disabled={!canApply || (scheduled && interval === 0 && !connection.schedule_configured)}
|
||||
onClick={() => void submit(true)}
|
||||
>
|
||||
{busy ? '正在验证并启用…' : '保存并启用调度'}
|
||||
</button>
|
||||
<button className="danger" disabled={!canApply} onClick={() => setPendingDisable(true)}>
|
||||
停用来源
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="source-schedule-actions">
|
||||
<button className="secondary" disabled={!canApply} onClick={() => void submit(true)}>
|
||||
保存并启用
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{connection.source_type === 'dingtalk' && isAdmin ? <DingtalkSessionControl /> : null}
|
||||
<div className="source-schedule-links">
|
||||
<button className="link" onClick={() => void loadHistory()}>
|
||||
{showHistory ? '收起修订历史' : '查看修订历史'}
|
||||
</button>
|
||||
{isAdmin ? (
|
||||
<button className="link danger" disabled={busy} onClick={() => setPendingArchive(true)}>
|
||||
去掉来源
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
{message ? (
|
||||
<p className="success-message" role="status">
|
||||
{message}
|
||||
</p>
|
||||
) : null}
|
||||
{failure ? (
|
||||
<p className="error-message" role="alert">
|
||||
{failure}
|
||||
</p>
|
||||
) : null}
|
||||
{showHistory && history ? (
|
||||
<ul className="revision-list">
|
||||
{history.map((item) => (
|
||||
<li key={item.id}>
|
||||
<b>修订 {item.revision_number}</b>
|
||||
<span>
|
||||
{item.state === 'active'
|
||||
? '当前启用'
|
||||
: item.state === 'validated'
|
||||
? '待启用'
|
||||
: item.state === 'retired'
|
||||
? '已退休'
|
||||
: '失败'}
|
||||
</span>
|
||||
<small>
|
||||
{item.created_by} · {new Date(item.created_at).toLocaleString('zh-CN', { hour12: false })} ·{' '}
|
||||
{item.refresh_interval_seconds ? `每${secondsLabel(Number(item.refresh_interval_seconds))}` : '仅手动'}
|
||||
</small>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
{showHistory && !history ? <small>正在加载修订历史…</small> : null}
|
||||
{pendingDisable ? (
|
||||
<div className="modal-backdrop" role="dialog" aria-modal="true">
|
||||
<div className="modal-card">
|
||||
<h3>停用「{connection.name}」?</h3>
|
||||
<p>
|
||||
停用会立即停止该来源的自动扫描与新刷新任务入队;历史快照、标注和审计全部保留,随时可以重新启用。此操作会先由后端再次校验权限。
|
||||
</p>
|
||||
<div className="modal-actions">
|
||||
<button className="danger" disabled={busy} onClick={() => void submit(false)}>
|
||||
{busy ? '正在停用…' : '确认停用'}
|
||||
</button>
|
||||
<button className="secondary" disabled={busy} onClick={() => setPendingDisable(false)}>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{pendingArchive ? (
|
||||
<div className="modal-backdrop" role="dialog" aria-modal="true">
|
||||
<div className="modal-card">
|
||||
<h3>去掉「{connection.name}」?</h3>
|
||||
<p>
|
||||
去掉 =
|
||||
归档下架:该来源会从数据源配置、来源与目录、计划刷新与手动扫描里摘掉。目录快照、发布记录与审计数据全部保留,
|
||||
随时可恢复(用 dws 重新登记同一来源即原地复活)。此操作会先由后端再次校验管理员权限。
|
||||
</p>
|
||||
<div className="modal-actions">
|
||||
<button className="danger" disabled={busy} onClick={() => void archive()}>
|
||||
{busy ? '正在归档…' : '确认去掉'}
|
||||
</button>
|
||||
<button className="secondary" disabled={busy} onClick={() => setPendingArchive(false)}>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
)
|
||||
}
|
||||
|
||||
export function SystemSettingsView({ sources, connections, monitor, settings, productionEnabled, productionBackupRestoreVerified = false, routingCapabilities, loading, saving, error, saveMessage, onSave, onSourcesChanged, onRefresh, initialSection = 'sources' }: Props) {
|
||||
export function SystemSettingsView({
|
||||
sources,
|
||||
connections,
|
||||
monitor,
|
||||
settings,
|
||||
productionEnabled,
|
||||
productionBackupRestoreVerified = false,
|
||||
routingCapabilities,
|
||||
loading,
|
||||
saving,
|
||||
error,
|
||||
saveMessage,
|
||||
onSave,
|
||||
onSourcesChanged,
|
||||
onRefresh,
|
||||
initialSection = 'sources',
|
||||
}: Props) {
|
||||
const auth = useOptionalAuth()
|
||||
const identity = auth?.identity ?? null
|
||||
const [section, setSection] = useState<SectionKey>(initialSection)
|
||||
@@ -189,9 +397,14 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
|
||||
const [endpoint, setEndpoint] = useState<string>(settings?.production_weknora_base_url ?? '')
|
||||
const [testEndpoint, setTestEndpoint] = useState<string>(settings?.test_weknora_base_url ?? '')
|
||||
const [productionTenantID, setProductionTenantID] = useState<string>(settings?.production_tenant_id ?? '')
|
||||
const [productionKnowledgeBaseID, setProductionKnowledgeBaseID] = useState<string>(settings?.production_knowledge_base_id ?? '')
|
||||
const [productionKnowledgeBaseID, setProductionKnowledgeBaseID] = useState<string>(
|
||||
settings?.production_knowledge_base_id ?? ''
|
||||
)
|
||||
const [dirty, setDirty] = useState(false)
|
||||
|
||||
// 本页只列 PP 来源;dws 导入由下面的发现面板负责(其余类型已归档下架,未删除)。
|
||||
const ppConnections = ppSourceConnections(connections)
|
||||
|
||||
useEffect(() => {
|
||||
if (!settings) return
|
||||
setDocumentRefresh(settings.document_refresh_seconds)
|
||||
@@ -212,76 +425,367 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
|
||||
const testEndpointValid = validServiceEndpoint(testEndpoint)
|
||||
const productionTenantIDValid = validProductionTenantID(productionTenantID)
|
||||
const productionKnowledgeBaseIDValid = validKnowledgeBaseID(productionKnowledgeBaseID)
|
||||
const serviceSettingsValid = endpointValid && testEndpointValid && productionTenantIDValid && productionKnowledgeBaseIDValid
|
||||
const serviceSettingsDirty = Boolean(settings && (
|
||||
testEndpoint.trim() !== settings.test_weknora_base_url ||
|
||||
endpoint.trim() !== settings.production_weknora_base_url ||
|
||||
productionTenantID.trim() !== settings.production_tenant_id ||
|
||||
productionKnowledgeBaseID.trim() !== settings.production_knowledge_base_id))
|
||||
const serviceSettingsValid =
|
||||
endpointValid && testEndpointValid && productionTenantIDValid && productionKnowledgeBaseIDValid
|
||||
const serviceSettingsDirty = Boolean(
|
||||
settings &&
|
||||
(testEndpoint.trim() !== settings.test_weknora_base_url ||
|
||||
endpoint.trim() !== settings.production_weknora_base_url ||
|
||||
productionTenantID.trim() !== settings.production_tenant_id ||
|
||||
productionKnowledgeBaseID.trim() !== settings.production_knowledge_base_id)
|
||||
)
|
||||
const candidateInput = (overrides: Partial<UISettingsCandidateInput> = {}): UISettingsCandidateInput => ({
|
||||
document_refresh_seconds: documentRefresh, resource_refresh_seconds: resourceRefresh,
|
||||
stalled_after_seconds: stalled, finalizing_after_seconds: finalizing, ingestion_concurrency: concurrency,
|
||||
test_weknora_base_url: testEndpoint.trim(), production_weknora_base_url: endpoint.trim(),
|
||||
production_tenant_id: productionTenantID.trim(), production_knowledge_base_id: productionKnowledgeBaseID.trim(), ...overrides,
|
||||
document_refresh_seconds: documentRefresh,
|
||||
resource_refresh_seconds: resourceRefresh,
|
||||
stalled_after_seconds: stalled,
|
||||
finalizing_after_seconds: finalizing,
|
||||
ingestion_concurrency: concurrency,
|
||||
test_weknora_base_url: testEndpoint.trim(),
|
||||
production_weknora_base_url: endpoint.trim(),
|
||||
production_tenant_id: productionTenantID.trim(),
|
||||
production_knowledge_base_id: productionKnowledgeBaseID.trim(),
|
||||
...overrides,
|
||||
})
|
||||
const saveEndpoint = () => { setDirty(false); onSave(candidateInput()) }
|
||||
return <main className="page-shell system-settings">
|
||||
<header className="hero compact"><div><h1>系统设置</h1><p className="subtitle">查看内容源、服务与备份状态;来源调度与刷新参数采用版本化保存。</p></div><button onClick={onRefresh} disabled={loading}>{loading ? '刷新中…' : '刷新状态'}</button></header>
|
||||
{error ? <div className="error-banner" role="alert">{error}</div> : null}
|
||||
{monitor && settings ? <div className="settings-layout">
|
||||
<nav className="settings-nav" aria-label="系统设置分区">{sections.filter((item) => !item.adminOnly || identity?.role === 'admin').map((item) => <button key={item.key} className={section === item.key ? 'active' : ''} onClick={() => setSection(item.key)}>{item.label}</button>)}</nav>
|
||||
<div className="settings-content">
|
||||
<div className="settings-role-strip"><span className="engineer-role">文档工程师可调整:来源调度周期、刷新间隔、停滞判断</span><span className="admin-role">管理员设置已锁定:端点、凭据、映射、生产开关</span></div>
|
||||
<div className="simulation-banner server-settings-banner"><strong>设置服务已启用</strong><span>当前活动版本 · 启用人 {settings.updated_by} · 启用时间 {settings.activated_at ? new Date(settings.activated_at).toLocaleString('zh-CN') : '待激活'};新设置先验证,再原子切换。</span></div>
|
||||
{section === 'sources' ? <section className="settings-panel wide source-settings-panel" id="settings-sources">
|
||||
<div className="settings-section-heading"><div><h2>数据源配置</h2><p>从下方「可加入的来源」勾选即可登记新来源;逐来源设置自动刷新周期或保持仅手动,保存会先生成修订、验证后原子启用。</p></div></div>
|
||||
{identity?.role === 'admin' ? <DingtalkSourceDiscovery registeredNames={connections.map((item) => item.name)} onRegistered={onSourcesChanged} /> : null}
|
||||
{connections.length ? <div className="settings-source-list">
|
||||
{connections.map((connection) => <SourceSettingsCard key={connection.id} connection={connection} onSourcesChanged={onSourcesChanged}/>)}
|
||||
{sources.length ? null : <small className="empty-inline">尚无快照数据;快照将在来源首次刷新完成后出现。</small>}
|
||||
</div> : <div className="empty-state">尚无可显示的来源连接。</div>}
|
||||
</section> : null}
|
||||
{section === 'services' ? <section className="settings-panel wide" id="settings-services">
|
||||
<div className="settings-section-heading"><div><h2>服务配置</h2><p>只配四项:测试地址、生产地址、生产 ID、知识库 ID。保存会先生成修订、验证后原子启用,旧版本保留用于审计;凭据只写不读。</p></div></div>
|
||||
<div className="environment-cards"><article><b>测试 WeKnora</b><span>{healthStateLabel(findHealth(monitor, 'WeKnora API'), undefined)}</span><small>{`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${routingCapabilities.internal_enabled ? '已配置' : '未配置'} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`}</small></article><article className="production"><b>生产 WeKnora</b><span>{!productionEnabled ? '未启用' : productionBackupRestoreVerified ? '已启用 · 可提交生产请求' : '已启用 · 被阻断'}</span><small>{`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'};发布目标与凭据:管理员受限配置,本页不可回读`}</small></article></div>
|
||||
<div className="safe-setting-grid production-endpoint-form">
|
||||
{isAdmin ? <>
|
||||
<label>测试地址<input value={testEndpoint} onChange={(event) => { setTestEndpoint(event.target.value); setDirty(true) }} placeholder="https://weknora.test.example" aria-invalid={!testEndpointValid} /></label>
|
||||
<label>生产地址<input value={endpoint} onChange={(event) => { setEndpoint(event.target.value); setDirty(true) }} placeholder="https://weknora.prod.example" aria-invalid={!endpointValid} /></label>
|
||||
<label>生产 ID<input value={productionTenantID} onChange={(event) => { setProductionTenantID(event.target.value); setDirty(true) }} placeholder="10000" aria-invalid={!productionTenantIDValid} /></label>
|
||||
<label>知识库 ID<input value={productionKnowledgeBaseID} onChange={(event) => { setProductionKnowledgeBaseID(event.target.value); setDirty(true) }} placeholder="生产知识库 ID" aria-invalid={!productionKnowledgeBaseIDValid} /></label>
|
||||
</> : <>
|
||||
<label>测试地址<input value={settings.test_weknora_base_url || '未配置'} readOnly disabled /></label>
|
||||
<label>生产地址<input value={settings.production_weknora_base_url || '未配置'} readOnly disabled /></label>
|
||||
<label>生产 ID<input value={settings.production_tenant_id || '未配置'} readOnly disabled /></label>
|
||||
<label>知识库 ID<input value={settings.production_knowledge_base_id || '未配置'} readOnly disabled /></label>
|
||||
</>}
|
||||
const saveEndpoint = () => {
|
||||
setDirty(false)
|
||||
onSave(candidateInput())
|
||||
}
|
||||
return (
|
||||
<main className="page-shell system-settings">
|
||||
<header className="hero compact">
|
||||
<div>
|
||||
<h1>系统设置</h1>
|
||||
<p className="subtitle">查看内容源、服务与备份状态;来源调度与刷新参数采用版本化保存。</p>
|
||||
</div>
|
||||
<button onClick={onRefresh} disabled={loading}>
|
||||
{loading ? '刷新中…' : '刷新状态'}
|
||||
</button>
|
||||
</header>
|
||||
{error ? (
|
||||
<div className="error-banner" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
{monitor && settings ? (
|
||||
<div className="settings-layout">
|
||||
<nav className="settings-nav" aria-label="系统设置分区">
|
||||
{sections
|
||||
.filter((item) => !item.adminOnly || identity?.role === 'admin')
|
||||
.map((item) => (
|
||||
<button
|
||||
key={item.key}
|
||||
className={section === item.key ? 'active' : ''}
|
||||
onClick={() => setSection(item.key)}
|
||||
>
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
<div className="settings-content">
|
||||
<div className="settings-role-strip">
|
||||
<span className="engineer-role">文档工程师可调整:来源调度周期、刷新间隔、停滞判断</span>
|
||||
<span className="admin-role">管理员设置已锁定:端点、凭据、映射、生产开关</span>
|
||||
</div>
|
||||
<div className="simulation-banner server-settings-banner">
|
||||
<strong>设置服务已启用</strong>
|
||||
<span>
|
||||
当前活动版本 · 启用人 {settings.updated_by} · 启用时间{' '}
|
||||
{settings.activated_at ? new Date(settings.activated_at).toLocaleString('zh-CN') : '待激活'}
|
||||
;新设置先验证,再原子切换。
|
||||
</span>
|
||||
</div>
|
||||
{section === 'sources' ? (
|
||||
<section className="settings-panel wide source-settings-panel" id="settings-sources">
|
||||
<div className="settings-section-heading">
|
||||
<div>
|
||||
<h2>数据源配置</h2>
|
||||
<p>
|
||||
只留两个入口:<strong>dws 导入</strong>(按当前钉钉账号列出可访问的知识库与钉盘空间)与
|
||||
<strong>PP 导入</strong>。逐来源设置自动刷新周期或保持仅手动,保存会先生成修订、验证后原子启用。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{identity?.role === 'admin' ? (
|
||||
<DingtalkSourceDiscovery
|
||||
registeredNames={connections.map((item) => item.name)}
|
||||
onRegistered={onSourcesChanged}
|
||||
/>
|
||||
) : null}
|
||||
<div className="settings-source-group" id="settings-sources-pp">
|
||||
<div className="settings-section-heading sub">
|
||||
<div>
|
||||
<h3>PP 导入</h3>
|
||||
<p>
|
||||
公开只读的 PP 资料下载中心。这里的「去掉来源」是归档下架:从列表、来源与目录、计划刷新里摘掉,
|
||||
但目录快照与发布记录不删,随时可恢复。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{ppConnections.length ? (
|
||||
<div className="settings-source-list">
|
||||
{ppConnections.map((connection) => (
|
||||
<SourceSettingsCard
|
||||
key={connection.id}
|
||||
connection={connection}
|
||||
onSourcesChanged={onSourcesChanged}
|
||||
/>
|
||||
))}
|
||||
{sources.length ? null : (
|
||||
<small className="empty-inline">尚无快照数据;快照将在来源首次刷新完成后出现。</small>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="empty-state">本页只列 PP 来源;现在还没有已接入的 PP 来源。</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
{section === 'services' ? (
|
||||
<section className="settings-panel wide" id="settings-services">
|
||||
<div className="settings-section-heading">
|
||||
<div>
|
||||
<h2>服务配置</h2>
|
||||
<p>
|
||||
只配四项:测试地址、生产地址、生产 ID、知识库
|
||||
ID。保存会先生成修订、验证后原子启用,旧版本保留用于审计;凭据只写不读。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="environment-cards">
|
||||
<article>
|
||||
<b>测试 WeKnora</b>
|
||||
<span>{healthStateLabel(findHealth(monitor, 'WeKnora API'), undefined)}</span>
|
||||
<small>{`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${routingCapabilities.internal_enabled ? '已配置' : '未配置'} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`}</small>
|
||||
</article>
|
||||
<article className="production">
|
||||
<b>生产 WeKnora</b>
|
||||
<span>
|
||||
{!productionEnabled
|
||||
? '未启用'
|
||||
: productionBackupRestoreVerified
|
||||
? '已启用 · 可提交生产请求'
|
||||
: '已启用 · 被阻断'}
|
||||
</span>
|
||||
<small>{`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'};发布目标与凭据:管理员受限配置,本页不可回读`}</small>
|
||||
</article>
|
||||
</div>
|
||||
<div className="safe-setting-grid production-endpoint-form">
|
||||
{isAdmin ? (
|
||||
<>
|
||||
<label>
|
||||
测试地址
|
||||
<input
|
||||
value={testEndpoint}
|
||||
onChange={(event) => {
|
||||
setTestEndpoint(event.target.value)
|
||||
setDirty(true)
|
||||
}}
|
||||
placeholder="https://weknora.test.example"
|
||||
aria-invalid={!testEndpointValid}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
生产地址
|
||||
<input
|
||||
value={endpoint}
|
||||
onChange={(event) => {
|
||||
setEndpoint(event.target.value)
|
||||
setDirty(true)
|
||||
}}
|
||||
placeholder="https://weknora.prod.example"
|
||||
aria-invalid={!endpointValid}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
生产 ID
|
||||
<input
|
||||
value={productionTenantID}
|
||||
onChange={(event) => {
|
||||
setProductionTenantID(event.target.value)
|
||||
setDirty(true)
|
||||
}}
|
||||
placeholder="10000"
|
||||
aria-invalid={!productionTenantIDValid}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
知识库 ID
|
||||
<input
|
||||
value={productionKnowledgeBaseID}
|
||||
onChange={(event) => {
|
||||
setProductionKnowledgeBaseID(event.target.value)
|
||||
setDirty(true)
|
||||
}}
|
||||
placeholder="生产知识库 ID"
|
||||
aria-invalid={!productionKnowledgeBaseIDValid}
|
||||
/>
|
||||
</label>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<label>
|
||||
测试地址
|
||||
<input value={settings.test_weknora_base_url || '未配置'} readOnly disabled />
|
||||
</label>
|
||||
<label>
|
||||
生产地址
|
||||
<input value={settings.production_weknora_base_url || '未配置'} readOnly disabled />
|
||||
</label>
|
||||
<label>
|
||||
生产 ID
|
||||
<input value={settings.production_tenant_id || '未配置'} readOnly disabled />
|
||||
</label>
|
||||
<label>
|
||||
知识库 ID
|
||||
<input value={settings.production_knowledge_base_id || '未配置'} readOnly disabled />
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{isAdmin ? (
|
||||
<>
|
||||
<button
|
||||
onClick={saveEndpoint}
|
||||
disabled={!canSave || !serviceSettingsValid || !serviceSettingsDirty}
|
||||
>
|
||||
{saving ? '正在验证并启用…' : '保存并启用服务配置'}
|
||||
</button>
|
||||
<small>
|
||||
四项留空即表示未配置。地址只接受 http(s) 源地址(不能带用户名密码、查询串或 #
|
||||
片段,凭据一律走文件引用);生产 ID 是发布契约里的租户 ID,十进制数字;知识库 ID
|
||||
是生产知识库标识,粘贴 URL 不会通过。保存写入服务器活动版本(版本化 + 审计 +
|
||||
原子切换);后端同时对测试地址/生产地址做真实探活,并用生产地址真查这两个 ID(WeKnora
|
||||
列库接口):端点回答"没有这个知识库"或租户不符会拒绝保存,端点抖动、鉴权失败或未配置生产凭据只警告不拦,核验原话与知识库名在保存后显示。
|
||||
</small>
|
||||
{serviceSettingsValid ? null : (
|
||||
<p className="error-message" role="alert">
|
||||
格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产
|
||||
ID 需为十进制数字;知识库 ID 不能含空格、/、?、# 或 \。
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<small>
|
||||
服务配置仅管理员可修改;当前值:测试地址 {settings.test_weknora_base_url || '未配置'} · 生产地址{' '}
|
||||
{settings.production_weknora_base_url || '未配置'} · 生产 ID{' '}
|
||||
{settings.production_tenant_id || '未配置'} · 知识库 ID{' '}
|
||||
{settings.production_knowledge_base_id || '未配置'}。
|
||||
</small>
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
{section === 'bindings' ? <RoutingBindingsSection /> : null}
|
||||
{section === 'production-bindings' ? <ProductionBindingsSection /> : null}
|
||||
{section === 'storage' ? <BackupScheduleSection /> : null}
|
||||
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
|
||||
{section === 'refresh' ? (
|
||||
<section className="settings-panel wide" id="settings-refresh">
|
||||
<div className="settings-section-heading">
|
||||
<div>
|
||||
<h2>刷新策略</h2>
|
||||
<p>这些值保存在服务器活动版本中;保存不会修改端点、凭据或生产开关。</p>
|
||||
</div>
|
||||
<span className="safe-badge">当前活动版本</span>
|
||||
</div>
|
||||
<div className="safe-setting-grid">
|
||||
<label>
|
||||
文档状态刷新间隔
|
||||
<select
|
||||
value={documentRefresh}
|
||||
onChange={(event) => {
|
||||
setDocumentRefresh(Number(event.target.value) as 15 | 30 | 60)
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={15}>15秒</option>
|
||||
<option value={30}>30秒</option>
|
||||
<option value={60}>1分钟</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
资源刷新间隔
|
||||
<select
|
||||
value={resourceRefresh}
|
||||
onChange={(event) => {
|
||||
setResourceRefresh(Number(event.target.value) as 30 | 60)
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={30}>30秒</option>
|
||||
<option value={60}>1分钟</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
解析停滞判定
|
||||
<select
|
||||
value={stalled}
|
||||
onChange={(event) => {
|
||||
setStalled(Number(event.target.value) as 1800 | 3600)
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={1800}>30分钟</option>
|
||||
<option value={3600}>1小时</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
finalizing 告警
|
||||
<select
|
||||
value={finalizing}
|
||||
onChange={(event) => {
|
||||
setFinalizing(Number(event.target.value) as 7200 | 14400)
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={7200}>2小时</option>
|
||||
<option value={14400}>4小时</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
入库并发上限
|
||||
<select
|
||||
value={concurrency}
|
||||
onChange={(event) => {
|
||||
setConcurrency(Number(event.target.value))
|
||||
setDirty(true)
|
||||
}}
|
||||
>
|
||||
<option value={1}>1(谨慎,MinerU 并发 1)</option>
|
||||
<option value={2}>2</option>
|
||||
<option value={3}>3</option>
|
||||
<option value={4}>4</option>
|
||||
<option value={6}>6</option>
|
||||
<option value={8}>8</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => {
|
||||
setDirty(false)
|
||||
onSave(candidateInput())
|
||||
}}
|
||||
disabled={!canSave}
|
||||
>
|
||||
{saving ? '正在验证并应用…' : '保存并应用刷新与告警参数'}
|
||||
</button>
|
||||
{visibleSaveMessage(saveMessage, dirty) ? (
|
||||
<p className="success-message" role="status">
|
||||
{saveMessage}
|
||||
</p>
|
||||
) : null}
|
||||
<small>
|
||||
当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源{' '}
|
||||
{secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}
|
||||
、finalizing {secondsLabel(settings.finalizing_after_seconds)}、入库并发{' '}
|
||||
{settings.ingestion_concurrency}。
|
||||
</small>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
{isAdmin ? <><button onClick={saveEndpoint} disabled={!canSave || !serviceSettingsValid || !serviceSettingsDirty}>{saving ? '正在验证并启用…' : '保存并启用服务配置'}</button>
|
||||
<small>四项留空即表示未配置。地址只接受 http(s) 源地址(不能带用户名密码、查询串或 # 片段,凭据一律走文件引用);生产 ID 是发布契约里的租户 ID,十进制数字;知识库 ID 是生产知识库标识,粘贴 URL 不会通过。保存写入服务器活动版本(版本化 + 审计 + 原子切换);后端同时对测试地址/生产地址做真实探活,并用生产地址真查这两个 ID(WeKnora 列库接口):端点回答"没有这个知识库"或租户不符会拒绝保存,端点抖动、鉴权失败或未配置生产凭据只警告不拦,核验原话与知识库名在保存后显示。</small>
|
||||
{serviceSettingsValid ? null : <p className="error-message" role="alert">格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产 ID 需为十进制数字;知识库 ID 不能含空格、/、?、# 或 \。</p>}</>
|
||||
: <small>服务配置仅管理员可修改;当前值:测试地址 {settings.test_weknora_base_url || '未配置'} · 生产地址 {settings.production_weknora_base_url || '未配置'} · 生产 ID {settings.production_tenant_id || '未配置'} · 知识库 ID {settings.production_knowledge_base_id || '未配置'}。</small>}
|
||||
</section> : null}
|
||||
{section === 'bindings' ? <RoutingBindingsSection /> : null}
|
||||
{section === 'production-bindings' ? <ProductionBindingsSection /> : null}
|
||||
{section === 'storage' ? <BackupScheduleSection /> : null}
|
||||
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
|
||||
{section === 'refresh' ? <section className="settings-panel wide" id="settings-refresh">
|
||||
<div className="settings-section-heading"><div><h2>刷新策略</h2><p>这些值保存在服务器活动版本中;保存不会修改端点、凭据或生产开关。</p></div><span className="safe-badge">当前活动版本</span></div>
|
||||
<div className="safe-setting-grid">
|
||||
<label>文档状态刷新间隔<select value={documentRefresh} onChange={(event) => { setDocumentRefresh(Number(event.target.value) as 15 | 30 | 60); setDirty(true) }}><option value={15}>15秒</option><option value={30}>30秒</option><option value={60}>1分钟</option></select></label>
|
||||
<label>资源刷新间隔<select value={resourceRefresh} onChange={(event) => { setResourceRefresh(Number(event.target.value) as 30 | 60); setDirty(true) }}><option value={30}>30秒</option><option value={60}>1分钟</option></select></label>
|
||||
<label>解析停滞判定<select value={stalled} onChange={(event) => { setStalled(Number(event.target.value) as 1800 | 3600); setDirty(true) }}><option value={1800}>30分钟</option><option value={3600}>1小时</option></select></label>
|
||||
<label>finalizing 告警<select value={finalizing} onChange={(event) => { setFinalizing(Number(event.target.value) as 7200 | 14400); setDirty(true) }}><option value={7200}>2小时</option><option value={14400}>4小时</option></select></label>
|
||||
<label>入库并发上限<select value={concurrency} onChange={(event) => { setConcurrency(Number(event.target.value)); setDirty(true) }}><option value={1}>1(谨慎,MinerU 并发 1)</option><option value={2}>2</option><option value={3}>3</option><option value={4}>4</option><option value={6}>6</option><option value={8}>8</option></select></label>
|
||||
</div>
|
||||
<button onClick={() => { setDirty(false); onSave(candidateInput()) }} disabled={!canSave}>{saving ? '正在验证并应用…' : '保存并应用刷新与告警参数'}</button>
|
||||
{visibleSaveMessage(saveMessage, dirty) ? <p className="success-message" role="status">{saveMessage}</p> : null}
|
||||
<small>当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源 {secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}、finalizing {secondsLabel(settings.finalizing_after_seconds)}、入库并发 {settings.ingestion_concurrency}。</small>
|
||||
</section> : null}
|
||||
</div>
|
||||
</div> : null}
|
||||
</main>
|
||||
</div>
|
||||
) : null}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
export function SystemSettings() {
|
||||
@@ -291,7 +795,10 @@ export function SystemSettings() {
|
||||
const [settings, setSettings] = useState<UISettings | null>(null)
|
||||
const [productionEnabled, setProductionEnabled] = useState(false)
|
||||
const [productionBackupRestoreVerified, setProductionBackupRestoreVerified] = useState(false)
|
||||
const [routingCapabilities, setRoutingCapabilities] = useState<CatalogRoutingCapabilities>({ internal_enabled: false, external_enabled: false })
|
||||
const [routingCapabilities, setRoutingCapabilities] = useState<CatalogRoutingCapabilities>({
|
||||
internal_enabled: false,
|
||||
external_enabled: false,
|
||||
})
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -299,24 +806,76 @@ export function SystemSettings() {
|
||||
const [revision, setRevision] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController(); setLoading(true)
|
||||
void Promise.all([fetchCatalogSources(controller.signal), fetchSourceConnectionList(controller.signal), fetchMonitorOverview(controller.signal), fetchReleaseCapabilities(controller.signal), fetchCatalogRoutingCapabilities(controller.signal), fetchActiveUISettings(controller.signal)]).then(([nextSources, nextConnections, overview, capabilities, routing, active]) => { if (!controller.signal.aborted) { setSources(nextSources); setConnections(nextConnections); setMonitor(overview); setProductionEnabled(capabilities.production_release_requests_enabled); setProductionBackupRestoreVerified(capabilities.production_backup_restore_verified); setRoutingCapabilities(routing); setSettings(active); setError(null) } }).catch((cause) => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载系统设置失败') }).finally(() => { if (!controller.signal.aborted) setLoading(false) })
|
||||
const controller = new AbortController()
|
||||
setLoading(true)
|
||||
void Promise.all([
|
||||
fetchCatalogSources(controller.signal),
|
||||
fetchSourceConnectionList(controller.signal),
|
||||
fetchMonitorOverview(controller.signal),
|
||||
fetchReleaseCapabilities(controller.signal),
|
||||
fetchCatalogRoutingCapabilities(controller.signal),
|
||||
fetchActiveUISettings(controller.signal),
|
||||
])
|
||||
.then(([nextSources, nextConnections, overview, capabilities, routing, active]) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setSources(nextSources)
|
||||
setConnections(nextConnections)
|
||||
setMonitor(overview)
|
||||
setProductionEnabled(capabilities.production_release_requests_enabled)
|
||||
setProductionBackupRestoreVerified(capabilities.production_backup_restore_verified)
|
||||
setRoutingCapabilities(routing)
|
||||
setSettings(active)
|
||||
setError(null)
|
||||
}
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载系统设置失败')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [revision])
|
||||
|
||||
const save = async (input: UISettingsCandidateInput) => {
|
||||
setSaving(true); setSaveMessage(null); setError(null)
|
||||
setSaving(true)
|
||||
setSaveMessage(null)
|
||||
setError(null)
|
||||
try {
|
||||
const candidate = await createUISettingsCandidate(input)
|
||||
const activated = await activateUISettings(candidate.settings.id)
|
||||
const active = activated.settings
|
||||
const verification = activated.verification ?? candidate.verification
|
||||
setSettings(active)
|
||||
setSaveMessage(`设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)}、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}`)
|
||||
setSaveMessage(
|
||||
`设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)}、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}`
|
||||
)
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '保存系统设置失败')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
catch (cause) { setError(cause instanceof Error ? cause.message : '保存系统设置失败') }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
const reloadSources = useCallback(() => { setSaveMessage(null); setRevision((value) => value + 1) }, [])
|
||||
return <SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={productionEnabled} productionBackupRestoreVerified={productionBackupRestoreVerified} routingCapabilities={routingCapabilities} loading={loading} saving={saving} error={error} saveMessage={saveMessage} onSave={(input) => void save(input)} onSourcesChanged={reloadSources} onRefresh={reloadSources}/>
|
||||
const reloadSources = useCallback(() => {
|
||||
setSaveMessage(null)
|
||||
setRevision((value) => value + 1)
|
||||
}, [])
|
||||
return (
|
||||
<SystemSettingsView
|
||||
sources={sources}
|
||||
connections={connections}
|
||||
monitor={monitor}
|
||||
settings={settings}
|
||||
productionEnabled={productionEnabled}
|
||||
productionBackupRestoreVerified={productionBackupRestoreVerified}
|
||||
routingCapabilities={routingCapabilities}
|
||||
loading={loading}
|
||||
saving={saving}
|
||||
error={error}
|
||||
saveMessage={saveMessage}
|
||||
onSave={(input) => void save(input)}
|
||||
onSourcesChanged={reloadSources}
|
||||
onRefresh={reloadSources}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -186,6 +186,19 @@ describe('VersionHistoryView', () => {
|
||||
expect(html).not.toContain('同步记录</button>')
|
||||
})
|
||||
|
||||
it('never renders a tag link without a URL (an empty href looks broken)', () => {
|
||||
const withURL = render()
|
||||
expect(withURL).toContain('查看 tag v0.1.0')
|
||||
expect(withURL).toContain('https://gitea.example/Weknora/knowledge-governance/src/tag/v0.1.0')
|
||||
const withoutURL = render({
|
||||
page: {
|
||||
...page,
|
||||
items: [{ ...releaseItem, release_tags: [{ name: 'v0.1.0', url: '' }] }],
|
||||
},
|
||||
})
|
||||
expect(withoutURL).not.toContain('查看 tag')
|
||||
})
|
||||
|
||||
it('keeps mobile single-column rules so nothing overflows horizontally', () => {
|
||||
const css = readFileSync(new URL('./versionHistory.css', import.meta.url), 'utf8')
|
||||
expect(css).toMatch(/@media \(max-width: 760px\)[\s\S]*?\.version-history[\s\S]*?overflow-wrap:\s*anywhere/)
|
||||
|
||||
@@ -197,11 +197,14 @@ function TimelineEntry({
|
||||
查看提交
|
||||
</a>
|
||||
) : null}
|
||||
{item.release_tags.map((tag) => (
|
||||
<a key={tag.name} href={tag.url} target="_blank" rel="noreferrer noopener">
|
||||
查看 tag {tag.name}
|
||||
</a>
|
||||
))}
|
||||
{/* 没有链接就不渲染:空 href 点下去像"没反应/空白",比不显示更糟 */}
|
||||
{item.release_tags
|
||||
.filter((tag) => tag.url)
|
||||
.map((tag) => (
|
||||
<a key={tag.name} href={tag.url} target="_blank" rel="noreferrer noopener">
|
||||
查看 tag {tag.name}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
|
||||
@@ -6,9 +6,17 @@ afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('DingTalk session client', () => {
|
||||
it('returns the starting state immediately while the QR is being generated', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
|
||||
id: 'session-1', state: 'starting', created_at: 1, expires_at: 2,
|
||||
}), { status: 201 }))
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
id: 'session-1',
|
||||
state: 'starting',
|
||||
created_at: 1,
|
||||
expires_at: 2,
|
||||
}),
|
||||
{ status: 201 }
|
||||
)
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const target = 'https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview'
|
||||
@@ -18,14 +26,51 @@ describe('DingTalk session client', () => {
|
||||
})
|
||||
|
||||
it('preserves login_required as a machine-readable error for automatic QR fallback', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(
|
||||
JSON.stringify({ error: 'login_required' }),
|
||||
{ status: 409, headers: { 'Content-Type': 'application/json' } },
|
||||
)))
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'login_required' }), {
|
||||
status: 409,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
const error = await registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview')
|
||||
.then(() => null, (cause: unknown) => cause)
|
||||
const error = await registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview').then(
|
||||
() => null,
|
||||
(cause: unknown) => cause
|
||||
)
|
||||
expect(error).toBeInstanceOf(DingtalkRequestError)
|
||||
expect(error).toMatchObject({ code: 'login_required', status: 409 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('钉钉知识库登记的失败说明', () => {
|
||||
it('后端 hint 优先,其次本地文案;错误码始终带出', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'space_name_conflict', hint: '已有同名来源仍在使用:先「去掉来源」' }), {
|
||||
status: 409,
|
||||
})
|
||||
)
|
||||
)
|
||||
await expect(registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/x')).rejects.toThrow(
|
||||
'已有同名来源仍在使用:先「去掉来源」'
|
||||
)
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'space_identity_conflict' }), { status: 409 }))
|
||||
)
|
||||
await expect(registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/x')).rejects.toThrow(
|
||||
'这个登记键已指向另一个知识库空间'
|
||||
)
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'space_registration_failed' }), { status: 500 }))
|
||||
)
|
||||
await expect(registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/x')).rejects.toThrow(
|
||||
'登记失败(服务端内部错误)'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
+59
-15
@@ -4,7 +4,8 @@ import { newOperationID } from './operationKey'
|
||||
// The API proxies to the dingtalk-login sidecar; this module never sees the
|
||||
// token itself — only the base64 QR image and a terminal state.
|
||||
|
||||
export type DingtalkSessionState = 'starting' | 'qr' | 'scanned' | 'reusing' | 'success' | 'expired' | 'failed' | 'closed'
|
||||
export type DingtalkSessionState =
|
||||
'starting' | 'qr' | 'scanned' | 'reusing' | 'success' | 'expired' | 'failed' | 'closed'
|
||||
|
||||
export interface DingtalkSessionView {
|
||||
id: string
|
||||
@@ -15,7 +16,16 @@ export interface DingtalkSessionView {
|
||||
error?: string
|
||||
}
|
||||
|
||||
const sessionStates = new Set<string>(['starting', 'qr', 'scanned', 'reusing', 'success', 'expired', 'failed', 'closed'])
|
||||
const sessionStates = new Set<string>([
|
||||
'starting',
|
||||
'qr',
|
||||
'scanned',
|
||||
'reusing',
|
||||
'success',
|
||||
'expired',
|
||||
'failed',
|
||||
'closed',
|
||||
])
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
@@ -24,7 +34,12 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
export async function startDingtalkSession(space?: string): Promise<DingtalkSessionView> {
|
||||
const response = await fetch('/api/v1/dingtalk-session', {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Governance-Action': 'dingtalk-session', 'Idempotency-Key': newOperationID() },
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Governance-Action': 'dingtalk-session',
|
||||
'Idempotency-Key': newOperationID(),
|
||||
},
|
||||
body: JSON.stringify(space ? { space } : {}),
|
||||
})
|
||||
if (!response.ok) throw new Error(`发起钉钉扫码会话失败(HTTP ${response.status})`)
|
||||
@@ -32,13 +47,19 @@ export async function startDingtalkSession(space?: string): Promise<DingtalkSess
|
||||
}
|
||||
|
||||
export async function fetchDingtalkSession(id: string, signal?: AbortSignal): Promise<DingtalkSessionView> {
|
||||
const response = await fetch(`/api/v1/dingtalk-session/${encodeURIComponent(id)}`, { headers: { Accept: 'application/json' }, signal })
|
||||
const response = await fetch(`/api/v1/dingtalk-session/${encodeURIComponent(id)}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal,
|
||||
})
|
||||
if (!response.ok) throw new Error(`读取钉钉扫码会话失败(HTTP ${response.status})`)
|
||||
return parseSession(await response.json())
|
||||
}
|
||||
|
||||
export async function cancelDingtalkSession(id: string): Promise<void> {
|
||||
await fetch(`/api/v1/dingtalk-session/${encodeURIComponent(id)}`, { method: 'DELETE', headers: { Accept: 'application/json' } }).catch(() => undefined)
|
||||
await fetch(`/api/v1/dingtalk-session/${encodeURIComponent(id)}`, {
|
||||
method: 'DELETE',
|
||||
headers: { Accept: 'application/json' },
|
||||
}).catch(() => undefined)
|
||||
}
|
||||
|
||||
export interface RegisteredDingtalkSpace {
|
||||
@@ -50,7 +71,7 @@ export class DingtalkRequestError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly code: string,
|
||||
public readonly status: number,
|
||||
public readonly status: number
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'DingtalkRequestError'
|
||||
@@ -63,36 +84,59 @@ export class DingtalkRequestError extends Error {
|
||||
export async function registerDingtalkSpace(url: string): Promise<RegisteredDingtalkSpace> {
|
||||
const response = await fetch('/api/v1/dingtalk-spaces', {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Governance-Action': 'dingtalk-space', 'Idempotency-Key': newOperationID() },
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Governance-Action': 'dingtalk-space',
|
||||
'Idempotency-Key': newOperationID(),
|
||||
},
|
||||
body: JSON.stringify({ url }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
// 响应体只能读一次:错误码与后端 hint 一起取出(hint 优先,它比本地文案更具体)。
|
||||
let code = ''
|
||||
let hint = ''
|
||||
try {
|
||||
const parsed = await response.json() as unknown
|
||||
if (isRecord(parsed) && typeof parsed.error === 'string') code = parsed.error
|
||||
} catch { /* status-only */ }
|
||||
const parsed = (await response.json()) as unknown
|
||||
if (isRecord(parsed)) {
|
||||
if (typeof parsed.error === 'string') code = parsed.error
|
||||
if (typeof parsed.hint === 'string') hint = parsed.hint
|
||||
}
|
||||
} catch {
|
||||
/* status-only */
|
||||
}
|
||||
const friendly: Record<string, string> = {
|
||||
login_required: '钉钉扫码会话无效或已过期,请先在钉钉来源卡片上「扫码刷新会话」',
|
||||
space_not_found: '未找到该知识库空间:请确认空间链接正确且当前账号有阅读权限',
|
||||
name_conflict: '该空间与已登记的来源同名',
|
||||
// 登记冲突分两种:同名来源还在用 vs 同一个登记键指向了别的空间。原因要说清,
|
||||
// 否则用户只能看到一个无细节的 409(2026-10-14 线上就是这样卡住的)。
|
||||
space_name_conflict: '已有同名来源仍在使用(未下架):先在该来源卡片上「去掉来源」,或确认选的是同一个知识库空间',
|
||||
space_identity_conflict: '这个登记键已指向另一个知识库空间:刷新列表后重试;仍失败就把该来源「去掉来源」再登记',
|
||||
space_registration_failed: '登记失败(服务端内部错误):已记录,请稍后重试或让管理员看服务日志',
|
||||
invalid_space_url: '链接不是有效的钉钉知识库空间地址(应形如 alidocs.dingtalk.com/i/spaces/…)',
|
||||
}
|
||||
throw new DingtalkRequestError(
|
||||
friendly[code] || `登记钉钉知识库失败(HTTP ${response.status}${code ? ':' + code : ''})`,
|
||||
hint || friendly[code] || `登记钉钉知识库失败(HTTP ${response.status}${code ? ':' + code : ''})`,
|
||||
code,
|
||||
response.status,
|
||||
response.status
|
||||
)
|
||||
}
|
||||
const value = await response.json() as unknown
|
||||
const value = (await response.json()) as unknown
|
||||
if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid dingtalk space response')
|
||||
const data = value.data
|
||||
if (typeof data.connection_id !== 'string' || typeof data.name !== 'string') throw new Error('invalid dingtalk space response')
|
||||
if (typeof data.connection_id !== 'string' || typeof data.name !== 'string')
|
||||
throw new Error('invalid dingtalk space response')
|
||||
return { connection_id: data.connection_id, name: data.name }
|
||||
}
|
||||
|
||||
function parseSession(value: unknown): DingtalkSessionView {
|
||||
if (!isRecord(value) || typeof value.id !== 'string' || typeof value.state !== 'string' || !sessionStates.has(value.state)) {
|
||||
if (
|
||||
!isRecord(value) ||
|
||||
typeof value.id !== 'string' ||
|
||||
typeof value.state !== 'string' ||
|
||||
!sessionStates.has(value.state)
|
||||
) {
|
||||
throw new Error('invalid dingtalk session response')
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
activateSourceSettingsRevision,
|
||||
archiveSourceConnection,
|
||||
createSourceSettingsRevision,
|
||||
fetchSourceConnectionList,
|
||||
fetchSourceConnections,
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
parseSourceConnectionsResponse,
|
||||
parseSourceScanDetailResponse,
|
||||
parseSourceScansResponse,
|
||||
restoreSourceConnection,
|
||||
triggerSourceScan,
|
||||
} from './sourceConnections'
|
||||
|
||||
@@ -19,31 +21,65 @@ afterEach(() => vi.unstubAllGlobals())
|
||||
describe('parseSourceConnectionsResponse', () => {
|
||||
it('normalizes only the safe source connection projection', () => {
|
||||
const result = parseSourceConnectionsResponse({
|
||||
data: [{
|
||||
id: 'conn-safe', source_type: 'alist', name: 'AList只读源', enabled: true,
|
||||
schedule_configured: true, health_status: 'healthy', item_count: 42,
|
||||
updated_at: '2026-09-06T01:00:00Z', base_url: 'https://secret-origin.example', secret_ref: 'secret-name',
|
||||
last_scan: {
|
||||
id: 'scan-1', state: 'completed', observed_items: 42, unchanged_items: 40,
|
||||
added_items: 1, updated_items: 1, over_limit_items: 0, missing_items: 0,
|
||||
planned_uploads: 1, error_code: '', created_at: '2026-09-06T00:59:00Z',
|
||||
completed_at: '2026-09-06T01:00:00Z', snapshot_sha256: 'must-strip', previous_revision: 'must-strip',
|
||||
data: [
|
||||
{
|
||||
id: 'conn-safe',
|
||||
source_type: 'alist',
|
||||
name: 'AList只读源',
|
||||
enabled: true,
|
||||
schedule_configured: true,
|
||||
health_status: 'healthy',
|
||||
item_count: 42,
|
||||
updated_at: '2026-09-06T01:00:00Z',
|
||||
base_url: 'https://secret-origin.example',
|
||||
secret_ref: 'secret-name',
|
||||
last_scan: {
|
||||
id: 'scan-1',
|
||||
state: 'completed',
|
||||
observed_items: 42,
|
||||
unchanged_items: 40,
|
||||
added_items: 1,
|
||||
updated_items: 1,
|
||||
over_limit_items: 0,
|
||||
missing_items: 0,
|
||||
planned_uploads: 1,
|
||||
error_code: '',
|
||||
created_at: '2026-09-06T00:59:00Z',
|
||||
completed_at: '2026-09-06T01:00:00Z',
|
||||
snapshot_sha256: 'must-strip',
|
||||
previous_revision: 'must-strip',
|
||||
},
|
||||
},
|
||||
}],
|
||||
],
|
||||
summary: { total: 1, enabled: 1, disabled: 0, healthy: 1, degraded: 0, unhealthy: 0, unknown: 0 },
|
||||
})
|
||||
|
||||
expect(result.items).toEqual([{
|
||||
id: 'conn-safe', source_type: 'alist', name: 'AList只读源', enabled: true,
|
||||
schedule_configured: true, health_status: 'healthy', item_count: 42,
|
||||
updated_at: '2026-09-06T01:00:00Z',
|
||||
last_scan: {
|
||||
id: 'scan-1', state: 'completed', observed_items: 42, unchanged_items: 40,
|
||||
added_items: 1, updated_items: 1, over_limit_items: 0, missing_items: 0,
|
||||
planned_uploads: 1, error_code: '', created_at: '2026-09-06T00:59:00Z',
|
||||
completed_at: '2026-09-06T01:00:00Z',
|
||||
expect(result.items).toEqual([
|
||||
{
|
||||
id: 'conn-safe',
|
||||
source_type: 'alist',
|
||||
name: 'AList只读源',
|
||||
enabled: true,
|
||||
schedule_configured: true,
|
||||
health_status: 'healthy',
|
||||
item_count: 42,
|
||||
updated_at: '2026-09-06T01:00:00Z',
|
||||
last_scan: {
|
||||
id: 'scan-1',
|
||||
state: 'completed',
|
||||
observed_items: 42,
|
||||
unchanged_items: 40,
|
||||
added_items: 1,
|
||||
updated_items: 1,
|
||||
over_limit_items: 0,
|
||||
missing_items: 0,
|
||||
planned_uploads: 1,
|
||||
error_code: '',
|
||||
created_at: '2026-09-06T00:59:00Z',
|
||||
completed_at: '2026-09-06T01:00:00Z',
|
||||
},
|
||||
},
|
||||
}])
|
||||
])
|
||||
expect(result.summary.total).toBe(1)
|
||||
expect(result.items[0]).not.toHaveProperty('base_url')
|
||||
expect(result.items[0]).not.toHaveProperty('secret_ref')
|
||||
@@ -66,7 +102,7 @@ describe('fetchSourceConnections', () => {
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/v1/source-connections',
|
||||
expect.objectContaining({ headers: { Accept: 'application/json' } }),
|
||||
expect.objectContaining({ headers: { Accept: 'application/json' } })
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -76,54 +112,120 @@ describe('triggerSourceScan', () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
id: 'scan-safe', source_connection_id: 'conn/a', source_type: 'pp', state: 'pending',
|
||||
created_at: '2026-09-06T01:00:00Z', snapshot_sha256: 'must-strip',
|
||||
id: 'scan-safe',
|
||||
source_connection_id: 'conn/a',
|
||||
source_type: 'pp',
|
||||
state: 'pending',
|
||||
created_at: '2026-09-06T01:00:00Z',
|
||||
snapshot_sha256: 'must-strip',
|
||||
}),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const scan = await triggerSourceScan('conn/a')
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/source-connections/conn%2Fa/scan', expect.objectContaining({ method: 'POST' }))
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/v1/source-connections/conn%2Fa/scan',
|
||||
expect.objectContaining({ method: 'POST' })
|
||||
)
|
||||
expect(scan).toEqual({
|
||||
id: 'scan-safe', source_connection_id: 'conn/a', source_type: 'pp', state: 'pending', created_at: '2026-09-06T01:00:00Z',
|
||||
id: 'scan-safe',
|
||||
source_connection_id: 'conn/a',
|
||||
source_type: 'pp',
|
||||
state: 'pending',
|
||||
created_at: '2026-09-06T01:00:00Z',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('source scan history and details', () => {
|
||||
const scan = {
|
||||
id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
|
||||
added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
|
||||
planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
|
||||
snapshot_sha256: 'must-be-dropped', stable_external_id: 'must-be-dropped',
|
||||
id: 'scan-safe',
|
||||
state: 'completed',
|
||||
observed_items: 2,
|
||||
unchanged_items: 0,
|
||||
added_items: 1,
|
||||
updated_items: 0,
|
||||
over_limit_items: 0,
|
||||
missing_items: 1,
|
||||
planned_uploads: 1,
|
||||
error_code: '',
|
||||
created_at: '2026-09-06T06:00:00Z',
|
||||
completed_at: '2026-09-06T06:01:00Z',
|
||||
snapshot_sha256: 'must-be-dropped',
|
||||
stable_external_id: 'must-be-dropped',
|
||||
}
|
||||
|
||||
it('strictly parses safe history and detail projections', () => {
|
||||
expect(parseSourceScansResponse({ data: [scan], total: 1, limit: 20, offset: 0 })).toEqual({
|
||||
items: [{
|
||||
id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
|
||||
added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
|
||||
planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
|
||||
}], total: 1, limit: 20, offset: 0,
|
||||
items: [
|
||||
{
|
||||
id: 'scan-safe',
|
||||
state: 'completed',
|
||||
observed_items: 2,
|
||||
unchanged_items: 0,
|
||||
added_items: 1,
|
||||
updated_items: 0,
|
||||
over_limit_items: 0,
|
||||
missing_items: 1,
|
||||
planned_uploads: 1,
|
||||
error_code: '',
|
||||
created_at: '2026-09-06T06:00:00Z',
|
||||
completed_at: '2026-09-06T06:01:00Z',
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
limit: 20,
|
||||
offset: 0,
|
||||
})
|
||||
expect(parseSourceScanDetailResponse({ data: {
|
||||
...scan,
|
||||
changes: [{
|
||||
id: 'chg-safe', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 42,
|
||||
created_at: '2026-09-06T06:01:00Z', previous_revision: 'must-be-dropped', observed_revision: 'must-be-dropped',
|
||||
}],
|
||||
}})).toEqual({
|
||||
id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
|
||||
added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
|
||||
planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
|
||||
changes: [{ id: 'chg-safe', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 42, created_at: '2026-09-06T06:01:00Z' }],
|
||||
expect(
|
||||
parseSourceScanDetailResponse({
|
||||
data: {
|
||||
...scan,
|
||||
changes: [
|
||||
{
|
||||
id: 'chg-safe',
|
||||
source_item_id: 'si-safe',
|
||||
change_type: 'updated',
|
||||
observed_size_bytes: 42,
|
||||
created_at: '2026-09-06T06:01:00Z',
|
||||
previous_revision: 'must-be-dropped',
|
||||
observed_revision: 'must-be-dropped',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
).toEqual({
|
||||
id: 'scan-safe',
|
||||
state: 'completed',
|
||||
observed_items: 2,
|
||||
unchanged_items: 0,
|
||||
added_items: 1,
|
||||
updated_items: 0,
|
||||
over_limit_items: 0,
|
||||
missing_items: 1,
|
||||
planned_uploads: 1,
|
||||
error_code: '',
|
||||
created_at: '2026-09-06T06:00:00Z',
|
||||
completed_at: '2026-09-06T06:01:00Z',
|
||||
changes: [
|
||||
{
|
||||
id: 'chg-safe',
|
||||
source_item_id: 'si-safe',
|
||||
change_type: 'updated',
|
||||
observed_size_bytes: 42,
|
||||
created_at: '2026-09-06T06:01:00Z',
|
||||
},
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('requests connection-scoped history and details', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: [scan], total: 1, limit: 20, offset: 0 }), { status: 200 }))
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ data: [scan], total: 1, limit: 20, offset: 0 }), { status: 200 })
|
||||
)
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { ...scan, changes: [] } }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await fetchSourceScans('conn / pp')
|
||||
@@ -135,47 +237,165 @@ describe('source scan history and details', () => {
|
||||
|
||||
describe('V1 source settings client', () => {
|
||||
it('projects the connection list without sensitive fields', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
|
||||
data: [{ id: 'conn-1', source_type: 'alist', name: 'A', enabled: true, schedule_configured: true,
|
||||
health_status: 'healthy', item_count: 3, updated_at: '2026-09-12T01:00:00Z', next_refresh_at: '2026-09-12T09:00:00Z',
|
||||
base_url: 'https://strip.me', secret_ref: 'strip-too' }],
|
||||
}), { status: 200 }))
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: [
|
||||
{
|
||||
id: 'conn-1',
|
||||
source_type: 'alist',
|
||||
name: 'A',
|
||||
enabled: true,
|
||||
schedule_configured: true,
|
||||
health_status: 'healthy',
|
||||
item_count: 3,
|
||||
updated_at: '2026-09-12T01:00:00Z',
|
||||
next_refresh_at: '2026-09-12T09:00:00Z',
|
||||
base_url: 'https://strip.me',
|
||||
secret_ref: 'strip-too',
|
||||
},
|
||||
],
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const items = await fetchSourceConnectionList()
|
||||
expect(items).toEqual([{ id: 'conn-1', source_type: 'alist', name: 'A', enabled: true, schedule_configured: true,
|
||||
health_status: 'healthy', item_count: 3, updated_at: '2026-09-12T01:00:00Z', next_refresh_at: '2026-09-12T09:00:00Z' }])
|
||||
expect(items).toEqual([
|
||||
{
|
||||
id: 'conn-1',
|
||||
source_type: 'alist',
|
||||
name: 'A',
|
||||
enabled: true,
|
||||
schedule_configured: true,
|
||||
health_status: 'healthy',
|
||||
item_count: 3,
|
||||
updated_at: '2026-09-12T01:00:00Z',
|
||||
next_refresh_at: '2026-09-12T09:00:00Z',
|
||||
},
|
||||
])
|
||||
expect(JSON.stringify(items)).not.toContain('strip')
|
||||
})
|
||||
it('rejects malformed connection items', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({
|
||||
data: [{ id: 'x' }],
|
||||
}), { status: 200 })))
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: [{ id: 'x' }],
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
)
|
||||
)
|
||||
await expect(fetchSourceConnectionList()).rejects.toThrow('invalid source connection item')
|
||||
})
|
||||
it('creates and activates revisions with intent + idempotency headers and surfaces operation', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { id: 'scr-2' }, operation: 'created' }), { status: 201 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { connection_id: 'c', revision_id: 'scr-2' }, operation: 'replayed' }), { status: 200 }))
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ data: { id: 'scr-2' }, operation: 'created' }), { status: 201 })
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ data: { connection_id: 'c', revision_id: 'scr-2' }, operation: 'replayed' }), {
|
||||
status: 200,
|
||||
})
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
expect(await createSourceSettingsRevision('conn/1', { source_type: 'alist', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 } })).toEqual({ operation: 'created', id: 'scr-2' })
|
||||
expect(
|
||||
await createSourceSettingsRevision('conn/1', {
|
||||
source_type: 'alist',
|
||||
name: 'A',
|
||||
endpoint: '',
|
||||
credential_ref: '',
|
||||
enabled: true,
|
||||
schedule: { refresh_interval_seconds: 3600 },
|
||||
})
|
||||
).toEqual({ operation: 'created', id: 'scr-2' })
|
||||
expect(await activateSourceSettingsRevision('conn/1', 'scr/2')).toEqual({ operation: 'replayed', id: null })
|
||||
const [createCall, activateCall] = fetchMock.mock.calls
|
||||
expect(createCall[0]).toBe('/api/v1/source-connections/conn%2F1/settings/revisions')
|
||||
expect((createCall[1] as RequestInit).headers).toMatchObject({ 'X-Governance-Action': 'source-settings' })
|
||||
expect(((createCall[1] as RequestInit).headers as Record<string, string>)['Idempotency-Key']).toMatch(/[0-9a-f-]{36}/)
|
||||
expect(((createCall[1] as RequestInit).headers as Record<string, string>)['Idempotency-Key']).toMatch(
|
||||
/[0-9a-f-]{36}/
|
||||
)
|
||||
expect(activateCall[0]).toBe('/api/v1/source-connections/conn%2F1/settings/revisions/scr%2F2/activate')
|
||||
expect(createCall[1]).not.toBe(activateCall[1])
|
||||
})
|
||||
it('surfaces server error details on failure', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'manual sources cannot be scheduled' }), { status: 400 })))
|
||||
await expect(createSourceSettingsRevision('c', { source_type: 'manual', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 } })).rejects.toThrow('保存来源设置草稿失败:manual sources cannot be scheduled')
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: 'manual sources cannot be scheduled' }), { status: 400 })
|
||||
)
|
||||
)
|
||||
await expect(
|
||||
createSourceSettingsRevision('c', {
|
||||
source_type: 'manual',
|
||||
name: 'A',
|
||||
endpoint: '',
|
||||
credential_ref: '',
|
||||
enabled: true,
|
||||
schedule: { refresh_interval_seconds: 3600 },
|
||||
})
|
||||
).rejects.toThrow('保存来源设置草稿失败:manual sources cannot be scheduled')
|
||||
})
|
||||
it('parses revision history strictly', async () => {
|
||||
const revision = { id: 'scr-1', revision_number: 1, state: 'active', name: 'A', endpoint: 'http://x', credential_ref: 'ref', enabled: true, refresh_interval_seconds: '3600', created_by: 'z', created_at: '2026-09-12T01:00:00Z', validated_at: null, activated_at: '2026-09-12T01:00:00Z', retired_at: null }
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [revision] }), { status: 200 })))
|
||||
const revision = {
|
||||
id: 'scr-1',
|
||||
revision_number: 1,
|
||||
state: 'active',
|
||||
name: 'A',
|
||||
endpoint: 'http://x',
|
||||
credential_ref: 'ref',
|
||||
enabled: true,
|
||||
refresh_interval_seconds: '3600',
|
||||
created_by: 'z',
|
||||
created_at: '2026-09-12T01:00:00Z',
|
||||
validated_at: null,
|
||||
activated_at: '2026-09-12T01:00:00Z',
|
||||
retired_at: null,
|
||||
}
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [revision] }), { status: 200 }))
|
||||
)
|
||||
const history = await fetchSourceSettingsRevisions('c')
|
||||
expect(history[0].state).toBe('active')
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [{ ...revision, state: 'weird' }] }), { status: 200 })))
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValue(new Response(JSON.stringify({ data: [{ ...revision, state: 'weird' }] }), { status: 200 }))
|
||||
)
|
||||
await expect(fetchSourceSettingsRevisions('c')).rejects.toThrow('invalid source settings revision')
|
||||
})
|
||||
})
|
||||
|
||||
describe('去掉来源(归档)客户端', () => {
|
||||
it('归档/恢复都带写意图头与幂等键,并正确编码来源 ID', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response('{}', { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await archiveSourceConnection('conn/1')
|
||||
const [archiveURL, archiveInit] = fetchMock.mock.calls[0]
|
||||
expect(archiveURL).toBe('/api/v1/source-connections/conn%2F1/archive')
|
||||
expect(archiveInit.method).toBe('POST')
|
||||
expect(archiveInit.headers['X-Governance-Action']).toBe('source-archive')
|
||||
expect(typeof archiveInit.headers['Idempotency-Key']).toBe('string')
|
||||
expect(archiveInit.headers['Idempotency-Key'].length).toBeGreaterThan(0)
|
||||
|
||||
await restoreSourceConnection('conn/1')
|
||||
const [restoreURL, restoreInit] = fetchMock.mock.calls[1]
|
||||
expect(restoreURL).toBe('/api/v1/source-connections/conn%2F1/restore')
|
||||
expect(restoreInit.headers['X-Governance-Action']).toBe('source-restore')
|
||||
})
|
||||
it('后端拒绝时把原因带出来(不吞错误)', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'source connection not found' }), { status: 404 }))
|
||||
)
|
||||
await expect(archiveSourceConnection('conn-x')).rejects.toThrow('去掉来源失败:source connection not found')
|
||||
})
|
||||
})
|
||||
|
||||
+218
-58
@@ -79,7 +79,13 @@ const healthStatuses = new Set<SourceHealthStatus>(['unknown', 'healthy', 'degra
|
||||
const scanStates = new Set<SourceScanState>(['pending', 'running', 'completed', 'failed'])
|
||||
const scanChangeTypes = new Set<SourceScanChangeType>(['added', 'updated', 'unavailable'])
|
||||
const summaryKeys: ReadonlyArray<keyof SourceConnectionSummary> = [
|
||||
'total', 'enabled', 'disabled', 'healthy', 'degraded', 'unhealthy', 'unknown',
|
||||
'total',
|
||||
'enabled',
|
||||
'disabled',
|
||||
'healthy',
|
||||
'degraded',
|
||||
'unhealthy',
|
||||
'unknown',
|
||||
]
|
||||
|
||||
export function parseSourceConnectionsResponse(value: unknown): SourceConnectionPage {
|
||||
@@ -87,11 +93,19 @@ export function parseSourceConnectionsResponse(value: unknown): SourceConnection
|
||||
throw new Error('invalid source connections response')
|
||||
}
|
||||
const items = value.data.map((raw): SourceConnectionView => {
|
||||
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.source_type !== 'string' ||
|
||||
!sourceTypes.has(raw.source_type as SourceConnectionType) || typeof raw.name !== 'string' ||
|
||||
typeof raw.enabled !== 'boolean' || typeof raw.schedule_configured !== 'boolean' ||
|
||||
typeof raw.health_status !== 'string' || !healthStatuses.has(raw.health_status as SourceHealthStatus) ||
|
||||
!isCount(raw.item_count) || typeof raw.updated_at !== 'string') {
|
||||
if (
|
||||
!isRecord(raw) ||
|
||||
typeof raw.id !== 'string' ||
|
||||
typeof raw.source_type !== 'string' ||
|
||||
!sourceTypes.has(raw.source_type as SourceConnectionType) ||
|
||||
typeof raw.name !== 'string' ||
|
||||
typeof raw.enabled !== 'boolean' ||
|
||||
typeof raw.schedule_configured !== 'boolean' ||
|
||||
typeof raw.health_status !== 'string' ||
|
||||
!healthStatuses.has(raw.health_status as SourceHealthStatus) ||
|
||||
!isCount(raw.item_count) ||
|
||||
typeof raw.updated_at !== 'string'
|
||||
) {
|
||||
throw new Error('invalid source connection item')
|
||||
}
|
||||
const lastScan = parseSourceScanSummary(raw.last_scan)
|
||||
@@ -131,18 +145,28 @@ export interface SourceConnectionListItem {
|
||||
function parseConnectionList(raw: unknown): SourceConnectionListItem[] {
|
||||
if (!Array.isArray(raw)) throw new Error('invalid source connections list')
|
||||
return raw.map((item): SourceConnectionListItem => {
|
||||
if (!isRecord(item) || typeof item.id !== 'string' || typeof item.source_type !== 'string' ||
|
||||
typeof item.name !== 'string' || typeof item.enabled !== 'boolean' ||
|
||||
typeof item.schedule_configured !== 'boolean' || typeof item.item_count !== 'number' ||
|
||||
typeof item.updated_at !== 'string' ||
|
||||
(item.next_refresh_at !== null && typeof item.next_refresh_at !== 'string')) {
|
||||
if (
|
||||
!isRecord(item) ||
|
||||
typeof item.id !== 'string' ||
|
||||
typeof item.source_type !== 'string' ||
|
||||
typeof item.name !== 'string' ||
|
||||
typeof item.enabled !== 'boolean' ||
|
||||
typeof item.schedule_configured !== 'boolean' ||
|
||||
typeof item.item_count !== 'number' ||
|
||||
typeof item.updated_at !== 'string' ||
|
||||
(item.next_refresh_at !== null && typeof item.next_refresh_at !== 'string')
|
||||
) {
|
||||
throw new Error('invalid source connection item')
|
||||
}
|
||||
return {
|
||||
id: item.id, source_type: item.source_type as SourceConnectionType, name: item.name,
|
||||
enabled: item.enabled, schedule_configured: item.schedule_configured,
|
||||
id: item.id,
|
||||
source_type: item.source_type as SourceConnectionType,
|
||||
name: item.name,
|
||||
enabled: item.enabled,
|
||||
schedule_configured: item.schedule_configured,
|
||||
health_status: typeof item.health_status === 'string' ? item.health_status : '',
|
||||
item_count: item.item_count, updated_at: item.updated_at,
|
||||
item_count: item.item_count,
|
||||
updated_at: item.updated_at,
|
||||
next_refresh_at: (item.next_refresh_at as string | null) ?? null,
|
||||
}
|
||||
})
|
||||
@@ -151,7 +175,7 @@ function parseConnectionList(raw: unknown): SourceConnectionListItem[] {
|
||||
export async function fetchSourceConnectionList(signal?: AbortSignal): Promise<SourceConnectionListItem[]> {
|
||||
const response = await fetch('/api/v1/source-connections', { headers: { Accept: 'application/json' }, signal })
|
||||
if (!response.ok) throw new Error(`加载来源连接失败(HTTP ${response.status})`)
|
||||
const value = await response.json() as unknown
|
||||
const value = (await response.json()) as unknown
|
||||
if (!isRecord(value) || !Array.isArray(value.data)) throw new Error('invalid source connections response')
|
||||
return parseConnectionList(value.data)
|
||||
}
|
||||
@@ -175,10 +199,17 @@ export async function triggerSourceScan(connectionID: string): Promise<Triggered
|
||||
if (!response.ok) {
|
||||
throw new Error(response.status === 409 ? '该来源已有扫描正在运行' : `触发来源扫描失败(HTTP ${response.status})`)
|
||||
}
|
||||
const raw = await response.json() as unknown
|
||||
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.source_connection_id !== 'string' ||
|
||||
typeof raw.source_type !== 'string' || !sourceTypes.has(raw.source_type as SourceConnectionType) ||
|
||||
typeof raw.state !== 'string' || !scanStates.has(raw.state as SourceScanState) || typeof raw.created_at !== 'string') {
|
||||
const raw = (await response.json()) as unknown
|
||||
if (
|
||||
!isRecord(raw) ||
|
||||
typeof raw.id !== 'string' ||
|
||||
typeof raw.source_connection_id !== 'string' ||
|
||||
typeof raw.source_type !== 'string' ||
|
||||
!sourceTypes.has(raw.source_type as SourceConnectionType) ||
|
||||
typeof raw.state !== 'string' ||
|
||||
!scanStates.has(raw.state as SourceScanState) ||
|
||||
typeof raw.created_at !== 'string'
|
||||
) {
|
||||
throw new Error('invalid triggered source scan response')
|
||||
}
|
||||
return {
|
||||
@@ -191,8 +222,14 @@ export async function triggerSourceScan(connectionID: string): Promise<Triggered
|
||||
}
|
||||
|
||||
export function parseSourceScansResponse(value: unknown): SourceScanPage {
|
||||
if (!isRecord(value) || !Array.isArray(value.data) || !isCount(value.total) ||
|
||||
!isCount(value.limit) || value.limit < 1 || !isCount(value.offset)) {
|
||||
if (
|
||||
!isRecord(value) ||
|
||||
!Array.isArray(value.data) ||
|
||||
!isCount(value.total) ||
|
||||
!isCount(value.limit) ||
|
||||
value.limit < 1 ||
|
||||
!isCount(value.offset)
|
||||
) {
|
||||
throw new Error('invalid source scans response')
|
||||
}
|
||||
return {
|
||||
@@ -214,10 +251,15 @@ export function parseSourceScanDetailResponse(value: unknown): SourceScanDetail
|
||||
const summary = parseSourceScanSummary(value.data)
|
||||
if (!summary) throw new Error('invalid source scan detail response')
|
||||
const changes = value.data.changes.map((raw): SourceScanChangeView => {
|
||||
if (!isRecord(raw) || typeof raw.id !== 'string' ||
|
||||
(raw.source_item_id !== null && typeof raw.source_item_id !== 'string') ||
|
||||
typeof raw.change_type !== 'string' || !scanChangeTypes.has(raw.change_type as SourceScanChangeType) ||
|
||||
(raw.observed_size_bytes !== null && !isCount(raw.observed_size_bytes)) || typeof raw.created_at !== 'string') {
|
||||
if (
|
||||
!isRecord(raw) ||
|
||||
typeof raw.id !== 'string' ||
|
||||
(raw.source_item_id !== null && typeof raw.source_item_id !== 'string') ||
|
||||
typeof raw.change_type !== 'string' ||
|
||||
!scanChangeTypes.has(raw.change_type as SourceScanChangeType) ||
|
||||
(raw.observed_size_bytes !== null && !isCount(raw.observed_size_bytes)) ||
|
||||
typeof raw.created_at !== 'string'
|
||||
) {
|
||||
throw new Error('invalid source scan change')
|
||||
}
|
||||
return {
|
||||
@@ -231,31 +273,59 @@ export function parseSourceScanDetailResponse(value: unknown): SourceScanDetail
|
||||
return { ...summary, changes }
|
||||
}
|
||||
|
||||
export async function fetchSourceScans(connectionID: string, limit = 20, offset = 0, signal?: AbortSignal): Promise<SourceScanPage> {
|
||||
export async function fetchSourceScans(
|
||||
connectionID: string,
|
||||
limit = 20,
|
||||
offset = 0,
|
||||
signal?: AbortSignal
|
||||
): Promise<SourceScanPage> {
|
||||
const params = new URLSearchParams({ limit: String(limit), offset: String(offset) })
|
||||
const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/scans?${params}`, {
|
||||
headers: { Accept: 'application/json' }, signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
signal,
|
||||
})
|
||||
if (!response.ok) throw new Error(`加载扫描历史失败(HTTP ${response.status})`)
|
||||
return parseSourceScansResponse(await response.json())
|
||||
}
|
||||
|
||||
export async function fetchSourceScanDetail(connectionID: string, scanID: string, signal?: AbortSignal): Promise<SourceScanDetail> {
|
||||
const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/scans/${encodeURIComponent(scanID)}`, {
|
||||
headers: { Accept: 'application/json' }, signal,
|
||||
})
|
||||
export async function fetchSourceScanDetail(
|
||||
connectionID: string,
|
||||
scanID: string,
|
||||
signal?: AbortSignal
|
||||
): Promise<SourceScanDetail> {
|
||||
const response = await fetch(
|
||||
`/api/v1/source-connections/${encodeURIComponent(connectionID)}/scans/${encodeURIComponent(scanID)}`,
|
||||
{
|
||||
headers: { Accept: 'application/json' },
|
||||
signal,
|
||||
}
|
||||
)
|
||||
if (!response.ok) throw new Error(`加载扫描详情失败(HTTP ${response.status})`)
|
||||
return parseSourceScanDetailResponse(await response.json())
|
||||
}
|
||||
|
||||
function parseSourceScanSummary(raw: unknown): SourceScanSummary | null {
|
||||
if (raw === null || raw === undefined) return null
|
||||
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.state !== 'string' ||
|
||||
!scanStates.has(raw.state as SourceScanState) || typeof raw.error_code !== 'string' ||
|
||||
typeof raw.created_at !== 'string' || (raw.completed_at !== null && typeof raw.completed_at !== 'string')) {
|
||||
if (
|
||||
!isRecord(raw) ||
|
||||
typeof raw.id !== 'string' ||
|
||||
typeof raw.state !== 'string' ||
|
||||
!scanStates.has(raw.state as SourceScanState) ||
|
||||
typeof raw.error_code !== 'string' ||
|
||||
typeof raw.created_at !== 'string' ||
|
||||
(raw.completed_at !== null && typeof raw.completed_at !== 'string')
|
||||
) {
|
||||
throw new Error('invalid source scan summary')
|
||||
}
|
||||
const countKeys = ['observed_items', 'unchanged_items', 'added_items', 'updated_items', 'over_limit_items', 'missing_items', 'planned_uploads'] as const
|
||||
const countKeys = [
|
||||
'observed_items',
|
||||
'unchanged_items',
|
||||
'added_items',
|
||||
'updated_items',
|
||||
'over_limit_items',
|
||||
'missing_items',
|
||||
'planned_uploads',
|
||||
] as const
|
||||
for (const key of countKeys) {
|
||||
if (!isCount(raw[key])) throw new Error('invalid source scan summary')
|
||||
}
|
||||
@@ -315,63 +385,153 @@ export interface SourceSettingsDraftRequest {
|
||||
const revisionStates = new Set<SourceSettingsRevisionState>(['validated', 'active', 'retired', 'failed'])
|
||||
|
||||
function parseSettingsRevision(raw: unknown): SourceSettingsRevision {
|
||||
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.revision_number !== 'number' ||
|
||||
typeof raw.state !== 'string' || !revisionStates.has(raw.state as SourceSettingsRevisionState) ||
|
||||
typeof raw.name !== 'string' || typeof raw.endpoint !== 'string' || typeof raw.credential_ref !== 'string' ||
|
||||
typeof raw.enabled !== 'boolean' || typeof raw.refresh_interval_seconds !== 'string' ||
|
||||
typeof raw.created_by !== 'string' || typeof raw.created_at !== 'string' ||
|
||||
(raw.validated_at !== null && typeof raw.validated_at !== 'string') ||
|
||||
(raw.activated_at !== null && typeof raw.activated_at !== 'string') ||
|
||||
(raw.retired_at !== null && typeof raw.retired_at !== 'string')) {
|
||||
if (
|
||||
!isRecord(raw) ||
|
||||
typeof raw.id !== 'string' ||
|
||||
typeof raw.revision_number !== 'number' ||
|
||||
typeof raw.state !== 'string' ||
|
||||
!revisionStates.has(raw.state as SourceSettingsRevisionState) ||
|
||||
typeof raw.name !== 'string' ||
|
||||
typeof raw.endpoint !== 'string' ||
|
||||
typeof raw.credential_ref !== 'string' ||
|
||||
typeof raw.enabled !== 'boolean' ||
|
||||
typeof raw.refresh_interval_seconds !== 'string' ||
|
||||
typeof raw.created_by !== 'string' ||
|
||||
typeof raw.created_at !== 'string' ||
|
||||
(raw.validated_at !== null && typeof raw.validated_at !== 'string') ||
|
||||
(raw.activated_at !== null && typeof raw.activated_at !== 'string') ||
|
||||
(raw.retired_at !== null && typeof raw.retired_at !== 'string')
|
||||
) {
|
||||
throw new Error('invalid source settings revision')
|
||||
}
|
||||
return {
|
||||
id: raw.id, revision_number: raw.revision_number, state: raw.state as SourceSettingsRevisionState,
|
||||
name: raw.name, endpoint: raw.endpoint, credential_ref: raw.credential_ref, enabled: raw.enabled,
|
||||
refresh_interval_seconds: raw.refresh_interval_seconds, created_by: raw.created_by, created_at: raw.created_at,
|
||||
id: raw.id,
|
||||
revision_number: raw.revision_number,
|
||||
state: raw.state as SourceSettingsRevisionState,
|
||||
name: raw.name,
|
||||
endpoint: raw.endpoint,
|
||||
credential_ref: raw.credential_ref,
|
||||
enabled: raw.enabled,
|
||||
refresh_interval_seconds: raw.refresh_interval_seconds,
|
||||
created_by: raw.created_by,
|
||||
created_at: raw.created_at,
|
||||
validated_at: (raw.validated_at as string | null) ?? null,
|
||||
activated_at: (raw.activated_at as string | null) ?? null,
|
||||
retired_at: (raw.retired_at as string | null) ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchSourceSettingsRevisions(connectionID: string, signal?: AbortSignal): Promise<SourceSettingsRevision[]> {
|
||||
export async function fetchSourceSettingsRevisions(
|
||||
connectionID: string,
|
||||
signal?: AbortSignal
|
||||
): Promise<SourceSettingsRevision[]> {
|
||||
const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal,
|
||||
})
|
||||
if (!response.ok) throw new Error(`加载来源设置历史失败(HTTP ${response.status})`)
|
||||
const value = await response.json() as unknown
|
||||
const value = (await response.json()) as unknown
|
||||
if (!isRecord(value) || !Array.isArray(value.data)) throw new Error('invalid source settings revisions response')
|
||||
return value.data.map(parseSettingsRevision)
|
||||
}
|
||||
|
||||
async function postSourceSettings(path: string, body: string, errorMessage: string): Promise<{ operation: string; id: string | null }> {
|
||||
async function postSourceSettings(
|
||||
path: string,
|
||||
body: string,
|
||||
errorMessage: string
|
||||
): Promise<{ operation: string; id: string | null }> {
|
||||
const response = await fetch(path, {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Governance-Action': 'source-settings', 'Idempotency-Key': newOperationID() },
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Governance-Action': 'source-settings',
|
||||
'Idempotency-Key': newOperationID(),
|
||||
},
|
||||
body,
|
||||
})
|
||||
if (!response.ok) {
|
||||
let detail = ''
|
||||
try {
|
||||
const parsed = await response.json() as unknown
|
||||
const parsed = (await response.json()) as unknown
|
||||
if (isRecord(parsed) && typeof parsed.error === 'string') detail = parsed.error
|
||||
} catch { /* keep status-only message */ }
|
||||
} catch {
|
||||
/* keep status-only message */
|
||||
}
|
||||
throw new Error(detail ? `${errorMessage}:${detail}` : `${errorMessage}(HTTP ${response.status})`)
|
||||
}
|
||||
const value = await response.json() as unknown
|
||||
if (!isRecord(value) || (value.operation !== 'created' && value.operation !== 'replayed') || !isRecord(value.data)) throw new Error('invalid source settings response')
|
||||
const value = (await response.json()) as unknown
|
||||
if (!isRecord(value) || (value.operation !== 'created' && value.operation !== 'replayed') || !isRecord(value.data))
|
||||
throw new Error('invalid source settings response')
|
||||
const id = typeof value.data.id === 'string' ? value.data.id : null
|
||||
return { operation: value.operation, id }
|
||||
}
|
||||
|
||||
export async function createSourceSettingsRevision(connectionID: string, draft: SourceSettingsDraftRequest): Promise<{ operation: string; id: string }> {
|
||||
const result = await postSourceSettings(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions`, JSON.stringify(draft), '保存来源设置草稿失败')
|
||||
export async function createSourceSettingsRevision(
|
||||
connectionID: string,
|
||||
draft: SourceSettingsDraftRequest
|
||||
): Promise<{ operation: string; id: string }> {
|
||||
const result = await postSourceSettings(
|
||||
`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions`,
|
||||
JSON.stringify(draft),
|
||||
'保存来源设置草稿失败'
|
||||
)
|
||||
if (!result.id) throw new Error('创建来源设置草稿未返回修订号')
|
||||
return result as { operation: string; id: string }
|
||||
}
|
||||
|
||||
export async function activateSourceSettingsRevision(connectionID: string, revisionID: string): Promise<{ operation: string }> {
|
||||
return postSourceSettings(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions/${encodeURIComponent(revisionID)}/activate`, '{}', '启用来源设置修订失败')
|
||||
export async function activateSourceSettingsRevision(
|
||||
connectionID: string,
|
||||
revisionID: string
|
||||
): Promise<{ operation: string }> {
|
||||
return postSourceSettings(
|
||||
`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions/${encodeURIComponent(revisionID)}/activate`,
|
||||
'{}',
|
||||
'启用来源设置修订失败'
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 「去掉来源」:归档下架(**不是物理删除**)。
|
||||
* 来源会从数据源配置、来源与目录、计划刷新与手动扫描里消失;目录快照、发布记录与
|
||||
* 审计数据原样保留 —— 再用 dws 重新登记同一个来源就会原地复活。幂等,仅管理员可用。
|
||||
*/
|
||||
export async function archiveSourceConnection(connectionID: string): Promise<void> {
|
||||
await postSourceArchive(
|
||||
`/api/v1/source-connections/${encodeURIComponent(connectionID)}/archive`,
|
||||
'source-archive',
|
||||
'去掉来源失败'
|
||||
)
|
||||
}
|
||||
|
||||
/** 撤销归档:来源重新出现,但保持停用(调度不会自动恢复)。 */
|
||||
export async function restoreSourceConnection(connectionID: string): Promise<void> {
|
||||
await postSourceArchive(
|
||||
`/api/v1/source-connections/${encodeURIComponent(connectionID)}/restore`,
|
||||
'source-restore',
|
||||
'恢复来源失败'
|
||||
)
|
||||
}
|
||||
|
||||
async function postSourceArchive(path: string, intent: string, errorMessage: string): Promise<void> {
|
||||
const response = await fetch(path, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Governance-Action': intent,
|
||||
'Idempotency-Key': newOperationID(),
|
||||
},
|
||||
body: '{}',
|
||||
})
|
||||
if (!response.ok) {
|
||||
let detail = ''
|
||||
try {
|
||||
const parsed = (await response.json()) as unknown
|
||||
if (isRecord(parsed) && typeof parsed.error === 'string') detail = parsed.error
|
||||
} catch {
|
||||
/* keep status-only message */
|
||||
}
|
||||
throw new Error(detail ? `${errorMessage}:${detail}` : `${errorMessage}(HTTP ${response.status})`)
|
||||
}
|
||||
}
|
||||
|
||||
+841
-62
@@ -1,64 +1,843 @@
|
||||
.system-settings{max-width:1500px}.settings-role-strip{display:flex;gap:10px;margin-bottom:12px}.settings-role-strip span{border-radius:8px;padding:8px 11px;font-size:10px}.engineer-role{background:var(--c-run-bg);color:var(--c-run)}.admin-role{background:var(--bg-soft);color:var(--ink-mute)}.settings-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.settings-panel{min-width:0;border:1px solid var(--border-base);border-radius:12px;padding:15px;background:var(--bg-panel)}.settings-panel.wide{grid-column:1/-1}.settings-panel h2{margin:0 0 12px;color:var(--ink-base);font-size:14px}.settings-panel dl{display:grid;grid-template-columns:1fr auto;gap:8px;margin:0;color:var(--ink-mute);font-size:10px}.settings-panel dd{margin:0;color:var(--ink-base);font-weight:700}.settings-panel dd.ok{color:var(--c-done)}.settings-panel dd.off,.settings-panel .production span{color:var(--c-fail)}.environment-cards{display:grid;grid-template-columns:1fr 1fr;gap:10px}.environment-cards article{display:grid;grid-template-columns:1fr auto;gap:6px;border:1px solid var(--border-base);border-radius:9px;padding:11px;background:var(--bg-soft)}.environment-cards b{color:var(--ink-base);font-size:11px}.environment-cards span{color:var(--c-done);font-size:10px}.environment-cards small{grid-column:1/-1;color:var(--ink-mute);font-size:9px}.environment-cards button{grid-column:2;padding:5px 7px}.mapping-row{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}.mapping-row>*{border-radius:6px;padding:6px 8px;background:var(--border-soft);color:var(--ink-mute);font-size:9px}.dependency-grid{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:8px}.dependency-grid article{display:grid;gap:4px;border-radius:8px;padding:9px;background:var(--bg-soft)}.dependency-grid span{color:var(--ink-mute);font-size:9px}.dependency-grid b{color:var(--ink-base);font-size:10px}.dependency-grid small{color:var(--ink-mute);font-size:8px;line-height:1.5}.target-list{display:grid;gap:7px;margin:0;padding:0;list-style:none}.target-list li{display:flex;justify-content:space-between;gap:10px;color:var(--ink-mute);font-size:10px}.target-list b{color:var(--c-fail)}.settings-panel>button{margin-top:12px;padding:7px 10px}.settings-panel>small{display:block;margin-top:7px;color:var(--ink-mute);font-size:8px}.safe-setting-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}.safe-setting-grid label{display:grid;gap:6px;color:var(--ink-mute);font-size:10px}.safe-setting-grid select{border:1px solid var(--border-strong);border-radius:7px;padding:8px;background:var(--bg-panel);color:var(--ink-base)}.locked-gates{display:flex;flex-wrap:wrap;gap:7px;margin-top:11px}.locked-gates span{border-radius:6px;padding:6px 8px;background:var(--c-fail-bg);color:var(--c-fail);font-size:9px}@media(max-width:900px){.dependency-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.safe-setting-grid{grid-template-columns:1fr 1fr}}@media(max-width:650px){.settings-grid,.environment-cards{grid-template-columns:1fr}.settings-panel.wide{grid-column:auto}.dependency-grid,.safe-setting-grid{grid-template-columns:1fr}.settings-role-strip{flex-direction:column}}
|
||||
.settings-section-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:14px}.settings-section-heading h2{margin-bottom:4px}.settings-section-heading p{margin:0;color:var(--ink-mute);font-size:10px}.settings-section-heading button{padding:7px 10px;box-shadow:none}.settings-source-list{display:grid;gap:9px}.settings-source-row{display:grid;grid-template-columns:minmax(170px,.8fr) minmax(420px,2fr) minmax(130px,.55fr) auto;align-items:center;gap:14px;border:1px solid var(--border-base);border-radius:10px;padding:12px;background:var(--bg-page)}.settings-source-name{display:grid;gap:4px}.settings-source-name strong{color:var(--ink-base);font-size:12px}.settings-source-name span{color:var(--ink-mute);font-size:9px}.settings-source-row dl{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}.settings-source-row dl div{display:grid;gap:3px}.settings-source-row dt{color:var(--ink-mute);font-size:8px}.settings-source-row dd{overflow-wrap:anywhere;color:var(--ink-base);font-size:9px;font-weight:650}.settings-source-row label{display:grid;gap:5px;color:var(--ink-mute);font-size:9px}.settings-source-row select{border:1px solid #c9d9e4;border-radius:7px;padding:7px;background:var(--bg-panel);color:var(--ink-base)}.settings-source-row>button{padding:7px 9px;box-shadow:none}.dependency-grid{margin-top:12px}.storage-settings-grid{display:grid;grid-template-columns:1fr 1fr minmax(220px,.8fr);gap:14px}.storage-settings-grid>dl,.storage-settings-grid>.target-list{border:1px solid var(--border-base);border-radius:9px;padding:12px;background:var(--bg-soft)}@media(max-width:1100px){.settings-source-row{grid-template-columns:1fr 1fr}.settings-source-row dl{grid-column:1/-1}.storage-settings-grid{grid-template-columns:1fr 1fr}.storage-settings-grid>.target-list{grid-column:1/-1}}@media(max-width:700px){.settings-section-heading{flex-direction:column}.settings-source-row,.settings-source-row dl,.storage-settings-grid{grid-template-columns:1fr}.settings-source-row dl{grid-column:auto}.storage-settings-grid>.target-list{grid-column:auto}}.settings-layout{display:grid;grid-template-columns:200px minmax(0,1fr);gap:18px;align-items:start}
|
||||
.settings-nav{display:flex;flex-direction:column;gap:6px;position:sticky;top:16px}
|
||||
.settings-nav button{border:1px solid transparent;background:transparent;text-align:left;padding:9px 12px;border-radius:8px;font:inherit;cursor:pointer;color:var(--ink-base)}
|
||||
.settings-nav button:hover{background:var(--border-soft)}
|
||||
.settings-nav button.active{background:var(--c-run);color:var(--bg-panel);font-weight:600}
|
||||
.settings-content{display:flex;flex-direction:column;gap:14px;min-width:0}
|
||||
.source-schedule-form{display:flex;flex-wrap:wrap;gap:10px;align-items:end;padding-top:6px}
|
||||
.source-schedule-form label{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var(--ink-base)}
|
||||
.source-schedule-form select,.source-schedule-form input{padding:6px 8px;border:1px solid var(--border-strong);border-radius:6px;font:inherit;background:var(--bg-panel)}
|
||||
.source-schedule-actions{display:flex;gap:8px;align-items:end}
|
||||
button.danger{background:var(--c-fail);color:var(--bg-panel);border:none;padding:8px 14px;border-radius:8px;font:inherit;cursor:pointer}
|
||||
button.danger:hover{background:var(--c-fail)}
|
||||
button.danger:disabled{background:var(--c-fail-border);cursor:not-allowed}
|
||||
button.link{background:none;border:none;color:var(--c-run);cursor:pointer;text-decoration:underline;font:inherit;padding:4px}
|
||||
.manual-source-note{color:var(--ink-mute);font-size:13px}
|
||||
.error-message{color:var(--c-fail);font-size:13px;margin:4px 0}
|
||||
.revision-list{list-style:none;margin:8px 0 0;padding:8px 10px;background:var(--bg-soft);border-radius:8px;display:flex;flex-direction:column;gap:6px;font-size:13px}
|
||||
.revision-list li{display:flex;gap:8px;align-items:baseline;flex-wrap:wrap}
|
||||
.revision-list span{color:var(--c-run);font-weight:600}
|
||||
.revision-list small{color:var(--ink-mute)}
|
||||
.empty-inline{color:var(--ink-mute);font-size:13px}
|
||||
.modal-backdrop{position:fixed;inset:0;background:rgba(10,25,40,.45);display:flex;align-items:center;justify-content:center;z-index:50;padding:16px}
|
||||
.modal-card{background:var(--bg-panel);border-radius:12px;padding:20px;max-width:420px;box-shadow:0 18px 48px rgba(9,28,46,.35)}
|
||||
.modal-card h3{margin:0 0 8px}
|
||||
.modal-card p{color:var(--ink-base);font-size:14px;line-height:1.6}
|
||||
.modal-actions{display:flex;gap:10px;justify-content:flex-end;margin-top:14px}
|
||||
@media (max-width:900px){.settings-layout{grid-template-columns:1fr}.settings-nav{position:static;flex-direction:row;flex-wrap:wrap}}
|
||||
.kb-binding-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:12px 0}.kb-binding-side{display:grid;gap:4px;border:1px solid var(--border-base);border-radius:9px;padding:11px;background:var(--bg-soft)}.kb-binding-side.bound{border-color:var(--c-done)}.kb-binding-side.warn{border-color:var(--c-fail)}.kb-binding-side b{color:var(--ink-base);font-size:11px}.kb-binding-side span{color:var(--c-done);font-size:11px;word-break:break-all}.kb-binding-side.warn span{color:var(--c-fail)}.kb-binding-side small{color:var(--ink-mute);font-size:9px}.kb-binding-editor{display:grid;gap:10px;border-top:1px dashed var(--border-base);margin-top:8px;padding-top:12px}.kb-binding-editor label{display:grid;gap:6px;color:var(--ink-mute);font-size:10px}.kb-binding-editor select,.kb-binding-editor input{border:1px solid var(--border-strong);border-radius:7px;padding:8px;background:var(--bg-panel);color:var(--ink-base)}.kb-binding-editor button{justify-self:start;padding:7px 10px}@media(max-width:650px){.kb-binding-grid{grid-template-columns:1fr}}.hint{color:var(--ink-mute);font-size:10px;margin:4px 0}
|
||||
.dingtalk-session-control{display:flex;flex-direction:column;gap:4px;align-self:end}
|
||||
.dingtalk-qr-card{max-width:440px;text-align:center}
|
||||
.dingtalk-qr-hint{color:var(--ink-mute);font-size:13px;min-height:20px}
|
||||
.dingtalk-qr-image{display:block;margin:12px auto;width:320px;height:320px;image-rendering:pixelated;border:12px solid #fff;border-radius:4px;background:#fff;box-sizing:content-box}
|
||||
.dingtalk-qr-loading{display:grid;place-items:center;margin:12px auto;width:320px;height:320px;max-width:80vw;max-height:80vw;border:12px solid #fff;border-radius:4px;background:#fff;box-sizing:content-box}
|
||||
.dingtalk-qr-loading span{width:42px;height:42px;border:4px solid #dbe4ee;border-top-color:var(--brand);border-radius:50%;animation:dingtalk-qr-spin .8s linear infinite}
|
||||
@keyframes dingtalk-qr-spin{to{transform:rotate(360deg)}}
|
||||
.dingtalk-qr-card .modal-actions{justify-content:center}
|
||||
.filename-filter-editor{flex-basis:100%;margin-top:10px;padding:12px;border:1px solid var(--border-base);border-radius:10px;background:var(--bg-soft)}
|
||||
.filename-filter-heading{display:flex;justify-content:space-between;gap:10px;margin-bottom:7px}.filename-filter-heading div{display:grid;gap:3px}.filename-filter-heading small{color:var(--ink-mute)}
|
||||
.filename-filter-inherited,.filename-filter-direct{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin:6px 0}.filename-filter-inherited span,.filename-filter-direct span{font-size:10px;color:var(--ink-mute)}
|
||||
.filename-filter-editor code{padding:2px 7px;border-radius:999px;background:#eaf2ff;color:#2456a6;font-family:inherit;font-size:11px}
|
||||
.filename-filter-form{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:9px 0}.filename-filter-form input{min-width:220px;flex:1;padding:7px 9px;border:1px solid var(--border-strong);border-radius:7px;background:var(--bg-panel)}
|
||||
.filename-filter-modes{display:flex;gap:12px;align-self:center;font-size:11px;color:var(--ink-base)}.filename-filter-modes label{display:flex;gap:4px;align-items:center;cursor:pointer}
|
||||
.filename-filter-groups{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px 14px;margin:8px 0}.filename-filter-group{display:grid;gap:4px}.filename-filter-group>span{color:var(--ink-mute);font-size:9px}
|
||||
.filename-filter-group>div{display:flex;flex-wrap:wrap;gap:4px}.filename-filter-group button{border:1px solid var(--border-base);background:var(--bg-panel);color:var(--ink-base);border-radius:999px;padding:2px 8px;font-size:10px;font-family:inherit;cursor:pointer}
|
||||
.filename-filter-group button.picked{background:var(--c-run);border-color:var(--c-run);color:var(--bg-panel);font-weight:650}.filename-filter-group button.blocked{color:var(--c-fail)}
|
||||
@media(max-width:900px){.filename-filter-groups{grid-template-columns:1fr 1fr}}
|
||||
.system-settings {
|
||||
max-width: 1500px;
|
||||
}
|
||||
.settings-role-strip {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.settings-role-strip span {
|
||||
border-radius: 8px;
|
||||
padding: 8px 11px;
|
||||
font-size: 10px;
|
||||
}
|
||||
.engineer-role {
|
||||
background: var(--c-run-bg);
|
||||
color: var(--c-run);
|
||||
}
|
||||
.admin-role {
|
||||
background: var(--bg-soft);
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.settings-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
}
|
||||
.settings-panel {
|
||||
min-width: 0;
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: 12px;
|
||||
padding: 15px;
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
.settings-panel.wide {
|
||||
grid-column: 1/-1;
|
||||
}
|
||||
.settings-panel h2 {
|
||||
margin: 0 0 12px;
|
||||
color: var(--ink-base);
|
||||
font-size: 14px;
|
||||
}
|
||||
.settings-panel dl {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
color: var(--ink-mute);
|
||||
font-size: 10px;
|
||||
}
|
||||
.settings-panel dd {
|
||||
margin: 0;
|
||||
color: var(--ink-base);
|
||||
font-weight: 700;
|
||||
}
|
||||
.settings-panel dd.ok {
|
||||
color: var(--c-done);
|
||||
}
|
||||
.settings-panel dd.off,
|
||||
.settings-panel .production span {
|
||||
color: var(--c-fail);
|
||||
}
|
||||
.environment-cards {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
.environment-cards article {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
gap: 6px;
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: 9px;
|
||||
padding: 11px;
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
.environment-cards b {
|
||||
color: var(--ink-base);
|
||||
font-size: 11px;
|
||||
}
|
||||
.environment-cards span {
|
||||
color: var(--c-done);
|
||||
font-size: 10px;
|
||||
}
|
||||
.environment-cards small {
|
||||
grid-column: 1/-1;
|
||||
color: var(--ink-mute);
|
||||
font-size: 9px;
|
||||
}
|
||||
.environment-cards button {
|
||||
grid-column: 2;
|
||||
padding: 5px 7px;
|
||||
}
|
||||
.mapping-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.mapping-row > * {
|
||||
border-radius: 6px;
|
||||
padding: 6px 8px;
|
||||
background: var(--border-soft);
|
||||
color: var(--ink-mute);
|
||||
font-size: 9px;
|
||||
}
|
||||
.dependency-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(6, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
.dependency-grid article {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
border-radius: 8px;
|
||||
padding: 9px;
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
.dependency-grid span {
|
||||
color: var(--ink-mute);
|
||||
font-size: 9px;
|
||||
}
|
||||
.dependency-grid b {
|
||||
color: var(--ink-base);
|
||||
font-size: 10px;
|
||||
}
|
||||
.dependency-grid small {
|
||||
color: var(--ink-mute);
|
||||
font-size: 8px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.target-list {
|
||||
display: grid;
|
||||
gap: 7px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
.target-list li {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
color: var(--ink-mute);
|
||||
font-size: 10px;
|
||||
}
|
||||
.target-list b {
|
||||
color: var(--c-fail);
|
||||
}
|
||||
.settings-panel > button {
|
||||
margin-top: 12px;
|
||||
padding: 7px 10px;
|
||||
}
|
||||
.settings-panel > small {
|
||||
display: block;
|
||||
margin-top: 7px;
|
||||
color: var(--ink-mute);
|
||||
font-size: 8px;
|
||||
}
|
||||
.safe-setting-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.safe-setting-grid label {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
color: var(--ink-mute);
|
||||
font-size: 10px;
|
||||
}
|
||||
.safe-setting-grid select {
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 7px;
|
||||
padding: 8px;
|
||||
background: var(--bg-panel);
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.locked-gates {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 7px;
|
||||
margin-top: 11px;
|
||||
}
|
||||
.locked-gates span {
|
||||
border-radius: 6px;
|
||||
padding: 6px 8px;
|
||||
background: var(--c-fail-bg);
|
||||
color: var(--c-fail);
|
||||
font-size: 9px;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.dependency-grid {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
.safe-setting-grid {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
@media (max-width: 650px) {
|
||||
.settings-grid,
|
||||
.environment-cards {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.settings-panel.wide {
|
||||
grid-column: auto;
|
||||
}
|
||||
.dependency-grid,
|
||||
.safe-setting-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.settings-role-strip {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
.settings-section-heading {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.settings-section-heading h2 {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.settings-section-heading p {
|
||||
margin: 0;
|
||||
color: var(--ink-mute);
|
||||
font-size: 10px;
|
||||
}
|
||||
.settings-section-heading button {
|
||||
padding: 7px 10px;
|
||||
box-shadow: none;
|
||||
}
|
||||
.settings-source-list {
|
||||
display: grid;
|
||||
gap: 9px;
|
||||
}
|
||||
.settings-source-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(170px, 0.8fr) minmax(420px, 2fr) minmax(130px, 0.55fr) auto;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: 10px;
|
||||
padding: 12px;
|
||||
background: var(--bg-page);
|
||||
}
|
||||
.settings-source-name {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
.settings-source-name strong {
|
||||
color: var(--ink-base);
|
||||
font-size: 12px;
|
||||
}
|
||||
.settings-source-name span {
|
||||
color: var(--ink-mute);
|
||||
font-size: 9px;
|
||||
}
|
||||
.settings-source-row dl {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
.settings-source-row dl div {
|
||||
display: grid;
|
||||
gap: 3px;
|
||||
}
|
||||
.settings-source-row dt {
|
||||
color: var(--ink-mute);
|
||||
font-size: 8px;
|
||||
}
|
||||
.settings-source-row dd {
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--ink-base);
|
||||
font-size: 9px;
|
||||
font-weight: 650;
|
||||
}
|
||||
.settings-source-row label {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
color: var(--ink-mute);
|
||||
font-size: 9px;
|
||||
}
|
||||
.settings-source-row select {
|
||||
border: 1px solid #c9d9e4;
|
||||
border-radius: 7px;
|
||||
padding: 7px;
|
||||
background: var(--bg-panel);
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.settings-source-row > button {
|
||||
padding: 7px 9px;
|
||||
box-shadow: none;
|
||||
}
|
||||
.dependency-grid {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.storage-settings-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr minmax(220px, 0.8fr);
|
||||
gap: 14px;
|
||||
}
|
||||
.storage-settings-grid > dl,
|
||||
.storage-settings-grid > .target-list {
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: 9px;
|
||||
padding: 12px;
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
@media (max-width: 1100px) {
|
||||
.settings-source-row {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
.settings-source-row dl {
|
||||
grid-column: 1/-1;
|
||||
}
|
||||
.storage-settings-grid {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
.storage-settings-grid > .target-list {
|
||||
grid-column: 1/-1;
|
||||
}
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
.settings-section-heading {
|
||||
flex-direction: column;
|
||||
}
|
||||
.settings-source-row,
|
||||
.settings-source-row dl,
|
||||
.storage-settings-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.settings-source-row dl {
|
||||
grid-column: auto;
|
||||
}
|
||||
.storage-settings-grid > .target-list {
|
||||
grid-column: auto;
|
||||
}
|
||||
}
|
||||
.settings-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 200px minmax(0, 1fr);
|
||||
gap: 18px;
|
||||
align-items: start;
|
||||
}
|
||||
.settings-nav {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
position: sticky;
|
||||
top: 16px;
|
||||
}
|
||||
.settings-nav button {
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
padding: 9px 12px;
|
||||
border-radius: 8px;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.settings-nav button:hover {
|
||||
background: var(--border-soft);
|
||||
}
|
||||
.settings-nav button.active {
|
||||
background: var(--c-run);
|
||||
color: var(--bg-panel);
|
||||
font-weight: 600;
|
||||
}
|
||||
.settings-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
.source-schedule-form {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
align-items: end;
|
||||
padding-top: 6px;
|
||||
}
|
||||
.source-schedule-form label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 13px;
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.source-schedule-form select,
|
||||
.source-schedule-form input {
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 6px;
|
||||
font: inherit;
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
.source-schedule-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: end;
|
||||
}
|
||||
button.danger {
|
||||
background: var(--c-fail);
|
||||
color: var(--bg-panel);
|
||||
border: none;
|
||||
padding: 8px 14px;
|
||||
border-radius: 8px;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
button.danger:hover {
|
||||
background: var(--c-fail);
|
||||
}
|
||||
button.danger:disabled {
|
||||
background: var(--c-fail-border);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
button.link {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--c-run);
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
font: inherit;
|
||||
padding: 4px;
|
||||
}
|
||||
.manual-source-note {
|
||||
color: var(--ink-mute);
|
||||
font-size: 13px;
|
||||
}
|
||||
.error-message {
|
||||
color: var(--c-fail);
|
||||
font-size: 13px;
|
||||
margin: 4px 0;
|
||||
}
|
||||
.revision-list {
|
||||
list-style: none;
|
||||
margin: 8px 0 0;
|
||||
padding: 8px 10px;
|
||||
background: var(--bg-soft);
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.revision-list li {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: baseline;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.revision-list span {
|
||||
color: var(--c-run);
|
||||
font-weight: 600;
|
||||
}
|
||||
.revision-list small {
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.empty-inline {
|
||||
color: var(--ink-mute);
|
||||
font-size: 13px;
|
||||
}
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(10, 25, 40, 0.45);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 50;
|
||||
padding: 16px;
|
||||
}
|
||||
.modal-card {
|
||||
background: var(--bg-panel);
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
max-width: 420px;
|
||||
box-shadow: 0 18px 48px rgba(9, 28, 46, 0.35);
|
||||
}
|
||||
.modal-card h3 {
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.modal-card p {
|
||||
color: var(--ink-base);
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
justify-content: flex-end;
|
||||
margin-top: 14px;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.settings-layout {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.settings-nav {
|
||||
position: static;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
.kb-binding-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
margin: 12px 0;
|
||||
}
|
||||
.kb-binding-side {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: 9px;
|
||||
padding: 11px;
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
.kb-binding-side.bound {
|
||||
border-color: var(--c-done);
|
||||
}
|
||||
.kb-binding-side.warn {
|
||||
border-color: var(--c-fail);
|
||||
}
|
||||
.kb-binding-side b {
|
||||
color: var(--ink-base);
|
||||
font-size: 11px;
|
||||
}
|
||||
.kb-binding-side span {
|
||||
color: var(--c-done);
|
||||
font-size: 11px;
|
||||
word-break: break-all;
|
||||
}
|
||||
.kb-binding-side.warn span {
|
||||
color: var(--c-fail);
|
||||
}
|
||||
.kb-binding-side small {
|
||||
color: var(--ink-mute);
|
||||
font-size: 9px;
|
||||
}
|
||||
.kb-binding-editor {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
border-top: 1px dashed var(--border-base);
|
||||
margin-top: 8px;
|
||||
padding-top: 12px;
|
||||
}
|
||||
.kb-binding-editor label {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
color: var(--ink-mute);
|
||||
font-size: 10px;
|
||||
}
|
||||
.kb-binding-editor select,
|
||||
.kb-binding-editor input {
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 7px;
|
||||
padding: 8px;
|
||||
background: var(--bg-panel);
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.kb-binding-editor button {
|
||||
justify-self: start;
|
||||
padding: 7px 10px;
|
||||
}
|
||||
@media (max-width: 650px) {
|
||||
.kb-binding-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
.hint {
|
||||
color: var(--ink-mute);
|
||||
font-size: 10px;
|
||||
margin: 4px 0;
|
||||
}
|
||||
.dingtalk-session-control {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
align-self: end;
|
||||
}
|
||||
.dingtalk-qr-card {
|
||||
max-width: 440px;
|
||||
text-align: center;
|
||||
}
|
||||
.dingtalk-qr-hint {
|
||||
color: var(--ink-mute);
|
||||
font-size: 13px;
|
||||
min-height: 20px;
|
||||
}
|
||||
.dingtalk-qr-image {
|
||||
display: block;
|
||||
margin: 12px auto;
|
||||
width: 320px;
|
||||
height: 320px;
|
||||
image-rendering: pixelated;
|
||||
border: 12px solid #fff;
|
||||
border-radius: 4px;
|
||||
background: #fff;
|
||||
box-sizing: content-box;
|
||||
}
|
||||
.dingtalk-qr-loading {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
margin: 12px auto;
|
||||
width: 320px;
|
||||
height: 320px;
|
||||
max-width: 80vw;
|
||||
max-height: 80vw;
|
||||
border: 12px solid #fff;
|
||||
border-radius: 4px;
|
||||
background: #fff;
|
||||
box-sizing: content-box;
|
||||
}
|
||||
.dingtalk-qr-loading span {
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
border: 4px solid #dbe4ee;
|
||||
border-top-color: var(--brand);
|
||||
border-radius: 50%;
|
||||
animation: dingtalk-qr-spin 0.8s linear infinite;
|
||||
}
|
||||
@keyframes dingtalk-qr-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
.dingtalk-qr-card .modal-actions {
|
||||
justify-content: center;
|
||||
}
|
||||
.filename-filter-editor {
|
||||
flex-basis: 100%;
|
||||
margin-top: 10px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--border-base);
|
||||
border-radius: 10px;
|
||||
background: var(--bg-soft);
|
||||
}
|
||||
.filename-filter-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
margin-bottom: 7px;
|
||||
}
|
||||
.filename-filter-heading div {
|
||||
display: grid;
|
||||
gap: 3px;
|
||||
}
|
||||
.filename-filter-heading small {
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.filename-filter-inherited,
|
||||
.filename-filter-direct {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
margin: 6px 0;
|
||||
}
|
||||
.filename-filter-inherited span,
|
||||
.filename-filter-direct span {
|
||||
font-size: 10px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.filename-filter-editor code {
|
||||
padding: 2px 7px;
|
||||
border-radius: 999px;
|
||||
background: #eaf2ff;
|
||||
color: #2456a6;
|
||||
font-family: inherit;
|
||||
font-size: 11px;
|
||||
}
|
||||
.filename-filter-form {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
margin: 9px 0;
|
||||
}
|
||||
.filename-filter-form input {
|
||||
min-width: 220px;
|
||||
flex: 1;
|
||||
padding: 7px 9px;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 7px;
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
.filename-filter-modes {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-self: center;
|
||||
font-size: 11px;
|
||||
color: var(--ink-base);
|
||||
}
|
||||
.filename-filter-modes label {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
.filename-filter-groups {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 6px 14px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
.filename-filter-group {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
.filename-filter-group > span {
|
||||
color: var(--ink-mute);
|
||||
font-size: 9px;
|
||||
}
|
||||
.filename-filter-group > div {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
.filename-filter-group button {
|
||||
border: 1px solid var(--border-base);
|
||||
background: var(--bg-panel);
|
||||
color: var(--ink-base);
|
||||
border-radius: 999px;
|
||||
padding: 2px 8px;
|
||||
font-size: 10px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.filename-filter-group button.picked {
|
||||
background: var(--c-run);
|
||||
border-color: var(--c-run);
|
||||
color: var(--bg-panel);
|
||||
font-weight: 650;
|
||||
}
|
||||
.filename-filter-group button.blocked {
|
||||
color: var(--c-fail);
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.filename-filter-groups {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
/* 数据源发现(系统设置 → 数据源配置):列出可勾选为来源的钉钉知识库与钉盘空间。 */
|
||||
.dingtalk-discovery { display: flex; flex-direction: column; gap: 10px; padding: 12px; margin-bottom: 14px; border: 1px solid var(--border, #e3e8ec); border-radius: 10px; background: var(--card, #fff); }
|
||||
.dingtalk-discovery-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.dingtalk-discovery-heading strong { display: block; font-size: 14px; }
|
||||
.dingtalk-discovery-heading small { display: block; color: var(--muted-foreground, #5b6773); font-size: 12px; }
|
||||
.dingtalk-discovery-groups { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.discovery-group h4 { margin: 0 0 6px; font-size: 13px; }
|
||||
.discovery-group ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; max-height: 220px; overflow: auto; }
|
||||
.discovery-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 4px 6px; border-radius: 6px; }
|
||||
.discovery-row:hover { background: var(--accent, #f2f5f8); }
|
||||
.discovery-row label { display: flex; align-items: center; gap: 8px; cursor: pointer; }
|
||||
.discovery-row.registered label { cursor: default; color: var(--muted-foreground, #5b6773); }
|
||||
.discovery-row strong { font-size: 13px; font-weight: 500; }
|
||||
.discovery-row small { display: block; font-size: 11px; color: var(--muted-foreground, #5b6773); }
|
||||
.dingtalk-discovery-actions { display: flex; align-items: center; gap: 10px; }
|
||||
.dingtalk-discovery-actions small { color: var(--muted-foreground, #5b6773); font-size: 12px; }
|
||||
.dingtalk-discovery {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 12px;
|
||||
margin-bottom: 14px;
|
||||
border: 1px solid var(--border, #e3e8ec);
|
||||
border-radius: 10px;
|
||||
background: var(--card, #fff);
|
||||
}
|
||||
.dingtalk-discovery-heading {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.dingtalk-discovery-heading strong {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
}
|
||||
.dingtalk-discovery-heading small {
|
||||
display: block;
|
||||
color: var(--muted-foreground, #5b6773);
|
||||
font-size: 12px;
|
||||
}
|
||||
.dingtalk-discovery-groups {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
.discovery-group h4 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.discovery-group ul {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
}
|
||||
.discovery-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 4px 6px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.discovery-row:hover {
|
||||
background: var(--accent, #f2f5f8);
|
||||
}
|
||||
.discovery-row label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.discovery-row.registered label {
|
||||
cursor: default;
|
||||
color: var(--muted-foreground, #5b6773);
|
||||
}
|
||||
.discovery-row strong {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.discovery-row small {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: var(--muted-foreground, #5b6773);
|
||||
}
|
||||
.dingtalk-discovery-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.dingtalk-discovery-actions small {
|
||||
color: var(--muted-foreground, #5b6773);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* 折叠的 AList/钉钉知识库来源开关:默认收起,只露一行说明,不抢 PP 资料的视线。 */
|
||||
.settings-legacy-toggle {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem 0.75rem;
|
||||
margin: 0 0 0.75rem;
|
||||
}
|
||||
.settings-legacy-toggle small {
|
||||
color: #5a6572;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@@ -85,6 +85,7 @@ export const reasonLabels: Record<string, string> = {
|
||||
no_release_tag_for_commit: '没有指向该提交的正式 tag',
|
||||
no_baseline: '找不到可核验的发布基线(该版本没有对应的 tag)',
|
||||
shallow_or_incomplete_graph: '提交图不完整(检出被截断),提交数算不准',
|
||||
release_tag_created_later: '该版本是在更晚的提交上发布的 —— 这个提交当时还没有 tag',
|
||||
}
|
||||
|
||||
export const reasonLabel = (reason: string): string => reasonLabels[reason] ?? '版本号未能核验'
|
||||
|
||||
Reference in New Issue
Block a user