Merge remote-tracking branch 'origin/master' into feat/ui-editor-auto-seperation
# Conflicts: # apps/ai-game-creator-shell/src/view/project-development/index.tsx
This commit is contained in:
@@ -5,6 +5,7 @@
|
||||
## 目录约定
|
||||
|
||||
- `.codex/skills/` 是项目专属 skill 根目录。每个 skill 以目录中的 `SKILL.md` 为入口,配套的参考资料和脚本放在同一目录下。
|
||||
- `spec-driven-development` 负责跨模块、公开契约、SpacetimeDB、AGC/Runtime 和复杂 UI 任务的规范先行与逐里程碑验收;具体规则以 `docs/` 下的 SDD 工作流和模板为准。
|
||||
- `.codex/plugins/` 保存随仓库分发的项目插件资源及其参考资料。当前的 `game-studio` 插件提供浏览器游戏设计、原型、2D/3D 技术栈、素材管线和 playtest 工作流;是否启用遵循当前 Codex 的插件加载机制,不依赖旧工具的环境变量或个人配置脚本。
|
||||
- `.codex/hooks/`、`.codex/environments/` 等目录保存项目工具链所需的 hooks 和环境模板;它们不替代项目代码中的运行时配置。
|
||||
- 长期有效的产品、架构、接口、排障和协作知识统一放在 `docs/` 与 `docs/project-memory/`,不复制到本目录。
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
name: spec-driven-development
|
||||
description: 在 Genarrative 中处理跨模块功能、公开 API/DTO、SpacetimeDB schema、AGC/Runtime 或复杂 UI 状态链路时,按主规范、里程碑规范、单里程碑实现计划和验收证据推进;小型局部修复不触发。
|
||||
license: MIT
|
||||
metadata:
|
||||
codex:
|
||||
tags: [SDD, 规范驱动开发, 主规范, 里程碑, 验收]
|
||||
---
|
||||
|
||||
# SDD 规范驱动开发
|
||||
|
||||
本 skill 把 Genarrative 的复杂任务路由到规范先行、单里程碑交付的工作流。权威规则和模板分别见:
|
||||
|
||||
- `docs/【协作规范】规范驱动开发工作流-2026-09-12.md`
|
||||
- `docs/project-memory/shared-memory/【模板】规范驱动开发主规范与里程碑模板-2026-09-12.md`
|
||||
|
||||
## 触发条件
|
||||
|
||||
使用本 skill 的任务包括:
|
||||
|
||||
- 跨前端、`api-server`、`platform-*`、`spacetime-client`、`spacetime-module` 或 `module-*` 的功能。
|
||||
- `/api/external/v1`、共享 DTO、OpenAPI、SpacetimeDB schema、迁移或跨版本重放合同变化。
|
||||
- AGC / DirectProject、Agent Runtime、工具白名单、审批、持久化恢复或资源工作流变化。
|
||||
- 复杂 UI 状态链路、入口/页面生命周期变化,或需要多个独立验收面的功能。
|
||||
|
||||
文案、单文件局部修复、无行为变化重构和一次性诊断继续使用轻量流程;执行中一旦触及公开行为或跨模块合同,切换到本 skill。
|
||||
|
||||
## 执行要求
|
||||
|
||||
1. 检查工作树,读取当前专题、源码、测试、契约和历史决策;写清交付结果、验收判据和不做项。
|
||||
2. 找到或更新唯一主规范。主规范描述行为合同、边界、非目标、兼容/迁移和证据,不绑定实现细节。
|
||||
3. 在 `docs/project-memory/plans/` 创建一个或多个 `【里程碑】中文标题-YYYY-MM-DD.md`,填写 `Version`、`Status`、`Date`、`Parent Spec`、范围、依赖和验收标准;评审通过前不写业务代码。
|
||||
4. 每次只选择一个已评审里程碑,创建对应的 `【实施计划】中文标题-YYYY-MM-DD.md`,明确修改边界、顺序、验证命令、风险和回滚点。
|
||||
5. 发现行为需要变化时,严格按 `主规范 → 尚未实现的里程碑规范 → 当前实现计划 → 代码与测试` 更新。
|
||||
6. 完成一个里程碑后,提供主规范/里程碑逐条对照、自动化验证、必要运行时 smoke、边界验证和未验证项;未验收不得推进下一个里程碑。
|
||||
7. 全部验收通过后,将持久结论合并回主规范,删除已完成的临时计划,并检查文档、契约、测试和提交边界一致。
|
||||
|
||||
## 约束
|
||||
|
||||
- 里程碑和实现计划是开发期协调文件,完成或取消后删除;阶段编号和临时名称不得进入产品代码、用户文档、测试名称或提交标题。
|
||||
- 活动计划可以提交以便团队同步,但不得把一次性实现步骤写进长期规范。
|
||||
- 继续遵守现有 API、SpacetimeDB、AGC、编码和中文文档约束;本 skill 不替代专题门禁。
|
||||
- 文档任务至少运行 `npm run check:doc-index`、`npm run check:encoding` 和 `git diff --check`;代码任务再运行范围匹配的测试、类型检查、schema/OpenAPI 或运行时 smoke。
|
||||
@@ -40,6 +40,8 @@ temp*build*/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/win-x64/codex-path/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/win-x64/codex-resources/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/win-x64/codex-package.json
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/plugins/
|
||||
/plugins/agc-cocos-editor/native/payload/
|
||||
/apps/ai-game-creator-shell/logs/
|
||||
/apps/ai-game-creator-shell/.llm-drafts/
|
||||
/apps/ai-game-creator-shell/game-creator.config.local.json
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
3. [`docs/project-memory/README.md`](docs/project-memory/README.md)、[`project-overview.md`](docs/project-memory/shared-memory/project-overview.md)、[`team-conventions.md`](docs/project-memory/shared-memory/team-conventions.md)、[`development-workflow.md`](docs/project-memory/shared-memory/development-workflow.md)。
|
||||
4. 与任务相关的 [`decision-log.md`](docs/project-memory/shared-memory/decision-log.md)、[`pitfalls.md`](docs/project-memory/shared-memory/pitfalls.md)、[`docs/README.md`](docs/README.md) 和当前专题文档。
|
||||
- 落地工程修改前,先确认是否已有足够具体的 PRD、技术方案或当前融合文档;文档仍存在编码级歧义时,先补文档再编码。
|
||||
- 跨模块功能、公开 API/DTO、SpacetimeDB schema、AGC/Runtime 或复杂 UI 状态链路必须按 [`docs/【协作规范】规范驱动开发工作流-2026-09-12.md`](docs/【协作规范】规范驱动开发工作流-2026-09-12.md) 先完成主规范、里程碑规范和单里程碑实现计划;评审与验收门禁未通过前不得进入下一里程碑。局部修复、文案和无行为变化重构继续走轻量流程。
|
||||
- 本仓库的本地 RAG 位于 [`scripts/rag/`](scripts/rag/);RAG 只作为候选上下文,不替代打开源文件核对。默认不安装 RAG 运行时依赖,需要启用时必须先询问用户,并只安装到 gitignored 的 `.rag/runtime/`。
|
||||
|
||||
## 绝对约束
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# resources/plugins 由 build.rs 从 plugins/ 复制生成,属于构建产物。
|
||||
# 它在 dev 监听范围内,重新生成会让 Tauri dev 误判为源码改动而触发
|
||||
# “构建 -> 监听 -> 再构建”的自触发循环。
|
||||
resources/plugins/
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@genarrative/ai-game-creator-shell",
|
||||
"private": true,
|
||||
"version": "0.1.12",
|
||||
"version": "0.1.27",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "node scripts/start-tauri-dev.mjs",
|
||||
|
||||
@@ -371,7 +371,15 @@ async function runMissingConfigWizard(setActiveChild, explicitConfigDir) {
|
||||
}
|
||||
}
|
||||
|
||||
async function secureWindowsPrivateRuntimePath(targetPath, options) {
|
||||
async function secureWindowsPrivateRuntimePath(
|
||||
targetPath,
|
||||
options,
|
||||
secureWindowsPath = null,
|
||||
) {
|
||||
if (secureWindowsPath) {
|
||||
await secureWindowsPath(targetPath, options);
|
||||
return;
|
||||
}
|
||||
const { secureWindowsGameCreatorPathForCurrentUser } = await import(
|
||||
'./game-creator-config-wizard.mjs'
|
||||
);
|
||||
@@ -383,6 +391,7 @@ async function copyPrivateRuntimeConfigEntry(
|
||||
runtimeConfigDir,
|
||||
fileName,
|
||||
required,
|
||||
secureWindowsPath = null,
|
||||
) {
|
||||
const sourcePath = path.join(sourceConfigDir, fileName);
|
||||
const sourceMetadata = await lstat(sourcePath).catch((error) => {
|
||||
@@ -402,9 +411,11 @@ async function copyPrivateRuntimeConfigEntry(
|
||||
const sourceBytes = await readFile(sourcePath);
|
||||
const destinationFile = await open(destinationPath, 'wx', 0o600);
|
||||
try {
|
||||
await secureWindowsPrivateRuntimePath(destinationPath, {
|
||||
isDirectory: false,
|
||||
});
|
||||
await secureWindowsPrivateRuntimePath(
|
||||
destinationPath,
|
||||
{ isDirectory: false },
|
||||
secureWindowsPath,
|
||||
);
|
||||
await destinationFile.writeFile(sourceBytes);
|
||||
await destinationFile.sync();
|
||||
} finally {
|
||||
@@ -437,7 +448,11 @@ async function copyPrivateRuntimeConfigEntry(
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function prepareSwarmTestRuntimeConfig(sourceConfigDir, tempRoot) {
|
||||
export async function prepareSwarmTestRuntimeConfig(
|
||||
sourceConfigDir,
|
||||
tempRoot,
|
||||
{ secureWindowsPath = null } = {},
|
||||
) {
|
||||
if (!path.isAbsolute(sourceConfigDir)) {
|
||||
throw new Error('配置来源目录必须是绝对路径');
|
||||
}
|
||||
@@ -457,9 +472,11 @@ export async function prepareSwarmTestRuntimeConfig(sourceConfigDir, tempRoot) {
|
||||
);
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
await secureWindowsPrivateRuntimePath(runtimeConfigDir, {
|
||||
isDirectory: true,
|
||||
});
|
||||
await secureWindowsPrivateRuntimePath(
|
||||
runtimeConfigDir,
|
||||
{ isDirectory: true },
|
||||
secureWindowsPath,
|
||||
);
|
||||
} else {
|
||||
await chmod(runtimeConfigDir, 0o700);
|
||||
}
|
||||
@@ -477,12 +494,14 @@ export async function prepareSwarmTestRuntimeConfig(sourceConfigDir, tempRoot) {
|
||||
runtimeConfigDir,
|
||||
configFileName,
|
||||
true,
|
||||
secureWindowsPath,
|
||||
);
|
||||
await copyPrivateRuntimeConfigEntry(
|
||||
canonicalSourceConfigDir,
|
||||
runtimeConfigDir,
|
||||
localConfigFileName,
|
||||
false,
|
||||
secureWindowsPath,
|
||||
);
|
||||
return {
|
||||
path: await realpath(runtimeConfigDir),
|
||||
|
||||
@@ -4,6 +4,11 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import {
|
||||
defaultEditorFeatures,
|
||||
withDefaultCargoFeatures,
|
||||
} from './cargo-features.mjs';
|
||||
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const defaultReleaseTarget = 'x86_64-pc-windows-msvc';
|
||||
const releaseTarget =
|
||||
@@ -159,10 +164,30 @@ export async function prepareReleaseVersion() {
|
||||
return nextVersion;
|
||||
}
|
||||
|
||||
export function runTauriBuild(args = []) {
|
||||
export function buildTauriBuildArguments(
|
||||
args = [],
|
||||
target = releaseTarget,
|
||||
platform = process.platform,
|
||||
) {
|
||||
const noBundle = args.includes('--no-bundle');
|
||||
const hasTarget = args.includes('--target');
|
||||
const targetArgs = noBundle || hasTarget ? [] : ['--target', releaseTarget];
|
||||
const targetIndex = args.indexOf('--target');
|
||||
const explicitTarget =
|
||||
targetIndex >= 0
|
||||
? args[targetIndex + 1]
|
||||
: args
|
||||
.find((value) => value.startsWith('--target='))
|
||||
?.slice('--target='.length);
|
||||
const targetArgs = noBundle || explicitTarget ? [] : ['--target', target];
|
||||
const features = defaultEditorFeatures(
|
||||
explicitTarget || (noBundle ? platform : target),
|
||||
);
|
||||
return [
|
||||
'build',
|
||||
...withDefaultCargoFeatures([...targetArgs, ...args], features),
|
||||
];
|
||||
}
|
||||
|
||||
export function runTauriBuild(args = []) {
|
||||
const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm';
|
||||
const result = spawnSync(
|
||||
npmCommand,
|
||||
@@ -172,9 +197,7 @@ export function runTauriBuild(args = []) {
|
||||
'exec',
|
||||
'tauri',
|
||||
'--',
|
||||
'build',
|
||||
...targetArgs,
|
||||
...args,
|
||||
...buildTauriBuildArguments(args),
|
||||
],
|
||||
{ cwd: appRoot, stdio: 'inherit', shell: process.platform === 'win32' },
|
||||
);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
/** 默认桌面能力;显式 feature 参数优先,不把应用参数当 Cargo 参数。 */
|
||||
export function withDefaultCargoFeatures(argv, features) {
|
||||
const separator = argv.indexOf('--');
|
||||
const cargoArgs = separator < 0 ? argv : argv.slice(0, separator);
|
||||
if (
|
||||
!features.length ||
|
||||
cargoArgs.some(
|
||||
(value) =>
|
||||
value === '--features' ||
|
||||
value === '-f' ||
|
||||
value.startsWith('--features=') ||
|
||||
/^-f.+/u.test(value),
|
||||
)
|
||||
) {
|
||||
return argv;
|
||||
}
|
||||
return [`--features=${features.join(',')}`, ...argv];
|
||||
}
|
||||
|
||||
export function defaultEditorFeatures(target) {
|
||||
return target === 'win32' || target.includes('windows')
|
||||
? ['cocos-editor-execute']
|
||||
: [];
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
|
||||
import { buildTauriBuildArguments } from './build-release.mjs';
|
||||
import { withDefaultCargoFeatures } from './cargo-features.mjs';
|
||||
|
||||
test('Windows release includes the same editor feature as development', () => {
|
||||
assert.deepEqual(
|
||||
buildTauriBuildArguments([], 'x86_64-pc-windows-msvc', 'win32'),
|
||||
[
|
||||
'build',
|
||||
'--features=cocos-editor-execute',
|
||||
'--target',
|
||||
'x86_64-pc-windows-msvc',
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
buildTauriBuildArguments(
|
||||
['--no-bundle'],
|
||||
'x86_64-pc-windows-msvc',
|
||||
'linux',
|
||||
),
|
||||
['build', '--no-bundle'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
buildTauriBuildArguments(['--target=aarch64-apple-darwin']),
|
||||
['build', '--target=aarch64-apple-darwin'],
|
||||
);
|
||||
});
|
||||
test('explicit Cargo features override defaults in every supported spelling', () => {
|
||||
for (const args of [
|
||||
['--features', 'custom'],
|
||||
['--features=custom'],
|
||||
['-f', 'custom'],
|
||||
['-fcustom'],
|
||||
]) {
|
||||
assert.deepEqual(
|
||||
withDefaultCargoFeatures(args, ['cocos-editor-execute']),
|
||||
args,
|
||||
);
|
||||
}
|
||||
assert.deepEqual(
|
||||
withDefaultCargoFeatures(
|
||||
['--', '--features=app'],
|
||||
['cocos-editor-execute'],
|
||||
),
|
||||
['--features=cocos-editor-execute', '--', '--features=app'],
|
||||
);
|
||||
});
|
||||
@@ -120,6 +120,16 @@ const allowedUncalledTauriCommands = [
|
||||
'stop_local_game_preview_if_matches',
|
||||
'start_game_creator_external_mcp',
|
||||
'stop_game_creator_external_mcp',
|
||||
'list_agc_plugins',
|
||||
'list_agc_extensions',
|
||||
'refresh_agc_plugins',
|
||||
'start_agc_plugin',
|
||||
'stop_agc_plugin',
|
||||
'reload_agc_plugin',
|
||||
'call_agc_plugin',
|
||||
'read_agc_plugin_panel',
|
||||
'set_agc_plugin_project_path',
|
||||
'set_agc_plugin_enabled',
|
||||
];
|
||||
const sourceExtensions = new Set([
|
||||
'.json',
|
||||
@@ -1291,7 +1301,7 @@ if (tauriConfig.identifier !== 'world.genarrative.ai-game-creator') {
|
||||
const expectedBundledDesignAgentResources = {
|
||||
'design-agent': 'design-agent',
|
||||
};
|
||||
const expectedBundledCodexResources = {
|
||||
const expectedBundledWindowsResources = {
|
||||
'resources/codex/win-x64/bin/codex.exe': 'codex/win-x64/bin/codex.exe',
|
||||
'resources/codex/win-x64/bin/codex-code-mode-host.exe':
|
||||
'codex/win-x64/bin/codex-code-mode-host.exe',
|
||||
@@ -1305,6 +1315,7 @@ const expectedBundledCodexResources = {
|
||||
'codex/win-x64/codex-package.json',
|
||||
'resources/codex/win-x64/NOTICE.md': 'codex/win-x64/NOTICE.md',
|
||||
'resources/codex/win-x64/manifest.json': 'codex/win-x64/manifest.json',
|
||||
'resources/plugins': 'plugins',
|
||||
};
|
||||
assert.deepEqual(
|
||||
tauriConfig.bundle?.resources,
|
||||
@@ -1320,8 +1331,8 @@ for (const key of Object.keys(tauriConfig.bundle?.resources ?? {})) {
|
||||
}
|
||||
assert.deepEqual(
|
||||
windowsTauriConfig.bundle?.resources,
|
||||
expectedBundledCodexResources,
|
||||
'AI game creator shell Windows Tauri config must bundle the complete pinned Codex resource set',
|
||||
expectedBundledWindowsResources,
|
||||
'AI game creator shell Windows Tauri config must bundle the complete pinned Codex resource set and Cocos bridge payload directory',
|
||||
);
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(
|
||||
|
||||
@@ -436,6 +436,10 @@ function spawnChild(command, args, options, spawnImpl = spawn) {
|
||||
const child = spawnImpl(command, args, {
|
||||
...options,
|
||||
shell: useShell,
|
||||
// npm.cmd and the Windows shell otherwise create a visible console for
|
||||
// every service in the dev stack. Their stdout/stderr is already inherited
|
||||
// by the launcher, so no separate terminal window is useful.
|
||||
windowsHide: process.platform === 'win32' ? true : options.windowsHide,
|
||||
// POSIX 下让每个长驻服务拥有独立进程组,退出时可以连同 npm、
|
||||
// Node、Cargo 及其子进程一起清理,避免残留订阅任务持续刷日志。
|
||||
detached: isPosix,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { withDefaultCargoFeatures } from './cargo-features.mjs';
|
||||
import {
|
||||
readAgcDevEndpoint,
|
||||
resolveAgcDevEndpoint,
|
||||
@@ -47,6 +48,24 @@ function buildTauriArguments(argv, devUrl = readAgcDevEndpoint().url) {
|
||||
];
|
||||
}
|
||||
|
||||
// `agc_cocos_execute` 与 Cocos 编辑器适配器只在 `cocos-editor-execute` feature 下
|
||||
// 注册。开发构建默认在 Windows 打开它,否则 Agent 的工具清单里根本没有该工具,
|
||||
// 只能退化成改写脚本。可用 AGC_DEV_CARGO_FEATURES(逗号分隔)覆盖,传空串即关闭。
|
||||
function readDevCargoFeatures(env = process.env) {
|
||||
const override = env.AGC_DEV_CARGO_FEATURES;
|
||||
if (override !== undefined) {
|
||||
return override
|
||||
.split(',')
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
return process.platform === 'win32' ? ['cocos-editor-execute'] : [];
|
||||
}
|
||||
|
||||
function withDevCargoFeatures(argv, features = readDevCargoFeatures()) {
|
||||
return withDefaultCargoFeatures(argv, features);
|
||||
}
|
||||
|
||||
function spawnTauriCli(argv, { env = process.env } = {}) {
|
||||
return spawnChild(process.execPath, [tauriCliPath, ...argv], {
|
||||
cwd: appRoot,
|
||||
@@ -110,7 +129,10 @@ async function runTauriDev(
|
||||
shutdownRequested.then(() => false),
|
||||
]);
|
||||
if (!prepared || shutdownSignal) return 1;
|
||||
const tauriArguments = buildTauriArguments(argv, endpoint.url);
|
||||
const tauriArguments = buildTauriArguments(
|
||||
withDevCargoFeatures(argv),
|
||||
endpoint.url,
|
||||
);
|
||||
child = spawnCli(tauriArguments, {
|
||||
env: {
|
||||
...withAgcDevEndpointEnv(endpoint),
|
||||
@@ -207,6 +229,7 @@ export {
|
||||
isDirectModuleExecution,
|
||||
runTauriDev,
|
||||
spawnTauriCli,
|
||||
withDevCargoFeatures,
|
||||
};
|
||||
|
||||
if (isDirectModuleExecution()) {
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# resources/plugins 由 build.rs 从 plugins/ 复制生成,属于构建产物。
|
||||
# 它在 dev 监听范围内,重新生成会让 Tauri dev 误判为源码改动而触发
|
||||
# “构建 -> 监听 -> 再构建”的自触发循环。
|
||||
resources/plugins/
|
||||
+26
-1
@@ -733,6 +733,20 @@ dependencies = [
|
||||
"error-code",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cocos-editor-bridge"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"editor-adapter-api",
|
||||
"reqwest 0.12.28",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tungstenite",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "combine"
|
||||
version = "4.6.7"
|
||||
@@ -1205,6 +1219,14 @@ version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
|
||||
|
||||
[[package]]
|
||||
name = "editor-adapter-api"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.16.0"
|
||||
@@ -1703,12 +1725,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "genarrative-ai-game-creator-shell"
|
||||
version = "0.1.12"
|
||||
version = "0.1.27"
|
||||
dependencies = [
|
||||
"agent-runtime-core",
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"chromiumoxide",
|
||||
"cocos-editor-bridge",
|
||||
"editor-adapter-api",
|
||||
"futures",
|
||||
"getrandom 0.3.4",
|
||||
"http",
|
||||
@@ -4281,6 +4305,7 @@ dependencies = [
|
||||
"cookie",
|
||||
"cookie_store",
|
||||
"encoding_rs",
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"h2",
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
[package]
|
||||
name = "genarrative-ai-game-creator-shell"
|
||||
version = "0.1.12"
|
||||
version = "0.1.27"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
default = []
|
||||
cocos-editor = ["cocos-editor-bridge/process-discovery"]
|
||||
cocos-editor-execute = ["cocos-editor", "cocos-editor-bridge/windows-bootstrap"]
|
||||
cocos-editor-injection = ["cocos-editor-execute", "cocos-editor-bridge/windows-injection"]
|
||||
|
||||
[build-dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
@@ -19,6 +22,8 @@ ts-rs = "12.0.1"
|
||||
typed_floats = { version = "1.0.7", features = ["serde"] }
|
||||
nalgebra = { version = "0.35.0", features = ["serde-serialize"] }
|
||||
agent-runtime-core = { path = "../../../server-rs/crates/agent-runtime-core" }
|
||||
cocos-editor-bridge = { path = "../../../plugins/agc-cocos-editor/native/cocos-editor-bridge", default-features = false }
|
||||
editor-adapter-api = { path = "../../../server-rs/crates/editor-adapter-api" }
|
||||
base64 = "0.22"
|
||||
axum = "0.8"
|
||||
chromiumoxide = "0.9.1"
|
||||
|
||||
@@ -182,6 +182,8 @@ fn main() {
|
||||
);
|
||||
let manifest_path = manifest_dir.join("prompts/runtime/manifest.json");
|
||||
stage_bundled_codex_cli(&manifest_dir);
|
||||
stage_plugin_workspace(&manifest_dir);
|
||||
stage_cocos_editor_payload(&manifest_dir);
|
||||
let compiled = runtime_prompt_bundle::compile_manifest(&manifest_path)
|
||||
.unwrap_or_else(|error| panic!("Prompt Bundle 编译失败:{error}"));
|
||||
validate_seed_task_catalog(&compiled);
|
||||
@@ -203,3 +205,146 @@ fn main() {
|
||||
}
|
||||
tauri_build::build()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn stage_cocos_editor_payload(manifest_dir: &std::path::Path) {
|
||||
if std::env::var_os("CARGO_FEATURE_COCOS_EDITOR_INJECTION").is_none() {
|
||||
return;
|
||||
}
|
||||
let out_dir = std::path::PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR"));
|
||||
let profile_dir = out_dir
|
||||
.ancestors()
|
||||
.find(|path| path.file_name().is_some_and(|name| name == "build"))
|
||||
.and_then(|build_dir| build_dir.parent())
|
||||
.expect("AGC Cargo profile directory not found");
|
||||
let candidates = [
|
||||
profile_dir.join("deps/cocos_editor_bridge.dll"),
|
||||
profile_dir.join("cocos_editor_bridge.dll"),
|
||||
];
|
||||
let source = candidates
|
||||
.iter()
|
||||
.find(|path| path.is_file())
|
||||
.unwrap_or_else(|| {
|
||||
panic!(
|
||||
"Cocos bridge native payload 未构建:{}",
|
||||
candidates
|
||||
.iter()
|
||||
.map(|p| p.display().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(";")
|
||||
)
|
||||
});
|
||||
for destination in [
|
||||
// 插件工作区里的 payload 是开发态与打包态的唯一真源。
|
||||
manifest_dir
|
||||
.join("../../../plugins/agc-cocos-editor/native/payload/cocos-editor-bridge.dll"),
|
||||
// 随包资源目录与 tauri.windows.conf.json 的 `resources/plugins` 映射保持一致。
|
||||
manifest_dir
|
||||
.join("resources/plugins/agc-cocos-editor/native/payload/cocos-editor-bridge.dll"),
|
||||
] {
|
||||
std::fs::create_dir_all(destination.parent().expect("payload resource parent"))
|
||||
.expect("创建 Cocos bridge payload 目录失败");
|
||||
std::fs::copy(source, &destination).expect("复制 Cocos bridge native payload 失败");
|
||||
}
|
||||
println!("cargo:rerun-if-changed={}", source.display());
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn stage_cocos_editor_payload(_manifest_dir: &std::path::Path) {}
|
||||
|
||||
/// 把 `plugins/` 工作区里的插件包随包映射到应用资源目录。
|
||||
///
|
||||
/// 只复制插件运行需要的清单、入口、面板和 native payload,不复制 native 源码、
|
||||
/// Cargo target 目录或 node_modules。
|
||||
#[cfg(windows)]
|
||||
fn stage_plugin_workspace(manifest_dir: &std::path::Path) {
|
||||
let repo_root = manifest_dir
|
||||
.parent()
|
||||
.and_then(|app_root| app_root.parent())
|
||||
.and_then(|apps_dir| apps_dir.parent())
|
||||
.expect("AGC 应用必须位于仓库 apps 目录下")
|
||||
.to_path_buf();
|
||||
let workspace = repo_root.join("plugins");
|
||||
let destination_root = manifest_dir.join("resources/plugins");
|
||||
std::fs::create_dir_all(&destination_root).expect("创建插件资源目录失败");
|
||||
let entries = match std::fs::read_dir(&workspace) {
|
||||
Ok(entries) => entries,
|
||||
Err(_) => return,
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let plugin_root = entry.path();
|
||||
if !plugin_root.is_dir() || !plugin_root.join("plugin.json").is_file() {
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let destination = destination_root.join(&name);
|
||||
copy_plugin_file(
|
||||
&plugin_root.join("plugin.json"),
|
||||
&destination.join("plugin.json"),
|
||||
);
|
||||
for relative in [
|
||||
std::path::PathBuf::from("src"),
|
||||
std::path::PathBuf::from("panels"),
|
||||
std::path::PathBuf::from("native/payload"),
|
||||
] {
|
||||
copy_plugin_tree(&plugin_root.join(&relative), &destination.join(&relative));
|
||||
}
|
||||
println!("cargo:rerun-if-changed={}", plugin_root.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn stage_plugin_file(source: &std::path::Path, destination: &std::path::Path) {
|
||||
let Ok(bytes) = std::fs::read(source) else {
|
||||
return;
|
||||
};
|
||||
if std::fs::read(destination).is_ok_and(|existing| existing == bytes) {
|
||||
return;
|
||||
}
|
||||
if let Some(parent) = destination.parent() {
|
||||
std::fs::create_dir_all(parent).expect("创建插件资源目录失败");
|
||||
}
|
||||
std::fs::write(destination, bytes).expect("复制插件资源失败");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn copy_plugin_tree(source: &std::path::Path, destination: &std::path::Path) {
|
||||
let entries = match std::fs::read_dir(source) {
|
||||
Ok(entries) => entries,
|
||||
Err(_) => return,
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let target = destination.join(entry.file_name());
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if matches!(name.as_ref(), "target" | "node_modules" | ".git") {
|
||||
continue;
|
||||
}
|
||||
std::fs::create_dir_all(&target).expect("创建插件资源目录失败");
|
||||
copy_plugin_tree(&path, &target);
|
||||
} else {
|
||||
// 测试文件不随包分发。
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if name.contains(".test.") {
|
||||
continue;
|
||||
}
|
||||
stage_plugin_file(&path, &target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn copy_plugin_file(source: &std::path::Path, destination: &std::path::Path) {
|
||||
if !source.is_file() {
|
||||
return;
|
||||
}
|
||||
std::fs::create_dir_all(destination.parent().expect("插件资源父目录"))
|
||||
.expect("创建插件资源目录失败");
|
||||
std::fs::copy(source, destination).expect("复制插件资源失败");
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn stage_plugin_workspace(_manifest_dir: &std::path::Path) {}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "main",
|
||||
"description": "AI 游戏创作主窗口允许读取系统剪贴板图片,用于粘贴素材附件。",
|
||||
"description": "AI 游戏创作主窗口允许读取系统剪贴板图片,用于粘贴素材附件;允许弹出原生打开/保存对话框用于素材上传与导出。",
|
||||
"windows": ["client"],
|
||||
"permissions": [
|
||||
"clipboard-manager:allow-read-image",
|
||||
@@ -21,6 +21,7 @@
|
||||
]
|
||||
},
|
||||
"opener:default",
|
||||
"dialog:allow-open"
|
||||
"dialog:allow-open",
|
||||
"dialog:allow-save"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
你是游戏创作需求的润色助手。把用户给创作 Agent 的一段需求改写成更清晰、可执行的中文需求。要求:保留用户的原始意图、玩法、美术方向、数值与限制条件,不得新增或删除需求点,不得替用户做决定,不得写成方案书或任务清单。只输出润色后的需求正文,不要解释、不要引言、不要 Markdown 标记、不要引号包裹、不要重复用户原文;无法润色时原样输出用户输入。
|
||||
@@ -0,0 +1 @@
|
||||
*.dll
|
||||
@@ -16,6 +16,7 @@ mod design_runtime;
|
||||
mod design_tools;
|
||||
mod direct_codex_attachments;
|
||||
mod direct_codex_audit;
|
||||
mod direct_codex_references;
|
||||
mod direct_project_history;
|
||||
mod direct_project_turn_history;
|
||||
mod direct_runtime;
|
||||
@@ -43,6 +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_project_history::*;
|
||||
pub(crate) use direct_project_turn_history::*;
|
||||
pub(crate) use direct_runtime::*;
|
||||
|
||||
@@ -16,7 +16,21 @@ const GAME_CREATOR_CODEX_APP_SERVER_REMOTE_CONTROL_DISABLED_ENV: &str =
|
||||
"CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED";
|
||||
const GAME_CREATOR_CODEX_AUTH_BRIDGE_API_BASE_URL: &str = "https://api.openai.com/v1";
|
||||
const GAME_CREATOR_CODEX_APP_SERVER_PROTOCOL: &str = "genarrative-codex-app-server.v3";
|
||||
const GAME_CREATOR_CODEX_APP_SERVER_LINE_MAX_BYTES: usize = 4 * 1024 * 1024;
|
||||
/// 单条 JSON-RPC 消息(NDJSON 一行)的字节上限:**同时**是 stdout 读侧上限与 stdin 写侧守卫。
|
||||
///
|
||||
/// 两侧必须共用这一个常量。2026-09-11 的隔离探针实测(codex-cli 0.147.0,AGC 捆绑版本):
|
||||
/// `experimentalRawEvents: true` 的线程收到 `thread/inject_items` 后,会**逐条原样回显**
|
||||
/// `rawResponseItem/completed` —— 注入一个 5 MiB 的 item,stdout 就回一条 5 243 245 字节的单行。
|
||||
/// 因此「我们注入得进去」就必须「我们读得回来」;两侧取不同值(曾为读侧 4 MiB、图片单张 5 MiB/
|
||||
/// 单次 16 MiB)会让一次**原本合法**的注入在随后的读行里被误判成连接级故障。
|
||||
///
|
||||
/// 32 MiB 的依据:单张图 base64 data URL 上限 10 MiB(`..._IMAGE_MAX_BYTES * 2`)、单次请求图片
|
||||
/// 总量上限 16 MiB(`..._IMAGE_TOTAL_MAX_BYTES`,base64 后约 21.3 MiB)+ JSON 信封,取 32 MiB
|
||||
/// 覆盖现有写侧全部单一消息;再大就失去内存/DoS 边界的意义(每连接单行最多驻留该数量级)。
|
||||
const GAME_CREATOR_CODEX_APP_SERVER_LINE_MAX_BYTES: usize = 32 * 1024 * 1024;
|
||||
/// 回显信封余量:item 会被包进 `{"method":"rawResponseItem/completed","params":{…,"item":…}}`
|
||||
/// 之后再输出,所以**单条 item** 允许占用的字节数必须小于整行上限。
|
||||
const GAME_CREATOR_CODEX_APP_SERVER_ECHO_ENVELOPE_MARGIN_BYTES: usize = 8 * 1024;
|
||||
const GAME_CREATOR_CODEX_APP_SERVER_STDERR_RECORD_MAX_BYTES: usize = 256 * 1024;
|
||||
const GAME_CREATOR_CODEX_APP_SERVER_AUTH_MAX_BYTES: usize = 1024 * 1024;
|
||||
const GAME_CREATOR_CODEX_APP_SERVER_BACKLOG_TURN_MAX: usize = 128;
|
||||
@@ -44,6 +58,13 @@ pub(in crate::agent) const GAME_CREATOR_CODEX_APP_SERVER_TERMINAL_UNKNOWN_PREFIX
|
||||
"codex-app-server-terminal-unknown:";
|
||||
pub(in crate::agent) const GAME_CREATOR_CODEX_APP_SERVER_ERROR_KIND_PREFIX: &str =
|
||||
"codex-app-server-error:";
|
||||
/// DirectProject 历史注入超限:专属前缀,供 `direct_runtime.rs` 判「可重试性」与给专属恢复提示。
|
||||
///
|
||||
/// 命中它意味着**同一份历史每次都会得到同一结论**(历史文件不变则载荷不变),所以按不可重试
|
||||
/// 处理,与 `DIRECT_PROJECT_HISTORY_SHAPE_FAILURE_MARKERS` 同口径(见技术方案
|
||||
/// `docs/technical/【技术方案】DirectProject Codex原始历史与异常恢复-2026-09-04.md` 末节)。
|
||||
pub(in crate::agent) const DIRECT_PROJECT_HISTORY_INJECTION_OVERSIZE_PREFIX: &str =
|
||||
"DirectProject 历史注入载荷超过单行上限";
|
||||
const CODEX_APP_SERVER_BASE_INSTRUCTIONS_FALLBACK: &str =
|
||||
"You are Codex working directly in the user's Genarrative game project. Follow the AGC system instructions, inspect and modify files in the current workspace when needed, and report concrete progress and failures. Do not invent completion evidence.";
|
||||
const DIRECT_CODEX_BASE_INSTRUCTIONS_FALLBACK: &str =
|
||||
@@ -305,6 +326,35 @@ fn game_creator_codex_app_server_error_detail_indicates_auth_failure(
|
||||
|| detail.contains("http 403")
|
||||
}
|
||||
|
||||
fn game_creator_codex_app_server_error_detail(error: &serde_json::Value) -> String {
|
||||
let Some(error) = error.as_object() else {
|
||||
return String::new();
|
||||
};
|
||||
["message", "additionalDetails", "code"]
|
||||
.into_iter()
|
||||
.filter_map(|field| error.get(field).and_then(serde_json::Value::as_str))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.to_ascii_lowercase()
|
||||
}
|
||||
|
||||
fn game_creator_codex_app_server_error_detail_indicates_stream_requirement(
|
||||
error: &serde_json::Value,
|
||||
) -> bool {
|
||||
let detail = game_creator_codex_app_server_error_detail(error);
|
||||
detail.contains("stream must be set to true")
|
||||
|| detail.contains("stream=true")
|
||||
|| detail.contains("stream is required")
|
||||
}
|
||||
|
||||
fn game_creator_codex_app_server_error_detail_indicates_timeout(error: &serde_json::Value) -> bool {
|
||||
let detail = game_creator_codex_app_server_error_detail(error);
|
||||
detail.contains("timed out")
|
||||
|| detail.contains("timeout")
|
||||
|| detail.contains("request deadline exceeded")
|
||||
|| detail.contains("deadline exceeded")
|
||||
}
|
||||
|
||||
fn game_creator_codex_app_server_error_detail_indicates_request_too_large(
|
||||
error: &serde_json::Value,
|
||||
) -> bool {
|
||||
@@ -362,6 +412,15 @@ fn game_creator_codex_app_server_failed_turn_error(
|
||||
if game_creator_codex_app_server_error_detail_indicates_request_too_large(error) {
|
||||
return game_creator_codex_app_server_error_kind("request-too-large");
|
||||
}
|
||||
if game_creator_codex_app_server_error_detail_indicates_stream_requirement(error) {
|
||||
return game_creator_codex_app_server_error_kind("stream-required");
|
||||
}
|
||||
if game_creator_codex_app_server_error_detail_indicates_timeout(error) {
|
||||
return platform_llm::LlmError::Connectivity {
|
||||
attempts: 1,
|
||||
message: "Codex app-server 上游请求超时".to_string(),
|
||||
};
|
||||
}
|
||||
if game_creator_codex_app_server_error_detail_indicates_auth_failure(error) {
|
||||
return game_creator_codex_app_server_error_kind("unauthorized");
|
||||
}
|
||||
@@ -1070,6 +1129,7 @@ fn game_creator_codex_app_server_pool_key(
|
||||
"skillPackIdentity": skill_pack_identity,
|
||||
"clientSkillIdentity": client_skill_identity,
|
||||
"clientMcpIdentity": client_mcp_identity,
|
||||
"builtinPluginTools": crate::builtin_plugins::available_agent_tools(),
|
||||
"controlledWebSearch": llm.web_search_enabled,
|
||||
"directToolBridgeProtocol": if workspace_mode == CodexAppServerWorkspaceMode::DirectProject { DIRECT_TOOL_BRIDGE_PROTOCOL } else { "disabled" },
|
||||
"providerProxyProtocol": if workspace_mode == CodexAppServerWorkspaceMode::DirectProject { CODEX_PROVIDER_PROXY_PROTOCOL } else { "disabled" },
|
||||
@@ -2296,6 +2356,11 @@ impl CodexAppServerConnection {
|
||||
let mut bytes = serde_json::to_vec(value)
|
||||
.map_err(|error| format!("序列化 Codex app-server JSON-RPC 失败:{error}"))?;
|
||||
bytes.push(b'\n');
|
||||
// 写侧守卫:绝不写出自己读不回来的行(两侧共用 `..._LINE_MAX_BYTES`)。
|
||||
// 失败关闭并给出字节数,**不做任何截断**。
|
||||
if let Some(error) = game_creator_codex_app_server_message_oversize_error(bytes.len()) {
|
||||
return Err(error);
|
||||
}
|
||||
let mut writer = self.inner.writer.lock().await;
|
||||
writer
|
||||
.write_all(&bytes)
|
||||
@@ -2463,10 +2528,12 @@ impl CodexAppServerConnection {
|
||||
// Codex's default provider in Debug builds.
|
||||
self.inner._provider_proxy.is_some() || !llm.api_key.trim().is_empty(),
|
||||
);
|
||||
let result = self
|
||||
.request("thread/start", params)
|
||||
.await
|
||||
.map_err(platform_llm::LlmError::Transport)?;
|
||||
let result = match self.request("thread/start", params).await {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
return Err(platform_llm::LlmError::Transport(error));
|
||||
}
|
||||
};
|
||||
let thread_id = result
|
||||
.pointer("/thread/id")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
@@ -2616,13 +2683,18 @@ impl CodexAppServerConnection {
|
||||
return Err(platform_llm::LlmError::InvalidRequest(error));
|
||||
}
|
||||
};
|
||||
if let Err(error) = self
|
||||
.request(
|
||||
"thread/inject_items",
|
||||
serde_json::json!({"threadId": thread_id, "items": items}),
|
||||
)
|
||||
.await
|
||||
let params = serde_json::json!({"threadId": thread_id.clone(), "items": items});
|
||||
let payload_bytes = serde_json::to_vec(¶ms)
|
||||
.map(|bytes| bytes.len().saturating_add(1))
|
||||
.unwrap_or(usize::MAX);
|
||||
// 注入前的前置校验:失败关闭并指名 itemId 与字节数,**不截断、不摘要、不改写**。
|
||||
if let Some(error) =
|
||||
direct_project_history_injection_oversize_error(¶ms, payload_bytes)
|
||||
{
|
||||
self.release_thread(snapshot, &thread_id).await;
|
||||
return Err(platform_llm::LlmError::InvalidRequest(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));
|
||||
}
|
||||
@@ -3430,6 +3502,61 @@ async fn read_game_creator_codex_app_server_stdout(
|
||||
}
|
||||
}
|
||||
|
||||
/// 写侧守卫的纯函数部分(便于单测):超限时给出带字节数的错误。
|
||||
///
|
||||
/// 与读侧共用同一个上限,保证「我们能注入的」一定「我们读得回来」。
|
||||
fn game_creator_codex_app_server_message_oversize_error(byte_len: usize) -> Option<String> {
|
||||
let limit = GAME_CREATOR_CODEX_APP_SERVER_LINE_MAX_BYTES;
|
||||
(byte_len > limit).then(|| {
|
||||
format!(
|
||||
"Codex app-server JSON-RPC 单行超过大小上限(写侧):{byte_len} 字节 > 上限 {limit} 字节;未发送、未截断"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// DirectProject 历史注入的前置校验(纯函数,便于单测)。
|
||||
///
|
||||
/// 判据来自实测:app-server 会把注入的 item **逐条原样回显**,所以
|
||||
/// ① 单条 item 必须 ≤ 上限 − 回显信封余量;② 整份载荷本身也必须 ≤ 上限。
|
||||
/// 任一不满足即**失败关闭**(指名 `itemId` 与字节数),**不截断、不摘要、不改写**历史。
|
||||
fn direct_project_history_injection_oversize_error(
|
||||
params: &serde_json::Value,
|
||||
payload_bytes: usize,
|
||||
) -> Option<String> {
|
||||
let limit = GAME_CREATOR_CODEX_APP_SERVER_LINE_MAX_BYTES;
|
||||
if payload_bytes > limit {
|
||||
return Some(format!(
|
||||
"{DIRECT_PROJECT_HISTORY_INJECTION_OVERSIZE_PREFIX}:整份历史载荷 {payload_bytes} 字节 > 上限 {limit} 字节;未注入、未截断"
|
||||
));
|
||||
}
|
||||
let Some(items) = params.get("items").and_then(serde_json::Value::as_array) else {
|
||||
return None;
|
||||
};
|
||||
let item_limit = limit.saturating_sub(GAME_CREATOR_CODEX_APP_SERVER_ECHO_ENVELOPE_MARGIN_BYTES);
|
||||
for item in items {
|
||||
let Ok(bytes) = serde_json::to_vec(item) else {
|
||||
return Some(format!(
|
||||
"{DIRECT_PROJECT_HISTORY_INJECTION_OVERSIZE_PREFIX}:历史记录无法序列化;未注入、未截断"
|
||||
));
|
||||
};
|
||||
if bytes.len() > item_limit {
|
||||
let item_id = item
|
||||
.get("id")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("<无 id>");
|
||||
let item_type = item
|
||||
.get("type")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("<无 type>");
|
||||
return Some(format!(
|
||||
"{DIRECT_PROJECT_HISTORY_INJECTION_OVERSIZE_PREFIX}:单条记录 {} 字节 > 单条上限 {item_limit} 字节(itemId={item_id}, type={item_type});未注入、未截断",
|
||||
bytes.len()
|
||||
));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
async fn read_bounded_game_creator_codex_app_server_line<R>(
|
||||
reader: &mut R,
|
||||
) -> Result<Option<Vec<u8>>, String>
|
||||
@@ -4810,6 +4937,37 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_app_server_failed_turn_maps_stream_and_timeout_details() {
|
||||
let stream_error = game_creator_codex_app_server_failed_turn_error(&serde_json::json!({
|
||||
"status": "failed",
|
||||
"error": {
|
||||
"message": "Stream must be set to true",
|
||||
"codexErrorInfo": "other"
|
||||
}
|
||||
}));
|
||||
assert_eq!(
|
||||
stream_error,
|
||||
platform_llm::LlmError::InvalidRequest(
|
||||
"codex-app-server-error:stream-required".to_string()
|
||||
)
|
||||
);
|
||||
let timeout_error = game_creator_codex_app_server_failed_turn_error(&serde_json::json!({
|
||||
"status": "failed",
|
||||
"error": {
|
||||
"message": "provider request timed out",
|
||||
"codexErrorInfo": "other"
|
||||
}
|
||||
}));
|
||||
assert_eq!(
|
||||
timeout_error,
|
||||
platform_llm::LlmError::Connectivity {
|
||||
attempts: 1,
|
||||
message: "Codex app-server 上游请求超时".to_string()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_app_server_failed_turn_maps_insufficient_mud_points_to_stable_upstream_error() {
|
||||
for detail in [
|
||||
@@ -5051,6 +5209,42 @@ while IFS= read -r line; do :; done
|
||||
assert_ne!(disabled, enabled);
|
||||
}
|
||||
|
||||
#[cfg(feature = "cocos-editor-execute")]
|
||||
#[test]
|
||||
fn codex_app_server_pool_key_tracks_builtin_plugin_switch() {
|
||||
let _guard = crate::builtin_plugins::test_lock();
|
||||
let config = tempfile::tempdir().unwrap();
|
||||
crate::builtin_plugins::initialize(config.path()).unwrap();
|
||||
let key = || {
|
||||
game_creator_codex_app_server_pool_key(
|
||||
&test_llm(),
|
||||
"codex-cli 0.147.0",
|
||||
&test_snapshot(),
|
||||
"credential",
|
||||
CodexAppServerWorkspaceMode::DirectProject,
|
||||
)
|
||||
};
|
||||
crate::builtin_plugins::set_enabled(
|
||||
crate::builtin_plugins::AGC_COCOS_EDITOR_PLUGIN_ID,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
let disabled = key();
|
||||
crate::builtin_plugins::set_enabled(
|
||||
crate::builtin_plugins::AGC_COCOS_EDITOR_PLUGIN_ID,
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
let enabled = key();
|
||||
assert_ne!(disabled, enabled);
|
||||
crate::builtin_plugins::set_enabled(
|
||||
crate::builtin_plugins::AGC_COCOS_EDITOR_PLUGIN_ID,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(disabled, key());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_file_change_approval_is_limited_to_workspace() {
|
||||
let temp = tempfile::tempdir().expect("temp dir");
|
||||
@@ -5438,6 +5632,66 @@ while IFS= read -r line; do :; done
|
||||
assert!(!diagnostic.contains(std::str::from_utf8(&secret).expect("fixture utf8")));
|
||||
}
|
||||
|
||||
/// 写侧对称守卫:我们绝不写出自己读不回来的行。
|
||||
///
|
||||
/// 与上面那条读侧用例共用 `..._LINE_MAX_BYTES`,所以这条断言同时锁住「两侧同界」这个不变量:
|
||||
/// 上限本身必须放行,上限 + 1 必须失败关闭(而不是被静默截断)。
|
||||
#[test]
|
||||
fn codex_app_server_write_guard_matches_the_read_cap() {
|
||||
assert!(game_creator_codex_app_server_message_oversize_error(
|
||||
GAME_CREATOR_CODEX_APP_SERVER_LINE_MAX_BYTES
|
||||
)
|
||||
.is_none());
|
||||
|
||||
let oversized = GAME_CREATOR_CODEX_APP_SERVER_LINE_MAX_BYTES + 1;
|
||||
let error = game_creator_codex_app_server_message_oversize_error(oversized)
|
||||
.expect("oversized outbound message must be rejected before it is written");
|
||||
assert!(error.contains("单行超过大小上限(写侧)"));
|
||||
assert!(error.contains(&oversized.to_string()));
|
||||
assert!(error.contains("未发送、未截断"));
|
||||
}
|
||||
|
||||
/// DirectProject 历史注入的前置校验:**单条 item** 与**整份载荷**都必须失败关闭。
|
||||
///
|
||||
/// 形状照抄实测(隔离探针,codex-cli 0.147.0):`thread/inject_items` 注入的 item 会被
|
||||
/// app-server 逐条原样回显成一条 `rawResponseItem/completed`,所以「单条 item 超限」就等于
|
||||
/// 「回显行超限」——必须在注入前拦下,而不是让它在读行时变成连接级故障。
|
||||
#[test]
|
||||
fn direct_project_history_injection_rejects_oversized_items_and_payloads() {
|
||||
let ok_params = serde_json::json!({
|
||||
"threadId": "probe-thread",
|
||||
"items": [{ "type": "message", "id": "msg_1", "role": "user" }],
|
||||
});
|
||||
assert!(direct_project_history_injection_oversize_error(&ok_params, 1024).is_none());
|
||||
|
||||
let payload_error = direct_project_history_injection_oversize_error(
|
||||
&ok_params,
|
||||
GAME_CREATOR_CODEX_APP_SERVER_LINE_MAX_BYTES + 1,
|
||||
)
|
||||
.expect("oversized payload must be rejected");
|
||||
assert!(payload_error.contains(DIRECT_PROJECT_HISTORY_INJECTION_OVERSIZE_PREFIX));
|
||||
assert!(payload_error.contains("整份历史载荷"));
|
||||
assert!(payload_error.contains("未注入、未截断"));
|
||||
|
||||
let huge = "x".repeat(GAME_CREATOR_CODEX_APP_SERVER_LINE_MAX_BYTES);
|
||||
let big_params = serde_json::json!({
|
||||
"threadId": "probe-thread",
|
||||
"items": [{
|
||||
"type": "message",
|
||||
"id": "msg_big",
|
||||
"role": "assistant",
|
||||
"content": [{ "type": "output_text", "text": huge }],
|
||||
}],
|
||||
});
|
||||
let item_error = direct_project_history_injection_oversize_error(&big_params, 1024)
|
||||
.expect("oversized single item must be rejected");
|
||||
assert!(item_error.contains(DIRECT_PROJECT_HISTORY_INJECTION_OVERSIZE_PREFIX));
|
||||
assert!(item_error.contains("单条记录"));
|
||||
assert!(item_error.contains("itemId=msg_big"));
|
||||
assert!(item_error.contains("type=message"));
|
||||
assert!(item_error.contains("未注入、未截断"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn codex_app_server_uses_initialize_thread_and_turn_protocol() {
|
||||
|
||||
@@ -229,15 +229,18 @@ fn prepare_design_decision(
|
||||
}
|
||||
if approved {
|
||||
let phase = approve_design_phase(session, request_id)?;
|
||||
let suffix = if phase == "consultant" {
|
||||
""
|
||||
} else {
|
||||
"请开始该阶段工作。"
|
||||
};
|
||||
append_design_user(
|
||||
session,
|
||||
id,
|
||||
format!("用户已批准上一阶段,现在进入 {phase} 阶段。{suffix}"),
|
||||
if phase == "consultant" {
|
||||
format!(
|
||||
"用户已批准上一阶段,现在进入 {phase} 阶段。开始本轮工作前,先调用 get_workflow_status 确认 Runtime 当前阶段;在工具返回前,不要开始顾问工作或断言阶段状态。"
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"用户已批准上一阶段,现在进入 {phase} 阶段。开始本轮工作前,先调用 get_workflow_status 确认 Runtime 当前阶段;在工具返回前,不要开始新阶段工作、写入文件、提交审批或断言阶段状态。"
|
||||
)
|
||||
},
|
||||
);
|
||||
begin_design_turn(session, id);
|
||||
} else {
|
||||
@@ -473,7 +476,7 @@ fn design_debug(root: &Path, kind: &str, data: Value) {
|
||||
type Entry = (PathBuf, Value);
|
||||
static QUEUE: OnceLock<std::sync::mpsc::SyncSender<Entry>> = OnceLock::new();
|
||||
let sender = QUEUE.get_or_init(|| {
|
||||
let (sender, receiver) = std::sync::mpsc::sync_channel::<Entry>(16);
|
||||
let (sender, receiver) = std::sync::mpsc::sync_channel::<Entry>(256);
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("design-debug".into())
|
||||
.spawn(move || {
|
||||
@@ -546,8 +549,26 @@ async fn request_design_provider(
|
||||
None,
|
||||
));
|
||||
let result = if llm.stream {
|
||||
let mut stream_sequence = 0_u64;
|
||||
client
|
||||
.stream_run(request.clone(), |delta| {
|
||||
stream_sequence = stream_sequence.saturating_add(1);
|
||||
design_debug(
|
||||
root,
|
||||
"stream",
|
||||
json!({
|
||||
"turnId": turn_id,
|
||||
"requestIndex": session.turn.as_ref().map(|turn| turn.request_index),
|
||||
"attempt": attempt,
|
||||
"sequence": stream_sequence,
|
||||
"occurredAtUnixNanos": unix_timestamp_nanos().to_string(),
|
||||
"model": llm.model,
|
||||
"deltaChars": delta.delta_text.chars().count(),
|
||||
"accumulatedChars": delta.accumulated_text.chars().count(),
|
||||
"deltaText": delta.delta_text,
|
||||
"finishReason": delta.finish_reason,
|
||||
}),
|
||||
);
|
||||
emit(design_event(
|
||||
root,
|
||||
&turn_id,
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
use super::*;
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
fn render_resource_reference_line(
|
||||
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());
|
||||
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 都要扫一遍 manifest(O(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(&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("素材 ID:asset-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("关联素材 ID:asset-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("关联素材 ID:asset-hero\n")
|
||||
|| section.trim_end().ends_with("关联素材 ID:asset-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}");
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user