合并主线Mac运行资源与发布门禁更新

合入 origin/master b137f1759,保留画布验收与计时返修。
同步主线0.1.67版本及Mac随包资源、插件能力和发布目标检查。
合并双方排障说明,不提交个人依赖锁文件改动。
This commit is contained in:
2026-09-18 13:27:28 +08:00
28 changed files with 1267 additions and 184 deletions
+6
View File
@@ -41,6 +41,12 @@ temp*build*/
/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/
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/bin/
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/codex-path/
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/codex-resources/
/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
/plugins/agc-cocos-editor/native/payload/
/apps/ai-game-creator-shell/logs/
/apps/ai-game-creator-shell/.llm-drafts/
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@genarrative/ai-game-creator-shell",
"private": true,
"version": "0.1.47",
"version": "0.1.67",
"type": "module",
"scripts": {
"dev": "node scripts/start-tauri-dev.mjs",
@@ -14,16 +14,71 @@ const appRoot = fileURLToPath(new URL('..', import.meta.url));
// 提交摘要里的 pathspec 与 `git log` 都以仓库根为基准,不能在应用目录里执行。
const repoRoot = path.resolve(appRoot, '..', '..');
const defaultReleaseTarget = 'x86_64-pc-windows-msvc';
const releaseTarget =
process.env.AGC_BUILD_TARGET?.trim() || defaultReleaseTarget;
const bundleRoot = path.join(
appRoot,
'src-tauri',
'target',
releaseTarget,
'release',
'bundle',
);
function defaultTarget() {
return process.env.AGC_BUILD_TARGET?.trim() || defaultReleaseTarget;
}
function explicitBuildTarget(args) {
let target;
const separator = args.indexOf('--');
const options = separator < 0 ? args : args.slice(0, separator);
for (let index = 0; index < options.length; index += 1) {
const argument = options[index];
let value;
if (argument === '--target' || argument === '-t') {
value = options[++index];
} else if (argument.startsWith('--target=')) {
value = argument.slice('--target='.length);
} else {
continue;
}
if (!value?.trim() || value.startsWith('-')) {
throw new Error('--target 缺少有效目标');
}
if (target !== undefined) throw new Error('不能重复指定 --target');
target = value.trim();
}
return target;
}
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',
].includes(target)
) {
throw new Error(`不支持的发布目标:${target}`);
}
return target;
}
/** 在入口冻结目标;所有发布步骤共享同一上下文,不再各自读取默认目标。 */
export function resolveReleaseContext(args = [], env = process.env) {
const target = validateReleaseTarget(
explicitBuildTarget(args) ||
env.AGC_BUILD_TARGET?.trim() ||
defaultReleaseTarget,
);
return Object.freeze({
target,
channel: resolveReleaseChannel(env, target),
bundleRoot: path.join(
appRoot,
'src-tauri',
'target',
target,
'release',
'bundle',
),
});
}
const packageJsonPath = path.join(appRoot, 'package.json');
const rootPackageLockPath = path.resolve(appRoot, '../..', 'package-lock.json');
const tauriConfigPath = path.join(appRoot, 'src-tauri', 'tauri.conf.json');
@@ -99,7 +154,7 @@ export function nextPatchVersion(localVersion, remoteVersion) {
return `${major}.${minor}.${patch + 1}`;
}
export function resolveReleasePlatform(target = releaseTarget) {
export function resolveReleasePlatform(target = defaultTarget()) {
if (target.includes('windows')) return 'windows';
if (target.includes('apple-darwin')) return 'darwin';
if (target.includes('linux')) return 'linux';
@@ -108,7 +163,7 @@ export function resolveReleasePlatform(target = releaseTarget) {
export function resolveReleaseChannel(
env = process.env,
target = releaseTarget,
target = defaultTarget(),
) {
const platform = resolveReleasePlatform(target);
const requested = env.AGC_UPDATE_CHANNEL?.trim();
@@ -142,13 +197,10 @@ export function updateManifestUrl(channel = resolveReleaseChannel()) {
}
/**
* 更新插件按运行时平台键查找清单条目:universal macOS 包同时挂
* `darwin-aarch64` 与 `darwin-x86_64`,单架构目标只挂对应键。
* 单架构产物只登记实际目标,不能把同一原生资源映射为另一架构。
*/
export function resolveManifestPlatformKeys(target = releaseTarget) {
if (target === 'universal-apple-darwin') {
return ['darwin-aarch64', 'darwin-x86_64'];
}
export function resolveManifestPlatformKeys(target = defaultTarget()) {
validateReleaseTarget(target);
if (target === 'aarch64-apple-darwin') return ['darwin-aarch64'];
if (target === 'x86_64-apple-darwin') return ['darwin-x86_64'];
if (target.includes('windows')) {
@@ -256,8 +308,8 @@ function replaceVersionLine(source, version, pattern, label) {
return source.replace(pattern, `$1${version}$3`);
}
export async function prepareReleaseVersion() {
const channel = resolveReleaseChannel();
export async function prepareReleaseVersion(context = resolveReleaseContext()) {
const { channel } = context;
const localVersion = parseVersion(readPackageJson().version, '本地版本');
const remoteVersion = await resolveRemoteHighWaterVersion(channel);
const requestedVersion = process.env.AGC_RELEASE_VERSION?.trim();
@@ -330,18 +382,14 @@ export async function prepareReleaseVersion() {
export function buildTauriBuildArguments(
args = [],
target = releaseTarget,
target = defaultTarget(),
platform = process.platform,
) {
const noBundle = args.includes('--no-bundle');
const targetIndex = args.indexOf('--target');
const explicitTarget =
targetIndex >= 0
? args[targetIndex + 1]
: args
.find((value) => value.startsWith('--target='))
?.slice('--target='.length);
const explicitTarget = explicitBuildTarget(args);
const targetArgs = noBundle || explicitTarget ? [] : ['--target', target];
if (!noBundle || explicitTarget)
validateReleaseTarget(explicitTarget || target);
const features = defaultEditorFeatures(
explicitTarget || (noBundle ? platform : target),
);
@@ -374,18 +422,33 @@ function writeChannelConfigFile(channel) {
return configPath;
}
export function runTauriBuild(args = []) {
const tauriArguments = buildTauriBuildArguments(args);
if (!tauriArguments.includes('--config') && !tauriArguments.includes('-c')) {
const channel = resolveReleaseChannel();
const configPath = writeChannelConfigFile(channel);
console.log(
`[ai-game-creator-shell] 渠道 ${channel} 端点配置:${configPath}`,
);
tauriArguments.push('--config', configPath);
export function runTauriBuild(
args = [],
context = resolveReleaseContext(args),
{ spawn = spawnSync } = {},
) {
if (
explicitBuildTarget(args) &&
explicitBuildTarget(args) !== context.target
) {
throw new Error('构建参数与发布上下文目标不一致');
}
const tauriArguments = buildTauriBuildArguments(args, context.target);
const { channel } = context;
const configPath = writeChannelConfigFile(channel);
console.log(
`[ai-game-creator-shell] 渠道 ${channel} 端点配置:${configPath}`,
);
// 最后合并渠道配置,防止用户配置中的端点与实际发布目标分叉。
const separator = tauriArguments.indexOf('--');
tauriArguments.splice(
separator < 0 ? tauriArguments.length : separator,
0,
'--config',
configPath,
);
const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const result = spawnSync(
const result = spawn(
npmCommand,
['--prefix', '../..', 'exec', 'tauri', '--', ...tauriArguments],
{ cwd: appRoot, stdio: 'inherit', shell: process.platform === 'win32' },
@@ -402,11 +465,11 @@ function listFiles(root) {
});
}
function artifactPriority(filePath) {
function artifactPriority(filePath, target) {
const name = path.basename(filePath).toLowerCase();
if (releaseTarget.includes('windows')) return name.endsWith('.exe') ? 0 : 99;
if (target.includes('windows')) return name.endsWith('.exe') ? 0 : 99;
// 更新链路要的是 updater 产物(macOS 为 .app.tar.gz),dmg 只作人工分发。
if (releaseTarget.includes('apple-darwin')) {
if (target.includes('apple-darwin')) {
return name.endsWith('.app.tar.gz') ? 0 : 99;
}
if (name.endsWith('.appimage.tar.gz')) return 0;
@@ -416,7 +479,8 @@ function artifactPriority(filePath) {
return 99;
}
export function selectReleaseArtifact(files) {
export function selectReleaseArtifact(files, target = defaultTarget()) {
validateReleaseTarget(target);
const explicit = process.env.AGC_UPDATE_ARTIFACT?.trim();
if (explicit) {
const resolved = path.resolve(explicit);
@@ -427,9 +491,10 @@ export function selectReleaseArtifact(files) {
}
return (
[...files]
.filter((filePath) => artifactPriority(filePath) < 99)
.filter((filePath) => artifactPriority(filePath, target) < 99)
.sort((left, right) => {
const priority = artifactPriority(left) - artifactPriority(right);
const priority =
artifactPriority(left, target) - artifactPriority(right, target);
return priority || left.localeCompare(right);
})[0] ?? null
);
@@ -450,13 +515,15 @@ function readUpdaterSignature(artifactPath) {
export function createUpdateManifest(
artifactPath,
{
channel = resolveReleaseChannel(),
target = releaseTarget,
target = defaultTarget(),
channel = resolveReleaseChannel(process.env, target),
publishedAt = new Date().toISOString(),
notes = readReleaseNotes(),
commit = readHeadCommit(),
} = {},
) {
validateReleaseTarget(target);
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: channel }, target);
const signature = readUpdaterSignature(artifactPath);
const version = readPackageJson().version;
const fileName = path.basename(artifactPath);
@@ -604,9 +671,11 @@ export function createLegacyUpdateManifest(
};
}
export async function generateUpdateManifest() {
const channel = resolveReleaseChannel();
const artifact = selectReleaseArtifact(listFiles(bundleRoot));
export async function generateUpdateManifest(
context = resolveReleaseContext(),
) {
const { channel, target, bundleRoot } = context;
const artifact = selectReleaseArtifact(listFiles(bundleRoot), target);
if (!artifact) {
throw new Error(`未找到可发布的 AGC 安装包:${bundleRoot}`);
}
@@ -623,7 +692,7 @@ export async function generateUpdateManifest() {
`[ai-game-creator-shell] 未生成自动更新摘要(上一发布 commit=${previousCommit ?? '未知'},客户端相关提交=${commits ? commits.length : '不可判定'},最近提交=${recentCommits ? recentCommits.length : '不可判定'}`,
);
}
const manifest = createUpdateManifest(artifact, { channel, notes });
const manifest = createUpdateManifest(artifact, { channel, target, notes });
const manifestPath = path.join(bundleRoot, 'latest.json');
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
const notesPath = path.join(bundleRoot, 'release-notes.txt');
@@ -675,12 +744,24 @@ export async function generateUpdateManifest() {
};
}
export async function buildRelease(
args = [],
{
prepareVersion = prepareReleaseVersion,
build = runTauriBuild,
generateManifest = generateUpdateManifest,
} = {},
) {
const context = resolveReleaseContext(args);
if (!args.includes('--no-bundle')) await prepareVersion(context);
build(args, context);
if (!args.includes('--no-bundle')) return generateManifest(context);
}
if (
process.argv[1] &&
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
const args = process.argv.slice(2);
if (!args.includes('--no-bundle')) await prepareReleaseVersion();
runTauriBuild(args);
if (!args.includes('--no-bundle')) await generateUpdateManifest();
await buildRelease(args);
}
@@ -14,6 +14,8 @@ import { fileURLToPath } from 'node:url';
import {
agcReleasePathPatterns,
buildRelease,
buildTauriBuildArguments,
collectRecentReleaseCommits,
collectReleaseCommits,
compareVersions,
@@ -22,11 +24,14 @@ import {
createUpdateManifest,
formatRecentReleaseNotes,
formatReleaseNotes,
generateUpdateManifest,
nextPatchVersion,
resolveManifestPlatformKeys,
resolvePreviousReleaseCommit,
resolveReleaseChannel,
resolveReleaseContext,
resolveRemoteHighWaterVersion,
runTauriBuild,
selectReleaseArtifact,
updateManifestUrl,
} from './build-release.mjs';
@@ -34,6 +39,21 @@ 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']) {
assert.deepEqual(buildTauriBuildArguments([], target), [
'build',
'--target',
target,
]);
}
});
function withEnv(overrides, run) {
const previous = new Map();
for (const [key, value] of Object.entries(overrides)) {
@@ -132,9 +152,12 @@ test('channel manifest URL and build-time endpoint follow the channel', () => {
});
});
test('universal macOS builds publish one artifact under both platform keys', () => {
assert.deepEqual(resolveManifestPlatformKeys(universalTarget), [
test('macOS manifests only advertise the architecture actually built', () => {
assert.throws(() => resolveManifestPlatformKeys(universalTarget), /单架构/);
assert.deepEqual(resolveManifestPlatformKeys('aarch64-apple-darwin'), [
'darwin-aarch64',
]);
assert.deepEqual(resolveManifestPlatformKeys('x86_64-apple-darwin'), [
'darwin-x86_64',
]);
assert.deepEqual(resolveManifestPlatformKeys(windowsTarget), [
@@ -142,6 +165,218 @@ test('universal macOS builds publish one artifact under both platform keys', ()
]);
});
test('release context resolves explicit targets before environment/default and fails closed', () => {
for (const args of [
['--target', 'aarch64-apple-darwin'],
['--target=aarch64-apple-darwin'],
['-t', 'aarch64-apple-darwin'],
]) {
for (const env of [{}, { AGC_BUILD_TARGET: windowsTarget }]) {
const context = resolveReleaseContext(args, env);
assert.equal(context.target, 'aarch64-apple-darwin');
assert.equal(context.channel, 'dev-mac');
assert.match(
context.bundleRoot.replaceAll('\\', '/'),
/target\/aarch64-apple-darwin\/release\/bundle$/,
);
assert.ok(Object.isFrozen(context));
}
assert.throws(
() => resolveReleaseContext(args, { AGC_UPDATE_CHANNEL: 'dev-win' }),
/只能用于 windows/,
);
}
assert.equal(resolveReleaseContext([], {}).target, windowsTarget);
assert.equal(
resolveReleaseContext([], { AGC_BUILD_TARGET: 'x86_64-apple-darwin' })
.channel,
'dev-mac',
);
for (const args of [
['--target'],
['--target='],
['--target', '--no-bundle'],
['--target', windowsTarget, '--target=aarch64-apple-darwin'],
['--target', universalTarget],
['--target', 'unknown'],
])
assert.throws(() => resolveReleaseContext(args, {}));
});
test('explicit macOS target drives version lookup, Tauri endpoint, artifact and manifest together', async () => {
const calls = [];
const seenContexts = [];
await withStubbedFetch(
(url) => {
calls.push(url);
assert.match(url, /\/dev-mac\/latest\.json$/);
return jsonResponse({ version: '0.1.67' });
},
() =>
withEnv(
{ AGC_BUILD_TARGET: undefined, AGC_UPDATE_CHANNEL: undefined },
() =>
buildRelease(['--target', 'aarch64-apple-darwin'], {
prepareVersion: async (context) => {
seenContexts.push(context);
assert.equal(
await resolveRemoteHighWaterVersion(context.channel),
'0.1.67',
);
},
build: (args, context) => {
seenContexts.push(context);
runTauriBuild(args, context, {
spawn: (_binary, command) => {
const configIndex = command.lastIndexOf('--config');
const config = JSON.parse(
readFileSync(command[configIndex + 1], 'utf8'),
);
assert.match(
config.plugins.updater.endpoints[0],
/\/dev-mac\/latest\.json$/,
);
assert.ok(command.includes('aarch64-apple-darwin'));
assert.ok(
!command.includes('--features=cocos-editor-execute'),
);
return { status: 0 };
},
});
},
generateManifest: (context) => {
seenContexts.push(context);
withSignedArtifact('陶泥儿.app.tar.gz', (artifact) => {
assert.equal(
selectReleaseArtifact(
['/tmp/win.exe', artifact, '/tmp/mac.dmg'],
context.target,
),
artifact,
);
const manifest = createUpdateManifest(artifact, context);
assert.deepEqual(Object.keys(manifest.platforms), [
'darwin-aarch64',
]);
assert.match(
manifest.platforms['darwin-aarch64'].url,
/\/dev-mac\//,
);
});
},
}),
),
);
assert.equal(calls.length, 1, 'Mac 不应读取 Windows 迁移指针');
assert.equal(seenContexts.length, 3);
assert.ok(seenContexts.every((context) => context === seenContexts[0]));
});
test('real manifest writer uses the resolved bundle root and does not emit Windows artifacts', async () => {
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-mac-manifest-'));
try {
const artifact = path.join(root, '陶泥儿.app.tar.gz');
writeFileSync(artifact, 'mac package');
writeFileSync(`${artifact}.sig`, 'mac signature');
writeFileSync(path.join(root, 'windows.exe'), 'wrong platform');
const context = {
...resolveReleaseContext(['--target=x86_64-apple-darwin'], {}),
bundleRoot: root,
};
const result = await withStubbedFetch(
(url) => {
assert.match(url, /\/dev-mac\/latest\.json$/);
return jsonResponse({}, 404);
},
() => generateUpdateManifest(context),
);
assert.equal(result.artifact, artifact);
assert.equal(result.manifestPath, path.join(root, 'latest.json'));
assert.equal(result.legacyManifestPath, null);
assert.deepEqual(Object.keys(result.manifest.platforms), ['darwin-x86_64']);
assert.match(result.manifest.platforms['darwin-x86_64'].url, /\/dev-mac\//);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
test('invalid target or mismatched channel fails before any release side effect', async () => {
let touched = false;
const sideEffects = {
prepareVersion: () => {
touched = true;
},
build: () => {
touched = true;
},
generateManifest: () => {
touched = true;
},
};
await assert.rejects(
() => buildRelease(['--target', universalTarget], sideEffects),
/单架构/,
);
await withEnv({ AGC_UPDATE_CHANNEL: 'dev-win' }, () =>
assert.rejects(
() => buildRelease(['--target=aarch64-apple-darwin'], sideEffects),
/只能用于 windows/,
),
);
assert.equal(touched, false);
});
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 [
resolveReleaseContext([], {}),
resolveReleaseContext(['--target', windowsTarget], {
AGC_BUILD_TARGET: 'aarch64-apple-darwin',
}),
]) {
assert.equal(context.channel, 'dev-win');
assert.equal(
selectReleaseArtifact(files, context.target),
'/tmp/windows.exe',
);
runTauriBuild(
['--target', windowsTarget, '--config', 'user-config.json'],
context,
{
spawn: (_binary, command) => {
assert.ok(command.includes('--features=cocos-editor-execute'));
assert.ok(command.includes('user-config.json'));
const configIndex = command.lastIndexOf('--config');
const config = JSON.parse(
readFileSync(command[configIndex + 1], 'utf8'),
);
assert.match(
config.plugins.updater.endpoints[0],
/\/dev-win\/latest\.json$/,
);
return { status: 0 };
},
},
);
}
});
test('no-bundle smoke skips version writes and manifest generation', async () => {
const steps = [];
await buildRelease(['--no-bundle', '--target=aarch64-apple-darwin'], {
prepareVersion: () => {
steps.push('version');
},
build: (_args, context) => {
steps.push(context.channel);
},
generateManifest: () => {
steps.push('manifest');
},
});
assert.deepEqual(steps, ['dev-mac']);
});
test('channel manifest carries version, platform keys and signature', () => {
withSignedArtifact('陶泥儿_0.1.48_x64-setup.exe', (artifact) => {
withEnv({ AGC_UPDATE_RELEASE_NOTES: '修复与改进' }, () => {
@@ -345,6 +580,7 @@ test('release upload forces overwrite for artifact, signature and channel pointe
);
assert.match(source, /agc\/\$\{channel\}\/latest\.json/u);
assert.match(source, /agc\/latest\.json/u);
assert.match(source, /await buildRelease\(process\.argv\.slice\(2\)\)/u);
});
test('release notes list client commits with short sha and bound their size', () => {
@@ -35,6 +35,12 @@ const windowsTauriConfig = JSON.parse(
'utf8',
),
);
const macosTauriConfig = JSON.parse(
fs.readFileSync(
new URL('../src-tauri/tauri.macos.conf.json', import.meta.url),
'utf8',
),
);
const cargoManifestSource = fs.readFileSync(
new URL('../src-tauri/Cargo.toml', import.meta.url),
'utf8',
@@ -1358,6 +1364,37 @@ if (windowsTauriConfig.bundle?.useLocalToolsDir !== true) {
'AI game creator shell Windows Tauri config must cache bundling tools in the project target directory',
);
}
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}`,
]),
['resources/plugins', 'plugins'],
]),
'macOS must bundle the complete native Codex layout and plugin workspace',
);
assert.deepEqual(
macosTauriConfig.plugins?.updater?.endpoints,
[
'https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/dev-mac/latest.json',
],
'macOS local builds must not use the Windows update channel',
);
assert.equal(
macosTauriConfig.bundle?.macOS?.minimumSystemVersion,
'15.0',
'macOS deployment baseline must cover the bundled native zsh requirement',
);
if (tauriConfig.app?.withGlobalTauri !== true) {
throw new Error(
@@ -1722,7 +1759,7 @@ for (const snippet of [
'fn append_local_permission_log_at(',
'"command.auto"',
'GameCreationAppPermission::Auto',
'GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH',
'fn game_creator_bundled_codex_cli_path',
'validate_game_creator_bundled_codex_cli',
'内置 Codex CLI 完整性校验失败',
]) {
@@ -0,0 +1,222 @@
import assert from 'node:assert/strict';
import { spawn, spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
// 只操作临时复制品;不启动 GUI、不读取开发机凭据、不访问 Provider。
assert.equal(process.platform, 'darwin', '此验证必须在 macOS 执行');
const source = path.resolve(process.argv[2] || '');
assert.ok(
source.endsWith('.app') && fs.statSync(source).isDirectory(),
'请传入 .app 绝对路径',
);
const root = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), 'agc-macos-bundle-')),
);
const app = path.join(root, '陶泥儿 隔离测试.app');
const home = path.join(root, 'home');
const config = path.join(root, 'config');
const tmp = path.join(root, 'tmp');
const codexHome = path.join(root, 'codex-home');
for (const directory of [home, config, tmp, codexHome]) {
fs.mkdirSync(directory, { mode: 0o700 });
}
const env = {
HOME: home,
PATH: '/usr/bin:/bin',
TMPDIR: tmp,
CODEX_HOME: codexHome,
};
function run(command, args) {
const result = spawnSync(command, args, {
cwd: root,
env,
encoding: 'utf8',
timeout: 30_000,
maxBuffer: 1024 * 1024,
});
assert.ifError(result.error);
return result;
}
async function hashFile(file) {
const hash = createHash('sha256');
for await (const chunk of fs.createReadStream(file)) hash.update(chunk);
return hash.digest('hex');
}
async function handshake(executable) {
const child = spawn(executable, ['app-server'], {
cwd: root,
env,
stdio: ['pipe', 'pipe', 'pipe'],
});
let buffered = '';
let stderrBytes = 0;
try {
await new Promise((resolve, reject) => {
const timer = setTimeout(
() => reject(new Error('app-server 初始化超时')),
15_000,
);
const finish = (error) => {
clearTimeout(timer);
if (error) reject(error);
else resolve();
};
child.on('error', finish);
child.on('exit', (code) =>
finish(new Error(`app-server 提前退出 ${code}`)),
);
child.stderr.on('data', (chunk) => {
stderrBytes += chunk.length;
if (stderrBytes > 1024 * 1024)
finish(new Error('app-server stderr 超限'));
});
child.stdout.on('data', (chunk) => {
buffered += chunk.toString('utf8');
if (buffered.length > 1024 * 1024)
return finish(new Error('app-server stdout 超限'));
let end;
while ((end = buffered.indexOf('\n')) >= 0) {
const line = buffered.slice(0, end);
buffered = buffered.slice(end + 1);
try {
const message = JSON.parse(line);
if (message.id !== 1) continue;
assert.ok(message.result?.userAgent, '初始化必须返回真实服务身份');
assert.equal(message.error, undefined);
child.stdin.write(`${JSON.stringify({ method: 'initialized' })}\n`);
finish();
} catch (error) {
finish(error);
}
}
});
child.stdin.on('error', finish);
child.stdin.write(
`${JSON.stringify({
id: 1,
method: 'initialize',
params: {
clientInfo: {
name: 'agc_bundle_smoke',
title: 'AGC bundle smoke',
version: '1',
},
capabilities: { experimentalApi: true },
},
})}\n`,
);
});
} finally {
if (child.exitCode === null && child.signalCode === null) {
await new Promise((resolve) => {
const timer = setTimeout(() => child.kill('SIGKILL'), 3000);
child.once('exit', () => {
clearTimeout(timer);
resolve();
});
child.kill('SIGTERM');
});
}
}
}
try {
fs.cpSync(source, app, { recursive: true });
const resources = path.join(app, 'Contents/Resources');
const bundle = path.join(resources, 'coding-agent/mac-native');
const executable = path.join(bundle, 'bin/codex');
const main = path.join(
app,
'Contents/MacOS/genarrative-ai-game-creator-shell',
);
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.version, 'codex-cli 0.147.0');
const components = [
'bin/codex',
'bin/codex-code-mode-host',
'codex-path/rg',
'codex-resources/zsh/bin/zsh',
'codex-package.json',
];
assert.deepEqual(Object.keys(manifest.files).sort(), [...components].sort());
for (const component of components) {
const file = path.join(bundle, component);
assert.equal(await hashFile(file), manifest.files[component], component);
if (component !== 'codex-package.json') {
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.ok(fs.existsSync(path.join(bundle, 'NOTICE.md')));
const plugin = path.join(resources, 'plugins/agc-cocos-editor');
for (const file of [
'plugin.json',
'src/entry.mjs',
'panels/cocos-editor.html',
]) {
assert.ok(fs.existsSync(path.join(plugin, file)), file);
}
const packageFiles = fs.readdirSync(resources, { recursive: true });
assert.ok(
!packageFiles.some((file) =>
/(^|\/)(\.env[^/]*|auth\.json|node_modules|target|\.git)(\/|$)|\.(exe|dll)$/.test(
file,
),
),
);
assert.equal(run(executable, ['--version']).stdout.trim(), manifest.version);
assert.equal(
run(path.join(bundle, 'codex-path/rg'), ['--version']).status,
0,
);
assert.equal(
run(path.join(bundle, 'codex-resources/zsh/bin/zsh'), ['--version']).status,
0,
);
// 使用正式 AGC 查找/校验入口,而非只证明 sidecar 可以独立执行。
const status = run(main, ['--config-dir', config, '--llm-status']);
const statusText = `${status.stdout}\n${status.stderr}`;
assert.ok(!statusText.includes('Codex CLI 未安装'), statusText);
assert.ok(
statusText.includes('authentication-required'),
'隔离账号应仅被登录门禁拒绝',
);
await handshake(executable);
// 临时复制品缺少辅助程序时,正式入口必须拒绝内置程序;PATH 无全局 Codex 可兜底。
fs.renameSync(
path.join(bundle, 'bin/codex-code-mode-host'),
path.join(root, 'saved-code-mode-host'),
);
const broken = run(main, ['--config-dir', config, '--llm-status']);
assert.notEqual(broken.status, 0);
assert.match(`${broken.stdout}\n${broken.stderr}`, /Codex CLI 未安装/);
console.log(
'PASS: 隔离安装包资源、架构、摘要、权限、正式 Codex 查找、app-server 握手及缺组件拒绝',
);
console.log(
'未验证:GUI、真实登录/Provider 对话、Cocos macOS 原生桥接;插件 Node 仍为外部前提',
);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
@@ -12,8 +12,7 @@ if (!/^[a-z0-9][a-z0-9.-]{1,62}$/u.test(bucket) || /[\r\n\0]/u.test(endpoint)) {
process.env.AGC_UPDATE_OSS_BASE_URL ||= `https://${bucket}.${endpoint}/agc`;
const dryRun = readReleaseDryRun();
const { generateUpdateManifest, prepareReleaseVersion, runTauriBuild } =
await import('./build-release.mjs');
const { buildRelease } = await import('./build-release.mjs');
function runOssutil(args) {
const binary = process.env.OSSUTIL_BIN?.trim() || 'ossutil';
@@ -51,10 +50,8 @@ function runOssutil(args) {
if (result.status !== 0) process.exit(result.status ?? 1);
}
await prepareReleaseVersion();
runTauriBuild([]);
const { artifact, channel, legacyManifestPath, manifest, manifestPath } =
await generateUpdateManifest();
await buildRelease(process.argv.slice(2));
const artifactKey = `agc/${channel}/${manifest.version}/${path.basename(artifact)}`;
// Jenkins/ossutil 默认会在目标对象已存在时交互询问并按默认值跳过;
// 发布清单是固定的 latest 指针,必须显式覆盖,否则流水线会误报成功但远端仍保留旧版本。
+1 -1
View File
@@ -1745,7 +1745,7 @@ dependencies = [
[[package]]
name = "genarrative-ai-game-creator-shell"
version = "0.1.47"
version = "0.1.67"
dependencies = [
"agent-runtime-core",
"axum",
@@ -1,6 +1,6 @@
[package]
name = "genarrative-ai-game-creator-shell"
version = "0.1.47"
version = "0.1.67"
edition = "2021"
publish = false
+82 -48
View File
@@ -1,31 +1,18 @@
#[path = "build_support/codex_bundle.rs"]
mod codex_bundle;
#[path = "build_support/frontend_dist_guard.rs"]
mod frontend_dist_guard;
#[path = "build_support/runtime_prompt_bundle.rs"]
mod runtime_prompt_bundle;
#[cfg(windows)]
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;
use std::env;
use std::fs;
use std::path::PathBuf;
#[cfg(windows)]
use std::io::{BufReader, Read};
const BUNDLED_CODEX_CLI_VERSION: &str = "codex-cli 0.147.0";
#[cfg(windows)]
const BUNDLED_CODEX_FILES: [&str; 6] = [
"bin/codex.exe",
"bin/codex-code-mode-host.exe",
"codex-path/rg.exe",
"codex-resources/codex-command-runner.exe",
"codex-resources/codex-windows-sandbox-setup.exe",
"codex-package.json",
];
#[cfg(windows)]
fn sha256_file(path: &std::path::Path) -> Result<String, std::io::Error> {
let file = fs::File::open(path)?;
let mut reader = BufReader::new(file);
@@ -42,7 +29,15 @@ fn sha256_file(path: &std::path::Path) -> Result<String, std::io::Error> {
}
fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) {
#[cfg(windows)]
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 {
assert!(
!target.contains("windows") && !target.contains("apple-darwin"),
"不支持的 Codex 随包目标:{target}"
);
return;
};
{
let app_root = manifest_dir
.parent()
@@ -51,24 +46,23 @@ fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) {
.parent()
.and_then(|apps_dir| apps_dir.parent())
.expect("AI 游戏创作应用必须位于仓库 apps 目录下");
let source_candidates = [
app_root.join(
"node_modules/@openai/codex-win32-x64/vendor/x86_64-pc-windows-msvc",
),
app_root.join(
"node_modules/@openai/codex/node_modules/@openai/codex-win32-x64/vendor/x86_64-pc-windows-msvc",
),
repo_root.join(
"node_modules/@openai/codex-win32-x64/vendor/x86_64-pc-windows-msvc",
),
repo_root.join(
"node_modules/@openai/codex/node_modules/@openai/codex-win32-x64/vendor/x86_64-pc-windows-msvc",
),
];
let package = layout.npm_package;
let source_candidates = [app_root, repo_root]
.into_iter()
.flat_map(|root| {
[
root.join(format!("node_modules/@openai/{package}/vendor/{target}")),
root.join(format!(
"node_modules/@openai/codex/node_modules/@openai/{package}/vendor/{target}"
)),
]
})
.collect::<Vec<_>>();
let source = source_candidates
.iter()
.find(|path| {
BUNDLED_CODEX_FILES
layout
.files
.iter()
.all(|relative| path.join(relative).is_file())
})
@@ -83,14 +77,26 @@ fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) {
.join("")
)
});
let target_dir = manifest_dir.join("resources/codex/win-x64");
let metadata: serde_json::Value = serde_json::from_slice(
&fs::read(source.join("codex-package.json")).expect("读取 Codex 原生包元数据失败"),
)
.expect("Codex 原生包元数据无效");
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");
if target.contains("apple-darwin") {
let source_notice =
manifest_dir.join("resources/codex/【声明】Mac内置Codex组件-2026-09-18.md");
stage_plugin_file(&source_notice, &notice);
println!("cargo:rerun-if-changed={}", source_notice.display());
}
if !notice.is_file() {
panic!("内置 Codex CLI 第三方声明缺失:{}", notice.display());
}
fs::create_dir_all(&target_dir).expect("创建内置 Codex CLI 资源目录失败");
let mut file_hashes = serde_json::Map::new();
for relative in BUNDLED_CODEX_FILES {
for relative in layout.files {
let source_path = source.join(relative);
let target_path = target_dir.join(relative);
if let Some(parent) = target_path.parent() {
@@ -104,15 +110,23 @@ fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) {
if !target_matches_source {
fs::copy(&source_path, &target_path).expect("复制内置 Codex CLI 资源失败");
}
// 内容相同但曾被错误 chmod 的 staging 文件也必须恢复执行权限。
fs::set_permissions(
&target_path,
fs::metadata(&source_path)
.expect("读取组件权限失败")
.permissions(),
)
.expect("保留内置 Codex CLI 组件权限失败");
file_hashes.insert(
relative.to_string(),
serde_json::Value::String(source_sha256),
);
}
let manifest = serde_json::json!({
"schemaVersion": "genarrative-codex-sidecar.v2",
"platform": "win32-x64",
"version": BUNDLED_CODEX_CLI_VERSION,
"schemaVersion": codex_bundle::SCHEMA,
"platform": layout.platform,
"version": codex_bundle::CLI_VERSION,
"files": file_hashes,
});
let manifest_path = target_dir.join("manifest.json");
@@ -126,7 +140,7 @@ fn stage_bundled_codex_cli(manifest_dir: &std::path::Path) {
{
fs::write(&manifest_path, manifest_payload).expect("写入内置 Codex CLI 清单失败");
}
for relative in BUNDLED_CODEX_FILES {
for relative in layout.files {
println!("cargo:rerun-if-changed={}", source.join(relative).display());
}
println!("cargo:rerun-if-changed={}", notice.display());
@@ -256,8 +270,11 @@ fn stage_cocos_editor_payload(_manifest_dir: &std::path::Path) {}
///
/// 只复制插件运行需要的清单、入口、面板和 native payload,不复制 native 源码、
/// Cargo target 目录或 node_modules。
#[cfg(windows)]
fn stage_plugin_workspace(manifest_dir: &std::path::Path) {
let target = env::var("TARGET").expect("Cargo TARGET");
if !target.contains("windows") && !target.contains("apple-darwin") {
return;
}
let repo_root = manifest_dir
.parent()
.and_then(|app_root| app_root.parent())
@@ -266,6 +283,10 @@ fn stage_plugin_workspace(manifest_dir: &std::path::Path) {
.to_path_buf();
let workspace = repo_root.join("plugins");
let destination_root = manifest_dir.join("resources/plugins");
// staging 是专用生成目录;重建清除跨目标 payload 与已删除插件的残留。
if destination_root.exists() {
std::fs::remove_dir_all(&destination_root).expect("清理插件 staging 失败");
}
std::fs::create_dir_all(&destination_root).expect("创建插件资源目录失败");
let entries = match std::fs::read_dir(&workspace) {
Ok(entries) => entries,
@@ -273,6 +294,13 @@ fn stage_plugin_workspace(manifest_dir: &std::path::Path) {
};
for entry in entries.flatten() {
let plugin_root = entry.path();
assert!(
!entry
.file_type()
.expect("读取插件目录类型失败")
.is_symlink(),
"插件工作区不允许符号链接"
);
if !plugin_root.is_dir() || !plugin_root.join("plugin.json").is_file() {
continue;
}
@@ -287,17 +315,18 @@ fn stage_plugin_workspace(manifest_dir: &std::path::Path) {
std::path::PathBuf::from("panels"),
std::path::PathBuf::from("native/payload"),
] {
if relative == std::path::Path::new("native/payload") && !target.contains("windows") {
continue;
}
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;
};
let bytes = std::fs::read(source)
.unwrap_or_else(|error| panic!("读取随包资源失败 {}{error}", source.display()));
if std::fs::read(destination).is_ok_and(|existing| existing == bytes) {
return;
}
@@ -307,7 +336,6 @@ fn stage_plugin_file(source: &std::path::Path, destination: &std::path::Path) {
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,
@@ -316,10 +344,17 @@ fn copy_plugin_tree(source: &std::path::Path, destination: &std::path::Path) {
for entry in entries.flatten() {
let target = destination.join(entry.file_name());
let path = entry.path();
assert!(
!entry
.file_type()
.expect("读取插件文件类型失败")
.is_symlink(),
"插件资源不允许符号链接"
);
if path.is_dir() {
let name = entry.file_name();
let name = name.to_string_lossy();
if matches!(name.as_ref(), "target" | "node_modules" | ".git") {
if name.starts_with('.') || matches!(name.as_ref(), "target" | "node_modules") {
continue;
}
std::fs::create_dir_all(&target).expect("创建插件资源目录失败");
@@ -331,12 +366,14 @@ fn copy_plugin_tree(source: &std::path::Path, destination: &std::path::Path) {
if name.contains(".test.") {
continue;
}
if name.starts_with('.') {
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;
@@ -345,6 +382,3 @@ fn copy_plugin_file(source: &std::path::Path, destination: &std::path::Path) {
.expect("创建插件资源目录失败");
std::fs::copy(source, destination).expect("复制插件资源失败");
}
#[cfg(not(windows))]
fn stage_plugin_workspace(_manifest_dir: &std::path::Path) {}
@@ -0,0 +1,133 @@
//! 构建与运行共用的平台布局;只允许分发锁定原生包里的明确组件。
pub const VERSION: &str = "0.147.0";
pub const CLI_VERSION: &str = "codex-cli 0.147.0";
pub const SCHEMA: &str = "genarrative-codex-sidecar.v2";
#[derive(Clone, Copy, Debug)]
pub struct Layout {
pub platform: &'static str,
pub npm_package: &'static str,
pub directory: &'static str,
pub executable: &'static str,
pub files: &'static [&'static str],
}
const WINDOWS_FILES: &[&str] = &[
"bin/codex.exe",
"bin/codex-code-mode-host.exe",
"codex-path/rg.exe",
"codex-resources/codex-command-runner.exe",
"codex-resources/codex-windows-sandbox-setup.exe",
"codex-package.json",
];
const MAC_FILES: &[&str] = &[
"bin/codex",
"bin/codex-code-mode-host",
"codex-path/rg",
"codex-resources/zsh/bin/zsh",
"codex-package.json",
];
pub fn for_target(target: &str) -> Option<Layout> {
match target {
"x86_64-pc-windows-msvc" => Some(Layout {
platform: "win32-x64",
npm_package: "codex-win32-x64",
directory: "win-x64",
executable: "bin/codex.exe",
files: WINDOWS_FILES,
}),
"aarch64-apple-darwin" | "x86_64-apple-darwin" => Some(Layout {
platform: if target.starts_with("aarch64") {
"darwin-arm64"
} else {
"darwin-x64"
},
npm_package: if target.starts_with("aarch64") {
"codex-darwin-arm64"
} else {
"codex-darwin-x64"
},
directory: "mac-native",
executable: "bin/codex",
files: MAC_FILES,
}),
_ => None,
}
}
pub fn validate_package_metadata(
metadata: &serde_json::Value,
target: &str,
layout: Layout,
) -> Result<(), String> {
if metadata["layoutVersion"] == 1
&& metadata["version"] == VERSION
&& metadata["target"] == target
&& metadata["entrypoint"] == layout.executable
&& metadata["resourcesDir"] == "codex-resources"
&& metadata["pathDir"] == "codex-path"
{
Ok(())
} else {
Err(format!("Codex 原生包版本、布局或架构不匹配目标 {target}"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn platform_layouts_are_explicit_and_preserve_upstream_components() {
let mac = for_target("aarch64-apple-darwin").unwrap();
assert_eq!(mac.platform, "darwin-arm64");
assert_eq!(mac.npm_package, "codex-darwin-arm64");
assert!(mac.files.contains(&"codex-resources/zsh/bin/zsh"));
assert!(mac.files.contains(&"bin/codex-code-mode-host"));
assert!(!mac.files.iter().any(|file| file.ends_with(".exe")));
let intel = for_target("x86_64-apple-darwin").unwrap();
assert_eq!(intel.platform, "darwin-x64");
assert_eq!(intel.npm_package, "codex-darwin-x64");
let windows = for_target("x86_64-pc-windows-msvc").unwrap();
assert_eq!(windows.directory, "win-x64");
assert_eq!(windows.files.len(), 6);
assert!(windows
.files
.contains(&"codex-resources/codex-windows-sandbox-setup.exe"));
assert!(for_target("universal-apple-darwin").is_none());
assert!(for_target("aarch64-pc-windows-msvc").is_none());
assert!(for_target("x86_64-unknown-linux-gnu").is_none());
}
#[test]
fn metadata_rejects_version_architecture_and_layout_drift() {
let target = "aarch64-apple-darwin";
let layout = for_target(target).unwrap();
let valid = serde_json::json!({
"layoutVersion": 1,
"version": VERSION,
"target": target,
"entrypoint": "bin/codex",
"resourcesDir": "codex-resources",
"pathDir": "codex-path",
});
assert!(validate_package_metadata(&valid, target, layout).is_ok());
for (key, value) in [
("layoutVersion", serde_json::json!(2)),
("version", serde_json::json!("0.0.0")),
("target", serde_json::json!("x86_64-apple-darwin")),
("entrypoint", serde_json::json!("bin/codex.exe")),
("resourcesDir", serde_json::json!("../private")),
("pathDir", serde_json::json!(null)),
] {
let mut invalid = valid.clone();
invalid[key] = value;
assert!(
validate_package_metadata(&invalid, target, layout).is_err(),
"{key}"
);
}
}
}
@@ -0,0 +1,14 @@
# 内置 Codex CLI
本安装包包含锁定版本 Codex CLI 0.147.0 的 macOS 原生组件。
Codex CLI 按 Apache License 2.0 分发,源码与许可证见
https://github.com/openai/codex。
组件来自项目锁定的 `@openai/codex` 原生 npm 依赖,保留上游的
`bin/codex``bin/codex-code-mode-host``codex-path/rg`
`codex-resources/zsh/bin/zsh``codex-package.json` 相对布局。
原生依赖中的 ripgrep 与 zsh 按各自上游许可证分发:
https://github.com/BurntSushi/ripgrep 和 https://www.zsh.org/。
安装包不包含 API Key、登录状态、用户配置或项目数据。
@@ -5,18 +5,10 @@ use std::process::Stdio;
use sha2::{Digest, Sha256};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
#[path = "../../build_support/codex_bundle.rs"]
mod codex_bundle;
const GAME_CREATOR_CODEX_CLI_EXECUTABLE: &str = "codex";
const GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH: &str = "coding-agent/win-x64/bin/codex.exe";
const GAME_CREATOR_BUNDLED_CODEX_CLI_MANIFEST_RELATIVE_PATH: &str =
"coding-agent/win-x64/manifest.json";
const GAME_CREATOR_BUNDLED_CODEX_CLI_REQUIRED_FILES: [&str; 6] = [
"bin/codex.exe",
"bin/codex-code-mode-host.exe",
"codex-path/rg.exe",
"codex-resources/codex-command-runner.exe",
"codex-resources/codex-windows-sandbox-setup.exe",
"codex-package.json",
];
const GAME_CREATOR_CODEX_CLI_PROMPT_MAX_BYTES: usize = 4 * 1024 * 1024;
const GAME_CREATOR_CODEX_CLI_STDOUT_MAX_BYTES: usize = 4 * 1024 * 1024;
const GAME_CREATOR_CODEX_CLI_STDERR_MAX_BYTES: usize = 256 * 1024;
@@ -38,11 +30,11 @@ fn game_creator_codex_cli_executable_candidates_for(
path: Option<&std::ffi::OsStr>,
) -> Vec<PathBuf> {
let mut candidates = Vec::new();
if let Some(bundled) = game_creator_bundled_codex_cli_path(resource_dir) {
candidates.push(bundled);
}
#[cfg(windows)]
{
if let Some(resource_dir) = resource_dir {
candidates.push(resource_dir.join(GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH));
}
fn append_native_npm_candidates(candidates: &mut Vec<PathBuf>, npm_root: &Path) {
let vendor_root = npm_root
.join("node_modules")
@@ -109,52 +101,71 @@ fn game_creator_codex_cli_executable_candidates() -> Vec<PathBuf> {
}
fn game_creator_bundled_resource_dir() -> Option<PathBuf> {
let executable = std::env::current_exe().ok()?;
game_creator_bundled_resource_dir_for(&executable)
}
fn game_creator_bundled_resource_dir_for(executable: &Path) -> Option<PathBuf> {
#[cfg(windows)]
{
std::env::current_exe()
.ok()
.and_then(|path| path.parent().map(Path::to_path_buf))
executable.parent().map(Path::to_path_buf)
}
#[cfg(not(windows))]
#[cfg(target_os = "macos")]
{
let macos = executable.parent()?;
let contents = macos.parent()?;
// 只接受真正的 app bundle 结构,开发态不从任意相邻目录加载程序。
if macos.file_name()? != "MacOS"
|| contents.file_name()? != "Contents"
|| contents.parent()?.extension()? != "app"
{
return None;
}
Some(contents.join("Resources"))
}
#[cfg(not(any(windows, target_os = "macos")))]
{
let _ = executable;
None
}
}
fn game_creator_bundled_codex_cli_path(resource_dir: Option<&Path>) -> Option<PathBuf> {
resource_dir.map(|resource_dir| resource_dir.join(GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH))
let layout = codex_bundle::for_target(env!("AGC_BUILD_TARGET"))?;
Some(
resource_dir?
.join("coding-agent")
.join(layout.directory)
.join(layout.executable),
)
}
fn validate_game_creator_bundled_codex_cli(executable: &Path) -> Result<String, String> {
let layout = codex_bundle::for_target(env!("AGC_BUILD_TARGET"))
.ok_or_else(|| "当前平台不支持内置 Codex CLI".to_string())?;
let bundle_root = executable
.parent()
.and_then(Path::parent)
.ok_or_else(|| "内置 Codex CLI 路径无效".to_string())?;
let manifest_path = bundle_root.join(
Path::new(GAME_CREATOR_BUNDLED_CODEX_CLI_MANIFEST_RELATIVE_PATH)
.file_name()
.expect("bundled Codex manifest file name"),
);
let manifest_path = bundle_root.join("manifest.json");
let manifest = std::fs::read_to_string(&manifest_path)
.map_err(|_| "内置 Codex CLI 缺少完整性清单".to_string())
.and_then(|value| {
serde_json::from_str::<GameCreatorBundledCodexCliManifest>(&value)
.map_err(|_| "内置 Codex CLI 完整性清单无效".to_string())
})?;
if manifest.schema_version != "genarrative-codex-sidecar.v2"
|| manifest.platform != "win32-x64"
if manifest.schema_version != codex_bundle::SCHEMA
|| manifest.platform != layout.platform
|| manifest.version.trim().is_empty()
|| GAME_CREATOR_BUNDLED_CODEX_CLI_REQUIRED_FILES
.iter()
.any(|relative| {
manifest.files.get(*relative).map_or(true, |hash| {
hash.len() != 64 || !hash.bytes().all(|byte| byte.is_ascii_hexdigit())
})
|| layout.files.iter().any(|relative| {
manifest.files.get(*relative).map_or(true, |hash| {
hash.len() != 64 || !hash.bytes().all(|byte| byte.is_ascii_hexdigit())
})
})
{
return Err("内置 Codex CLI 完整性清单不受支持".to_string());
}
for relative in GAME_CREATOR_BUNDLED_CODEX_CLI_REQUIRED_FILES {
for relative in layout.files {
let path = bundle_root.join(relative);
let bytes = std::fs::read(&path).map_err(|_| {
format!(
@@ -163,7 +174,7 @@ fn validate_game_creator_bundled_codex_cli(executable: &Path) -> Result<String,
)
})?;
let actual = format!("{:x}", Sha256::digest(bytes));
if !actual.eq_ignore_ascii_case(manifest.files.get(relative).expect("validated hash")) {
if !actual.eq_ignore_ascii_case(manifest.files.get(*relative).expect("validated hash")) {
return Err(format!("内置 Codex CLI 完整性校验失败:组件 {relative}"));
}
}
@@ -899,7 +910,7 @@ mod tests {
fn codex_cli_candidates_prefer_bundled_sidecar_before_npm_and_path() {
let temp = tempfile::tempdir().expect("temp dir");
let resources = temp.path().join("resources");
let bundled = resources.join(GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH);
let bundled = game_creator_bundled_codex_cli_path(Some(&resources)).unwrap();
std::fs::create_dir_all(bundled.parent().expect("bundled parent")).expect("bundled dir");
let app_data = temp.path().join("app-data");
let native = app_data
@@ -918,20 +929,19 @@ mod tests {
assert_eq!(candidates[1], native);
}
#[cfg(windows)]
#[cfg(any(windows, target_os = "macos"))]
#[test]
fn bundled_codex_cli_requires_matching_manifest_hash() {
let temp = tempfile::tempdir().expect("temp dir");
let executable = temp
.path()
.join(GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH);
let executable = game_creator_bundled_codex_cli_path(Some(temp.path())).unwrap();
let layout = codex_bundle::for_target(env!("AGC_BUILD_TARGET")).unwrap();
std::fs::create_dir_all(executable.parent().expect("sidecar parent")).expect("sidecar dir");
let bundle_root = executable
.parent()
.and_then(Path::parent)
.expect("bundle root");
let mut hashes = std::collections::BTreeMap::new();
for relative in GAME_CREATOR_BUNDLED_CODEX_CLI_REQUIRED_FILES {
for relative in layout.files {
let path = bundle_root.join(relative);
std::fs::create_dir_all(path.parent().expect("component parent"))
.expect("component dir");
@@ -939,14 +949,14 @@ mod tests {
std::fs::write(&path, bytes.as_bytes()).expect("component bytes");
hashes.insert(relative, format!("{:x}", Sha256::digest(bytes.as_bytes())));
}
let files = serde_json::to_string(&hashes).expect("component hashes");
std::fs::write(
bundle_root.join("manifest.json"),
format!(
r#"{{"schemaVersion":"genarrative-codex-sidecar.v2","platform":"win32-x64","version":"codex-cli test","files":{files}}}"#
),
)
.expect("sidecar manifest");
let manifest = serde_json::json!({
"schemaVersion": codex_bundle::SCHEMA,
"platform": layout.platform,
"version": "codex-cli test",
"files": hashes,
});
let manifest_path = bundle_root.join("manifest.json");
std::fs::write(&manifest_path, manifest.to_string()).expect("sidecar manifest");
assert_eq!(
validate_game_creator_bundled_codex_cli(&executable).expect("trusted sidecar"),
@@ -956,15 +966,31 @@ mod tests {
assert!(validate_game_creator_bundled_codex_cli(&executable)
.expect_err("tampered sidecar must be rejected")
.contains("完整性校验失败"));
std::fs::write(&executable, format!("trusted {}", layout.executable)).unwrap();
let mut wrong_platform = manifest.clone();
wrong_platform["platform"] = serde_json::json!("wrong-platform");
std::fs::write(&manifest_path, wrong_platform.to_string()).unwrap();
assert!(validate_game_creator_bundled_codex_cli(&executable)
.expect_err("wrong platform must be rejected")
.contains("完整性清单不受支持"));
std::fs::write(&manifest_path, manifest.to_string()).unwrap();
let helper = bundle_root.join(layout.files[1]);
std::fs::write(&helper, b"tampered helper").unwrap();
assert!(validate_game_creator_bundled_codex_cli(&executable)
.expect_err("tampered helper must be rejected")
.contains("完整性校验失败"));
std::fs::remove_file(&helper).unwrap();
assert!(validate_game_creator_bundled_codex_cli(&executable)
.expect_err("missing helper must be rejected")
.contains("缺少必需组件"));
}
#[cfg(windows)]
#[cfg(any(windows, target_os = "macos"))]
#[test]
fn bundled_codex_cli_rejects_a_manifest_without_code_mode_host() {
let temp = tempfile::tempdir().expect("temp dir");
let executable = temp
.path()
.join(GAME_CREATOR_BUNDLED_CODEX_CLI_RELATIVE_PATH);
let executable = game_creator_bundled_codex_cli_path(Some(temp.path())).unwrap();
let layout = codex_bundle::for_target(env!("AGC_BUILD_TARGET")).unwrap();
std::fs::create_dir_all(executable.parent().expect("sidecar parent")).expect("sidecar dir");
let bundle_root = executable
.parent()
@@ -975,9 +1001,13 @@ mod tests {
let hash = format!("{:x}", Sha256::digest(bytes));
std::fs::write(
bundle_root.join("manifest.json"),
format!(
r#"{{"schemaVersion":"genarrative-codex-sidecar.v2","platform":"win32-x64","version":"codex-cli test","files":{{"bin/codex.exe":"{hash}"}}}}"#
),
serde_json::json!({
"schemaVersion": codex_bundle::SCHEMA,
"platform": layout.platform,
"version": "codex-cli test",
"files": { layout.executable: hash },
})
.to_string(),
)
.expect("sidecar manifest");
@@ -986,6 +1016,38 @@ mod tests {
.contains("完整性清单不受支持"));
}
#[cfg(target_os = "macos")]
#[test]
fn macos_bundle_resources_and_candidates_do_not_require_a_development_path() {
let executable = Path::new("/Applications/陶泥儿 测试.app/Contents/MacOS/taonier");
let resources = game_creator_bundled_resource_dir_for(executable).unwrap();
assert_eq!(
resources,
Path::new("/Applications/陶泥儿 测试.app/Contents/Resources")
);
let bundled = game_creator_bundled_codex_cli_path(Some(&resources)).unwrap();
let candidates = game_creator_codex_cli_executable_candidates_for(
Some(&resources),
None,
None,
None,
None,
);
assert_eq!(candidates, vec![bundled, PathBuf::from("codex")]);
assert!(
game_creator_bundled_resource_dir_for(Path::new("/tmp/target/release/taonier"))
.is_none()
);
assert!(
game_creator_bundled_resource_dir_for(Path::new("/tmp/Contents/MacOS/taonier"))
.is_none()
);
assert_eq!(
game_creator_codex_cli_executable_candidates_for(None, None, None, None, None),
vec![PathBuf::from("codex")],
);
}
#[cfg(windows)]
#[test]
fn codex_cli_resolver_finds_current_native_install() {
@@ -237,7 +237,7 @@ fn persist(guard: &BuiltinPluginState) -> Result<(), String> {
/// Agent 工具面是否可用:编译期 feature 打开且用户没有禁用该内置插件。
pub(crate) fn agent_tool_available(plugin: BuiltinPlugin) -> bool {
plugin.exposes_agent_tools()
&& cfg!(feature = "cocos-editor-execute")
&& cfg!(all(windows, feature = "cocos-editor-execute"))
&& is_enabled(plugin.id())
}
@@ -431,7 +431,7 @@ mod tests {
let _guard = test_lock();
let directory = tempdir().expect("temp config");
initialize(directory.path()).expect("initialize");
let tool_visible_when_enabled = cfg!(feature = "cocos-editor-execute");
let tool_visible_when_enabled = cfg!(all(windows, feature = "cocos-editor-execute"));
set_enabled(AGC_COCOS_EDITOR_PLUGIN_ID, true).expect("enable");
assert_eq!(
@@ -4,10 +4,10 @@
//! 目前由宿主在编译期链接(Cargo path 依赖),再按插件 manifest 的 `adapter`
//! 字段注册到通用插件宿主。宿主只认适配器 id,不包含目标编辑器知识。
#[cfg(feature = "cocos-editor")]
#[cfg(all(windows, feature = "cocos-editor-execute"))]
use std::path::PathBuf;
#[cfg(feature = "cocos-editor")]
#[cfg(all(windows, feature = "cocos-editor-execute"))]
use tauri::Manager;
use crate::plugin_host::PluginHost;
@@ -21,20 +21,20 @@ pub(crate) fn register_linked_editor_adapters(
app: &tauri::AppHandle,
host: &PluginHost,
) -> Result<(), String> {
#[cfg(feature = "cocos-editor")]
#[cfg(all(windows, feature = "cocos-editor-execute"))]
{
let adapter =
cocos_editor_bridge::CocosEditorAdapter::new(cocos_bridge_payload_candidates(app));
host.register_editor_adapter(Box::new(adapter))?;
}
#[cfg(not(feature = "cocos-editor"))]
#[cfg(not(all(windows, feature = "cocos-editor-execute")))]
{
let _ = (app, host);
}
Ok(())
}
#[cfg(feature = "cocos-editor")]
#[cfg(all(windows, feature = "cocos-editor-execute"))]
fn cocos_bridge_payload_candidates(app: &tauri::AppHandle) -> Vec<PathBuf> {
let mut candidates = Vec::new();
if let Ok(resource_dir) = app.path().resource_dir() {
@@ -767,6 +767,22 @@ fn permission_for_method(method: &str) -> Option<&'static str> {
}
}
fn has_cocos_editor_adapter(editors: &EditorRegistry) -> Result<bool, String> {
Ok(editors
.lock()
.map_err(|_| "编辑器注册表锁已损坏".to_string())?
.contains_key("cocos-editor"))
}
fn require_plugin_adapter(id: &str, editors: &EditorRegistry) -> Result<(), String> {
if id == crate::builtin_plugins::AGC_COCOS_EDITOR_PLUGIN_ID
&& !has_cocos_editor_adapter(editors)?
{
return Err("当前客户端不支持 Cocos 编辑器桥接".to_string());
}
Ok(())
}
impl PluginHost {
pub(crate) fn initialize(&self, config_dir: &Path) -> Result<(), String> {
let root = plugin_root(config_dir)?;
@@ -948,11 +964,12 @@ impl PluginHost {
.flatten()
.is_some()
});
let cocos_available = cocos_project && has_cocos_editor_adapter(&state.editors)?;
state
.plugins
.values()
.filter(|record| {
record.id != crate::builtin_plugins::AGC_COCOS_EDITOR_PLUGIN_ID || cocos_project
record.id != crate::builtin_plugins::AGC_COCOS_EDITOR_PLUGIN_ID || cocos_available
})
.map(|record| self.summary_locked(record))
.collect()
@@ -1017,6 +1034,7 @@ impl PluginHost {
.clone()
.ok_or_else(|| "插件宿主尚未初始化".to_string())?;
let active_project = state.active_project.clone();
require_plugin_adapter(id, &state.editors)?;
if id == crate::builtin_plugins::AGC_COCOS_EDITOR_PLUGIN_ID
&& !active_project
.lock()
@@ -1124,6 +1142,7 @@ impl PluginHost {
.state
.lock()
.map_err(|_| "插件宿主锁已损坏".to_string())?;
require_plugin_adapter(id, &state.editors)?;
let record = state
.plugins
.get(id)
@@ -1535,6 +1554,7 @@ impl PluginHost {
Ok(json!({"path": input.path, "content": content}))
}
"host.rpc" => {
require_plugin_adapter(&manifest.id, editors)?;
let input: EditorRpcInput = descriptor_from_params(params)?;
if manifest.id == crate::builtin_plugins::AGC_COCOS_EDITOR_PLUGIN_ID
&& !active_project
@@ -2122,6 +2142,8 @@ setTimeout(() => send({ jsonrpc: '2.0', id: 1, method: 'host.registerCommand', p
let host = PluginHost::default();
crate::builtin_plugins::initialize(directory.path()).expect("builtin plugin state");
host.initialize(directory.path()).expect("initialize");
host.register_editor_adapter(Box::new(StubCocosAdapter))
.expect("register adapter");
host.set_plugin_workspace(workspace)
.expect("set plugins workspace");
host.set_active_project(Some(directory.path().to_string_lossy().into_owned()))
@@ -2223,6 +2245,8 @@ setTimeout(() => send({ jsonrpc: '2.0', id: 1, method: 'host.registerCommand', p
let workspace = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../plugins");
let host = PluginHost::default();
host.initialize(directory.path()).expect("initialize");
host.register_editor_adapter(Box::new(StubCocosAdapter))
.expect("register adapter");
host.set_plugin_workspace(workspace).expect("set workspace");
let project = tempdir().expect("web project");
@@ -2235,4 +2259,53 @@ setTimeout(() => send({ jsonrpc: '2.0', id: 1, method: 'host.registerCommand', p
.all(|plugin| plugin.id != "agc-cocos-editor"));
assert!(host.start("agc-cocos-editor").is_err());
}
#[test]
fn cocos_plugin_requires_registered_adapter_even_for_a_cocos_project() {
let _guard = crate::builtin_plugins::test_lock();
let directory = tempdir().expect("temp config");
fs::write(
directory.path().join("package.json"),
r#"{"creator":{"version":"3.8.8"}}"#,
)
.unwrap();
fs::create_dir(directory.path().join("assets")).unwrap();
crate::builtin_plugins::initialize(directory.path()).unwrap();
let host = PluginHost::default();
host.initialize(directory.path()).unwrap();
host.set_plugin_workspace(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../plugins"))
.unwrap();
host.set_active_project(Some(directory.path().to_string_lossy().into_owned()))
.unwrap();
assert!(host
.list()
.unwrap()
.iter()
.all(|plugin| plugin.id != "agc-cocos-editor"));
assert!(host
.list_extensions()
.unwrap()
.iter()
.all(|plugin| plugin.id != "agc-cocos-editor"));
assert!(host
.start("agc-cocos-editor")
.err()
.expect("unsupported adapter")
.contains("不支持 Cocos"));
assert!(host
.read_panel("agc-cocos-editor", "cocos-editor")
.err()
.expect("unsupported adapter")
.contains("不支持 Cocos"));
assert!(host.state.lock().unwrap().plugins["agc-cocos-editor"]
.running
.is_none());
host.register_editor_adapter(Box::new(StubCocosAdapter))
.unwrap();
assert!(host
.list()
.unwrap()
.iter()
.any(|plugin| plugin.id == "agc-cocos-editor"));
}
}
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "陶泥儿",
"version": "0.1.47",
"version": "0.1.67",
"identifier": "world.genarrative.ai-game-creator",
"build": {
"beforeDevCommand": "npm --prefix ../.. run agc:serve",
@@ -0,0 +1,25 @@
{
"$schema": "https://schema.tauri.app/config/2",
"bundle": {
"macOS": {
"minimumSystemVersion": "15.0"
},
"resources": {
"resources/codex/mac-native/bin/codex": "coding-agent/mac-native/bin/codex",
"resources/codex/mac-native/bin/codex-code-mode-host": "coding-agent/mac-native/bin/codex-code-mode-host",
"resources/codex/mac-native/codex-path/rg": "coding-agent/mac-native/codex-path/rg",
"resources/codex/mac-native/codex-resources/zsh/bin/zsh": "coding-agent/mac-native/codex-resources/zsh/bin/zsh",
"resources/codex/mac-native/codex-package.json": "coding-agent/mac-native/codex-package.json",
"resources/codex/mac-native/NOTICE.md": "coding-agent/mac-native/NOTICE.md",
"resources/codex/mac-native/manifest.json": "coding-agent/mac-native/manifest.json",
"resources/plugins": "plugins"
}
},
"plugins": {
"updater": {
"endpoints": [
"https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/dev-mac/latest.json"
]
}
}
}
+5 -2
View File
@@ -303,7 +303,10 @@ import {
currentPlatformSessionGeneration,
requestPlatformSessionRefresh,
} from './services/platformSession';
import { setAgcPluginProjectPath, startAgcPlugin } from './services/pluginHost';
import {
setAgcPluginProjectPath,
startAvailableAgcPlugin,
} from './services/pluginHost';
import {
canSubscribeTauriEvents,
subscribeTauriEvent,
@@ -614,7 +617,7 @@ export function App({
void setAgcPluginProjectPath(nextProjectPath)
.then(async () => {
if (workspaceProjectKind === 'cocos' && nextProjectPath) {
await startAgcPlugin('agc-cocos-editor');
await startAvailableAgcPlugin('agc-cocos-editor');
}
})
.catch((error) => {
@@ -33,6 +33,16 @@ export async function startAgcPlugin(id: string) {
}) as Promise<AgcPluginSummary>;
}
/** 只消费宿主的能力投影,不因项目类型自行推断原生适配器是否存在。 */
export async function startAvailableAgcPlugin(id: string) {
const plugins = await listAgcPlugins();
const plugin = plugins.find((candidate) => candidate.id === id);
if (!plugin?.enabled || !plugin.hasRuntime || plugin.status === 'invalid') {
return;
}
return startAgcPlugin(id);
}
export async function stopAgcPlugin(id: string) {
return invokeOrThrow()('stop_agc_plugin', {
id,
@@ -0,0 +1,63 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { startAvailableAgcPlugin } from '../src/services/pluginHost';
afterEach(() => vi.unstubAllGlobals());
describe('插件自动启动使用后端能力投影', () => {
it.each(
[
[],
[
{
id: 'agc-cocos-editor',
enabled: false,
hasRuntime: true,
status: 'stopped',
},
],
[
{
id: 'agc-cocos-editor',
enabled: true,
hasRuntime: false,
status: 'package',
},
],
[
{
id: 'agc-cocos-editor',
enabled: true,
hasRuntime: true,
status: 'invalid',
},
],
].map((plugins) => ({ plugins })),
)('隐藏、禁用或不可执行的插件不启动(%j)', async ({ plugins }) => {
const invoke = vi.fn(async () => plugins);
vi.stubGlobal('window', { __TAURI__: { core: { invoke } } });
await startAvailableAgcPlugin('agc-cocos-editor');
expect(invoke).toHaveBeenCalledTimes(1);
expect(invoke).toHaveBeenCalledWith('list_agc_plugins');
});
it('支持的 Cocos 插件继续按原入口启动', async () => {
const invoke = vi.fn(async (command: string) =>
command === 'list_agc_plugins'
? [
{
id: 'agc-cocos-editor',
enabled: true,
hasRuntime: true,
status: 'stopped',
},
]
: {},
);
vi.stubGlobal('window', { __TAURI__: { core: { invoke } } });
await startAvailableAgcPlugin('agc-cocos-editor');
expect(invoke).toHaveBeenLastCalledWith('start_agc_plugin', {
id: 'agc-cocos-editor',
});
});
});
@@ -0,0 +1,27 @@
# Mac 客户端随包运行依赖补齐实施计划
- Version: 2
- Status: awaiting-windows-acceptance
- Date: 2026-09-18
- Parent Spec: `【里程碑】Mac客户端随包运行依赖补齐-2026-09-18.md`
## 修改顺序
本轮评审修复顺序:统一 release context(覆盖 build/upload 两入口)→ 版本/端点/产物/清单的定向回归 → 宿主列表/启动/面板与前端自动启动能力门禁 → 同步单架构权威文档 → Node/Vitest/Rust/typecheck/编码/文档/diff 检查。用户随后授权同步 master、重打 0.1.67 并推送当前 PR 分支;不读取私钥、不上传安装包、不合并 PR。
1. 提取构建与运行共用的 Codex 平台布局;按 Cargo TARGET stage 锁定原生依赖并校验包元数据,保留可执行位。
2. 增加 macOS 专属 Tauri 资源映射、声明、产物忽略规则;复用插件 staging,不复制 Windows 原生 payload。
3. 修正 `.app/Contents/Resources` 定位与平台清单验证,保持外部安装回退。
4. 补目标布局、资源映射、缺失/篡改/平台身份、候选顺序与路径测试,运行定向门禁。
5. 构建 `.app`,在隔离目录做资源清点、原生二进制启动和 app-server 握手;生成 DMG 并校验。记录 GUI/真实 Provider 和 Cocos 未验收项。
## 命令与边界
- `cargo test --locked --manifest-path apps/ai-game-creator-shell/src-tauri/Cargo.toml agent::codex_cli::tests:: -- --test-threads=1`
- `npm run ai-game-creator-shell:typecheck`
- 定向 Node 打包契约测试、`npm run check:encoding``npm run check:doc-index``git diff --check`
- 本地 Tauri 构建关闭 updater artifact;版本按用户要求统一为 0.1.67,不读取发布私钥,不运行 release upload。
## 风险与停止条件
磁盘不足、目标包不匹配或配置测试回归时停止打包,先修正原因,不跳过验证。用户已确认 Mac 本地可用并授权提交、推送当前分支和创建草稿 PR;产物放 gitignored target,不上传发布。回滚以本次路径 diff 为边界,不恢复无关文件。保留计划等待 Windows 回归验收,证据见对应里程碑规范。
@@ -0,0 +1,42 @@
# Mac 客户端随包运行依赖补齐
- Version: 2
- Status: awaiting-windows-acceptance
- Date: 2026-09-18
- Parent Spec: `docs/technical/【技术方案】AI游戏创作智能体App实施计划-2026-06-24.md` / Runtime 边界 / 安装包侧车
## 目标与范围
产出可交给用户本地测试的 Apple Silicon DMGCodex、平台辅助组件、插件入口和面板来自安装包,不依赖仓库或全局 Codex。保持 Windows 现有路径、版本、回退和安全语义。
## 非目标与依赖
不修改 Agent Loop、公开 API、持久化数据、版本号或更新签名;远程推送与草稿 PR 已获用户确认,不发布安装包、不自动合并。Node/Cocos Creator/账号仍使用现有外部前提。Cocos macOS 原生桥接不是文件打包修复,不计为本里程碑完成能力;Intel 实机构建与 universal 不在本次交付验收内。
## 验收标准
1. 构建目标与锁定原生包匹配,缺组件或元数据错误失败关闭。
2. `.app` 内包含全部原生组件、SHA-256 清单、声明及插件清单/入口/面板;Unix 可执行位保留,不含 Windows DLL、私有配置与构建缓存。
3. 运行时先选随包文件,验证完整性和版本;覆盖缺失、篡改、平台不匹配及 macOS Resources 路径解析。
4. 脱离仓库且限制 PATH、隔离 HOME 后,真实内置 Codex app-server 完成初始化握手;不能借全局 Codex 掩盖缺包。
5. 定向 Rust 测试、配置/类型门禁、编码、文档索引和 diff 检查通过,DMG 校验通过;用户本地 GUI/登录/对话测试另行验收。
## 评审结论
2026-09-18 编码前自审:平台资源与运行时查找必须一起改;共享文件白名单避免双份清单漂移;不会复制 Windows 专属组件到 Mac;安装包结构证据和真实交互证据分开。以上范围可实施,不推进 Cocos 原生桥接下一里程碑。
## 验收现状与剩余门禁
### 评审反馈修订合同
2026-09-18 编码前自审:本轮仅修复同里程碑的目标平台传递、Cocos 能力门禁和文档冲突,不新增原生桥接或发布管线。CLI 显式目标必须覆盖环境默认,并在版本、构建、产物和清单全链路保持一致;不支持平台或渠道错配应在副作用前失败。Cocos 必须由已注册适配器决定可见/启动,覆盖无适配器、有适配器及非 Cocos 项目;前端不盲目启动隐藏插件。更新权威文档改为单架构策略,拒绝 universal,且不宣称现有发布脚本支持跨构建合并两种架构。新增回归通过后仍等待 Windows 验收;本地 0.1.67 版本修改保留,不与旧 0.1.47 安装包证据混淆。
评审修复验证:发布/feature/上传脚本测试 32 项通过,前端插件自动启动 5 项通过,Rust PluginHost 11 项与内置插件 10 项通过;Rust 使用 `TMPDIR=/private/tmp` 避免 macOS `/var` 系统链接触发既有路径安全断言。类型/配置、定向 ESLint、编码、文档索引和 diff 检查通过。测试覆盖显式目标覆盖环境、错误渠道提前拒绝、Tauri 实际注入配置、真实临时清单写入、Windows 默认 feature 保留、无 adapter 隐藏/启动拒绝、有 adapter RPC 回归。上述是自动化证据,不代表 Windows 真机、GUI 或带本次修复的新安装包已验收。
重打验证:重新 fetch/merge `origin/master` 确认当前分支已包含最新 master;按用户要求将 package、Tauri、Cargo 与锁文件版本同步到 `0.1.67`。包含上述修复的 Release `.app` 构建通过,Info.plist 实测版本 `0.1.67`、最低系统 `15.0`;隔离安装包脚本再次通过,DMG 用 hdiutil 生成并校验通过。此版本仍等待用户 GUI 与 Windows 回归,不做正式签名、公证、更新签名或产物上传。
- Mac 本地测试包已由用户确认“可以用了”;不外推为全部对话、工具和其它机器兼容性已覆盖。
- 定向 Rust 验证 14 项通过,1 项真实认证用例按原配置跳过;发布脚本测试 21 项通过;隔离 HOME/PATH 的安装包资源检查、正式 Codex 查找、app-server 握手及缺组件拒绝通过。
- 类型与配置、编码、文档索引、定向脚本 lint 和 diff 检查通过;139 MiB DMG 完整性通过。
- 随包 zsh 的原生最低系统为 macOS 15.0macOS Tauri 最低版本声明随之对齐,不能仅按主程序的 macOS 11.0 下限宣称整包兼容性。
- Windows NSIS 构建、安装、随包 Codex 与 Cocos 原有能力回归尚待用户测试;其它 Mac、Intel、正式签名/公证和更新签名未验收。保持草稿,不推进合并或发布。
@@ -12,6 +12,14 @@ Phaser `Scale.FIT` 与 `autoCenter: CENTER_BOTH` 会给 canvas 计算定位外
开发 Agent 的实际系统工程提示和 `agc-web-game-development` Skill 均包含此规则。布局修改后重新构建 dist,分别在桌面、移动与 resize 后测量 canvas 相对游戏父容器的中心误差(预期居中时不超过 1 CSS px),同时检查无溢出和意外滚动条;构建成功不等于视觉验收通过。
## 发布目标与原生能力必须贯穿完整入口
显式 `--target` 不能只改变 Tauri 命令参数;AGC 发布入口必须把同一解析结果传给版本高水位、更新端点、产物目录/后缀和清单平台键,否则 macOS 构建可能错误使用 Windows 渠道。插件文件存在也不代表 native 能力可用:Cocos 在宿主注册表缺少适配器时应隐藏并拒绝启动,前端自动启动消费后端列表投影,不能仅凭项目类型推断能力。发布策略以客户端更新权威文档为准,单架构资源不能登记成双架构产物。
## macOS 安装包小不代表运行依赖齐全
AGC 的 DMG 生成成功只证明应用可以被打包。平台专属 Codex staging、Tauri resource 映射、运行时资源目录定位和辅助组件 SHA-256 清单必须同时闭合;只配置 Windows 资源会让 Mac 开发机因全局 Codex 而掩盖缺包。macOS 使用锁定原生依赖中的 Codex、code-mode host、rg 和 zsh,不能复制 Windows EXE/DLL。用 `scripts/check-macos-bundle.mjs`(AGC 应用目录下)对复制到临时目录的 `.app` 做限制 PATH、隔离 HOME 的正式查找、app-server 握手和缺组件拒绝检查;GUI、账号、Provider 与 Cocos 原生桥接另行验收。插件 JS 入口仍依赖系统 Node,不得将“插件文件随包”表述为“无需任何外部工具链”。
## AGC 空快照测试必须等待请求完成
`waitFor(() => expect(activeTurns).toEqual([]))` 在 Hook 初始状态就能成功,不能证明首次异步读取已经完成。引用稳定性回归应显式控制 Promise 完成,并同时检查首次空响应与禁用后的引用;快照签名初值必须与初始空数组一致。窗口同步测试应验证未变化状态不重复发布,不能依赖一次多余的空态更新。
@@ -75,11 +75,11 @@
| 渠道 | 构建目标 | 清单平台键 | 更新包 | 清单地址 |
| --------- | ------------------------ | ---------------------------------------------- | ------------------------ | ------------------------------------ |
| `dev-win` | `x86_64-pc-windows-msvc` | `windows-x86_64` | NSIS `.exe` + `.exe.sig` | `<OSS base>/agc/dev-win/latest.json` |
| `dev-mac` | `universal-apple-darwin` | `darwin-aarch64` + `darwin-x86_64`(同一对象) | `*.app.tar.gz` + `.sig` | `<OSS base>/agc/dev-mac/latest.json` |
| `dev-mac` | `aarch64-apple-darwin``x86_64-apple-darwin` | 对应 `darwin-aarch64` `darwin-x86_64` | `*.app.tar.gz` + `.sig` | `<OSS base>/agc/dev-mac/latest.json` |
- 对象布局:清单固定写成 `agc/<channel>/latest.json`;安装包与签名写成 `agc/<channel>/<version>/<file>``<file>.sig`
- macOS 使用 universal 包:`dev-mac` 按 universal 目标构建(Intel 与 Apple Silicon 共用一个包),清单把同一个 `.app.tar.gz` 与同一个签名分别写入 `darwin-aarch64``darwin-x86_64`,升级后仍是 universal 包。这是 Tauri 官方发布工具对 universal 产物的既有写法
- 上一条的两个键不能合成单一 `darwin-universal` 键:更新插件按运行时实际架构解析清单键(Apple Silicon 命中 `darwin-aarch64`Intel 命中 `darwin-x86_64`),不存在自动命中 `darwin-universal` 的情形。将来真要单独发该键,必须在客户端同时设置自定义 target,否则清单里这一项永远不会被读取
- macOS 当前采用单架构包:Apple Silicon 使用 `aarch64-apple-darwin`Intel 使用 `x86_64-apple-darwin`;每次生成的清单只登记本次实际构建的架构,不把单架构原生 Codex 资源挂到另一架构。`universal-apple-darwin` 在版本读取/写入、构建和清单生成之前拒绝
- 渠道清单以实际运行架构为键。两种单架构构建不可轮流覆盖同一个 `latest.json` 并宣称双架构均可更新;当前不实现跨构建合并,Intel 发布需先完成其构建验证与多架构清单发布方案
- 构建期要求:打开 `bundle.createUpdaterArtifacts` 以生成 `.sig`;构建环境提供签名私钥与密码(私钥内容不得入库);公钥写入客户端配置。公钥在首个带更新能力的版本发布后不可更换,更换等于放弃自动更新(只能手动重装)。
- 版本递增按渠道独立进行:发布脚本读取该渠道远端 `latest.json``version`,与本地版本取较高者递增 patch;两个渠道的版本号互不影响。
- 版本高水位:发布脚本取「渠道清单版本」与「旧协议迁移指针版本」(迁移窗口内)中的较大值再递增。只看渠道清单会在渠道启用初期把版本链改小 —— 2026-09-17 首次渠道发布即把旧指针的 0.1.57 退回 0.1.48,随后以显式 0.1.60 纠偏;迁移窗口结束(旧指针 404)后自动只剩渠道清单,`dev-mac` 不参与旧指针比较。
@@ -90,6 +90,7 @@
## 构建与发布
- 发布入口:`npm run ai-game-creator-shell:release:upload`(构建 + 按渠道上传);仅构建不发布的 smoke 使用 `--no-bundle` 分支,不读远端版本、不改版本、不生成清单。
- 发布入口只解析一次目标,优先级为 CLI `--target value` / `--target=value` / `-t value``AGC_BUILD_TARGET`、Windows 默认值;重复/空目标与不支持目标失败关闭。版本高水位、构建 feature/渠道端点、bundle 路径、产物后缀、清单平台键及摘要必须消费同一个发布上下文,不能分别回读默认目标。
- 渠道由构建参数显式指定,并按目标平台校验:Windows 目标只允许 `dev-win`macOS 目标只允许 `dev-mac`;未显式指定时按目标平台取默认渠道。
- 定时调度只在本轮到达的提交包含 AGC 相关路径(客户端、共享包、`server-rs/crates`、AGC 插件、桌面壳图标、根依赖清单)时才触发渠道发布;纯文档或流水线自身的提交只跑 Full Build,不推高客户端版本号。判定失败或勾选强制触发时按"需要发布"处理。
- 更新摘要自动生成:发布脚本用渠道清单里的 `commit` 字段(上一次发布的提交)到本次提交之间、且只覆盖客户端相关路径的提交列表生成 `notes`(每条 `- 提交标题(短 SHA`,最多 12 条、主题 80 字、整体 900 字,超出折叠或截断),同时写入旧协议清单的 `releaseNotes` 和归档文件 `release-notes.txt``AGC_UPDATE_RELEASE_NOTES` 非空时以手动文案为准;无法判定起点(缺少上次 `commit` 或本地没有该提交)时不写摘要。清单缺少 `commit` 时回退用上一次成功构建的 `COMMIT_HASH`CI 通过 `AGC_UPDATE_PREVIOUS_COMMIT` 传入)作为锚点,因此首次启用摘要或更换渠道后也能立即产出摘要。锚点仍不可得(清单读取失败或没有 CI 锚点)时降级为「最近客户端改动」列表并注明可能与上一版重复 —— 摘要属于附注,任何情况下都不允许因为它让发布失败。
@@ -105,7 +106,7 @@
| 条款 | 验收方式 | 证据 |
| ---------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| 渠道与端点映射、渠道校验 | `node --test apps/ai-game-creator-shell/scripts/build-release.test.mjs` | 通过(默认渠道、错配失败关闭、未知渠道失败关闭) |
| universal 包挂两个平台键 | 同上 + 本地发布烟测(伪造 bundle) | 通过(两键同 URL 同签名,不生成迁移清单) |
| macOS 单架构清单与 universal 拒绝 | 定向发布脚本测试 | 单架构各用对应平台键;拒绝未闭合的 universal 发布 |
| 缺签名时失败关闭 | 同上 | 通过 |
| 开发态不检查更新 | `vitest run apps/ai-game-creator-shell/tests/appUpdate.test.ts` | 通过(开关关闭时不请求清单) |
| 旧自研链路整条删除 | 代码检索无残留命令、事件与白名单条目 | 通过(`download_agc_update` / 下载事件 / 清单常量均无残留) |
@@ -127,7 +128,7 @@
已决策:
- macOS 采用 universal 包,同一产物同时挂 `darwin-aarch64``darwin-x86_64` 两个清单键(见「契约与迁移」)
- macOS 采用单架构包,只登记实际构建架构;Intel 真机构建与跨架构清单合并未验收,不公开宣称双架构分发就绪
- 旧客户端迁移桥:保留一个版本周期。渠道清单上线后,发布管线同时把旧的 `agc/latest.json`sha256 格式)指向 `dev-win` 最新安装包,让已发布客户端自动升级到新协议;下个周期整条删除。
- 签名密钥:由本仓库维护者生成并保管,私钥保存在仓库外(`%USERPROFILE%\.tauri\genarrative-agc-updater.key`),只有公钥进入客户端配置;Jenkins 用受保护凭据 `AgcUpdaterSigningKey``AgcUpdaterSigningKeyPassword` 注入为 Tauri 打包器读取的 `TAURI_SIGNING_PRIVATE_KEY``TAURI_SIGNING_PRIVATE_KEY_PASSWORD`,本机可用 `TAURI_SIGNING_PRIVATE_KEY_PATH` 指向同一私钥。当前密钥不带密码;首次发布前仍可重新生成,首次发布后不可更换。
- macOS 发布方式:`dev-mac` 产物在本机 mac 上执行发布入口上传,Jenkins 暂不新增 macOS 节点;macOS 代码签名与公证凭据未确认前,相关闭环记为未验证项,不静默通过。

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