Compare commits

..

64 Commits

Author SHA1 Message Date
k88936 23819d699c 补充DirectProject Skill提及输入规范
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Failing after 1m47s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Failing after 2m5s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Failing after 2m11s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Failing after 2m10s
Project CI / Backend tests (pull_request) Failing after 10s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 2m13s
Project CI / Repository checks (pull_request) Failing after 10s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 3m24s
Project CI / AI game creator shell web tests (pull_request) Failing after 3m54s
Project CI / Frontend tests (pull_request) Failing after 4m32s
Project CI / Native shell tests (pull_request) Successful in 8m0s
更新聊天输入主规范并增加 Skill 提及边界

新增 Skill 提及里程碑与小切片实施计划
2026-09-15 16:46:40 +08:00
k88936 17716347e2 收紧历史测试与注释口径
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Failing after 2m17s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Failing after 2m7s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 2m7s
Project CI / Backend tests (pull_request) Failing after 19s
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Failing after 2m19s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Failing after 2m17s
Project CI / Repository checks (pull_request) Failing after 11s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 2m26s
Project CI / AI game creator shell web tests (pull_request) Failing after 3m43s
Project CI / Frontend tests (pull_request) Failing after 4m6s
Project CI / Native shell tests (pull_request) Successful in 7m29s
移除 legacy 投影描述

将历史测试统一为 Response item 合同
2026-09-15 16:16:03 +08:00
k88936 9ad66a67a3 接入前端 canonical 用户 Response item
按 Lexical 顺序构造 message.content

DirectProject payload 改为发送 userItem

策略重试保留同一 canonical item
2026-09-15 16:12:56 +08:00
k88936 ba3aa3ccdb 更新用户 Response item 里程碑进度
标记 canonical、wire 与失败关闭验收项

同步实施计划为进行中状态
2026-09-15 16:09:28 +08:00
k88936 2b38eaafba 补充前端用户 Response item 契约测试
覆盖 Lexical 文本与引用交错顺序

验证资源引用只发送稳定 resourceId
2026-09-15 16:08:34 +08:00
k88936 7d5b9071e7 删除旧 DirectProject 引用协议
移除 DirectCodexTurnReference 平行 DTO 与渲染路径

将引用数量上限收回 canonical user item 校验模块
2026-09-15 16:01:45 +08:00
k88936 9e83f1d88c 补齐 Response item 严格合同测试
拒绝资源引用额外身份字段与未知 content part

补充历史 item wire 投影边界测试

同步 DirectProject 历史文档为无 fallback 合同
2026-09-15 15:55:15 +08:00
k88936 7e35d7c344 严格使用 DirectProject Response item 历史
移除 game-creator-conversation.v1 读取 fallback

历史注入前逐项投影 canonical user item 为 Codex message

无效 item 在持久化前失败关闭
2026-09-15 15:42:27 +08:00
k88936 5ec40c8b83 抽离 DirectProject 身份解析模块
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Failing after 2m16s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Failing after 2m20s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Failing after 2m4s
Project CI / Backend tests (pull_request) Failing after 18s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Failing after 1m54s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 2m22s
Project CI / Repository checks (pull_request) Failing after 9s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 3m20s
Project CI / AI game creator shell web tests (pull_request) Successful in 2m36s
Project CI / Frontend tests (pull_request) Successful in 3m45s
Project CI / Native shell tests (pull_request) Successful in 5m27s
将项目 canonical identity 与 digest 放入独立文件

保持 Codex app-server 线程池调用接口不变
2026-09-15 15:22:39 +08:00
k88936 948a80fc49 重构 DirectProject Agent 深模块
将 direct_runtime 与 codex_app_server 改为目录模块

拆分 user item 的模型、校验与 wire 投影文件

抽离 DirectProject 历史注入载荷构造 seam
2026-09-15 15:19:17 +08:00
k88936 dfd6fadedf 新增 DirectProject 用户 Response item 契约
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Successful in 4m35s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Successful in 4m34s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 1m36s
Project CI / Backend tests (pull_request) Failing after 10s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Successful in 4m31s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Successful in 4m46s
Project CI / Repository checks (pull_request) Failing after 10s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 3m32s
Project CI / Frontend tests (pull_request) Successful in 4m0s
Project CI / AI game creator shell web tests (pull_request) Successful in 3m34s
Project CI / Native shell tests (pull_request) Successful in 6m35s
新增 Rust canonical user item 与 Codex wire 转换模块

增加 ts-rs 绑定目录及生成文件检查边界

更新聊天素材引用规范与里程碑实施计划
2026-09-15 14:45:58 +08:00
lhk229 9aa6f5efea 解决platform-llm和策划agent reasoning问题,并修复若干bug (#350)
Project CI / AI game creator shell Rust shard 1/4 (push) Successful in 4m44s
Project CI / AI game creator shell Rust shard 2/4 (push) Successful in 5m9s
Project CI / AI game creator shell Rust shard 3/4 (push) Successful in 4m33s
Project CI / AI game creator shell Rust smoke (push) Successful in 1m50s
Project CI / AI game creator shell Rust shard 4/4 (push) Successful in 3m53s
Project CI / AI game creator shell Rust crates (push) Successful in 2m51s
Project CI / Frontend tests (push) Successful in 4m58s
Project CI / Repository checks (push) Successful in 3m18s
Project CI / Native shell tests (push) Successful in 6m10s
Project CI / Backend tests (push) Successful in 7m7s
Project CI / AI game creator shell web tests (push) Successful in 2m16s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 4/4 (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 / Frontend tests (pull_request) Has been cancelled
Project CI / Repository checks (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 shard 1/4 (pull_request) Has been cancelled
Reviewed-on: #350
2026-09-15 00:50:36 +08:00
suzmii 0ced0c2564 Merge pull request 'AGC 资源工作台三处交互收口:侧栏关闭入口合并、删除折叠把手、播放左对齐' (#361) from fix/agc-resource-workbench-chrome into master
Project CI / AI game creator shell Rust shard 3/4 (push) Successful in 5m37s
Project CI / AI game creator shell Rust shard 2/4 (push) Successful in 5m40s
Project CI / AI game creator shell Rust shard 1/4 (push) Successful in 5m43s
Project CI / AI game creator shell Rust shard 4/4 (push) Successful in 5m49s
Project CI / AI game creator shell Rust smoke (push) Successful in 1m41s
Project CI / AI game creator shell Rust crates (push) Successful in 2m22s
Project CI / Repository checks (push) Successful in 3m48s
Project CI / Frontend tests (push) Successful in 4m41s
Project CI / Native shell tests (push) Successful in 6m31s
Project CI / Backend tests (push) Successful in 7m26s
Project CI / AI game creator shell web tests (push) Successful in 2m58s
Reviewed-on: #361
2026-09-15 00:44:02 +08:00
suzmii 0aa6dfe994 修复两个 CSS 文件末尾多出的空行(CI git diff --check 报 new blank line at EOF)
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Successful in 5m21s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Successful in 5m26s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Successful in 5m9s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Successful in 5m16s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 2m1s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 3m21s
Project CI / Frontend tests (pull_request) Failing after 3m36s
Project CI / Native shell tests (pull_request) Successful in 7m39s
Project CI / AI game creator shell web tests (pull_request) Successful in 3m1s
Project CI / Backend tests (pull_request) Successful in 12m59s
Project CI / Repository checks (pull_request) Successful in 18m21s
- resourceCanvasAssetGenerationTasksSidebar.css:文件末尾由 ``}\n\n\n`` 收敛为 ``}\n``,与 origin/master 的结尾字节一致
- styles.css:同上(此前由编辑工具补写整文件时多留了两个空行)
- 两处都只删结尾空白,文件内容与行尾风格(LF)不变
2026-09-15 00:02:57 +08:00
suzmii 40e2a1b9b1 AGC 资源工作台工具条:把布局状态提示移出动作行,按钮间距不再随提示文案变长而变化
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Successful in 4m41s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Successful in 4m22s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 2m2s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Successful in 4m25s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Successful in 4m36s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 2m34s
Project CI / Repository checks (pull_request) Failing after 3m33s
Project CI / Frontend tests (pull_request) Successful in 6m19s
Project CI / Native shell tests (pull_request) Successful in 7m26s
Project CI / Backend tests (pull_request) Has been cancelled
Project CI / AI game creator shell web tests (pull_request) Has been cancelled
- 根因(按真机截图逐像素量出来的):动作行 `game-workbench-view-actions` 里除了按钮还挂着 `game-resource-reorder-status` 这个 `role="status"` 提示,它是 flex 子项、`white-space: nowrap`,文案从空 →「保存中」→「布局已保存」→ 失败原因会越变越长,于是把右侧按钮按文本宽度顶开:同一份截图里「资源面板→生成素材」「生成素材→整理画布」的空隙是 64/66px,而「整理画布→生成任务」是 80px,差值正是这条提示当时的宽度(10px × 8 字符 ≈ 16px)
- 修法:把它从动作行里搬出来,改成工具条内的绝对定位(`bottom: 4px; left: 12px`,`max-width` + 省略号兜底),不再参与行内排版;四枚动作按钮的内容宽度实测都是 132~134px,间距因此只剩一套
- 保留上一笔的分段控件 `margin-left: 17px`:它解决的是另一半——分段控件内部 0 间距导致它与前一按钮只隔 10px,而其余按钮之间是 24px
- 用例:新增「布局状态提示不参与动作行排版,不会按文案宽度顶开按钮」,钉住 `position: absolute` 与锚点;既有「布局已保存」文本断言(按文本查,不依赖它在哪个容器)不受影响
- 文档:AGC 入口矩阵补「工具条动作行的间距只有一套」口径,写清提示为什么不进这一行

验证:tsc --noEmit 通过;appSurface 全量 441 条通过;侧栏开合与入口 5 条、画布手动布局 9 条通过;变异验证:把提示改回 `position: static`,新用例变红
2026-09-14 23:33:32 +08:00
suzmii e272492f25 AGC 资源工作台工具条:统一行内间距,「依赖 / 类型」不再与前一按钮贴得过近
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Successful in 4m53s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Successful in 4m42s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Successful in 4m29s
Project CI / Native shell tests (pull_request) Has been cancelled
Project CI / Frontend tests (pull_request) Has been cancelled
Project CI / Repository checks (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 crates (pull_request) Has been cancelled
Project CI / AI game creator shell Rust smoke (pull_request) Has been cancelled
Project CI / Backend tests (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Has been cancelled
- 现象:工具条动作行里「资源面板 / 生成素材 / 整理画布 / 生成任务」之间是 gap 7px + 两侧 padding 11px = 视觉 24px,而「整理画布 → 生成任务 → 依赖」这一段只有 gap 7px + 分段控件自带 padding 3px = 10~13px,一行里两套间距;截图量出来的词间距是 64/65/65px,换算后正好差在这一段落上
- 根因:`.game-workbench-tabs.game-resource-sort-tabs` 把分段控件的 `padding: 3px` 归零后,它和同容器兄弟之间就只剩行本身的 7px gap,而其余按钮靠自身左右 padding 各撑出 11px
- 修法:给分段控件补 `margin-left: 17px`(7 + 17 = 24px),整行只剩一套间距;分段控件内部仍是 0 间距的连通分段(依赖 / 类型 共享边界不变),高度 36px 与其余按钮对齐的既有口径不变
- 用例:`resourceCanvasGenerationTasksSidebarDismiss.test.tsx` 新增「依赖 / 类型 与前一按钮之间的间距跟行内其他按钮一致」,钉住 `margin-left: 17px` 与 `padding: 0` 两条声明

验证:tsc --noEmit 通过;appSurface 全量 441 条通过;侧栏开合与入口 4 条、画布手动布局 9 条通过;变异验证:把 `margin-left` 改回 0,新用例变红
2026-09-14 23:25:46 +08:00
suzmii 38928167f4 Merge branch 'master' into fix/agc-resource-workbench-chrome
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Successful in 5m13s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Successful in 5m33s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Successful in 5m35s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Successful in 5m41s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 1m52s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 3m3s
Project CI / Frontend tests (pull_request) Successful in 5m34s
Project CI / Repository checks (pull_request) Failing after 4m36s
Project CI / Backend tests (pull_request) Successful in 7m57s
Project CI / Native shell tests (pull_request) Successful in 8m11s
Project CI / AI game creator shell web tests (pull_request) Successful in 5m5s
2026-09-14 23:11:57 +08:00
suzmii d0b15dbc54 AGC 生成任务侧栏:收起也补上退场动画,退场期间内容不跳
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Failing after 2m52s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Failing after 2m58s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Failing after 2m59s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Failing after 3m2s
Project CI / AI game creator shell Rust smoke (pull_request) Failing after 1m40s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 3m2s
Project CI / Native shell tests (pull_request) Failing after 6m29s
Project CI / Repository checks (pull_request) Failing after 4m3s
Project CI / Backend tests (pull_request) Successful in 9m6s
Project CI / AI game creator shell web tests (pull_request) Successful in 3m13s
Project CI / Frontend tests (pull_request) Has been cancelled
- 进场本来就有动画(`…-enter`),收起却是瞬间卸载,观感上"闪一下没了"。现在收起先播退场再卸载:`open` 变 false 后进入 `leaving`,根节点挂 `is-leaving` 播 `…-leave`(与进场同向反向,160ms,`pointer-events: none`),播完才卸载
- 时长在组件与 CSS 两处各写一次,组件导出 `RESOURCE_CANVAS_ASSET_GENERATION_TASKS_LEAVE_MILLIS` 并由用例钉住两处一致
- 减动效偏好下 CSS 已关掉动画,组件那边同步按 0ms 处理,收起立即卸载,不白等 160ms
- 退场期间沿用收起前那一份列表(`lastRenderedRef`):宿主会在同一帧里收起侧栏并把在途任务收口,直接吃新 props 会让退场动画里的内容跳一下;滚动区的空态分支也改读这份冻结快照,不能读实时 `ordered`(这是本批调试时用假时钟用例抓到的真问题)
- 用例:面板用例新增「收起时先播完收起动画再卸载,动画期间列表内容不跳」;样式用例新增「is-leaving 挂上收起动画、pointer-events: none、减动效同样关掉」;既有生成任务相关性用例改为等退场动画走完再断言(新增 `waitForTasksSidebarLeaveAnimationToFinish`)
- 文档:AGC 入口矩阵与 decision-log 同步退场动画口径

验证:tsc --noEmit 通过;appSurface 全量 441 条通过;侧栏面板 9 条、样式 10 条、开合与入口 3 条通过;变异验证:把早返回改回「立即卸载」与把 CSS 的 `is-leaving` 选择器写错,对应断言分别变红
2026-09-14 23:01:35 +08:00
suzmii 96971403ee AGC 资源画布:定位到素材后把视口居中到该卡
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Failing after 2m38s
Project CI / AI game creator shell Rust smoke (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 3/4 (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 / Frontend tests (pull_request) Has been cancelled
Project CI / Repository checks (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 shard 4/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Has been cancelled
- 根因:`handleResourceSelect` 只改选中、不移动画布,而这张画布是 transform 平移的、资源卡不在任何滚动容器里;既有的 `card.scrollIntoView()` 碰不到滚动祖先,卡在视口外时用户看到的就是「定位过去了但依然见不到素材」
- 新增 `centerResourceCanvasOnResource`:读该卡在当前布局位置表里的 x/y 与卡片尺寸,按 `canvasSize / 2 − 卡中心 × scale` 求视口平移量;缩放保持不变(定位不改用户缩放预期,与 `ensureResourceBookContentVisible` 同口径)
- 聚焦链在「选中新资源」那一步之后调用它;`scrollIntoView` 保留(栏目页仍有带滚动条的祖先)
- 用例:新增「centers the canvas viewport on the located asset so it is actually visible」,用渲染进 DOM 的真实画布尺寸断言 `viewportX + 卡中心 × scale = 画布中心`
- 文档:decision-log 补「失去焦点即收起」与「定位必须让素材真的可见」两条决策;AGC 入口矩阵同步自动收起、入口顺序与定位居中口径

验证:tsc --noEmit 通过;appSurface 全量 441 条通过;变异验证:把定位链里的居中调用摘掉,新用例变红(450 vs 400,正好是画布宽 800 的一半与旧视口之差)
2026-09-14 22:36:32 +08:00
lhk229 a439b2cb34 修复 Linux CI 缺少策略路径归一化实现
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Successful in 5m11s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Successful in 5m15s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Successful in 5m21s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Successful in 5m7s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 1m47s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 2m25s
Project CI / Repository checks (pull_request) Successful in 3m34s
Project CI / Frontend tests (pull_request) Successful in 4m25s
Project CI / Native shell tests (pull_request) Successful in 6m6s
Project CI / Backend tests (pull_request) Successful in 7m5s
Project CI / AI game creator shell web tests (pull_request) Successful in 2m45s
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
Project CI / AI game creator shell Rust shard 4/4 (push) Has been cancelled
Project CI / AI game creator shell Rust shard 1/4 (push) Has been cancelled
Project CI / AI game creator shell Rust shard 2/4 (push) Has been cancelled
Project CI / AI game creator shell Rust shard 3/4 (push) Has been cancelled
为非 Windows 平台补充 normalize_windows_policy_path 恒等实现,修复 Linux Rust 编译失败。
2026-09-14 22:35:56 +08:00
suzmii 45ccc58969 AGC 生成任务侧栏:失去焦点自动收起、入口挪到排列方式之前
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Failing after 2m4s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Failing after 1m53s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Failing after 2m2s
Project CI / AI game creator shell Rust smoke (pull_request) Failing after 1m32s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Failing after 1m58s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 1m56s
Project CI / Repository checks (pull_request) Successful in 3m45s
Project CI / Frontend tests (pull_request) Successful in 4m12s
Project CI / Native shell tests (pull_request) Failing after 4m48s
Project CI / Backend tests (pull_request) Successful in 7m7s
Project CI / AI game creator shell web tests (pull_request) Successful in 3m17s
- 侧栏展开时挂 document 级 pointerdown 捕获监听:点在侧栏内部与工具条那枚开合按钮以外的地方(画布、其他工具条按钮、对话框)即自动收起侧栏
- 排除开合按钮本身:它自己负责 toggle,若在「点外部」里也命中会先收起再被 toggle 打开,表现为按钮失灵
- 工具条「生成任务」入口加 data-resource-generation-task-toggle 标记,供上面的判定排除
- 「生成任务」入口从资源排列方式之后挪到之前:动作在前、排列方式(依赖 / 类型)收在行尾;入口抽成可复用元素,资源页签与运行页签各渲染一次,同一时刻只渲染一处
- 新增 tests/resourceCanvasGenerationTasksSidebarDismiss.test.tsx:点外部收起、点内部与开合按钮不收起且仍能 toggle、入口排在依赖/类型之前

验证:tsc --noEmit 通过;vitest(新用例 3 条 + 生成任务侧栏 8 条 + 侧栏样式 9 条 + 画布手动布局 9 条)通过;变异验证:关掉自动收起 effect 与把入口挪回排列方式之后,对应断言分别变红
2026-09-14 22:29:16 +08:00
suzmii 9e709ce727 AGC 资源工作台交互收口:补充改动前三处截图对照图
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Failing after 2m1s
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Failing after 2m7s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Failing after 2m16s
Project CI / AI game creator shell Rust smoke (pull_request) Failing after 2m2s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Failing after 2m19s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 2m18s
Project CI / Native shell tests (pull_request) Failing after 4m28s
Project CI / Frontend tests (pull_request) Successful in 4m13s
Project CI / Repository checks (pull_request) Successful in 3m30s
Project CI / Backend tests (pull_request) Successful in 7m9s
Project CI / AI game creator shell web tests (pull_request) Successful in 2m59s
- 新增 docs/technical/assets/agc-resource-workbench-ui-before-20260914/:任务侧栏两个关闭入口、左侧贴边折叠把手、顶部播放按钮居中悬浮三张改动前截图
- 新增该目录 README,逐图说明改动前的问题与同步过的文档口径,供 PR 与后续回归对照
2026-09-14 22:02:54 +08:00
suzmii 96ae3db1df AGC 资源工作台三处交互收口:侧栏关闭入口合并、删除折叠把手、播放左对齐
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Failing after 2m14s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Failing after 2m9s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Failing after 2m53s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Failing after 2m46s
Project CI / AI game creator shell Rust smoke (pull_request) Failing after 1m53s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 2m5s
Project CI / Frontend tests (pull_request) Successful in 4m28s
Project CI / Native shell tests (pull_request) Failing after 4m57s
Project CI / Repository checks (pull_request) Successful in 3m30s
Project CI / Backend tests (pull_request) Successful in 7m19s
Project CI / AI game creator shell web tests (pull_request) Successful in 3m21s
- 「生成任务」侧栏头部右上角由返回箭头(ChevronLeft / aria-label=收起生成任务)改为关闭 X,并与底部那枚重复的 X 统一为同一个 aria-label=关闭生成任务
- 删除「生成任务」侧栏底部 footer(关闭按钮 + border-top 分割线):关闭入口只留头部一枚
- 删除「生成任务」侧栏折叠态的左侧贴边竖排把手(handle 及其标签 / 在途角标 / 进场动画 / 悬停位移):折叠后组件不再渲染任何常驻入口
- 清理上述删除留下的悬空样式:focus-visible 分组选择器、480px 窄屏媒体查询与 prefers-reduced-motion 块里的把手分支
- 工具条「生成任务」入口移出 `mode === 'resources'` 分支:两个页签下都常驻。侧栏本体本来就是无条件渲染的浮层,运行态可见;入口只留资源页签时,切到运行关掉侧栏就再也打不开(此前靠左侧贴边把手兼作运行态入口)
- 工具条把「播放」移到「资源管理 / 运行」右侧并左对齐:新增 .game-workbench-view-tabs 作为左侧控件组,播放按钮由 absolute + left:50% + translateX(-50%) 的居中悬浮改为 static;相应删除 max-width:1000px 里的居中兜底规则
- 播放按钮并进按钮基础外观与 focus-visible 规则列表:新位置不再命中 .game-workbench-tabs / .game-workbench-view-actions 的选择器,漏掉会掉成零圆角、零内边距、无边框、默认字号的裸按钮(颜色规则仍生效,肉眼容易漏)
- 播放按钮保持两个页签下都常驻(回到改动前的可见性):运行视图空态与预览失败态要靠它重跑
- 同步更新断言:侧栏关闭入口唯一且 footer 不存在、折叠态不渲染任何按钮或把手、样式表不残留被删类名、播放按钮声明为左对齐静态定位且仍在基础外观/焦点环规则内
- 生成任务用例补回机器证据:折叠后工具条按钮的 data-resource-generation-task-count 归零、重开后头部「在途生成任务 0」徽标跟上收口结果、运行页签下侧栏仍能重开(先用 aria-selected 钉住真的切了页签);用例夹具新增 runnable 开关把首个原型标成完成
- 同步文档现状:PRD 顶部播放按钮与任务侧栏进度面两条、AGC 栏目画布底部工具栏入口矩阵的侧栏形态、decision-log 的进度面形态决策

验证:tsc -p apps/ai-game-creator-shell/tsconfig.json --noEmit 通过;vitest appSurface 全量 440 条通过、生成任务侧栏 8 条与侧栏样式 9 条通过;check-encoding 通过;prettier --list-different 未新增命中(project-development/index.tsx 属基线既有非格式化文件);变异验证:还原播放按钮基础外观规则、还原折叠把手与 footer、还原折叠态早返回、把「生成任务」入口退回 mode 分支,对应断言均变红
2026-09-14 22:00:06 +08:00
kdletters 1877aea33c 修复 Windows verbatim AppData 路径权限识别
Project CI / AI game creator shell Rust shard 1/4 (push) Failing after 2m2s
Project CI / AI game creator shell Rust shard 2/4 (push) Failing after 2m15s
Project CI / AI game creator shell Rust shard 3/4 (push) Failing after 2m13s
Project CI / AI game creator shell Rust shard 4/4 (push) Failing after 2m13s
Project CI / AI game creator shell Rust smoke (push) Failing after 1m44s
Project CI / AI game creator shell Rust crates (push) Successful in 2m58s
Project CI / Native shell tests (push) Failing after 4m10s
Project CI / Frontend tests (push) Successful in 4m10s
Project CI / Repository checks (push) Successful in 3m4s
Project CI / AI game creator shell web tests (push) Successful in 2m32s
Project CI / Backend tests (push) Successful in 6m55s
归一化 \\?\ 与 \\?\UNC\ 路径后再判断受管 ACL scope

补充 verbatim AppData 回归测试
2026-09-14 21:04:01 +08:00
kdletters 2bdee990a2 AGC 开发态补齐后台 Web 启动与端口汇总,端口归属探测从 WMI 换成 netstat
- dev-port.mjs 新增 resolveAgcAdminWebEndpoint:后台 Web 端口按 Linux 用户端口段 start + 3、非 Linux 优先 3102 解析,ADMIN_WEB_PORT 可显式指定,并把已解析的 AGC Vite 端口列为保留端口
- start-dev-stack.mjs 随 AGC 一起拉起 apps/admin-web(AGC_DEV_ADMIN_WEB=0 关闭):与 AGC Vite 一样由启动器直接持有并纳入信号与退出收束,不走会整体重写 .app/dev-stack.json 的 dev:admin-web
- start-dev-stack.mjs 新增启动汇总行,一次给出前端、后端、后台、数据库与 bgfilter-worker 的实际地址,端口漂移后以该行为准
- start-dev-stack.mjs 端口归属探测改用 netstat -ano 取端口到 PID、.NET Process 读可执行文件路径,仅在核对 SpacetimeDB --data-dir 归属时按 PID 取命令行并做 5 分钟 TTL 缓存:本机实测单轮探测由约 43 秒降到 0.37 秒,agc:serve 的 starting backend stack 到 backend ready 由约 80 秒降到 16.7 秒
- 后台 Web 端口解析或启动失败只告警,不阻断也不连带停止 AGC 客户端与配套后端
- tests/dev-port.test.ts、tests/start-dev-stack.test.ts 补充用例覆盖后台 Web 端口解析与严格占用、失败软化、启动汇总、netstat 探测脚本与命令行缓存失效
- docs/【开发运维】与 docs/technical 同步 AGC 开发态启动口径,pitfalls.md 记录 WMI 慢速探测的实测数据、netstat 改法与 PID 取最后一列的易错点
2026-09-14 21:02:08 +08:00
suzmii 330e4d6c5b Merge pull request 'AGC 画布:生成期间可退出与任务侧栏(高优)、画布手动整理、透明底判据、素材类型独立入口' (#358) from fix/agc-canvas-acceptance-batch into master
Project CI / AI game creator shell Rust shard 1/4 (push) Successful in 4m41s
Project CI / AI game creator shell Rust shard 2/4 (push) Successful in 4m38s
Project CI / AI game creator shell Rust smoke (push) Successful in 1m34s
Project CI / AI game creator shell Rust shard 3/4 (push) Successful in 4m25s
Project CI / AI game creator shell Rust shard 4/4 (push) Successful in 4m34s
Project CI / AI game creator shell Rust crates (push) Successful in 2m30s
Project CI / Frontend tests (push) Successful in 4m9s
Project CI / Repository checks (push) Successful in 3m15s
Project CI / Backend tests (push) Successful in 6m49s
Project CI / Native shell tests (push) Successful in 6m28s
Project CI / AI game creator shell web tests (push) Successful in 3m15s
2026-09-14 20:31:21 +08:00
suzmii aeac6c7b74 合并 origin/master(279a5e8e0,#356 UI 编辑器返回后资源画布平移)到验收批次
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Successful in 4m55s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 1m32s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Successful in 4m43s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Successful in 4m38s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Successful in 4m15s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 2m3s
Project CI / Frontend tests (pull_request) Successful in 3m56s
Project CI / Repository checks (pull_request) Successful in 3m28s
Project CI / Native shell tests (pull_request) Successful in 6m19s
Project CI / Backend tests (pull_request) Successful in 7m32s
Project CI / AI game creator shell web tests (pull_request) Successful in 3m0s
- 合并最新 master,使 PR #358 的头包含当前 master 顶端(CI 门禁要求)
- 冲突按「两侧语义都保住」解:
  - docs/project-memory/shared-memory/pitfalls.md:保留我方新增的「严格 IPC 桩缺登记新命令」
    与上游新增的「UI 编辑器返回后资源画布滚轮平移失效」两条,只删除冲突标记行
  - index.tsx / tests/appSurface/harness.ts / project-development.suite.ts:保留本批生成任务与
    资源画布改动,同时并入上游的资源画布平移回归用例与共享 ResizeObserver 桩
- 工作树里另有 5 个版本号改动(package.json / Cargo.toml / Cargo.lock / tauri.conf.json /
  package-lock.json,0.1.29 → 0.1.34)属发布动作,**本次刻意未提交**,原样留在工作树
2026-09-14 20:27:05 +08:00
suzmii 2292ae1fc1 Merge branch 'master' into fix/agc-canvas-acceptance-batch
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Successful in 4m48s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 1m35s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Successful in 4m29s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Successful in 4m25s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Successful in 4m33s
Project CI / AI game creator shell Rust crates (pull_request) Successful in 3m8s
Project CI / Frontend tests (pull_request) Successful in 4m30s
Project CI / Repository checks (pull_request) Successful in 3m2s
Project CI / Backend tests (pull_request) Successful in 6m51s
Project CI / Native shell tests (pull_request) Successful in 6m28s
Project CI / AI game creator shell web tests (pull_request) Successful in 3m2s
2026-09-14 19:59:44 +08:00
suzmii b077cb5277 更正 decision-log:「整理画布」最终位置固定在「生成素材」之后、「管理未完成编辑」之前(不在行尾)
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 / Frontend tests (pull_request) Has been cancelled
Project CI / Repository checks (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 shard 1/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Has been cancelled
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Has been cancelled
2026-09-14 19:30:02 +08:00
suzmii 8ad0487b8d 合并 fix/agc-resource-layout-manual:「整理画布」移入资源动作簇(离开行尾)
- 冲突解在 index.tsx 工具条动作区:两侧都要在同一位置插入按钮(WS1 的「生成任务」入口 +
  WS2 把「整理画布」从行尾移到「生成素材」之后),按「两侧语义都保住」解——
  「整理画布」在前(紧邻「生成素材」,满足其 previousElementSibling 断言与「不是行尾」断言),
  「生成任务」紧随其后,共用同一个闭合标签;行尾那份旧「整理画布」由 WS2 的删除 hunk 干净应用
- 已核对:ria-label="整理画布" 与 ria-label="生成任务" 在文件中各恰好一处
- 合并后实测:gc:typecheck 通过;resourceCanvasManualLayout 9 + appSurface 439 = 448 passed
2026-09-14 19:29:51 +08:00
suzmii 417b5ec630 「整理画布」移入资源动作簇:排在「生成素材」之后,不再挂在这一行行尾
- index.tsx:把「整理画布」从 game-workbench-view-actions 行尾(排序 tab 之后)
  移到「生成素材」之后、「管理未完成编辑」之前,与其它资源动作同类相邻,
  标签仍为 aria-label=\"整理画布\",零 CSS 改动
- index.tsx:语义与行为一字未改——disabled={!resourceLayoutReady}、
  aria-busy={resourceLayoutSaving}、onClick 仍调 activeResourceLayout.rederiveNow(),
  反馈仍走既有 resourceLayoutNotice / resourceLayoutSaving,changed 门保留
- resourceCanvasManualLayout.test.tsx:位置断言改为钉新位置——该行最后一个按钮不是它、
  它在「生成素材」之后(previousElementSibling)、在排序组左侧;
  继续保留「资源排列方式」组内只有「按依赖 / 按类型」与本按钮不在该组 /
  不在 .game-resource-sort-tabs 内的断言
2026-09-14 19:25:21 +08:00
suzmii 5adc16fbda Merge branch 'feat/agc-generation-task-progress' into fix/agc-canvas-acceptance-batch 2026-09-14 19:16:16 +08:00
suzmii 6c98c19c12 更正 decision-log:「整理画布」是资源工具条动作区里的独立动作按钮,不在「资源排列方式」分组内 2026-09-14 19:11:33 +08:00
suzmii 41c59a37a0 style(agc): 「生成任务」侧栏做视觉与信息层级收口(行为与语义一个不动)
- 新增 `resourceCanvasAssetGenerationTasksSidebar.css`:侧栏样式独立成文件,取值全部走平台设计 token
  (`--platform-subpanel-fill/-border`、`--platform-panel-shadow`、`--platform-text-muted`、`--platform-line-soft`、
  `--platform-neutral-*`、`--platform-accent`、`--platform-success-*`、`--platform-button-danger-*`、
  `--platform-input-focus-ring`),不硬编码任何颜色,也不新增第二套色板
- 条目卡片化:素材名为主信息(加粗、单行省略)、阶段文案为次要信息(muted、小一号)、
  已耗时 `font-variant-numeric: tabular-nums` + 右对齐(秒数跳动不抖)、失败原因 `overflow-wrap: anywhere`
  折行不截断、「定位到素材」轻量下划线按钮 + hover 换色
- 状态徽标成体系:`data-tone` 四档——排队中 `--platform-neutral-*`(中性)、生成中 `--platform-accent`
  (品牌色 + 呼吸感圆点,**不做百分比**)、已完成 `--platform-success-*`、失败 `--platform-button-danger-*`;
  tone 映射提到模型层 `resourceCanvasAssetGenerationTaskTone`(组件只导出组件与常量,保住 react-refresh 边界)
- 分栏标题小字 + 条数胶囊,两栏之间用 `--platform-line-soft` 分隔;空态只给一句简短文案
- 侧栏容器圆角 + 边框 + `--platform-panel-shadow` + `backdrop-filter: blur(10px)`;展开/折叠各有进场动画
  (位移 + 淡入,不做宽度 reflow 抖动);折叠把手是竖向标签 + 在途数量胶囊;列表滚动条细样式
- 无障碍与降级:`:focus-visible` 用 `--platform-accent` 焦点环 + `--platform-input-focus-ring`;
  `@media (prefers-reduced-motion: reduce)` 关掉全部 animation / transition 与 hover 位移;
  `@media (max-width: 480px)` 下侧栏撑满可用宽度、把手收窄,不挡画布操作
- 测试:新增 `resourceCanvasAssetGenerationTasksSidebarStyle.test.ts`(用仓库既有 `tests/styleCascade.ts`
  按真实层叠断言:四档 tone 互不相同且只引平台 token、tabular-nums + 右对齐、卡片圆角与 hover、
  过渡与把手、细滚动条、360px 降级、reduced-motion 关动效、焦点环);
  侧栏行为用例补「四种状态各自输出对应 data-tone」,并把原先断言 Tailwind 类名的部分交还给样式用例
- 未改任何行为:分栏、条数、已完成封顶 20、折叠不清列表、提交后自动展开、入口在途计数、
  定位终局化、非模态(无遮罩 / 无焦点陷阱 / 不进模态遮挡判据)全部保持原样
2026-09-14 19:11:21 +08:00
suzmii a6de1b5570 Merge remote-tracking branch 'origin/master' into fix/agc-canvas-acceptance-batch 2026-09-14 19:07:46 +08:00
suzmii 444bf9bc24 Merge branch 'fix/agc-resource-layout-manual' into fix/agc-canvas-acceptance-batch 2026-09-14 19:07:45 +08:00
suzmii 21c85c4dd1 「整理画布」移出「资源排列方式」分组,成为独立动作按钮
- index.tsx:把「整理画布」从 aria-label=\"资源排列方式\" 的 role=group 里搬出来,
  紧跟排序 tab 之后、作为 game-workbench-view-actions 动作区里的独立按钮,
  外观直接复用该容器既有动作按钮样式(有边圆角 + secondary 填充),不新增 CSS
- index.tsx:语义与行为一字未改——aria-label=\"整理画布\"、disabled={!resourceLayoutReady}、
  aria-busy={resourceLayoutSaving}、onClick 仍调 activeResourceLayout.rederiveNow(),
  成功/失败反馈仍复用既有 resourceLayoutNotice / resourceLayoutSaving,changed 门保留
- resourceCanvasManualLayout.test.tsx:新增结构断言——「资源排列方式」分组里只有
  「按依赖 / 按类型」两枚按钮、「整理画布」不在该容器内也不在 .game-resource-sort-tabs 里,
  同时仍是动作区内可用按钮(布局就绪后不再 disabled)
2026-09-14 19:07:22 +08:00
suzmii a45172e055 同步文档:生成进度面收敛为常驻可折叠侧栏、提交即关面板、定位终局化、类型选项纵向列表
- PRD §3.10:进度面由「非模态浮层」改为「常驻画布的可折叠任务侧栏」(折叠把手带在途计数、两个分栏、已完成封顶 20、左侧覆盖式、提交后自动展开);定位动作终局化(跨栏目先切栏目 / 不在投影给结论 / 3 秒有界兜底)
- PRD §3.10 面板形态:改为「点「生成」即同步关闭面板、面板内不出现阶段文案;只有点击瞬间失败才带草稿重开;受理后失败只在侧栏收口」
- 栏目画布入口矩阵 §4/§4a:同步上述两条,并把 4a 标题由「「生成任务」面板」改为「「生成任务」侧栏」
- decision-log:新增 2026-09-14 条目(进度面收敛为常驻可折叠侧栏 + 提交即关面板 + 定位终局化,含位置取舍与覆盖式理由、五条变异证据);并在「素材类型」条目补记选项形态修订(纵向单选列表、radio 语义、方向键只移焦点、行列与滚动口径、建议后续抽 PlatformRadioList)
2026-09-14 18:50:48 +08:00
suzmii e6d92b2d98 Merge branch 'feat/agc-generation-task-progress' into fix/agc-canvas-acceptance-batch 2026-09-14 18:50:00 +08:00
suzmii ec02c39a5d feat(agc): 「生成任务」改造成常驻画布的可折叠侧栏(分栏 / 计数 / 自动展开 / 折叠不影响任务)
- ResourceCanvasAssetGenerationTasksPanelView 由非模态浮层改造成任务侧栏:展开时是贴边
  `<aside>`(`role="region"`、`aria-label="生成任务"`、不铺遮罩、不做焦点陷阱、不进模态遮挡判据),
  折叠时只留一个可点的贴边把手(`aria-label="展开生成任务"`)并带在途数量角标
- 位置取舍:右侧是「智能创作」对话面板、底部是栏目工具栏、顶部是栏目标题栏,所以挂在**左侧、标题栏
  之下、工具栏之上**(`top-16 / bottom-24 / left-3 / w-[300px]`)且是**覆盖式**而不是把画布挤窄——
  画布视口数学与资源卡排布都不被 reflow 动到,收起即完全让出画布;不再保留原来的浮层形态,没有平行入口
- 两个分栏:「排队/生成中」与「已完成」各带条数,只做客户端分组;「已完成」条数封顶 20 条(超出给出
  还剩多少条的说明),列表自身 `overflow-y-auto`,侧栏高度有界
- 入口按钮常驻可见并显示在途数量(`生成任务 · N`,无在途时仍是「生成任务」,`aria-label="生成任务"` 保留),
  把手上的角标同步;提交受理后侧栏自动展开(对齐网页端排队提交后主动弹任务栏)
- index.tsx:新增在途数量派生;侧栏常驻渲染并受同一个开合开关控制,折叠只影响这个视图,
  任务本身仍活在账本与本地队列里
- 测试:任务侧栏用例改为侧栏形态并补「两个分栏 + 条数」「高度有界 + 列表滚动 + 已完成封顶 20」
  「折叠后把手带上在途计数(0 / 2)」;AppSurface 补「提交后自动展开」「折叠期间任务照常推进、
  在途计数归零、再展开仍能看到结果」
2026-09-14 18:49:22 +08:00
suzmii 14a0286f70 fix(agc): 生成面板点击即关闭、面板内不再出现阶段文案,只有即时失败才把草稿带回来
- ResourceCanvasAssetGenerationPanelView:删掉 `phaseDetail` 通道与整套在途状态(`submitting` /
  禁用输入 / 「后台运行并关闭」),主按钮文案恒为动作名;提交时**同步**调用 onSubmit 并 onClose,
  面板不等 IPC、不等排队、不等生成。新增 `draft` / `error` 两个入参:只有「后端从未受理」的即时
  失败重开时,宿主才把草稿与原因带回来(`role="alert"` 可见、改完即可重试)
- index.tsx:`submitResourceAssetGeneration` 改为同步返回(不再 await 终局),记录本次提交上下文
  (taskId / action / 草稿 / 是否本来就该立刻派发),提交后自动开任务面板并给一次提示条;
  收尾回调里区分两类失败:`record === null` 且本来就该立刻派发 → 重开提交面板并带回草稿;
  受理之后才失败 → 不重开面板,只在任务面板收口为失败 + 提示条
- index.tsx:删掉只为旧「在途阶段文案」服务的 `resourceAssetGenerationPanelTaskIdRef` 与成功后的
  自动收面板逻辑(面板此时已关闭)
- 测试:`resourceCanvasAssetGenerationBackgroundClose.test.tsx` 的图片类用例改写为「点击即关闭 +
  面板 DOM 里从不出现 排队中。/正在生成。/提交中…」+「即时失败重开带回草稿与原因」;音频面板用例不变
- 测试:`resourceCanvasBottomToolbar.test.tsx` 的失败重试用例按新语义改写(点击即关闭、重开时显示原因)
- 测试:AppSurface 新增三条(同步关闭且面板无阶段文案、后端未受理时重开并保留草稿、受理后失败不重开
  只在任务面板收口),并把既有生成任务 e2e 的提交步骤改为「点击即关闭」
- 顺带按仓库规范修正以上文件的 eslint import sort 与 prettier 格式(未触碰无关文件)
2026-09-14 18:35:11 +08:00
suzmii 2f47540eeb fix(agc): 「定位到素材」每次点击都终局化,不再卡在「正在定位生成的素材…」
- index.tsx 新增 `resourceAssetGenerationFocusRequest` 序号并加进聚焦 effect 的依赖:手动点定位不改画布
  任何状态,原依赖一个都不变 → effect 不重跑、intent 永远没人消费,这正是「点了没反应 + 提示条永久
  停在中转文案」的根因
- index.tsx `focusResourceAssetGenerationTask` 重写:先按当前投影与清单判一次目标——不在投影里就当场给
  结论(素材已不在项目里 / 已登记但尚未同步),不挂 intent 也不留中转提示;在别的栏目先切栏目再定位;
  挂 intent 后推进聚焦请求序号,并起一个 3 秒有界兜底:仍停在中转文案就收口成可执行提示,intent 被判
  invalid 被静默清掉时也给一条「定位请求已失效」的结论,绝不留下悬而未决的状态
- index.tsx 聚焦 effect 的 `focusedCommitIdsRef` 提前返回分支补 `setResourceWorkbenchNotice('')`:
  已聚焦过时把中转提示一并收掉,不再永久留在提示条上(自动落卡那条链同源问题)
- index.tsx `resourceAssetGenerationContextRef` 扩到带 `manifest` / `resources` / `activePageCategory`
  并在每次渲染刷新:定位回调据此取权威目标与栏目,不再依赖可能过期的闭包值
- 新增 4 条 AppSurface 用例(同栏目直点定位并选中卡片、素材在另一个栏目先切栏目再定位、被搜索挡住时给出
  既有「清除搜索并定位」、素材不在项目里时给明确结论且清掉中转提示)
2026-09-14 18:20:50 +08:00
suzmii a2b016bb9b Merge branch 'feat/agc-generation-task-progress' into fix/agc-canvas-acceptance-batch 2026-09-14 18:18:45 +08:00
suzmii b898590c7d 合并 feat/agc-resource-type-entry:类型选项改纵向单选列表
- 合并 WS4 追加修复(928a0ea13:类型选项由横排 PlatformSegmentedTabs 改为 role=radiogroup 纵向单选列表,
  复用共享 PlatformNavigableListItem,列表有界独立滚动,rogiving tabindex + 方向键移焦点、Enter 落盘)
- 同时并入 origin/master a70ef2d6e(PR #354 Windows sccache / CI 分片改「一片一 job」)
- decision-log.md / pitfalls.md 冲突按「上游改写优先、我方新增保留」解:
  保留我方新增的「放开手工图片生成本地并发」「素材类型独立入口」「退役同步命令」三条与
  「严格 IPC 桩缺登记新命令」一条;AGC 壳 Rust 套件条目采用上游改写后的新标题(「一片一 job」),
  删掉被它取代的旧标题(旧正文早已被上游替换),不留自相矛盾的两条
2026-09-14 18:18:30 +08:00
suzmii 4e277798b8 Merge remote-tracking branch 'origin/master' into feat/agc-resource-type-entry 2026-09-14 18:17:10 +08:00
suzmii 928a0ea13e 素材类型选项改成纵向单选列表,不再横排成一条
- ResourceTypePanel:选项区从 PlatformSegmentedTabs(3~6 列网格,6 项正好挤成一行)换成纵向单选列表,复用共享的 PlatformNavigableListItem 作行骨架
- ResourceTypePanel:容器改为 role="radiogroup" + aria-label,每项 role="radio" + aria-checked,选中态与读屏读的是同一个属性
- ResourceTypePanel:roving tabindex(只有选中项 tabIndex=0)与方向键在选项间移动焦点,走到头不越界;方向键不顺手选中,Enter/Space 才落盘(选中=一次 CAS 写盘,浏览选项不该连环写盘)
- ResourceTypePanel:选中行额外渲染勾选图标作为第二视觉线索,图标 aria-hidden 不污染可读名字
- resourceTypePanel.css:选项容器改成单列网格(grid-template-columns: minmax(0, 1fr) + grid-auto-flow: row + align-content: start),一行一个选项
- resourceTypePanel.css:选项行补 width/min-width/min-height: 44px 与 overflow-wrap,移动端热区与窄屏换行都不依赖共享件的工具类
- resourceTypePanel.css:选中态由 [aria-checked='true'] 驱动并显式提权到 (0,3,0) 以上(含覆盖 :hover:not(:disabled)),避免被共享列表行的悬停底色顶掉
- resourceTypePanel.css:滚动从 body 挪到选项列表(列表现有 max-height: min(320px, 40dvh) + overflow-y: auto),body 改为 auto/minmax(0,1fr)/auto 三段,标题、素材名与错误提示不跟着滚
- 测试:新增「选项区是纵向单列列表」用例,按 styleCascade 解析真实生效声明(360/390/1440 三档宽度都是单列、行满宽、热区 44px),并断言 6 项都是 radiogroup 的直接子元素
- 测试:新增「单选语义与键盘」用例(radiogroup/radio + aria-checked + roving tabindex,方向键只移焦点不落盘,Enter 才写盘)
- 测试:新增「选中态由 aria-checked 驱动并压过共享列表行悬停底色」用例
- 测试:把「面板有高度上界且中间行可滚动」改成「选项区有上界并独立滚动,标题与错误提示不滚」
- 测试:集成用例的类型选项查询从 button/aria-pressed 改为 radio/aria-checked
2026-09-14 18:16:56 +08:00
suzmii cdc0e3d163 fix(agc): 生成任务读门禁用合法 command id、中断任务按清单核对不谎报未完成,并同步注释事实
- asset_generation_tasks.rs:`list_local_project_asset_generations` 的读门禁 command id 由 `asset.read`
  改为契约里真实存在的 `asset.list`(`asset.read` 不在命令表里,写进 `denied_commands` 也不可能命中
  → 原门禁恒不生效);补用例把 `asset.list` 放进项目策略 `denied_commands` 后读账本必须被拒
- asset_generation_tasks.rs:中断任务收口改为与 manifest 交叉核对(新增账本字段 `output_path`,serde 默认值
  兼容旧账本):能找到本次请求的精确落点 → 按事实收口为已完成并带上 assetId;落点存在但清单里没有
  → 报「目标素材未登记,生成未完成」;没有精确落点或清单读不到 → 只报「状态未知(可能已完成)」,不再
  对「素材已登记、账本还停在 running」的窗口谎报「生成未完成」
- asset_generation_tasks.rs:补四条用例(已登记→已完成、未登记→未完成、无落点→状态未知、读门禁可拒绝),
  并把既有的两条中断用例按新语义改为断言「状态未知」
- resourceCanvasBottomToolbarModel.ts:两处注释的入口命令名改为 `start_local_project_asset_generation`
- check-config.mjs:`generate_local_project_asset` 白名单注释改为「没有生产调用方,只有 Rust 集成测试与
  commands.rs 单测在调,待后续批次删除或改为转调 start_local_project_asset_generation」
- resourceCanvasAssetGenerationTaskModel.ts / resourceCanvasAssetGenerationQueue.ts:把「远端 single-flight
  输出槽会拒绝并发」这个已不成立的排队理由改为当前事实——本地 durable 输出槽已按精确动作指纹分槽,
  本批仍按「同一时刻只派发一条」排队是**提交节流**,真并行派发需要并发收口设计,留待下一批
2026-09-14 18:13:12 +08:00
suzmii 8ac77cb090 同步共享记忆与专题文档:并发槽身份、素材类型入口、退役同步命令
- PRD §3.10 本地排队一条:删掉已失效的「共用 single-flight 输出槽」理由,改为「本地槽已按精确动作指纹分槽(具备并行能力),本批前端仍按单条在途排队,真并行派发留待下一批」
- 栏目画布底部工具栏入口矩阵 §4a:同上更正,并写明槽身份材料的 8 个字段与旧槽懒迁移
- decision-log:追加三条 2026-09-14 条目(放开手工图片生成本地并发 / 素材类型拆成独立入口 / 同步命令 generate_local_project_asset 退役为仅测试调用)
- decision-log:更正同日「图片类生成后台化」条目里已被同批次推翻的两处表述(槽身份、本地排队的理由),并给 2026-09-11 的类型选择器入口决策加「已被取代」标记
- decision-log/pitfalls:把「严格 IPC 桩缺登记新命令」的排障经验记入共享记忆(unhandled rejection 与不相干提示断言的组合症状、桩必须返回数组、形状错会「看着绿」)
- 端到端验收用例 S12:更正「用户手动设置 category 已移除」与「面板内删除资源是唯一入口」两处与当前实现不符的描述
2026-09-14 17:52:27 +08:00
suzmii 7240b3793f Merge branch 'feat/agc-generation-task-progress' into fix/agc-canvas-acceptance-batch 2026-09-14 17:50:40 +08:00
suzmii 4fff733516 fix(agc): 生成任务账本读不到时不再抛未处理拒绝,改为保留本地状态并给出提示
- resourceCanvasAssetGenerationTaskModel.applyLocalProjectAssetGenerationRecords:入参在函数入口归一化,
  非数组(undefined / null / 字符串 / 数字 / 对象)一律按「没有后端记录」处理,数组内的垃圾条目
  (null / 数字 / 缺 taskId)逐条丢弃;类型放宽为 `readonly …[] | null | undefined`
- resourceCanvasAssetGenerationQueue:轮询 `list_local_project_asset_generations` 的 IPC 拒绝与非数组
  返回值都在本地接住,按「本轮读不到」计数;到上限后按「账本不可用」与「账本里没有这条」两种原因分别收口;
  派发循环再补两道兜底(dispatch 意外抛出、宿主 onSettled 抛出),保证 `void (async …)()` 不产生未处理拒绝、
  也不会把任务永远卡在「已派发但未终态」
- index.tsx 恢复任务账本的 effect:IPC 拒绝与返回非数组都落到既有提示条
  「生成任务列表读取失败,暂时无法恢复历史任务」,本地任务列表保持原样不清空
- 测试:模型层补「undefined / 非数组 / 垃圾条目不抛错且列表不变」,驱动器层补
  「轮询返回 undefined」「轮询 IPC reject」两条(收口原因、不产生未处理拒绝、后续排队任务照常补发)
- AppSurface 补两条:账本返回 undefined / 读取被拒绝时视图照常渲染、生成入口还在、提示可见
- AppSurface 既有的「布局读时提示」用例显式登记 `list_local_project_asset_generations` 返回空账本:
  该命令是只读的独立链路,严格桩把它判成 unexpected invoke 会让新提示混进「没有任何提示」的断言
2026-09-14 17:47:03 +08:00
suzmii 5d336bf147 Merge branch 'fix/agc-resource-layout-manual' into fix/agc-canvas-acceptance-batch 2026-09-14 17:40:50 +08:00
suzmii 3d6d51737c 测试 harness 登记 WS1 新增的后台生成任务账本 IPC
- resourceCanvasManualLayout.test.tsx:installLayoutTauri 登记
  list_local_project_asset_generations(工作台打开 / 切项目时由 WS1 的生成任务面板读取),
  回空账本,形状按 src-tauri/src/asset_generation_tasks.rs 的
  list_local_project_asset_generations 返回值核对为数组(Vec<AssetGenerationTaskRecord>),
  与前端 invoke<LocalProjectAssetGenerationTaskRecord[]> 一致,不是 { tasks: [] }
- 保留 unexpectedCommands 断言不放宽,也不删除:这条门禁继续拦截意外 IPC
2026-09-14 17:38:21 +08:00
suzmii 1de661df10 Merge branch 'feat/agc-generation-concurrency' into fix/agc-canvas-acceptance-batch 2026-09-14 17:31:40 +08:00
suzmii 6b5f67d207 Merge branch 'feat/agc-generation-task-progress' into fix/agc-canvas-acceptance-batch 2026-09-14 17:31:32 +08:00
suzmii 74b3760d0f docs(prd): 同步功能画布生成入口的后台化事实
- 头部更新时间改为 2026-09-14 并说明本次同步内容,2026-09-13 的原口径与其余合同保持不变的声明保留
- §3.10 实现状态补 2026-09-14 后台化口径(提交即返回 + 项目内任务账本 + 本地排队 + 非模态「生成任务」面板)
- §3.10 接线:图片类入口由 `generate_local_project_asset` 改写为 `start_local_project_asset_generation` + `list_local_project_asset_generations`
  + 项目内账本 `.agent/runtime/asset-generation-tasks/tasks.json`;音频 / 上传两条接线不变
- §3.10 新增「本地排队与进度可见」一条:第二条停在本地队列不调用提交 IPC、阶段文案由后端账本提供、
  非模态「生成任务」浮层与按素材卡定位
- §3.10 面板形态:补「提交期间面板不锁关闭」(×/遮罩/Esc/「后台运行并关闭」),并明确关闭不等于取消请求
- §3.10 前置规范图:命令名同步,并明确「后台化没有改这条前置判据」(`ui-prototype` / `art-spritesheet` 判据不变)
- §7.9 第 3 条:改写为 `start_local_project_asset_generation` 的载荷与「提交即返回」事实,
  保留「原载荷字段名与取值口径逐字不变」的说明,并补 `projectId` / `taskId` 两个新增字段
- §7.9 第 6 条:配对读改为「发生在该任务收口之后(提交命令不再等待生成)」,音频入口描述不变
- §7.9 新增第 8 条:生成期间可退出、面板关闭后进度可见、第二条本地排队(IPC 次数 1→2)、
  两条各自完成后各走一次「配对读 + 落卡」且 revision 单调
2026-09-14 17:30:08 +08:00
suzmii 53026fe8f3 放开 AGC 手工图片生成的 durable 输出槽并发生成限制
- canvas_generation.rs:standalone 图片生成的 durable 输出槽身份改为由精确动作身份派生(run_id = slot-<actionFingerprint>),同一项目里不同 prompt/素材名/参数的生成各自独立成槽,可以同时在途
- canvas_generation.rs:动作指纹材料逐字节保持升级前取值,新增 legacy_standalone_platform_art_generation_run_id 复现升级前 {outputPath, requireSlices} 槽公式,只用于定位升级前遗留账本
- canvas_generation.rs:在取得 durable guard 之后、任何远端 POST 之前调用旧槽账本一次性迁移
- external_generation_state.rs:新增 adopt_legacy_standalone_platform_art_generation_runtime_state_at,在项目写锁内把仍属于本次精确动作的旧 slot- 账本迁移到新身份路径并保留原 idempotencyKey 与 operationId;属于其他动作的旧账本原样保留,不迁移、不删除、不阻塞
- external_generation_state.rs:新增三个 #[cfg(test)] 只读访问器,供跨模块用例断言账本身份
- canvas_generation.rs:新增两条不同动作并发都成功且远端各 POST 一次、不同动作的 durable 槽互不阻塞、旧槽账本仅被同一精确动作迁移三组用例;同动作并发冲突用例改用同一精确动作以钉住幂等语义
2026-09-14 17:30:00 +08:00
suzmii bb7cbae118 feat(agc): 图片类生成后台化,生成面板可随时关闭并新增「生成任务」进度面板
- Rust 新增 asset_generation_tasks.rs:图片类生成拆成「提交即返回任务记录 + 后台 spawn 生成」,
  生成本身仍转调既有 generate_platform_art_asset_with_options_at(不复制生成 / 幂等 / 登记逻辑)
- 任务账本落项目内 .agent/runtime/asset-generation-tasks/tasks.json(复用 agent runtime sidecar 原语),
  阶段文案 phaseDetail 由后端拥有,读取时把上次运行留下的非终态记录收口为「中断失败」,账本上限 50 条
- Rust 新增 IPC start_local_project_asset_generation / list_local_project_asset_generations 并在 main.rs 注册;
  同步命令 generate_local_project_asset 保留不动
- 新增前端纯模型 resourceCanvasAssetGenerationTaskModel.ts:任务状态机、在途判据、账本恢复、耗时文案
- 新增 resourceCanvasAssetGenerationQueue.ts:本地排队驱动器,第二条不发提交 IPC、前一条终态后自动补发,
  状态与阶段一律以后端账本为准,账本查不到该任务时按上限停止等待
- 两块生成浮层在提交期间放开 × / 遮罩 / Esc,次按钮在途时改为「后台运行并关闭」(关闭不等于取消请求),
  图片类面板的在途文案改为渲染后端 phaseDetail
- 新增非模态「生成任务」面板(不铺遮罩 / 不做焦点陷阱 / 不进模态遮挡判据),显示状态、后端阶段、
  已耗时与素材名,已完成条目复用 pendingResourceFocusRef 聚焦链定位素材卡
- index.tsx 宿主接线:任务列表状态与 ref、提交回调不再读面板状态、按项目恢复任务账本、
  工具栏「生成任务」入口按钮与面板渲染点
- check-config.mjs:把已无前端调用方的同步命令 generate_local_project_asset 登记进 native-only 白名单
- 测试:新增「生成面板提交期间可关闭」「本地排队驱动器」「生成任务面板」三组用例;
  appSurface 生成载荷断言改为 start_local_project_asset_generation + list 轮询桩
- 文档:入口矩阵补 §4a 与验证命令、V3 验收 S11a 判据、decision-log 记录本次决策
2026-09-14 17:26:36 +08:00
suzmii 0b3bf3e52d 合并 fix/agc-resource-layout-manual:资源画布改为手动整理口径
- 合并 WS2 分支(新素材不再自动重排 + 显式「整理画布」+ 生成后自动聚焦)
- index.tsx 与 useProjectResourceCanvasLayout.ts 自动合并成功,无需手工介入
- decision-log.md / pitfalls.md 冲突按「两侧语义都保住」解:保留 origin/master 新增的
  「AGC 壳 Rust 套件分片并行」与「根门禁 label 字面量契约」两条,同时保留 WS2 新增的
  「AGC 资源画布改为手动整理」与「不要恢复无条件重派生」两条,只删除冲突标记行
- 新增 tests/resourceCanvasManualLayout.test.tsx
2026-09-14 17:16:58 +08:00
suzmii 6d5cd51649 Merge branch 'fix/agc-preview-alpha-background' into fix/agc-canvas-acceptance-batch 2026-09-14 17:16:30 +08:00
suzmii 181e364d80 AGC 资源卡棋盘格底改按图像真实 alpha 判定
- 原生预览新增头部级 alpha 判据:`LocalProjectImagePreview.hasAlpha`(PNG colorType 4/6 或 tRNS、WebP VP8X/VP8L alpha 标志;JPEG 恒 false),只读签名与 chunk 头、不做像素解码。
- 前端预览 payload 增加可选 `hasAlpha`,并在 `materializeProjectResourceCardPreview` 的两条分支里透传。
- 资源卡根节点新增排障属性 `data-preview-has-alpha`:只有预览已加载且判据为真才写 `'true'`,其余一律不写(缺属性与不透明同档)。
- 棋盘格底选择器加 `[data-preview-has-alpha='true']` 条件;无 alpha 时退回卡片既有纯色底,不引入第二套底色。
- 新增 TS 用例(真渲染资源卡 + styles.css 声明级层叠求值)与 Rust 用例(PNG/WebP/JPEG 头部判据、tRNS、坏文件失败关闭、非解码证明、IPC 字段序列化契约)。
- 验收文档补记 `data-preview-has-alpha` 判据与「真假棋盘格」取证脚本,便于现场区分真透明底与 AI 画出的假棋盘格。
2026-09-14 17:13:43 +08:00
suzmii 3b8ecb02d4 记录 AGC 资源画布「手动整理」口径变更
- decision-log:追加 2026-09-14 条目,记录默认 preserve、显式「整理画布」、
  依赖侧关系图首次就绪的一次性重派生、新素材按 manifest 新增 id 聚焦四条决策与变异验证
- pitfalls:追加「不要恢复无条件重派生」条目,含 changed 门、ready 时序、
  项目作用域 flag 与新素材基线四个易错点
2026-09-14 17:08:00 +08:00
suzmii d02d0ed7a4 AGC 资源画布:新素材不再自动重排,改为显式「整理画布」并在生成后自动聚焦新素材
- useProjectResourceCanvasLayout:资源写意图新增 rederive 标记,显式整理那一笔按 rederive
  策略重算自动坐标(手动坐标原样保留),自动同步仍是 preserve 只补新卡
- useProjectResourceCanvasLayout:新增 rederiveNow(),复用既有写队列 / sidecar 写回链路,
  只在坐标确有变化时落盘,成功复用既有「布局已保存」提示
- index.tsx:两个排序模式的 rederiveAutomaticPositions 都固定 false,画布不再因为资源
  协调签名变化(新增素材、改标签、改分类、拓扑重建)整体重排
- index.tsx:依赖侧「关系图首次就绪」改为按项目作用域的一次性 flag,等该侧 sidecar ready
  后调用一次 rederiveNow(),之后一律只补新卡(切排序 tab 不重新武装)
- index.tsx:依赖/类型 tab 组新增「整理画布」按钮,作为整张画布重排的唯一显式入口
- index.tsx:新增 manifest.assets 新增 id 检测(seenManifestAssetIdsRef),把新卡交给既有
  pendingResourceFocusRef + advanceFocusGeneration() 裁决链聚焦;首次打开 / 切项目只登记
  基线不聚焦,重命名不改 id 天然不触发,已有同目标意图时不重复挂
- 新增 tests/resourceCanvasManualLayout.test.tsx(8 条):新素材入库后既有自动坐标逐值不变、
  依赖侧首次就绪后不再重排、新素材自动聚焦、被搜索挡住走既有「清除搜索并定位」、
  「整理画布」重算并保留手动坐标、已经整齐时再按一次不写盘、首次打开与切项目不聚焦
2026-09-14 17:07:55 +08:00
suzmii ef3e783ab1 Merge remote-tracking branch 'origin/master' into feat/agc-resource-type-entry 2026-09-14 17:07:36 +08:00
suzmii 7ce4a3a9c6 把素材类型从「编辑素材标签」面板拆成独立入口
- 新增 ResourceTypePanel(src/view/project-development/ResourceTypePanel.tsx):类型选一项即落盘,category 传用户选中值、tags 逐字回传落盘原值,保存在飞时沿用 closeOnBackdrop/closeOnEscape = !saving
- 新增 resourceAssetDisplayName.ts:两块面板共用同一个素材名副标题口径(localPath basename),不再各写一份
- 新增 resourceTypePanel.css:类型面板的弹窗骨架与信息浮层「分类」行入口样式,按 AGC 内独立文件约定,不动 packages/** 与 styles.css
- ResourceClassificationPanel 删掉类型 chip 与 categoryChoice:保存时恒回传 gameCreationAppAssetPersistedCategory(asset),「只改标签不动分类」由结构保证
- index.tsx 新增 resourceTypeAssetId 与 resourceTypeAsset;工具条在「编辑标签」旁新增「素材类型」按钮(Shapes 图标)
- index.tsx 用合并后的 resourceClassificationOverlayOpen 纳入点外部/Esc 浮层遮挡判据,并同步 useEffect 依赖项
- index.tsx 渲染新面板:保存成功后由宿主收起面板并沿用 manifest 重载路径,让卡片立刻落到新栏目
- 信息浮层「分类」行接出第二入口:按钮渲染在 dd 之外,不污染 dt/dd 字段读取口径;非 manifest 资产不给入口
- resourceCanvasInfoModel 导出 RESOURCE_INFO_CATEGORY_FIELD_LABEL,模型与入口共用同一行标识
- 新增 tests/resourceTypePanel.test.tsx:选中即落盘、tags 逐字回传、没碰过不写盘、显式待归类、失败回退、saving 锁、Esc/遮罩、面板骨架共 11 条
- 迁移「没碰过分类就回传落盘原值」对照用例并保留两条(标签面板侧),chip 用例搬到新面板文件
- 集成用例改走新入口:选中即落盘并自动关窗,另补 Esc/点外部不串台、只改标签后 manifest category 逐字不变两条宿主级用例
- appSurface 工具条清单补上「素材类型」
2026-09-14 17:07:15 +08:00
136 changed files with 13100 additions and 2786 deletions
+1
View File
@@ -164,6 +164,7 @@ module.exports = {
'server-rs/target-*',
'apps/desktop-shell/src-tauri/target',
'apps/ai-game-creator-shell/src/features/ui-editor/types/**',
'apps/ai-game-creator-shell/src/features/project-workspace/generated/**',
'target',
'src/main.tsx',
'src/App.tsx',
@@ -113,6 +113,11 @@ const allowedUncalledTauriCommands = [
'chat_with_game_creator_agent',
'check_ui_editor_font_glyph_coverage',
'create_ui_design_resource',
// 图片类生成的同步变体:GUI 已改为 `start_local_project_asset_generation` + 项目内任务账本
// (提交即返回、后台生成)。这条命令**没有生产调用方**,只有 Rust 集成测试
// `src/tests/project.rs`)与 `commands.rs` 单测在调;待后续批次删除,或改为转调
// `start_local_project_asset_generation`。
'generate_local_project_asset',
'open_game_creator_launcher_window',
'open_game_creator_workspace_window',
'read_direct_project_conversation',
@@ -9,6 +9,10 @@ import {
const agcDevHost = '127.0.0.1';
const legacyAgcDevPort = 3080;
const agcVitePortEnvKey = 'GENARRATIVE_AGC_VITE_PORT';
const agcAdminWebHost = '127.0.0.1';
const legacyAgcAdminWebPort = 3102;
// 与 scripts/dev.mjs 的后台 Web 端口配置保持同一环境变量名。
const agcAdminWebPortEnvKey = 'ADMIN_WEB_PORT';
function readConfiguredAgcDevPort(env = process.env) {
const rawPort = String(env[agcVitePortEnvKey] ?? '').trim();
@@ -99,13 +103,100 @@ function withAgcDevEndpointEnv(endpoint, env = process.env) {
};
}
function readConfiguredAgcAdminWebPort(env = process.env) {
const rawPort = String(env[agcAdminWebPortEnvKey] ?? '').trim();
if (!rawPort) {
return null;
}
const port = normalizePort(rawPort, -1);
if (port < 1024) {
throw new Error(`${agcAdminWebPortEnvKey} 必须是 1024-65535 的有效端口`);
}
return port;
}
function createAgcAdminWebEndpoint(port, portRange = null) {
const origin = `http://${agcAdminWebHost}:${port}`;
return {
host: agcAdminWebHost,
port,
origin,
basePath: '/admin/',
url: `${origin}/admin/`,
portRange,
};
}
// AGC 开发态的后台 Web 与 `npm run dev` 的后台 Vite 共用同一套优先端口约定:
// Linux 取当前用户端口段的 `start + 3` 槽位,非 Linux 保留 `3102` 兼容首选并允许统一漂移。
async function resolveAgcAdminWebEndpoint({
env = process.env,
platform = process.platform,
strictConfigured = false,
reservedPorts = [],
reservePortRange = reserveLinuxDevPortRange,
findPort = findAvailablePort,
} = {}) {
const configuredPort = readConfiguredAgcAdminWebPort(env);
let portRange = null;
let preferredPort = configuredPort ?? legacyAgcAdminWebPort;
if (platform === 'linux') {
const allocation = await reservePortRange({ env });
if (!allocation?.range) {
throw new Error('无法取得当前 Linux 用户的 dev 端口段');
}
portRange = allocation.range;
const mappedAdminWebPort = mapDevPortsToPortRange(portRange)?.adminWebPort;
if (!Number.isInteger(mappedAdminWebPort)) {
throw new Error(
`当前 Linux dev 端口段 ${portRange.label} 缺少后台 Web 槽位;请先迁移为至少 6 个端口且不与其它用户重叠的端口段`,
);
}
preferredPort = configuredPort ?? mappedAdminWebPort;
}
const reservedPortSet = new Set(
reservedPorts.filter((value) => Number.isInteger(value) && value > 0),
);
const port = await findPort({
host: agcAdminWebHost,
preferredPort,
portRange,
reservedPorts: reservedPortSet,
strict: strictConfigured && configuredPort != null,
});
console.log(
formatPortDecision({
name: 'ai-game-creator-shell-admin-web',
host: agcAdminWebHost,
preferredPort,
resolvedPort: port,
}),
);
if (portRange) {
console.log(
`[ai-game-creator-shell] admin-web port-range: ${portRange.label}`,
);
}
return createAgcAdminWebEndpoint(port, portRange);
}
export {
agcAdminWebHost,
agcAdminWebPortEnvKey,
agcDevHost,
agcVitePortEnvKey,
createAgcAdminWebEndpoint,
createAgcDevEndpoint,
legacyAgcAdminWebPort,
legacyAgcDevPort,
readAgcDevEndpoint,
readConfiguredAgcAdminWebPort,
readConfiguredAgcDevPort,
resolveAgcAdminWebEndpoint,
resolveAgcDevEndpoint,
withAgcDevEndpointEnv,
};
@@ -14,12 +14,14 @@ import {
import {
agcVitePortEnvKey,
readAgcDevEndpoint,
resolveAgcAdminWebEndpoint,
resolveAgcDevEndpoint,
withAgcDevEndpointEnv,
} from './dev-port.mjs';
const appRoot = fileURLToPath(new URL('..', import.meta.url));
const repoRoot = resolve(appRoot, '../..');
const adminWebDir = resolve(repoRoot, 'apps/admin-web');
const devStackStatePath = resolve(repoRoot, '.app/dev-stack.json');
const apiServerExePath = resolve(
repoRoot,
@@ -32,6 +34,8 @@ const backendSpacetimeDataDir = resolve(
repoRoot,
'server-rs/.spacetimedb/ai-game-creator/data',
);
// 后台 Web 默认跟随 AGC 一起起来,便于联调后台页面;`AGC_DEV_ADMIN_WEB=0` 可关闭。
const agcDevAdminWebEnvKey = 'AGC_DEV_ADMIN_WEB';
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const childLifecycles = new WeakMap();
@@ -200,36 +204,122 @@ function urlPort(url) {
}
}
// 读取端口当前真正的监听进程身份。返回 null 表示探测本身不可用(例如缺少
// Get-NetTCPConnection),此时调用方必须退化为旧行为,不能让本地启动直接失败。
// 端口归属探测脚本。历史实现用 `Get-NetTCPConnection` 取监听进程,而它底层走
// WMI:实测单端口单次 11.2 秒、再叠加每个 PID 的 `Get-CimInstance` 3.3 秒,
// 一轮探测约 43 秒,直接把"配套后端就绪"等待拖到分钟级。改用原生
// `netstat -ano`(约 30 毫秒)取端口 -> PID,再用 .NET `Process` 读进程名和
// 可执行文件路径(毫秒级);只有核对 SpacetimeDB `--data-dir` 归属时才按 PID
// 取命令行,并允许调用方把已知命令行传进来复用。
const windowsPortOwnerProbeCommand = [
'$ErrorActionPreference = "SilentlyContinue"',
'$queriedPorts = @()',
'foreach ($raw in ($env:GENARRATIVE_QUERY_PORTS -split ",")) {',
' if ($raw -match "^\\d+$") { $queriedPorts += [int]$raw }',
'}',
'$knownCommandLines = @{}',
'if ($env:GENARRATIVE_KNOWN_COMMAND_LINES) {',
' try {',
' foreach ($property in (ConvertFrom-Json $env:GENARRATIVE_KNOWN_COMMAND_LINES).PSObject.Properties) {',
' $knownCommandLines[[int]$property.Name] = [string]$property.Value',
' }',
' } catch { }',
'}',
'$listenerPidByPort = @{}',
'foreach ($line in (netstat -ano -p tcp)) {',
' $fields = @($line -split "\\s+" | Where-Object { $_ })',
' if ($fields.Count -lt 4) { continue }',
' if ($fields[0] -ne "TCP") { continue }',
' # A listening socket always has foreign address 0.0.0.0:0 / [::]:0, which',
' # is locale-independent unlike the localized netstat State column.',
' if ($fields[2] -notmatch ":0$") { continue }',
' $localPort = [int]($fields[1].Split(":")[-1])',
' if ($queriedPorts -notcontains $localPort) { continue }',
' # The PID is the last column; do not hardcode its index.',
' if ($fields[-1] -notmatch "^\\d+$") { continue }',
' $listenerPidByPort[$localPort] = [int]$fields[-1]',
'}',
'$result = @()',
'foreach ($port in ($listenerPidByPort.Keys | Sort-Object)) {',
' $processId = $listenerPidByPort[$port]',
' $name = $null',
' $executablePath = $null',
' $commandLine = $null',
' try {',
' $process = [System.Diagnostics.Process]::GetProcessById($processId)',
' $name = $process.ProcessName + ".exe"',
' try { $executablePath = $process.MainModule.FileName } catch { }',
' } catch { }',
' if ($knownCommandLines.ContainsKey($processId)) {',
' $commandLine = $knownCommandLines[$processId]',
' } elseif (($name -like "spacetime*") -or (-not $executablePath)) {',
' try { $commandLine = (Get-CimInstance Win32_Process -Filter ("ProcessId=" + $processId)).CommandLine } catch { }',
' }',
' $result += [pscustomobject]@{ port = [int]$port; processId = $processId; name = $name; executablePath = $executablePath; commandLine = $commandLine }',
'}',
'ConvertTo-Json -InputObject @($result) -Compress',
].join('\n');
// 进程命令行在进程生命周期内不变,但 PID 会被系统复用;按 PID 记 TTL 缓存,
// 让"等配套后端就绪"的轮询只在首个周期付出 WMI 成本。TTL 取 5 分钟:本轮实测
// 这台机器上首次 WMI 调用约 18 秒(热调用 3.3 秒),而 PID 在 5 分钟内被复用
// 成另一个运行本工作树 data dir 的 SpacetimeDB 才能造成误判,概率可忽略。
// 默认实现才缓存,注入实现(测试)与显式 env 始终重新读取。
const WINDOWS_COMMAND_LINE_CACHE_TTL_MS = 300_000;
const windowsPortOwnerCommandLineCache = new Map();
function resolveCommandLineCache({ spawnImpl, env }) {
return spawnImpl === spawnSync && env === process.env
? windowsPortOwnerCommandLineCache
: new Map();
}
// 读取端口当前真正的监听进程身份。返回 null 表示探测本身不可用(例如系统缺少
// netstat),此时调用方必须退化为旧行为,不能让本地启动直接失败。
function readWindowsPortOwnerIdentities(
ports,
{ spawnImpl = spawnSync, env = process.env } = {},
{
spawnImpl = spawnSync,
env = process.env,
now = Date.now,
commandLineTtlMs = WINDOWS_COMMAND_LINE_CACHE_TTL_MS,
commandLineCache = resolveCommandLineCache({ spawnImpl, env }),
} = {},
) {
const uniquePorts = [...new Set(ports.filter((port) => port > 0))];
if (uniquePorts.length === 0) {
return null;
}
const command = [
'$ErrorActionPreference = "SilentlyContinue"',
'$ports = ($env:GENARRATIVE_QUERY_PORTS -split ",") | Where-Object { $_ }',
'$result = @()',
'foreach ($port in $ports) {',
' $connection = Get-NetTCPConnection -State Listen -LocalPort ([int]$port) -ErrorAction SilentlyContinue | Select-Object -First 1',
' if (-not $connection) { continue }',
' $owner = Get-CimInstance Win32_Process -Filter ("ProcessId=" + $connection.OwningProcess) -ErrorAction SilentlyContinue',
' $result += [pscustomobject]@{ port = [int]$port; processId = [int]$connection.OwningProcess; name = $owner.Name; executablePath = $owner.ExecutablePath; commandLine = $owner.CommandLine }',
'}',
'ConvertTo-Json -InputObject @($result) -Compress',
].join('\n');
const knownCommandLines = {};
for (const [processId, record] of [...commandLineCache]) {
if (record && now() - record.at < commandLineTtlMs) {
knownCommandLines[processId] = record.commandLine;
} else {
commandLineCache.delete(processId);
}
}
const childEnv = {
...env,
GENARRATIVE_QUERY_PORTS: uniquePorts.join(','),
};
if (Object.keys(knownCommandLines).length > 0) {
childEnv.GENARRATIVE_KNOWN_COMMAND_LINES =
JSON.stringify(knownCommandLines);
}
const result = spawnImpl(
'powershell.exe',
['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', command],
[
'-NoProfile',
'-ExecutionPolicy',
'Bypass',
'-Command',
windowsPortOwnerProbeCommand,
],
{
encoding: 'utf8',
env: { ...env, GENARRATIVE_QUERY_PORTS: uniquePorts.join(',') },
env: childEnv,
maxBuffer: 8 * 1024 * 1024,
},
);
@@ -240,9 +330,22 @@ function readWindowsPortOwnerIdentities(
const owners = new Map();
for (const entry of parseWindowsProcessSnapshot(result.stdout)) {
const port = Number(entry?.port);
if (Number.isInteger(port) && port > 0) {
owners.set(port, entry);
if (!Number.isInteger(port) || port <= 0) {
continue;
}
const processId = Number(entry?.processId);
if (
Number.isInteger(processId) &&
processId > 0 &&
typeof entry?.commandLine === 'string' &&
entry.commandLine
) {
commandLineCache.set(processId, {
commandLine: entry.commandLine,
at: now(),
});
}
owners.set(port, entry);
}
return owners;
}
@@ -879,10 +982,102 @@ async function startVite(apiTarget, endpoint = readAgcDevEndpoint()) {
);
}
function readAdminWebEnabled(env = process.env) {
return String(env[agcDevAdminWebEnvKey] ?? '').trim() !== '0';
}
// 后台 Web 与 AGC Vite 一样直接由本启动器持有,不经过 `dev.mjs admin-web`
// 后者会整体重写 `.app/dev-stack.json`,把本次配套后端的状态覆盖掉。
function startAdminWeb(
apiUrl,
endpoint,
{ env = process.env, spawnImpl = spawnChild } = {},
) {
return spawnImpl(
npm,
[
'--prefix',
'../..',
'exec',
'vite',
'--',
'--host',
endpoint.host,
'--port',
String(endpoint.port),
'--strictPort',
],
{
cwd: adminWebDir,
env: {
...env,
ADMIN_API_TARGET: apiUrl,
GENARRATIVE_API_TARGET: apiUrl,
GENARRATIVE_API_PORT: String(urlPort(apiUrl) || 8082),
ADMIN_WEB_BASE: endpoint.basePath,
},
},
);
}
function formatStartupSummary({
frontendUrl = '',
apiUrl = '',
adminWebUrl = '',
spacetimeUrl = '',
bgfilterWorkerUrl = '',
} = {}) {
const segments = [
['前端', frontendUrl],
['后端', apiUrl],
['后台', adminWebUrl],
['数据库', spacetimeUrl],
['bgfilter-worker', bgfilterWorkerUrl],
]
.filter(([, value]) => Boolean(value))
.map(([label, value]) => `${label} ${value}`);
return `[ai-game-creator-shell] 启动汇总: ${segments.join(' | ')}`;
}
// 后台 Web 是可选联调服务:端口解析或启动失败只告警,不能阻断 AGC 客户端与配套后端。
async function ensureAdminWeb({
apiUrl,
reservedPorts = [],
env = process.env,
enabled = readAdminWebEnabled(env),
resolveEndpoint = resolveAgcAdminWebEndpoint,
spawnAdminWeb = startAdminWeb,
waitForExit = waitForChildTermination,
warn = (message) => console.warn(message),
} = {}) {
if (!enabled) {
return { endpoint: null, child: null };
}
try {
const endpoint = await resolveEndpoint({ env, reservedPorts });
const child = spawnAdminWeb(apiUrl, endpoint, { env });
waitForExit(child).then((failure) => {
warn(
`[ai-game-creator-shell] 后台 Web 已退出(${formatChildFailure(failure)}),AGC 继续运行。`,
);
});
return { endpoint, child };
} catch (error) {
warn(
`[ai-game-creator-shell] 后台 Web 未能启动(${
error instanceof Error ? error.message : String(error)
}),AGC 继续运行。`,
);
return { endpoint: null, child: null };
}
}
async function main() {
let backendChild = null;
let startedBackend = false;
let viteChild = null;
let adminWebChild = null;
let shutdownSignal = '';
const signalHandlers = new Map();
@@ -905,6 +1100,7 @@ async function main() {
const handler = () => {
shutdownSignal = signal;
stopChild(viteChild, signal);
stopChild(adminWebChild, signal);
stopChild(backendChild, signal);
// 立刻清扫,避免外层 taskkill /F 抢在 finally 之前把本进程杀掉。
sweepStartedBackend();
@@ -937,6 +1133,25 @@ async function main() {
throw new Error(`启动期收到 ${shutdownSignal},已停止前端服务`);
}
const adminWeb = await ensureAdminWeb({
apiUrl: backend.targets.apiUrl,
// AGC Vite 端口尚未监听,必须显式保留,避免被后台 Web 抢先占用。
reservedPorts: [endpoint.port],
});
adminWebChild = adminWeb.child;
if (shutdownSignal) {
throw new Error(`启动期收到 ${shutdownSignal},已停止后台 Web`);
}
console.log(
formatStartupSummary({
frontendUrl: endpoint.url,
apiUrl: backend.targets.apiUrl,
adminWebUrl: adminWeb.endpoint?.url ?? '',
spacetimeUrl: backend.targets.spacetimeUrl,
bgfilterWorkerUrl: backend.targets.bgfilterWorkerUrl,
}),
);
const children = [backendChild, viteChild].filter(Boolean);
if (children.length === 0) {
return 0;
@@ -946,10 +1161,12 @@ async function main() {
children.map((child) => waitForChildTermination(child)),
);
stopChild(viteChild);
stopChild(adminWebChild);
stopChild(backendChild);
return failure.type === 'error' || failure.signal ? 1 : (failure.code ?? 0);
} catch (error) {
stopChild(viteChild);
stopChild(adminWebChild);
stopChild(backendChild);
console.error(
`[ai-game-creator-shell] ${error instanceof Error ? error.message : String(error)}`,
@@ -958,6 +1175,7 @@ async function main() {
} finally {
await Promise.all([
terminateChildTree(viteChild),
terminateChildTree(adminWebChild),
terminateChildTree(backendChild),
]);
sweepStartedBackend();
@@ -975,9 +1193,12 @@ function isDirectModuleExecution() {
}
export {
agcDevAdminWebEnvKey,
ensureAdminWeb,
ensureBackend,
formatChildFailure,
formatOwnerLabel,
formatStartupSummary,
isAiGameCreatorServer,
isBackendReady,
isDirectModuleExecution,
@@ -985,6 +1206,7 @@ export {
isWorktreeApiServerOwner,
isWorktreeSpacetimeOwner,
preflightExistingVite,
readAdminWebEnabled,
readBackendServiceFailure,
readChildFailure,
readExistingViteServer,
@@ -993,6 +1215,7 @@ export {
resolveBackendTargetsFromState,
runWindowsTaskkill,
spawnChild,
startAdminWeb,
stopChild,
terminateChildTree,
verifyAgcBackendOwnership,
-2
View File
@@ -4900,8 +4900,6 @@ dependencies = [
"serde",
"serde_json",
"sha2",
"tracing",
"ts-rs",
]
[[package]]
@@ -14,7 +14,7 @@ cocos-editor-injection = ["cocos-editor-execute", "cocos-editor-bridge/windows-i
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
shared-contracts = { path = "../../../server-rs/crates/shared-contracts", default-features = false, features = ["ts-bindings"] }
shared-contracts = { path = "../../../server-rs/crates/shared-contracts", default-features = false }
tauri-build = { version = "2.6.2", features = [] }
[dependencies]
@@ -50,7 +50,7 @@ portable-pty = "0.9"
percent-encoding = "2"
reqwest = { version = "0.12", default-features = false, features = ["json", "multipart", "native-tls", "stream"] }
regex = "1"
shared-contracts = { path = "../../../server-rs/crates/shared-contracts", default-features = false, features = ["ts-bindings"] }
shared-contracts = { path = "../../../server-rs/crates/shared-contracts", default-features = false }
tauri = { version = "2.11.2", features = [] }
tauri-plugin-dialog = "2.7.1"
tauri-plugin-http = { version = "2.5.9", default-features = false, features = ["charset", "cookies", "http2", "rustls-tls"] }
@@ -16,7 +16,7 @@ mod design_runtime;
mod design_tools;
mod direct_codex_attachments;
mod direct_codex_audit;
mod direct_codex_references;
mod direct_codex_user_item;
mod direct_project_history;
mod direct_project_turn_history;
mod direct_runtime;
@@ -44,7 +44,7 @@ pub(crate) use codex_provider_proxy::*;
pub(crate) use design_runtime::*;
pub(crate) use direct_codex_attachments::*;
pub(crate) use direct_codex_audit::*;
pub(crate) use direct_codex_references::*;
pub(crate) use direct_codex_user_item::*;
pub(crate) use direct_project_history::*;
pub(crate) use direct_project_turn_history::*;
pub(crate) use direct_runtime::*;
@@ -0,0 +1,32 @@
//! DirectProject 历史注入载荷的单一构造 seam。
//!
//! 历史读取与大小前置校验集中在这里;调用方只负责线程生命周期与 RPC 传输。
use super::super::*;
use super::direct_project_history_injection_oversize_error;
use serde_json::Value;
use std::path::Path;
pub(super) fn build_direct_project_history_injection_params(
history_root: &Path,
thread_id: &str,
) -> Result<Value, platform_llm::LlmError> {
let canonical_items = read_direct_project_history_items_at(history_root)
.map_err(platform_llm::LlmError::InvalidRequest)?;
let items = canonical_items
.iter()
.map(|item| {
direct_codex_user_item_to_response_item(history_root, item)
.map_err(platform_llm::LlmError::InvalidRequest)
})
.collect::<Result<Vec<_>, _>>()?;
let params = serde_json::json!({"threadId": thread_id, "items": items});
let payload_bytes = serde_json::to_vec(&params)
.map(|bytes| bytes.len().saturating_add(1))
.unwrap_or(usize::MAX);
// 注入前的前置校验:失败关闭并指名 itemId 与字节数,**不截断、不摘要、不改写**。
if let Some(error) = direct_project_history_injection_oversize_error(&params, payload_bytes) {
return Err(platform_llm::LlmError::InvalidRequest(error));
}
Ok(params)
}
@@ -0,0 +1,50 @@
//! DirectProject 线程池身份的 canonical 解析与摘要。
use super::super::*;
use sha2::{Digest, Sha256};
pub(super) fn direct_codex_canonical_project_identity(
root: &std::path::Path,
) -> Result<(std::path::PathBuf, String), String> {
let (canonical_root, _) = resolve_direct_codex_project_authority(root)?;
let manifest = read_manifest(&canonical_root.join(".agent/manifest.json"))
.map_err(|error| format!("读取 DirectProject 权威项目身份失败:{error}"))?;
let manifest_project_id = manifest.project_id.trim();
if manifest_project_id.is_empty() || manifest_project_id.chars().count() > 256 {
return Err("DirectProject manifest.projectId 不满足身份边界".to_string());
}
let path_identity = direct_codex_os_path_identity_bytes(&canonical_root);
Ok((
canonical_root,
direct_codex_project_identity_digest(&path_identity, manifest_project_id.as_bytes()),
))
}
fn direct_codex_os_path_identity_bytes(path: &std::path::Path) -> Vec<u8> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
return path.as_os_str().as_bytes().to_vec();
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let mut bytes = Vec::new();
for unit in path.as_os_str().encode_wide() {
bytes.extend_from_slice(&unit.to_le_bytes());
}
return bytes;
}
#[cfg(not(any(unix, windows)))]
path.as_os_str().to_string_lossy().as_bytes().to_vec()
}
fn direct_codex_project_identity_digest(path_identity: &[u8], project_id: &[u8]) -> String {
let mut digest = Sha256::new();
digest.update(b"genarrative-direct-project-identity.v1\0");
digest.update((path_identity.len() as u64).to_le_bytes());
digest.update(path_identity);
digest.update((project_id.len() as u64).to_le_bytes());
digest.update(project_id);
format!("{:x}", digest.finalize())
}
@@ -10,6 +10,11 @@ use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufR
use tokio::sync::{mpsc, oneshot, Mutex, Notify};
use uuid::Uuid;
mod direct_project_history_wire;
use direct_project_history_wire::build_direct_project_history_injection_params;
mod direct_project_identity;
use direct_project_identity::*;
const GAME_CREATOR_CODEX_APP_SERVER_PROVIDER_ID: &str = "genarrative_agc";
const GAME_CREATOR_CODEX_APP_SERVER_API_KEY_ENV: &str = "GENARRATIVE_AGC_CODEX_API_KEY";
const GAME_CREATOR_CODEX_APP_SERVER_REMOTE_CONTROL_DISABLED_ENV: &str =
@@ -2620,6 +2625,7 @@ impl CodexAppServerConnection {
request,
None,
None,
None,
on_agent_message_delta,
direct_observer,
audit,
@@ -2634,6 +2640,7 @@ impl CodexAppServerConnection {
request: LlmRunRequest,
direct_history_root: Option<&std::path::Path>,
direct_client_turn_id: Option<&str>,
direct_user_item: Option<&serde_json::Value>,
mut on_agent_message_delta: Option<&mut (dyn FnMut(&platform_llm::LlmStreamDelta) + Send)>,
mut direct_observer: Option<&mut (dyn FnMut(DirectCodexTurnObservation) + Send)>,
mut audit: Option<&mut DirectCodexTurnAudit>,
@@ -2649,12 +2656,19 @@ impl CodexAppServerConnection {
));
}
if let Some(client_turn_id) = direct_client_turn_id {
let user_item = direct_project_local_message_item(
"user",
current_prompt,
Some(&format!("direct-codex:{client_turn_id}:user")),
)
.map_err(platform_llm::LlmError::InvalidRequest)?;
let user_item = match direct_user_item {
Some(item) => {
direct_codex_user_item_to_response_item(history_root, item)
.map_err(platform_llm::LlmError::InvalidRequest)?;
item.clone()
}
None => direct_project_local_message_item(
"user",
current_prompt,
Some(&format!("direct-codex:{client_turn_id}:user")),
)
.map_err(platform_llm::LlmError::InvalidRequest)?,
};
append_direct_project_user_message_at(history_root, &user_item)
.map_err(platform_llm::LlmError::InvalidRequest)?;
}
@@ -2664,24 +2678,14 @@ impl CodexAppServerConnection {
let thread_id = thread_lease.thread_id.clone();
if self.inner.workspace_mode == CodexAppServerWorkspaceMode::DirectProject {
if thread_created {
let items = match read_direct_project_history_items_at(history_root) {
Ok(items) => items,
Err(error) => {
self.release_thread(snapshot, &thread_id).await;
return Err(platform_llm::LlmError::InvalidRequest(error));
}
};
let params = serde_json::json!({"threadId": thread_id.clone(), "items": items});
let payload_bytes = serde_json::to_vec(&params)
.map(|bytes| bytes.len().saturating_add(1))
.unwrap_or(usize::MAX);
// 注入前的前置校验:失败关闭并指名 itemId 与字节数,**不截断、不摘要、不改写**。
if let Some(error) =
direct_project_history_injection_oversize_error(&params, payload_bytes)
{
self.release_thread(snapshot, &thread_id).await;
return Err(platform_llm::LlmError::InvalidRequest(error));
}
let params =
match build_direct_project_history_injection_params(history_root, &thread_id) {
Ok(params) => params,
Err(error) => {
self.release_thread(snapshot, &thread_id).await;
return Err(error);
}
};
if let Err(error) = self.request("thread/inject_items", params).await {
self.release_thread(snapshot, &thread_id).await;
return Err(platform_llm::LlmError::Transport(error));
@@ -2829,6 +2833,8 @@ impl CodexAppServerConnection {
callback(&platform_llm::LlmStreamDelta {
accumulated_text: streamed_text.clone(),
delta_text: delta,
accumulated_reasoning: String::new(),
reasoning_delta: String::new(),
finish_reason: None,
});
}
@@ -3133,6 +3139,7 @@ fn parse_game_creator_codex_app_server_text(
} else {
String::new()
},
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id: Some(thread_id.to_string()),
usage: None,
@@ -3709,6 +3716,7 @@ pub(crate) async fn direct_game_creator_codex_chat_at(
None,
None,
None,
None,
)
.await
}
@@ -3726,56 +3734,11 @@ pub(crate) async fn direct_game_creator_codex_chat_at_with_observer(
None,
Some(observer),
None,
None,
)
.await
}
fn direct_codex_canonical_project_identity(
root: &std::path::Path,
) -> Result<(std::path::PathBuf, String), String> {
let (canonical_root, _) = resolve_direct_codex_project_authority(root)?;
let manifest = read_manifest(&canonical_root.join(".agent/manifest.json"))
.map_err(|error| format!("读取 DirectProject 权威项目身份失败:{error}"))?;
let manifest_project_id = manifest.project_id.trim();
if manifest_project_id.is_empty() || manifest_project_id.chars().count() > 256 {
return Err("DirectProject manifest.projectId 不满足身份边界".to_string());
}
let path_identity = direct_codex_os_path_identity_bytes(&canonical_root);
Ok((
canonical_root,
direct_codex_project_identity_digest(&path_identity, manifest_project_id.as_bytes()),
))
}
fn direct_codex_os_path_identity_bytes(path: &std::path::Path) -> Vec<u8> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
return path.as_os_str().as_bytes().to_vec();
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let mut bytes = Vec::new();
for unit in path.as_os_str().encode_wide() {
bytes.extend_from_slice(&unit.to_le_bytes());
}
return bytes;
}
#[cfg(not(any(unix, windows)))]
path.as_os_str().to_string_lossy().as_bytes().to_vec()
}
fn direct_codex_project_identity_digest(path_identity: &[u8], project_id: &[u8]) -> String {
let mut digest = Sha256::new();
digest.update(b"genarrative-direct-project-identity.v1\0");
digest.update((path_identity.len() as u64).to_le_bytes());
digest.update(path_identity);
digest.update((project_id.len() as u64).to_le_bytes());
digest.update(project_id);
format!("{:x}", digest.finalize())
}
pub(crate) async fn direct_game_creator_codex_chat_at_with_optional_observer(
root: &std::path::Path,
system_prompt: String,
@@ -3783,6 +3746,7 @@ pub(crate) async fn direct_game_creator_codex_chat_at_with_optional_observer(
client_turn_id: Option<&str>,
observer: Option<&mut (dyn FnMut(DirectCodexTurnObservation) + Send)>,
audit: Option<&mut DirectCodexTurnAudit>,
direct_user_item: Option<serde_json::Value>,
) -> Result<String, String> {
// Resolve project authority before deriving the pool/thread identity. A
// caller may hold a stable symlink path whose target changes between
@@ -3846,6 +3810,7 @@ pub(crate) async fn direct_game_creator_codex_chat_at_with_optional_observer(
request,
Some(&codex_root),
effective_client_turn_id,
direct_user_item.as_ref(),
None,
observer,
audit,
@@ -589,6 +589,7 @@ fn parse_game_creator_codex_cli_response(
} else {
String::new()
},
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id,
usage,
@@ -49,6 +49,18 @@ pub(crate) struct DesignView {
messages: Vec<DesignMessage>,
running: bool,
can_retry: bool,
#[serde(skip_serializing_if = "Option::is_none")]
reasoning_text: Option<String>,
reasoning_entries: Vec<DesignReasoningEntry>,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct DesignReasoningEntry {
id: String,
text: String,
#[serde(skip_serializing_if = "Option::is_none")]
message_id: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
@@ -65,6 +77,7 @@ pub(crate) struct DesignEvent {
}
fn design_view(session: &DesignSession, running: bool) -> DesignView {
let reasoning_entries = persisted_design_reasoning_entries(session);
DesignView {
session: DesignSessionSummary {
session_id: session.session_id.clone(),
@@ -82,9 +95,124 @@ fn design_view(session: &DesignSession, running: bool) -> DesignView {
&& session.turn.as_ref().is_some_and(|turn| turn.pending)
&& session.pending_approval.is_none()
&& session.pending_clarification.is_none(),
reasoning_text: reasoning_entries.last().map(|entry| entry.text.clone()),
reasoning_entries,
}
}
fn reasoning_text_from_history_item(item: &Value) -> Option<String> {
if item.get("type").and_then(Value::as_str) != Some("reasoning") {
return None;
}
let mut text = String::new();
if let Some(summary) = item.get("summary").and_then(Value::as_array) {
for part in summary {
if let Some(value) = part.get("text").and_then(Value::as_str) {
text.push_str(value.trim());
}
}
}
if let Some(content) = item.get("content").and_then(Value::as_array) {
for part in content {
let part_type = part.get("type").and_then(Value::as_str).unwrap_or_default();
if matches!(
part_type,
"reasoning" | "reasoning_content" | "reasoning_text" | "analysis" | "thinking"
) {
if let Some(value) = part.get("text").and_then(Value::as_str) {
text.push_str(value.trim());
}
}
}
}
(!text.trim().is_empty()).then_some(text)
}
fn persisted_design_reasoning_entries(session: &DesignSession) -> Vec<DesignReasoningEntry> {
// Responses history contains tool-only provider responses. Their reasoning is
// followed by function calls and only the next provider response may contain
// visible assistant text, so pairing on the next `message` item makes the
// earlier reasoning look like an orphan and moves it to the bottom of the UI.
// Both persisted streams retain user-turn boundaries; pair reasoning and
// visible assistant messages by their response order within each turn.
let mut assistant_groups: Vec<Vec<String>> = vec![Vec::new()];
for message in &session.messages {
if message.role == "user" {
assistant_groups.push(Vec::new());
} else if message.role == "assistant" {
assistant_groups
.last_mut()
.expect("assistant group always exists")
.push(message.id.clone());
}
}
let mut entries = Vec::new();
let mut group_index = 0;
let mut assistant_index = 0;
let mut sequence = 0_u64;
let mut current_reasoning = Vec::new();
let mut pending_reasoning = Vec::new();
let mut saw_response_output = false;
for item in &session.history {
if item.get("role").and_then(Value::as_str) == Some("user") {
if !pending_reasoning.is_empty() || !current_reasoning.is_empty() {
pending_reasoning.append(&mut current_reasoning);
}
group_index += 1;
assistant_index = 0;
saw_response_output = false;
continue;
}
if item.get("type").and_then(Value::as_str) == Some("reasoning") {
if saw_response_output {
pending_reasoning.append(&mut current_reasoning);
saw_response_output = false;
}
if let Some(text) = reasoning_text_from_history_item(item) {
sequence += 1;
current_reasoning.push(DesignReasoningEntry {
id: item
.get("id")
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("reasoning-{sequence}")),
text,
message_id: None,
});
}
continue;
}
if item.get("role").and_then(Value::as_str) == Some("assistant")
|| item.get("type").and_then(Value::as_str) == Some("message")
{
pending_reasoning.extend(current_reasoning.drain(..));
let assistant_id = assistant_groups
.get(group_index)
.and_then(|ids| ids.get(assistant_index))
.cloned();
assistant_index += 1;
for mut entry in pending_reasoning.drain(..) {
entry.message_id = assistant_id.clone();
entries.push(entry);
}
saw_response_output = false;
} else if item.get("type").is_some() {
saw_response_output = true;
}
}
pending_reasoning.append(&mut current_reasoning);
let fallback_id = assistant_groups
.get(group_index)
.and_then(|ids| ids.last())
.cloned();
for mut entry in pending_reasoning {
entry.message_id = fallback_id.clone();
entries.push(entry);
}
entries
}
fn design_event(
root: &Path,
turn_id: &str,
@@ -104,6 +232,17 @@ fn design_event(
}
}
fn design_reasoning_event(
root: &Path,
turn_id: &str,
id: Option<&str>,
reasoning: String,
) -> DesignEvent {
let mut event = design_event(root, turn_id, "reasoning", id, None, None);
event.reasoning_text = Some(reasoning);
event
}
fn design_project_id(root: &Path) -> Result<String, String> {
validate_project_root(root)?;
Ok(read_existing_manifest_for_project(root)?.project_id)
@@ -462,6 +601,7 @@ fn build_design_request(
.with_tool_choice(platform_llm::LlmToolChoice::Auto)
.with_web_search(false);
apply_game_creator_llm_reasoning_effort(request, llm)
.map(|request| request.with_reasoning_capture(true))
}
// 调试队列只接收副本,写盘慢或失败时丢弃,不参与会话恢复。
@@ -548,8 +688,15 @@ async fn request_design_provider(
Some(String::new()),
None,
));
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
String::new(),
));
let result = if llm.stream {
let mut stream_sequence = 0_u64;
let mut emitted_reasoning = String::new();
client
.stream_run(request.clone(), |delta| {
stream_sequence = stream_sequence.saturating_add(1);
@@ -565,18 +712,33 @@ async fn request_design_provider(
"model": llm.model,
"deltaChars": delta.delta_text.chars().count(),
"accumulatedChars": delta.accumulated_text.chars().count(),
"reasoningDeltaChars": delta.reasoning_delta.chars().count(),
"reasoningAccumulatedChars": delta.accumulated_reasoning.chars().count(),
"deltaText": delta.delta_text,
"finishReason": delta.finish_reason,
}),
);
emit(design_event(
root,
&turn_id,
"text",
Some(&message_id),
Some(delta.accumulated_text.clone()),
None,
));
if !delta.delta_text.is_empty() || delta.finish_reason.is_some() {
emit(design_event(
root,
&turn_id,
"text",
Some(&message_id),
Some(delta.accumulated_text.clone()),
None,
));
}
if !delta.reasoning_delta.is_empty()
|| delta.accumulated_reasoning != emitted_reasoning
{
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
delta.accumulated_reasoning.clone(),
));
emitted_reasoning = delta.accumulated_reasoning.clone();
}
})
.await
} else {
@@ -584,6 +746,14 @@ async fn request_design_provider(
};
match result {
Ok(response) => {
if !response.reasoning.is_empty() {
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
response.reasoning.clone(),
));
}
design_debug(
root,
"response",
@@ -606,6 +776,12 @@ async fn request_design_provider(
|| game_creator_agent_runtime_transient_provider_error_kind(&error, false)
.is_none()
{
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
String::new(),
));
return Err(detail);
}
tokio::time::sleep(Duration::from_millis(
@@ -654,8 +830,24 @@ async fn request_scripted_design_provider(
Some(String::new()),
None,
));
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
String::new(),
));
match fake_provider::take() {
Some(Ok(response)) => return Ok(response),
Some(Ok(response)) => {
if !response.reasoning.is_empty() {
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
response.reasoning.clone(),
));
}
return Ok(response);
}
Some(Err(error)) => {
let detail = redact_agent_runtime_error(
root,
@@ -666,10 +858,24 @@ async fn request_scripted_design_provider(
|| game_creator_agent_runtime_transient_provider_error_kind(&error, false)
.is_none()
{
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
String::new(),
));
return Err(detail);
}
}
None => return Err("假 Provider 脚本耗尽".into()),
None => {
emit(design_reasoning_event(
root,
&turn_id,
Some(&message_id),
String::new(),
));
return Err("假 Provider 脚本耗尽".into());
}
}
}
unreachable!()
@@ -940,7 +1146,9 @@ pub(crate) fn set_design_agent_runtime_mode(
"design.runtime-mode",
)?;
if active_runtime.trim() == "game" {
crate::assets::register_design_artifacts_at(root)?;
if crate::assets::register_design_artifacts_at(root)? {
advance_agent_runtime_project_revision_locked(root)?;
}
}
write_design_runtime_mode(root, active_runtime.trim())
}
@@ -1176,6 +1384,38 @@ mod tests {
let error = ensure_design_runtime_active(root).expect_err("game mode must reject design");
assert!(error.contains("游戏运行态"));
}
#[test]
fn switching_to_game_pairs_design_artifact_registration_with_revision() {
let temporary = tempfile::tempdir().expect("create runtime mode root");
let root = temporary.path();
crate::project::init_local_game_project_at(root, "design-switch-test", "策划切换")
.expect("init project");
fs::create_dir_all(root.join("design_artifacts/project")).expect("create artifacts");
fs::write(root.join("design_artifacts/project/design.md"), "设计内容")
.expect("write artifact");
let before = read_game_creator_agent_runtime_project_revision(root)
.expect("read initial revision")
.revision;
assert_eq!(
set_design_agent_runtime_mode(root.to_string_lossy().into_owned(), "game".to_string(),)
.expect("switch to game")
.active_runtime,
"game"
);
let after = read_game_creator_agent_runtime_project_revision(root)
.expect("read committed revision")
.revision;
assert_eq!(after, before + 1);
set_design_agent_runtime_mode(root.to_string_lossy().into_owned(), "game".to_string())
.expect("repeat switch to game");
let repeated = read_game_creator_agent_runtime_project_revision(root)
.expect("read repeated revision")
.revision;
assert_eq!(repeated, after);
}
use serde_json::json;
use std::fs;
@@ -1285,6 +1525,7 @@ mod tests {
provider: platform_llm::LlmProvider::OpenAiCompatible,
model: "fake-design".into(),
text: text.into(),
reasoning: String::new(),
finish_reason: Some(if calls.is_empty() {
"stop".into()
} else {
@@ -1345,6 +1586,110 @@ mod tests {
.clone()
}
#[test]
fn design_request_enables_reasoning_capture_only_for_design_runtime() {
let session = new_design_session("project", "quality");
let request = build_design_request(&session, &pack(), &GameCreatorLlmConfig::default())
.expect("design request");
assert!(request.capture_reasoning);
}
#[test]
fn persisted_reasoning_follows_response_order_across_tool_only_responses() {
let mut session = new_design_session("project", "quality");
session.messages = vec![
DesignMessage {
id: "turn:user".into(),
role: "user".into(),
text: "需求".into(),
},
DesignMessage {
id: "call-1:tool".into(),
role: "tool".into(),
text: "读取资源".into(),
},
DesignMessage {
id: "turn:response:0".into(),
role: "assistant".into(),
text: "给出方案".into(),
},
];
session.history = vec![
json!({"role":"user", "content":"需求"}),
json!({"type":"reasoning", "id":"r1", "content":[{"type":"reasoning_text", "text":"第一段思考"}]}),
json!({"type":"function_call", "call_id":"call-1", "name":"read_resource", "arguments":"{}"}),
json!({"type":"reasoning", "id":"r2", "content":[{"type":"reasoning_text", "text":"第二段思考"}]}),
json!({"type":"message", "role":"assistant", "content":[{"type":"output_text", "text":"给出方案"}]}),
];
let entries = persisted_design_reasoning_entries(&session);
assert_eq!(
entries
.iter()
.map(|entry| (entry.id.as_str(), entry.message_id.as_deref()))
.collect::<Vec<_>>(),
vec![
("r1", Some("turn:response:0")),
("r2", Some("turn:response:0")),
]
);
}
#[tokio::test(flavor = "current_thread")]
async fn scripted_design_provider_emits_reasoning_without_persisting_it() {
let (_temp, root, _resources) = init_design_project();
let mut session = new_design_session("design-fake", "quality");
begin_design_turn(&mut session, "turn-reasoning");
let mut response = fake_response("reasoning", "正文", Vec::new());
response.reasoning = "先分析需求,再组织方案。".into();
let _fake = fake_provider::install(vec![Ok(response)], 0);
let mut events = Vec::new();
let response =
request_scripted_design_provider(&root, &mut session, &mut |event| events.push(event))
.await
.expect("scripted provider");
let reasoning_events = events
.iter()
.filter_map(|event| event.reasoning_text.as_deref())
.collect::<Vec<_>>();
assert_eq!(reasoning_events, vec!["", "先分析需求,再组织方案。"]);
assert_eq!(response.text, "正文");
assert!(session.history.is_empty());
}
#[tokio::test(flavor = "current_thread")]
async fn scripted_design_provider_retry_clears_previous_reasoning_attempt() {
let (_temp, root, _resources) = init_design_project();
let mut session = new_design_session("design-fake", "quality");
begin_design_turn(&mut session, "turn-reasoning-retry");
let mut response = fake_response("reasoning-retry", "重试后的正文", Vec::new());
response.reasoning = "重试后的推理".into();
let _fake = fake_provider::install(
vec![
Err(platform_llm::LlmError::Upstream {
status_code: 503,
message: "busy".into(),
}),
Ok(response),
],
1,
);
let mut events = Vec::new();
let response =
request_scripted_design_provider(&root, &mut session, &mut |event| events.push(event))
.await
.expect("scripted retry provider");
let reasoning_events = events
.iter()
.filter_map(|event| event.reasoning_text.as_deref())
.collect::<Vec<_>>();
assert_eq!(reasoning_events, vec!["", "", "重试后的推理"]);
assert_eq!(response.text, "重试后的正文");
assert!(session.history.is_empty());
}
#[tokio::test(flavor = "current_thread")]
async fn fake_provider_walks_five_phases_and_enters_consultant() {
let (_temp, root, resources) = init_design_project();
@@ -1,427 +0,0 @@
use super::*;
use crate::ui_editor::persistence::{
generate_ui_design_code_at, GenerateUiDesignCodeInput, UI_DESIGN_DOC_ASSET_KIND,
UI_DESIGN_DOC_MEDIA_TYPE,
};
pub(crate) const MAX_DIRECT_CODEX_REFERENCES: usize = 32;
const MAX_DIRECT_CODEX_REFERENCE_ID_CHARS: usize = 200;
const MAX_DIRECT_CODEX_REFERENCE_LABEL_CHARS: usize = 160;
const MAX_DIRECT_CODEX_REFERENCE_SOURCE_CHARS: usize = 32;
const MAX_DIRECT_CODEX_REFERENCE_ELEMENT_CHARS: usize = 80;
const MAX_DIRECT_CODEX_REFERENCE_TEXT_CHARS: usize = 240;
const DIRECT_CODEX_REFERENCE_HEADER: &str =
"[本轮用户引用素材:以下均为当前项目已确认的安全引用。请使用稳定资源 ID 和项目相对路径读取,不要读取或输出其它路径。]";
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase", tag = "type")]
pub(crate) enum DirectCodexTurnReference {
#[serde(rename = "resource")]
Resource(DirectCodexResourceReference),
#[serde(rename = "runtime-region")]
RuntimeRegion(DirectCodexRuntimeRegionReference),
}
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct DirectCodexResourceReference {
pub(crate) resource_id: String,
#[serde(default)]
pub(crate) label: Option<String>,
#[serde(default)]
pub(crate) source: Option<String>,
}
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct DirectCodexRuntimeRegionReference {
#[serde(default)]
pub(crate) label: Option<String>,
#[serde(default)]
pub(crate) run_id: Option<String>,
#[serde(default)]
pub(crate) version_id: Option<String>,
#[serde(default)]
pub(crate) element_tag: Option<String>,
#[serde(default)]
pub(crate) element_role: Option<String>,
#[serde(default)]
pub(crate) text: Option<String>,
#[serde(default)]
pub(crate) width: Option<f64>,
#[serde(default)]
pub(crate) height: Option<f64>,
#[serde(default)]
pub(crate) resource_ids: Vec<String>,
}
fn sanitize_reference_text(value: &str, max_chars: usize) -> Option<String> {
let sanitized = value
.trim()
.chars()
.filter(|character| !character.is_control())
.take(max_chars)
.collect::<String>();
if sanitized.is_empty() {
None
} else {
Some(sanitized)
}
}
fn sanitize_reference_label(value: Option<&str>) -> Option<String> {
value.and_then(|value| sanitize_reference_text(value, MAX_DIRECT_CODEX_REFERENCE_LABEL_CHARS))
}
fn sanitize_reference_source(value: Option<&str>) -> Option<String> {
let value = sanitize_reference_text(value?, MAX_DIRECT_CODEX_REFERENCE_SOURCE_CHARS)?;
if value
.chars()
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.'))
{
Some(value)
} else {
None
}
}
fn sanitize_reference_element(value: Option<&str>) -> Option<String> {
let value = sanitize_reference_text(value?, MAX_DIRECT_CODEX_REFERENCE_ELEMENT_CHARS)?;
if value
.chars()
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.'))
{
Some(value)
} else {
None
}
}
fn sanitize_reference_dimension(value: Option<f64>) -> Option<u32> {
value
.filter(|value| value.is_finite() && *value > 0.0)
.map(|value| value.round().clamp(1.0, 100_000.0) as u32)
}
fn asset_display_label(asset: &GameCreationAppAssetManifestEntry) -> String {
let basename = asset
.local_path
.rsplit(['/', '\\'])
.next()
.unwrap_or(&asset.id);
let without_extension = basename
.rsplit_once('.')
.map(|(name, _)| name)
.unwrap_or(basename)
.trim();
if without_extension.is_empty() {
asset.id.clone()
} else {
without_extension
.chars()
.filter(|character| !character.is_control())
.take(MAX_DIRECT_CODEX_REFERENCE_LABEL_CHARS)
.collect()
}
}
fn validate_resource_reference_id(value: &str) -> Result<String, String> {
let resource_id = value.trim();
if resource_id.is_empty()
|| resource_id.chars().count() > MAX_DIRECT_CODEX_REFERENCE_ID_CHARS
|| resource_id.chars().any(char::is_control)
{
return Err("引用的素材 ID 无效,请移除后重新选择".to_string());
}
Ok(resource_id.to_string())
}
/// Render the prompt context for a UI design asset.
///
/// Keep this separate from the generic resource renderer so UI-specific
/// instructions/metadata can evolve without changing other asset kinds.
fn render_ui_design_reference_line(
root: &Path,
manifest: &GameCreationAppManifest,
asset: &GameCreationAppAssetManifestEntry,
resource_id: &str,
label: &str,
local_path: &str,
source: &str,
) -> String {
let context = match generate_ui_design_code_at(GenerateUiDesignCodeInput {
project_path: root.to_string_lossy().into_owned(),
expected_project_id: manifest.project_id.clone(),
asset_id: resource_id.to_string(),
}) {
Ok(result) => format!("请先阅读生成的带有文档的代码片段: {}", result.relative_path),
Err(error) => format!("生成代码遇到错误{error}"),
};
format!(
"- 素材 ID{resource_id};名称:{label};类型:{};媒体类型:{};项目路径:{local_path};来源:{source}",
asset.kind, asset.media_type
) + "\n" + &context
}
fn render_resource_reference_line(
root: &Path,
manifest: &GameCreationAppManifest,
reference: &DirectCodexResourceReference,
) -> Result<String, String> {
let resource_id = validate_resource_reference_id(&reference.resource_id)?;
let asset = manifest
.assets
.iter()
.find(|asset| asset.id == resource_id)
.ok_or_else(|| "引用的素材已不存在,请移除后重新选择".to_string())?;
let local_path = sanitize_attachment_local_path(&asset.local_path)
.ok_or_else(|| "引用的素材路径无效,请移除后重新选择".to_string())?;
let label = sanitize_reference_label(reference.label.as_deref())
.unwrap_or_else(|| asset_display_label(asset));
let source = sanitize_reference_source(reference.source.as_deref())
.unwrap_or_else(|| "unknown".to_string());
let is_ui_design =
asset.kind == UI_DESIGN_DOC_ASSET_KIND && asset.media_type == UI_DESIGN_DOC_MEDIA_TYPE;
if is_ui_design {
return Ok(render_ui_design_reference_line(
root,
manifest,
asset,
&resource_id,
&label,
&local_path,
&source,
));
}
Ok(format!(
"- 素材 ID{resource_id};名称:{label};类型:{};媒体类型:{};项目路径:{local_path};来源:{source}",
asset.kind, asset.media_type
))
}
fn render_runtime_region_reference_line(
manifest: &GameCreationAppManifest,
reference: &DirectCodexRuntimeRegionReference,
) -> Result<String, String> {
let label = sanitize_reference_label(reference.label.as_deref())
.unwrap_or_else(|| "运行画面区域".to_string());
let run_id = sanitize_reference_source(reference.run_id.as_deref());
let version_id = sanitize_reference_source(reference.version_id.as_deref());
let element_tag = sanitize_reference_element(reference.element_tag.as_deref());
let element_role = sanitize_reference_element(reference.element_role.as_deref());
let text = reference
.text
.as_deref()
.and_then(|value| sanitize_reference_text(value, MAX_DIRECT_CODEX_REFERENCE_TEXT_CHARS));
let width = sanitize_reference_dimension(reference.width);
let height = sanitize_reference_dimension(reference.height);
// `resourceIds` 是本模块唯一由客户端直接给出、且自身还是一条列表的字段:条数不设界时,
// 每个 id 都要扫一遍 manifestO(assets)),注入提示词的 `关联素材 ID:…` 行也会跟着无界
// 变长(最终只被 32 MiB 写入护栏拦下,变成一条和原因无关的连接级错误)。这里按模块的
// 失败关闭口径直接拒绝超限,而不是静默丢掉用户选中的关联。
if reference.resource_ids.len() > MAX_DIRECT_CODEX_REFERENCES {
return Err(format!(
"运行画面区域一次最多关联 {MAX_DIRECT_CODEX_REFERENCES} 个素材,请重新点选"
));
}
let mut related_resource_ids = Vec::new();
for resource_id in &reference.resource_ids {
let resource_id = validate_resource_reference_id(resource_id)?;
if !manifest.assets.iter().any(|asset| asset.id == resource_id) {
return Err("运行画面引用的素材已变化,请重新点选".to_string());
}
// 去重:同一个 id 在注入提示词里重复出现没有信息量,只是把行撑长。
// 条数已按上限收口,所以这里的逐项比较不会退化成大面积二次扫描。
if !related_resource_ids.contains(&resource_id) {
related_resource_ids.push(resource_id);
}
}
let mut parts = vec![format!("名称:{label}")];
if let Some(run_id) = run_id {
parts.push(format!("运行标识:{run_id}"));
}
if let Some(version_id) = version_id {
parts.push(format!("版本标识:{version_id}"));
}
if let Some(element_tag) = element_tag {
parts.push(format!("元素:{element_tag}"));
}
if let Some(element_role) = element_role {
parts.push(format!("角色:{element_role}"));
}
if let Some(text) = text {
parts.push(format!("文本摘要:{text}"));
}
if let (Some(width), Some(height)) = (width, height) {
parts.push(format!("尺寸:{width}x{height}"));
}
if !related_resource_ids.is_empty() {
parts.push(format!("关联素材 ID{}", related_resource_ids.join(",")));
}
Ok(format!("- 运行画面区域:{}", parts.join("")))
}
pub(crate) fn render_direct_codex_references_section(
root: &Path,
references: &[DirectCodexTurnReference],
) -> Result<Option<String>, String> {
if references.is_empty() {
return Ok(None);
}
if references.len() > MAX_DIRECT_CODEX_REFERENCES {
return Err(format!("一次最多引用 {MAX_DIRECT_CODEX_REFERENCES} 个素材"));
}
let manifest = read_manifest_for_project(root)?;
let mut lines = Vec::with_capacity(references.len());
for reference in references {
lines.push(match reference {
DirectCodexTurnReference::Resource(reference) => {
render_resource_reference_line(root, &manifest, reference)?
}
DirectCodexTurnReference::RuntimeRegion(reference) => {
render_runtime_region_reference_line(&manifest, reference)?
}
});
}
Ok(Some(
std::iter::once(DIRECT_CODEX_REFERENCE_HEADER.to_string())
.chain(lines)
.collect::<Vec<_>>()
.join("\n"),
))
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture_project() -> tempfile::TempDir {
let directory = tempfile::tempdir().expect("temp project");
let root = directory.path();
std::fs::create_dir_all(root.join(".agent")).expect("create agent dir");
let mut manifest = new_game_creation_app_manifest("project-1", "测试项目");
manifest.assets.push(GameCreationAppAssetManifestEntry {
id: "asset-hero".to_string(),
kind: "character".to_string(),
media_type: "image/png".to_string(),
local_path: "assets/hero.png".to_string(),
source: GameCreationAppAssetSource {
kind: GameCreationAppAssetSourceKind::Uploaded,
canvas_project_id: None,
resource_id: None,
asset_object_id: None,
task_id: None,
prompt: None,
model: None,
generation_route: None,
generation_kind: None,
reference_resource_ids: Vec::new(),
},
image_sequence_frames: None,
image_sequence_duration_ms: None,
category: game_creation_app_asset_category_for_kind("character"),
tags: Vec::new(),
});
write_manifest(&root.join(".agent/manifest.json"), &manifest).expect("write manifest");
directory
}
#[test]
fn resource_reference_uses_manifest_identity_and_never_accepts_client_paths() {
let project = fixture_project();
let reference: DirectCodexTurnReference = serde_json::from_str(
r#"{"type":"resource","resourceId":"asset-hero","label":"主角","source":"asset-picker","localPath":"C:\\secret.png"}"#,
)
.expect("reference json");
let section = render_direct_codex_references_section(
project.path(),
std::slice::from_ref(&reference),
)
.expect("render")
.expect("section");
assert!(section.contains("素材 IDasset-hero"));
assert!(section.contains("名称:主角"));
assert!(section.contains("项目路径:assets/hero.png"));
assert!(!section.contains("C:\\secret.png"));
}
#[test]
fn deleted_resource_fails_closed() {
let project = fixture_project();
let reference: DirectCodexTurnReference = serde_json::from_str(
r#"{"type":"resource","resourceId":"asset-missing","label":"不存在"}"#,
)
.expect("reference json");
let error = render_direct_codex_references_section(
project.path(),
std::slice::from_ref(&reference),
)
.expect_err("missing resource");
assert_eq!(error, "引用的素材已不存在,请移除后重新选择");
}
#[test]
fn runtime_region_keeps_only_safe_summary_and_existing_resource_ids() {
let project = fixture_project();
let reference: DirectCodexTurnReference = serde_json::from_str(
r#"{"type":"runtime-region","label":"开始按钮","runId":"run-1","elementTag":"button","elementRole":"button","text":"开始游戏","width":120.4,"height":40.2,"resourceIds":["asset-hero"],"html":"<button onclick=secret>"}"#,
)
.expect("reference json");
let section = render_direct_codex_references_section(
project.path(),
std::slice::from_ref(&reference),
)
.expect("render")
.expect("section");
assert!(section.contains("运行画面区域:名称:开始按钮"));
assert!(section.contains("文本摘要:开始游戏"));
assert!(section.contains("尺寸:120x40"));
assert!(section.contains("关联素材 IDasset-hero"));
assert!(!section.contains("onclick"));
assert!(!section.contains("secret"));
}
#[test]
fn runtime_region_dedupes_and_bounds_related_resource_ids() {
let project = fixture_project();
// 同一个 id 重复出现只应产生一条关联。
let duplicated: DirectCodexTurnReference = serde_json::from_str(
r#"{"type":"runtime-region","label":"开始按钮","resourceIds":["asset-hero","asset-hero"," asset-hero "],"text":"开始游戏"}"#,
)
.expect("reference json");
let section = render_direct_codex_references_section(
project.path(),
std::slice::from_ref(&duplicated),
)
.expect("render")
.expect("section");
assert!(
section.contains("关联素材 IDasset-hero\n")
|| section.trim_end().ends_with("关联素材 IDasset-hero"),
"{section}"
);
assert!(
!section.contains("asset-hero,"),
"重复 id 不得在注入提示词里重复出现:{section}"
);
// 超出上限直接失败关闭:不能按对方给的长度注入提示词。
let oversized_ids = (0..MAX_DIRECT_CODEX_REFERENCES + 1)
.map(|_| "\"asset-hero\"".to_string())
.collect::<Vec<_>>()
.join(",");
let oversized: DirectCodexTurnReference = serde_json::from_str(&format!(
r#"{{"type":"runtime-region","label":"开始按钮","resourceIds":[{oversized_ids}]}}"#
))
.expect("reference json");
let error = render_direct_codex_references_section(
project.path(),
std::slice::from_ref(&oversized),
)
.expect_err("oversized resource id list must fail closed");
assert!(error.contains("最多关联"), "{error}");
}
}
@@ -0,0 +1,15 @@
//! DirectProject user input 的 canonical Response item 深模块。
mod model;
mod validation;
mod wire;
pub(crate) use model::{
DirectCodexUserContentPart, DirectCodexUserItem, DirectCodexUserMessageEnvelope,
DirectCodexUserMessageItem, DirectCodexUserRole, DirectCodexUserRuntimeRegionPart,
};
pub(crate) use validation::validate_direct_codex_user_item;
pub(crate) use wire::{
direct_codex_user_item_to_prompt, direct_codex_user_item_to_response_item,
direct_codex_user_item_to_wire_input,
};
@@ -0,0 +1,125 @@
use serde::{Deserialize, Serialize};
use ts_rs::TS;
/// DirectProject 本轮 user input 的唯一结构化入口。
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[serde(tag = "type", deny_unknown_fields)]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/features/project-workspace/generated/"))]
pub(crate) enum DirectCodexUserItem {
#[serde(rename = "message")]
Message(DirectCodexUserMessageItem),
}
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/features/project-workspace/generated/"))]
pub(crate) struct DirectCodexUserMessageItem {
pub(crate) role: DirectCodexUserRole,
pub(crate) content: Vec<DirectCodexUserContentPart>,
pub(crate) id: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/features/project-workspace/generated/"))]
pub(crate) enum DirectCodexUserRole {
User,
}
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[serde(tag = "type", rename_all_fields = "camelCase", deny_unknown_fields)]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/features/project-workspace/generated/"))]
pub(crate) enum DirectCodexUserContentPart {
#[serde(rename = "input_text")]
InputText { text: String },
#[serde(rename = "agc_resource_reference")]
AgcResourceReference { resource_id: String },
#[serde(rename = "agc_runtime_region_reference")]
AgcRuntimeRegionReference(DirectCodexUserRuntimeRegionPart),
}
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/features/project-workspace/generated/"))]
pub(crate) struct DirectCodexUserRuntimeRegionPart {
pub(crate) label: String,
#[serde(default)]
pub(crate) run_id: Option<String>,
#[serde(default)]
pub(crate) version_id: Option<String>,
#[serde(default)]
pub(crate) element_tag: Option<String>,
#[serde(default)]
pub(crate) element_role: Option<String>,
#[serde(default)]
pub(crate) text: Option<String>,
#[serde(default)]
pub(crate) width: Option<f64>,
#[serde(default)]
pub(crate) height: Option<f64>,
#[serde(default)]
pub(crate) resource_ids: Vec<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/features/project-workspace/generated/"))]
pub(crate) struct DirectCodexUserMessageEnvelope {
pub(crate) item: DirectCodexUserItem,
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn resource_reference_serializes_with_only_camel_case_resource_id() {
let item = DirectCodexUserItem::Message(DirectCodexUserMessageItem {
role: DirectCodexUserRole::User,
content: vec![DirectCodexUserContentPart::AgcResourceReference {
resource_id: "asset-hero".to_string(),
}],
id: "turn-1".to_string(),
});
assert_eq!(
serde_json::to_value(item).expect("serialize user item"),
json!({
"type": "message",
"role": "user",
"content": [{
"type": "agc_resource_reference",
"resourceId": "asset-hero"
}],
"id": "turn-1"
})
);
}
#[test]
fn resource_reference_rejects_extra_identity_fields() {
let error = serde_json::from_value::<DirectCodexUserItem>(json!({
"type": "message",
"role": "user",
"content": [{
"type": "agc_resource_reference",
"resourceId": "asset-hero",
"label": "主角"
}],
"id": "turn-1"
}))
.expect_err("label must not be accepted on resource reference");
assert!(error.to_string().contains("unknown field"), "{error}");
}
#[test]
fn unknown_content_part_fails_closed() {
serde_json::from_value::<DirectCodexUserItem>(json!({
"type": "message",
"role": "user",
"content": [{"type": "future_part", "value": "x"}],
"id": "turn-1"
}))
.expect_err("unknown content part must fail closed");
}
}
@@ -0,0 +1,88 @@
use super::model::{
DirectCodexUserContentPart, DirectCodexUserItem, DirectCodexUserRole,
DirectCodexUserRuntimeRegionPart,
};
use crate::agent::{
read_manifest_for_project, sanitize_attachment_local_path, GameCreationAppManifest,
};
use std::path::Path;
pub(crate) const MAX_DIRECT_CODEX_REFERENCES: usize = 32;
pub(crate) fn validate_direct_codex_user_item(
root: &Path,
item: &DirectCodexUserItem,
) -> Result<(), String> {
let DirectCodexUserItem::Message(message) = item;
if !matches!(message.role, DirectCodexUserRole::User) {
return Err("DirectProject 只接受 user message item".to_string());
}
if message.id.trim().is_empty() {
return Err("DirectProject user item 缺少稳定 id".to_string());
}
if message.content.is_empty() {
return Err("DirectProject user item content 不能为空".to_string());
}
let manifest = read_manifest_for_project(root)?;
let mut reference_count = 0usize;
for part in &message.content {
match part {
DirectCodexUserContentPart::InputText { text } => {
if text.trim().is_empty() {
return Err("DirectProject input_text 不能为空".to_string());
}
}
DirectCodexUserContentPart::AgcResourceReference { resource_id } => {
reference_count = reference_count.saturating_add(1);
validate_resource_id_and_manifest(&manifest, resource_id)?;
}
DirectCodexUserContentPart::AgcRuntimeRegionReference(reference) => {
reference_count = reference_count.saturating_add(1);
validate_runtime_region_reference(&manifest, reference)?;
}
}
}
if reference_count > MAX_DIRECT_CODEX_REFERENCES {
return Err(format!("一次最多引用 {MAX_DIRECT_CODEX_REFERENCES} 个素材"));
}
Ok(())
}
pub(crate) fn validate_resource_id_and_manifest(
manifest: &GameCreationAppManifest,
resource_id: &str,
) -> Result<(), String> {
let resource_id = resource_id.trim();
if resource_id.is_empty()
|| resource_id.chars().count() > 200
|| resource_id.chars().any(char::is_control)
{
return Err("引用的素材 ID 无效,请移除后重新选择".to_string());
}
let asset = manifest
.assets
.iter()
.find(|asset| asset.id == resource_id)
.ok_or_else(|| "引用的素材已不存在,请移除后重新选择".to_string())?;
sanitize_attachment_local_path(&asset.local_path)
.ok_or_else(|| "引用的素材路径无效,请移除后重新选择".to_string())?;
Ok(())
}
fn validate_runtime_region_reference(
manifest: &GameCreationAppManifest,
reference: &DirectCodexUserRuntimeRegionPart,
) -> Result<(), String> {
if reference.label.trim().is_empty() {
return Err("运行画面区域缺少名称".to_string());
}
if reference.resource_ids.len() > MAX_DIRECT_CODEX_REFERENCES {
return Err(format!(
"运行画面区域一次最多关联 {MAX_DIRECT_CODEX_REFERENCES} 个素材"
));
}
for resource_id in &reference.resource_ids {
validate_resource_id_and_manifest(manifest, resource_id)?;
}
Ok(())
}
@@ -0,0 +1,143 @@
use super::model::{DirectCodexUserContentPart, DirectCodexUserItem};
use super::validation::validate_direct_codex_user_item;
use crate::agent::{read_manifest_for_project, sanitize_attachment_local_path};
use serde_json::Value;
use std::path::Path;
/// 将历史中的 canonical user item 投影为 Codex `response_item` message。
/// 非 user message 的标准 Response item 原样返回;未知形状直接失败。
pub(crate) fn direct_codex_user_item_to_response_item(
root: &Path,
item: &Value,
) -> Result<Value, String> {
let is_user_message = item.get("type").and_then(Value::as_str) == Some("message")
&& item.get("role").and_then(Value::as_str) == Some("user");
if !is_user_message {
if item.get("type").and_then(Value::as_str).is_some() {
return Ok(item.clone());
}
return Err("DirectProject 历史 item 缺少 type,无法投影为 Codex item".to_string());
}
let canonical: DirectCodexUserItem = serde_json::from_value(item.clone())
.map_err(|error| format!("DirectProject user item 无法转换为 Codex item{error}"))?;
let Value::Array(content) = direct_codex_user_item_to_wire_input(root, &canonical)? else {
return Err("DirectProject user item wire content 不是数组".to_string());
};
let mut projected = serde_json::json!({
"type": "message",
"role": "user",
"content": content,
});
if let Some(id) = item.get("id").and_then(Value::as_str) {
projected["id"] = Value::String(id.to_string());
}
Ok(projected)
}
/// 将 canonical user item 转为 app-server `turn/start.input` 可接受的文本数组。
/// AGC 私有 part 只在这里投影为安全摘要,canonical item 本身不被修改。
pub(crate) fn direct_codex_user_item_to_wire_input(
root: &Path,
item: &DirectCodexUserItem,
) -> Result<Value, String> {
validate_direct_codex_user_item(root, item)?;
let manifest = read_manifest_for_project(root)?;
let DirectCodexUserItem::Message(message) = item;
let mut input = Vec::with_capacity(message.content.len());
for part in &message.content {
let text = match part {
DirectCodexUserContentPart::InputText { text } => text.clone(),
DirectCodexUserContentPart::AgcResourceReference { resource_id } => {
let asset = manifest
.assets
.iter()
.find(|asset| asset.id == resource_id.trim())
.ok_or_else(|| "引用的素材已不存在,请移除后重新选择".to_string())?;
let path = sanitize_attachment_local_path(&asset.local_path)
.ok_or_else(|| "引用的素材路径无效,请移除后重新选择".to_string())?;
format!(
"[素材引用 resourceId={};项目路径={path}]",
resource_id.trim()
)
}
DirectCodexUserContentPart::AgcRuntimeRegionReference(reference) => {
let resources = reference
.resource_ids
.iter()
.map(|id| id.trim())
.collect::<Vec<_>>()
.join(",");
let mut summary = format!("[运行画面区域:名称={} ", reference.label.trim());
if let Some(run_id) = reference.run_id.as_deref() {
summary.push_str(&format!("运行标识={} ", run_id.trim()));
}
if let Some(role) = reference.element_role.as_deref() {
summary.push_str(&format!("角色={} ", role.trim()));
}
if let Some(text) = reference.text.as_deref() {
summary.push_str(&format!("文本={} ", text.trim()));
}
if !resources.is_empty() {
summary.push_str(&format!("关联素材={resources}"));
}
summary.push(']');
summary
}
};
input.push(serde_json::json!({ "type": "text", "text": text }));
}
Ok(Value::Array(input))
}
pub(crate) fn direct_codex_user_item_to_prompt(
root: &Path,
item: &DirectCodexUserItem,
) -> Result<String, String> {
let wire = direct_codex_user_item_to_wire_input(root, item)?;
wire.as_array()
.ok_or_else(|| "DirectProject user item wire input 不是数组".to_string())
.map(|parts| {
parts
.iter()
.filter_map(|part| part.get("text").and_then(Value::as_str))
.collect::<String>()
})
.and_then(|prompt| {
if prompt.trim().is_empty() {
Err("DirectProject user item 不能转换为空 prompt".to_string())
} else {
Ok(prompt)
}
})
}
#[cfg(test)]
mod tests {
use super::direct_codex_user_item_to_response_item;
use serde_json::json;
use std::path::Path;
#[test]
fn standard_response_item_passes_through_without_agc_private_parts() {
let item = json!({
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "完成"}]
});
assert_eq!(
direct_codex_user_item_to_response_item(Path::new("/unused"), &item)
.expect("assistant response item should pass through"),
item
);
}
#[test]
fn history_item_without_type_fails_closed() {
let error = direct_codex_user_item_to_response_item(
Path::new("/unused"),
&json!({"role": "assistant"}),
)
.expect_err("history item without type must fail");
assert!(error.contains("缺少 type"), "{error}");
}
}
@@ -17,9 +17,6 @@ const DIRECT_PROJECT_HISTORY_SCAN_PROBE_FINISHED: usize = 1;
/// 写入侧与读取侧共用同一个信封类型:`project.jsonl` 由项目主对话与 DirectProject 共享,
/// 这个值一旦只在写入侧改动,读取侧就会把对方的行当成坏行,整份历史立刻读不出来。
pub(crate) const DIRECT_PROJECT_HISTORY_RECORD_TYPE: &str = "response_item";
/// 格式切换到 `response_item`#282)之前,DirectProject 主对话通过通用对话写入器
/// 落到同一份 `project.jsonl`,行形状是 `PersistedLocalConversationMessageRecord`。
const DIRECT_PROJECT_HISTORY_LEGACY_SCHEMA_VERSION: &str = "game-creator-conversation.v1";
const DIRECT_PROJECT_INTERNAL_CONTEXT_KINDS: &[&str] = &[
"host_skills.instructions",
"permissions.instructions",
@@ -180,79 +177,22 @@ fn direct_project_history_item_from_line(
Ok(Some(item))
}
/// 只接受两种行信封:`response_item`,以及白名单化的 legacy 行。返回 `None` 表示行已
/// 被识别、但不该进入 Codex 上下文(legacy 的 `tool` 行)。
/// 其余任何形状(含换了 `schemaVersion`、带 `type` 却不是 `response_item`、role 不在
/// legacy 写入器自己的角色集合内、content 不是非空字符串)都判定为损坏并失败关闭。
/// 只接受 `response_item` 行信封;其它历史格式不提供迁移或 fallback,直接失败关闭。
fn direct_project_history_item_from_parsed_line(
path: &Path,
parsed: &Value,
) -> Result<Option<Value>, String> {
if parsed.get("type").and_then(Value::as_str) == Some(DIRECT_PROJECT_HISTORY_RECORD_TYPE) {
return parsed
.get("payload")
.cloned()
.map(Some)
.ok_or_else(|| format!("DirectProject 历史记录缺少 payload{}", path.display()));
if parsed.get("type").and_then(Value::as_str) != Some(DIRECT_PROJECT_HISTORY_RECORD_TYPE) {
return Err(format!(
"DirectProject 历史记录类型无效:{}",
path.display()
));
}
direct_project_legacy_row(parsed)
.map(|row| row.message_item())
.ok_or_else(|| format!("DirectProject 历史记录类型无效:{}", path.display()))
}
/// 白名单化 legacy 行的投影结果。
enum DirectProjectLegacyRow {
/// user/assistant 行:投影成 message item 进入历史。
Message(Value),
/// 已识别但不可注入的行(`tool`):与 developer/system item 同样处理,不进 Codex
/// 上下文。legacy 行不是 Responses item`tool` 行无法还原成真正的工具 item,
/// 注入会造出假的工具消息;聊天投影本来也只展示 user/assistant。
NotChat,
}
impl DirectProjectLegacyRow {
fn message_item(self) -> Option<Value> {
match self {
DirectProjectLegacyRow::Message(item) => Some(item),
DirectProjectLegacyRow::NotChat => None,
}
}
}
/// 格式切换前的 legacy 行投影。存量用户项目的历史文件全是这种行,读取时投影成与
/// `direct_project_local_message_item` 同形状的 message item`role` 与 `content`
/// 原样保留(不 trim、不改写、不合并),未知字段忽略。
///
/// 角色白名单取的是 legacy 写入器自己的角色集合,也就是
/// `project/conversation.rs` 里 `matches!(role, "user" | "assistant" | "tool")` 这一
/// 条校验,所以「legacy 写入器能写出的行」被完整覆盖,不会有第三种角色漏进来;
/// 白名单之外的角色(手改文件、未来写入器)仍按损坏失败关闭。
fn direct_project_legacy_row(parsed: &Value) -> Option<DirectProjectLegacyRow> {
let object = parsed.as_object()?;
if object.contains_key("type")
|| object.get("schemaVersion").and_then(Value::as_str)
!= Some(DIRECT_PROJECT_HISTORY_LEGACY_SCHEMA_VERSION)
{
return None;
}
let role = object.get("role").and_then(Value::as_str)?;
if !matches!(role, "user" | "assistant" | "tool") {
return None;
}
let content = object.get("content").and_then(Value::as_str)?;
if content.is_empty() {
return None;
}
if role == "tool" {
return Some(DirectProjectLegacyRow::NotChat);
}
let message_id = object
.get("messageId")
.and_then(Value::as_str)
.filter(|message_id| !message_id.is_empty());
Some(DirectProjectLegacyRow::Message(
direct_project_message_item(role, content, message_id),
))
parsed
.get("payload")
.cloned()
.map(Some)
.ok_or_else(|| format!("DirectProject 历史记录缺少 payload{}", path.display()))
}
/// 测试专用探针:在"锁外幂等回扫"这一段的两端回调。
@@ -512,8 +452,8 @@ pub(crate) fn direct_project_local_message_item(
))
}
/// 本地补写与 legacy 投影共用同一种 Responses message item 形状,两者的区别只在
/// 是否对入参做 trim 校验:本地补写走上面的校验,legacy 行按文件内容逐字节投影
/// 本地补写与 Codex response item 共用同一种 Responses message item 形状;本地补写额外做
/// trim 校验,历史读取只接受 response_item envelope
fn direct_project_message_item(role: &str, content: &str, message_id: Option<&str>) -> Value {
let mut item = serde_json::json!({
"type": "message",
@@ -626,7 +566,7 @@ mod tests {
fn init_history_project(name: &str) -> tempfile::TempDir {
let root = tempfile::tempdir().expect("temp project");
crate::init_local_game_project_at(root.path(), name, "历史格式兼容测试")
crate::init_local_game_project_at(root.path(), name, "Response item 历史测试")
.expect("init project");
root
}
@@ -637,9 +577,8 @@ mod tests {
std::fs::write(&path, format!("{}\n", lines.join("\n"))).expect("write history fixture");
}
const LEGACY_USER_ROW: &str = r#"{"schemaVersion":"game-creator-conversation.v1","role":"user","content":"请创建菜单","agentId":null,"messageId":"direct-codex:turn-0001:user","updatedAt":1757000000}"#;
const LEGACY_ASSISTANT_ROW: &str = r#"{"schemaVersion":"game-creator-conversation.v1","role":"assistant","content":"已完成 第一行\n第二行 ","agentId":null,"updatedAt":1757000001}"#;
const RESPONSE_ITEM_ROW: &str = r#"{"type":"response_item","payload":{"type":"message","role":"user","id":"codex-item-2","content":[{"type":"input_text","text":"再加一个按钮"}]}}"#;
const RESPONSE_ASSISTANT_ROW: &str = r#"{"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"已完成"}]}}"#;
/// 判据:争用类失败会被"有界退避重试"真的吃掉,最终把条目落一行。
///
@@ -648,7 +587,7 @@ mod tests {
#[test]
fn contention_failure_is_retried_with_bounded_backoff() {
let root = init_history_project("contention-retry");
write_history_lines(root.path(), &[LEGACY_USER_ROW]);
write_history_lines(root.path(), &[RESPONSE_ITEM_ROW]);
let marker = root
.path()
.join(".agent/runtime/test-fail-next-direct-project-history-append");
@@ -680,7 +619,7 @@ mod tests {
#[test]
fn contention_failure_beyond_the_backoff_budget_fails_closed() {
let root = init_history_project("contention-bounded");
write_history_lines(root.path(), &[LEGACY_USER_ROW]);
write_history_lines(root.path(), &[RESPONSE_ITEM_ROW]);
let marker = root
.path()
.join(".agent/runtime/test-fail-next-direct-project-history-append");
@@ -723,7 +662,7 @@ mod tests {
write_history_lines(
root.path(),
&[
LEGACY_USER_ROW,
RESPONSE_ITEM_ROW,
r#"{"schemaVersion":"game-creator"#,
RESPONSE_ITEM_ROW,
],
@@ -761,7 +700,7 @@ mod tests {
let root = init_history_project("scan-outside-lock");
write_history_lines(
root.path(),
&[LEGACY_USER_ROW, RESPONSE_ITEM_ROW, LEGACY_ASSISTANT_ROW],
&[RESPONSE_ITEM_ROW, RESPONSE_ITEM_ROW, RESPONSE_ASSISTANT_ROW],
);
let path = history_path(root.path());
let fired = Arc::new(AtomicBool::new(false));
@@ -805,7 +744,7 @@ mod tests {
#[test]
fn concurrent_append_after_the_out_of_lock_scan_still_prevents_a_duplicate_row() {
let root = init_history_project("scan-stale-state");
write_history_lines(root.path(), &[LEGACY_USER_ROW]);
write_history_lines(root.path(), &[RESPONSE_ITEM_ROW]);
let path = history_path(root.path());
let item = json!({
"type": "message",
@@ -845,7 +784,7 @@ mod tests {
#[test]
fn conflicting_item_id_still_fails_closed_with_the_scan_outside_the_lock() {
let root = init_history_project("id-conflict-outside-lock");
write_history_lines(root.path(), &[LEGACY_USER_ROW]);
write_history_lines(root.path(), &[RESPONSE_ITEM_ROW]);
append_direct_project_history_item_at(
root.path(),
&json!({
@@ -1033,97 +972,13 @@ mod tests {
}
#[test]
fn legacy_conversation_rows_project_into_responses_message_items() {
let root = init_history_project("legacy-projection");
write_history_lines(root.path(), &[LEGACY_USER_ROW, LEGACY_ASSISTANT_ROW]);
let items = read_direct_project_history_items_at(root.path()).expect("read legacy history");
assert_eq!(
items,
vec![
json!({
"type": "message",
"role": "user",
"id": "direct-codex:turn-0001:user",
"content": [{"type": "input_text", "text": "请创建菜单"}],
}),
json!({
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "已完成 第一行\n第二行 "}],
}),
]
);
let chat = read_direct_project_chat_history_at(root.path()).expect("read legacy chat");
assert_eq!(chat.messages.len(), 2);
assert_eq!(chat.messages[0].role, "user");
assert_eq!(chat.messages[0].content, "请创建菜单");
assert_eq!(
chat.messages[0].message_id.as_deref(),
Some("direct-codex:turn-0001:user")
);
assert_eq!(chat.messages[1].role, "assistant");
assert_eq!(chat.messages[1].content, "已完成 第一行\n第二行 ");
assert_eq!(chat.messages[1].message_id, None);
}
#[test]
fn mixed_legacy_and_response_item_history_reads_in_file_order() {
let root = init_history_project("mixed-history");
write_history_lines(
root.path(),
&[LEGACY_USER_ROW, RESPONSE_ITEM_ROW, LEGACY_ASSISTANT_ROW],
);
let items = read_direct_project_history_items_at(root.path()).expect("read mixed history");
assert_eq!(
items
.iter()
.map(|item| item.get("id").and_then(Value::as_str))
.collect::<Vec<_>>(),
vec![
Some("direct-codex:turn-0001:user"),
Some("codex-item-2"),
None
]
);
assert_eq!(
items[1],
json!({
"type": "message",
"role": "user",
"id": "codex-item-2",
"content": [{"type": "input_text", "text": "再加一个按钮"}],
})
);
assert_eq!(
items[2]["content"][0]["text"],
json!("已完成 第一行\n第二行 ")
);
let chat = read_direct_project_chat_history_at(root.path()).expect("read mixed chat");
assert_eq!(
chat.messages
.iter()
.map(|message| (message.role.as_str(), message.content.as_str()))
.collect::<Vec<_>>(),
vec![
("user", "请创建菜单"),
("user", "再加一个按钮"),
("assistant", "已完成 第一行\n第二行 "),
]
);
}
#[test]
fn legacy_compat_keeps_unrecognized_rows_failing_closed() {
fn non_response_item_history_fails_closed() {
let unrecognized_rows = [
// 带 type 却不是 response_item
r#"{"type":"message","role":"user","content":[{"type":"input_text","text":"x"}]}"#,
// schemaVersion 不在白名单里
// schema 不提供 fallback
r#"{"schemaVersion":"game-creator-conversation.v2","role":"user","content":"x","agentId":null,"updatedAt":1}"#,
// legacy 写入器角色集合之外的角色
// 旧 schema 的其它角色也拒绝
r#"{"schemaVersion":"game-creator-conversation.v1","role":"system","content":"x","agentId":null,"updatedAt":1}"#,
r#"{"schemaVersion":"game-creator-conversation.v1","role":"developer","content":"x","agentId":null,"updatedAt":1}"#,
// content 不是字符串
@@ -1159,61 +1014,4 @@ mod tests {
.expect_err("broken json must fail closed");
assert!(error.starts_with("解析 DirectProject 历史失败"), "{error}");
}
#[test]
fn legacy_tool_row_is_recognized_but_stays_out_of_the_codex_context() {
let root = init_history_project("legacy-tool-row");
write_history_lines(
root.path(),
&[
LEGACY_USER_ROW,
r#"{"schemaVersion":"game-creator-conversation.v1","role":"tool","content":"{\"ok\":true}","agentId":null,"updatedAt":1757000002}"#,
LEGACY_ASSISTANT_ROW,
],
);
let items = read_direct_project_history_items_at(root.path()).expect("read history");
assert_eq!(
items
.iter()
.map(|item| item["role"].as_str().unwrap_or_default())
.collect::<Vec<_>>(),
vec!["user", "assistant"]
);
let chat = read_direct_project_chat_history_at(root.path()).expect("read chat");
assert_eq!(
chat.messages
.iter()
.map(|message| message.role.as_str())
.collect::<Vec<_>>(),
vec!["user", "assistant"]
);
}
#[test]
fn generic_writer_rows_are_covered_by_the_legacy_whitelist() {
let root = init_history_project("generic-writer-shape");
crate::append_local_conversation_message_at(
root.path(),
None,
crate::LocalConversationMessage {
role: "user".to_string(),
content: "通用写入器写的旧格式回合".to_string(),
agent_id: None,
},
)
.expect("append legacy row through the generic writer");
let items =
read_direct_project_history_items_at(root.path()).expect("read generic writer row");
assert_eq!(
items,
vec![json!({
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "通用写入器写的旧格式回合"}],
})]
);
}
}
@@ -6,6 +6,9 @@ use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
mod user_input;
pub(crate) use user_input::chat_with_game_creator_direct_codex;
const MAX_DIRECT_SYSTEM_PROMPT_CHARS: usize = 16 * 1024;
const MIN_DIRECT_CLIENT_TURN_ID_CHARS: usize = 6;
const MAX_DIRECT_CLIENT_TURN_ID_CHARS: usize = 160;
@@ -2020,7 +2023,7 @@ fn direct_taonier_art_asset_identity(
local_asset_id: asset.id.clone(),
source_sha256: validated.content_sha256,
media_type: asset.media_type.clone(),
canonical_asset_kind: asset.kind.to_string(),
canonical_asset_kind: asset.kind.clone(),
resource_id: asset
.source
.resource_id
@@ -2546,7 +2549,7 @@ async fn recover_direct_taonier_spritesheet_read_only_at(
&source_asset.id,
&format!("{:x}", Sha256::digest(&source_bytes)),
&source_asset.media_type,
source_asset.kind.as_str(),
&source_asset.kind,
)?;
let principal = external_editor_binding_principal(&access)?;
let Some(project_binding) =
@@ -4055,6 +4058,7 @@ pub(crate) async fn run_direct_game_creator_turn_at_with_creation_type(
creation_type,
None,
None,
None,
)
.await
}
@@ -4065,6 +4069,7 @@ async fn run_direct_game_creator_turn_at_with_creation_type_and_emitter(
creation_type: Option<&str>,
turn_emitter: Option<&DirectGameCreatorTurnUpdateEmitter>,
audit: Option<&mut DirectCodexTurnAudit>,
direct_user_item: Option<serde_json::Value>,
) -> Result<String, String> {
if !root.is_absolute() || !root.is_dir() {
return Err("当前项目目录不存在或不是绝对路径".to_string());
@@ -4080,7 +4085,15 @@ async fn run_direct_game_creator_turn_at_with_creation_type_and_emitter(
if let Some(emitter) = turn_emitter {
emitter.emit("accepted", Some("request-accepted"), None);
}
match run_direct_game_creator_turn_inner(root, prompt, creation_type, turn_emitter, audit).await
match run_direct_game_creator_turn_inner(
root,
prompt,
creation_type,
turn_emitter,
audit,
direct_user_item,
)
.await
{
Ok(reply) => Ok(reply),
Err(failure) => {
@@ -4099,6 +4112,7 @@ async fn run_direct_game_creator_turn_inner(
creation_type: Option<&str>,
turn_emitter: Option<&DirectGameCreatorTurnUpdateEmitter>,
audit: Option<&mut DirectCodexTurnAudit>,
direct_user_item: Option<serde_json::Value>,
) -> Result<String, DirectCodexTurnFailure> {
emit_direct_game_creator_progress(root, "codex.turn", "陶泥儿正在处理这条消息");
if let Some(emitter) = turn_emitter {
@@ -4152,6 +4166,7 @@ async fn run_direct_game_creator_turn_inner(
Some(&client_turn_id),
Some(&mut observer),
audit,
direct_user_item.clone(),
)
.await
} else {
@@ -4162,6 +4177,7 @@ async fn run_direct_game_creator_turn_inner(
None,
None,
audit,
direct_user_item.clone(),
)
.await
}
@@ -4453,95 +4469,6 @@ async fn run_direct_game_creator_turn_with_private_editor_credentials(
))
}
fn normalize_direct_client_turn_id(client_turn_id: Option<&str>) -> Result<String, String> {
let Some(client_turn_id) = client_turn_id else {
return Err("Direct 客户端回合缺少稳定 clientTurnId,已拒绝创建可计费生成身份".to_string());
};
let client_turn_id = client_turn_id.trim();
let valid_length = (MIN_DIRECT_CLIENT_TURN_ID_CHARS..=MAX_DIRECT_CLIENT_TURN_ID_CHARS)
.contains(&client_turn_id.len());
let mut bytes = client_turn_id.bytes();
let valid_first = bytes
.next()
.is_some_and(|byte| byte.is_ascii_alphanumeric());
let valid_rest = bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-');
if !valid_length || !valid_first || !valid_rest {
return Err(format!(
"clientTurnId 必须为 {MIN_DIRECT_CLIENT_TURN_ID_CHARS} 到 {MAX_DIRECT_CLIENT_TURN_ID_CHARS} 位 ASCII 字母、数字或连字符,且首位必须为字母或数字"
));
}
Ok(client_turn_id.to_string())
}
#[tauri::command]
pub(crate) async fn chat_with_game_creator_direct_codex(
project_path: String,
prompt: String,
creation_type: Option<String>,
client_turn_id: Option<String>,
attachments: Option<Vec<DirectCodexTurnAttachment>>,
references: Option<Vec<DirectCodexTurnReference>>,
) -> Result<String, String> {
let root = Path::new(project_path.trim());
let turn_id = normalize_direct_client_turn_id(client_turn_id.as_deref())?;
let _active_invocation = DirectTaonierActiveInvocationGuard::enter(root, &turn_id)?;
recover_direct_taonier_regeneration_workflow_at(root).map_err(|error| {
redact_agent_runtime_error(root, &format!("恢复上一轮陶泥儿整包事务失败:{error}"), 500)
})?;
let turn_emitter = DirectGameCreatorTurnUpdateEmitter::new(root, turn_id.clone());
let mut audit = DirectCodexTurnAudit::start(
root,
&turn_id,
&prompt,
attachments.as_deref().unwrap_or_default(),
);
let attachments = attachments.unwrap_or_default();
let references = references.unwrap_or_default();
let mut user_prompt = match render_direct_codex_user_prompt(&prompt, &attachments) {
Ok(prompt) => prompt,
Err(_) if !references.is_empty() && prompt.trim().is_empty() => String::new(),
Err(error) => {
audit.finish(false);
return Err(error);
}
};
if let Some(reference_section) = match render_direct_codex_references_section(root, &references)
{
Ok(section) => section,
Err(error) => {
audit.finish(false);
return Err(error);
}
} {
if !user_prompt.trim().is_empty() {
user_prompt.push_str("\n\n");
}
user_prompt.push_str(&reference_section);
}
if user_prompt.trim().is_empty() {
audit.finish(false);
return Err("聊天内容不能为空".to_string());
}
let reply = match run_direct_game_creator_turn_at_with_creation_type_and_emitter(
root,
&user_prompt,
creation_type.as_deref(),
Some(&turn_emitter),
Some(&mut audit),
)
.await
{
Ok(reply) => reply,
Err(error) => {
audit.finish(false);
return Err(error);
}
};
audit.finish(true);
turn_emitter.emit("completed", Some("none"), Some(reply.clone()));
Ok(reply)
}
#[tauri::command]
pub(crate) async fn chat_with_game_creator_home_direct_codex(
prompt: String,
@@ -0,0 +1,84 @@
//! DirectProject 用户输入命令适配器。
//!
//! Tauri 只在这里接收前端 item,校验与 canonical→prompt 投影交给 user-item
//! 深模块,回合编排仍由父模块负责。
use super::*;
fn normalize_direct_client_turn_id(client_turn_id: Option<&str>) -> Result<String, String> {
let Some(client_turn_id) = client_turn_id else {
return Err("Direct 客户端回合缺少稳定 clientTurnId,已拒绝创建可计费生成身份".to_string());
};
let client_turn_id = client_turn_id.trim();
let valid_length = (MIN_DIRECT_CLIENT_TURN_ID_CHARS..=MAX_DIRECT_CLIENT_TURN_ID_CHARS)
.contains(&client_turn_id.len());
let mut bytes = client_turn_id.bytes();
let valid_first = bytes
.next()
.is_some_and(|byte| byte.is_ascii_alphanumeric());
let valid_rest = bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-');
if !valid_length || !valid_first || !valid_rest {
return Err(format!(
"clientTurnId 必须为 {MIN_DIRECT_CLIENT_TURN_ID_CHARS}{MAX_DIRECT_CLIENT_TURN_ID_CHARS} 位 ASCII 字母、数字或连字符,且首位必须为字母或数字"
));
}
Ok(client_turn_id.to_string())
}
#[tauri::command]
pub(crate) async fn chat_with_game_creator_direct_codex(
project_path: String,
prompt: String,
user_item: DirectCodexUserItem,
creation_type: Option<String>,
client_turn_id: Option<String>,
attachments: Option<Vec<DirectCodexTurnAttachment>>,
) -> Result<String, String> {
let root = Path::new(project_path.trim());
let turn_id = normalize_direct_client_turn_id(client_turn_id.as_deref())?;
let _active_invocation = DirectTaonierActiveInvocationGuard::enter(root, &turn_id)?;
recover_direct_taonier_regeneration_workflow_at(root).map_err(|error| {
redact_agent_runtime_error(root, &format!("恢复上一轮陶泥儿整包事务失败:{error}"), 500)
})?;
let turn_emitter = DirectGameCreatorTurnUpdateEmitter::new(root, turn_id.clone());
let mut audit = DirectCodexTurnAudit::start(
root,
&turn_id,
&prompt,
attachments.as_deref().unwrap_or_default(),
);
let attachments = attachments.unwrap_or_default();
validate_direct_codex_user_item(root, &user_item).map_err(|error| {
audit.finish(false);
error
})?;
let user_prompt = direct_codex_user_item_to_prompt(root, &user_item).map_err(|error| {
audit.finish(false);
error
})?;
if user_prompt.trim().is_empty() {
audit.finish(false);
return Err("聊天内容不能为空".to_string());
}
let canonical_user_item =
Some(serde_json::to_value(user_item).map_err(|error| error.to_string())?);
let reply = match run_direct_game_creator_turn_at_with_creation_type_and_emitter(
root,
&user_prompt,
creation_type.as_deref(),
Some(&turn_emitter),
Some(&mut audit),
canonical_user_item,
)
.await
{
Ok(reply) => reply,
Err(error) => {
audit.finish(false);
return Err(error);
}
};
audit.finish(true);
turn_emitter.emit("completed", Some("none"), Some(reply.clone()));
Ok(reply)
}
@@ -1169,7 +1169,7 @@ fn bridge_registered_resource(
// (落盘值 + 按 kind 派生 + 读时自愈),这里走 Rust 的同构实现。
// 直接透传落盘 `asset.category` 会让 `kind:"ui"` 的资产在 UI 显示「UI 交互」、
// 在 Agent 侧读到 `unclassified`(真机 55 条分歧)。
"category": game_creation_app_asset_effective_category(asset.kind.as_str(), asset.category),
"category": game_creation_app_asset_effective_category(&asset.kind, asset.category),
"tags": asset.tags,
"canvasProjectId": asset.source.canvas_project_id,
"resourceId": asset.source.resource_id,
@@ -1828,7 +1828,7 @@ async fn bridge_create_or_derive_resource(
source_asset_id: source_asset.as_ref().map(|asset| asset.id.clone()),
source_path: source_asset.as_ref().map(|asset| asset.local_path.clone()),
source_media_type: source_asset.as_ref().map(|asset| asset.media_type.clone()),
source_subtype: source_asset.as_ref().map(|asset| asset.kind.to_string()),
source_subtype: source_asset.as_ref().map(|asset| asset.kind.clone()),
producer_task_id: source_asset
.as_ref()
.and_then(|asset| asset.source.task_id.clone()),
File diff suppressed because it is too large Load Diff
@@ -1074,6 +1074,102 @@ pub(in crate::agent) fn remove_platform_art_generation_runtime_state_at(
}
}
/// 一次性兼容:升级前 standalone 槽身份只由 `{outputPath, requireSlices}` 派生,
/// 同一项目所有图片类生成共用一个槽;升级后槽身份按精确动作派生,路径随之变化。
///
/// 若旧槽路径上的账本仍然属于本次精确动作(`agentId` 与 `actionFingerprint` 都与
/// 当前上下文一致),就在项目写锁内把它迁移到新身份路径:保留原 `idempotencyKey`
/// 与 `operationId`,避免同一精确动作在升级后二次 POST 计费。旧账本属于其他动作时
/// 原样保留(不迁移、不删除、不阻塞),由对应动作自己的请求迁移。
///
/// 返回 `Ok(false)` 表示没有需要迁移的旧账本。任何身份无法安全解释的情形都失败关闭。
pub(super) fn adopt_legacy_standalone_platform_art_generation_runtime_state_at(
root: &Path,
context: &PlatformArtGenerationRuntimeContext,
legacy_run_id: &str,
) -> Result<bool, String> {
if !is_standalone_platform_art_generation_runtime_context(context)
|| legacy_run_id == context.run_id
|| !is_lowercase_sha256(legacy_run_id.strip_prefix("slot-").unwrap_or_default())
{
return Ok(false);
}
// 与账本创建互斥:迁移必须在同一把项目写锁内完成,否则两个调用可能同时把同一份
// 旧账本迁移到新路径,或与新建账本互相覆盖。
let _claim_lock = acquire_game_creator_agent_runtime_project_write_lock_with_wait(
root,
"canvas.asset_generate.runtime.claim",
)?;
if game_creator_agent_runtime_external_generation_exists(
root,
&context.agent_id,
&context.run_id,
) {
// 新身份账本已经存在:旧账本不属于本次动作的权威状态,保持两边各自的身份。
return Ok(false);
}
let legacy_relative_path =
platform_art_generation_runtime_relative_path(&context.agent_id, legacy_run_id);
let Some(legacy_state) =
read_agent_runtime_json_sidecar_with_max_bytes::<PlatformArtGenerationRuntimeState>(
root,
&legacy_relative_path,
"External Editor 生成账本",
PLATFORM_ART_GENERATION_RUNTIME_MAX_BYTES,
)?
else {
return Ok(false);
};
if legacy_state.agent_id != context.agent_id
|| legacy_state.run_id != legacy_run_id
|| legacy_state.action_fingerprint != context.action_fingerprint
{
// 旧槽里是另一个精确动作的账本:它仍归那个动作所有,本次调用不得消费、改写或删除它。
return Ok(false);
}
let legacy_identity = format!("{}:{legacy_run_id}", context.agent_id);
let legacy_context = PlatformArtGenerationRuntimeContext {
task_id: legacy_identity.clone(),
session_id: legacy_identity.clone(),
run_id: legacy_run_id.to_string(),
action_id: legacy_identity,
..context.clone()
};
let Some(mut migrated) = read_platform_art_generation_runtime_state(root, &legacy_context)?
else {
return Ok(false);
};
migrated.run_id = context.run_id.clone();
migrated.task_id = context.task_id.clone();
migrated.session_id = context.session_id.clone();
migrated.action_id = context.action_id.clone();
migrated.updated_at = unix_timestamp();
write_platform_art_generation_runtime_state(root, &migrated)?;
remove_platform_art_generation_runtime_state_at(root, &context.agent_id, legacy_run_id)?;
Ok(true)
}
#[cfg(test)]
pub(super) fn platform_art_generation_runtime_operation_id_for_test(
state: &PlatformArtGenerationRuntimeState,
) -> Option<&str> {
state.operation_id.as_deref()
}
#[cfg(test)]
pub(super) fn platform_art_generation_runtime_run_id_for_test(
state: &PlatformArtGenerationRuntimeState,
) -> &str {
&state.run_id
}
#[cfg(test)]
pub(super) fn platform_art_generation_runtime_action_fingerprint_for_test(
state: &PlatformArtGenerationRuntimeState,
) -> &str {
&state.action_fingerprint
}
#[cfg(test)]
pub(crate) fn write_platform_art_generation_runtime_accepted_for_test(
root: &Path,
@@ -98,7 +98,7 @@ pub(crate) fn render_local_asset_prompt_context(root: &Path) -> Result<String, S
output.push_str("- ");
output.push_str(&asset.id);
output.push_str(": ");
output.push_str(asset.kind.as_str());
output.push_str(&asset.kind);
output.push_str(" / ");
output.push_str(&asset.media_type);
output.push_str(" / ");
@@ -409,6 +409,8 @@ where
(self.on_delta)(&platform_llm::LlmStreamDelta {
accumulated_text,
delta_text,
accumulated_reasoning: String::new(),
reasoning_delta: String::new(),
finish_reason,
});
}
@@ -499,6 +501,7 @@ mod tests {
provider: LlmProvider::OpenAiCompatible,
model: "interaction-test".to_string(),
text: text.to_string(),
reasoning: String::new(),
finish_reason: Some("stop".to_string()),
response_id: Some("interaction-response".to_string()),
usage: None,

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