Compare commits
119 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8b2d0cb9df | |||
| 4d313a44eb | |||
| 01ed9fadc6 | |||
| 02a7abeb3f | |||
| 6845cdcbc5 | |||
| 4044ffd89b | |||
| 8d0c021126 | |||
| 1cb91f9444 | |||
| 2e31a485d8 | |||
| 4ad131d74d | |||
| 886bdc06ed | |||
| 562e1ba586 | |||
| e18067e028 | |||
| 613d62fdb2 | |||
| b4ce6877c8 | |||
| e53992fdc2 | |||
| a5ee06a4c7 | |||
| 7b57cba14d | |||
| 55cb047654 | |||
| beebcca4de | |||
| 9bf35e8745 | |||
| 90207bc1d5 | |||
| 2f248ea0c3 | |||
| 117d482f93 | |||
| 9f15c1c572 | |||
| 959d367ed4 | |||
| 56dcb06fb8 | |||
| f947807fba | |||
| 1997dfeb80 | |||
| 0ac86f941c | |||
| 3815d00c84 | |||
| 4172534bab | |||
| ab9820990c | |||
| 510e550f19 | |||
| 6dadd76c1b | |||
| 1a507dbf2d | |||
| 5467ed6d7b | |||
| 4b788fa73a | |||
| 7148ff9eaf | |||
| b20d980ba7 | |||
| de502e9bc3 | |||
| 9639a080c6 | |||
| d56b5ff15a | |||
| 485ed50b26 | |||
| 1655a2eab4 | |||
| df39d5a16f | |||
| 914791d63c | |||
| 5574f41129 | |||
| cd98e0603e | |||
| 4bc0f04d74 | |||
| 329dd749eb | |||
| 2a2e4c1cea | |||
| 12c1e5f3f8 | |||
| b178431a57 | |||
| 65b7ae0e2b | |||
| 4be95f50ae | |||
| f19a003dec | |||
| 8cffbf6112 | |||
| eed72ba39a | |||
| aa3e29f04e | |||
| 04db93faab | |||
| 55259683b8 | |||
| 5b4f9e961d | |||
| 98e42e6dae | |||
| 973e965f4f | |||
| f2a3ba7aca | |||
| 7b1bc1d3e8 | |||
| ae0ab0ddf4 | |||
| fca111239c | |||
| 573f9f447a | |||
| 81e0c41f1c | |||
| 9a6875b4ce | |||
| 99fb6c38c1 | |||
| 5b73082ad0 | |||
| d354e5e7c3 | |||
| 62bffebf8e | |||
| dbbbef8a0d | |||
| fdc48aa573 | |||
| 88090fcc6e | |||
| a0d432b63d | |||
| d4de81c128 | |||
| c0154c2aed | |||
| 429f991bde | |||
| c4b391cb84 | |||
| bd0f9f481a | |||
| a2acfa9a6f | |||
| 6fb17de9db | |||
| 57017ee046 | |||
| cde34428f9 | |||
| 07dc1e9add | |||
| bdf6d0f556 | |||
| 39aed2e486 | |||
| 752116fe41 | |||
| d64ce64056 | |||
| 9e0cbc7041 | |||
| 4864e92e30 | |||
| 288e1d4f4a | |||
| bb1df3c6da | |||
| 5822b64d7c | |||
| 1e17d2c852 | |||
| e230d9dc32 | |||
| b10a2d5d79 | |||
| a35cdcc68c | |||
| 37189c9252 | |||
| e1c8edd6bf | |||
| 8a3daff55b | |||
| 97d8a6c39a | |||
| 70271b408e | |||
| 623e007fae | |||
| fc0ce4ee5f | |||
| c1d26f11df | |||
| b1cadd0cc8 | |||
| 261228ed3f | |||
| 8c17e40d7d | |||
| 237e440057 | |||
| fc46cabb75 | |||
| 762f037150 | |||
| 48985d3447 | |||
| ca80cb28d2 |
@@ -4,3 +4,5 @@
|
||||
src/components/AdventurePanel.tsx
|
||||
src/data/customWorldCharacterLoadout.ts
|
||||
dist_check_monster_position/**
|
||||
# 固定上游UTF-8测试刻意包含U+FFFD;upstream-integrity.test.mjs逐字节验证来源hash。
|
||||
apps/ai-game-creator-shell/src-tauri/vendor/codex-utils-path-uri/src/api_path_string_tests.rs
|
||||
|
||||
@@ -235,6 +235,10 @@ VITE_DEBUG_MODE=""
|
||||
# This is read by api-server and exposed through /api/runtime/frontend-config.
|
||||
GENARRATIVE_ENABLE_IMAGE_EDITOR_AGENT_SIDEBAR="false"
|
||||
|
||||
# 官网客户端下载检测渠道:dev、release 或自定义渠道;修改后重启 API 服务。
|
||||
# Windows/macOS 是系统维度,不填写 dev-win/dev-mac。
|
||||
GENARRATIVE_CLIENT_DOWNLOAD_CHANNEL="dev"
|
||||
|
||||
# Optional: official VikingDB credentials for regenerating build-tag similarities
|
||||
# with the Python embedding script. The script auto-loads `.env.local` and uses
|
||||
# the fixed `bge-large-zh` embedding model.
|
||||
|
||||
@@ -31,28 +31,26 @@ env:
|
||||
RUSTC_WRAPPER: ''
|
||||
CARGO_BUILD_RUSTC_WRAPPER: ''
|
||||
|
||||
# job 声明顺序就是 runner 领取顺序,因此把最长尾的客户端 Rust 门禁排在前面,
|
||||
# job 声明顺序就是 runner 领取顺序,因此把两条最长尾的客户端 Rust lane 排在前面,
|
||||
# 让它在最少的等待下占用并发槽位;其余 job 按时长递减排列。
|
||||
#
|
||||
# 客户端(微信壳 / Expo 移动壳 / Tauri 桌面壳 / AI 游戏创作壳)门禁原先全部串在
|
||||
# `Native shell tests` 一个 job 里,实测 18 分 37 秒。现在按门禁组拆成一个分组一个 job:
|
||||
# `Native shell tests`(契约 + H5 / 微信 / 移动 / 桌面壳门禁 + 发布构建 smoke)、
|
||||
# `AI game creator shell web tests`(typecheck + 壳内测试)、`AI game creator shell
|
||||
# Rust shard 1/4` 到 `4/4`(AGC 壳 bin 单测按名单分 4 片)、`AI game creator shell
|
||||
# Rust smoke`(agent-run smoke)与 `AI game creator shell Rust crates`(AGC 壳依赖的
|
||||
# Rust lane 1/2`、`lane 2/2`(每条 lane 顺序运行两片 AGC 壳 bin 单测)、`AI game creator
|
||||
# shell Rust smoke`(agent-run smoke)与 `AI game creator shell Rust crates`(AGC 壳依赖的
|
||||
# 共享 / 平台 crate 测试)。各自的命令与拆分前逐一对应,本地
|
||||
# `npm run check:native-shells` 仍是同一条串行序列。
|
||||
#
|
||||
# AGC 壳的 bin 单测(2466 条)按名单分 4 片、一片一个 job:片内保持 `--test-threads=1`
|
||||
# (当年线程并行会互相干扰的是进程内后台锁与异步终态),片与片之间靠 job 级并发摊开。
|
||||
# 不要改回「一个 job 里多进程并行这几片」:同一容器内它们会争抢共享 HOME、target 与固定
|
||||
# 临时路径,实测比整套串行还慢。每个分片 job 都会自校验「片并集等于全集且互斥」。
|
||||
# AGC 壳的 bin 单测(2466 条)仍按名单分 4 片、片内保持 `--test-threads=1`;两条 lane
|
||||
# 各自顺序运行两片,让一次 job 只做一次依赖预热,同时避免同一容器内多进程并行争抢
|
||||
# 共享 HOME、target 与固定临时路径。每个分片调用仍会自校验「片并集等于全集且互斥」。
|
||||
jobs:
|
||||
# AGC 壳自身的 Rust bin 单测分片,4 片各自独立 job 并发执行、片内仍保持
|
||||
# `--test-threads=1`。这里不装 npm 依赖:壳 Rust 门禁只用 cargo 与 node 内建模块,
|
||||
# 也只需要 AGC 壳自己那份锁定依赖。
|
||||
ai-game-creator-shell-rust-shard-1:
|
||||
name: AI game creator shell Rust shard 1/4
|
||||
# AGC 壳自身的 Rust bin 单测由两条 lane 承载,每条 lane 顺序运行两片;这里不装 npm
|
||||
# 依赖:壳 Rust 门禁只用 cargo 与 node 内建模块,也只需要 AGC 壳自己那份锁定依赖。
|
||||
ai-game-creator-shell-rust-lane-1:
|
||||
name: AI game creator shell Rust lane 1/2
|
||||
runs-on: genarrative-ci
|
||||
steps:
|
||||
- name: Checkout full history from Gitea
|
||||
@@ -87,41 +85,11 @@ jobs:
|
||||
- name: Run AI game creator shell Rust shard 1/4
|
||||
run: npm run check:native-shells:agc-rust-shard-1
|
||||
|
||||
ai-game-creator-shell-rust-shard-2:
|
||||
name: AI game creator shell Rust shard 2/4
|
||||
runs-on: genarrative-ci
|
||||
steps:
|
||||
- name: Checkout full history from Gitea
|
||||
env:
|
||||
GENARRATIVE_GITEA_FETCH_DEPTH: '0'
|
||||
GENARRATIVE_GITEA_TOKEN: ${{ github.token }}
|
||||
run: genarrative-gitea-checkout
|
||||
|
||||
- name: Validate preinstalled CI job image and sandbox
|
||||
run: GENARRATIVE_GITEA_CI_CHECK_RUNTIME=1 bash scripts/check-gitea-ci-job-image.sh
|
||||
|
||||
- name: Prepare AI game creator shell Rust dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for attempt in $(seq 1 5); do
|
||||
if cargo fetch --locked \
|
||||
--target x86_64-unknown-linux-gnu \
|
||||
--manifest-path apps/ai-game-creator-shell/src-tauri/Cargo.toml; then
|
||||
break
|
||||
fi
|
||||
if [[ "${attempt}" -eq 5 ]]; then
|
||||
echo 'AI game creator shell Cargo dependency fetch failed after 5 attempts.' >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep $((attempt * 2))
|
||||
done
|
||||
|
||||
- name: Run AI game creator shell Rust shard 2/4
|
||||
run: npm run check:native-shells:agc-rust-shard-2
|
||||
|
||||
ai-game-creator-shell-rust-shard-3:
|
||||
name: AI game creator shell Rust shard 3/4
|
||||
ai-game-creator-shell-rust-lane-2:
|
||||
name: AI game creator shell Rust lane 2/2
|
||||
runs-on: genarrative-ci
|
||||
steps:
|
||||
- name: Checkout full history from Gitea
|
||||
@@ -153,36 +121,6 @@ jobs:
|
||||
- name: Run AI game creator shell Rust shard 3/4
|
||||
run: npm run check:native-shells:agc-rust-shard-3
|
||||
|
||||
ai-game-creator-shell-rust-shard-4:
|
||||
name: AI game creator shell Rust shard 4/4
|
||||
runs-on: genarrative-ci
|
||||
steps:
|
||||
- name: Checkout full history from Gitea
|
||||
env:
|
||||
GENARRATIVE_GITEA_FETCH_DEPTH: '0'
|
||||
GENARRATIVE_GITEA_TOKEN: ${{ github.token }}
|
||||
run: genarrative-gitea-checkout
|
||||
|
||||
- name: Validate preinstalled CI job image and sandbox
|
||||
run: GENARRATIVE_GITEA_CI_CHECK_RUNTIME=1 bash scripts/check-gitea-ci-job-image.sh
|
||||
|
||||
- name: Prepare AI game creator shell Rust dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for attempt in $(seq 1 5); do
|
||||
if cargo fetch --locked \
|
||||
--target x86_64-unknown-linux-gnu \
|
||||
--manifest-path apps/ai-game-creator-shell/src-tauri/Cargo.toml; then
|
||||
break
|
||||
fi
|
||||
if [[ "${attempt}" -eq 5 ]]; then
|
||||
echo 'AI game creator shell Cargo dependency fetch failed after 5 attempts.' >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep $((attempt * 2))
|
||||
done
|
||||
|
||||
- name: Run AI game creator shell Rust shard 4/4
|
||||
run: npm run check:native-shells:agc-rust-shard-4
|
||||
|
||||
|
||||
@@ -47,12 +47,16 @@ temp*build*/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/codex-package.json
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/manifest.json
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/NOTICE.md
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/darwin-arm64/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/darwin-x64/
|
||||
/plugins/agc-cocos-editor/native/payload/
|
||||
/plugins/agc-unity-editor/dotnet/**/bin/
|
||||
/plugins/agc-unity-editor/dotnet/**/obj/
|
||||
/plugins/agc-unity-editor/dotnet/publish/
|
||||
/plugins/agc-unity-editor/dotnet/native-build/
|
||||
/apps/ai-game-creator-shell/logs/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/node-runtime/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/node-runtime-staging-*/
|
||||
/apps/ai-game-creator-shell/.llm-drafts/
|
||||
/apps/ai-game-creator-shell/game-creator.config.local.json
|
||||
/apps/mobile-shell/.expo/
|
||||
|
||||
@@ -4,12 +4,13 @@
|
||||
|
||||
- 本文件只保留 Agent 进入仓库后必须立即遵守的最高优先级规则;完整执行细则见 [`docs/【协作规范】Agent工作入口与执行准则-2026-06-22.md`](docs/【协作规范】Agent工作入口与执行准则-2026-06-22.md)。
|
||||
- 团队级长期项目记忆位于 [`docs/project-memory/`](docs/project-memory/),供 3 名开发人员和各自本地 Agent 通过 Git 同步。
|
||||
- [`.codex/`](.codex/) 只保存仓库级 Codex 工具资源,例如 skills、plugins、hooks 和配置模板;长期项目知识不要写入 `.codex/`。
|
||||
- [`.codex/`](.codex/) 保存仓库级 Codex 工具资源,例如 skills、plugins、hooks 和配置模板;长期项目知识写入 `docs/` 与 `docs/project-memory/`。
|
||||
- 若 `docs/project-memory/shared-memory/` 与当前代码或最新 `docs/` 冲突,以代码和最新 `docs/` 为准,并同步修正过期共享记忆。
|
||||
|
||||
## 开始任务前
|
||||
|
||||
- 先写清一句话交付结果、验收判据和不做项,再按“必须项 / 风险项 / 可选项”排序;优先完成修改、定向验证和边界检查组成的最小闭环。设置时间盒和检查点,新增发现只有在影响交付判据时才扩大范围,否则记录为后续事项;工具探测、历史整理或验证便利不能自行改变任务目标。
|
||||
- 先写清一句话交付结果、验收判据和修改范围,再按“必须项 / 风险项 / 可选项”排序;优先完成修改、定向验证和边界检查组成的最小闭环。设置时间盒和检查点,新增发现只有在影响交付判据时才扩大范围,其余记录为后续事项。
|
||||
- Agent 可见内容直接描述当前任务、输入和成功条件,细节按调用需要提供。
|
||||
- 简单自包含任务可以直接执行;复杂开发、跨模块修改、后端 / UI / 文档体系调整前,按顺序读取:
|
||||
1. 本文件。
|
||||
2. [`docs/【协作规范】Agent工作入口与执行准则-2026-06-22.md`](docs/【协作规范】Agent工作入口与执行准则-2026-06-22.md)。
|
||||
@@ -23,24 +24,20 @@
|
||||
|
||||
- 禁止提交个人 `~/.codex` 配置、`.env`、API Key、Token、Cookie、会话记录、认证文件、本地私密路径、构建产物、日志、缓存和数据库 dump。
|
||||
- 不要在 `.gitignore` 中新增 `.env.local`。
|
||||
- 不要擅自把现有中文文案、注释、剧情或文档改写成英文;看到中文乱码时先确认真实编码,不要沿用乱码或用英文替换。
|
||||
- 修改包含中文的文件时优先局部补丁,避免整文件重写;修改后优先运行仓库编码检查。
|
||||
- 后续新增 Markdown 文档文件名必须以分类标签开头,格式为 `【标签名】中文标题-日期.md`;历史文档不要求批量重命名,除非本次任务明确涉及。
|
||||
- 现有中文文案、注释、剧情和文档保持中文;看到乱码时先确认真实编码并恢复正确中文。
|
||||
- 修改包含中文的文件时优先局部补丁;修改后优先运行仓库编码检查。
|
||||
- 新增 Markdown 文档文件名必须以分类标签开头,格式为 `【标签名】中文标题-日期.md`。
|
||||
- 工程修改要同步更新对应 `docs/` 文档;产生长期有效的架构约定、接口变化、排障经验、开发流程或协作规则时,同步更新 `docs/project-memory/shared-memory/`。
|
||||
- 默认保持系统简洁:优先复用、修改、扩展现有系统、页面和公共组件,不新建平行系统或平行页面。
|
||||
- UI 开发优先复用现有公共组件;发现跨页面或跨端重复的视觉/交互模式时,先抽取到 `packages/shared` 共享组件库并让现有页面迁移使用,禁止在业务页复制同类 UI。共享组件只承载通用表现与交互,不下沉领域规则、后端副作用或正式业务状态。
|
||||
- 对已明确退役且不存在现役调用方、公开契约、持久化数据、活跃实例或迁移要求的对象,坚持“四不写”:
|
||||
1. 不写历史兼容代码。
|
||||
2. 不写用于维持退役行为的防御性兼容测试。
|
||||
3. 不写仅说明其曾存在或已删除的墓碑注释。
|
||||
4. 不写仅记录其已删除的墓碑文档;直接将权威文档更新为当前状态。
|
||||
- 公开 API、持久化数据、SpacetimeDB schema、跨版本重放、活跃实例和正式迁移不适用“四不写”;必要兼容应最小化、白名单化并配套契约或迁移测试,迁移完成后同步删除兼容实现与对应测试。
|
||||
- UI 面板中不要默认写功能说明、规则描述或开发解释文案;移动端优先,同时保证网页端可正常显示和操作。
|
||||
- 点击按钮弹出独立面板的设计,不要实现成在当前面板下面追加内容。
|
||||
- 默认保持系统简洁:优先复用、修改、扩展现有系统、页面和公共组件。
|
||||
- UI 开发优先复用现有公共组件;发现跨页面或跨端重复的视觉/交互模式时,先抽取到 `packages/shared` 共享组件库并让现有页面迁移使用。共享组件承载通用表现与交互,领域规则、后端副作用和正式业务状态由后端负责。
|
||||
- 对已明确退役且不存在现役调用方、公开契约、持久化数据、活跃实例或迁移要求的对象,直接清理实现、专属测试和说明,将权威文档更新为当前状态;历史由 Git 保存。
|
||||
- 公开 API、持久化数据、SpacetimeDB schema、跨版本重放、活跃实例和正式迁移按实际需求保留最小、白名单化的兼容,并配套契约或迁移测试;迁移完成后同步删除兼容实现与对应测试。
|
||||
- UI 面板优先呈现任务内容与操作,说明按当前操作需要提供;移动端优先,同时保证网页端可正常显示和操作。
|
||||
- 点击按钮弹出的独立面板使用弹窗、抽屉、popover 或页面级 portal。
|
||||
|
||||
## 任务路由
|
||||
|
||||
- Issue 使用自托管 Gitea;优先用 Gitea UI/API 或 `tea` CLI,不使用 GitHub `gh` 或 GitLab `glab`,除非仓库已迁移。默认 triage 标签:`needs-triage`、`needs-info`、`ready-for-agent`、`ready-for-human`、`wontfix`。
|
||||
- Issue 使用自托管 Gitea;优先用 Gitea UI/API 或 `tea` CLI。默认 triage 标签:`needs-triage`、`needs-info`、`ready-for-agent`、`ready-for-human`、`wontfix`。
|
||||
- 需要仓库级 Codex skills/plugins 时,再读取 [`.codex/README.md`](.codex/README.md)。
|
||||
- 涉及 AI 游戏创作独立 App、多智能体 Runtime、本地项目产物或本地 HTTP 预览时,先读取 [`docs/technical/【技术方案】AI游戏创作智能体App实施计划-2026-06-24.md`](docs/technical/【技术方案】AI游戏创作智能体App实施计划-2026-06-24.md)。
|
||||
- 新增、补齐、迁移或重构玩法入口、玩法类型、创作工作台、生成页、结果页、发布、运行态、作品架、广场或公开 read model 前,必须读取并按 [`genarrative-play-type-integration`](.codex/skills/genarrative-play-type-integration/SKILL.md) 执行。
|
||||
@@ -50,10 +47,10 @@
|
||||
## 后端红线
|
||||
|
||||
- 后端最新技术约束以 [`docs/【后端架构】server-rs与SpacetimeDB数据契约-2026-05-15.md`](docs/【后端架构】server-rs与SpacetimeDB数据契约-2026-05-15.md) 为准。
|
||||
- 后端路线固定为 `server-rs + Axum + SpacetimeDB`;旧 `server-node`、Express、PostgreSQL、Go 服务端、`maincloud` / `Maincloud` / `MAINCLOUD` 只作为历史残留,不作为兼容目标。
|
||||
- 后端路线固定为 `server-rs + Axum + SpacetimeDB`。
|
||||
- DDD 分层边界按总纲执行:领域规则沉到 `module-*`,SpacetimeDB 表和事务编排留在 `spacetime-module`,后端访问 SpacetimeDB 统一经 `spacetime-client` facade,HTTP/SSE/BFF 留在 `api-server`,外部副作用留在 `platform-*`,前后端 DTO 留在 `shared-contracts`。
|
||||
- 前端只做表现、交互和临时 UI 状态,不承接正式业务真相,不绕过后端投影或后端 API 直接实现业务规则。
|
||||
- 契约、路由、DTO 去留和 breaking change 以当前后端架构文档、`server-rs/crates/api-server/src/app.rs`、`shared-contracts` 和 `packages/shared` 为准;不得在前端、`api-server` 或临时兼容层中重新发明旧接口。
|
||||
- 前端负责表现、交互和临时 UI 状态;正式业务状态与规则以后端投影和后端 API 为准。
|
||||
- 契约、路由、DTO 去留和 breaking change 以当前后端架构文档、`server-rs/crates/api-server/src/app.rs`、`shared-contracts` 和 `packages/shared` 为准。
|
||||
- 凡修改 `/api/external/v1` 的路由、HTTP 方法、请求 / 响应 DTO、请求头、状态码、鉴权或异步语义,必须在同一次变更中同步更新权威契约 [`docs/openapi/genarrative-external-v1.openapi.json`](docs/openapi/genarrative-external-v1.openapi.json) 及对应契约测试;Rust 实现与 OpenAPI 未保持一致时任务不得视为完成。
|
||||
- SpacetimeDB 已有表新增字段时,字段必须放在 Rust 表结构体最后,并设置明确默认值;需要删除、改名、重排或改类型时,必须先询问用户并确认迁移计划。
|
||||
- 修改 SpacetimeDB schema 后必须同步 `migration.rs`、表目录和生成绑定,并运行 `npm run check:spacetime-schema`。
|
||||
|
||||
@@ -3,12 +3,14 @@ import { afterEach, expect, test, vi } from 'vitest';
|
||||
import {
|
||||
createAdminAccount,
|
||||
executeAdminRechargeRefund,
|
||||
getAdminAgcTemplates,
|
||||
getAdminFeatureGateConfig,
|
||||
getAdminUserDetail,
|
||||
listAdminRechargeOrders,
|
||||
reconcileAdminUserConsumption,
|
||||
resolveAdminRechargeRefundManualReview,
|
||||
updateAdminAccount,
|
||||
updateAdminAgcTemplate,
|
||||
uploadAdminEditorShowcaseCampaignImage,
|
||||
upsertAdminFeatureGateConfig,
|
||||
upsertProfileWalletConfig,
|
||||
@@ -18,6 +20,51 @@ afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
test('模板管理读取和更新复用认证封装,提交 revision 和封面但不提交 ZIP 或版本', async () => {
|
||||
const library = { revision: 'revision-new', writable: true, templates: [] };
|
||||
const fetchMock = vi.fn().mockImplementation(
|
||||
async () =>
|
||||
new Response(JSON.stringify({ ok: true, data: library }), {
|
||||
status: 200,
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const controller = new AbortController();
|
||||
expect(await getAdminAgcTemplates('admin-token', controller.signal)).toEqual(
|
||||
library,
|
||||
);
|
||||
const update = {
|
||||
expectedRevision: 'revision-old',
|
||||
title: '空白模板',
|
||||
summary: '简介',
|
||||
tags: ['2D'],
|
||||
enabled: true,
|
||||
cover: { contentType: 'image/png', dataBase64: 'aW1hZ2U=' },
|
||||
};
|
||||
expect(
|
||||
await updateAdminAgcTemplate('admin-token', 'template/1', update),
|
||||
).toEqual(library);
|
||||
expect(fetchMock.mock.calls[0]).toEqual([
|
||||
'/admin/api/agc-templates',
|
||||
expect.objectContaining({
|
||||
method: 'GET',
|
||||
signal: controller.signal,
|
||||
headers: expect.objectContaining({ Authorization: 'Bearer admin-token' }),
|
||||
}),
|
||||
]);
|
||||
expect(fetchMock.mock.calls[1]).toEqual([
|
||||
'/admin/api/agc-templates/template%2F1',
|
||||
expect.objectContaining({
|
||||
method: 'PUT',
|
||||
headers: expect.objectContaining({
|
||||
Authorization: 'Bearer admin-token',
|
||||
'Content-Type': 'application/json',
|
||||
}),
|
||||
body: JSON.stringify(update),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
test('后台账号创建和更新同时携带 Tab 与独立操作权限', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation(() =>
|
||||
Promise.resolve(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
AdminAccountListResponse,
|
||||
AdminAgcTemplateLibraryResponse,
|
||||
AdminConfirmEditorShowcaseCampaignImageUploadRequest,
|
||||
AdminCreateAccountRequest,
|
||||
AdminCreateAccountResponse,
|
||||
@@ -47,6 +48,7 @@ import type {
|
||||
AdminTrackingEventListResponse,
|
||||
AdminUpdateAccountRequest,
|
||||
AdminUpdateAccountResponse,
|
||||
AdminUpdateAgcTemplateRequest,
|
||||
AdminUploadedEditorShowcaseCampaignImage,
|
||||
AdminUpsertEditorShowcaseCampaignRequest,
|
||||
AdminUpsertFeatureGateConfigRequest,
|
||||
@@ -1176,3 +1178,21 @@ export function saveAgcModelCatalog(
|
||||
{ token, method: 'PUT', body },
|
||||
);
|
||||
}
|
||||
|
||||
export function getAdminAgcTemplates(token: string, signal?: AbortSignal) {
|
||||
return request<AdminAgcTemplateLibraryResponse>('/admin/api/agc-templates', {
|
||||
token,
|
||||
signal,
|
||||
});
|
||||
}
|
||||
|
||||
export function updateAdminAgcTemplate(
|
||||
token: string,
|
||||
id: string,
|
||||
body: AdminUpdateAgcTemplateRequest,
|
||||
) {
|
||||
return request<AdminAgcTemplateLibraryResponse>(
|
||||
`/admin/api/agc-templates/${encodeURIComponent(id)}`,
|
||||
{ token, method: 'PUT', body },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -144,6 +144,8 @@ export interface AdminErrorReportListResponse {
|
||||
}
|
||||
|
||||
export interface AdminErrorReportDetail extends AdminErrorReportEntry {
|
||||
firstFingerprint?: string;
|
||||
firstSource?: string;
|
||||
note?: string;
|
||||
events: Array<Record<string, unknown>>;
|
||||
logNames: string[];
|
||||
@@ -1031,3 +1033,35 @@ export interface AdminAgcModelCatalog {
|
||||
defaultModelId: string;
|
||||
models: AdminAgcModel[];
|
||||
}
|
||||
|
||||
export interface AdminAgcTemplatePayload {
|
||||
id: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
tags: string[];
|
||||
runtime: string;
|
||||
engine: string;
|
||||
engineVersion: string;
|
||||
templateVersion: string;
|
||||
enabled: boolean;
|
||||
coverUrl: string;
|
||||
zipSizeBytes: number;
|
||||
}
|
||||
|
||||
export interface AdminAgcTemplateLibraryResponse {
|
||||
revision: string;
|
||||
writable: boolean;
|
||||
templates: AdminAgcTemplatePayload[];
|
||||
}
|
||||
|
||||
export interface AdminUpdateAgcTemplateRequest {
|
||||
expectedRevision: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
tags: string[];
|
||||
enabled: boolean;
|
||||
cover?: {
|
||||
contentType: string;
|
||||
dataBase64: string;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
} from '../auth/adminAuthStore';
|
||||
import { AdminAccountsPage } from '../pages/AdminAccountsPage';
|
||||
import { AdminAgcModelsPage } from '../pages/AdminAgcModelsPage';
|
||||
import { AdminAgcTemplatesPage } from '../pages/AdminAgcTemplatesPage';
|
||||
import { AdminDashboardPage } from '../pages/AdminDashboardPage';
|
||||
import { AdminDatabaseTablesPage } from '../pages/AdminDatabaseTablesPage';
|
||||
import { AdminDebugHttpPage } from '../pages/AdminDebugHttpPage';
|
||||
@@ -294,6 +295,12 @@ export function AdminApp() {
|
||||
{activeRouteId === 'agc-models' ? (
|
||||
<AdminAgcModelsPage token={token} onUnauthorized={handleUnauthorized} />
|
||||
) : null}
|
||||
{activeRouteId === 'agc-templates' ? (
|
||||
<AdminAgcTemplatesPage
|
||||
token={token}
|
||||
onUnauthorized={handleUnauthorized}
|
||||
/>
|
||||
) : null}
|
||||
{activeRouteId === 'editor-showcase' ? (
|
||||
<AdminEditorShowcaseReviewPage
|
||||
token={token}
|
||||
|
||||
@@ -53,6 +53,7 @@ const routeIcons = {
|
||||
'project-snapshots': FolderArchive,
|
||||
accounts: Users,
|
||||
'agc-models': ListChecks,
|
||||
'agc-templates': Images,
|
||||
} satisfies Record<AdminRouteId, typeof LayoutDashboard>;
|
||||
|
||||
export function AdminShell({
|
||||
|
||||
@@ -147,3 +147,30 @@ test('项目工程入口对 owner 与已授权 member 开放且可分配权限',
|
||||
}),
|
||||
).not.toContainEqual(route);
|
||||
});
|
||||
|
||||
test('模板管理只对 owner 或具有 agc-templates 权限的 member 可见', () => {
|
||||
expect(adminRoutes).toContainEqual({
|
||||
id: 'agc-templates',
|
||||
label: '模板管理',
|
||||
hash: '#agc-templates',
|
||||
});
|
||||
expect(resolveAdminRoute('#agc-templates')).toBe('agc-templates');
|
||||
expect(routeHash('agc-templates')).toBe('#agc-templates');
|
||||
expect(
|
||||
getAccessibleAdminRoutes({ accountRole: 'owner', tabPermissions: [] }).some(
|
||||
(route) => route.id === 'agc-templates',
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
getAccessibleAdminRoutes({
|
||||
accountRole: 'member',
|
||||
tabPermissions: ['agc-templates'],
|
||||
}).map((route) => route.id),
|
||||
).toEqual(['agc-templates']);
|
||||
expect(
|
||||
getAccessibleAdminRoutes({
|
||||
accountRole: 'member',
|
||||
tabPermissions: ['editor-assets'],
|
||||
}).some((route) => route.id === 'agc-templates'),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
@@ -18,6 +18,7 @@ export type AdminRouteId =
|
||||
| 'editor-assets'
|
||||
| 'project-snapshots'
|
||||
| 'agc-models'
|
||||
| 'agc-templates'
|
||||
| 'accounts';
|
||||
|
||||
export type AdminTabPermission = Exclude<
|
||||
@@ -53,6 +54,7 @@ export const adminRoutes: AdminRouteDefinition[] = [
|
||||
hash: '#editor-generation-pricing',
|
||||
},
|
||||
{ id: 'agc-models', label: 'AGC 模型', hash: '#agc-models', ownerOnly: true },
|
||||
{ id: 'agc-templates', label: '模板管理', hash: '#agc-templates' },
|
||||
{ id: 'editor-showcase', label: '精选审核', hash: '#editor-showcase' },
|
||||
{ id: 'editor-assets', label: '素材查询', hash: '#editor-assets' },
|
||||
{ id: 'project-snapshots', label: '项目工程', hash: '#project-snapshots' },
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import '@genarrative/shared/styles.css';
|
||||
import './styles/admin.css';
|
||||
|
||||
import { StrictMode } from 'react';
|
||||
|
||||
@@ -0,0 +1,498 @@
|
||||
// @vitest-environment jsdom
|
||||
import {
|
||||
act,
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from '@testing-library/react';
|
||||
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
AdminApiError,
|
||||
getAdminAgcTemplates,
|
||||
updateAdminAgcTemplate,
|
||||
} from '../api/adminApiClient';
|
||||
import type {
|
||||
AdminAgcTemplateLibraryResponse,
|
||||
AdminAgcTemplatePayload,
|
||||
} from '../api/adminApiTypes';
|
||||
import { AdminAgcTemplatesPage } from './AdminAgcTemplatesPage';
|
||||
|
||||
vi.mock('../api/adminApiClient', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../api/adminApiClient')>()),
|
||||
getAdminAgcTemplates: vi.fn(),
|
||||
updateAdminAgcTemplate: vi.fn(),
|
||||
}));
|
||||
|
||||
const template: AdminAgcTemplatePayload = {
|
||||
id: 'cocos-empty-2d',
|
||||
title: '空白 2D',
|
||||
summary: '二维项目',
|
||||
tags: ['2D', '入门'],
|
||||
runtime: 'cocos',
|
||||
engine: 'Cocos Creator',
|
||||
engineVersion: '3.8.8',
|
||||
templateVersion: '1',
|
||||
enabled: true,
|
||||
coverUrl: 'https://example.test/cover.png',
|
||||
zipSizeBytes: 2048,
|
||||
};
|
||||
const library: AdminAgcTemplateLibraryResponse = {
|
||||
revision: 'rev-1',
|
||||
writable: true,
|
||||
templates: [
|
||||
template,
|
||||
{
|
||||
...template,
|
||||
id: 'godot-starter',
|
||||
title: 'Godot 起步',
|
||||
runtime: 'godot',
|
||||
engine: 'Godot',
|
||||
engineVersion: '4',
|
||||
tags: ['3D'],
|
||||
enabled: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(getAdminAgcTemplates)
|
||||
.mockReset()
|
||||
.mockImplementation(async () => structuredClone(library));
|
||||
vi.mocked(updateAdminAgcTemplate)
|
||||
.mockReset()
|
||||
.mockImplementation(async (_token, id, update) => ({
|
||||
...structuredClone(library),
|
||||
revision: 'rev-2',
|
||||
templates: library.templates.map((entry) =>
|
||||
entry.id === id
|
||||
? {
|
||||
...entry,
|
||||
title: update.title,
|
||||
summary: update.summary,
|
||||
tags: update.tags,
|
||||
enabled: update.enabled,
|
||||
}
|
||||
: entry,
|
||||
),
|
||||
}));
|
||||
vi.stubGlobal(
|
||||
'URL',
|
||||
Object.assign(class extends URL {}, {
|
||||
createObjectURL: vi.fn(() => 'blob:template-cover'),
|
||||
revokeObjectURL: vi.fn(),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function openEditor() {
|
||||
fireEvent.click(await screen.findByRole('button', { name: '编辑 空白 2D' }));
|
||||
return screen.getByRole('dialog', { name: '编辑模板' });
|
||||
}
|
||||
|
||||
async function confirmWrite() {
|
||||
const confirmation = await screen.findByRole('dialog', { name: '确认操作' });
|
||||
fireEvent.click(within(confirmation).getByRole('button', { name: '确认' }));
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason: unknown) => void;
|
||||
const promise = new Promise<T>((next, fail) => {
|
||||
resolve = next;
|
||||
reject = fail;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
test('按名称、ID、标签、运行时和上下架状态筛选,展示版本与封面', async () => {
|
||||
render(<AdminAgcTemplatesPage token="token" onUnauthorized={vi.fn()} />);
|
||||
await screen.findByText('空白 2D');
|
||||
expect(screen.getByText('Cocos Creator 3.8.8')).not.toBeNull();
|
||||
expect(screen.getAllByText('模板 1')).toHaveLength(2);
|
||||
expect(screen.getAllByText('2.0 KiB')).toHaveLength(2);
|
||||
expect(
|
||||
screen.getByRole('img', { name: '空白 2D封面' }).getAttribute('src'),
|
||||
).toBe(template.coverUrl);
|
||||
for (const value of ['空白', 'cocos-empty-2d', '入门']) {
|
||||
fireEvent.change(screen.getByLabelText('搜索模板'), { target: { value } });
|
||||
expect(screen.getByText('空白 2D')).not.toBeNull();
|
||||
expect(screen.queryByText('Godot 起步')).toBeNull();
|
||||
}
|
||||
fireEvent.change(screen.getByLabelText('搜索模板'), {
|
||||
target: { value: '' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('运行时'), {
|
||||
target: { value: 'godot' },
|
||||
});
|
||||
expect(screen.queryByText('空白 2D')).toBeNull();
|
||||
fireEvent.change(screen.getByLabelText('上架状态'), {
|
||||
target: { value: 'enabled' },
|
||||
});
|
||||
expect(screen.getByText('没有符合筛选条件的模板')).not.toBeNull();
|
||||
});
|
||||
|
||||
test('独立弹窗保存经写确认,只提交展示字段和冻结 revision', async () => {
|
||||
render(<AdminAgcTemplatesPage token="token" onUnauthorized={vi.fn()} />);
|
||||
const editor = await openEditor();
|
||||
expect(editor.closest('.admin-agc-templates')).toBeNull();
|
||||
fireEvent.change(within(editor).getByLabelText('名称'), {
|
||||
target: { value: ' 新名称 ' },
|
||||
});
|
||||
fireEvent.change(within(editor).getByLabelText('简介'), {
|
||||
target: { value: '新简介' },
|
||||
});
|
||||
fireEvent.change(within(editor).getByLabelText('标签'), {
|
||||
target: { value: '2D, 新手,2D' },
|
||||
});
|
||||
fireEvent.click(within(editor).getByRole('button', { name: '保存' }));
|
||||
expect(updateAdminAgcTemplate).not.toHaveBeenCalled();
|
||||
await confirmWrite();
|
||||
await waitFor(() =>
|
||||
expect(updateAdminAgcTemplate).toHaveBeenCalledWith('token', template.id, {
|
||||
expectedRevision: 'rev-1',
|
||||
title: '新名称',
|
||||
summary: '新简介',
|
||||
tags: ['2D', '新手'],
|
||||
enabled: true,
|
||||
}),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('dialog', { name: '编辑模板' })).toBeNull(),
|
||||
);
|
||||
expect(screen.getByText('新名称')).not.toBeNull();
|
||||
expect(screen.getByText('已保存')).not.toBeNull();
|
||||
});
|
||||
|
||||
test('上下架复用确认且只用服务端结果更新列表', async () => {
|
||||
render(<AdminAgcTemplatesPage token="token" onUnauthorized={vi.fn()} />);
|
||||
fireEvent.click(await screen.findByRole('button', { name: '下架 空白 2D' }));
|
||||
await confirmWrite();
|
||||
await waitFor(() =>
|
||||
expect(updateAdminAgcTemplate).toHaveBeenCalledWith('token', template.id, {
|
||||
expectedRevision: 'rev-1',
|
||||
title: template.title,
|
||||
summary: template.summary,
|
||||
tags: template.tags,
|
||||
enabled: false,
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
await screen.findByRole('button', { name: '上架 空白 2D' }),
|
||||
).not.toBeNull();
|
||||
});
|
||||
|
||||
test('只读模式禁用字段、保存与上下架', async () => {
|
||||
vi.mocked(getAdminAgcTemplates).mockResolvedValue({
|
||||
...library,
|
||||
writable: false,
|
||||
});
|
||||
render(<AdminAgcTemplatesPage token="token" onUnauthorized={vi.fn()} />);
|
||||
expect(
|
||||
await screen.findByText('当前为只读模式,无法保存或上下架'),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
(screen.getByRole('button', { name: '下架 空白 2D' }) as HTMLButtonElement)
|
||||
.disabled,
|
||||
).toBe(true);
|
||||
const editor = await openEditor();
|
||||
expect(
|
||||
(within(editor).getByLabelText('名称') as HTMLInputElement).disabled,
|
||||
).toBe(true);
|
||||
expect(
|
||||
(within(editor).getByRole('button', { name: '保存' }) as HTMLButtonElement)
|
||||
.disabled,
|
||||
).toBe(true);
|
||||
expect(updateAdminAgcTemplate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('409 保留草稿,显式刷新后重新编辑才采用新 revision,不自动重试', async () => {
|
||||
vi.mocked(updateAdminAgcTemplate).mockRejectedValueOnce(
|
||||
new AdminApiError({ message: '模板库已被修改', status: 409 }),
|
||||
);
|
||||
render(<AdminAgcTemplatesPage token="token" onUnauthorized={vi.fn()} />);
|
||||
let editor = await openEditor();
|
||||
fireEvent.change(within(editor).getByLabelText('名称'), {
|
||||
target: { value: '未保存草稿' },
|
||||
});
|
||||
fireEvent.click(within(editor).getByRole('button', { name: '保存' }));
|
||||
await confirmWrite();
|
||||
await screen.findByText('模板库已被修改');
|
||||
expect((screen.getByLabelText('名称') as HTMLInputElement).value).toBe(
|
||||
'未保存草稿',
|
||||
);
|
||||
expect(updateAdminAgcTemplate).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
(screen.getByRole('button', { name: '保存' }) as HTMLButtonElement)
|
||||
.disabled,
|
||||
).toBe(true);
|
||||
vi.mocked(getAdminAgcTemplates).mockResolvedValueOnce({
|
||||
...library,
|
||||
revision: 'rev-3',
|
||||
templates: [{ ...template, title: '最新名称' }],
|
||||
});
|
||||
fireEvent.click(screen.getByRole('button', { name: '刷新后重新编辑' }));
|
||||
await screen.findByDisplayValue('最新名称');
|
||||
editor = screen.getByRole('dialog', { name: '编辑模板' });
|
||||
fireEvent.change(within(editor).getByLabelText('名称'), {
|
||||
target: { value: '重新编辑' },
|
||||
});
|
||||
fireEvent.click(within(editor).getByRole('button', { name: '保存' }));
|
||||
await confirmWrite();
|
||||
await waitFor(() =>
|
||||
expect(updateAdminAgcTemplate).toHaveBeenLastCalledWith(
|
||||
'token',
|
||||
template.id,
|
||||
expect.objectContaining({ expectedRevision: 'rev-3', title: '重新编辑' }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('防止重复确认和保存中重复提交', async () => {
|
||||
const pending = deferred<AdminAgcTemplateLibraryResponse>();
|
||||
vi.mocked(updateAdminAgcTemplate).mockReturnValue(pending.promise);
|
||||
render(<AdminAgcTemplatesPage token="token" onUnauthorized={vi.fn()} />);
|
||||
const editor = await openEditor();
|
||||
const form = within(editor).getByLabelText('名称').closest('form')!;
|
||||
fireEvent.submit(form);
|
||||
fireEvent.submit(form);
|
||||
expect(screen.getAllByRole('dialog', { name: '确认操作' })).toHaveLength(1);
|
||||
await confirmWrite();
|
||||
await waitFor(() => expect(updateAdminAgcTemplate).toHaveBeenCalledTimes(1));
|
||||
fireEvent.submit(form);
|
||||
expect(updateAdminAgcTemplate).toHaveBeenCalledTimes(1);
|
||||
await act(async () => pending.resolve(library));
|
||||
});
|
||||
|
||||
test.each([409, 503])(
|
||||
'滚到表单底部后出现 HTTP %s 写入错误,聚焦并仅滚动弹窗到提示区',
|
||||
async (status) => {
|
||||
vi.mocked(updateAdminAgcTemplate).mockRejectedValueOnce(
|
||||
new AdminApiError({ message: '本次保存失败', status }),
|
||||
);
|
||||
render(
|
||||
<div data-testid="background-page">
|
||||
<AdminAgcTemplatesPage token="token" onUnauthorized={vi.fn()} />
|
||||
</div>,
|
||||
);
|
||||
const background = screen.getByTestId('background-page');
|
||||
background.scrollTop = 240;
|
||||
const editor = await openEditor();
|
||||
const viewport = editor.querySelector<HTMLElement>(
|
||||
'.genarrative-ui-modal__body',
|
||||
)!;
|
||||
viewport.scrollTop = 400;
|
||||
const bounds = (top: number, bottom: number) =>
|
||||
({
|
||||
top,
|
||||
bottom,
|
||||
height: bottom - top,
|
||||
left: 0,
|
||||
right: 300,
|
||||
width: 300,
|
||||
x: 0,
|
||||
y: top,
|
||||
toJSON: () => ({}),
|
||||
}) as DOMRect;
|
||||
vi.spyOn(viewport, 'getBoundingClientRect').mockReturnValue(
|
||||
bounds(100, 450),
|
||||
);
|
||||
const originalBounds = HTMLElement.prototype.getBoundingClientRect;
|
||||
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(
|
||||
function (this: HTMLElement) {
|
||||
return this.classList.contains('admin-agc-template-feedback')
|
||||
? bounds(-280, -120)
|
||||
: originalBounds.call(this);
|
||||
},
|
||||
);
|
||||
const windowScroll = vi
|
||||
.spyOn(window, 'scrollTo')
|
||||
.mockImplementation(() => {});
|
||||
const focus = vi.spyOn(HTMLElement.prototype, 'focus');
|
||||
fireEvent.click(within(editor).getByRole('button', { name: '保存' }));
|
||||
await confirmWrite();
|
||||
const message = await screen.findByRole('alert');
|
||||
const feedback = message.parentElement!;
|
||||
expect(document.activeElement).toBe(feedback);
|
||||
expect(feedback.tabIndex).toBe(-1);
|
||||
expect(focus).toHaveBeenCalledWith({ preventScroll: true });
|
||||
expect(viewport.scrollTop).toBe(20);
|
||||
expect(background.scrollTop).toBe(240);
|
||||
expect(windowScroll).not.toHaveBeenCalled();
|
||||
if (status === 409) {
|
||||
expect(
|
||||
within(feedback).getByRole('button', { name: '刷新后重新编辑' }),
|
||||
).not.toBeNull();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test('token 切换后忽略旧列表和未确认写操作', async () => {
|
||||
const pending = deferred<AdminAgcTemplateLibraryResponse>();
|
||||
vi.mocked(getAdminAgcTemplates).mockReturnValueOnce(pending.promise);
|
||||
const props = { onUnauthorized: vi.fn() };
|
||||
const view = render(<AdminAgcTemplatesPage token="old" {...props} />);
|
||||
view.rerender(<AdminAgcTemplatesPage token="new" {...props} />);
|
||||
await screen.findByText('空白 2D');
|
||||
await act(async () =>
|
||||
pending.resolve({
|
||||
...library,
|
||||
templates: [{ ...template, title: '过期列表' }],
|
||||
}),
|
||||
);
|
||||
expect(screen.queryByText('过期列表')).toBeNull();
|
||||
const editor = await openEditor();
|
||||
fireEvent.click(within(editor).getByRole('button', { name: '保存' }));
|
||||
view.rerender(<AdminAgcTemplatesPage token="third" {...props} />);
|
||||
await screen.findByText('空白 2D');
|
||||
expect(screen.queryByRole('dialog')).toBeNull();
|
||||
expect(updateAdminAgcTemplate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test.each(['success', 'unauthorized'])(
|
||||
'token 切换后忽略旧保存 %s,不污染新会话',
|
||||
async (result) => {
|
||||
const pending = deferred<AdminAgcTemplateLibraryResponse>();
|
||||
vi.mocked(updateAdminAgcTemplate).mockReturnValueOnce(pending.promise);
|
||||
const onUnauthorized = vi.fn();
|
||||
const view = render(
|
||||
<AdminAgcTemplatesPage token="old" onUnauthorized={onUnauthorized} />,
|
||||
);
|
||||
const editor = await openEditor();
|
||||
fireEvent.click(within(editor).getByRole('button', { name: '保存' }));
|
||||
await confirmWrite();
|
||||
await waitFor(() =>
|
||||
expect(updateAdminAgcTemplate).toHaveBeenCalledTimes(1),
|
||||
);
|
||||
view.rerender(
|
||||
<AdminAgcTemplatesPage token="new" onUnauthorized={onUnauthorized} />,
|
||||
);
|
||||
await screen.findByText('空白 2D');
|
||||
await act(async () => {
|
||||
if (result === 'success') {
|
||||
pending.resolve({
|
||||
...library,
|
||||
templates: [{ ...template, title: '旧保存结果' }],
|
||||
});
|
||||
} else {
|
||||
pending.reject(
|
||||
new AdminApiError({ status: 401, message: '旧会话失效' }),
|
||||
);
|
||||
}
|
||||
});
|
||||
expect(onUnauthorized).not.toHaveBeenCalled();
|
||||
expect(screen.queryByText('旧会话失效')).toBeNull();
|
||||
expect(screen.queryByText('旧保存结果')).toBeNull();
|
||||
expect(screen.queryByText('已保存')).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
test('封面在草稿中转 base64,保存携带,取消释放预览 URL 且不串到下一条', async () => {
|
||||
render(<AdminAgcTemplatesPage token="token" onUnauthorized={vi.fn()} />);
|
||||
let editor = await openEditor();
|
||||
const file = new File(['cover'], 'cover.png', { type: 'image/png' });
|
||||
fireEvent.change(within(editor).getByLabelText('更换封面'), {
|
||||
target: { files: [file] },
|
||||
});
|
||||
await waitFor(() => expect(screen.queryByText('正在读取封面')).toBeNull());
|
||||
fireEvent.click(within(editor).getByRole('button', { name: '保存' }));
|
||||
await confirmWrite();
|
||||
await waitFor(() =>
|
||||
expect(updateAdminAgcTemplate).toHaveBeenCalledWith(
|
||||
'token',
|
||||
template.id,
|
||||
expect.objectContaining({
|
||||
cover: { contentType: 'image/png', dataBase64: 'Y292ZXI=' },
|
||||
}),
|
||||
),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:template-cover'),
|
||||
);
|
||||
editor = await openEditor();
|
||||
fireEvent.change(within(editor).getByLabelText('更换封面'), {
|
||||
target: { files: [file] },
|
||||
});
|
||||
fireEvent.click(within(editor).getByRole('button', { name: '取消' }));
|
||||
fireEvent.click(screen.getByRole('button', { name: '编辑 Godot 起步' }));
|
||||
expect(
|
||||
screen.getByRole('img', { name: '模板封面预览' }).getAttribute('src'),
|
||||
).toBe(template.coverUrl);
|
||||
expect(URL.revokeObjectURL).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['bad.svg', 'image/svg+xml', 1, '封面仅支持 PNG、JPEG 或 WebP'],
|
||||
[
|
||||
'large.png',
|
||||
'image/png',
|
||||
5 * 1024 * 1024 + 1,
|
||||
'封面文件须大于 0 且不超过 5 MiB',
|
||||
],
|
||||
])('拒绝无效封面 %s,不上传', async (name, type, size, message) => {
|
||||
render(<AdminAgcTemplatesPage token="token" onUnauthorized={vi.fn()} />);
|
||||
const editor = await openEditor();
|
||||
const file = new File(['x'], name, { type });
|
||||
Object.defineProperty(file, 'size', { value: size });
|
||||
fireEvent.change(within(editor).getByLabelText('更换封面'), {
|
||||
target: { files: [file] },
|
||||
});
|
||||
expect(screen.getByText(message)).not.toBeNull();
|
||||
expect(
|
||||
(screen.getByRole('button', { name: '保存' }) as HTMLButtonElement)
|
||||
.disabled,
|
||||
).toBe(true);
|
||||
expect(URL.createObjectURL).not.toHaveBeenCalled();
|
||||
expect(updateAdminAgcTemplate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('名称和标签校验失败时不进入写确认', async () => {
|
||||
render(<AdminAgcTemplatesPage token="token" onUnauthorized={vi.fn()} />);
|
||||
const editor = await openEditor();
|
||||
fireEvent.change(within(editor).getByLabelText('名称'), {
|
||||
target: { value: ' ' },
|
||||
});
|
||||
fireEvent.click(within(editor).getByRole('button', { name: '保存' }));
|
||||
expect(screen.getByText('名称须为 1–80 个字符')).not.toBeNull();
|
||||
fireEvent.change(within(editor).getByLabelText('名称'), {
|
||||
target: { value: '有效名称' },
|
||||
});
|
||||
fireEvent.change(within(editor).getByLabelText('标签'), {
|
||||
target: {
|
||||
value: Array.from({ length: 17 }, (_, index) => `标签${index}`).join(','),
|
||||
},
|
||||
});
|
||||
fireEvent.click(within(editor).getByRole('button', { name: '保存' }));
|
||||
expect(
|
||||
screen.getByText('最多 16 个标签,每个标签不超过 32 个字符'),
|
||||
).not.toBeNull();
|
||||
expect(updateAdminAgcTemplate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('读取失败显示真实错误,401 交给会话处理且不显示空库', async () => {
|
||||
const onUnauthorized = vi.fn();
|
||||
vi.mocked(getAdminAgcTemplates).mockRejectedValueOnce(
|
||||
new AdminApiError({ status: 503, message: '模板服务不可用' }),
|
||||
);
|
||||
render(
|
||||
<AdminAgcTemplatesPage token="token" onUnauthorized={onUnauthorized} />,
|
||||
);
|
||||
await screen.findByText('模板服务不可用');
|
||||
expect(screen.queryByText('暂无模板')).toBeNull();
|
||||
vi.mocked(getAdminAgcTemplates).mockRejectedValueOnce(
|
||||
new AdminApiError({ status: 401, message: '会话失效' }),
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: '刷新' }));
|
||||
await waitFor(() =>
|
||||
expect(onUnauthorized).toHaveBeenCalledWith('登录状态已失效'),
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
formatAdminTimestamp,
|
||||
parseAdminTimestamp,
|
||||
} from './AdminErrorReportsPage';
|
||||
|
||||
describe('错误报告时间格式化', () => {
|
||||
it('解析 SpacetimeDB seconds.microsZ 时间', () => {
|
||||
expect(parseAdminTimestamp('1778207451.731746Z')).toBe(1778207451731);
|
||||
});
|
||||
|
||||
it('解析微秒字符串并拒绝无效时间', () => {
|
||||
expect(parseAdminTimestamp('1778207451731746')).toBe(1778207451731);
|
||||
expect(formatAdminTimestamp('not-a-date')).toBe('-');
|
||||
expect(formatAdminTimestamp('999999999999999999999999')).toBe('-');
|
||||
});
|
||||
});
|
||||
@@ -17,6 +17,57 @@ type Props = { token: string; onUnauthorized: (message?: string) => void };
|
||||
|
||||
const ADMIN_ERROR_REPORT_STATUSES = ['new', 'in-progress', 'resolved'] as const;
|
||||
const ERROR_REPORT_PAGE_SIZE = 50;
|
||||
const ERROR_REPORT_STATUS_LABELS: Record<string, string> = {
|
||||
new: '待处理',
|
||||
'in-progress': '处理中',
|
||||
resolved: '已解决',
|
||||
};
|
||||
|
||||
export function parseAdminTimestamp(value: string | null | undefined) {
|
||||
const normalized = value?.trim() ?? '';
|
||||
if (/^-?\d+\.\d{6}Z$/u.test(normalized)) {
|
||||
const [secondsText, microsText] = normalized.slice(0, -1).split('.');
|
||||
const seconds = Number(secondsText);
|
||||
const micros = Number(microsText);
|
||||
return Number.isFinite(seconds) && Number.isFinite(micros)
|
||||
? seconds * 1000 + Math.floor(micros / 1000)
|
||||
: Number.NaN;
|
||||
}
|
||||
if (/^-?\d+$/u.test(normalized)) {
|
||||
const numeric = Number(normalized);
|
||||
if (!Number.isFinite(numeric)) return Number.NaN;
|
||||
if (Math.abs(numeric) >= 1e14) return Math.floor(numeric / 1000);
|
||||
if (Math.abs(numeric) >= 1e11) return numeric;
|
||||
return numeric * 1000;
|
||||
}
|
||||
return Date.parse(normalized);
|
||||
}
|
||||
|
||||
export function formatAdminTimestamp(value: string | null | undefined) {
|
||||
const timestamp = parseAdminTimestamp(value);
|
||||
if (!Number.isFinite(timestamp)) return '-';
|
||||
const date = new Date(timestamp);
|
||||
if (!Number.isFinite(date.getTime())) return '-';
|
||||
try {
|
||||
return new Intl.DateTimeFormat('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
}).format(date);
|
||||
} catch {
|
||||
return '-';
|
||||
}
|
||||
}
|
||||
|
||||
function eventText(event: Record<string, unknown>, key: string) {
|
||||
const value = event[key];
|
||||
return typeof value === 'string' || typeof value === 'number'
|
||||
? String(value)
|
||||
: '';
|
||||
}
|
||||
|
||||
export function AdminErrorReportsPage({ token, onUnauthorized }: Props) {
|
||||
const [reports, setReports] = useState<AdminErrorReportEntry[]>([]);
|
||||
@@ -29,6 +80,24 @@ export function AdminErrorReportsPage({ token, onUnauthorized }: Props) {
|
||||
const [pageInfo, setPageInfo] = useState({ total: 0, hasMore: false });
|
||||
const openReportRequestId = useRef(0);
|
||||
const loadRequestId = useRef(0);
|
||||
const detailCloseButtonRef = useRef<HTMLButtonElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selected) return;
|
||||
const previousFocus = document.activeElement as HTMLElement | null;
|
||||
const focusFrame = window.requestAnimationFrame(() => {
|
||||
detailCloseButtonRef.current?.focus();
|
||||
});
|
||||
const handleEscape = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') setSelected(null);
|
||||
};
|
||||
window.addEventListener('keydown', handleEscape);
|
||||
return () => {
|
||||
window.cancelAnimationFrame(focusFrame);
|
||||
window.removeEventListener('keydown', handleEscape);
|
||||
previousFocus?.focus?.();
|
||||
};
|
||||
}, [selected]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const requestId = ++loadRequestId.current;
|
||||
@@ -184,9 +253,15 @@ export function AdminErrorReportsPage({ token, onUnauthorized }: Props) {
|
||||
<td>{report.batchId}</td>
|
||||
<td>{report.eventCount}</td>
|
||||
<td>{report.source ?? '-'}</td>
|
||||
<td>{report.status}</td>
|
||||
<td>
|
||||
<span
|
||||
className={`admin-error-report-status is-${report.status}`}
|
||||
>
|
||||
{ERROR_REPORT_STATUS_LABELS[report.status] ?? report.status}
|
||||
</span>
|
||||
</td>
|
||||
<td>{report.userId}</td>
|
||||
<td>{new Date(report.createdAt).toLocaleString()}</td>
|
||||
<td>{formatAdminTimestamp(report.createdAt)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
@@ -224,66 +299,173 @@ export function AdminErrorReportsPage({ token, onUnauthorized }: Props) {
|
||||
className="admin-detail-modal"
|
||||
role="dialog"
|
||||
aria-label="错误报告详情"
|
||||
aria-modal="true"
|
||||
onMouseDown={(event) => {
|
||||
if (event.target === event.currentTarget) setSelected(null);
|
||||
}}
|
||||
>
|
||||
<div className="admin-detail-modal__panel">
|
||||
<header>
|
||||
<h2>{selected.batchId}</h2>
|
||||
<button type="button" onClick={() => setSelected(null)}>
|
||||
关闭
|
||||
<div className="admin-detail-modal__panel admin-error-report-detail">
|
||||
<header className="admin-error-report-detail__header">
|
||||
<div className="admin-error-report-detail__heading">
|
||||
<span className="admin-error-report-detail__eyebrow">
|
||||
错误报告详情
|
||||
</span>
|
||||
<h2>{selected.batchId}</h2>
|
||||
<div className="admin-error-report-detail__badges">
|
||||
<span
|
||||
className={`admin-error-report-status is-${selected.status}`}
|
||||
>
|
||||
{ERROR_REPORT_STATUS_LABELS[selected.status] ??
|
||||
selected.status}
|
||||
</span>
|
||||
<span className="admin-error-report-detail__badge">
|
||||
{selected.firstSource ?? selected.source ?? '未知来源'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="admin-error-report-detail__close"
|
||||
ref={detailCloseButtonRef}
|
||||
onClick={() => setSelected(null)}
|
||||
aria-label="关闭错误报告详情"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
<p>
|
||||
用户:{selected.userId} · 事件:{selected.eventCount} · 日志:
|
||||
{selected.logCount}
|
||||
</p>
|
||||
<pre>{JSON.stringify(selected.events.slice(0, 20), null, 2)}</pre>
|
||||
{selected.userDescription ? (
|
||||
<p>用户描述:{selected.userDescription}</p>
|
||||
) : null}
|
||||
<label className="admin-detail-modal__note">
|
||||
处理备注
|
||||
<textarea
|
||||
value={selected.note ?? ''}
|
||||
onChange={(event) =>
|
||||
setSelected((current) =>
|
||||
current
|
||||
? { ...current, note: event.target.value }
|
||||
: current,
|
||||
)
|
||||
}
|
||||
maxLength={2000}
|
||||
rows={4}
|
||||
placeholder="记录处理结论或后续跟进事项"
|
||||
disabled={busy}
|
||||
/>
|
||||
</label>
|
||||
<div className="admin-detail-modal__actions">
|
||||
<select
|
||||
value={selected.status}
|
||||
onChange={(event) => void saveStatus(event.target.value)}
|
||||
disabled={busy}
|
||||
>
|
||||
{ADMIN_ERROR_REPORT_STATUSES.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{value}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void saveStatus(selected.status)}
|
||||
disabled={busy}
|
||||
>
|
||||
保存备注
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void download(selected.batchId)}
|
||||
disabled={downloading}
|
||||
>
|
||||
{downloading ? '下载中…' : '下载诊断包'}
|
||||
</button>
|
||||
<div className="admin-error-report-detail__summary">
|
||||
<div>
|
||||
<span>用户</span>
|
||||
<strong>{selected.userId}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>发生时间</span>
|
||||
<strong>{formatAdminTimestamp(selected.createdAt)}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>错误事件</span>
|
||||
<strong>{selected.eventCount}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>应用日志</span>
|
||||
<strong>{selected.logCount}</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-error-report-detail__body">
|
||||
<section className="admin-error-report-detail__section">
|
||||
<div className="admin-error-report-detail__section-heading">
|
||||
<div>
|
||||
<h3>错误事件</h3>
|
||||
<span>展示最近 20 条,完整内容请下载诊断包。</span>
|
||||
</div>
|
||||
<span className="admin-error-report-detail__count">
|
||||
{selected.events.length} 条
|
||||
</span>
|
||||
</div>
|
||||
<div className="admin-error-report-event-list">
|
||||
{selected.events.length === 0 ? (
|
||||
<p className="admin-error-report-detail__empty">
|
||||
归档中没有可展示的错误事件。
|
||||
</p>
|
||||
) : null}
|
||||
{selected.events.slice(0, 20).map((event, index) => {
|
||||
const message = eventText(event, 'message') || '未知错误';
|
||||
const stack = eventText(event, 'stack');
|
||||
const occurredAt = eventText(event, 'occurredAt');
|
||||
return (
|
||||
<article
|
||||
className="admin-error-report-event"
|
||||
key={`${index}-${message}`}
|
||||
>
|
||||
<div className="admin-error-report-event__topline">
|
||||
<span className="admin-error-report-event__index">
|
||||
#{index + 1}
|
||||
</span>
|
||||
<span>{eventText(event, 'source') || 'client'}</span>
|
||||
<span>{eventText(event, 'count') || '1'} 次</span>
|
||||
<time>{formatAdminTimestamp(occurredAt)}</time>
|
||||
</div>
|
||||
<p className="admin-error-report-event__message">
|
||||
{message}
|
||||
</p>
|
||||
{eventText(event, 'fingerprint') ? (
|
||||
<code>{eventText(event, 'fingerprint')}</code>
|
||||
) : null}
|
||||
{stack ? (
|
||||
<details>
|
||||
<summary>查看调用栈</summary>
|
||||
<pre>{stack}</pre>
|
||||
</details>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
{selected.userDescription ? (
|
||||
<section className="admin-error-report-detail__section">
|
||||
<div className="admin-error-report-detail__section-heading">
|
||||
<div>
|
||||
<h3>用户描述</h3>
|
||||
</div>
|
||||
</div>
|
||||
<p className="admin-error-report-detail__description">
|
||||
{selected.userDescription}
|
||||
</p>
|
||||
</section>
|
||||
) : null}
|
||||
<section className="admin-error-report-detail__section admin-error-report-detail__section--note">
|
||||
<label className="admin-detail-modal__note">
|
||||
<span>处理备注</span>
|
||||
<textarea
|
||||
value={selected.note ?? ''}
|
||||
onChange={(event) =>
|
||||
setSelected((current) =>
|
||||
current
|
||||
? { ...current, note: event.target.value }
|
||||
: current,
|
||||
)
|
||||
}
|
||||
maxLength={2000}
|
||||
rows={4}
|
||||
placeholder="记录处理结论或后续跟进事项"
|
||||
disabled={busy}
|
||||
/>
|
||||
</label>
|
||||
</section>
|
||||
</div>
|
||||
<footer className="admin-error-report-detail__footer">
|
||||
<label className="admin-error-report-detail__status-field">
|
||||
状态
|
||||
<select
|
||||
value={selected.status}
|
||||
onChange={(event) => void saveStatus(event.target.value)}
|
||||
disabled={busy}
|
||||
>
|
||||
{ADMIN_ERROR_REPORT_STATUSES.map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{ERROR_REPORT_STATUS_LABELS[value]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="admin-error-report-detail__footer-actions">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void saveStatus(selected.status)}
|
||||
disabled={busy}
|
||||
>
|
||||
{busy ? '保存中…' : '保存备注'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void download(selected.batchId)}
|
||||
disabled={downloading}
|
||||
>
|
||||
{downloading ? '下载中…' : '下载诊断包'}
|
||||
</button>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -154,6 +154,27 @@ test('灰度发布页可通过功能入口生成画布 Agent Gate Key', async ()
|
||||
);
|
||||
});
|
||||
|
||||
test('灰度发布页可选择模板库并默认启用零比例灰度', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<AdminGrayReleaseConfigPage token="admin-token" onUnauthorized={vi.fn()} />,
|
||||
);
|
||||
await screen.findByRole('button', { name: 'editor.new-toolbar' });
|
||||
await user.selectOptions(screen.getByLabelText('Gate Key 前缀'), ['agc']);
|
||||
expect((screen.getByLabelText('Gate Key') as HTMLInputElement).value).toBe(
|
||||
'agc:template-library',
|
||||
);
|
||||
expect(
|
||||
(screen.getByLabelText('Gate Key 目标') as HTMLSelectElement).value,
|
||||
).toBe('template-library');
|
||||
expect((screen.getByLabelText('启用') as HTMLInputElement).checked).toBe(
|
||||
true,
|
||||
);
|
||||
expect((screen.getByLabelText('灰度比例') as HTMLInputElement).value).toBe(
|
||||
'0',
|
||||
);
|
||||
});
|
||||
|
||||
test('灰度发布页保存时转换数组和百分比', async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(upsertAdminFeatureGateConfig).mockResolvedValueOnce({
|
||||
|
||||
@@ -27,9 +27,17 @@ interface GateTargetOption {
|
||||
|
||||
const GATE_PREFIX_LABELS: Record<string, string> = {
|
||||
'image-editor': '画布',
|
||||
agc: '客户端',
|
||||
};
|
||||
|
||||
const FIXED_GATE_TARGETS: GateTargetOption[] = [
|
||||
{
|
||||
prefix: 'agc',
|
||||
suffix: 'template-library',
|
||||
key: 'agc:template-library',
|
||||
label: '模板库',
|
||||
description: '客户端模板库灰度',
|
||||
},
|
||||
{
|
||||
prefix: 'image-editor',
|
||||
suffix: 'agent-sidebar',
|
||||
@@ -180,7 +188,7 @@ export function AdminGrayReleaseConfigPage({
|
||||
setSelectedGateKey('');
|
||||
setGatePrefix(option.prefix);
|
||||
setGateKey(option.key);
|
||||
setEnabled(false);
|
||||
setEnabled(option.key === 'agc:template-library');
|
||||
setRolloutPercent('0');
|
||||
setAllowUserIds('');
|
||||
setAllowUserTags('');
|
||||
|
||||
@@ -13,6 +13,87 @@
|
||||
text-rendering: optimizeLegibility;
|
||||
}
|
||||
|
||||
.admin-agc-templates {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.admin-agc-template-filters {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(180px, 1fr) repeat(2, minmax(130px, 190px));
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.admin-agc-template-table {
|
||||
min-width: 850px;
|
||||
}
|
||||
|
||||
.admin-agc-template-table td:nth-child(2) {
|
||||
min-width: 230px;
|
||||
max-width: 380px;
|
||||
}
|
||||
|
||||
.admin-agc-template-cover {
|
||||
display: block;
|
||||
width: 88px;
|
||||
height: 62px;
|
||||
border-radius: 8px;
|
||||
object-fit: cover;
|
||||
background: #f8efe7;
|
||||
}
|
||||
|
||||
.admin-agc-template-summary {
|
||||
display: -webkit-box;
|
||||
overflow: hidden;
|
||||
margin: 8px 0;
|
||||
color: #866954;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
|
||||
.admin-agc-template-tags,
|
||||
.admin-agc-template-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.admin-agc-template-tags span {
|
||||
padding: 3px 7px;
|
||||
border-radius: 5px;
|
||||
background: #f8efe7;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.admin-agc-template-dialog {
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.admin-agc-template-editor,
|
||||
.admin-agc-template-conflict {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.admin-agc-template-cover-preview {
|
||||
display: block;
|
||||
width: min(100%, 300px);
|
||||
max-height: 180px;
|
||||
border-radius: 8px;
|
||||
object-fit: contain;
|
||||
background: #f8efe7;
|
||||
}
|
||||
|
||||
.admin-agc-template-dialog .admin-confirm-backdrop {
|
||||
z-index: 1100;
|
||||
}
|
||||
|
||||
@media (max-width: 680px) {
|
||||
.admin-agc-template-filters {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
@@ -3213,6 +3294,377 @@ button:disabled {
|
||||
padding: 12px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.admin-error-report-detail {
|
||||
width: min(980px, 100%);
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
border: 1px solid #eadfd6;
|
||||
background: #fffdfb;
|
||||
box-shadow: 0 24px 80px rgb(57 31 18 / 22%);
|
||||
}
|
||||
|
||||
.admin-error-report-detail__header {
|
||||
align-items: flex-start;
|
||||
padding: 24px 28px 20px;
|
||||
border-bottom: 1px solid #eee2d8;
|
||||
background: linear-gradient(135deg, #fffaf5, #fffdfb 65%);
|
||||
}
|
||||
|
||||
.admin-error-report-detail__heading {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__eyebrow {
|
||||
display: block;
|
||||
margin-bottom: 7px;
|
||||
color: #a4775d;
|
||||
font-size: 12px;
|
||||
font-weight: 750;
|
||||
letter-spacing: 0.08em;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__heading h2 {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
color: #3d2a20;
|
||||
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
|
||||
font-size: 19px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__badges,
|
||||
.admin-error-report-detail__footer-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__badges {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__badge,
|
||||
.admin-error-report-detail__count {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 26px;
|
||||
padding: 0 9px;
|
||||
border: 1px solid #eadfd6;
|
||||
border-radius: 999px;
|
||||
color: #785b49;
|
||||
background: #fff;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__close {
|
||||
display: inline-flex;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 0 0 auto;
|
||||
border: 1px solid #e5d5c8;
|
||||
border-radius: 9px;
|
||||
color: #765848;
|
||||
background: #fff;
|
||||
font-size: 24px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__close:hover,
|
||||
.admin-error-report-detail__close:focus-visible {
|
||||
border-color: #b6623f;
|
||||
color: #9b4f31;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.admin-error-report-status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 26px;
|
||||
padding: 0 9px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.admin-error-report-status.is-new {
|
||||
color: #a14e20;
|
||||
background: #fff0e5;
|
||||
}
|
||||
|
||||
.admin-error-report-status.is-in-progress {
|
||||
color: #72551b;
|
||||
background: #fff7d9;
|
||||
}
|
||||
|
||||
.admin-error-report-status.is-resolved {
|
||||
color: #28704d;
|
||||
background: #e9f7ee;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__summary {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.7fr) repeat(3, minmax(100px, 1fr));
|
||||
gap: 1px;
|
||||
border-bottom: 1px solid #eee2d8;
|
||||
background: #eee2d8;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__summary > div {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
gap: 5px;
|
||||
padding: 14px 18px;
|
||||
background: #fffdfb;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__summary span,
|
||||
.admin-error-report-detail__section-heading span,
|
||||
.admin-error-report-detail__status-field {
|
||||
color: #997d6a;
|
||||
font-size: 12px;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__summary strong {
|
||||
overflow-wrap: anywhere;
|
||||
color: #4d3326;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__body {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
max-height: min(62vh, 640px);
|
||||
overflow: auto;
|
||||
padding: 20px 28px;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__section {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__section-heading {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__section-heading h3 {
|
||||
margin: 0 0 4px;
|
||||
color: #4d3326;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__section-heading span {
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__count {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.admin-error-report-event-list {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__empty {
|
||||
margin: 0;
|
||||
padding: 16px;
|
||||
border: 1px dashed #e4d2c5;
|
||||
border-radius: 10px;
|
||||
color: #997d6a;
|
||||
background: #fffaf6;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.admin-error-report-event {
|
||||
display: grid;
|
||||
gap: 9px;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid #eee2d8;
|
||||
border-radius: 12px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.admin-error-report-event__topline {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: #927663;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.admin-error-report-event__topline time {
|
||||
margin-left: auto;
|
||||
color: #aa9282;
|
||||
}
|
||||
|
||||
.admin-error-report-event__index {
|
||||
color: #b6623f;
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.admin-error-report-event__message {
|
||||
margin: 0;
|
||||
color: #4a3024;
|
||||
font-size: 14px;
|
||||
line-height: 1.55;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.admin-error-report-event code {
|
||||
overflow-wrap: anywhere;
|
||||
color: #957a69;
|
||||
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.admin-error-report-event details {
|
||||
border-top: 1px solid #f0e7df;
|
||||
padding-top: 9px;
|
||||
}
|
||||
|
||||
.admin-error-report-event summary {
|
||||
color: #a15d3e;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.admin-error-report-event pre {
|
||||
max-height: 180px;
|
||||
margin: 9px 0 0;
|
||||
padding: 10px;
|
||||
border: 1px solid #f0e7df;
|
||||
background: #fffaf6;
|
||||
color: #72594a;
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__description {
|
||||
margin: 0;
|
||||
padding: 13px 15px;
|
||||
border-radius: 10px;
|
||||
color: #634b3c;
|
||||
background: #fff8f2;
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__section--note {
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__section--note .admin-detail-modal__note {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
color: #624938;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__section--note textarea {
|
||||
width: 100%;
|
||||
min-height: 100px;
|
||||
box-sizing: border-box;
|
||||
resize: vertical;
|
||||
border: 1px solid #e4d2c5;
|
||||
border-radius: 10px;
|
||||
padding: 11px 12px;
|
||||
color: #4d3326;
|
||||
background: #fff;
|
||||
font: inherit;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__section--note textarea:focus {
|
||||
border-color: #b6623f;
|
||||
box-shadow: 0 0 0 3px rgb(182 98 63 / 14%);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__footer {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 16px 28px 20px;
|
||||
border-top: 1px solid #eee2d8;
|
||||
background: #fffaf6;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__status-field {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__status-field select {
|
||||
min-width: 132px;
|
||||
min-height: 38px;
|
||||
border: 1px solid #e4d2c5;
|
||||
border-radius: 8px;
|
||||
padding: 0 10px;
|
||||
color: #4d3326;
|
||||
background: #fff;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__footer-actions button {
|
||||
min-height: 38px;
|
||||
border: 1px solid #d9c3b4;
|
||||
border-radius: 8px;
|
||||
padding: 0 13px;
|
||||
color: #6d4b3a;
|
||||
background: #fff;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__footer-actions button:last-child {
|
||||
border-color: #a96442;
|
||||
color: #fff;
|
||||
background: #a96442;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__footer-actions button:hover,
|
||||
.admin-error-report-detail__footer-actions button:focus-visible {
|
||||
border-color: #a96442;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.admin-error-report-detail__header,
|
||||
.admin-error-report-detail__body,
|
||||
.admin-error-report-detail__footer {
|
||||
padding-right: 18px;
|
||||
padding-left: 18px;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__summary {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.admin-error-report-detail__footer {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.admin-error-report-detail__footer-actions button {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
.admin-agc-models {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
@@ -66,15 +66,15 @@
|
||||
"zustand": "^5.0.14"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@openai/codex": "0.147.0",
|
||||
"@openai/codex": "0.155.1",
|
||||
"@tailwindcss/vite": "^4.1.14",
|
||||
"@tauri-apps/cli": "^2.11.2",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/three": "^0.184.1",
|
||||
"@types/react-window": "^1.8.8",
|
||||
"@types/three": "^0.184.1",
|
||||
"tailwindcss": "^4.1.14",
|
||||
"typescript": "~5.8.2",
|
||||
"vitest": "^0.34.6"
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
/**
|
||||
* AGC 总版本号(发号源)。
|
||||
*
|
||||
* 唯一事实源是 OSS 对象 `agc/global-version.json`;渠道清单只写各自本次拿到的号。
|
||||
* 仓库里的 5 个版本文件仍由构建改写,但只作构建输入参考,不作为事实源。
|
||||
*
|
||||
* 发号顺序固定为「先写总号 → 再构建 → 再发渠道清单」:任何一步失败都不回滚,
|
||||
* 只烧号。这样渠道之间不会复用同一个号,代价是可能出现空洞。
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
export const AGC_GLOBAL_VERSION_OBJECT_KEY = 'agc/global-version.json';
|
||||
const defaultOssBaseUrl =
|
||||
'https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc';
|
||||
const versionPattern = /^\d+\.\d+\.\d+$/u;
|
||||
|
||||
function trimTrailingSlashes(value) {
|
||||
return value.replace(/\/+$/u, '');
|
||||
}
|
||||
|
||||
export function ossBaseUrl(env = process.env) {
|
||||
return trimTrailingSlashes(
|
||||
env.AGC_UPDATE_OSS_BASE_URL?.trim() || defaultOssBaseUrl,
|
||||
);
|
||||
}
|
||||
|
||||
export function globalVersionUrl(env = process.env) {
|
||||
return `${ossBaseUrl(env)}/global-version.json`;
|
||||
}
|
||||
|
||||
export function parseVersion(value, label) {
|
||||
if (typeof value !== 'string' || !versionPattern.test(value.trim())) {
|
||||
throw new Error(`${label} 不是有效的三段版本号:${String(value)}`);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
export function compareVersions(left, right) {
|
||||
const leftParts = parseVersion(left, '左版本').split('.').map(Number);
|
||||
const rightParts = parseVersion(right, '右版本').split('.').map(Number);
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
if (leftParts[index] !== rightParts[index]) {
|
||||
return leftParts[index] > rightParts[index] ? 1 : -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** 取较大版本;任一为空时返回另一个。 */
|
||||
export function maxVersion(...versions) {
|
||||
return versions
|
||||
.filter((value) => typeof value === 'string' && value.trim())
|
||||
.map((value) => parseVersion(value, '候选版本'))
|
||||
.reduce(
|
||||
(best, current) =>
|
||||
best == null || compareVersions(current, best) > 0 ? current : best,
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
export function nextVersion(current) {
|
||||
const [major, minor, patch] = parseVersion(current, '总版本')
|
||||
.split('.')
|
||||
.map(Number);
|
||||
if (patch === Number.MAX_SAFE_INTEGER) {
|
||||
throw new Error(`版本号 patch 已达到上限:${current}`);
|
||||
}
|
||||
return `${major}.${minor}.${patch + 1}`;
|
||||
}
|
||||
|
||||
export function readReleaseDryRun(env = process.env) {
|
||||
const value = env.AGC_RELEASE_DRY_RUN?.trim().toLowerCase();
|
||||
return value === '1' || value === 'true';
|
||||
}
|
||||
|
||||
async function fetchJson(url, label, { fetchImpl = fetch } = {}) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetchImpl(url, {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(`读取 ${label} 失败:${error.message}`);
|
||||
}
|
||||
if (response.status === 404) return null;
|
||||
if (!response.ok) {
|
||||
throw new Error(`读取 ${label} 失败:HTTP ${response.status}`);
|
||||
}
|
||||
try {
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
throw new Error(`${label} 不是有效 JSON:${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 渠道清单版本;缺失或 404 时返回 null(首次启用渠道)。 */
|
||||
export async function readChannelVersion(channel, options = {}) {
|
||||
const payload = await fetchJson(
|
||||
`${ossBaseUrl(options.env)}/${channel}/latest.json`,
|
||||
`${channel} 渠道清单`,
|
||||
options,
|
||||
);
|
||||
if (payload == null) return null;
|
||||
const version = typeof payload.version === 'string' ? payload.version : '';
|
||||
if (!version) {
|
||||
throw new Error(`${channel} 渠道清单缺少 version 字段`);
|
||||
}
|
||||
return parseVersion(version, `${channel} 渠道清单 version`);
|
||||
}
|
||||
|
||||
/** 旧协议迁移指针 `agc/latest.json`;只在迁移窗口内存在,仅参与播种。 */
|
||||
export async function readLegacyPointerVersion(options = {}) {
|
||||
const payload = await fetchJson(
|
||||
`${ossBaseUrl(options.env)}/latest.json`,
|
||||
'OSS 迁移指针',
|
||||
options,
|
||||
);
|
||||
if (payload == null) return null;
|
||||
const version = typeof payload.version === 'string' ? payload.version : '';
|
||||
return version ? parseVersion(version, 'OSS 迁移指针 version') : null;
|
||||
}
|
||||
|
||||
export async function readGlobalVersion(options = {}) {
|
||||
const payload = await fetchJson(
|
||||
globalVersionUrl(options.env),
|
||||
'AGC 总版本号',
|
||||
options,
|
||||
);
|
||||
if (payload == null) return null;
|
||||
const version = typeof payload.version === 'string' ? payload.version : '';
|
||||
if (!version) {
|
||||
throw new Error('AGC 总版本号对象缺少 version 字段');
|
||||
}
|
||||
return {
|
||||
...payload,
|
||||
version: parseVersion(version, 'AGC 总版本号 version'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次性播种基线:仓库当前版本、渠道清单与旧迁移指针里的最大值。
|
||||
* 基线本身不发给客户端,首个发放号是 baseline + 1。
|
||||
*/
|
||||
export async function resolveSeedBaseline({
|
||||
channels = ['dev-win', 'dev-mac'],
|
||||
repoVersion = null,
|
||||
env = process.env,
|
||||
fetchImpl = fetch,
|
||||
} = {}) {
|
||||
const candidates = [];
|
||||
if (repoVersion) candidates.push(parseVersion(repoVersion, '仓库当前版本'));
|
||||
for (const channel of channels) {
|
||||
const version = await readChannelVersion(channel, { env, fetchImpl });
|
||||
if (version) candidates.push(version);
|
||||
}
|
||||
const legacy = await readLegacyPointerVersion({ env, fetchImpl });
|
||||
if (legacy) candidates.push(legacy);
|
||||
const baseline = maxVersion(...candidates);
|
||||
if (!baseline) {
|
||||
throw new Error('无法确定总版本号播种基线:仓库版本与渠道清单都不可用');
|
||||
}
|
||||
return baseline;
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装 ossutil 参数。
|
||||
*
|
||||
* 该桶与凭据按 v1 签名使用(ossutil v2 默认 v4,缺 region 会直接失败),
|
||||
* 因此默认显式传 `--sign-version v1`;需要 v4 时用 `AGC_OSS_SIGN_VERSION=v4`
|
||||
* 并同时给 `AGC_OSS_REGION`。
|
||||
*/
|
||||
export function buildOssutilArgs({
|
||||
args,
|
||||
endpoint,
|
||||
accessKeyId,
|
||||
accessKeySecret,
|
||||
env = process.env,
|
||||
}) {
|
||||
const finalArgs = [...args, '--endpoint', endpoint];
|
||||
const region = env.AGC_OSS_REGION?.trim();
|
||||
if (region) finalArgs.push('--region', region);
|
||||
finalArgs.push('--sign-version', env.AGC_OSS_SIGN_VERSION?.trim() || 'v1');
|
||||
if (accessKeyId) {
|
||||
finalArgs.push(
|
||||
'--access-key-id',
|
||||
accessKeyId,
|
||||
'--access-key-secret',
|
||||
accessKeySecret,
|
||||
);
|
||||
}
|
||||
return finalArgs;
|
||||
}
|
||||
|
||||
function runOssutil(args, { env = process.env } = {}) {
|
||||
const binary = env.OSSUTIL_BIN?.trim() || 'ossutil';
|
||||
const endpoint =
|
||||
env.AGC_OSS_ENDPOINT?.trim() || 'oss-rg-china-mainland.aliyuncs.com';
|
||||
const accessKeyId = env.AGC_OSS_ACCESS_KEY_ID?.trim();
|
||||
const accessKeySecret = env.AGC_OSS_ACCESS_KEY_SECRET;
|
||||
if (Boolean(accessKeyId) !== Boolean(accessKeySecret)) {
|
||||
throw new Error('OSS AccessKey ID 和 Secret 必须同时提供');
|
||||
}
|
||||
const result = spawnSync(
|
||||
binary,
|
||||
buildOssutilArgs({
|
||||
args,
|
||||
endpoint,
|
||||
accessKeyId,
|
||||
accessKeySecret,
|
||||
env,
|
||||
}),
|
||||
{ stdio: 'inherit', shell: false, env },
|
||||
);
|
||||
if (result.error) {
|
||||
throw new Error(`无法执行 ${binary},请先安装并配置 ossutil`);
|
||||
}
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`${binary} 执行失败,退出码 ${result.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 写入总版本号对象;dry-run 下只打印将要执行的上传。 */
|
||||
export function writeGlobalVersion(payload, options = {}) {
|
||||
const { env = process.env, dryRun = readReleaseDryRun(env) } = options;
|
||||
const bucket = env.AGC_OSS_BUCKET?.trim() || 'agc-dev';
|
||||
const body = Buffer.from(`${JSON.stringify(payload, null, 2)}\n`, 'utf8');
|
||||
const tempDirectory = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), 'agc-global-version-'),
|
||||
);
|
||||
const tempPath = path.join(tempDirectory, 'global-version.json');
|
||||
try {
|
||||
fs.writeFileSync(tempPath, body);
|
||||
const ossUrl = `oss://${bucket}/${AGC_GLOBAL_VERSION_OBJECT_KEY}`;
|
||||
if (dryRun) {
|
||||
console.log(
|
||||
`[dry-run] 不写总版本号:${ossUrl} <- ${JSON.stringify(payload)}`,
|
||||
);
|
||||
return { written: false, objectUrl: ossUrl, payload };
|
||||
}
|
||||
runOssutil(['cp', '--force', tempPath, ossUrl], { env });
|
||||
return { written: true, objectUrl: ossUrl, payload };
|
||||
} finally {
|
||||
fs.rmSync(tempDirectory, { force: true, recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发一次号并写回总版本号对象。
|
||||
*
|
||||
* 写后回读校验:若远端值与自己写下的不一致,说明有并发发号,按失败关闭处理
|
||||
* (号已烧,不重试、不回滚),由人工确认后再发。
|
||||
*/
|
||||
export async function issueGlobalVersion({
|
||||
channel,
|
||||
commit = null,
|
||||
buildId = null,
|
||||
repoVersion = null,
|
||||
env = process.env,
|
||||
fetchImpl = fetch,
|
||||
now = () => new Date().toISOString(),
|
||||
writeImpl = writeGlobalVersion,
|
||||
} = {}) {
|
||||
if (!channel) throw new Error('发号必须显式指定 channel');
|
||||
const dryRun = readReleaseDryRun(env);
|
||||
const current = await readGlobalVersion({ env, fetchImpl });
|
||||
let baseline = current?.version ?? null;
|
||||
let seeded = false;
|
||||
if (!baseline) {
|
||||
baseline = await resolveSeedBaseline({ repoVersion, env, fetchImpl });
|
||||
seeded = true;
|
||||
}
|
||||
const issued = nextVersion(baseline);
|
||||
const payload = {
|
||||
version: issued,
|
||||
updatedAt: now(),
|
||||
channel,
|
||||
commit,
|
||||
buildId,
|
||||
};
|
||||
console.log(
|
||||
`[agc-global-version] ${
|
||||
seeded ? `按播种基线 ${baseline} 首发` : `总号 ${baseline}`
|
||||
} -> ${issued}(channel=${channel} dry-run=${dryRun})`,
|
||||
);
|
||||
writeImpl(payload, { env, dryRun });
|
||||
if (!dryRun) {
|
||||
const stored = await readGlobalVersion({ env, fetchImpl });
|
||||
if (!stored || stored.version !== issued) {
|
||||
throw new Error(
|
||||
`总版本号写后回读不一致:期望 ${issued},远端 ${
|
||||
stored?.version ?? '不存在'
|
||||
};可能存在并发发号,本次构建失败关闭`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return issued;
|
||||
}
|
||||
|
||||
/** 渠道高水位断言:请求号低于本渠道清单版本即失败关闭。 */
|
||||
export function assertRequestedVersionNotBelowChannel({
|
||||
requested,
|
||||
channelVersion,
|
||||
channel,
|
||||
}) {
|
||||
const requestedVersion = parseVersion(requested, '请求版本');
|
||||
if (channelVersion == null) return requestedVersion;
|
||||
const current = parseVersion(channelVersion, `${channel} 渠道版本`);
|
||||
if (compareVersions(requestedVersion, current) < 0) {
|
||||
throw new Error(
|
||||
`请求版本 ${requestedVersion} 低于 ${channel} 渠道当前清单版本 ${current};拒绝回退发布`,
|
||||
);
|
||||
}
|
||||
return requestedVersion;
|
||||
}
|
||||
|
||||
/** 只读预览:不写回、不烧号。 */
|
||||
export async function previewNextGlobalVersion(options = {}) {
|
||||
const current = await readGlobalVersion(options);
|
||||
const baseline =
|
||||
current?.version ??
|
||||
(await resolveSeedBaseline({
|
||||
repoVersion: options.repoVersion,
|
||||
env: options.env,
|
||||
fetchImpl: options.fetchImpl,
|
||||
}));
|
||||
return nextVersion(baseline);
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
|
||||
import {
|
||||
assertRequestedVersionNotBelowChannel,
|
||||
buildOssutilArgs,
|
||||
issueGlobalVersion,
|
||||
maxVersion,
|
||||
nextVersion,
|
||||
previewNextGlobalVersion,
|
||||
resolveSeedBaseline,
|
||||
} from './agc-global-version.mjs';
|
||||
|
||||
function jsonResponse(payload, status = 200) {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
json: async () => payload,
|
||||
};
|
||||
}
|
||||
|
||||
/** 以 URL 为键的假 OSS:只读 fetch + 记录写入。 */
|
||||
function createFakeOss({ objects = {} } = {}) {
|
||||
const state = { ...objects };
|
||||
const writes = [];
|
||||
return {
|
||||
state,
|
||||
writes,
|
||||
fetchImpl: async (url) => {
|
||||
const key = String(url).replace(/^https?:\/\/[^/]+\//u, '');
|
||||
if (!(key in state)) return jsonResponse(null, 404);
|
||||
return jsonResponse(state[key]);
|
||||
},
|
||||
writeImpl: (payload, options = {}) => {
|
||||
writes.push({ payload, dryRun: Boolean(options.dryRun) });
|
||||
if (!options.dryRun) state['agc/global-version.json'] = payload;
|
||||
return { written: !options.dryRun, payload };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('播种基线取仓库版本、各渠道清单与旧迁移指针的最大值', async () => {
|
||||
const oss = createFakeOss({
|
||||
objects: {
|
||||
'agc/dev-win/latest.json': { version: '0.1.57' },
|
||||
'agc/dev-mac/latest.json': { version: '0.1.12' },
|
||||
'agc/latest.json': { version: '0.1.60' },
|
||||
},
|
||||
});
|
||||
assert.equal(
|
||||
await resolveSeedBaseline({
|
||||
repoVersion: '0.1.48',
|
||||
env: {},
|
||||
fetchImpl: oss.fetchImpl,
|
||||
}),
|
||||
'0.1.60',
|
||||
);
|
||||
assert.equal(maxVersion('0.1.9', '0.1.10', null), '0.1.10');
|
||||
});
|
||||
|
||||
test('无总号时按播种基线发首号,并把总号写回唯一事实源', async () => {
|
||||
const oss = createFakeOss({
|
||||
objects: {
|
||||
'agc/dev-win/latest.json': { version: '0.1.57' },
|
||||
'agc/dev-mac/latest.json': { version: '0.1.12' },
|
||||
},
|
||||
});
|
||||
const issued = await issueGlobalVersion({
|
||||
channel: 'dev-win',
|
||||
commit: 'a'.repeat(40),
|
||||
buildId: '319',
|
||||
repoVersion: '0.1.48',
|
||||
env: {},
|
||||
fetchImpl: oss.fetchImpl,
|
||||
writeImpl: oss.writeImpl,
|
||||
now: () => '2026-09-20T00:00:00.000Z',
|
||||
});
|
||||
assert.equal(issued, '0.1.58');
|
||||
assert.deepEqual(
|
||||
oss.writes.map((entry) => entry.payload.version),
|
||||
['0.1.58'],
|
||||
);
|
||||
assert.equal(oss.state['agc/global-version.json'].version, '0.1.58');
|
||||
assert.equal(oss.state['agc/global-version.json'].channel, 'dev-win');
|
||||
assert.equal(oss.state['agc/global-version.json'].buildId, '319');
|
||||
});
|
||||
|
||||
test('已有总号时只递增,不再回看渠道清单', async () => {
|
||||
const oss = createFakeOss({
|
||||
objects: {
|
||||
'agc/global-version.json': { version: '0.2.7' },
|
||||
// 渠道清单被手工改小也不能把总号拉回去。
|
||||
'agc/dev-win/latest.json': { version: '0.1.10' },
|
||||
},
|
||||
});
|
||||
const issued = await issueGlobalVersion({
|
||||
channel: 'dev-mac',
|
||||
env: {},
|
||||
fetchImpl: oss.fetchImpl,
|
||||
writeImpl: oss.writeImpl,
|
||||
});
|
||||
assert.equal(issued, '0.2.8');
|
||||
assert.equal(oss.state['agc/global-version.json'].version, '0.2.8');
|
||||
});
|
||||
|
||||
test('dry-run 只预览下一位,不写回、不烧号', async () => {
|
||||
const oss = createFakeOss({
|
||||
objects: { 'agc/global-version.json': { version: '0.3.4' } },
|
||||
});
|
||||
const preview = await previewNextGlobalVersion({
|
||||
env: {},
|
||||
fetchImpl: oss.fetchImpl,
|
||||
});
|
||||
assert.equal(preview, '0.3.5');
|
||||
assert.equal(oss.writes.length, 0);
|
||||
|
||||
const issued = await issueGlobalVersion({
|
||||
channel: 'dev-win',
|
||||
env: { AGC_RELEASE_DRY_RUN: '1' },
|
||||
fetchImpl: oss.fetchImpl,
|
||||
writeImpl: oss.writeImpl,
|
||||
});
|
||||
assert.equal(issued, '0.3.5');
|
||||
assert.deepEqual(
|
||||
oss.writes.map((entry) => entry.dryRun),
|
||||
[true],
|
||||
);
|
||||
assert.equal(oss.state['agc/global-version.json'].version, '0.3.4');
|
||||
});
|
||||
|
||||
test('传入低于本渠道清单的号时失败关闭', () => {
|
||||
assert.equal(
|
||||
assertRequestedVersionNotBelowChannel({
|
||||
requested: '0.1.60',
|
||||
channelVersion: '0.1.60',
|
||||
channel: 'dev-win',
|
||||
}),
|
||||
'0.1.60',
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
assertRequestedVersionNotBelowChannel({
|
||||
requested: '0.1.59',
|
||||
channelVersion: '0.1.60',
|
||||
channel: 'dev-win',
|
||||
}),
|
||||
/低于 dev-win 渠道当前清单版本/u,
|
||||
);
|
||||
assert.equal(
|
||||
assertRequestedVersionNotBelowChannel({
|
||||
requested: '0.1.1',
|
||||
channelVersion: null,
|
||||
channel: 'dev-mac',
|
||||
}),
|
||||
'0.1.1',
|
||||
);
|
||||
});
|
||||
|
||||
test('写后回读不一致(并发发号)时失败关闭', async () => {
|
||||
const oss = createFakeOss({
|
||||
objects: { 'agc/global-version.json': { version: '0.5.1' } },
|
||||
});
|
||||
await assert.rejects(
|
||||
issueGlobalVersion({
|
||||
channel: 'dev-win',
|
||||
env: {},
|
||||
// 模拟另一个发号进程在写入后覆盖了总号。
|
||||
writeImpl: (payload, options) => {
|
||||
const result = oss.writeImpl(payload, options);
|
||||
// 另一个发号进程紧随其后覆盖总号。
|
||||
oss.state['agc/global-version.json'] = { version: '0.5.9' };
|
||||
return result;
|
||||
},
|
||||
fetchImpl: oss.fetchImpl,
|
||||
}),
|
||||
/写后回读不一致/u,
|
||||
);
|
||||
});
|
||||
|
||||
test('nextVersion 只在 patch 位递增', () => {
|
||||
assert.equal(nextVersion('0.1.9'), '0.1.10');
|
||||
assert.equal(nextVersion('1.0.0'), '1.0.1');
|
||||
assert.throws(() => nextVersion('0.1'), /不是有效的三段版本号/u);
|
||||
});
|
||||
|
||||
test('ossutil 参数默认使用 v1 签名,并可按需带 region 与 v4', () => {
|
||||
const base = {
|
||||
args: ['cp', '--force', '/tmp/a.json', 'oss://agc-dev/agc/global-version.json'],
|
||||
endpoint: 'oss-rg-china-mainland.aliyuncs.com',
|
||||
accessKeyId: 'id',
|
||||
accessKeySecret: 'secret',
|
||||
env: {},
|
||||
};
|
||||
const v1 = buildOssutilArgs(base);
|
||||
assert.equal(v1[v1.indexOf('--sign-version') + 1], 'v1');
|
||||
assert.ok(!v1.includes('--region'));
|
||||
assert.equal(v1[v1.indexOf('--access-key-id') + 1], 'id');
|
||||
assert.equal(v1[v1.indexOf('--access-key-secret') + 1], 'secret');
|
||||
|
||||
const v4 = buildOssutilArgs({
|
||||
...base,
|
||||
env: { AGC_OSS_SIGN_VERSION: 'v4', AGC_OSS_REGION: 'cn-beijing' },
|
||||
});
|
||||
assert.equal(v4[v4.indexOf('--region') + 1], 'cn-beijing');
|
||||
assert.equal(v4[v4.indexOf('--sign-version') + 1], 'v4');
|
||||
});
|
||||
@@ -957,9 +957,6 @@ async function runInteractiveCargo(cliArguments, setActiveChild) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// 立项策划跑 standard 档,`agent.delegate` 这类动作按项目权限策略必须逐个确认,
|
||||
// 而确认和问询都只从 CLI 的 stdin 读。自主构建档没有这一步,所以只有 --plan 需要
|
||||
// 一个把「人坐在终端前敲 approve」自动化掉的应答器;判据本身仍然走后端确认命令。
|
||||
const swarmConfirmationPromptPattern = /输入 approve 或 reject:$/u;
|
||||
const swarmUserInputPromptPattern = /请选择 1-\d+,或直接输入其他答案:$/u;
|
||||
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync, spawnSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import {
|
||||
generateUpdateManifest,
|
||||
prepareReleaseVersion,
|
||||
resolveManifestPlatformKeys,
|
||||
resolveReleaseContext,
|
||||
resolveReleasePartition,
|
||||
runTauriBuild,
|
||||
} from './build-release.mjs';
|
||||
import { readReleaseDryRun, uploadReleaseArtifacts } from './release-oss.mjs';
|
||||
import {
|
||||
readUpdaterPubkey,
|
||||
verifyUpdaterSignature,
|
||||
} from './verify-updater-signature.mjs';
|
||||
|
||||
/**
|
||||
* AGC macOS 分区(`<channel>-mac`)发布入口:构建 arm64 单架构包 → arm64 隔离 smoke → 生成 arm64 DMG
|
||||
* → 生成分区清单 latest.json → 用产物内烘焙的公钥验签 → 按 dry-run 决定是否上传 OSS。
|
||||
*
|
||||
* 边界:
|
||||
* - 只出 Apple Silicon(arm64)单架构:清单只登记 `darwin-aarch64`。Intel 侧要可用,前提是随包 Node
|
||||
* 也能按架构各带一份(`stage-node-runtime.mjs` 对 universal 目标失败关闭);在实现之前**不得**
|
||||
* 把 arm64 产物登记成 `darwin-x86_64`,否则 Intel 客户端会装到跑不起来的包。
|
||||
* - Apple 签名与公证暂缺:本入口剥离 `APPLE_*` 凭据让 Tauri 跳过 Apple 签名,但**不能传
|
||||
* `--no-sign`** —— 该标志同时会跳过 updater 的 minisign 签名,产物就没有 `.sig`;
|
||||
* 未签名 + 未公证必须显式记录而非静默通过;
|
||||
* - 更新包签名(TAURI_SIGNING_PRIVATE_KEY,minisign)是硬需求:缺了客户端一律拒绝安装,
|
||||
* 因此构建前要求凭据存在,构建后用内置公钥复核 `.sig` 才允许继续上传;
|
||||
* - 未通过验签绝不写 OSS:上传顺序为更新包、签名、首装包,全部成功后才覆盖渠道清单指针。
|
||||
*/
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = path.resolve(appRoot, '../..');
|
||||
|
||||
/**
|
||||
* 产品名只从 Tauri 配置读取:它同时决定 `*.app` 目录名、updater 归档名与 DMG 卷名。
|
||||
* 写死会在改名后让入口静默找错对象(清理、打包、归档三处一起失效)。
|
||||
*/
|
||||
function readProductName() {
|
||||
const read = (file) =>
|
||||
JSON.parse(fs.readFileSync(path.join(appRoot, 'src-tauri', file), 'utf8'));
|
||||
const base = read('tauri.conf.json');
|
||||
const macosPath = path.join(appRoot, 'src-tauri', 'tauri.macos.conf.json');
|
||||
const productName = fs.existsSync(macosPath)
|
||||
? (read('tauri.macos.conf.json').productName ?? base.productName)
|
||||
: base.productName;
|
||||
assert.ok(
|
||||
typeof productName === 'string' && productName.trim().length > 0,
|
||||
'Tauri 配置缺少 productName',
|
||||
);
|
||||
return productName;
|
||||
}
|
||||
|
||||
const productName = readProductName();
|
||||
const appBundleName = `${productName}.app`;
|
||||
const updaterArtifactName = `${productName}.app.tar.gz`;
|
||||
assert.equal(process.platform, 'darwin', '只能在 macOS Agent 执行');
|
||||
assert.equal(
|
||||
process.env.JENKINS_URL?.length > 0,
|
||||
true,
|
||||
'此入口仅用于 Jenkins 独立工作区',
|
||||
);
|
||||
assert.equal(
|
||||
fs.realpathSync(process.env.WORKSPACE || '.'),
|
||||
fs.realpathSync(repoRoot),
|
||||
'必须在 Jenkins workspace 根目录执行',
|
||||
);
|
||||
const space = fs.statfsSync(repoRoot);
|
||||
assert.ok(
|
||||
space.bavail * space.bsize >= 8 * 1024 ** 3,
|
||||
'构建前至少需要 8 GiB 可用空间;禁止自动清理开发缓存',
|
||||
);
|
||||
|
||||
// 仅剥离 Apple 签名/公证变量:本节点没有证书,误用只会让构建失败;
|
||||
// 更新包签名与 OSS 凭据必须保留,它们是本入口发布能力的组成部分。
|
||||
for (const key of Object.keys(process.env)) {
|
||||
if (/^APPLE_/u.test(key)) delete process.env[key];
|
||||
}
|
||||
assert.ok(
|
||||
process.env.TAURI_SIGNING_PRIVATE_KEY?.length > 0 ||
|
||||
process.env.TAURI_SIGNING_PRIVATE_KEY_PATH?.length > 0,
|
||||
'缺少更新包签名私钥(TAURI_SIGNING_PRIVATE_KEY / _PATH):无签名的更新包会被客户端拒绝,禁止继续',
|
||||
);
|
||||
|
||||
const bucket = process.env.AGC_OSS_BUCKET?.trim() || 'agc-dev';
|
||||
const endpoint =
|
||||
process.env.AGC_OSS_ENDPOINT?.trim() || 'oss-rg-china-mainland.aliyuncs.com';
|
||||
if (!/^[a-z0-9][a-z0-9.-]{1,62}$/u.test(bucket) || /[\r\n\0]/u.test(endpoint)) {
|
||||
throw new Error('OSS bucket 或 endpoint 配置无效');
|
||||
}
|
||||
process.env.AGC_UPDATE_OSS_BASE_URL ||= `https://${bucket}.${endpoint}/agc`;
|
||||
const dryRun = readReleaseDryRun();
|
||||
|
||||
process.env.CARGO_TARGET_DIR = path.join(appRoot, 'src-tauri/target');
|
||||
// 单架构目标:清单侧 `resolveManifestPlatformKeys` 只为它登记 darwin-aarch64。
|
||||
const macTarget = 'aarch64-apple-darwin';
|
||||
const context = resolveReleaseContext([`--target=${macTarget}`]);
|
||||
const partition = resolveReleasePartition(context.channel, context.target);
|
||||
const version = await prepareReleaseVersion(context);
|
||||
// 首装包名必须让清单侧的单架构分支唯一匹配:`<产品名>_<版本>_<架构>.dmg`,
|
||||
// 架构段用 Tauri 的 aarch64 口径(不是 updater 平台键的 arm64 / x86_64)。
|
||||
const firstInstallName = `${productName}_${version}_aarch64.dmg`;
|
||||
|
||||
// 幂等边界:workspace 会保留上一轮产物。先删掉本次将要写出的对象,否则
|
||||
// 1) hdiutil 会因同名 DMG 已存在直接失败(首次实跑即命中);
|
||||
// 2) 上一轮遗留的 `.sig` 会让验签门禁把「本轮其实没签」判成通过。
|
||||
// 只删本次要写出的确切路径,不动其它版本产物与编译缓存。
|
||||
const macosBundle = path.join(context.bundleRoot, 'macos');
|
||||
for (const stale of [
|
||||
path.join(macosBundle, updaterArtifactName),
|
||||
path.join(macosBundle, `${updaterArtifactName}.sig`),
|
||||
path.join(macosBundle, `${firstInstallName}`),
|
||||
path.join(macosBundle, `${firstInstallName}.sha256`),
|
||||
path.join(context.bundleRoot, 'latest.json'),
|
||||
path.join(context.bundleRoot, 'release-notes.txt'),
|
||||
]) {
|
||||
fs.rmSync(stale, { force: true });
|
||||
}
|
||||
|
||||
const args = [
|
||||
`--target=${macTarget}`,
|
||||
'--bundles',
|
||||
'app',
|
||||
'--ci',
|
||||
// 刻意不传 `--no-sign`:它会连带跳过 updater 签名,而客户端强制校验更新包签名。
|
||||
// Apple 侧改为剥离 APPLE_* 凭据,未配置身份时 Tauri 不签名也不失败。
|
||||
// 基础配置已开启;这里显式声明,避免被其它配置来源关掉后静默失去更新能力。
|
||||
'--config',
|
||||
'{"bundle":{"createUpdaterArtifacts":true}}',
|
||||
];
|
||||
const command = (binary, argv, options = {}) =>
|
||||
execFileSync(binary, argv, { cwd: repoRoot, stdio: 'inherit', ...options });
|
||||
runTauriBuild(args, context);
|
||||
|
||||
const app = path.join(context.bundleRoot, 'macos', appBundleName);
|
||||
command(process.execPath, [
|
||||
path.join(appRoot, 'scripts/check-macos-bundle.mjs'),
|
||||
app,
|
||||
'arm64',
|
||||
]);
|
||||
|
||||
// DMG 放在 bundle 根目录下:渠道清单的首装包选择会扫描该目录,命名必须匹配 `_<version>_aarch64.dmg`。
|
||||
const dmgDirectory = path.join(context.bundleRoot, 'macos');
|
||||
fs.mkdirSync(dmgDirectory, { recursive: true });
|
||||
const dmg = path.join(dmgDirectory, firstInstallName);
|
||||
const stage = fs.mkdtempSync(path.join(os.tmpdir(), 'agc-ci-dmg-'));
|
||||
try {
|
||||
command('ditto', [app, path.join(stage, appBundleName)]);
|
||||
fs.symlinkSync('/Applications', path.join(stage, 'Applications'));
|
||||
command('hdiutil', [
|
||||
'create',
|
||||
// 前面已删除同名对象;这里再要求显式覆盖,避免残留文件让构建以「文件已存在」失败。
|
||||
'-ov',
|
||||
'-volname',
|
||||
productName,
|
||||
'-srcfolder',
|
||||
stage,
|
||||
'-format',
|
||||
'UDZO',
|
||||
dmg,
|
||||
]);
|
||||
command('hdiutil', ['verify', dmg]);
|
||||
} finally {
|
||||
fs.rmSync(stage, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
const release = await generateUpdateManifest(context);
|
||||
assert.equal(
|
||||
path.resolve(release.downloadArtifact),
|
||||
path.resolve(dmg),
|
||||
'首装包必须锁定本次生成的 arm64 DMG',
|
||||
);
|
||||
|
||||
// 上传前门禁:用产物里烘焙的公钥复核更新包签名。验不过就停在这里,绝不写 OSS。
|
||||
const signature = verifyUpdaterSignature({
|
||||
artifactPath: release.artifact,
|
||||
signaturePath: `${release.artifact}.sig`,
|
||||
pubkey: readUpdaterPubkey(),
|
||||
});
|
||||
console.log(
|
||||
`[agc-macos] 更新包签名校验通过:alg=${signature.algorithm},keyId=${signature.keyId}`,
|
||||
);
|
||||
|
||||
const artifacts = path.join(repoRoot, 'artifacts');
|
||||
// 只清理本 Job 的归档输出,不能把上次 DMG 当成本次成功产物。
|
||||
fs.rmSync(artifacts, { recursive: true, force: true });
|
||||
fs.mkdirSync(artifacts, { recursive: true });
|
||||
const sha256 = (file) => {
|
||||
const hash = createHash('sha256');
|
||||
hash.update(fs.readFileSync(file));
|
||||
return hash.digest('hex');
|
||||
};
|
||||
const dmgHash = sha256(dmg);
|
||||
fs.writeFileSync(`${dmg}.sha256`, `${dmgHash} ${path.basename(dmg)}\n`);
|
||||
|
||||
const uploadPlan = uploadReleaseArtifacts(release, {
|
||||
bucket,
|
||||
endpoint,
|
||||
binary: process.env.OSSUTIL_BIN?.trim() || 'ossutil',
|
||||
accessKeyId: process.env.AGC_OSS_ACCESS_KEY_ID?.trim(),
|
||||
accessKeySecret: process.env.AGC_OSS_ACCESS_KEY_SECRET,
|
||||
dryRun,
|
||||
});
|
||||
|
||||
const archived = [
|
||||
dmg,
|
||||
`${dmg}.sha256`,
|
||||
release.manifestPath,
|
||||
release.notesPath,
|
||||
`${release.artifact}.sig`,
|
||||
];
|
||||
for (const file of archived) {
|
||||
fs.copyFileSync(file, path.join(artifacts, path.basename(file)));
|
||||
}
|
||||
|
||||
const commit = execFileSync('git', ['rev-parse', 'HEAD'], {
|
||||
cwd: repoRoot,
|
||||
encoding: 'utf8',
|
||||
}).trim();
|
||||
// Apple 签名状态必须实测:剥离 APPLE_* 后 Tauri 通常跳过签名,但节点若装了 Developer ID
|
||||
// 证书仍可能签上,硬编码 appleSigned=false 会把「其实签了」写成假事实。
|
||||
const signatureProbe = spawnSync('codesign', ['-dv', '--verbose=2', app], {
|
||||
encoding: 'utf8',
|
||||
});
|
||||
const signatureText = `${signatureProbe.stdout ?? ''}${signatureProbe.stderr ?? ''}`;
|
||||
const appleSigned = /Authority=Developer ID Application/u.test(signatureText);
|
||||
const appleSignatureKind = appleSigned
|
||||
? 'developer-id'
|
||||
: /Signature=adhoc/u.test(signatureText)
|
||||
? 'adhoc'
|
||||
: 'unsigned';
|
||||
fs.writeFileSync(
|
||||
path.join(artifacts, 'build-manifest.json'),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
version,
|
||||
commit,
|
||||
target: context.target,
|
||||
channel: context.channel,
|
||||
// Apple 签名与公证暂缺:显式记录为未验证项,不静默通过。
|
||||
appleSigned,
|
||||
appleSignatureKind,
|
||||
notarized: false,
|
||||
dryRun,
|
||||
uploaded: !dryRun,
|
||||
updaterSignature: {
|
||||
algorithm: signature.algorithm,
|
||||
keyId: signature.keyId,
|
||||
verified: true,
|
||||
},
|
||||
oss: {
|
||||
bucket,
|
||||
endpoint,
|
||||
partition,
|
||||
latest: `oss://${bucket}/agc/${partition}/latest.json`,
|
||||
objects: uploadPlan.map(({ destination }) => destination),
|
||||
},
|
||||
artifacts: {
|
||||
updater: path.basename(release.artifact),
|
||||
updaterSha256: sha256(release.artifact),
|
||||
updaterBytes: fs.statSync(release.artifact).size,
|
||||
updaterSignature: path.basename(`${release.artifact}.sig`),
|
||||
firstInstall: path.basename(dmg),
|
||||
firstInstallSha256: dmgHash,
|
||||
manifest: 'latest.json',
|
||||
},
|
||||
// 单架构发布:只跑 arm64 隔离 smoke;Intel 未支持(清单里没有 darwin-x86_64 键)。
|
||||
smokes: ['arm64'],
|
||||
manifestPlatformKeys: resolveManifestPlatformKeys(context.target),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
console.log(
|
||||
dryRun
|
||||
? `[agc-macos] dry-run 完成:${partition} 分区产物与清单已生成,未写入 OSS`
|
||||
: `[agc-macos] ${partition} 分区更新包、签名、首装包与清单已上传 OSS`,
|
||||
);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user