Compare commits
45 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fc46cabb75 | |||
| 762f037150 | |||
| 48985d3447 | |||
| 9a21690fe9 | |||
| deff6319e2 | |||
| 2257a78d6b | |||
| a0f6b7c67d | |||
| 21b059bd41 | |||
| 2d90b73b94 | |||
| cd8f480719 | |||
| 2ffccb844c | |||
| 1bd153d7f2 | |||
| f5a333b839 | |||
| 20b1fd63de | |||
| 105591bac5 | |||
| da44d66dc8 | |||
| 0a85c4f87e | |||
| efce7b102f | |||
| db5edc948c | |||
| 45c3780bf5 | |||
| 6fcf42e4ac | |||
| e0f9f811b7 | |||
| 03b5c1c9f4 | |||
| 58992330aa | |||
| 2c687b01a4 | |||
| c0e377f479 | |||
| 6001b87215 | |||
| b08ab6ee66 | |||
| 7f80012d7f | |||
| fbe95591d5 | |||
| d222aad2ec | |||
| 13b28ebbc7 | |||
| 30648e6b93 | |||
| 9dd1052374 | |||
| aec9568c39 | |||
| 0a1f0e0b26 | |||
| 5c31ae91ca | |||
| 3ba6168c6a | |||
| 2628b83d4b | |||
| a7b2b0e23b | |||
| ef982fdb78 | |||
| 91b65f94ca | |||
| 70513cf049 | |||
| 87aed0b765 | |||
| 733a7015af |
@@ -47,6 +47,8 @@ temp*build*/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/codex-package.json
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/manifest.json
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/NOTICE.md
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/darwin-arm64/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/darwin-x64/
|
||||
/plugins/agc-cocos-editor/native/payload/
|
||||
/apps/ai-game-creator-shell/logs/
|
||||
/apps/ai-game-creator-shell/.llm-drafts/
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { resolveReleaseContext, runTauriBuild } from './build-release.mjs';
|
||||
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = path.resolve(appRoot, '../..');
|
||||
assert.equal(process.platform, 'darwin', '只能在 macOS Agent 执行');
|
||||
assert.equal(
|
||||
process.env.JENKINS_URL?.length > 0,
|
||||
true,
|
||||
'此入口仅用于 Jenkins 独立工作区',
|
||||
);
|
||||
assert.equal(
|
||||
fs.realpathSync(process.env.WORKSPACE || '.'),
|
||||
fs.realpathSync(repoRoot),
|
||||
'必须在 Jenkins workspace 根目录执行',
|
||||
);
|
||||
const space = fs.statfsSync(repoRoot);
|
||||
assert.ok(
|
||||
space.bavail * space.bsize >= 8 * 1024 ** 3,
|
||||
'构建前至少需要 8 GiB 可用空间;禁止自动清理开发缓存',
|
||||
);
|
||||
|
||||
// 本入口永不发布,不使用 Agent 用户可能持有的发布或 Apple 认证环境。
|
||||
for (const key of Object.keys(process.env)) {
|
||||
if (/^(TAURI_SIGNING_|APPLE_|AGC_OSS_)/u.test(key)) delete process.env[key];
|
||||
}
|
||||
process.env.RUSTC_WRAPPER = '';
|
||||
process.env.CARGO_TARGET_DIR = path.join(appRoot, 'src-tauri/target');
|
||||
const context = resolveReleaseContext(['--target=universal-apple-darwin']);
|
||||
const args = [
|
||||
'--target=universal-apple-darwin',
|
||||
'--bundles',
|
||||
'app',
|
||||
'--ci',
|
||||
'--no-sign',
|
||||
'--config',
|
||||
'{"bundle":{"createUpdaterArtifacts":false}}',
|
||||
];
|
||||
const command = (binary, argv, options = {}) =>
|
||||
execFileSync(binary, argv, { cwd: repoRoot, stdio: 'inherit', ...options });
|
||||
runTauriBuild(args, context);
|
||||
const app = path.join(context.bundleRoot, 'macos/陶泥儿.app');
|
||||
for (const architecture of ['arm64', 'x86_64']) {
|
||||
command(process.execPath, [
|
||||
path.join(appRoot, 'scripts/check-macos-bundle.mjs'),
|
||||
app,
|
||||
architecture,
|
||||
'--universal',
|
||||
]);
|
||||
}
|
||||
const version = JSON.parse(
|
||||
fs.readFileSync(path.join(appRoot, 'package.json'), 'utf8'),
|
||||
).version;
|
||||
assert.match(version, /^\d+\.\d+\.\d+$/u);
|
||||
const artifacts = path.join(repoRoot, 'artifacts');
|
||||
// 只清理本 Job 的归档输出,不能把上次 DMG 当成本次成功产物。
|
||||
fs.rmSync(artifacts, { recursive: true, force: true });
|
||||
fs.mkdirSync(artifacts, { recursive: true });
|
||||
const dmg = path.join(artifacts, `陶泥儿_${version}_universal.dmg`);
|
||||
const stage = fs.mkdtempSync(path.join(os.tmpdir(), 'agc-ci-dmg-'));
|
||||
try {
|
||||
command('ditto', [app, path.join(stage, '陶泥儿.app')]);
|
||||
fs.symlinkSync('/Applications', path.join(stage, 'Applications'));
|
||||
command('hdiutil', [
|
||||
'create',
|
||||
'-volname',
|
||||
'陶泥儿',
|
||||
'-srcfolder',
|
||||
stage,
|
||||
'-format',
|
||||
'UDZO',
|
||||
dmg,
|
||||
]);
|
||||
command('hdiutil', ['verify', dmg]);
|
||||
} finally {
|
||||
fs.rmSync(stage, { recursive: true, force: true });
|
||||
}
|
||||
const hash = createHash('sha256');
|
||||
for await (const chunk of fs.createReadStream(dmg)) hash.update(chunk);
|
||||
fs.writeFileSync(
|
||||
`${dmg}.sha256`,
|
||||
`${hash.digest('hex')} ${path.basename(dmg)}\n`,
|
||||
);
|
||||
const commit = execFileSync('git', ['rev-parse', 'HEAD'], {
|
||||
cwd: repoRoot,
|
||||
encoding: 'utf8',
|
||||
}).trim();
|
||||
fs.writeFileSync(
|
||||
path.join(artifacts, 'build-manifest.json'),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
version,
|
||||
commit,
|
||||
target: context.target,
|
||||
channel: context.channel,
|
||||
signed: false,
|
||||
notarized: false,
|
||||
uploaded: false,
|
||||
smoke: ['arm64', 'x86_64'],
|
||||
intelSmoke: process.arch === 'arm64' ? 'Rosetta' : 'native',
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
console.log('[macOS CI] universal 包与校验文件已生成;未发布、未签名或公证');
|
||||
@@ -42,16 +42,12 @@ function explicitBuildTarget(args) {
|
||||
}
|
||||
|
||||
function validateReleaseTarget(target) {
|
||||
if (target === 'universal-apple-darwin') {
|
||||
throw new Error(
|
||||
'内置 Codex 资源仅支持 macOS 单架构构建,请使用 aarch64-apple-darwin 或 x86_64-apple-darwin',
|
||||
);
|
||||
}
|
||||
if (
|
||||
![
|
||||
'x86_64-pc-windows-msvc',
|
||||
'aarch64-apple-darwin',
|
||||
'x86_64-apple-darwin',
|
||||
'universal-apple-darwin',
|
||||
].includes(target)
|
||||
) {
|
||||
throw new Error(`不支持的发布目标:${target}`);
|
||||
@@ -197,10 +193,12 @@ export function updateManifestUrl(channel = resolveReleaseChannel()) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 单架构产物只登记实际目标,不能把同一原生资源映射为另一架构。
|
||||
* universal 主程序与双目录原生资源共用一个更新包;单架构只登记实际目标。
|
||||
*/
|
||||
export function resolveManifestPlatformKeys(target = defaultTarget()) {
|
||||
validateReleaseTarget(target);
|
||||
if (target === 'universal-apple-darwin')
|
||||
return ['darwin-aarch64', 'darwin-x86_64'];
|
||||
if (target === 'aarch64-apple-darwin') return ['darwin-aarch64'];
|
||||
if (target === 'x86_64-apple-darwin') return ['darwin-x86_64'];
|
||||
if (target.includes('windows')) {
|
||||
|
||||
@@ -39,13 +39,12 @@ import {
|
||||
const windowsTarget = 'x86_64-pc-windows-msvc';
|
||||
const universalTarget = 'universal-apple-darwin';
|
||||
|
||||
test('native sidecar builds reject universal targets and accept each macOS architecture', () => {
|
||||
assert.throws(() => buildTauriBuildArguments([], universalTarget), /单架构/);
|
||||
assert.throws(
|
||||
() => buildTauriBuildArguments(['--target=universal-apple-darwin']),
|
||||
/单架构/,
|
||||
);
|
||||
for (const target of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) {
|
||||
test('native sidecar builds accept universal and each macOS architecture', () => {
|
||||
for (const target of [
|
||||
universalTarget,
|
||||
'aarch64-apple-darwin',
|
||||
'x86_64-apple-darwin',
|
||||
]) {
|
||||
assert.deepEqual(buildTauriBuildArguments([], target), [
|
||||
'build',
|
||||
'--target',
|
||||
@@ -152,8 +151,11 @@ test('channel manifest URL and build-time endpoint follow the channel', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('macOS manifests only advertise the architecture actually built', () => {
|
||||
assert.throws(() => resolveManifestPlatformKeys(universalTarget), /单架构/);
|
||||
test('macOS manifests advertise exactly the architectures actually built', () => {
|
||||
assert.deepEqual(resolveManifestPlatformKeys(universalTarget), [
|
||||
'darwin-aarch64',
|
||||
'darwin-x86_64',
|
||||
]);
|
||||
assert.deepEqual(resolveManifestPlatformKeys('aarch64-apple-darwin'), [
|
||||
'darwin-aarch64',
|
||||
]);
|
||||
@@ -197,7 +199,6 @@ test('release context resolves explicit targets before environment/default and f
|
||||
['--target='],
|
||||
['--target', '--no-bundle'],
|
||||
['--target', windowsTarget, '--target=aarch64-apple-darwin'],
|
||||
['--target', universalTarget],
|
||||
['--target', 'unknown'],
|
||||
])
|
||||
assert.throws(() => resolveReleaseContext(args, {}));
|
||||
@@ -314,8 +315,8 @@ test('invalid target or mismatched channel fails before any release side effect'
|
||||
},
|
||||
};
|
||||
await assert.rejects(
|
||||
() => buildRelease(['--target', universalTarget], sideEffects),
|
||||
/单架构/,
|
||||
() => buildRelease(['--target', 'unknown'], sideEffects),
|
||||
/不支持的发布目标/,
|
||||
);
|
||||
await withEnv({ AGC_UPDATE_CHANNEL: 'dev-win' }, () =>
|
||||
assert.rejects(
|
||||
@@ -326,6 +327,26 @@ test('invalid target or mismatched channel fails before any release side effect'
|
||||
assert.equal(touched, false);
|
||||
});
|
||||
|
||||
test('universal uses the Mac channel and the same signed artifact for both architectures', () => {
|
||||
const context = resolveReleaseContext(['--target', universalTarget], {
|
||||
AGC_BUILD_TARGET: windowsTarget,
|
||||
});
|
||||
assert.equal(context.channel, 'dev-mac');
|
||||
assert.ok(context.bundleRoot.includes(universalTarget));
|
||||
withSignedArtifact('陶泥儿.app.tar.gz', (artifact) => {
|
||||
const manifest = createUpdateManifest(artifact, context);
|
||||
assert.deepEqual(Object.keys(manifest.platforms), [
|
||||
'darwin-aarch64',
|
||||
'darwin-x86_64',
|
||||
]);
|
||||
assert.deepEqual(
|
||||
manifest.platforms['darwin-aarch64'],
|
||||
manifest.platforms['darwin-x86_64'],
|
||||
);
|
||||
assert.match(manifest.platforms['darwin-aarch64'].url, /\/dev-mac\//);
|
||||
});
|
||||
});
|
||||
|
||||
test('Windows remains the default and explicit Windows overrides macOS environment', () => {
|
||||
const files = ['/tmp/mac.app.tar.gz', '/tmp/windows.exe', '/tmp/mac.dmg'];
|
||||
for (const context of [
|
||||
|
||||
@@ -1367,18 +1367,20 @@ if (windowsTauriConfig.bundle?.useLocalToolsDir !== true) {
|
||||
assert.deepEqual(
|
||||
macosTauriConfig.bundle?.resources,
|
||||
Object.fromEntries([
|
||||
...[
|
||||
'bin/codex',
|
||||
'bin/codex-code-mode-host',
|
||||
'codex-path/rg',
|
||||
'codex-resources/zsh/bin/zsh',
|
||||
'codex-package.json',
|
||||
'NOTICE.md',
|
||||
'manifest.json',
|
||||
].map((file) => [
|
||||
`resources/codex/mac-native/${file}`,
|
||||
`coding-agent/mac-native/${file}`,
|
||||
]),
|
||||
...['darwin-arm64', 'darwin-x64'].flatMap((arch) =>
|
||||
[
|
||||
'bin/codex',
|
||||
'bin/codex-code-mode-host',
|
||||
'codex-path/rg',
|
||||
'codex-resources/zsh/bin/zsh',
|
||||
'codex-package.json',
|
||||
'NOTICE.md',
|
||||
'manifest.json',
|
||||
].map((file) => [
|
||||
`resources/codex/mac-native/${arch}/${file}`,
|
||||
`coding-agent/mac-native/${arch}/${file}`,
|
||||
]),
|
||||
),
|
||||
['resources/plugins', 'plugins'],
|
||||
]),
|
||||
'macOS must bundle the complete native Codex layout and plugin workspace',
|
||||
|
||||
@@ -8,6 +8,13 @@ import path from 'node:path';
|
||||
// 只操作临时复制品;不启动 GUI、不读取开发机凭据、不访问 Provider。
|
||||
assert.equal(process.platform, 'darwin', '此验证必须在 macOS 执行');
|
||||
const source = path.resolve(process.argv[2] || '');
|
||||
const architecture =
|
||||
process.argv[3] || (process.arch === 'arm64' ? 'arm64' : 'x86_64');
|
||||
assert.ok(
|
||||
['arm64', 'x86_64'].includes(architecture),
|
||||
'架构只接受 arm64 / x86_64',
|
||||
);
|
||||
const requireUniversal = process.argv.includes('--universal');
|
||||
assert.ok(
|
||||
source.endsWith('.app') && fs.statSync(source).isDirectory(),
|
||||
'请传入 .app 绝对路径',
|
||||
@@ -31,13 +38,19 @@ const env = {
|
||||
};
|
||||
|
||||
function run(command, args) {
|
||||
const result = spawnSync(command, args, {
|
||||
cwd: root,
|
||||
env,
|
||||
encoding: 'utf8',
|
||||
timeout: 30_000,
|
||||
maxBuffer: 1024 * 1024,
|
||||
});
|
||||
// 只强制被测应用切片;本机 Xcode 检查工具可能仅提供宿主架构。
|
||||
const useSlice = command.startsWith(`${app}${path.sep}`);
|
||||
const result = spawnSync(
|
||||
useSlice ? '/usr/bin/arch' : command,
|
||||
useSlice ? [`-${architecture}`, command, ...args] : args,
|
||||
{
|
||||
cwd: root,
|
||||
env,
|
||||
encoding: 'utf8',
|
||||
timeout: 120_000,
|
||||
maxBuffer: 1024 * 1024,
|
||||
},
|
||||
);
|
||||
assert.ifError(result.error);
|
||||
return result;
|
||||
}
|
||||
@@ -60,7 +73,7 @@ async function handshake(executable) {
|
||||
await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
() => reject(new Error('app-server 初始化超时')),
|
||||
15_000,
|
||||
120_000,
|
||||
);
|
||||
const finish = (error) => {
|
||||
clearTimeout(timer);
|
||||
@@ -129,20 +142,39 @@ async function handshake(executable) {
|
||||
try {
|
||||
fs.cpSync(source, app, { recursive: true });
|
||||
const resources = path.join(app, 'Contents/Resources');
|
||||
const bundle = path.join(resources, 'coding-agent/mac-native');
|
||||
const platform = architecture === 'arm64' ? 'darwin-arm64' : 'darwin-x64';
|
||||
const bundle = path.join(resources, 'coding-agent/mac-native', platform);
|
||||
const executable = path.join(bundle, 'bin/codex');
|
||||
const main = path.join(
|
||||
app,
|
||||
'Contents/MacOS/genarrative-ai-game-creator-shell',
|
||||
);
|
||||
const mainArchitectures = run('/usr/bin/lipo', ['-archs', main]);
|
||||
assert.equal(mainArchitectures.status, 0);
|
||||
assert.ok(mainArchitectures.stdout.split(/\s+/).includes(architecture));
|
||||
if (requireUniversal) {
|
||||
assert.deepEqual(mainArchitectures.stdout.trim().split(/\s+/).sort(), [
|
||||
'arm64',
|
||||
'x86_64',
|
||||
]);
|
||||
for (const platform of ['darwin-arm64', 'darwin-x64']) {
|
||||
assert.ok(
|
||||
fs.existsSync(
|
||||
path.join(
|
||||
resources,
|
||||
'coding-agent/mac-native',
|
||||
platform,
|
||||
'manifest.json',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
const manifest = JSON.parse(
|
||||
fs.readFileSync(path.join(bundle, 'manifest.json'), 'utf8'),
|
||||
);
|
||||
assert.equal(manifest.schemaVersion, 'genarrative-codex-sidecar.v2');
|
||||
assert.equal(
|
||||
manifest.platform,
|
||||
process.arch === 'arm64' ? 'darwin-arm64' : 'darwin-x64',
|
||||
);
|
||||
assert.equal(manifest.platform, platform);
|
||||
assert.equal(manifest.version, 'codex-cli 0.147.0');
|
||||
const components = [
|
||||
'bin/codex',
|
||||
@@ -159,11 +191,7 @@ try {
|
||||
fs.accessSync(file, fs.constants.X_OK);
|
||||
const arch = run('/usr/bin/lipo', ['-archs', file]);
|
||||
assert.equal(arch.status, 0, component);
|
||||
assert.equal(
|
||||
arch.stdout.trim(),
|
||||
process.arch === 'arm64' ? 'arm64' : 'x86_64',
|
||||
component,
|
||||
);
|
||||
assert.equal(arch.stdout.trim(), architecture, component);
|
||||
}
|
||||
}
|
||||
assert.ok(fs.existsSync(path.join(bundle, 'NOTICE.md')));
|
||||
@@ -212,7 +240,7 @@ try {
|
||||
assert.notEqual(broken.status, 0);
|
||||
assert.match(`${broken.stdout}\n${broken.stderr}`, /Codex CLI 未安装/);
|
||||
console.log(
|
||||
'PASS: 隔离安装包资源、架构、摘要、权限、正式 Codex 查找、app-server 握手及缺组件拒绝',
|
||||
`PASS (${architecture}): 隔离安装包资源、架构、摘要、权限、正式 Codex 查找、app-server 握手及缺组件拒绝`,
|
||||
);
|
||||
console.log(
|
||||
'未验证:GUI、真实登录/Provider 对话、Cocos macOS 原生桥接;插件 Node 仍为外部前提',
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = path.resolve(appRoot, '../..');
|
||||
const platforms = {
|
||||
arm64: 'aarch64-apple-darwin',
|
||||
x64: 'x86_64-apple-darwin',
|
||||
};
|
||||
|
||||
export function lockedMacPackage(lock, arch, version) {
|
||||
assert.ok(Object.hasOwn(platforms, arch), '未知 macOS 架构');
|
||||
const alias = `@openai/codex-darwin-${arch}`;
|
||||
const entry = lock.packages?.[`node_modules/${alias}`];
|
||||
assert.equal(
|
||||
entry?.version,
|
||||
`${version}-darwin-${arch}`,
|
||||
'原生依赖必须与应用锁定版本一致',
|
||||
);
|
||||
assert.deepEqual(entry.os, ['darwin']);
|
||||
assert.deepEqual(entry.cpu, [arch]);
|
||||
const url = new URL(entry.resolved);
|
||||
assert.equal(url.protocol, 'https:');
|
||||
assert.equal(
|
||||
url.hostname,
|
||||
'registry.npmjs.org',
|
||||
'只下载锁定的官方 npm 原生包',
|
||||
);
|
||||
assert.equal(url.username + url.password + url.search + url.hash, '');
|
||||
assert.match(entry.integrity, /^sha512-[A-Za-z0-9+/]+={0,2}$/);
|
||||
return { alias, target: platforms[arch], ...entry };
|
||||
}
|
||||
|
||||
export function verifyPackageIntegrity(bytes, expected) {
|
||||
const actual = `sha512-${createHash('sha512').update(bytes).digest('base64')}`;
|
||||
assert.equal(actual, expected, 'Codex 下载包 lockfile integrity 不匹配');
|
||||
}
|
||||
|
||||
export function validateArchiveListing(listing) {
|
||||
const files = listing.trim().split(/\r?\n/u);
|
||||
assert.ok(files.length > 0);
|
||||
for (const file of files) {
|
||||
assert.ok(file.startsWith('package/'), '原生包必须只有 package 根目录');
|
||||
assert.ok(
|
||||
!file.split('/').includes('..') && !file.includes('\\'),
|
||||
'压缩包路径不安全',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareMacosCodex() {
|
||||
assert.equal(process.platform, 'darwin', '该入口仅用于 macOS 构建机');
|
||||
const lock = JSON.parse(
|
||||
fs.readFileSync(path.join(repoRoot, 'package-lock.json'), 'utf8'),
|
||||
);
|
||||
const app = JSON.parse(
|
||||
fs.readFileSync(path.join(appRoot, 'package.json'), 'utf8'),
|
||||
);
|
||||
const version = app.devDependencies['@openai/codex'];
|
||||
assert.match(version, /^\d+\.\d+\.\d+$/u, 'Codex 必须锁定精确版本');
|
||||
const cache = path.join(appRoot, 'src-tauri/target/.macos-native-cache');
|
||||
fs.mkdirSync(cache, { recursive: true });
|
||||
for (const arch of Object.keys(platforms)) {
|
||||
const entry = lockedMacPackage(lock, arch, version);
|
||||
const archive = path.join(cache, `codex-${entry.version}.tgz`);
|
||||
if (!fs.existsSync(archive)) {
|
||||
const response = await fetch(entry.resolved, {
|
||||
signal: AbortSignal.timeout(300_000),
|
||||
});
|
||||
assert.ok(response.ok, `原生包下载失败 HTTP ${response.status}`);
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
verifyPackageIntegrity(bytes, entry.integrity);
|
||||
const partial = `${archive}.${process.pid}.tmp`;
|
||||
fs.writeFileSync(partial, bytes);
|
||||
fs.renameSync(partial, archive);
|
||||
}
|
||||
verifyPackageIntegrity(fs.readFileSync(archive), entry.integrity);
|
||||
validateArchiveListing(
|
||||
execFileSync('tar', ['-tzf', archive], { encoding: 'utf8' }),
|
||||
);
|
||||
// 拒绝链接、设备及其它特殊条目,不能让 tar 在包目录之外写入。
|
||||
const entries = execFileSync('tar', ['-tvzf', archive], {
|
||||
encoding: 'utf8',
|
||||
});
|
||||
assert.ok(
|
||||
entries
|
||||
.trim()
|
||||
.split(/\r?\n/u)
|
||||
.every((line) => /^[-d]/u.test(line)),
|
||||
'原生包禁止链接或特殊文件',
|
||||
);
|
||||
const parent = path.join(repoRoot, 'node_modules/@openai');
|
||||
fs.mkdirSync(parent, { recursive: true });
|
||||
const stage = fs.mkdtempSync(path.join(parent, '.mac-native-'));
|
||||
try {
|
||||
execFileSync(
|
||||
'tar',
|
||||
['-xzf', archive, '-C', stage, '--strip-components=1'],
|
||||
{ stdio: 'pipe' },
|
||||
);
|
||||
const metadata = JSON.parse(
|
||||
fs.readFileSync(
|
||||
path.join(stage, 'vendor', entry.target, 'codex-package.json'),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
assert.equal(metadata.version, version);
|
||||
assert.equal(metadata.target, entry.target);
|
||||
assert.equal(metadata.entrypoint, 'bin/codex');
|
||||
const destination = path.join(repoRoot, 'node_modules', entry.alias);
|
||||
assert.ok(
|
||||
!fs.existsSync(destination) ||
|
||||
!fs.lstatSync(destination).isSymbolicLink(),
|
||||
'拒绝覆盖链接依赖',
|
||||
);
|
||||
fs.rmSync(destination, { recursive: true, force: true });
|
||||
fs.renameSync(stage, destination);
|
||||
} finally {
|
||||
fs.rmSync(stage, { recursive: true, force: true });
|
||||
}
|
||||
console.log(`[macOS Codex] ${entry.version}: lockfile integrity 已验证`);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
process.argv[1] &&
|
||||
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
||||
) {
|
||||
await prepareMacosCodex();
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import { test } from 'node:test';
|
||||
|
||||
import {
|
||||
lockedMacPackage,
|
||||
validateArchiveListing,
|
||||
verifyPackageIntegrity,
|
||||
} from './prepare-macos-codex.mjs';
|
||||
|
||||
const lock = JSON.parse(
|
||||
fs.readFileSync(new URL('../../../package-lock.json', import.meta.url)),
|
||||
);
|
||||
const version = JSON.parse(
|
||||
fs.readFileSync(new URL('../package.json', import.meta.url)),
|
||||
).devDependencies['@openai/codex'];
|
||||
|
||||
test('both macOS dependencies resolve from the lockfile without floating versions', () => {
|
||||
assert.equal(
|
||||
lockedMacPackage(lock, 'arm64', version).target,
|
||||
'aarch64-apple-darwin',
|
||||
);
|
||||
assert.equal(
|
||||
lockedMacPackage(lock, 'x64', version).target,
|
||||
'x86_64-apple-darwin',
|
||||
);
|
||||
assert.throws(() => lockedMacPackage(lock, 'other', version));
|
||||
assert.throws(() => lockedMacPackage(lock, 'x64', '0.0.0'));
|
||||
});
|
||||
|
||||
test('native package integrity rejects tampering', () => {
|
||||
const bytes = Buffer.from('pinned package');
|
||||
const integrity = `sha512-${createHash('sha512').update(bytes).digest('base64')}`;
|
||||
verifyPackageIntegrity(bytes, integrity);
|
||||
assert.throws(() =>
|
||||
verifyPackageIntegrity(Buffer.from('modified'), integrity),
|
||||
);
|
||||
});
|
||||
|
||||
test('archive traversal and non-package entries fail closed', () => {
|
||||
validateArchiveListing(
|
||||
'package/package.json\npackage/vendor/target/bin/codex\n',
|
||||
);
|
||||
for (const listing of [
|
||||
'',
|
||||
'/tmp/payload',
|
||||
'package/../private',
|
||||
'other/file',
|
||||
'package/..\\file',
|
||||
]) {
|
||||
assert.throws(() => validateArchiveListing(listing));
|
||||
}
|
||||
});
|
||||
|
||||
test('CI pipeline is manual archive-only and does not reuse a developer workspace', () => {
|
||||
const pipeline = fs.readFileSync(
|
||||
new URL(
|
||||
'../../../jenkins/Jenkinsfile.ai-game-creator-shell-macos-build',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
for (const required of [
|
||||
'genarrative-agc-macos',
|
||||
'disableConcurrentBuilds()',
|
||||
'$AGC_AGENT_ROOT',
|
||||
'StrictHostKeyChecking=yes',
|
||||
'git merge-base --is-ancestor',
|
||||
'allowEmptyArchive: false',
|
||||
]) {
|
||||
assert.ok(pipeline.includes(required), required);
|
||||
}
|
||||
for (const forbidden of [
|
||||
'triggers {',
|
||||
'cron(',
|
||||
'pollSCM(',
|
||||
'release:upload',
|
||||
'AgcUpdaterSigningKey',
|
||||
'AliyunAccessKeyId',
|
||||
'git clean -fdx',
|
||||
]) {
|
||||
assert.ok(!pipeline.includes(forbidden), forbidden);
|
||||
}
|
||||
});
|
||||
@@ -31,7 +31,23 @@ fn sha256_file(path: &std::path::Path) -> Result<String, std::io::Error> {
|
||||
fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) {
|
||||
let target = env::var("TARGET").expect("Cargo TARGET");
|
||||
println!("cargo:rustc-env=AGC_BUILD_TARGET={target}");
|
||||
let Some(layout) = codex_bundle::for_target(&target) else {
|
||||
if target.contains("apple-darwin") {
|
||||
// Tauri 的 universal 两次 Cargo 编译共用 resource staging,
|
||||
// 每次都生成完整双架构目录,最终 bundle 不取决于最后编译的切片。
|
||||
let staging = manifest_dir.join("resources/codex/mac-native");
|
||||
if staging.exists() {
|
||||
fs::remove_dir_all(&staging).expect("清理 macOS Codex staging 失败");
|
||||
}
|
||||
for target in ["aarch64-apple-darwin", "x86_64-apple-darwin"] {
|
||||
stage_codex_target(manifest_dir, target);
|
||||
}
|
||||
} else {
|
||||
stage_codex_target(manifest_dir, &target);
|
||||
}
|
||||
}
|
||||
|
||||
fn stage_codex_target(manifest_dir: &std::path::Path, target: &str) {
|
||||
let Some(layout) = codex_bundle::for_target(target) else {
|
||||
assert!(
|
||||
!target.contains("windows") && !target.contains("apple-darwin"),
|
||||
"不支持的 Codex 随包目标:{target}"
|
||||
@@ -81,7 +97,7 @@ fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) {
|
||||
&fs::read(source.join("codex-package.json")).expect("读取 Codex 原生包元数据失败"),
|
||||
)
|
||||
.expect("Codex 原生包元数据无效");
|
||||
codex_bundle::validate_package_metadata(&metadata, &target, layout)
|
||||
codex_bundle::validate_package_metadata(&metadata, target, layout)
|
||||
.unwrap_or_else(|error| panic!("{error}"));
|
||||
let target_dir = manifest_dir.join("resources/codex").join(layout.directory);
|
||||
let notice = target_dir.join("NOTICE.md");
|
||||
|
||||
@@ -49,7 +49,11 @@ pub fn for_target(target: &str) -> Option<Layout> {
|
||||
} else {
|
||||
"codex-darwin-x64"
|
||||
},
|
||||
directory: "mac-native",
|
||||
directory: if target.starts_with("aarch64") {
|
||||
"mac-native/darwin-arm64"
|
||||
} else {
|
||||
"mac-native/darwin-x64"
|
||||
},
|
||||
executable: "bin/codex",
|
||||
files: MAC_FILES,
|
||||
}),
|
||||
@@ -90,6 +94,9 @@ mod tests {
|
||||
let intel = for_target("x86_64-apple-darwin").unwrap();
|
||||
assert_eq!(intel.platform, "darwin-x64");
|
||||
assert_eq!(intel.npm_package, "codex-darwin-x64");
|
||||
assert_eq!(mac.directory, "mac-native/darwin-arm64");
|
||||
assert_eq!(intel.directory, "mac-native/darwin-x64");
|
||||
assert_ne!(mac.directory, intel.directory);
|
||||
let windows = for_target("x86_64-pc-windows-msvc").unwrap();
|
||||
assert_eq!(windows.directory, "win-x64");
|
||||
assert_eq!(windows.files.len(), 6);
|
||||
|
||||
+3
@@ -14,6 +14,9 @@ Implement the user's actual game request in the current project as an npm-manage
|
||||
3. Build with the project's npm script before previewing. The playable entry is the package directory's `dist/index.html`; never report an unbuilt bare-module page as playable. Import assets or configure public assets so all runtime media is included in dist; preview and exports cannot read outside it.
|
||||
4. Build a complete playable loop: visible objective, responsive input, meaningful state changes, success or failure feedback, and a reliable restart path where the game needs one.
|
||||
5. Fit the active game scene to desktop and mobile viewports without accidental page scrollbars. Reserve deliberate safe space for HUD elements instead of covering interactive content.
|
||||
- **画布居中只能由一处负责。** 使用 `Phaser.Scale.FIT` 与 `autoCenter: Phaser.Scale.CENTER_BOTH` 时,canvas 的直接父容器应使用尺寸明确的普通块布局,不再对同一 canvas 叠加 Grid/Flex 居中、`place-items: center`、自动外边距或居中 transform。Phaser 自动计算的 margin 与 CSS 居中叠加会使竖屏画面向右偏移。
|
||||
- 若决定由 CSS 居中,则显式使用 `autoCenter: Phaser.Scale.NO_CENTER`,由 CSS 独立完成定位;外围页面可以继续使用 Grid/Flex,限制只针对同一 canvas 的重复定位。
|
||||
- 出现偏移先检查游戏自身的 CSS 与 Phaser scale 配置,不添加 AGC 预览容器固定偏移补偿。修改布局后重新构建 dist,在桌面、移动及窗口 resize 后检查 canvas 相对游戏父容器居中(误差不超过 1 CSS px)、画面完整且无意外滚动条;不能仅凭 build 成功宣称布局通过。
|
||||
6. Invoke `taonier-art-assets` for every new game brief that needs visual assets. First reuse suitable registered Taonier art; when the brief's required visual elements are missing or unsuitable, call the reviewed `agc_tools` generation/edit workflow in the same task. After the tool returns, wire its relative paths into the game and verify the rendered result. A game with unused generated assets or placeholder emoji/CSS where requested art should appear is not complete. Load media defensively only for genuinely optional effects, and never relabel a local placeholder as platform art.
|
||||
7. Let Phaser own the render loop and input dispatch. Avoid duplicate scenes, stale event listeners, and state that survives restart unintentionally.
|
||||
8. After a meaningful game change, use the browser playtest Skill and fix issues shown by real evidence before reporting completion.
|
||||
|
||||
+2
@@ -7,5 +7,7 @@
|
||||
- Score, steps, health, timer, or other core state updates consistently.
|
||||
- Restart restores all state and does not duplicate timers, animation loops, or event listeners.
|
||||
- Desktop and mobile layouts keep the core scene visible without accidental document scrolling.
|
||||
- 画布的缩放与居中由 Phaser 或 CSS 中的一方独立负责。`FIT + CENTER_BOTH` 不与同一 canvas 父容器的 Grid/Flex 居中、自动外边距或居中 transform 叠加;使用 CSS 居中时关闭 Phaser 自动居中(`NO_CENTER`)。
|
||||
- 在构建后的实际页面检查桌面、移动和 resize:比较 canvas 与游戏父容器的中心,预期居中时水平/垂直误差不超过 1 CSS px,并检查画面没有溢出或意外滚动条。偏移先修游戏 CSS/scale 配置,不用修改 AGC 预览位置掩盖。
|
||||
- HUD and overlays reserve space and do not cover essential interactive content.
|
||||
- Requested Taonier art is visibly integrated into the core experience when available.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemaVersion": "agc-skill-pack.v1",
|
||||
"version": "2026-08-26.24",
|
||||
"version": "2026-08-26.25",
|
||||
"skills": [
|
||||
{
|
||||
"name": "agc-game-production-workflow",
|
||||
@@ -80,7 +80,7 @@
|
||||
"agents/openai.yaml",
|
||||
"references/game-quality-checklist.md"
|
||||
],
|
||||
"sha256": "05b5cfbf7a40fd303717491f5cea84ff339a73359c9678b283fd54d2b5c45efd"
|
||||
"sha256": "e122d8f3a6d986b594b95c971754d68197bf7896912fa8267d44a7aa129a57ba"
|
||||
},
|
||||
{
|
||||
"name": "agc-browser-playtest",
|
||||
|
||||
@@ -797,6 +797,16 @@ fn direct_thread_visible_item(
|
||||
direct_thread_event_item(root, item)
|
||||
}
|
||||
|
||||
/// AGC 预写的 canonical 用户条目 id:`direct-codex:{clientTurnId}:user`。
|
||||
///
|
||||
/// 与 `direct_project_history::is_direct_project_codex_user_item` 的判据同一份口径(前缀 +
|
||||
/// `:user` 后缀)。回合生命周期事件的 `userItemId` 只能来自这里或已落盘条目自身的 id;
|
||||
/// clientTurnId 缺失时不猜身份,返回 `None` 让前端按"未知归属"处理。
|
||||
fn direct_codex_user_item_id_for_client_turn_id(client_turn_id: &str) -> Option<String> {
|
||||
let client_turn_id = client_turn_id.trim();
|
||||
(!client_turn_id.is_empty()).then(|| format!("direct-codex:{client_turn_id}:user"))
|
||||
}
|
||||
|
||||
fn direct_codex_command_is_game_verification(command: &str) -> bool {
|
||||
let command = command.to_ascii_lowercase();
|
||||
command.contains("game.static_smoke")
|
||||
@@ -2927,7 +2937,7 @@ impl CodexAppServerConnection {
|
||||
None => direct_project_local_message_item(
|
||||
"user",
|
||||
current_prompt,
|
||||
Some(&format!("direct-codex:{client_turn_id}:user")),
|
||||
direct_codex_user_item_id_for_client_turn_id(client_turn_id).as_deref(),
|
||||
)
|
||||
.map_err(platform_llm::LlmError::InvalidRequest)?,
|
||||
};
|
||||
@@ -3046,13 +3056,30 @@ impl CodexAppServerConnection {
|
||||
};
|
||||
turn_start_guard.armed = false;
|
||||
let direct_thread_id = direct_thread_id_for_project(history_root);
|
||||
// 回合边界的阶段时间:Turn 上游只有**秒**级 `startedAt` / `completedAt`,秒级截断
|
||||
// 撑不起前端 0.1 秒粒度的展示,也可能让完成时刻落进该轮用户消息的同一秒、落在真实
|
||||
// 发送时间之前,被判成无效边界后整轮新回合被吞掉。因此这里只在宿主处理对应阶段时取
|
||||
// 毫秒钟(与条目侧"没有原生阶段时间就用宿主钟"同一口径),不再读上游秒字段。
|
||||
let direct_turn_started_at_ms = direct_tool_call_now_ms();
|
||||
// 本轮开口用户条目的 canonical id:只从已落盘的那条条目上读身份(`id`,工具条目才用
|
||||
// `call_id`),不在事件侧重造一份。拿不到就留空,让前端按"归属不可证明"处理。
|
||||
let direct_turn_user_item_id = direct_persisted_user_item
|
||||
.as_ref()
|
||||
.and_then(direct_thread_item_identity);
|
||||
if self.inner.workspace_mode == CodexAppServerWorkspaceMode::DirectProject {
|
||||
append_direct_thread_event(&direct_thread_id, DirectThreadEvent::turn_started());
|
||||
append_direct_thread_event(
|
||||
&direct_thread_id,
|
||||
DirectThreadEvent::turn_started(direct_turn_started_at_ms)
|
||||
.with_user_item_id(direct_turn_user_item_id.as_deref()),
|
||||
);
|
||||
if let Some(user_item) = direct_persisted_user_item.as_ref() {
|
||||
if let Some(entry_item) = direct_thread_event_item(history_root, user_item) {
|
||||
// 这里的条目时间可能是启动应答后的观测时间;前端按同一用户条目身份
|
||||
// 保留更早的真实发送时间,不用此事件时间覆盖它。
|
||||
let user_item_at = entry_item.at();
|
||||
append_direct_thread_event(
|
||||
&direct_thread_id,
|
||||
DirectThreadEvent::item_completed(entry_item),
|
||||
DirectThreadEvent::item_completed(entry_item, user_item_at),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3191,9 +3218,14 @@ impl CodexAppServerConnection {
|
||||
.map_err(platform_llm::LlmError::InvalidRequest)?;
|
||||
direct_project_history.complete_item(&item);
|
||||
if let Some(entry_item) = entry_item {
|
||||
// `rawResponseItem/completed` 不带阶段时间,宿主处理到这条
|
||||
// 通知的钟就是该阶段唯一可证明的时间。
|
||||
append_direct_thread_event(
|
||||
&direct_thread_id,
|
||||
DirectThreadEvent::item_completed(entry_item),
|
||||
DirectThreadEvent::item_completed(
|
||||
entry_item,
|
||||
direct_tool_call_now_ms(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3322,9 +3354,19 @@ impl CodexAppServerConnection {
|
||||
if let Some(entry_item) =
|
||||
direct_thread_visible_item(history_root, item)
|
||||
{
|
||||
// `item/started` 的通知层带 `startedAtMs`:这是工具真正
|
||||
// 开始的阶段时间,优先于条目展示时间与宿主钟。
|
||||
append_direct_thread_event(
|
||||
&direct_thread_id,
|
||||
DirectThreadEvent::item_started(entry_item),
|
||||
DirectThreadEvent::item_started(
|
||||
entry_item,
|
||||
direct_thread_item_event_at_ms(
|
||||
¶ms,
|
||||
item,
|
||||
false,
|
||||
direct_tool_call_now_ms(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3367,9 +3409,19 @@ impl CodexAppServerConnection {
|
||||
&& matches!(status, "completed" | "interrupted" | "failed")
|
||||
{
|
||||
terminal_recorded = true;
|
||||
// 终态时间:`durationMs` 与宿主记下的毫秒起点都可靠时才派生,
|
||||
// 否则取宿主处理这条终态的钟;上游秒级 `completedAt` 一律不用。
|
||||
append_direct_thread_event(
|
||||
&direct_thread_id,
|
||||
DirectThreadEvent::turn_completed(status.to_string()),
|
||||
DirectThreadEvent::turn_completed(
|
||||
status.to_string(),
|
||||
direct_thread_turn_completed_at_ms(
|
||||
turn,
|
||||
Some(direct_turn_started_at_ms),
|
||||
direct_tool_call_now_ms(),
|
||||
),
|
||||
)
|
||||
.with_user_item_id(direct_turn_user_item_id.as_deref()),
|
||||
);
|
||||
}
|
||||
match status {
|
||||
@@ -3426,7 +3478,11 @@ impl CodexAppServerConnection {
|
||||
"failed"
|
||||
}
|
||||
.to_string(),
|
||||
),
|
||||
// 这条兜底终态没有对应的 app-server 终态载荷,只能取宿主处理它的钟,
|
||||
// 不能拿最后一次正文或工具更新时间当回合终点。
|
||||
direct_tool_call_now_ms(),
|
||||
)
|
||||
.with_user_item_id(direct_turn_user_item_id.as_deref()),
|
||||
);
|
||||
}
|
||||
let text = match collect_result {
|
||||
@@ -3624,6 +3680,15 @@ enum DirectCodexTurnCancelTarget {
|
||||
/// 这时显式释放这条守卫并把可读原因返回给界面。释放条件见
|
||||
/// [`release_stale_direct_taonier_active_invocation`] 的注释;"正在跑的是另一轮"仍然
|
||||
/// 保持原拒绝语义,什么都不释放。
|
||||
///
|
||||
/// 兜底终态带 `userItemId`:身份取 `release_stale_direct_taonier_active_invocation` 返回的
|
||||
/// clientTurnId(客户端回合身份的唯一来源),与正常路径的开口条目 id 同一份 canonical 口径。
|
||||
/// 拿不到 clientTurnId 就留空——这一轮不会再有原生终态,猜一个身份会让前端把边界盖到别人身上。
|
||||
fn direct_stale_cancel_turn_completed_event(client_turn_id: &str) -> DirectThreadEvent {
|
||||
DirectThreadEvent::turn_completed("aborted".to_string(), direct_tool_call_now_ms())
|
||||
.with_user_item_id(direct_codex_user_item_id_for_client_turn_id(client_turn_id).as_deref())
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_direct_codex_turn_at(
|
||||
root: &Path,
|
||||
client_turn_id: Option<&str>,
|
||||
@@ -3680,7 +3745,7 @@ pub(crate) fn cancel_direct_codex_turn_at(
|
||||
// 兜底补一条,否则前端的"最新回合是否在跑"会永远停在运行中。
|
||||
append_direct_thread_event(
|
||||
&direct_thread_id_for_project(root),
|
||||
DirectThreadEvent::turn_completed("aborted".to_string()),
|
||||
direct_stale_cancel_turn_completed_event(&released),
|
||||
);
|
||||
Ok(DirectTurnCancelView {
|
||||
outcome: DIRECT_TURN_CANCEL_OUTCOME_RELEASED.to_string(),
|
||||
@@ -5006,6 +5071,109 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
/// 阶段时间取自**通知层**字段,形状照抄 codex-cli 0.147 / 0.155 的 v2 协议 schema:
|
||||
/// `item/started` 带 `startedAtMs`、`item/completed` 带 `completedAtMs`(毫秒),
|
||||
/// `turn/completed` 带 `turn.startedAt` / `turn.completedAt`(秒)与 `turn.durationMs`(毫秒)。
|
||||
/// 分类函数把 params 原样交给事件级 `at` 的投影函数,所以字段位置必须在这里钉住;
|
||||
/// 回合边界的秒字段按"不用"锁在这里,避免以后有人再把秒级截断当 0.1 秒精度。
|
||||
#[test]
|
||||
fn direct_lifecycle_stage_times_come_from_notification_params() {
|
||||
let started = serde_json::json!({
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-1",
|
||||
"startedAtMs": 1_700_000_000_123u64,
|
||||
"item": {"id": "call-1", "type": "commandExecution", "command": "ls"},
|
||||
});
|
||||
let completed = serde_json::json!({
|
||||
"threadId": "thread-1",
|
||||
"turnId": "turn-1",
|
||||
"completedAtMs": 1_700_000_001_500u64,
|
||||
"item": {"id": "call-1", "type": "commandExecution", "command": "ls"},
|
||||
});
|
||||
for (method, params, expected_at_ms) in [
|
||||
("item/started", &started, 1_700_000_000_123u64),
|
||||
("item/completed", &completed, 1_700_000_001_500u64),
|
||||
] {
|
||||
let Some(CodexTurnEvent::Item {
|
||||
completed,
|
||||
params: event_params,
|
||||
}) = direct_codex_notification_event(method, params, None, None, "turn-1")
|
||||
else {
|
||||
panic!("{method} 必须分类成条目生命周期事件");
|
||||
};
|
||||
let item = event_params.get("item").expect("item payload");
|
||||
assert_eq!(
|
||||
direct_thread_item_event_at_ms(&event_params, item, completed, 9_999),
|
||||
expected_at_ms,
|
||||
"{method} 必须用通知层的阶段时间,而不是宿主钟"
|
||||
);
|
||||
}
|
||||
|
||||
let terminal = serde_json::json!({
|
||||
"threadId": "thread-1",
|
||||
"turn": {
|
||||
"id": "turn-1",
|
||||
"items": [],
|
||||
"status": "completed",
|
||||
"startedAt": 1_700_000_000i64,
|
||||
"completedAt": 1_700_000_042i64,
|
||||
},
|
||||
});
|
||||
let Some(CodexTurnEvent::Terminal(params)) =
|
||||
direct_codex_notification_event("turn/completed", &terminal, None, None, "turn-1")
|
||||
else {
|
||||
panic!("turn/completed 必须分类成终态事件");
|
||||
};
|
||||
let turn = params.get("turn").unwrap_or(¶ms);
|
||||
assert_eq!(
|
||||
direct_thread_turn_completed_at_ms(turn, Some(1_700_000_000_500), 9_999),
|
||||
9_999,
|
||||
"上游只有秒级 completedAt:不采用,取宿主处理终态的毫秒钟"
|
||||
);
|
||||
let with_duration = serde_json::json!({
|
||||
"id": "turn-1",
|
||||
"items": [],
|
||||
"status": "completed",
|
||||
"startedAt": 1_700_000_000i64,
|
||||
"completedAt": 1_700_000_042i64,
|
||||
"durationMs": 42_500u64,
|
||||
});
|
||||
assert_eq!(
|
||||
direct_thread_turn_completed_at_ms(&with_duration, Some(1_700_000_000_500), 9_999),
|
||||
1_700_000_043_000,
|
||||
"durationMs + 宿主高精度起点才派生结束"
|
||||
);
|
||||
}
|
||||
|
||||
/// 取消兜底终态也要带开口用户条目身份,且身份只有一个来源:release 返回的 clientTurnId
|
||||
/// 走与正常路径同一份 canonical 口径;拿不到(空 / 空白)就留空,不猜。
|
||||
#[test]
|
||||
fn stale_cancel_terminal_event_keeps_opener_user_item_id_from_client_turn_id() {
|
||||
let event = direct_stale_cancel_turn_completed_event("turn-0001");
|
||||
assert_eq!(event.user_item_id(), Some("direct-codex:turn-0001:user"));
|
||||
assert!(event.at().is_some(), "兜底终态仍要带宿主观测时间");
|
||||
assert!(matches!(
|
||||
event,
|
||||
DirectThreadEvent::TurnCompleted { ref status, .. } if status == "aborted"
|
||||
));
|
||||
|
||||
for missing in ["", " "] {
|
||||
let event = direct_stale_cancel_turn_completed_event(missing);
|
||||
assert_eq!(
|
||||
event.user_item_id(),
|
||||
None,
|
||||
"拿不到 clientTurnId 时不得编造开口条目身份"
|
||||
);
|
||||
}
|
||||
|
||||
// canonical 口径与落盘侧同一份:`direct-codex:{clientTurnId}:user`。
|
||||
assert_eq!(
|
||||
direct_codex_user_item_id_for_client_turn_id(" turn-0001 ").as_deref(),
|
||||
Some("direct-codex:turn-0001:user")
|
||||
);
|
||||
assert_eq!(direct_codex_user_item_id_for_client_turn_id(""), None);
|
||||
}
|
||||
|
||||
fn test_llm() -> GameCreatorLlmConfig {
|
||||
GameCreatorLlmConfig {
|
||||
custom_enabled: false,
|
||||
@@ -6740,12 +6908,33 @@ done
|
||||
|
||||
let consumed = crate::agent::consume_direct_thread(&bootstrap.subscription_id)
|
||||
.expect("consume events");
|
||||
// 回合起止必须与开口用户条目同源:前端在「只有锚点 + 历史、运行态为空」的回合里靠这个
|
||||
// 身份把边界认领给同一条用户条目,缺了它就只能隐藏未知用时。
|
||||
let lifecycle_user_item_ids = consumed
|
||||
.events
|
||||
.iter()
|
||||
.filter(|event| {
|
||||
matches!(
|
||||
event,
|
||||
DirectThreadEvent::TurnStarted { .. } | DirectThreadEvent::TurnCompleted { .. }
|
||||
)
|
||||
})
|
||||
.map(DirectThreadEvent::user_item_id)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
lifecycle_user_item_ids,
|
||||
vec![
|
||||
Some("direct-codex:turn-0001:user"),
|
||||
Some("direct-codex:turn-0001:user"),
|
||||
],
|
||||
"turn.started / turn.completed 都要带本轮开口用户条目的 canonical itemId"
|
||||
);
|
||||
let mut user_items = Vec::new();
|
||||
let mut assistant_items = Vec::new();
|
||||
for event in &consumed.events {
|
||||
let item = match event {
|
||||
DirectThreadEvent::ItemStarted { item }
|
||||
| DirectThreadEvent::ItemCompleted { item } => item,
|
||||
DirectThreadEvent::ItemStarted { item, .. }
|
||||
| DirectThreadEvent::ItemCompleted { item, .. } => item,
|
||||
_ => continue,
|
||||
};
|
||||
match item {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -427,12 +427,16 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// 事件级阶段时间只在重放稳定性用例里逐个指定;其余用例用一个固定值即可,
|
||||
/// 它们断言的是队列 / 游标语义,不是时间本身。
|
||||
const FIXED_AT_MS: u64 = 1_000;
|
||||
|
||||
fn item_started(item_id: &str) -> DirectThreadEvent {
|
||||
DirectThreadEvent::item_started(message(item_id))
|
||||
DirectThreadEvent::item_started(message(item_id), FIXED_AT_MS)
|
||||
}
|
||||
|
||||
fn item_completed(item_id: &str) -> DirectThreadEvent {
|
||||
DirectThreadEvent::item_completed(message(item_id))
|
||||
DirectThreadEvent::item_completed(message(item_id), FIXED_AT_MS)
|
||||
}
|
||||
|
||||
fn item_delta(item_id: &str) -> DirectThreadEvent {
|
||||
@@ -450,7 +454,7 @@ mod tests {
|
||||
#[test]
|
||||
fn subscribers_have_independent_cursors_on_one_global_queue() {
|
||||
let mut manager = DirectThreadManager::with_limits(100, 100_000);
|
||||
manager.append("thread-1", DirectThreadEvent::turn_started());
|
||||
manager.append("thread-1", DirectThreadEvent::turn_started(FIXED_AT_MS));
|
||||
let first = manager.subscribe("thread-1");
|
||||
let second = manager.subscribe("thread-1");
|
||||
manager.append("thread-1", item_started("item-1"));
|
||||
@@ -474,7 +478,7 @@ mod tests {
|
||||
#[test]
|
||||
fn bootstrap_contains_lifecycle_anchor_and_unfinished_events_only() {
|
||||
let mut manager = DirectThreadManager::with_limits(100, 100_000);
|
||||
manager.append("thread-1", DirectThreadEvent::turn_started());
|
||||
manager.append("thread-1", DirectThreadEvent::turn_started(FIXED_AT_MS));
|
||||
manager.append("thread-1", item_started("item-1"));
|
||||
manager.append("thread-1", item_delta("item-1"));
|
||||
manager.append("thread-1", item_completed("item-1"));
|
||||
@@ -484,7 +488,7 @@ mod tests {
|
||||
assert!(matches!(
|
||||
bootstrap.events.as_slice(),
|
||||
[
|
||||
DirectThreadEvent::TurnStarted {},
|
||||
DirectThreadEvent::TurnStarted { .. },
|
||||
DirectThreadEvent::ItemStarted { item, .. },
|
||||
] if item.item_id() == "item-2"
|
||||
));
|
||||
@@ -589,15 +593,118 @@ mod tests {
|
||||
let mut manager = DirectThreadManager::with_limits(100, 100_000);
|
||||
manager.append(
|
||||
"thread-1",
|
||||
DirectThreadEvent::turn_completed("completed".to_string()),
|
||||
DirectThreadEvent::turn_completed("completed".to_string(), FIXED_AT_MS),
|
||||
);
|
||||
let bootstrap = manager.subscribe("thread-1");
|
||||
assert!(matches!(
|
||||
bootstrap.events.as_slice(),
|
||||
[DirectThreadEvent::TurnCompleted { status }] if status == "completed"
|
||||
[DirectThreadEvent::TurnCompleted { status, at, .. }]
|
||||
if status == "completed" && *at == Some(FIXED_AT_MS)
|
||||
));
|
||||
}
|
||||
|
||||
/// 阶段时间必须随事件一起进队列:bootstrap 与重复订阅都拿到**原值**,
|
||||
/// 重放不得重新取钟(否则每次重连都会把已固定的起止时间改掉)。
|
||||
#[test]
|
||||
fn replayed_events_keep_their_original_stage_time() {
|
||||
let mut manager = DirectThreadManager::with_limits(100, 100_000);
|
||||
manager.append("thread-1", DirectThreadEvent::turn_started(1_000));
|
||||
manager.append(
|
||||
"thread-1",
|
||||
DirectThreadEvent::item_started(message("item-1"), 2_000),
|
||||
);
|
||||
|
||||
let first = manager.subscribe("thread-1");
|
||||
assert_eq!(
|
||||
first
|
||||
.events
|
||||
.iter()
|
||||
.map(DirectThreadEvent::at)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![Some(1_000), Some(2_000)]
|
||||
);
|
||||
|
||||
// 第二个订阅看到的是同一份事件,时间不因"又取了一次当前时间"而漂移。
|
||||
let second = manager.subscribe("thread-1");
|
||||
assert_eq!(second.events, first.events);
|
||||
|
||||
manager.append(
|
||||
"thread-1",
|
||||
DirectThreadEvent::item_completed(message("item-1"), 3_000),
|
||||
);
|
||||
let completion = manager
|
||||
.consume(&first.subscription_id)
|
||||
.expect("consume completion")
|
||||
.events;
|
||||
assert_eq!(
|
||||
completion
|
||||
.iter()
|
||||
.map(DirectThreadEvent::at)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![Some(3_000)]
|
||||
);
|
||||
// 重复消费不产生新事件,也不改写已下发过的时间。
|
||||
assert!(manager
|
||||
.consume(&first.subscription_id)
|
||||
.expect("empty consume")
|
||||
.events
|
||||
.is_empty());
|
||||
assert_eq!(
|
||||
completion
|
||||
.iter()
|
||||
.map(DirectThreadEvent::at)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![Some(3_000)]
|
||||
);
|
||||
}
|
||||
|
||||
/// 生命周期锚点重放时必须带上开口用户条目身份:前端在「只有锚点 + 历史切片、运行态一直空」
|
||||
/// 的回合里也要能把边界认领给同一条用户条目,而不是按时间戳猜。
|
||||
#[test]
|
||||
fn bootstrap_replays_opener_user_item_id() {
|
||||
let mut manager = DirectThreadManager::with_limits(100, 100_000);
|
||||
manager.append(
|
||||
"thread-1",
|
||||
DirectThreadEvent::turn_started(1_000)
|
||||
.with_user_item_id(Some("direct-codex:turn-1:user")),
|
||||
);
|
||||
let bootstrap = manager.subscribe("thread-1");
|
||||
assert_eq!(
|
||||
bootstrap
|
||||
.events
|
||||
.iter()
|
||||
.map(DirectThreadEvent::user_item_id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![Some("direct-codex:turn-1:user")]
|
||||
);
|
||||
assert_eq!(bootstrap.events[0].at(), Some(1_000));
|
||||
|
||||
// 锚点是独立保存的副本:队列里那条事件被回收之后,新订阅仍拿到同一个身份。
|
||||
manager
|
||||
.consume(&bootstrap.subscription_id)
|
||||
.expect("consume anchor");
|
||||
manager.append(
|
||||
"thread-1",
|
||||
DirectThreadEvent::item_completed(message("item-1"), 2_000),
|
||||
);
|
||||
manager.append(
|
||||
"thread-1",
|
||||
DirectThreadEvent::turn_completed("completed".to_string(), 3_000)
|
||||
.with_user_item_id(Some("direct-codex:turn-1:user")),
|
||||
);
|
||||
let second = manager.subscribe("thread-1");
|
||||
assert_eq!(
|
||||
second
|
||||
.events
|
||||
.iter()
|
||||
.map(DirectThreadEvent::user_item_id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![Some("direct-codex:turn-1:user")],
|
||||
"起止同源:终态锚点也带同一个开口用户条目身份"
|
||||
);
|
||||
assert_eq!(second.events[0].at(), Some(3_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_cleanup_only_removes_a_cleanable_prefix() {
|
||||
let mut manager = DirectThreadManager::with_limits(100, 100_000);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2391,6 +2391,8 @@ async fn bridge_generate_image(state: &DirectToolBridgeState, arguments: &Value)
|
||||
slice_mode,
|
||||
grid_x,
|
||||
grid_y,
|
||||
reference_asset_ids: Vec::new(),
|
||||
target_category: None,
|
||||
screen_color,
|
||||
};
|
||||
let _generation_guard = state.image_generation_gate.lock().await;
|
||||
|
||||
@@ -67,10 +67,11 @@ pub(crate) use canvas_generation::{
|
||||
generate_platform_art_asset_with_options_at,
|
||||
generate_platform_art_asset_with_required_slices_at, maybe_generate_platform_art_asset_step,
|
||||
needs_platform_art_asset_generation, normalize_platform_art_asset_generation_kind,
|
||||
normalize_platform_art_reference_asset_ids, normalize_platform_art_target_category,
|
||||
platform_art_asset_art_spec, platform_art_asset_output_extension_matches,
|
||||
prepare_platform_art_asset_output_path, project_canvas_asset_media_types,
|
||||
role_has_canvas_assets, suggested_canvas_tool_call, PlatformArtAssetGenerationOptions,
|
||||
PLATFORM_ART_ASSET_GENERATION_KINDS,
|
||||
platform_art_runtime_references_match_request_contract, prepare_platform_art_asset_output_path,
|
||||
project_canvas_asset_media_types, role_has_canvas_assets, suggested_canvas_tool_call,
|
||||
PlatformArtAssetGenerationOptions, PLATFORM_ART_ASSET_GENERATION_KINDS,
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
pub(crate) use draft_validation::{
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -577,6 +577,8 @@ pub(in crate::agent) async fn observe_agent_runtime_platform_art_asset_generatio
|
||||
slice_mode: (!slice_mode.trim().is_empty()).then_some(slice_mode.clone()),
|
||||
grid_x,
|
||||
grid_y,
|
||||
reference_asset_ids: Vec::new(),
|
||||
target_category: None,
|
||||
screen_color: None,
|
||||
};
|
||||
if let Some(pending) = pending_action {
|
||||
@@ -629,6 +631,9 @@ pub(in crate::agent) async fn observe_agent_runtime_platform_art_asset_generatio
|
||||
.or_else(|| (!slice_mode.trim().is_empty()).then_some(slice_mode)),
|
||||
grid_x,
|
||||
grid_y,
|
||||
reference_asset_ids: requested_options.reference_asset_ids,
|
||||
// Agent 运行时不会指定完成登记的目标栏目,保持调用方给的值(默认 `None`)。
|
||||
target_category: requested_options.target_category,
|
||||
screen_color: requested_options.screen_color,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -390,6 +390,12 @@ pub(crate) async fn start_local_project_asset_generation(
|
||||
image_size: Option<String>,
|
||||
asset_name: Option<String>,
|
||||
output_path: Option<String>,
|
||||
// 前端 IPC 字段 `referenceAssetIds`:当前项目 manifest 里的图片素材 id,只做参考输入,
|
||||
// 不进任务账本(重试由调用方继续用同一份引用提交,账本本身不新增字段)。
|
||||
reference_asset_ids: Option<Vec<String>>,
|
||||
// 前端 IPC 字段 `targetCategory`:完成登记时要落盘的正式栏目分类。同样不进任务账本:
|
||||
// 它与引用一样属于「同一次提交的本地落点」,重试由调用方继续用同一个栏目提交。
|
||||
target_category: Option<String>,
|
||||
) -> Result<AssetGenerationTaskRecord, String> {
|
||||
let task_id = asset_generation_task_id(&task_id)?;
|
||||
let request = prepare_local_project_asset_generation(
|
||||
@@ -400,6 +406,8 @@ pub(crate) async fn start_local_project_asset_generation(
|
||||
image_size.as_deref(),
|
||||
asset_name.as_deref(),
|
||||
output_path.as_deref(),
|
||||
reference_asset_ids.as_deref().unwrap_or_default(),
|
||||
target_category.as_deref(),
|
||||
)?;
|
||||
enforce_project_permission_policy(&request.root, "canvas.asset_generate")?;
|
||||
enforce_project_permission_policy(&request.root, "asset.register")?;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::*;
|
||||
use sha2::{Digest as _, Sha256};
|
||||
use shared_contracts::game_creation_app::GameCreationAppAssetCategory;
|
||||
use std::future::Future;
|
||||
|
||||
const PRIVATE_EXTERNAL_EDITOR_API_KEY_FILE_PREFIX: &str = "external-editor-api-";
|
||||
@@ -662,6 +663,7 @@ pub(crate) fn register_design_artifacts_at(root: &Path) -> Result<bool, String>
|
||||
generation_kind: None,
|
||||
reference_resource_ids: Vec::new(),
|
||||
},
|
||||
None,
|
||||
)?;
|
||||
changed |= asset_changed;
|
||||
}
|
||||
@@ -1876,8 +1878,56 @@ pub(crate) fn register_local_asset_entry(
|
||||
id_prefix: &str,
|
||||
source: GameCreationAppAssetSource,
|
||||
) -> Result<UploadLocalAssetResult, String> {
|
||||
register_local_asset_entry_with_change(root, local_path, kind, media_type, id_prefix, source)
|
||||
.map(|(result, _)| result)
|
||||
register_local_asset_entry_with_change(
|
||||
root, local_path, kind, media_type, id_prefix, source, None,
|
||||
)
|
||||
.map(|(result, _)| result)
|
||||
}
|
||||
|
||||
/// 带**显式目标分类**的登记入口:只给 GUI 生成完成路径用(前端 `targetCategory`)。
|
||||
///
|
||||
/// 入口栏目与生成 kind 不是同一套词汇(栏目 `character` / `scene` / `ui-interaction`,
|
||||
/// 生成 kind 的派生分类会把图片落到 `unclassified`、规范图落到 `document`),所以要落回
|
||||
/// 入口栏目只能由调用方把目标分类显式交进来。取值必须先过
|
||||
/// [`shared_contracts::game_creation_app::game_creation_app_asset_category_from_str`],
|
||||
/// 非法值失败关闭,绝不回退到 kind 派生;其它调用方继续走
|
||||
/// [`register_local_asset_entry`],行为不变。
|
||||
pub(crate) fn register_local_asset_entry_with_category(
|
||||
root: &Path,
|
||||
local_path: &str,
|
||||
kind: &str,
|
||||
media_type: &str,
|
||||
id_prefix: &str,
|
||||
source: GameCreationAppAssetSource,
|
||||
target_category: Option<&str>,
|
||||
) -> Result<UploadLocalAssetResult, String> {
|
||||
let target_category = normalize_asset_category_override(target_category)?;
|
||||
register_local_asset_entry_with_change(
|
||||
root,
|
||||
local_path,
|
||||
kind,
|
||||
media_type,
|
||||
id_prefix,
|
||||
source,
|
||||
target_category,
|
||||
)
|
||||
.map(|(result, _)| result)
|
||||
}
|
||||
|
||||
/// 归一显式目标分类:只接受合法枚举值,返回落盘字符串。
|
||||
fn normalize_asset_category_override(
|
||||
target_category: Option<&str>,
|
||||
) -> Result<Option<GameCreationAppAssetCategory>, String> {
|
||||
let Some(target_category) = target_category else {
|
||||
return Ok(None);
|
||||
};
|
||||
let target_category = target_category.trim();
|
||||
if target_category.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
game_creation_app_asset_category_from_str(target_category)
|
||||
.map(Some)
|
||||
.ok_or_else(|| format!("非法资源分类:{target_category}"))
|
||||
}
|
||||
|
||||
fn register_local_asset_entry_with_change(
|
||||
@@ -1887,6 +1937,7 @@ fn register_local_asset_entry_with_change(
|
||||
media_type: &str,
|
||||
id_prefix: &str,
|
||||
source: GameCreationAppAssetSource,
|
||||
target_category: Option<GameCreationAppAssetCategory>,
|
||||
) -> Result<(UploadLocalAssetResult, bool), String> {
|
||||
let normalized_path = normalize_relative_path(local_path)?;
|
||||
let absolute_path = resolve_local_project_path(root, &normalized_path)?;
|
||||
@@ -1912,11 +1963,17 @@ fn register_local_asset_entry_with_change(
|
||||
// kind 没变时刻意不动 category——落盘分类是权威值,同 kind 重登记不得抹掉它。
|
||||
let changed = existing.kind != kind
|
||||
|| existing.media_type != media_type
|
||||
|| existing.source != source;
|
||||
|| existing.source != source
|
||||
|| target_category.is_some_and(|category| existing.category != category);
|
||||
if existing.kind != kind {
|
||||
existing.kind = kind.to_string();
|
||||
existing.category = game_creation_app_asset_category_for_kind(kind);
|
||||
}
|
||||
// 调用方显式给出目标分类时它就是权威值:GUI 完成登记必须能落回入口栏目,
|
||||
// 这也是同路径重新生成时把资产从旧栏目(或 unclassified)原位接管过来的唯一入口。
|
||||
if let Some(category) = target_category {
|
||||
existing.category = category;
|
||||
}
|
||||
existing.media_type = media_type.to_string();
|
||||
existing.source = source;
|
||||
Ok((existing.id.clone(), "asset.update", changed))
|
||||
@@ -1933,7 +1990,8 @@ fn register_local_asset_entry_with_change(
|
||||
local_path: normalized_path.clone(),
|
||||
image_sequence_frames: None,
|
||||
image_sequence_duration_ms: None,
|
||||
category: game_creation_app_asset_category_for_kind(kind),
|
||||
category: target_category
|
||||
.unwrap_or_else(|| game_creation_app_asset_category_for_kind(kind)),
|
||||
tags: Vec::new(),
|
||||
source,
|
||||
});
|
||||
@@ -2153,6 +2211,7 @@ pub(crate) fn delete_manifest_asset_at(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use shared_contracts::game_creation_app::GameCreationAppAssetCategory;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
#[test]
|
||||
@@ -2176,6 +2235,121 @@ mod tests {
|
||||
assert!(!register_design_artifacts_at(root).expect("register idempotently"));
|
||||
}
|
||||
|
||||
/// GUI 完成登记可以显式指定目标栏目:新建条目与已登记条目都按显式值落盘。
|
||||
///
|
||||
/// 入口栏目(character / scene / ui-interaction)与生成 kind 不是同一套词汇,按 kind 派生
|
||||
/// 会把图片落到 unclassified,占位拿不回原位;非法值必须失败关闭,不传时保持 kind 派生。
|
||||
#[test]
|
||||
fn explicit_target_category_overrides_the_kind_derived_category() {
|
||||
fn canvas_source() -> GameCreationAppAssetSource {
|
||||
GameCreationAppAssetSource {
|
||||
kind: GameCreationAppAssetSourceKind::Canvas,
|
||||
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(),
|
||||
}
|
||||
}
|
||||
fn category_of(root: &Path, asset_id: &str) -> GameCreationAppAssetCategory {
|
||||
read_existing_manifest_for_project(root)
|
||||
.expect("read manifest")
|
||||
.assets
|
||||
.into_iter()
|
||||
.find(|asset| asset.id == asset_id)
|
||||
.expect("registered asset is present")
|
||||
.category
|
||||
}
|
||||
|
||||
let temporary = tempfile::tempdir().expect("tempdir");
|
||||
let root = temporary.path();
|
||||
crate::project::init_local_game_project_at(root, "target-category-test", "目标栏目登记")
|
||||
.expect("init project");
|
||||
fs::create_dir_all(root.join("assets")).expect("create assets dir");
|
||||
fs::write(root.join("assets/hero.png"), b"png-bytes").expect("write asset");
|
||||
|
||||
let registered = register_local_asset_entry_with_category(
|
||||
root,
|
||||
"assets/hero.png",
|
||||
"image",
|
||||
"image/png",
|
||||
"platform-art",
|
||||
canvas_source(),
|
||||
Some("character"),
|
||||
)
|
||||
.expect("register with a target category");
|
||||
assert_eq!(
|
||||
category_of(root, ®istered.id),
|
||||
GameCreationAppAssetCategory::Character
|
||||
);
|
||||
|
||||
// 同 kind 重新生成时显式目标分类仍是权威值:资产要能换栏目原位接管。
|
||||
register_local_asset_entry_with_category(
|
||||
root,
|
||||
"assets/hero.png",
|
||||
"image",
|
||||
"image/png",
|
||||
"platform-art",
|
||||
canvas_source(),
|
||||
Some("ui-interaction"),
|
||||
)
|
||||
.expect("re-register with another target category");
|
||||
assert_eq!(
|
||||
category_of(root, ®istered.id),
|
||||
GameCreationAppAssetCategory::UiInteraction
|
||||
);
|
||||
|
||||
// 非法值失败关闭,且不动已落盘的分类。
|
||||
assert!(register_local_asset_entry_with_category(
|
||||
root,
|
||||
"assets/hero.png",
|
||||
"image",
|
||||
"image/png",
|
||||
"platform-art",
|
||||
canvas_source(),
|
||||
Some("version"),
|
||||
)
|
||||
.is_err());
|
||||
assert_eq!(
|
||||
category_of(root, ®istered.id),
|
||||
GameCreationAppAssetCategory::UiInteraction
|
||||
);
|
||||
|
||||
// 不传目标分类时保持原有行为:新条目按 kind 派生(image → unclassified)。
|
||||
fs::write(root.join("assets/plain.png"), b"png-bytes").expect("write plain asset");
|
||||
let plain = register_local_asset_entry(
|
||||
root,
|
||||
"assets/plain.png",
|
||||
"image",
|
||||
"image/png",
|
||||
"platform-art",
|
||||
canvas_source(),
|
||||
)
|
||||
.expect("register without a target category");
|
||||
assert_eq!(
|
||||
category_of(root, &plain.id),
|
||||
GameCreationAppAssetCategory::Unclassified
|
||||
);
|
||||
// 已落盘的显式分类在 kind 未变时仍然是权威值:同 kind 重登记不得把它抹掉。
|
||||
register_local_asset_entry(
|
||||
root,
|
||||
"assets/hero.png",
|
||||
"image",
|
||||
"image/png",
|
||||
"platform-art",
|
||||
canvas_source(),
|
||||
)
|
||||
.expect("re-register without a target category");
|
||||
assert_eq!(
|
||||
category_of(root, ®istered.id),
|
||||
GameCreationAppAssetCategory::UiInteraction
|
||||
);
|
||||
}
|
||||
|
||||
/// 画板导出推断出的 kind 必须已经是 canonical 值。
|
||||
///
|
||||
/// 这个值会被原样写进 manifest 并据以派生落盘 `category`;一旦写出非 canonical 值
|
||||
|
||||
@@ -2375,6 +2375,27 @@ pub(crate) fn update_local_project_resource_classification(
|
||||
)
|
||||
}
|
||||
|
||||
/// 为一批已登记素材追加标签:整批一次校验、一次 manifest 写入、一次 revision 推进。
|
||||
///
|
||||
/// 权限位与单素材分类更新同口径取 `asset.register`(命令包装层只做权限门面,
|
||||
/// 身份 / 写锁 / CAS / 原子写与审计都在 `project/manifest.rs` 内完成)。
|
||||
/// 这里刻意**不**循环调用单素材命令:逐项调用会写出多份 manifest、推进多次 revision,
|
||||
/// 中途失败还会留下"前几个素材改了、后面的没改"的部分写入。
|
||||
#[tauri::command]
|
||||
pub(crate) fn add_local_project_resource_tags(
|
||||
input: AddLocalProjectResourceTagsInput,
|
||||
) -> Result<AddLocalProjectResourceTagsResult, String> {
|
||||
let root = Path::new(input.project_path.trim());
|
||||
enforce_project_permission_policy(root, "asset.register")?;
|
||||
add_manifest_asset_tags_at(
|
||||
root,
|
||||
&input.expected_project_id,
|
||||
input.expected_project_revision,
|
||||
input.asset_ids,
|
||||
input.tags,
|
||||
)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub(crate) async fn derive_local_project_resource(
|
||||
input: DeriveLocalProjectResourceInput,
|
||||
@@ -4926,6 +4947,8 @@ pub(crate) fn prepare_local_project_asset_generation(
|
||||
image_size: Option<&str>,
|
||||
asset_name: Option<&str>,
|
||||
output_path: Option<&str>,
|
||||
reference_asset_ids: &[String],
|
||||
target_category: Option<&str>,
|
||||
) -> Result<LocalProjectAssetGenerationRequest, String> {
|
||||
let project_path = project_path.trim();
|
||||
if project_path.is_empty() {
|
||||
@@ -4933,6 +4956,13 @@ pub(crate) fn prepare_local_project_asset_generation(
|
||||
}
|
||||
let asset_kind = normalize_platform_art_asset_generation_kind(kind)
|
||||
.ok_or_else(|| format!("素材类型不受支持:{}", kind.trim()))?;
|
||||
// 参考入参只接受当前项目 manifest 素材 id:路径、远端 resourceId 与超限在这里就被拒绝,
|
||||
// 不把校验推迟到远端(远端只该收到当前账号绑定下的 resource ID)。
|
||||
let reference_asset_ids =
|
||||
normalize_platform_art_reference_asset_ids(asset_kind, reference_asset_ids)?;
|
||||
// GUI 完成登记层参数:入口栏目与生成 kind 不是同一套词汇,只有调用方显式给出目标分类
|
||||
// 才能把产物原位落回入口栏目。非法值(含 `version` / `all` 这类栏目伪值)直接失败关闭。
|
||||
let target_category = normalize_platform_art_target_category(target_category)?;
|
||||
Ok(LocalProjectAssetGenerationRequest {
|
||||
root: PathBuf::from(project_path),
|
||||
prompt: local_project_asset_prompt(prompt)?,
|
||||
@@ -4969,6 +4999,8 @@ pub(crate) fn prepare_local_project_asset_generation(
|
||||
.then(|| "connected-components".to_string()),
|
||||
grid_x: None,
|
||||
grid_y: None,
|
||||
reference_asset_ids,
|
||||
target_category,
|
||||
screen_color: None,
|
||||
},
|
||||
})
|
||||
@@ -4991,6 +5023,10 @@ pub(crate) async fn generate_local_project_asset(
|
||||
image_size: Option<String>,
|
||||
asset_name: Option<String>,
|
||||
output_path: Option<String>,
|
||||
reference_asset_ids: Option<Vec<String>>,
|
||||
// 前端 IPC 字段 `targetCategory`:本次生成完成登记时要落盘的正式栏目分类,
|
||||
// 只走 GUI 命令,取值必须是合法素材分类,Agent / Direct 路径不传。
|
||||
target_category: Option<String>,
|
||||
) -> Result<UploadLocalAssetResult, String> {
|
||||
let request = prepare_local_project_asset_generation(
|
||||
&project_path,
|
||||
@@ -5000,6 +5036,8 @@ pub(crate) async fn generate_local_project_asset(
|
||||
image_size.as_deref(),
|
||||
asset_name.as_deref(),
|
||||
output_path.as_deref(),
|
||||
reference_asset_ids.as_deref().unwrap_or_default(),
|
||||
target_category.as_deref(),
|
||||
)?;
|
||||
enforce_project_permission_policy(&request.root, "canvas.asset_generate")?;
|
||||
enforce_project_permission_policy(&request.root, "asset.register")?;
|
||||
@@ -5018,7 +5056,17 @@ mod local_project_asset_generation_tests {
|
||||
use super::*;
|
||||
|
||||
fn prepare(kind: &str, prompt: &str) -> Result<LocalProjectAssetGenerationRequest, String> {
|
||||
prepare_local_project_asset_generation("/tmp/project", kind, prompt, None, None, None, None)
|
||||
prepare_local_project_asset_generation(
|
||||
"/tmp/project",
|
||||
kind,
|
||||
prompt,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -5058,6 +5106,8 @@ mod local_project_asset_generation_tests {
|
||||
Some("2K"),
|
||||
Some(" 主角图集 "),
|
||||
Some(" assets/hero.png "),
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect("explicit options");
|
||||
assert_eq!(explicit.root, PathBuf::from("/tmp/project"));
|
||||
@@ -5085,8 +5135,18 @@ mod local_project_asset_generation_tests {
|
||||
#[test]
|
||||
fn invalid_toolbar_arguments_are_rejected_before_any_generation() {
|
||||
assert_eq!(
|
||||
prepare_local_project_asset_generation("", "image", "要求", None, None, None, None)
|
||||
.expect_err("empty project path"),
|
||||
prepare_local_project_asset_generation(
|
||||
"",
|
||||
"image",
|
||||
"要求",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect_err("empty project path"),
|
||||
"项目路径不能为空"
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -5097,6 +5157,60 @@ mod local_project_asset_generation_tests {
|
||||
prepare("game-art", "要求").expect_err("unverified kind"),
|
||||
"素材类型不受支持:game-art"
|
||||
);
|
||||
// 目标分类只接受合法素材分类枚举:栏目侧伪值 `version` / `all` 与任意其它值都失败关闭。
|
||||
for rejected in ["version", "all", "bogus", "UI"] {
|
||||
assert_eq!(
|
||||
prepare_local_project_asset_generation(
|
||||
"/tmp/project",
|
||||
"image",
|
||||
"要求",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
Some(rejected),
|
||||
)
|
||||
.expect_err("illegal target category"),
|
||||
format!("目标分类不是合法素材分类:{rejected}")
|
||||
);
|
||||
}
|
||||
// 合法值归一成落盘字符串(trim + kebab-case),供 manifest `category` 直接使用。
|
||||
assert_eq!(
|
||||
prepare_local_project_asset_generation(
|
||||
"/tmp/project",
|
||||
"image",
|
||||
"要求",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
Some(" ui-interaction "),
|
||||
)
|
||||
.expect("legal target category")
|
||||
.options
|
||||
.target_category
|
||||
.as_deref(),
|
||||
Some("ui-interaction")
|
||||
);
|
||||
assert_eq!(
|
||||
prepare_local_project_asset_generation(
|
||||
"/tmp/project",
|
||||
"image",
|
||||
"要求",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect("omitted target category")
|
||||
.options
|
||||
.target_category,
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
prepare(
|
||||
"spec",
|
||||
@@ -5113,7 +5227,9 @@ mod local_project_asset_generation_tests {
|
||||
Some("4:3"),
|
||||
None,
|
||||
None,
|
||||
None
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect_err("unsupported ratio"),
|
||||
"图片比例不受支持:4:3"
|
||||
@@ -5126,7 +5242,9 @@ mod local_project_asset_generation_tests {
|
||||
None,
|
||||
Some("4K"),
|
||||
None,
|
||||
None
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect_err("unsupported size"),
|
||||
"图片尺寸不受支持:4K"
|
||||
@@ -5139,7 +5257,9 @@ mod local_project_asset_generation_tests {
|
||||
None,
|
||||
None,
|
||||
Some("坏\u{7}名字"),
|
||||
None
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect_err("control character in asset name"),
|
||||
"素材名称超出安全边界"
|
||||
@@ -5152,7 +5272,9 @@ mod local_project_asset_generation_tests {
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(&"a".repeat(LOCAL_PROJECT_ASSET_MAX_OUTPUT_PATH_CHARS + 1))
|
||||
Some(&"a".repeat(LOCAL_PROJECT_ASSET_MAX_OUTPUT_PATH_CHARS + 1)),
|
||||
&[],
|
||||
None,
|
||||
)
|
||||
.expect_err("oversized output path"),
|
||||
"输出路径超出安全边界"
|
||||
|
||||
@@ -2589,6 +2589,7 @@ fn main() {
|
||||
register_local_asset,
|
||||
create_ui_design_resource,
|
||||
update_local_project_resource_classification,
|
||||
add_local_project_resource_tags,
|
||||
derive_local_project_resource,
|
||||
list_pending_local_project_resource_edits,
|
||||
resume_local_project_resource_edit,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user