Compare commits

..

24 Commits

Author SHA1 Message Date
k88936 8b2d0cb9df 统一错误事件同步留痕到 AppData 应用日志
Project CI / AI game creator shell Rust crates (pull_request) Successful in 2m57s
Project CI / Backend tests (pull_request) Failing after 12s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 3m50s
Project CI / AI game creator shell Rust lane 2/2 (pull_request) Failing after 6m44s
Project CI / Repository checks (pull_request) Failing after 11s
Project CI / AI game creator shell Rust lane 1/2 (pull_request) Failing after 7m28s
Project CI / Frontend tests (pull_request) Successful in 4m9s
Project CI / Native shell tests (pull_request) Successful in 8m24s
Project CI / AI game creator shell web tests (pull_request) Successful in 5m37s
- 新增 agent_runtime_error_app_log_lines,把统一错误事件的同一份已脱敏诊断投影成应用日志两行:agent.runtime.error 身份行与 agent.runtime.error.detail 详情行
- 身份行含 eventId/source/stage/code/retryable/clientTurnId/elapsedMs/detailRef/summary,详情行含 hint/detail/metadata;detail 与 metadata 各按 1200/200 字符预算先脱敏再截断,字段仍只来自 sidecar 那份 diagnosis
- 拆两行的原因:整行命中凭据标记会被 sanitize_diagnostic_message 整体替换成脱敏占位,详情行被吃掉时身份行仍能定位 eventId 与 detailRef
- app_log! 先于 sidecar 写入,sidecar 写失败也留下可提交的诊断;各字段先压平换行,保证应用日志逐行读取且 stderr 输出不拆行
- 新增用例覆盖身份字段、凭据脱敏、单行口径与实际 sanitize_diagnostic_message 落盘边界(含超长诊断)
- 同步文件【技术方案】AGC错误报告与诊断上传与【技术方案】AI游戏创作智能体App实施计划,共享记忆 decision-log 与 pitfalls 明确项目内 .agent/runtime/errors sidecar 与进程内错误报告事件池是两套东西,本次只写日志行
- 验证:cargo test runtime_error(7 passed)、cargo fmt --check、npm run check:encoding、git diff --check
2026-09-21 21:34:45 +08:00
kdletters 4d313a44eb 收口后台模板管理里程碑:回填验收证据并删除临时实施计划
Project CI / AI game creator shell Rust crates (push) Successful in 2m58s
Project CI / AI game creator shell Rust smoke (push) Successful in 3m58s
Project CI / AI game creator shell Rust lane 1/2 (push) Failing after 7m32s
Project CI / AI game creator shell Rust lane 2/2 (push) Failing after 8m26s
Project CI / Backend tests (push) Successful in 8m33s
Project CI / Repository checks (push) Successful in 4m50s
Project CI / Native shell tests (push) Successful in 9m20s
Project CI / Frontend tests (push) Successful in 5m57s
Project CI / AI game creator shell web tests (push) Successful in 3m19s
- 里程碑 Status 从 approved 更新为 implemented-awaiting-runtime-acceptance,并注明按验收口径未对真实 OSS 写入
- 新增验收证据:合同/权限/领域/存储/CLI 五层用例结果,本地 API 健康检查与未授权读取写入失败关闭,授权读取 9 个模板快照,受控浏览器桌面与 390×844 移动端 smoke
- 新增复审记录:写路径顺序与 409 语义、后台 DTO 结构上无法改动 ZIP/版本、封面公共域名与单 bucket 合同一致、迟到响应判据的覆盖方式
- 按实施计划第 4 步删除临时实施计划文件,里程碑文档保留为唯一验收依据
- 验证:check:doc-index(192 份)、check:encoding、git diff --check
2026-09-21 14:21:25 +08:00
kdletters 01ed9fadc6 修复手工 release 发布未透传 AGC 渠道
Project CI / AI game creator shell Rust crates (push) Successful in 2m45s
Project CI / AI game creator shell Rust smoke (push) Successful in 3m36s
Project CI / AI game creator shell Rust lane 1/2 (push) Failing after 7m5s
Project CI / AI game creator shell Rust lane 2/2 (push) Failing after 7m54s
Project CI / Backend tests (push) Successful in 11m10s
Project CI / Repository checks (push) Successful in 6m17s
Project CI / Frontend tests (push) Successful in 8m0s
Project CI / Native shell tests (push) Successful in 11m32s
Project CI / AI game creator shell web tests (push) Has been cancelled
补充手工发布目标到 AGC 更新渠道的踩坑记录

补充 release 客户端包分区与补发流程说明
2026-09-21 14:04:02 +08:00
kdletters 02a7abeb3f 新增后台 AGC 模板管理与模板库内容寻址落库
Project CI / AI game creator shell Rust crates (push) Successful in 2m53s
Project CI / AI game creator shell Rust smoke (push) Successful in 3m42s
Project CI / AI game creator shell Rust lane 2/2 (push) Has been cancelled
Project CI / Backend tests (push) Has been cancelled
Project CI / Frontend tests (push) Has been cancelled
Project CI / Repository checks (push) Has been cancelled
Project CI / AI game creator shell web tests (push) Has been cancelled
Project CI / AI game creator shell Rust lane 1/2 (push) Has been cancelled
Project CI / Native shell tests (push) Has been cancelled
- 后台新增「模板管理」页:按权限查看并编辑模板名称/简介/标签/封面,支持上架与下架;路由、侧栏、tab 权限、API 客户端与 DTO 同步接入
- api-server 新增 /admin/api/agc-templates 读取与更新路由,复用现有后台鉴权与 tab 权限校验,权限不足按既有失败关闭口径拒绝
- module-assets 收敛模板库纯规则(active/inactive 投影、索引 schema 与重复项校验、ZIP 大小与摘要核对),platform-oss 承担对象存储读写、不可变对象复用与发布互斥锁
- shared-contracts 补后台模板 DTO;spacetime-module 账号存储适配保持既有 schema 不变
- AGC 壳内置模板索引与建项读取改为内容寻址对象,补模板安装、越界归档、索引不匹配等用例
- 模板库发布脚本支持定向发布与上架/下架合并、内容地址复用与锁语义,CLI 守卫用例同步;jenkins 两条客户端打包管线统一触发邮件通知 Job 并传递首装包链接
- 内置 5 个 Cocos 官方模板载荷与索引 fixture(内容地址对象,共 90 个文件)
- 补「后台模板管理」里程碑与实施计划,更新模板库技术方案、开发运维文档与共享记忆
- 验证:admin-web 39 项用例与 typecheck、发布脚本 25 项用例、api-server 与 AGC 壳编译、模板库定向 Rust 用例(AGC 壳 18 项、module-assets/platform-oss 16 项、后台权限 1 项)、check:encoding / check:doc-index / check:production-ops / rustfmt 全部通过
2026-09-21 13:56:20 +08:00
suzmii 6845cdcbc5 修复 Mac 包校验脚本对合法随包 npm 的误判
Project CI / AI game creator shell Rust smoke (push) Successful in 2m14s
Project CI / AI game creator shell Rust crates (push) Successful in 1m26s
Project CI / Frontend tests (push) Has been cancelled
Project CI / AI game creator shell Rust lane 2/2 (push) Has been cancelled
Project CI / Backend tests (push) Has been cancelled
Project CI / Native shell tests (push) Has been cancelled
Project CI / Repository checks (push) Has been cancelled
Project CI / AI game creator shell web tests (push) Has been cancelled
Project CI / AI game creator shell Rust lane 1/2 (push) Has been cancelled
- check-macos-bundle 的「包里不得出现 node_modules」门禁只放行了 game-runtime/node/node_modules/npm,但 recursive readdir 会把目录项 game-runtime/node/node_modules 也列出来,于是合法包必然断言失败
- 这条门禁是 #439 引入的,之后每次构建都死在更早的阶段(staging/测试),直到 2026-09-21 arm64 单架构跑通才第一次走到它:12:58、13:24、13:43 三轮都挂在这里
- 修复:放行 npm 目录自身、其子树与它的上级 node_modules 容器目录;已用真实 arm64 产物跑通完整 smoke(资源、架构、摘要、权限、Codex 正式查找、app-server 握手、缺组件拒绝全部通过)
2026-09-21 13:50:32 +08:00
suzmii 4044ffd89b 修复 Mac 发布 Job 手工触发时 Checkout 因未定义参数失败
- 手工「立即构建」不会注入可选参数(COMMIT_HASH / SKIP_IF_SUPERSEDED 未定义而非空值),set -u 下 `[ -n "$COMMIT_HASH" ]` 直接以 unbound variable 退出,Job 2026-09-21 12:54 那一轮就是这样在 Checkout 失败的
- 两段 Checkout 脚本开头统一兜底:SOURCE_BRANCH 默认 master、COMMIT_HASH 默认空、SKIP_IF_SUPERSEDED 默认 false,调度器显式传参时行为不变(仍按 pinned commit 构建并判让位)
2026-09-21 13:50:32 +08:00
suzmii 8d0c021126 修正 Mac 发布文档口径:自动触发与描述原文
- 运维文档原写「不设置 trigger;不接入现有每小时版本调度」,与现状矛盾:调度 Job 会先发号再把 SOURCE_BRANCH/COMMIT_HASH/AGC_UPDATE_CHANNEL/AGC_RELEASE_VERSION/SKIP_IF_SUPERSEDED 透传给 Mac Job,正常发布不需要手工点构建
- 把 Jenkins Job 描述与节点描述的当前原文(arm64 单架构 + 由调度器自动触发 + dry-run 默认关)写进文档,并要求每次改口径同步 Jenkins 侧描述,避免描述停留在 universal/手动触发的旧口径
2026-09-21 13:50:32 +08:00
kdletters 1cb91f9444 修复画布绑定查询与生成失败归因
Project CI / AI game creator shell Rust lane 1/2 (push) Has been cancelled
Project CI / AI game creator shell Rust lane 2/2 (push) Has been cancelled
Project CI / AI game creator shell Rust smoke (push) Has been cancelled
Project CI / AI game creator shell Rust crates (push) Has been cancelled
Project CI / Backend tests (push) Has been cancelled
Project CI / Native shell tests (push) Has been cancelled
Project CI / Frontend tests (push) Has been cancelled
Project CI / Repository checks (push) Has been cancelled
Project CI / AI game creator shell web tests (push) Has been cancelled
- 画布绑定前置的项目列表查询改为 view=summary,站内与外部路由统一支持摘要视图(缺省 full 兼容,未知取值 400)
- 项目摘要投影收敛到 editor_project,外部 API 与 MCP 复用同一份实现,摘要不做内联媒体修复也不回传画布与全量资源
- 外部编辑器请求失败文案补 kind 语义与底层因链,区分请求超时、正文截断与非法 JSON,不拼接 URL
- 远端资源编辑终态文案带出稳定失败码并指向移出恢复队列这一唯一出口,上游原文仍不写入账本
- 补齐站内摘要视图与画布测试夹具的请求断言用例
- 更新共享决策记录与踩坑记录(图集切片上限条目归上游 #442,本提交不重复)
2026-09-21 13:33:23 +08:00
kdletters 2e31a485d8 修复 Stdb publish 事务确认超时被误判为失败
Project CI / AI game creator shell Rust crates (push) Successful in 3m0s
Project CI / AI game creator shell Rust smoke (push) Successful in 4m0s
Project CI / AI game creator shell Rust lane 1/2 (push) Failing after 7m41s
Project CI / AI game creator shell Rust lane 2/2 (push) Failing after 8m44s
Project CI / Backend tests (push) Successful in 8m52s
Project CI / Frontend tests (push) Has been cancelled
Project CI / Native shell tests (push) Has been cancelled
Project CI / AI game creator shell web tests (push) Has been cancelled
Project CI / Repository checks (push) Has been cancelled
- production-stdb-publish 新增 run_spacetime_publish:仅在出现 timeout waiting for transaction confirmation 时重试一次同版本 publish(SpacetimeDB 对已生效的同版本为幂等),重试成功即视为模块已在位,不再把生产留在维护态
- 其它失败原因保持原有失败关闭语义;生产运维门禁断言补上该重试口径
2026-09-21 13:27:37 +08:00
suzmii 4ad131d74d Merge pull request 'AGC 画布:锚点让位标题栏、生成浮层贴边、拖动误触点击、读秒 100ms 与图集参考口径' (#448) from fix/agc-canvas-bugfix into master
Project CI / AI game creator shell Rust smoke (push) Successful in 3m58s
Project CI / AI game creator shell Rust lane 1/2 (push) Failing after 7m26s
Project CI / AI game creator shell Rust crates (push) Successful in 1m40s
Project CI / AI game creator shell Rust lane 2/2 (push) Failing after 8m43s
Project CI / Frontend tests (push) Failing after 5m41s
Project CI / Backend tests (push) Successful in 7m29s
Project CI / Repository checks (push) Successful in 4m50s
Project CI / Native shell tests (push) Successful in 9m32s
Project CI / AI game creator shell web tests (push) Has been cancelled
Reviewed-on: #448
2026-09-21 13:04:11 +08:00
kdletters 886bdc06ed 去掉渠道环境变量用例里重复的 stageRuntime
Project CI / AI game creator shell Rust crates (push) Successful in 2m44s
Project CI / AI game creator shell Rust smoke (push) Successful in 3m37s
Project CI / AI game creator shell Rust lane 1/2 (push) Failing after 6m56s
Project CI / AI game creator shell Rust lane 2/2 (push) Failing after 7m58s
Project CI / Backend tests (push) Successful in 6m33s
Project CI / Frontend tests (push) Has been cancelled
Project CI / Repository checks (push) Has been cancelled
Project CI / Native shell tests (push) Has been cancelled
Project CI / AI game creator shell web tests (push) Has been cancelled
- 两次独立修复(#444 与本仓库 55cb04765)在同一处各加了一个 stageRuntime,合并后成为重复对象键,Web-Build 的 ESLint(no-dupe-keys) 失败
- 保留一条带说明的 stageRuntime stub,用例语义不变
2026-09-21 12:49:34 +08:00
suzmii 562e1ba586 「生成任务」侧栏读秒改为 100ms 粒度:与对话侧共用同一份时钟
Project CI / AI game creator shell Rust crates (pull_request) Successful in 2m57s
Project CI / Backend tests (pull_request) Failing after 12s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 4m2s
Project CI / AI game creator shell Rust lane 1/2 (pull_request) Failing after 7m15s
Project CI / Repository checks (pull_request) Failing after 20s
Project CI / AI game creator shell Rust lane 2/2 (pull_request) Failing after 8m16s
Project CI / Frontend tests (pull_request) Successful in 7m30s
Project CI / AI game creator shell web tests (pull_request) Successful in 4m1s
Project CI / Native shell tests (pull_request) Successful in 11m1s
- ResourceCanvasAssetGenerationTasksPanelView:删掉面板自带的 1000ms interval 与 nowMillis 状态;两条任务行的「已耗时」下沉为叶子组件(AssetGenerationElapsedLabel / ResourceEditElapsedLabel),各自订阅共享 hook useLiveNow(LIVE_TIMER_TICK_MS = 100)。
- 为什么不是面板级时钟:面板上通常同时挂着多条任务,100ms 的 tick 落在面板上等于每 0.1 秒重建整个侧栏;useLiveNow 的注释明确要求调用方是叶子节点。终态行不订阅,已耗时定格在账本给的结束时间上。
- 行为:不足一分钟的耗时本来就显示到 0.1 秒(formatElapsedDuration),现在每 100ms 真的更新一次,不再是「带小数却 1 秒跳一格」。
- 用例:新增「读秒按 100ms 刷新(0.0 → 0.1 → 0.5 秒)」「终态行不再走表,定格在结束时间」「秒表只订在运行中的那一行上(setInterval 只被调用一次)」;把 LIVE_TIMER_TICK_MS 临时改回 1000 时第一条用例即红,粒度确实被钉住。
2026-09-21 12:48:21 +08:00
suzmii e18067e028 Merge pull request 'macOS 发布改为只出 arm64 单架构(修复 Mac 管线 #7 起连续失败)' (#447) from feat/agc-macos-arm64-only into master
Project CI / AI game creator shell Rust smoke (push) Successful in 2m11s
Project CI / Frontend tests (push) Has been cancelled
Project CI / Repository checks (push) Has been cancelled
Project CI / AI game creator shell web tests (push) Has been cancelled
Project CI / Native shell tests (push) Has been cancelled
Project CI / AI game creator shell Rust lane 2/2 (push) Has been cancelled
Project CI / AI game creator shell Rust crates (push) Has been cancelled
Project CI / Backend tests (push) Has been cancelled
Project CI / AI game creator shell Rust lane 1/2 (push) Has been cancelled
Reviewed-on: #447
2026-09-21 12:38:03 +08:00
suzmii 613d62fdb2 同步里程碑计划:macOS 清单只登记 darwin-aarch64
Project CI / AI game creator shell Rust crates (pull_request) Failing after 53s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 2m3s
Project CI / AI game creator shell Rust lane 1/2 (pull_request) Failing after 6m52s
Project CI / AI game creator shell Rust lane 2/2 (pull_request) Failing after 7m40s
Project CI / Repository checks (pull_request) Failing after 2m0s
Project CI / Backend tests (pull_request) Successful in 7m42s
Project CI / Native shell tests (pull_request) Successful in 8m47s
Project CI / Frontend tests (pull_request) Successful in 6m54s
Project CI / AI game creator shell web tests (pull_request) Successful in 5m1s
- docs/project-memory/plans 的渠道化里程碑仍写着 dev-mac universal 同时写两个平台键,与 2026-09-21 的单架构决策冲突,按当前口径更新并指向决策记录
2026-09-21 12:35:36 +08:00
suzmii b4ce6877c8 修掉「拖动占位卡仍触发点击」的真因:点击抑制的计时起点必须在松手那一刻
- useResourceCanvasGenerationPlaceholders:抑制状态在越过拖动阈值时只登记、不起计时器,改到 pointerup 才起 0ms 计时(deferDragClickSuppressionCleanup);pointercancel 与切项目走 clearDragClickSuppression 立刻收干净。
- 原实现(越过阈值时就起 0ms 计时器)在真实鼠标下不成立:一次拖动里 pointermove 横跨多轮宏任务,计时器早在松手前就把抑制清掉,收尾那次 click 照样生效——jsdom 同步发 move/up 看不见这一档,所以上一版用例是假绿。
- 用例补上真实时序:拖动过程中显式让时钟走一轮宏任务再松手;宿主用例还补上浏览器在 pointerup 之后补发的 lostpointercapture,并断言它不能把这次拖动的抑制一起清掉。
- 敏感性已双向验证:把计时器搬回「越过阈值那一刻」、以及让 lostpointercapture 清抑制,两条用例都会红;改用例前的同步版本对两种错法都会绿(所以上一版没抓住)。
- 注释写明计时起点为什么是松手那一刻,并与资源卡链路的 deferSkippedResourceCardClickCleanup 对齐口径。
2026-09-21 12:34:47 +08:00
suzmii e53992fdc2 macOS 发布改为只出 arm64 单架构
Project CI / Frontend tests (pull_request) Has been cancelled
Project CI / Repository checks (pull_request) Has been cancelled
Project CI / AI game creator shell Rust lane 2/2 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust smoke (pull_request) Has been cancelled
Project CI / AI game creator shell Rust crates (pull_request) Has been cancelled
Project CI / Backend tests (pull_request) Has been cancelled
Project CI / Native shell tests (pull_request) Has been cancelled
Project CI / AI game creator shell web tests (pull_request) Has been cancelled
Project CI / AI game creator shell Rust lane 1/2 (pull_request) Has been cancelled
- build-macos-ci 固定 aarch64-apple-darwin:单架构构建、只跑 arm64 隔离 smoke、首装包命名 <产品名>_<版本>_aarch64.dmg,构建清单记录 smokes 与实际清单平台键
- stage-node-runtime 的 universal-apple-darwin 恢复失败关闭并说明原因:随包 Node 只有单架构官方发行版,按宿主架构放行会让 Intel 上这份侧车不可执行,且通用包自检按 process.arch 校验抓不到
- 守卫用例改为断言入口固定 arm64 目标与 _aarch64.dmg 后缀、universal 目标必须抛错
- Jenkinsfile 与三份技术/运维文档同步单架构口径:清单只登记 darwin-aarch64,Intel 非目标,恢复 universal 的前置条件写在文档里
- 共享记忆补 2026-09-21 决策记录,pitfalls 记下「只带宿主架构的通用包」陷阱,避免再次用过渡实现糊过去
2026-09-21 12:30:56 +08:00
suzmii a5ee06a4c7 Merge pull request '修复macOS主机上AGC发布测试未stub Node运行时staging' (#444) from fix/agc-test-node-runtime-stub into master
Project CI / AI game creator shell Rust smoke (push) Successful in 4m16s
Project CI / AI game creator shell Rust crates (push) Successful in 1m6s
Project CI / AI game creator shell Rust lane 1/2 (push) Failing after 7m51s
Project CI / AI game creator shell Rust lane 2/2 (push) Failing after 8m45s
Project CI / Repository checks (push) Failing after 1m55s
Project CI / Backend tests (push) Successful in 6m33s
Project CI / Native shell tests (push) Successful in 7m47s
Project CI / Frontend tests (push) Successful in 5m49s
Project CI / AI game creator shell web tests (push) Has been cancelled
Reviewed-on: #444
2026-09-21 12:23:52 +08:00
suzmii 7b57cba14d 补齐「图集(生成图标素材)为什么没有 @」的当面说明与依据
- 生成浮层:不给 @ 选择器的入口新增一段说明行(`data-resource-canvas-generation-reference-free`),讲清「该入口走平台图集通道,参考只有一张权威规范图(图标规范),不支持另挑参考图」——验收现场那条「生成图标素材没法 @」读起来像漏了按钮,原因其实在通道上。
- 样式:说明行允许折行、沿用次要文字色;与既有的「参考图 n/5」计数行区分开。
- 用例:图集入口断言说明行在场;逐条入口断言「说明行」与「@ 选择器」严格互补;原「不呈现参考选择」的判据从按词匹配改成按计数元素/计数值匹配(说明行本身会提到「参考图」三个字)。
- 文档:入口矩阵补「图集为什么没有 @」一条,写明图集走 `icon-spritesheets` 通道、提交体只有 referenceId + iconDescriptions(无 referenceImageSrcs)、结果绑定硬校验参考恰好一张,以及「平台 OpenAPI 该请求 schema 有 referenceImageSrcs 字段,放开属于产品 + 平台口径变更」。
2026-09-21 12:23:32 +08:00
kdletters 55cb047654 支持 macOS 通用包构建时的 Node 运行时暂存
Project CI / Frontend tests (push) Has been cancelled
Project CI / Native shell tests (push) Has been cancelled
Project CI / AI game creator shell Rust smoke (push) Has been cancelled
Project CI / AI game creator shell Rust crates (push) Has been cancelled
Project CI / Backend tests (push) Has been cancelled
Project CI / AI game creator shell Rust lane 2/2 (push) Has been cancelled
Project CI / Repository checks (push) Has been cancelled
Project CI / AI game creator shell web tests (push) Has been cancelled
Project CI / AI game creator shell Rust lane 1/2 (push) Has been cancelled
- stage-node-runtime 的 targetRuntime 支持 universal-apple-darwin:在 macOS 宿主上按宿主架构暂存官方 Node(通用包自检按 process.arch 校验),非 darwin 宿主仍失败关闭
- 同步 stage-node-runtime 测试期望:darwin 宿主可用、linux 宿主仍拒绝,Universal Node 合并(lipo)留作未完成项
- 共享记忆记录该限制:当前通用包侧车仍是宿主架构,Intel Mac 需等待真正的通用 Node
2026-09-21 12:15:28 +08:00
suzmii beebcca4de 修复 AGC 画布四项验收问题:锚点让位标题栏、浮层不再撞画布边缘、拖动不再触发点击、图标规范参考口径对齐
- 生成任务锚点新增「资源总览」档:资源总览页仍贴画布顶边内缩 0.85rem,资源栏目画布页让开顶部钉住的整宽栏目标题栏(42px + 0.5rem),两档切换走 margin-top 过渡(减动效下关掉)。
- 生成浮层的顶边与可用高度改为按占位卡的真实屏幕位置算(卡下沿到安全底边),不再假设卡片贴在安全带上沿——占位落到下半屏时浮层底边不再越过画布下沿被切掉。
- 生成浮层新增水平收口:按「浮层左右各留 12px」把锚点收进画布可视范围,卡片靠边时浮层不再有一半落到画布之外;宽度口径与面板 CSS 同源(min(560px, 100% - 24px))。
- 新增画布卡片手势的共享判据 resourceCanvasGestureExceededDragThreshold(阈值仍取 RESOURCE_CANVAS_DRAG_THRESHOLD):资源卡与生成占位卡共用同一份「拖动还是点击」判断。
- 生成占位卡修掉拖动收尾误触点击:越过阈值才算拖动、登记一次性点击抑制(consumeDragClick)由宿主消费,「拖动中」样式也从越过阈值那一刻起才亮。
- 生成占位卡的删除按钮起手手势不再被当成「点卡片」:按起手点判定,松手落回卡片时不触发开合生成浮层。
- 图标规范面板的参考选择注释按现行判据改写(只有图集 icon-spritesheet 不接受用户参考),入口矩阵文档同步补「参考图(@ 引用)」口径并修掉「本地 IPC 没有参考图入参」的旧说法。
- 补齐回归用例:手势模型判据、占位卡拖动/点击与阈值、宿主级「拖完不弹浮层且普通点击仍开合」、浮层顶边与水平收口、锚点分档与跨文件标题栏高度守卫、逐条生成入口的 @ 与判据一致、图标规范面板的 @ 与提交带引用。
- 共享记忆 pitfalls.md 记录两条排障口径:卡类手势必须只有一份阈值与点击抑制判据;画布浮层几何只能按真实屏幕位置算、分页锚点必须让开钉死的标题栏。
2026-09-21 11:58:13 +08:00
kdletters 9bf35e8745 修复 macOS 构建上的渠道环境变量用例宿主依赖
Project CI / AI game creator shell Rust crates (push) Successful in 2m58s
Project CI / AI game creator shell Rust smoke (push) Successful in 3m50s
Project CI / AI game creator shell Rust lane 1/2 (push) Failing after 7m0s
Project CI / AI game creator shell Rust lane 2/2 (push) Failing after 8m5s
Project CI / Backend tests (push) Successful in 7m2s
Project CI / Native shell tests (push) Successful in 8m12s
Project CI / Repository checks (push) Successful in 4m8s
Project CI / Frontend tests (push) Successful in 5m15s
Project CI / AI game creator shell web tests (push) Failing after 6m13s
- build-release.test.mjs 的「packaged renderer receives the same channel as the updater manifest」用 windows target 却未注入 stageRuntime,真实 staging 要求宿主 Node 平台/架构与目标一致,导致 macOS(arm64)/Linux 上必然失败
- 该用例只断言传给 spawn 的 VITE_AGC_PLATFORM_CHANNEL,改为注入空 stageRuntime,与同文件其它用例一致
2026-09-21 11:53:32 +08:00
kdletters 90207bc1d5 minimal 备份增加 freeze 副本路径
Project CI / AI game creator shell Rust smoke (push) Successful in 2m35s
Project CI / AI game creator shell Rust crates (push) Successful in 1m14s
Project CI / AI game creator shell Rust lane 1/2 (push) Failing after 7m4s
Project CI / AI game creator shell Rust lane 2/2 (push) Failing after 7m28s
Project CI / Backend tests (push) Successful in 7m25s
Project CI / Frontend tests (push) Successful in 7m18s
Project CI / Repository checks (push) Successful in 5m51s
Project CI / Native shell tests (push) Successful in 9m16s
Project CI / AI game creator shell web tests (push) Successful in 3m41s
- database-backup-to-oss.mjs 新增 --freeze-dir:minimal 模式先把选中子集 rsync 成冻结副本(保持原始相对路径)再从副本上传,避免热备时最新 commitlog 持续追加触发 stat 漂移失败
- files-minimal systemd 模板与发布前 minimal 备份默认传入 freeze 目录
- 生产运维门禁同步 freeze 口径断言
2026-09-21 11:37:14 +08:00
kdletters 2f248ea0c3 新增 minimal 备份口径并切换 release 定时备份
Project CI / Frontend tests (push) Has been cancelled
Project CI / AI game creator shell Rust lane 1/2 (push) Has been cancelled
Project CI / AI game creator shell Rust lane 2/2 (push) Has been cancelled
Project CI / AI game creator shell Rust smoke (push) Has been cancelled
Project CI / AI game creator shell Rust crates (push) Has been cancelled
Project CI / Backend tests (push) Has been cancelled
Project CI / Native shell tests (push) Has been cancelled
Project CI / Repository checks (push) Has been cancelled
Project CI / AI game creator shell web tests (push) Has been cancelled
- database-backup-to-oss.mjs 新增 --minimal/--retain-snapshots:按上游 retention 语义只备份最近 N 份 snapshot、覆盖最老保留 snapshot 的 commitlog 边界段及其后全部段,外加身份/配置/控制库/模块字节,且不停止任何服务
- 备份检查脚本补充 minimal 计划用例(保留次新+最新 snapshot、丢弃更早 snapshot 与 clog 段、状态路径齐全、保留数校验)
- 发布前备份默认走 minimal 热备(GENARRATIVE_STDB_PUBLISH_BACKUP_MINIMAL=0 可回到冷备),不再需要 44.7GiB 冷备空间
- Server-Provision 新增 DATABASE_BACKUP_PROFILE=files-minimal 与 systemd drop-in,release 推荐使用并继续禁止 files-history
- 运维文档与共享记忆记录上游 retention 依据、实测 40G→3.6G 与不停服热备口径
2026-09-21 11:33:39 +08:00
kdletters 117d482f93 发布前备份空间预检前置并支持自动降级
Project CI / AI game creator shell Rust smoke (push) Successful in 2m13s
Project CI / AI game creator shell Rust crates (push) Successful in 1m7s
Project CI / AI game creator shell Rust lane 1/2 (push) Failing after 7m9s
Project CI / AI game creator shell Rust lane 2/2 (push) Failing after 6m57s
Project CI / Native shell tests (push) Successful in 7m58s
Project CI / Repository checks (push) Successful in 5m13s
Project CI / Frontend tests (push) Successful in 7m19s
Project CI / Backend tests (push) Successful in 10m10s
Project CI / AI game creator shell web tests (push) Successful in 4m47s
- database-backup-to-oss.mjs 新增 --check-space-only:archive 按 data×1.1、files 按 max(data×0.05, 2GiB) 计算门槛,空间不足以退出码 3 返回
- production-stdb-publish.sh 在进入维护与停服务之前先做空间预检,archive 不足时自动降级 files(files 不支持 defer,async 收敛为 sync),可用环境变量关闭
- 尚未开始 publish 的失败自动恢复本次停掉的 API/controller/worker 并退出维护,只有真正开始发布之后的失败才保持维护态
- 备份检查脚本与生产运维门禁补上新口径与执行顺序断言,运维文档与共享记忆记录事故与规则
2026-09-21 10:57:29 +08:00
174 changed files with 24283 additions and 1102 deletions
@@ -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(
+20
View File
@@ -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 },
);
}
+32
View File
@@ -1033,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;
};
}
+7
View File
@@ -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}
+1
View File
@@ -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);
});
+2
View File
@@ -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
View File
@@ -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('名称须为 180 个字符')).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
+81
View File
@@ -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;
}
@@ -9,6 +9,7 @@ import { fileURLToPath } from 'node:url';
import {
generateUpdateManifest,
prepareReleaseVersion,
resolveManifestPlatformKeys,
resolveReleaseContext,
resolveReleasePartition,
runTauriBuild,
@@ -20,10 +21,13 @@ import {
} from './verify-updater-signature.mjs';
/**
* AGC macOS 分区(`<channel>-mac`)发布入口:构建 universal 包 → 双架构 smoke → 生成 universal DMG
* AGC macOS 分区(`<channel>-mac`)发布入口:构建 arm64 单架构包 → arm64 隔离 smoke → 生成 arm64 DMG
* → 生成分区清单 latest.json → 用产物内烘焙的公钥验签 → 按 dry-run 决定是否上传 OSS。
*
* 边界:
* - 只出 Apple Siliconarm64)单架构:清单只登记 `darwin-aarch64`。Intel 侧要可用,前提是随包 Node
* 也能按架构各带一份(`stage-node-runtime.mjs` 对 universal 目标失败关闭);在实现之前**不得**
* 把 arm64 产物登记成 `darwin-x86_64`,否则 Intel 客户端会装到跑不起来的包。
* - Apple 签名与公证暂缺:本入口剥离 `APPLE_*` 凭据让 Tauri 跳过 Apple 签名,但**不能传
* `--no-sign`** —— 该标志同时会跳过 updater 的 minisign 签名,产物就没有 `.sig`
* 未签名 + 未公证必须显式记录而非静默通过;
@@ -94,11 +98,14 @@ 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');
const context = resolveReleaseContext(['--target=universal-apple-darwin']);
// 单架构目标:清单侧 `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);
// 首装包名必须保持 `<产品名>_<版本>_universal.dmg`:清单侧按该后缀唯一匹配本次产物。
const firstInstallName = `${productName}_${version}_universal.dmg`;
// 首装包名必须让清单侧的单架构分支唯一匹配:`<产品名>_<版本>_<架构>.dmg`
// 架构段用 Tauri 的 aarch64 口径(不是 updater 平台键的 arm64 / x86_64)。
const firstInstallName = `${productName}_${version}_aarch64.dmg`;
// 幂等边界:workspace 会保留上一轮产物。先删掉本次将要写出的对象,否则
// 1) hdiutil 会因同名 DMG 已存在直接失败(首次实跑即命中);
@@ -117,7 +124,7 @@ for (const stale of [
}
const args = [
'--target=universal-apple-darwin',
`--target=${macTarget}`,
'--bundles',
'app',
'--ci',
@@ -132,16 +139,13 @@ const command = (binary, argv, options = {}) =>
runTauriBuild(args, context);
const app = path.join(context.bundleRoot, 'macos', appBundleName);
for (const architecture of ['arm64', 'x86_64']) {
command(process.execPath, [
path.join(appRoot, 'scripts/check-macos-bundle.mjs'),
app,
architecture,
'--universal',
]);
}
command(process.execPath, [
path.join(appRoot, 'scripts/check-macos-bundle.mjs'),
app,
'arm64',
]);
// DMG 放在 bundle 根目录下:渠道清单的首装包选择会扫描该目录,命名必须匹配 `_<version>_universal.dmg`。
// DMG 放在 bundle 根目录下:渠道清单的首装包选择会扫描该目录,命名必须匹配 `_<version>_aarch64.dmg`。
const dmgDirectory = path.join(context.bundleRoot, 'macos');
fs.mkdirSync(dmgDirectory, { recursive: true });
const dmg = path.join(dmgDirectory, firstInstallName);
@@ -170,7 +174,7 @@ const release = await generateUpdateManifest(context);
assert.equal(
path.resolve(release.downloadArtifact),
path.resolve(dmg),
'首装包必须锁定本次生成的 universal DMG',
'首装包必须锁定本次生成的 arm64 DMG',
);
// 上传前门禁:用产物里烘焙的公钥复核更新包签名。验不过就停在这里,绝不写 OSS。
@@ -266,8 +270,9 @@ fs.writeFileSync(
firstInstallSha256: dmgHash,
manifest: 'latest.json',
},
smokes: ['arm64', 'x86_64'],
intelSmoke: process.arch === 'arm64' ? 'Rosetta' : 'native',
// 单架构发布:只跑 arm64 隔离 smokeIntel 未支持(清单里没有 darwin-x86_64 键)。
smokes: ['arm64'],
manifestPlatformKeys: resolveManifestPlatformKeys(context.target),
},
null,
2,
@@ -13,7 +13,7 @@ import {
defaultEditorFeatures,
withDefaultCargoFeatures,
} from './cargo-features.mjs';
import { stageNodeRuntimeForTarget } from './stage-node-runtime.mjs';
import { stageNodeRuntime } from './stage-node-runtime.mjs';
const appRoot = fileURLToPath(new URL('..', import.meta.url));
// 提交摘要里的 pathspec 与 `git log` 都以仓库根为基准,不能在应用目录里执行。
@@ -459,8 +459,7 @@ function writeChannelConfigFile(channel, target, includeNodeRuntime = false) {
export function runTauriBuild(
args = [],
context = resolveReleaseContext(args),
// 默认按发布目标 stage:universal 需要两份架构运行时,单架构目标行为不变。
{ spawn = spawnSync, stageRuntime = stageNodeRuntimeForTarget } = {},
{ spawn = spawnSync, stageRuntime = stageNodeRuntime } = {},
) {
if (
explicitBuildTarget(args) &&
@@ -76,33 +76,6 @@ function run(command, args) {
return result;
}
/**
* 单独执行随包 Node 分片:分片架构与宿主一致时直接跑,不一致时用 `arch` 强制
* arm64 机器上的 x86_64 分片依赖 Rosetta,与 `.app` 双架构 smoke 的前提相同)。
*/
function runNodeSlice(directory, args) {
const native = process.arch === 'arm64' ? 'arm64' : 'x86_64';
const binary = path.join(directory, 'node');
const [command, argv] =
architecture === native
? [binary, args]
: ['/usr/bin/arch', [`-${architecture}`, binary, ...args]];
const result = spawnSync(command, argv, {
cwd: root,
env,
encoding: 'utf8',
timeout: 120_000,
maxBuffer: 1024 * 1024,
});
assert.ifError(result.error);
assert.equal(
result.status,
0,
`${directory} 随包 Node 执行失败:${result.stderr || result.stdout}`,
);
return result.stdout.trim();
}
/**
* APFS 上优先用 `ditto --clone`:整包按区块克隆,秒级完成且几乎不占额外空间。
* 跨卷或非 APFS 时回退到真实复制;两种路径都必须产出可独立改动的副本,
@@ -275,84 +248,37 @@ try {
}
}
assert.ok(fs.existsSync(path.join(bundle, 'NOTICE.md')));
// 随包 Node:单架构构建是扁平目录,universal 构建把两套架构运行时并列放进
// `game-runtime/node/<platform>-<arch>/`(与 Codex 侧车同形态,由 Rust 侧按运行架构选择)。
// 两套清单在本函数里都做完整性与架构校验;只执行与本次 smoke 架构一致的那一份,
// 另一份由另一次架构的 smoke 覆盖(build-macos-ci.mjs 会对 arm64 / x86_64 各跑一次)。
const nodeRoot = path.join(resources, 'game-runtime/node');
const nodeSlices = requireUniversal
? ['darwin-arm64', 'darwin-x64'].map((platform) => ({
platform,
directory: path.join(nodeRoot, platform),
}))
: [{ platform: null, directory: nodeRoot }];
for (const slice of nodeSlices) {
const { directory } = slice;
const nodeManifest = JSON.parse(
fs.readFileSync(path.join(directory, 'manifest.json'), 'utf8'),
const nodeManifest = JSON.parse(
fs.readFileSync(path.join(nodeRoot, 'manifest.json'), 'utf8'),
);
assert.equal(nodeManifest.schemaVersion, 'agc-node-runtime.v1');
assert.equal(nodeManifest.platform, 'darwin');
assert.equal(nodeManifest.arch, process.arch);
const runtimeFiles = fs
.readdirSync(nodeRoot, { recursive: true })
.filter(
(file) =>
fs.statSync(path.join(nodeRoot, file)).isFile() &&
file !== 'manifest.json',
);
assert.equal(nodeManifest.schemaVersion, 'agc-node-runtime.v1');
assert.equal(nodeManifest.platform, 'darwin');
if (slice.platform) {
// 目录名与清单架构必须一致:错位会让用户拿到跑不起来的运行时。
assert.equal(`darwin-${nodeManifest.arch}`, slice.platform);
assert.ok(
/^(arm64|x64)$/u.test(nodeManifest.arch),
`未知运行架构:${nodeManifest.arch}`,
);
} else {
assert.equal(nodeManifest.arch, process.arch);
}
const runtimeFiles = fs
.readdirSync(directory, { recursive: true })
.filter(
(file) =>
fs.statSync(path.join(directory, file)).isFile() &&
file !== 'manifest.json',
);
assert.deepEqual(
runtimeFiles.sort(),
Object.keys(nodeManifest.files).sort(),
slice.platform ?? 'flat',
);
for (const [file, digest] of Object.entries(nodeManifest.files)) {
assert.equal(await hashFile(path.join(directory, file)), digest, file);
}
assert.ok(nodeManifest.files['NODE-LICENSE']);
assert.ok(nodeManifest.files['node_modules/npm/LICENSE']);
fs.accessSync(path.join(directory, 'node'), fs.constants.X_OK);
// 二进制本身必须是本分片的单一架构:官方发行版不做 universal,lipo 能直接证明。
const sliceArchitecture = spawnSync(
'/usr/bin/lipo',
['-archs', path.join(directory, 'node')],
{ encoding: 'utf8' },
);
assert.equal(sliceArchitecture.status, 0, 'lipo -archs node');
assert.equal(
sliceArchitecture.stdout.trim(),
nodeManifest.arch === 'x64' ? 'x86_64' : 'arm64',
'随包 Node 的二进制架构必须等于清单架构',
);
// 只有与本次 smoke 架构一致的分片才执行;另一架构留给对应的那次 smoke。
if (
!requireUniversal ||
nodeManifest.arch === (architecture === 'arm64' ? 'arm64' : 'x64')
) {
assert.equal(
runNodeSlice(directory, ['--version']),
nodeManifest.nodeVersion,
`${slice.platform ?? 'flat'} node --version`,
);
assert.equal(
runNodeSlice(directory, [
path.join(directory, 'node_modules/npm/bin/npm-cli.js'),
'--version',
]),
nodeManifest.npmVersion,
`${slice.platform ?? 'flat'} npm --version`,
);
}
assert.deepEqual(runtimeFiles.sort(), Object.keys(nodeManifest.files).sort());
for (const [file, digest] of Object.entries(nodeManifest.files)) {
assert.equal(await hashFile(path.join(nodeRoot, file)), digest, file);
}
assert.ok(nodeManifest.files['NODE-LICENSE']);
assert.ok(nodeManifest.files['node_modules/npm/LICENSE']);
assert.equal(
run(path.join(nodeRoot, 'node'), ['--version']).stdout.trim(),
nodeManifest.nodeVersion,
);
assert.equal(
run(path.join(nodeRoot, 'node'), [
path.join(nodeRoot, 'node_modules/npm/bin/npm-cli.js'),
'--version',
]).stdout.trim(),
nodeManifest.npmVersion,
);
const plugin = path.join(resources, 'plugins/agc-cocos-editor');
for (const file of [
'plugin.json',
@@ -361,6 +287,13 @@ try {
]) {
assert.ok(fs.existsSync(path.join(plugin, file)), file);
}
// 随包 Node 的 npm 是包里唯一允许出现的 node_modules:除了 npm 目录自身与它的子项,
// 还要放行它的上级目录 `game-runtime/node/node_modules`recursive readdir 会列出目录项,
// 少了这一条会让整个门禁对合法包失败——#439 引入后一直没被跑到,直到 2026-09-21 才暴露)。
const allowedNodeModules = (file) =>
file === 'game-runtime/node/node_modules' ||
file === 'game-runtime/node/node_modules/npm' ||
file.startsWith('game-runtime/node/node_modules/npm/');
const packageFiles = fs.readdirSync(resources, { recursive: true });
assert.ok(
!packageFiles.some(
@@ -368,13 +301,7 @@ try {
/(^|\/)(\.env[^/]*|auth\.json|target|\.git)(\/|$)|\.(exe|dll)$/.test(
file,
) ||
// 只有随包 Node 自带的 npm 允许出现 node_modules;两种布局都要放行:
// 单架构的 `game-runtime/node/node_modules/npm` 与 universal 的
// `game-runtime/node/<platform>-<arch>/node_modules/npm`。
(/(^|\/)node_modules(\/|$)/.test(file) &&
!/^game-runtime\/node\/((darwin-(arm64|x64))\/)?node_modules\/npm(\/|$)/u.test(
file,
)),
(/(^|\/)node_modules(\/|$)/.test(file) && !allowedNodeModules(file)),
),
);
assert.equal(run(executable, ['--version']).stdout.trim(), manifest.version);
@@ -178,8 +178,12 @@ test('macOS release entry and smoke script derive product names from config and
assert.ok(entry.includes('readProductName'), '入口必须从 Tauri 配置读产品名');
assert.ok(!entry.includes('陶泥儿'), 'macOS 发布入口不得写死产品名');
assert.ok(
entry.includes('_${version}_universal.dmg'),
'首装包名必须保留清单侧唯一匹配所需的后缀',
entry.includes("const macTarget = 'aarch64-apple-darwin'"),
'macOS 发布入口必须固定单架构目标',
);
assert.ok(
entry.includes('_${version}_aarch64.dmg'),
'首装包名必须保留清单侧单架构分支唯一匹配所需的后缀(Tauri 口径 aarch64',
);
const smoke = fs.readFileSync(
@@ -6,13 +6,6 @@ import { fileURLToPath } from 'node:url';
const appRoot = fileURLToPath(new URL('..', import.meta.url));
export const nodeRuntimeSchema = 'agc-node-runtime.v1';
// 单架构目标写扁平目录;universal 在此目录下按架构分目录,见 stageNodeRuntimeForTarget。
const defaultRuntimeDestination = path.join(
appRoot,
'src-tauri',
'resources',
'node-runtime',
);
export function readInstalledNodeLicense(
version,
@@ -72,117 +65,20 @@ export function targetRuntime(target) {
'aarch64-apple-darwin': ['darwin', 'arm64'],
'x86_64-apple-darwin': ['darwin', 'x64'],
};
const value = targets[target];
// universal 不是单份运行时能表达的目标:它必须按架构展开成两份,见 targetRuntimes。
if (!value)
throw new Error(
target === 'universal-apple-darwin'
? 'Node 运行时不能直接按 universal-apple-darwin 制作:双架构请用 stageNodeRuntimeForTarget 按架构展开'
: `Node 运行时不支持发布目标:${target}`,
);
return { platform: value[0], arch: value[1] };
}
/**
* 发布目标需要的随包运行时列表:universal 需要两份单架构运行时,
* 其余目标仍然是一份(保持既有扁平布局与行为)。
*/
export function targetRuntimes(target) {
// 随包 Node 是**单架构**官方发行版:一份运行时只服务它自己的架构。
// macOS 发布当前固定为 aarch64-apple-darwin 单架构包(Intel 未支持),
// universal 目标没有正确的运行时来源,必须失败关闭——绝不能退化成
// 「按宿主架构暂存一份 arm64」:那样通用包自检(按 process.arch)能过,
// 但 Intel 机器上这份运行时不可执行,用户拿到的是坏包。
if (target === 'universal-apple-darwin')
return ['aarch64-apple-darwin', 'x86_64-apple-darwin'];
return [target];
}
/**
* 按架构选择 staging 输入。
*
* 契约(见实施计划):发布包只从**本机已安装且与目标平台/架构一致**的工具链取材,
* 不得使用项目内或相对 PATH 的伪造运行时。宿主架构直接复用当前 Node;
* 其它架构必须由构建节点显式提供,缺失即失败关闭——不静默跳过、不回退系统 Node。
*/
export function runtimeSourceForTarget(
archTarget,
{
env = process.env,
nodePath,
npmCli,
licensePath,
hostNodePath = process.execPath,
hostNpmCli = process.env.npm_execpath,
hostLicensePath = env.AGC_NODE_LICENSE_PATH,
hostPlatform = process.platform,
hostArch = process.arch,
} = {},
) {
const native = targetRuntime(archTarget);
if (native.platform === hostPlatform && native.arch === hostArch) {
return {
nodePath: nodePath ?? hostNodePath,
npmCli: npmCli ?? hostNpmCli,
licensePath: licensePath ?? hostLicensePath,
};
}
const key = `${native.platform}_${native.arch}`.toUpperCase();
const configured = env[`AGC_NODE_RUNTIME_${key}_PATH`]?.trim();
if (!configured) {
throw new Error(
`缺少 ${native.platform}/${native.arch} 的 Node 运行时:该架构不是构建宿主,` +
`请先在本机安装同架构 Node,再用 AGC_NODE_RUNTIME_${key}_PATH 指向其 bin/node`,
'Node 运行时不支持 universal-apple-darwin:随包 Node 只有单架构发行版,' +
'通用包需按架构各带一份(另行下载另一架构官方发行版)之后才能构建;' +
'当前 macOS 发布固定为 aarch64-apple-darwin 单架构',
);
}
return {
nodePath: configured,
// 明令不使用宿主 npm`npm_execpath`):另一架构的 npm 必须来自它自己那份发行版
// 安装目录,否则两份切片的 npm 来源不同源,架构与来源对不上。null 表示"按 node 目录查找"。
npmCli: null,
licensePath: env[`AGC_NODE_RUNTIME_${key}_LICENSE_PATH`]?.trim(),
};
}
/**
* 按发布目标 stage 运行时资源。
*
* 单架构目标沿用既有扁平目录(`node-runtime/`),universal 目标写进
* `node-runtime/<platform>-<arch>/`——与捆绑 Codex 的分架构目录同一形态,
* 由 Rust 侧按当前运行架构选择;构建期资源映射仍是整目录映射,无需按架构分叉。
*
* 先解析并校验**全部**来源,再逐个落盘:非宿主架构的运行时缺失、平台/架构不符、
* 两套版本不一致,都在写出任何运行时目录之前失败,不留下半套资源冒充发布内容。
*/
export function stageNodeRuntimeForTarget(
target,
{ destination = defaultRuntimeDestination, ...options } = {},
) {
const targets = targetRuntimes(target);
const plans = targets.map((archTarget) => {
const native = targetRuntime(archTarget);
return {
destination:
targets.length === 1
? destination
: path.join(destination, `${native.platform}-${native.arch}`),
inspected: inspectRuntimeSource(archTarget, {
...options,
...runtimeSourceForTarget(archTarget, options),
}),
};
});
// 两个切片必须是同一套 Node:版本不一致意味着其中一份被换过,
// 用户在不同架构上会拿到行为不同的工具链。
const identities = new Set(
plans.map(
({ inspected }) =>
`${inspected.info.version}|${inspected.npmPackage.version}`,
),
);
if (identities.size !== 1) {
throw new Error(
`多架构 Node 运行时版本不一致:${[...identities].join(' / ')}`,
);
}
return plans.map(({ inspected, destination }) =>
writeRuntimeBundle(inspected, { destination }),
);
const value = targets[target];
if (!value) throw new Error(`Node 运行时不支持发布目标:${target}`);
return { platform: value[0], arch: value[1] };
}
function inside(root, file) {
@@ -327,19 +223,13 @@ export function assertPortableMacNode(output) {
}
}
/**
* 只读校验一份运行时来源,返回 staging 需要的全部事实。
*
* 与写盘分离的原因:多架构发布必须能在写出任何文件之前发现「另一份来源缺失或
* 与目标不符」。校验口径保持原样——平台/架构必须等于目标、macOS 二进制只能链接
* 系统动态库、npm 的身份与实际版本必须一致、许可必须来自发行版本体。
*/
export function inspectRuntimeSource(
export function stageNodeRuntime(
target,
{
nodePath = process.execPath,
npmCli = process.env.npm_execpath,
licensePath = process.env.AGC_NODE_LICENSE_PATH,
destination = path.join(appRoot, 'src-tauri', 'resources', 'node-runtime'),
execute = execFileSync,
installedLicense = readInstalledNodeLicense,
} = {},
@@ -374,7 +264,6 @@ export function inspectRuntimeSource(
);
}
const nodeDirectory = path.dirname(node);
// `npmCli: null` 表示显式拒绝沿用宿主 npm,只按这份 node 自己的安装目录查找。
const npmCandidates = [
npmCli,
path.join(nodeDirectory, 'node_modules/npm/bin/npm-cli.js'),
@@ -431,14 +320,6 @@ export function inspectRuntimeSource(
throw new Error('Node LICENSE 不包含发行许可');
if (!fs.statSync(path.join(npmRoot, 'LICENSE')).isFile())
throw new Error('npm 缺少 LICENSE');
return { native, node, npmRoot, npmPackage, info, license, licenseName };
}
/** 把已校验的来源写成一份发布资源,返回清单。 */
function writeRuntimeBundle(
{ native, node, npmRoot, npmPackage, info, license, licenseName },
{ destination },
) {
// 临时同级目录完成后才替换资源;不污染 Node 安装或项目工作区。
const requestedDestination = path.resolve(destination);
if (requestedDestination === path.dirname(requestedDestination))
@@ -524,26 +405,3 @@ function writeRuntimeBundle(
cleanupStaging(staging, parent, stagingPrefix, stagingIdentity);
}
}
export function stageNodeRuntime(
target,
{
nodePath = process.execPath,
npmCli = process.env.npm_execpath,
licensePath = process.env.AGC_NODE_LICENSE_PATH,
destination = defaultRuntimeDestination,
execute = execFileSync,
installedLicense = readInstalledNodeLicense,
} = {},
) {
return writeRuntimeBundle(
inspectRuntimeSource(target, {
nodePath,
npmCli,
licensePath,
execute,
installedLicense,
}),
{ destination },
);
}
@@ -9,9 +9,7 @@ import {
assertPortableMacNode,
readInstalledNodeLicense,
stageNodeRuntime,
stageNodeRuntimeForTarget,
targetRuntime,
targetRuntimes,
} from './stage-node-runtime.mjs';
function fixture(run) {
@@ -283,10 +281,10 @@ test('native target and macOS dynamic dependency policy reject nonportable Node'
platform: 'darwin',
arch: 'arm64',
});
// universal 不是单份运行时目标:必须报出「按架构展开」而不是笼统的「不支持」
// universal 必须失败关闭:只带宿主架构那一份运行时,Intel 上不可执行
assert.throws(
() => targetRuntime('universal-apple-darwin'),
/stageNodeRuntimeForTarget/u,
/universal-apple-darwin/u,
);
assertPortableMacNode(
'/node:\n\t/usr/lib/libSystem.B.dylib (compatibility version 1)\n',
@@ -299,164 +297,3 @@ test('native target and macOS dynamic dependency policy reject nonportable Node'
/非系统动态库/u,
);
});
// 双架构夹具:每个架构一份来源目录,execute 按被查询的二进制回报对应架构。
function universalFixture(run) {
const root = fs.mkdtempSync(
path.join(os.tmpdir(), 'agc-node-universal-test-'),
);
const sourceFor = (arch, nodeVersion) => {
const dir = path.join(root, `source-${arch}`);
const npm = path.join(dir, 'node_modules/npm');
fs.mkdirSync(path.join(npm, 'bin'), { recursive: true });
fs.writeFileSync(path.join(dir, 'node'), `node-${arch}`);
fs.writeFileSync(
path.join(dir, 'LICENSE'),
'Node.js\nPermission is hereby granted',
);
fs.writeFileSync(path.join(npm, 'LICENSE'), 'npm distribution license');
fs.writeFileSync(
path.join(npm, 'package.json'),
JSON.stringify({ name: 'npm', version: '11.0.0' }),
);
for (const name of ['npm', 'npx'])
fs.writeFileSync(path.join(npm, `bin/${name}-cli.js`), `// ${arch}`);
return {
nodePath: path.join(dir, 'node'),
npmCli: path.join(npm, 'bin/npm-cli.js'),
licensePath: path.join(dir, 'LICENSE'),
nodeVersion,
};
};
try {
return run(root, {
arm64: sourceFor('arm64', 'v22.23.2'),
x64: sourceFor('x64', 'v22.23.2'),
});
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
}
function optionsFor(root, sources, overrides = {}) {
const archOf = (file) => (file.includes('source-x64') ? 'x64' : 'arm64');
return {
destination: path.join(root, 'resources/node-runtime'),
hostPlatform: 'darwin',
hostArch: 'arm64',
hostNodePath: sources.arm64.nodePath,
hostNpmCli: sources.arm64.npmCli,
env: {
AGC_NODE_RUNTIME_DARWIN_X64_PATH: sources.x64.nodePath,
AGC_NODE_RUNTIME_DARWIN_X64_LICENSE_PATH: sources.x64.licensePath,
},
installedLicense() {
throw new Error('no installed fixture license');
},
execute(file, args) {
if (file === '/usr/bin/otool')
return `\t/usr/lib/libSystem.B.dylib\n\t/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation\n`;
if (args[0] === '-p') {
const arch = archOf(file);
return JSON.stringify({
platform: 'darwin',
arch,
version: sources[arch].nodeVersion,
});
}
return '11.0.0';
},
...overrides,
};
}
test('universal stages one runtime per architecture with architecture-correct manifests', () =>
universalFixture((root, sources) => {
assert.deepEqual(targetRuntimes('universal-apple-darwin'), [
'aarch64-apple-darwin',
'x86_64-apple-darwin',
]);
// 模拟经 `npm run` 触发的构建:npm 把宿主的 npm-cli.js 放进环境变量。
// 另一架构的切片必须无视它,只能使用自己发行版目录里的 npm。
const previousNpmExecPath = process.env.npm_execpath;
process.env.npm_execpath = sources.arm64.npmCli;
let manifests;
try {
manifests = stageNodeRuntimeForTarget(
'universal-apple-darwin',
optionsFor(root, sources),
);
} finally {
if (previousNpmExecPath === undefined) delete process.env.npm_execpath;
else process.env.npm_execpath = previousNpmExecPath;
}
assert.deepEqual(
manifests.map((manifest) => `${manifest.platform}-${manifest.arch}`),
['darwin-arm64', 'darwin-x64'],
);
for (const manifest of manifests) {
const directory = path.join(
root,
'resources/node-runtime',
`${manifest.platform}-${manifest.arch}`,
);
assert.equal(
JSON.parse(
fs.readFileSync(path.join(directory, 'manifest.json'), 'utf8'),
).arch,
manifest.arch,
);
assert.ok(fs.existsSync(path.join(directory, 'node')));
assert.ok(
fs.existsSync(path.join(directory, 'node_modules/npm/LICENSE')),
);
// 每份切片必须自带对应架构发行版的 npm,不能借用宿主那一份。
assert.equal(
fs.readFileSync(
path.join(directory, 'node_modules/npm/bin/npm-cli.js'),
'utf8',
),
`// ${manifest.arch}`,
);
}
// 单架构目标仍写扁平目录(与既有发布一致),不产生分架构子目录。
const flat = stageNodeRuntimeForTarget(
'aarch64-apple-darwin',
optionsFor(root, sources, { destination: path.join(root, 'flat') }),
);
assert.equal(flat.length, 1);
assert.ok(fs.existsSync(path.join(root, 'flat/manifest.json')));
assert.ok(!fs.existsSync(path.join(root, 'flat/darwin-arm64')));
}));
test('universal fails closed when the non-host architecture runtime is absent', () =>
universalFixture((root, sources) => {
const options = optionsFor(root, sources, { env: {} });
assert.throws(
() => stageNodeRuntimeForTarget('universal-apple-darwin', options),
/AGC_NODE_RUNTIME_DARWIN_X64_PATH/u,
);
// 缺失时不得留下半成品目录。
assert.ok(!fs.existsSync(path.join(root, 'resources')));
}));
test('universal rejects mismatched Node versions between the two architectures', () =>
universalFixture((root, sources) => {
const options = optionsFor(root, sources);
options.execute = (file, args) => {
if (file === '/usr/bin/otool') return '\t/usr/lib/libSystem.B.dylib\n';
if (args[0] === '-p')
return JSON.stringify({
platform: 'darwin',
arch: file.includes('source-x64') ? 'x64' : 'arm64',
version: file.includes('source-x64') ? 'v22.23.2' : 'v24.0.0',
});
return '11.0.0';
};
assert.throws(
() => stageNodeRuntimeForTarget('universal-apple-darwin', options),
/版本不一致/u,
);
// 版本核对在写出任何架构之前完成,失败时不留下半套运行时。
assert.ok(!fs.existsSync(path.join(root, 'resources')));
}));
@@ -1006,16 +1006,58 @@ pub(crate) async fn external_editor_json_request(
let response = crate::http_client::with_agc_main_site_marker(request)
.send()
.await
.map_err(|error| format!("{action}失败:{error}"))?;
.map_err(|error| {
format!(
"{action}失败:{}",
describe_external_request_failure(&error)
)
})?;
let status = response.status();
if !status.is_success() {
let body = response.text().await.unwrap_or_default();
return Err(format_external_http_error(action, status, &body));
}
response
.json::<serde_json::Value>()
.await
.map_err(|error| format!("解析{action}响应失败:{error}"))
response.json::<serde_json::Value>().await.map_err(|error| {
format!(
"解析{action}响应失败:{}",
describe_external_request_failure(&error)
)
})
}
/// 把 reqwest 失败翻译成可现场定责的文案。
///
/// `reqwest::Error` 的 `Display` 只输出 kind:客户端预算内没读完正文(总超时)、
/// 正文被提前截断和正文不是合法 JSON 都会显示成同一句 `error decoding response body`
/// 现场无法区分是平台慢、链接慢还是响应被截断。这里补上 kind 语义与底层因链;
/// 因链只取错误文本,不拼接 URL,避免把绝对地址写进日志。
fn describe_external_request_failure(error: &reqwest::Error) -> String {
let kind = if error.is_timeout() {
"请求超时(连接、响应头或响应正文未在客户端预算内完成)"
} else if error.is_decode() {
"响应正文未完整返回或不是合法 JSON"
} else if error.is_body() {
"响应正文读取失败"
} else if error.is_connect() {
"连接失败"
} else if error.is_request() {
"请求发送失败"
} else {
"请求失败"
};
let mut causes: Vec<String> = Vec::new();
let mut source = std::error::Error::source(error);
while let Some(current) = source {
let text = current.to_string();
if !text.is_empty() && !causes.contains(&text) {
causes.push(text);
}
source = current.source();
}
if causes.is_empty() {
return kind.to_string();
}
format!("{kind}{}", causes.join(""))
}
/// Keep provider validation details useful to the operator without copying an
@@ -1443,10 +1485,14 @@ pub(crate) async fn prepare_external_canvas_generation_context(
let project_id = if let Some(project_id) = partial.remote_project_id.clone() {
project_id
} else {
// 这一步只需要按 projectId 确认绑定项目是否仍然存在,固定用摘要视图:
// 缺省 full 会把账号下每个项目的画布与全量资源都带回来,项目增长后会耗尽本次请求的
// 客户端预算,现场表现为「解析读取外部画布项目响应失败:error decoding response body」。
// 站内 `/api/editor/projects` 与 `/api/external/v1/editor/projects` 都支持该视图。
let projects_payload = external_editor_json_request(
client
.get(format!(
"{}{}",
"{}{}?view=summary",
access.api_base_url(),
access.api_route("/api/external/v1/editor/projects")
))
@@ -8535,6 +8581,28 @@ mod canvas_generation_tests {
);
}
/// reqwest 的 `Display` 只给 kind,超时 / 正文截断 / 非法 JSON 全都是同一句
/// `error decoding response body`。这个用例钉住「至少把 kind 语义换成人话」,
/// 避免再退回无法定责的原始文案。
#[tokio::test]
async fn external_request_failure_replaces_the_opaque_reqwest_kind() {
let error = reqwest::Client::new()
.get("http://127.0.0.1:1/healthz")
.timeout(Duration::from_secs(2))
.send()
.await
.expect_err("closed port must fail");
let described = describe_external_request_failure(&error);
// 该端口在真实环境里可能被直接拒绝、也可能被中间层吞掉直到超时,两种都必须能定责。
assert!(
described.contains("连接失败") || described.contains("请求超时"),
"{described}"
);
assert!(described.contains(""), "必须补上底层因链:{described}");
assert!(!described.contains("error sending request"), "{described}");
assert!(!described.contains("http://127.0.0.1:1"), "{described}");
}
fn read_test_http_request(stream: &mut std::net::TcpStream) -> String {
stream
.set_nonblocking(false)
@@ -8843,7 +8911,8 @@ mod canvas_generation_tests {
}),
);
false
} else if request.starts_with("GET /api/external/v1/editor/projects ") {
} else if request.starts_with("GET /api/external/v1/editor/projects?view=summary ")
{
write_test_json_response(
&mut stream,
"200 OK",
@@ -9213,7 +9282,7 @@ mod canvas_generation_tests {
.expect("write concurrent generation png body");
return;
}
if request.starts_with("GET /api/external/v1/editor/projects ") {
if request.starts_with("GET /api/external/v1/editor/projects?view=summary ") {
// 项目绑定已由 `install_test_external_project_binding` 预置,远端只需回认同一组身份。
write_test_json_response(
stream,
@@ -9687,7 +9756,7 @@ mod canvas_generation_tests {
"Bearer token-b" => "b",
unexpected => panic!("unexpected authorization {unexpected}"),
};
let response = if request.starts_with("GET /api/editor/projects ") {
let response = if request.starts_with("GET /api/editor/projects?view=summary ") {
let projects = if project_created.get(account).copied().unwrap_or(false) {
vec![serde_json::json!({
"projectId": format!("remote-project-{account}"),
@@ -9853,7 +9922,7 @@ mod canvas_generation_tests {
request_sender
.send(request.clone())
.expect("capture concurrent binding request");
let response = if request.starts_with("GET /api/editor/projects ") {
let response = if request.starts_with("GET /api/editor/projects?view=summary ") {
let (state_lock, ready) = &*state;
let mut state = state_lock.lock().expect("lock project fixture state");
if !state.project_created {
@@ -9988,7 +10057,7 @@ mod canvas_generation_tests {
request_sender
.send(request.clone())
.expect("capture project partial request");
if request.starts_with("GET /api/external/v1/editor/projects ") {
if request.starts_with("GET /api/external/v1/editor/projects?view=summary ") {
write_test_json_response(
&mut stream,
"200 OK",
@@ -10122,7 +10191,7 @@ mod canvas_generation_tests {
request_sender
.send(request.clone())
.expect("capture frozen binding request");
if request.starts_with("GET /api/external/v1/editor/projects ") {
if request.starts_with("GET /api/external/v1/editor/projects?view=summary ") {
write_test_json_response(
&mut stream,
"200 OK",
@@ -10247,23 +10316,24 @@ mod canvas_generation_tests {
request_sender
.send(request.clone())
.expect("capture folder partial request");
let response = if request.starts_with("GET /api/external/v1/editor/projects ") {
serde_json::json!({"data": {"projects": []}})
} else if request.starts_with("POST /api/external/v1/editor/projects ") {
serde_json::json!({"data": {"project": {
"projectId": "folder-partial-project"
}}})
} else if request.starts_with("GET /api/external/v1/editor/assets/library ") {
serde_json::json!({"data": {"library": {"folders": []}}})
} else if request.starts_with("POST /api/external/v1/editor/assets/folders ") {
fs::create_dir_all(&blocked_binding_path)
.expect("block final binding write after folder creation");
serde_json::json!({"data": {"folder": {
"folderId": "folder-partial-folder"
}}})
} else {
panic!("unexpected folder partial request: {request}");
};
let response =
if request.starts_with("GET /api/external/v1/editor/projects?view=summary ") {
serde_json::json!({"data": {"projects": []}})
} else if request.starts_with("POST /api/external/v1/editor/projects ") {
serde_json::json!({"data": {"project": {
"projectId": "folder-partial-project"
}}})
} else if request.starts_with("GET /api/external/v1/editor/assets/library ") {
serde_json::json!({"data": {"library": {"folders": []}}})
} else if request.starts_with("POST /api/external/v1/editor/assets/folders ") {
fs::create_dir_all(&blocked_binding_path)
.expect("block final binding write after folder creation");
serde_json::json!({"data": {"folder": {
"folderId": "folder-partial-folder"
}}})
} else {
panic!("unexpected folder partial request: {request}");
};
write_test_json_response(&mut stream, "200 OK", &response);
}
});
@@ -2,7 +2,8 @@
//!
//! Every caller supplies a safe public summary and a private detail. This
//! module is the only persistence boundary for the latter: it redacts project
//! paths and credentials before writing a bounded diagnostic sidecar.
//! paths and credentials before writing a bounded diagnostic sidecar, and
//! projects the same bounded diagnosis into the AppData application log.
use super::{redact_agent_runtime_error, write_agent_runtime_json_sidecar_with_max_bytes};
use serde::{Deserialize, Serialize};
@@ -14,6 +15,14 @@ use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) const AGENT_RUNTIME_ERROR_SCHEMA_VERSION: &str = "agent-runtime-error.v1";
pub(crate) const AGENT_RUNTIME_ERROR_MAX_DETAIL_CHARS: usize = 8 * 1024;
/// 应用日志里 detail / metadata 的字符预算。
///
/// `application.log` 的每一行在落盘前还会被 `sanitize_diagnostic_message` 截到 2 KiB
/// 这里的预算留出身份字段与中文摘要的位置,保证被截掉的是诊断正文的尾部,而不是
/// `eventId`、`code` 或 `detailRef`。
pub(crate) const AGENT_RUNTIME_ERROR_APP_LOG_DETAIL_CHARS: usize = 1_200;
pub(crate) const AGENT_RUNTIME_ERROR_APP_LOG_METADATA_CHARS: usize = 200;
static ERROR_EVENT_SEQUENCE: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
@@ -71,6 +80,27 @@ pub(crate) fn persist_agent_runtime_error(
"detail": safe_detail,
"metadata": metadata,
});
// 统一错误事件的项目内 sidecar 只在项目目录可见:用户提交错误报告时上传的是 AppData
// 应用日志,诊断包拿不到 detail。这里先把同一份已脱敏诊断留进应用日志,再落项目文件,
// 于是 sidecar 写失败也仍然留下可提交的诊断。
let app_log_lines = agent_runtime_error_app_log_lines(
root,
&event_id,
client_turn_id,
source,
stage,
code,
retryable,
public_text,
recovery_hint,
&detail_ref,
&safe_detail,
elapsed_ms,
&metadata,
);
for line in app_log_lines {
app_log!("{line}");
}
write_agent_runtime_json_sidecar_with_max_bytes(
root,
&detail_ref,
@@ -96,6 +126,65 @@ pub(crate) fn persist_agent_runtime_error(
})
}
/// 把统一错误事件投影成 AppData `diagnostics/application.log` 里的两行。
///
/// 传进来的 `detail` 已经是 sidecar 用的脱敏文本;这里只再按应用日志的预算截一次,
/// 让日志与项目内 sidecar 是同一份诊断,不再单独拼一套字段。
///
/// 拆成「身份行 + 详情行」是因为整行只要出现凭据标记就会被
/// [`crate::sanitize_diagnostic_message`] 整体替换成脱敏占位,详情行可能因此消失;
/// 身份行保持短小且只含摘要与引用,保证事件还能被定位。
///
/// 单行口径在这里落地:`app_log!` 同时把这行写到 stderr,那里没有人替我们压行,
/// 所以每个字段(含 `source` / `stage` / `code` / `detailRef` 这些调用方给的标识)都先
/// 过一遍 [`single_line_log_field`],不假设调用方一定给单行文本。
pub(crate) fn agent_runtime_error_app_log_lines(
root: &Path,
event_id: &str,
client_turn_id: Option<&str>,
source: &str,
stage: &str,
code: &str,
retryable: bool,
public_text: &str,
recovery_hint: &str,
detail_ref: &str,
detail: &str,
elapsed_ms: Option<u64>,
metadata: &Value,
) -> [String; 2] {
let event_id = single_line_log_field(event_id);
let client_turn_id = single_line_log_field(client_turn_id.unwrap_or("none"));
let source = single_line_log_field(source);
let stage = single_line_log_field(stage);
let code = single_line_log_field(code);
let detail_ref = single_line_log_field(detail_ref);
let public_text = single_line_log_field(public_text);
let elapsed_ms = elapsed_ms
.map(|value| value.to_string())
.unwrap_or_else(|| "none".to_string());
let identity = format!(
"agent.runtime.error eventId={event_id} source={source} stage={stage} code={code} retryable={retryable} clientTurnId={client_turn_id} elapsedMs={elapsed_ms} detailRef={detail_ref} summary={public_text}"
);
let detail = redact_agent_runtime_error(root, detail, AGENT_RUNTIME_ERROR_APP_LOG_DETAIL_CHARS);
let metadata = redact_agent_runtime_error(
root,
&metadata.to_string(),
AGENT_RUNTIME_ERROR_APP_LOG_METADATA_CHARS,
);
let detail_line = format!(
"agent.runtime.error.detail eventId={event_id} hint={} detail={} metadata={metadata}",
single_line_log_field(recovery_hint),
single_line_log_field(&detail),
);
[identity, detail_line]
}
/// 应用日志是逐行读取的:落到日志里的自由文本必须先压平换行。
fn single_line_log_field(value: &str) -> String {
value.replace(['\r', '\n'], " ")
}
pub(crate) fn classify_direct_codex_error(error: &str) -> &'static str {
let normalized = error.to_ascii_lowercase();
if normalized.contains("等待 turn/completed 超时") {
@@ -153,6 +242,47 @@ mod tests {
assert!(!text.contains("token=secret"));
}
#[test]
fn error_event_app_log_lines_keep_identity_and_redact_detail() {
let parent = tempfile::tempdir().expect("temp root");
let root = parent.path().join("project");
crate::project::init_local_game_project_at(&root, "runtime-error", "错误事件")
.expect("init project");
let lines = agent_runtime_error_app_log_lines(
&root,
"error-1-1",
Some("turn-123"),
"direct-codex",
"code-generation",
"turn-idle-timeout",
true,
"本轮没有收到完成事件\n附带换行",
"查看诊断后重试",
".agent/runtime/errors/error-1-1.json",
"C:\\Users\\private\\project https://provider.example/a?token=secret\n第二行诊断",
Some(1200),
&serde_json::json!({"authorization": "Bearer secret"}),
);
for line in &lines {
assert!(!line.contains('\n'), "{line}");
}
// 落盘边界按真实口径核验:应用日志的整行脱敏既不能吃掉身份字段,也不能靠换行拆行。
let persisted = crate::sanitize_diagnostic_message(&lines.join(" "), None);
assert!(persisted.contains("eventId=error-1-1"), "{persisted}");
assert!(persisted.contains("code=turn-idle-timeout"), "{persisted}");
assert!(
persisted.contains("detailRef=.agent/runtime/errors/error-1-1.json"),
"{persisted}"
);
assert!(persisted.contains("summary=本轮没有收到完成事件 附带换行"));
assert!(persisted.contains("detail=<absolute-path> <redacted-url> 第二行诊断"));
assert!(
!persisted.contains("token=secret") && !persisted.contains("Bearer secret"),
"{persisted}"
);
assert!(persisted.chars().count() <= 2_048, "{persisted}");
}
#[test]
fn timeout_and_tool_errors_have_distinct_codes() {
assert_eq!(
@@ -290,37 +290,15 @@ fn resolve_at(
let root = root
.canonicalize()
.map_err(|_| "project-root-unavailable")?;
// 候选顺序:既有扁平布局(单架构构建),其后是按**当前运行架构**命名的子目录
// universal 构建把两套运行时并列放进去)。两个候选都要过 manifest 的平台/架构
// 校验,因此顺序不会让另一架构的运行时被采用;存在但校验失败则失败关闭,
// 绝不因此退回系统 Node。
let mut bundle_error: Option<String> = None;
if let Some(base) = bundle {
let candidates = [
base.to_path_buf(),
base.join(format!("{}-{}", native_platform(), native_arch())),
];
for candidate in candidates.iter().filter(|candidate| candidate.exists()) {
match validate_bundle(candidate) {
Ok(()) => {
return runtime_from_paths(
&root,
candidate.join(executable_name()),
candidate.join("node_modules/npm/bin/npm-cli.js"),
"bundled",
path,
);
}
Err(error) => {
if bundle_error.is_none() {
bundle_error = Some(error);
}
}
}
}
}
if let Some(error) = bundle_error {
return Err(error);
if let Some(bundle) = bundle.filter(|bundle| bundle.exists()) {
validate_bundle(bundle)?;
return runtime_from_paths(
&root,
bundle.join(executable_name()),
bundle.join("node_modules/npm/bin/npm-cli.js"),
"bundled",
path,
);
}
if !development {
return Err("node-runtime-bundle-missing".into());
@@ -617,52 +595,6 @@ mod tests {
);
}
/// universal 构建把两套架构运行时并列放在 `<base>/<platform>-<arch>/`
/// 解析必须按当前运行架构选中自己那一份,且另一架构的存在与否不影响结果。
#[test]
fn universal_bundle_resolves_the_directory_matching_the_running_architecture() {
let project = tempfile::tempdir().unwrap();
let bundle = tempfile::tempdir().unwrap();
let current = bundle
.path()
.join(format!("{}-{}", native_platform(), native_arch()));
fs::create_dir_all(&current).unwrap();
bundle_fixture(&current);
let runtime = resolve_at(project.path(), Some(bundle.path()), false, OsStr::new(""))
.expect("universal bundle must resolve the running architecture");
assert_eq!(runtime.source, "bundled");
assert_eq!(
runtime.node.canonicalize().unwrap(),
current.join(executable_name()).canonicalize().unwrap()
);
// 另一架构的目录即使损坏也不能影响本架构选择。
let other = if native_arch() == "arm64" {
"x86_64"
} else {
"arm64"
};
let other_dir = bundle
.path()
.join(format!("{}-{}", native_platform(), other));
fs::create_dir_all(&other_dir).unwrap();
fs::write(other_dir.join("manifest.json"), b"not-json").unwrap();
assert_eq!(
resolve_at(project.path(), Some(bundle.path()), false, OsStr::new(""))
.unwrap()
.node
.canonicalize()
.unwrap(),
current.join(executable_name()).canonicalize().unwrap()
);
// 本架构目录缺失而另一架构完整时,绝不采用另一架构的运行时。
fs::remove_dir_all(&current).unwrap();
bundle_fixture(&other_dir);
assert!(resolve_at(project.path(), Some(bundle.path()), false, OsStr::new("")).is_err());
}
#[test]
fn development_runtime_rejects_relative_and_project_path_entries() {
let root = tempfile::tempdir().unwrap();
@@ -862,11 +862,22 @@ fn resource_edit_state_sha256<T: Serialize>(value: &T, label: &str) -> Result<St
.map_err(|error| format!("序列化{label}身份失败:{error}"))
}
fn ensure_resource_edit_phase_resumable(phase: &ResourceEditLedgerPhase) -> Result<(), String> {
match phase {
ResourceEditLedgerPhase::RemoteFailed => {
Err("remote-terminal-failed: 远端资源编辑已明确失败,不允许再次请求".to_string())
}
/// 只有仍可继续的阶段允许再次请求远端;终态必须在这里失败关闭。
///
/// 终态文案要带出稳定失败码和唯一出口(移出恢复队列):否则用户只会看到一句
/// 「已明确失败」并反复点重试。上游原文不进账本(见 `terminal_failure_code` 的写入边界),
/// 这里只透传分类码,不做二次解释。
fn ensure_resource_edit_phase_resumable(ledger: &ResourceEditLedger) -> Result<(), String> {
match ledger.phase {
ResourceEditLedgerPhase::RemoteFailed => Err(format!(
"remote-terminal-failed: 远端资源编辑已明确失败({}),不允许再次请求;如需重试,请先在待恢复资源编辑中把它移出恢复队列",
ledger
.terminal_failure_code
.as_deref()
.map(str::trim)
.filter(|code| !code.is_empty())
.unwrap_or("remote-failed")
)),
ResourceEditLedgerPhase::Archived => {
Err("resource-edit-archived: 资源编辑已移出恢复队列".to_string())
}
@@ -5122,7 +5133,7 @@ pub(crate) async fn request_resource_edit_service_identity_confirmation_at(
{
return Err("资源编辑服务身份确认对应的 operation 身份无效".to_string());
}
ensure_resource_edit_phase_resumable(&ledger.phase)?;
ensure_resource_edit_phase_resumable(&ledger)?;
let (api_base_url, api_key, platform_session) =
resolve_canvas_sync_api_credentials(None, None)?;
match prepare_resource_edit_service_identity(
@@ -5195,7 +5206,7 @@ fn confirm_resource_edit_service_identity_under_lease(
return Err("资源编辑服务身份确认对应的 operation 身份已变化".to_string());
}
validate_resource_edit_service_identity_owner(&ledger, platform_session)?;
ensure_resource_edit_phase_resumable(&ledger.phase)?;
ensure_resource_edit_phase_resumable(&ledger)?;
let confirmation = ledger
.service_identity_confirmation
.clone()
@@ -5321,7 +5332,7 @@ pub(crate) async fn resume_local_project_resource_edit_at(
{
return Err("待恢复的资源编辑账本身份无效".to_string());
}
ensure_resource_edit_phase_resumable(&ledger.phase)?;
ensure_resource_edit_phase_resumable(&ledger)?;
let source_asset = ledger
.source_asset_id
.as_deref()
@@ -5552,7 +5563,7 @@ pub(crate) async fn derive_local_project_resource_at(
{
return Err("operationId 或幂等键已绑定到不同资源编辑请求".to_string());
}
ensure_resource_edit_phase_resumable(&ledger.phase)?;
ensure_resource_edit_phase_resumable(&ledger)?;
ledger
}
None => {
@@ -6157,8 +6168,8 @@ mod tests {
let request = read_http_request(&mut stream);
let request_line = request.lines().next().unwrap_or_default();
requests.push(request.clone());
if request_line.starts_with("GET /api/external/v1/editor/projects ")
|| request_line.starts_with("GET /api/editor/projects ")
if request_line.starts_with("GET /api/external/v1/editor/projects?view=summary ")
|| request_line.starts_with("GET /api/editor/projects?view=summary ")
{
write_json(
&mut stream,
@@ -6686,7 +6697,9 @@ mod tests {
let request = read_http_request(&mut stream);
sender.send(request.clone()).expect("capture B request");
let request_line = request.lines().next().unwrap_or_default();
if request_line.starts_with("GET /api/external/v1/editor/projects ") {
if request_line
.starts_with("GET /api/external/v1/editor/projects?view=summary ")
{
write_json(
&mut stream,
"200 OK",
@@ -7186,7 +7199,7 @@ mod tests {
);
assert!(requests.iter().all(|request| {
let line = request.lines().next().unwrap_or_default();
line.starts_with("GET /api/external/v1/editor/projects ")
line.starts_with("GET /api/external/v1/editor/projects?view=summary ")
|| line.starts_with("GET /api/external/v1/editor/assets/library ")
}));
}
@@ -9293,7 +9306,7 @@ mod tests {
.expect("capture External video request");
let request_line = request.lines().next().unwrap_or_default();
let request_lower = request.to_ascii_lowercase();
if request_line.starts_with("GET /api/external/v1/editor/projects ") {
if request_line.starts_with("GET /api/external/v1/editor/projects?view=summary ") {
write_json(
&mut stream,
"200 OK",
@@ -391,8 +391,8 @@ fn assert_developer_submission(request: &str) {
fn respond_canvas_context_request(stream: &mut TcpStream, request: &str) -> bool {
let line = request.lines().next().unwrap_or_default();
if line.starts_with("GET /api/external/v1/editor/projects ")
|| line.starts_with("GET /api/editor/projects ")
if line.starts_with("GET /api/external/v1/editor/projects?view=summary ")
|| line.starts_with("GET /api/editor/projects?view=summary ")
{
write_json(
stream,
@@ -938,6 +938,24 @@ pub(crate) fn create_project_from_installed_template_at(
enforce_project_permission_policy(&project_root, "project.create")?;
let _lock = acquire_project_write_lock(&project_root, "project.create")?;
copy_template_project(installed_project_dir, &project_root)?;
if discover_local_cocos_project_root(&project_root)?.is_some() {
let package_path = project_root.join("package.json");
let mut package: serde_json::Value = serde_json::from_slice(
&fs::read(&package_path)
.map_err(|error| format!("读取 Cocos 项目配置失败:{error}"))?,
)
.map_err(|error| format!("解析 Cocos 项目配置失败:{error}"))?;
package["name"] = serde_json::json!(project_name);
package["uuid"] = serde_json::json!(uuid::Uuid::new_v4().to_string());
let bytes = serde_json::to_vec_pretty(&package)
.map_err(|error| format!("序列化 Cocos 项目配置失败:{error}"))?;
write_game_creator_private_file(&package_path, &bytes, "Cocos 项目配置")?;
return import_local_cocos_project_at(
&project_root,
&format!("gameagent-{workspace_id}"),
&project_name,
);
}
init_local_game_project_at(
&project_root,
&format!("gameagent-{workspace_id}"),
@@ -1182,6 +1200,39 @@ mod tests {
assert!(error.contains("重复模板"), "{error}");
}
#[test]
fn parses_content_addressed_objects_without_changing_the_template_contract() {
let mut index: serde_json::Value =
serde_json::from_str(&sample_index_body()).expect("sample index");
let keys = [
("zipKey", "template.zip", "a"),
("coverKey", "cover.png", "b"),
("metadataKey", "template.json", "c"),
]
.map(|(field, file, hash)| {
(
field,
format!(
"templates/v1/demo-template/sha256/{}/{file}",
hash.repeat(64)
),
)
});
for (field, key) in &keys {
index["templates"][0][field] = serde_json::json!(key);
}
let (_, templates) =
parse_game_template_library_index(&index.to_string()).expect("content addressed index");
let parsed = serde_json::to_value(&templates[0]).expect("serialize template");
for (field, key) in &keys {
assert_eq!(parsed[field], *key);
assert!(template_object_url(key)
.expect("trusted URL")
.ends_with(key));
}
assert_eq!(templates[0].template_version, "1.0.0");
}
#[test]
fn rejects_object_keys_outside_the_templates_prefix() {
assert!(validate_template_object_key("agc/templates/v1/demo/template.zip").is_err());
@@ -1225,6 +1276,10 @@ mod tests {
"blank-2d-canvas",
"blank-3d-scene",
"blank-web",
"cocos-empty-2d",
"cocos-empty-3d",
"cocos-empty-3d-hq",
"cocos-hello-world",
"phaser-2d-starter",
"threejs-3d-starter",
]
@@ -1360,6 +1415,142 @@ mod tests {
assert!(error.contains("模板尚未安装"), "{error}");
}
fn template_source_files(root: &Path) -> Vec<(String, Vec<u8>)> {
fn collect(root: &Path, directory: &Path, files: &mut Vec<(String, Vec<u8>)>) {
for entry in fs::read_dir(directory).expect("read template directory") {
let path = entry.expect("template entry").path();
if path.is_dir() {
collect(root, &path, files);
} else {
files.push((
path.strip_prefix(root)
.expect("relative path")
.to_string_lossy()
.replace('\\', "/"),
fs::read(&path).expect("read template file"),
));
}
}
}
let mut files = Vec::new();
collect(root, root, &mut files);
files.sort_by(|left, right| left.0.cmp(&right.0));
files
}
fn assert_cocos_template_creates_independent_projects(
summary: &GameTemplateSummary,
archive: &[u8],
) {
let cache_root = tempfile::tempdir().expect("cache directory");
let projects_root = unique_projects_root();
let record = install_template_archive(cache_root.path(), summary, archive)
.expect("install Cocos template");
let installed_root = Path::new(&record.project_dir);
let installed_files = template_source_files(installed_root);
let original_package: serde_json::Value = serde_json::from_slice(
&fs::read(installed_root.join("package.json")).expect("installed package"),
)
.expect("parse installed package");
let mut project_uuids = std::collections::HashSet::new();
for name in ["Cocos 模板项目一", "Cocos 模板项目二"] {
let created = create_project_from_installed_template_at(
&projects_root,
installed_root,
Some(name),
false,
)
.expect("create Cocos project from template");
let root = Path::new(&created.project_path);
assert_eq!(created.manifest.name, name);
assert_eq!(created.manifest.cocos_project_root.as_deref(), Some("."));
assert!(created.manifest.godot_project_root.is_none());
assert!(root.join(".agent/manifest.json").is_file());
assert!(root.join(".agent/agent.db").is_file());
for unexpected in ["game", "memory", "exports", TEMPLATE_INSTALLED_MARKER_FILE] {
assert!(!root.join(unexpected).exists(), "unexpected {unexpected}");
}
let package: serde_json::Value = serde_json::from_slice(
&fs::read(root.join("package.json")).expect("created package"),
)
.expect("parse created package");
assert_eq!(package["name"], name);
assert_eq!(package["creator"]["version"], "3.8.8");
let uuid = package["uuid"].as_str().expect("project uuid");
uuid::Uuid::parse_str(uuid).expect("valid project uuid");
assert_ne!(package["uuid"], original_package["uuid"]);
assert!(project_uuids.insert(uuid.to_string()));
for (relative, bytes) in &installed_files {
if relative != "package.json" && relative != TEMPLATE_INSTALLED_MARKER_FILE {
assert_eq!(&fs::read(root.join(relative)).expect("copied file"), bytes);
}
}
}
assert_eq!(template_source_files(installed_root), installed_files);
fs::remove_dir_all(&projects_root).expect("remove test projects");
}
#[test]
fn installs_official_cocos_templates_and_creates_native_projects() {
let library = Path::new(env!("CARGO_MANIFEST_DIR")).join("../template-library/v1");
for id in [
"cocos-empty-2d",
"cocos-empty-3d",
"cocos-empty-3d-hq",
"cocos-hello-world",
] {
let source = library.join(id).join("project");
let source_files = template_source_files(&source);
let entries = source_files
.iter()
.map(|(path, bytes)| (path.as_str(), bytes.as_slice()))
.collect::<Vec<_>>();
let archive = build_archive(&entries);
let mut summary = sample_summary();
summary.id = id.to_string();
summary.zip_size_bytes = archive.len() as u64;
summary.zip_sha256 = sha256_hex(&archive);
assert_cocos_template_creates_independent_projects(&summary, &archive);
assert_eq!(template_source_files(&source), source_files);
}
}
#[tokio::test]
#[ignore = "需要网络:下载线上 Cocos 模板并验证原生建项"]
async fn downloads_and_creates_live_cocos_templates() {
let base = template_library_base().expect("trusted base");
let client = build_template_library_client();
let body = fetch_limited_bytes(
&client,
&format!("{base}/{TEMPLATE_LIBRARY_INDEX_KEY}"),
TEMPLATE_LIBRARY_MAX_INDEX_BYTES,
)
.await
.expect("fetch live index");
let (_, templates) =
parse_game_template_library_index(&String::from_utf8(body).expect("utf-8 index"))
.expect("parse live index");
for id in [
"cocos-empty-2d",
"cocos-empty-3d",
"cocos-empty-3d-hq",
"cocos-hello-world",
] {
let summary = templates.iter().find(|entry| entry.id == id).expect(id);
assert_eq!(summary.runtime, "cocos");
assert_eq!(summary.engine_version, "3.8.8");
assert_eq!(summary.entry, "package.json");
let bytes = fetch_limited_bytes(
&client,
&template_object_url(&summary.zip_key).expect("trusted zip url"),
TEMPLATE_ARCHIVE_MAX_BYTES,
)
.await
.expect("download Cocos template");
assert_cocos_template_creates_independent_projects(summary, &bytes);
}
}
/// 正式构建(未开 feature)必须恒等透传:注入路径不能出现在默认产物里。
#[cfg(not(feature = "template-library-fixtures"))]
#[test]
@@ -3337,8 +3337,8 @@ fn spawn_mock_external_canvas_api_server_with_capture_and_generation_gate(
}
let normalized_request = request.to_ascii_lowercase();
let (status, content_type, body) = if request
.starts_with("GET /api/external/v1/editor/projects ")
|| request.starts_with("GET /api/editor/projects ")
.starts_with("GET /api/external/v1/editor/projects?view=summary ")
|| request.starts_with("GET /api/editor/projects?view=summary ")
{
assert!(normalized_request.contains("authorization: bearer "));
("200 OK", "application/json", projects_body.as_bytes().to_vec())
@@ -3564,8 +3564,8 @@ fn spawn_mock_external_canvas_generation_failure_server() -> String {
let (status, body) = match index {
0 => {
assert!(
request.starts_with("GET /api/external/v1/editor/projects ")
|| request.starts_with("GET /api/editor/projects ")
request.starts_with("GET /api/external/v1/editor/projects?view=summary ")
|| request.starts_with("GET /api/editor/projects?view=summary ")
);
(
"200 OK",
@@ -2,18 +2,13 @@
"schemaVersion": "agc-template-library.v1",
"library": "agc-game-templates",
"libraryVersion": 1,
"updatedAt": "2026-09-17T03:22:43Z",
"updatedAt": "2026-09-17T13:55:10Z",
"templates": [
{
"id": "blank-2d-canvas",
"title": "空白二维画布工程",
"summary": "原生 Canvas 二维空白工程:自适应画布、按设备像素比缩放与 requestAnimationFrame 主循环已就绪。",
"tags": [
"空白",
"起步工程",
"2d",
"canvas"
],
"tags": ["空白", "起步工程", "2d", "canvas"],
"runtime": "html",
"engine": "canvas",
"engineVersion": "",
@@ -33,12 +28,7 @@
"id": "blank-3d-scene",
"title": "空白三维场景工程",
"summary": "Three.js 空白场景:空场景、透视相机、网格地面与自适应视口已就绪,适合从零搭三维玩法。",
"tags": [
"空白",
"起步工程",
"3d",
"three.js"
],
"tags": ["空白", "起步工程", "3d", "three.js"],
"runtime": "html",
"engine": "three.js",
"engineVersion": "0.180.0",
@@ -58,12 +48,7 @@
"id": "blank-web",
"title": "空白网页工程",
"summary": "最小网页工程(HTML + CSS + 原生 JS + Vite),没有任何引擎依赖,适合从零写玩法。",
"tags": [
"空白",
"起步工程",
"网页",
"原生"
],
"tags": ["空白", "起步工程", "网页", "原生"],
"runtime": "html",
"engine": "none",
"engineVersion": "",
@@ -79,16 +64,91 @@
"coverSha256": "326a2753386618971b1311043effa46c2e74bc1cfb116862c0ee4097dcd5086a",
"metadataKey": "templates/v1/blank-web/template.json"
},
{
"id": "cocos-empty-2d",
"title": "Cocos 空白 2D 工程",
"summary": "官方二维空白模板,保留精灵导入默认值与二维编辑视图。",
"tags": ["空白", "起步工程", "2d", "cocos"],
"runtime": "cocos",
"engine": "cocos-creator",
"engineVersion": "3.8.8",
"templateVersion": "0.1.0",
"updatedAt": "2026-09-17T13:55:10Z",
"entry": "package.json",
"zipKey": "templates/v1/cocos-empty-2d/template.zip",
"zipSizeBytes": 1976,
"zipSha256": "e30bd6324fd2eb721c9a9fdcc9d8bb9838fba7b3413d09a890d3152c3576c485",
"coverKey": "templates/v1/cocos-empty-2d/cover.svg",
"coverWidth": 960,
"coverHeight": 540,
"coverSha256": "4ca21e32e890e8a3d20bde2b9f1228993cbd770532c496433de0e5ffecc31342",
"metadataKey": "templates/v1/cocos-empty-2d/template.json"
},
{
"id": "cocos-empty-3d",
"title": "Cocos 空白 3D 工程",
"summary": "官方三维空白模板,适合从零搭建 Cocos 场景与玩法。",
"tags": ["空白", "起步工程", "3d", "cocos"],
"runtime": "cocos",
"engine": "cocos-creator",
"engineVersion": "3.8.8",
"templateVersion": "0.1.0",
"updatedAt": "2026-09-17T13:55:10Z",
"entry": "package.json",
"zipKey": "templates/v1/cocos-empty-3d/template.zip",
"zipSizeBytes": 829,
"zipSha256": "e4016ed9bcd3d3b09d5d06e776c2cf4d98415473b3747bc4945e06e93967117a",
"coverKey": "templates/v1/cocos-empty-3d/cover.svg",
"coverWidth": 960,
"coverHeight": 540,
"coverSha256": "88111f77f6801a77acc05277dc2698378ce9eeb8e9265b7d2dedafde0d893aae",
"metadataKey": "templates/v1/cocos-empty-3d/template.json"
},
{
"id": "cocos-empty-3d-hq",
"title": "Cocos 高质量 3D 工程",
"summary": "官方高质量三维空白模板,保留天空盒、阴影与线性纹理采样预设。",
"tags": ["空白", "起步工程", "3d", "cocos"],
"runtime": "cocos",
"engine": "cocos-creator",
"engineVersion": "3.8.8",
"templateVersion": "0.1.0",
"updatedAt": "2026-09-17T13:55:10Z",
"entry": "package.json",
"zipKey": "templates/v1/cocos-empty-3d-hq/template.zip",
"zipSizeBytes": 1226,
"zipSha256": "4b4f12a7dd39be31bc471c7387b272717e9476b1a6eafb21273ce1a3ebc38384",
"coverKey": "templates/v1/cocos-empty-3d-hq/cover.svg",
"coverWidth": 960,
"coverHeight": 540,
"coverSha256": "276752f234c1209c182ca79b65d97c1d52d9e22b60be9aaee6cb0b134ab666ea",
"metadataKey": "templates/v1/cocos-empty-3d-hq/template.json"
},
{
"id": "cocos-hello-world",
"title": "Cocos Hello World",
"summary": "官方三维示例场景,包含岛屿、角色、植被、材质与天空盒资源。",
"tags": ["示例", "起步工程", "3d", "cocos"],
"runtime": "cocos",
"engine": "cocos-creator",
"engineVersion": "3.8.8",
"templateVersion": "0.1.0",
"updatedAt": "2026-09-17T13:55:10Z",
"entry": "package.json",
"zipKey": "templates/v1/cocos-hello-world/template.zip",
"zipSizeBytes": 2484948,
"zipSha256": "dac8cc2eae2ec9ff3cd429a1be2c2981b06919be720bfa50226619c0a56e00da",
"coverKey": "templates/v1/cocos-hello-world/cover.svg",
"coverWidth": 960,
"coverHeight": 540,
"coverSha256": "9363b728a792835f57d22d129c598449801d343f739e85159e83e531ba7d949c",
"metadataKey": "templates/v1/cocos-hello-world/template.json"
},
{
"id": "phaser-2d-starter",
"title": "Phaser 2D 起步工程",
"summary": "AGC 新建项目使用的默认二维起步工程(Phaser 4 + Vite),解压后即为可运行项目根。",
"tags": [
"起步工程",
"2d",
"phaser",
"像素"
],
"tags": ["起步工程", "2d", "phaser", "像素"],
"runtime": "html",
"engine": "phaser",
"engineVersion": "4.2.1",
@@ -108,12 +168,7 @@
"id": "threejs-3d-starter",
"title": "Three.js 3D 起步工程",
"summary": "网页三维起步工程(Three.js + Vite),自带可旋转立方体场景、方向光与自适应视口。",
"tags": [
"起步工程",
"3d",
"three.js",
"网页"
],
"tags": ["起步工程", "3d", "three.js", "网页"],
"runtime": "html",
"engine": "three.js",
"engineVersion": "0.180.0",

Some files were not shown because too many files have changed in this diff Show More