diff --git a/apps/ai-game-creator-shell/package.json b/apps/ai-game-creator-shell/package.json index c7aa09d56..50f3050c7 100644 --- a/apps/ai-game-creator-shell/package.json +++ b/apps/ai-game-creator-shell/package.json @@ -7,7 +7,8 @@ "dev": "node scripts/start-tauri-dev.mjs", "dev-server": "node scripts/start-dev-server.mjs", "dev-stack": "node scripts/start-dev-stack.mjs", - "build": "npm --prefix ../.. exec tauri -- build", + "build": "node scripts/build-release.mjs", + "release:upload": "node scripts/release-upload.mjs", "skill-pack:check": "node scripts/check-skill-pack.mjs", "skill-pack:sync": "node scripts/check-skill-pack.mjs --write", "skill-pack:test": "node --test scripts/check-skill-pack.test.mjs", diff --git a/apps/ai-game-creator-shell/scripts/build-release.mjs b/apps/ai-game-creator-shell/scripts/build-release.mjs new file mode 100644 index 000000000..03a61ba9d --- /dev/null +++ b/apps/ai-game-creator-shell/scripts/build-release.mjs @@ -0,0 +1,262 @@ +import { spawnSync } 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 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', +); +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'); +const cargoManifestPath = path.join(appRoot, 'src-tauri', 'Cargo.toml'); +const cargoLockPath = path.join(appRoot, 'src-tauri', 'Cargo.lock'); +const defaultOssBaseUrl = + 'https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc'; +const updateManifestUrl = + process.env.VITE_AGC_UPDATE_MANIFEST_URL?.trim() || + `${process.env.AGC_UPDATE_OSS_BASE_URL?.trim() || defaultOssBaseUrl}/latest.json`; + +function readPackageJson() { + return JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); +} + +export function compareVersions(left, right) { + const leftParts = left.split('.').map(Number); + const rightParts = right.split('.').map(Number); + for (let index = 0; index < 3; index += 1) { + if (leftParts[index] !== rightParts[index]) { + return leftParts[index] > rightParts[index] ? 1 : -1; + } + } + return 0; +} + +function parseVersion(value, label) { + if (typeof value !== 'string' || !/^\d+\.\d+\.\d+$/u.test(value)) { + throw new Error(`${label} 不是有效的三段版本号:${String(value)}`); + } + return value; +} + +export function nextPatchVersion(localVersion, remoteVersion) { + const local = parseVersion(localVersion, '本地版本'); + const remote = + remoteVersion == null ? null : parseVersion(remoteVersion, 'OSS版本'); + const base = remote && compareVersions(remote, local) > 0 ? remote : local; + const [major, minor, patch] = base.split('.').map(Number); + if (patch === Number.MAX_SAFE_INTEGER) { + throw new Error(`版本号 patch 已达到上限:${base}`); + } + return `${major}.${minor}.${patch + 1}`; +} + +async function readRemoteVersion() { + let response; + try { + response = await fetch(updateManifestUrl, { + headers: { Accept: 'application/json' }, + }); + } catch (error) { + throw new Error(`读取 OSS 版本清单失败:${error.message}`); + } + if (response.status === 404) return null; + if (!response.ok) { + throw new Error(`读取 OSS 版本清单失败:HTTP ${response.status}`); + } + let manifest; + try { + manifest = await response.json(); + } catch (error) { + throw new Error(`OSS 版本清单不是有效 JSON:${error.message}`); + } + return parseVersion(manifest?.version, 'OSS版本清单 version'); +} + +function replaceVersionLine(source, version, pattern, label) { + if (!pattern.test(source)) throw new Error(`未找到${label}版本字段`); + return source.replace(pattern, `$1${version}$3`); +} + +export async function prepareReleaseVersion() { + const localVersion = parseVersion(readPackageJson().version, '本地版本'); + const remoteVersion = await readRemoteVersion(); + const requestedVersion = process.env.AGC_RELEASE_VERSION?.trim(); + const nextVersion = requestedVersion + ? parseVersion(requestedVersion, '指定版本') + : nextPatchVersion(localVersion, remoteVersion); + + const packageSource = fs.readFileSync(packageJsonPath, 'utf8'); + fs.writeFileSync( + packageJsonPath, + replaceVersionLine( + packageSource, + nextVersion, + /("version"\s*:\s*")([^"]+)(")/u, + 'package.json', + ), + ); + + const rootPackageLockSource = fs.readFileSync(rootPackageLockPath, 'utf8'); + fs.writeFileSync( + rootPackageLockPath, + replaceVersionLine( + rootPackageLockSource, + nextVersion, + /("apps\/ai-game-creator-shell"\s*:\s*\{\s*\n\s*"name"\s*:\s*"@genarrative\/ai-game-creator-shell"\s*,\s*\n\s*"version"\s*:\s*")([^"]+)(")/u, + 'root package-lock.json', + ), + ); + + const tauriSource = fs.readFileSync(tauriConfigPath, 'utf8'); + fs.writeFileSync( + tauriConfigPath, + replaceVersionLine( + tauriSource, + nextVersion, + /("version"\s*:\s*")([^"]+)(")/u, + 'tauri.conf.json', + ), + ); + + const cargoSource = fs.readFileSync(cargoManifestPath, 'utf8'); + fs.writeFileSync( + cargoManifestPath, + replaceVersionLine( + cargoSource, + nextVersion, + /(^\[package\][\s\S]*?^version\s*=\s*")([^"]+)(")/mu, + 'Cargo.toml', + ), + ); + + const cargoLockSource = fs.readFileSync(cargoLockPath, 'utf8'); + fs.writeFileSync( + cargoLockPath, + replaceVersionLine( + cargoLockSource, + nextVersion, + /(^name\s*=\s*"genarrative-ai-game-creator-shell"\s*\nversion\s*=\s*")([^"]+)(")/mu, + 'Cargo.lock', + ), + ); + + console.log( + requestedVersion + ? `[ai-game-creator-shell] 使用指定版本 ${nextVersion}(本地 ${localVersion} / OSS ${remoteVersion ?? '不存在'})` + : `[ai-game-creator-shell] 版本 ${localVersion} / OSS ${remoteVersion ?? '不存在'} -> ${nextVersion}`, + ); + return nextVersion; +} + +export function runTauriBuild(args = []) { + const noBundle = args.includes('--no-bundle'); + const hasTarget = args.includes('--target'); + const targetArgs = noBundle || hasTarget ? [] : ['--target', releaseTarget]; + const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm'; + const result = spawnSync( + npmCommand, + [ + '--prefix', + '../..', + 'exec', + 'tauri', + '--', + 'build', + ...targetArgs, + ...args, + ], + { cwd: appRoot, stdio: 'inherit', shell: process.platform === 'win32' }, + ); + if (result.error) throw result.error; + if (result.status !== 0) process.exit(result.status ?? 1); +} + +function listFiles(root) { + if (!fs.existsSync(root)) return []; + return fs.readdirSync(root, { withFileTypes: true }).flatMap((entry) => { + const fullPath = path.join(root, entry.name); + return entry.isDirectory() ? listFiles(fullPath) : [fullPath]; + }); +} + +function artifactPriority(filePath) { + const name = path.basename(filePath).toLowerCase(); + if (releaseTarget.includes('windows')) return name.endsWith('.exe') ? 0 : 99; + if (process.platform === 'darwin') return name.endsWith('.dmg') ? 0 : 99; + if (name.endsWith('.appimage')) return 0; + if (name.endsWith('.deb')) return 1; + if (name.endsWith('.rpm')) return 2; + return 99; +} + +export function selectReleaseArtifact(files) { + const explicit = process.env.AGC_UPDATE_ARTIFACT?.trim(); + if (explicit) { + const resolved = path.resolve(explicit); + if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) { + throw new Error(`AGC_UPDATE_ARTIFACT 不是有效文件:${resolved}`); + } + return resolved; + } + return ( + [...files] + .filter((filePath) => artifactPriority(filePath) < 99) + .sort((left, right) => { + const priority = artifactPriority(left) - artifactPriority(right); + return priority || left.localeCompare(right); + })[0] ?? null + ); +} + +export function createUpdateManifest(artifactPath) { + const bytes = fs.readFileSync(artifactPath); + const version = readPackageJson().version; + const fileName = path.basename(artifactPath); + const baseUrl = ( + process.env.AGC_UPDATE_OSS_BASE_URL?.trim() || defaultOssBaseUrl + ).replace(/\/+$/u, ''); + const encodedFileName = encodeURIComponent(fileName).replace(/%2F/giu, '/'); + return { + version, + downloadUrl: `${baseUrl}/${encodeURIComponent(version)}/${encodedFileName}`, + sha256: createHash('sha256').update(bytes).digest('hex'), + size: bytes.length, + ...(process.env.AGC_UPDATE_RELEASE_NOTES?.trim() + ? { releaseNotes: process.env.AGC_UPDATE_RELEASE_NOTES.trim() } + : {}), + }; +} + +export function generateUpdateManifest() { + const artifact = selectReleaseArtifact(listFiles(bundleRoot)); + if (!artifact) { + throw new Error(`未找到可发布的 AGC 安装包:${bundleRoot}`); + } + const manifest = createUpdateManifest(artifact); + const manifestPath = path.join(bundleRoot, 'latest.json'); + fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + console.log(`[ai-game-creator-shell] 已生成 ${manifestPath}`); + console.log(`[ai-game-creator-shell] 安装包:${artifact}`); + return { artifact, manifestPath, manifest }; +} + +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')) generateUpdateManifest(); +} diff --git a/apps/ai-game-creator-shell/scripts/build-release.test.mjs b/apps/ai-game-creator-shell/scripts/build-release.test.mjs new file mode 100644 index 000000000..ffc8bb8b2 --- /dev/null +++ b/apps/ai-game-creator-shell/scripts/build-release.test.mjs @@ -0,0 +1,48 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { + compareVersions, + createUpdateManifest, + nextPatchVersion, + selectReleaseArtifact, +} from './build-release.mjs'; + +test('selects an explicit release artifact when configured', () => { + const artifactPath = new URL('../package.json', import.meta.url).pathname; + const previous = process.env.AGC_UPDATE_ARTIFACT; + process.env.AGC_UPDATE_ARTIFACT = artifactPath; + try { + assert.equal(selectReleaseArtifact([]), artifactPath); + } finally { + if (previous === undefined) delete process.env.AGC_UPDATE_ARTIFACT; + else process.env.AGC_UPDATE_ARTIFACT = previous; + } +}); + +test('does not select unsupported files', () => { + assert.equal( + selectReleaseArtifact(['/tmp/latest.json', '/tmp/readme.txt']), + null, + ); +}); + +test('manifest contains version, download URL and integrity fields', () => { + const manifest = createUpdateManifest( + new URL('../package.json', import.meta.url).pathname, + ); + assert.match(manifest.version, /^\d+\.\d+\.\d+$/u); + assert.match( + manifest.downloadUrl, + new RegExp(`/agc/${manifest.version}/package\\.json$`, 'u'), + ); + assert.equal(manifest.sha256.length, 64); + assert.equal(typeof manifest.size, 'number'); +}); + +test('next release version follows the higher local or OSS version', () => { + assert.equal(compareVersions('0.1.15', '0.1.12'), 1); + assert.equal(nextPatchVersion('0.1.12', '0.1.15'), '0.1.16'); + assert.equal(nextPatchVersion('0.1.18', '0.1.15'), '0.1.19'); + assert.equal(nextPatchVersion('0.1.12', null), '0.1.13'); +}); diff --git a/apps/ai-game-creator-shell/scripts/check-config.mjs b/apps/ai-game-creator-shell/scripts/check-config.mjs index 6817d69bb..65cc17b1d 100644 --- a/apps/ai-game-creator-shell/scripts/check-config.mjs +++ b/apps/ai-game-creator-shell/scripts/check-config.mjs @@ -1532,13 +1532,17 @@ if ( ); } +const releaseVersions = [ + packageConfig.version, + tauriConfig.version, + cargoPackageVersion, +]; if ( - tauriConfig.version !== '0.1.12' || - packageConfig.version !== '0.1.12' || - cargoPackageVersion !== '0.1.12' + releaseVersions.some((version) => !/^\d+\.\d+\.\d+$/u.test(version ?? '')) || + new Set(releaseVersions).size !== 1 ) { throw new Error( - 'AI game creator standard release must remain version 0.1.12', + 'AI game creator release versions must be valid three-part semver and synchronized', ); } diff --git a/apps/ai-game-creator-shell/scripts/release-upload.mjs b/apps/ai-game-creator-shell/scripts/release-upload.mjs new file mode 100644 index 000000000..e2085345a --- /dev/null +++ b/apps/ai-game-creator-shell/scripts/release-upload.mjs @@ -0,0 +1,46 @@ +import { spawnSync } from 'node:child_process'; +import path from 'node:path'; + +const bucket = process.env.AGC_OSS_BUCKET?.trim() || 'agc-dev'; +const endpoint = + process.env.AGC_OSS_ENDPOINT?.trim() || 'oss-rg-china-mainland.aliyuncs.com'; +if (!/^[a-z0-9][a-z0-9.-]{1,62}$/u.test(bucket) || /[\r\n\0]/u.test(endpoint)) { + throw new Error('OSS bucket 或 endpoint 配置无效'); +} +process.env.AGC_UPDATE_OSS_BASE_URL ||= `https://${bucket}.${endpoint}/agc`; + +const { generateUpdateManifest, prepareReleaseVersion, runTauriBuild } = + await import('./build-release.mjs'); + +function runOssutil(args) { + const binary = process.env.OSSUTIL_BIN?.trim() || 'ossutil'; + const accessKeyId = process.env.AGC_OSS_ACCESS_KEY_ID?.trim(); + const accessKeySecret = process.env.AGC_OSS_ACCESS_KEY_SECRET; + if (Boolean(accessKeyId) !== Boolean(accessKeySecret)) { + throw new Error('OSS AccessKey ID 和 Secret 必须同时提供'); + } + const credentialArgs = accessKeyId + ? ['--access-key-id', accessKeyId, '--access-key-secret', accessKeySecret] + : []; + const result = spawnSync( + binary, + [...args, '--endpoint', endpoint, ...credentialArgs], + { + stdio: 'inherit', + shell: false, + }, + ); + if (result.error) { + throw new Error(`无法执行 ${binary},请先安装并配置 ossutil`); + } + if (result.status !== 0) process.exit(result.status ?? 1); +} + +await prepareReleaseVersion(); +runTauriBuild([]); +const { artifact, manifestPath, manifest } = generateUpdateManifest(); +const artifactKey = `agc/${manifest.version}/${path.basename(artifact)}`; +runOssutil(['cp', artifact, `oss://${bucket}/${artifactKey}`]); +runOssutil(['cp', manifestPath, `oss://${bucket}/agc/latest.json`]); +console.log(`[ai-game-creator-shell] 已上传 oss://${bucket}/${artifactKey}`); +console.log(`[ai-game-creator-shell] 已上传 oss://${bucket}/agc/latest.json`); diff --git a/apps/ai-game-creator-shell/src-tauri/Cargo.lock b/apps/ai-game-creator-shell/src-tauri/Cargo.lock index a6936c44b..3215ccc82 100644 --- a/apps/ai-game-creator-shell/src-tauri/Cargo.lock +++ b/apps/ai-game-creator-shell/src-tauri/Cargo.lock @@ -1722,6 +1722,7 @@ dependencies = [ "oxc_parser", "oxc_semantic", "oxc_span", + "percent-encoding", "platform-agent", "platform-llm", "portable-pty", diff --git a/apps/ai-game-creator-shell/src-tauri/Cargo.toml b/apps/ai-game-creator-shell/src-tauri/Cargo.toml index 318951ed9..055a317d7 100644 --- a/apps/ai-game-creator-shell/src-tauri/Cargo.toml +++ b/apps/ai-game-creator-shell/src-tauri/Cargo.toml @@ -42,6 +42,7 @@ similar = "2.7" platform-llm = { path = "../../../server-rs/crates/platform-llm" } platform-agent = { path = "../../../server-rs/crates/platform-agent" } portable-pty = "0.9" +percent-encoding = "2" reqwest = { version = "0.12", default-features = false, features = ["json", "multipart", "native-tls", "stream"] } shared-contracts = { path = "../../../server-rs/crates/shared-contracts", default-features = false } tauri = { version = "2.11.2", features = [] } diff --git a/apps/ai-game-creator-shell/src-tauri/capabilities/main.json b/apps/ai-game-creator-shell/src-tauri/capabilities/main.json index 2c0510b8c..d4e2ade6a 100644 --- a/apps/ai-game-creator-shell/src-tauri/capabilities/main.json +++ b/apps/ai-game-creator-shell/src-tauri/capabilities/main.json @@ -14,6 +14,7 @@ "allow": [ { "url": "https://dev.genarrative.world/api/*" }, { "url": "https://www.genarrative.world/api/*" }, + { "url": "https://agc-dev.oss-rg-china-mainland.aliyuncs.com/*" }, { "url": "https://*/api/*" }, { "url": "http://localhost:*/*" }, { "url": "http://127.0.0.1:*/*" } diff --git a/apps/ai-game-creator-shell/src-tauri/src/main.rs b/apps/ai-game-creator-shell/src-tauri/src/main.rs index 7dfcabe02..3bd9d27c8 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/main.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/main.rs @@ -6,11 +6,13 @@ use std::fs::{File, OpenOptions}; use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write}; use std::net::{TcpListener, TcpStream}; use std::path::{Path, PathBuf}; +use std::process::Command; use std::sync::atomic::AtomicBool; use std::sync::{mpsc, Arc, Mutex, OnceLock}; use std::thread; use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use futures::StreamExt; use platform_agent::{ build_game_creation_seed_task_graph, plan_game_creation_agent_pass, route_game_creation_repair_issues, @@ -21,6 +23,7 @@ use platform_llm::{ }; use reqwest::header; use serde::{Deserialize, Serialize}; +use sha2::Digest; use shared_contracts::game_creation_app::{ new_game_creation_app_manifest, new_game_creation_app_seed_tasks, validate_game_iteration_versions, GameCreationAgentArtifactTrace, @@ -43,6 +46,182 @@ use tauri::{Emitter, Manager}; use tauri_plugin_dialog::DialogExt; use tauri_plugin_opener::OpenerExt; +const AGC_UPDATE_OSS_HOST: &str = "agc-dev.oss-rg-china-mainland.aliyuncs.com"; +const AGC_UPDATE_MAX_DOWNLOAD_BYTES: u64 = 512 * 1024 * 1024; +const AGC_UPDATE_DOWNLOAD_PROGRESS_EVENT: &str = "agc-update-download-progress"; + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct AgcUpdateDownloadProgress { + downloaded_bytes: u64, + total_bytes: Option, +} + +#[cfg(windows)] +fn launch_agc_installer(path: &Path, relaunch_path: &Path) -> Result<(), String> { + use std::os::windows::process::CommandExt; + + let executable = path.to_string_lossy().replace('\'', "''"); + let relaunch_executable = relaunch_path.to_string_lossy().replace('\'', "''"); + let script = format!( + "$ErrorActionPreference = 'Stop'; $installer = Start-Process -Verb RunAs -Wait -PassThru -FilePath '{executable}' -ArgumentList @('/S'); if ($installer.ExitCode -eq 0 -and (Test-Path -LiteralPath '{relaunch_executable}')) {{ Start-Process -FilePath '{relaunch_executable}' }}; exit $installer.ExitCode" + ); + Command::new("powershell.exe") + .args([ + "-NoProfile", + "-NonInteractive", + "-WindowStyle", + "Hidden", + "-Command", + script.as_str(), + ]) + .creation_flags(0x0800_0000) + .spawn() + .map(|_| ()) + .map_err(|error| format!("无法启动更新安装程序:{error}")) +} + +#[cfg(not(windows))] +fn launch_agc_installer(path: &Path, _relaunch_path: &Path) -> Result<(), String> { + Command::new(path) + .arg("/S") + .spawn() + .map(|_| ()) + .map_err(|error| format!("无法启动更新安装程序:{error}")) +} + +#[tauri::command] +async fn download_agc_update( + app: tauri::AppHandle, + download_url: String, + expected_sha256: Option, + expected_size: Option, +) -> Result { + let parsed = url::Url::parse(download_url.trim()).map_err(|_| "更新下载地址无效".to_string())?; + if parsed.scheme() != "https" || parsed.host_str() != Some(AGC_UPDATE_OSS_HOST) { + return Err("更新下载地址必须来自受信任的 OSS".to_string()); + } + let encoded_filename = parsed + .path_segments() + .and_then(|segments| segments.last()) + .filter(|value| !value.is_empty()) + .ok_or_else(|| "更新下载地址缺少文件名".to_string())? + .to_string(); + let filename = percent_encoding::percent_decode_str(&encoded_filename) + .decode_utf8() + .map_err(|_| "更新文件名无效".to_string())? + .into_owned(); + if filename.contains('/') || filename.contains('\\') || filename.contains("..") { + return Err("更新文件名无效".to_string()); + } + if filename.is_empty() || filename.len() > 128 { + return Err("更新文件名无效".to_string()); + } + let response = reqwest::Client::new() + .get(parsed) + .send() + .await + .map_err(|_| "下载更新失败".to_string())?; + if !response.status().is_success() { + return Err("下载更新失败".to_string()); + } + if response + .content_length() + .is_some_and(|length| length > AGC_UPDATE_MAX_DOWNLOAD_BYTES) + { + return Err("更新文件超过大小限制".to_string()); + } + let download_dir = app + .path() + .temp_dir() + .map_err(|_| "无法定位临时目录".to_string())? + .join("genarrative-agc-update"); + fs::create_dir_all(&download_dir).map_err(|_| "无法创建临时目录".to_string())?; + let target = download_dir.join(&filename); + let temporary = download_dir.join(format!( + "{}.{}.download", + filename, + uuid::Uuid::new_v4().simple() + )); + let mut file = File::create(&temporary).map_err(|_| "保存更新文件失败".to_string())?; + let mut hasher = sha2::Sha256::new(); + let total_bytes = response.content_length(); + let mut downloaded_bytes = 0_u64; + let _ = app.emit( + AGC_UPDATE_DOWNLOAD_PROGRESS_EVENT, + AgcUpdateDownloadProgress { + downloaded_bytes, + total_bytes, + }, + ); + let mut stream = response.bytes_stream(); + while let Some(chunk_result) = stream.next().await { + let chunk = match chunk_result { + Ok(chunk) => chunk, + Err(_) => { + let _ = fs::remove_file(&temporary); + return Err("读取更新文件失败".to_string()); + } + }; + downloaded_bytes = match downloaded_bytes.checked_add(chunk.len() as u64) { + Some(value) if value <= AGC_UPDATE_MAX_DOWNLOAD_BYTES => value, + _ => { + let _ = fs::remove_file(&temporary); + return Err("更新文件超过大小限制".to_string()); + } + }; + hasher.update(&chunk); + if file.write_all(&chunk).is_err() { + let _ = fs::remove_file(&temporary); + return Err("保存更新文件失败".to_string()); + } + let _ = app.emit( + AGC_UPDATE_DOWNLOAD_PROGRESS_EVENT, + AgcUpdateDownloadProgress { + downloaded_bytes, + total_bytes, + }, + ); + } + if file.flush().is_err() { + let _ = fs::remove_file(&temporary); + return Err("保存更新文件失败".to_string()); + } + drop(file); + if let Some(expected_size) = expected_size { + if downloaded_bytes != expected_size { + let _ = fs::remove_file(&temporary); + return Err("更新文件大小校验失败".to_string()); + } + } + if let Some(expected_sha256) = expected_sha256 { + let expected_sha256 = expected_sha256.trim().to_ascii_lowercase(); + if !expected_sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) + || expected_sha256.len() != 64 + { + let _ = fs::remove_file(&temporary); + return Err("更新文件摘要无效".to_string()); + } + let actual = format!("{:x}", hasher.finalize()); + if actual != expected_sha256 { + let _ = fs::remove_file(&temporary); + return Err("更新文件完整性校验失败".to_string()); + } + } + if target.exists() { + let _ = fs::remove_file(&target); + } + if let Err(error) = fs::rename(&temporary, &target) { + let _ = fs::remove_file(&temporary); + return Err(format!("提交更新文件失败:{error}")); + } + let relaunch_path = std::env::current_exe() + .map_err(|error| format!("无法定位客户端程序:{error}"))?; + launch_agc_installer(&target, &relaunch_path)?; + app.exit(0); + Ok(target.to_string_lossy().into_owned()) +} + // 调试落盘模块(保存 LLM 原始输出 / 失败输入,排查截断、空返回等)放在 debug_drafts.rs。 // 用 #[cfg] 编译期门控:仅开发(debug)且非测试构建编入;生产 release 与 cargo test 下整体剔除。 mod agent; @@ -2341,7 +2520,8 @@ fn main() { commit_local_project_asset, commit_local_project_asset_canvas_candidate, get_local_game_project_revision, - get_local_game_manifest + get_local_game_manifest, + download_agc_update, ]) .build(tauri_context); let app = match app { diff --git a/apps/ai-game-creator-shell/src-tauri/tauri.conf.json b/apps/ai-game-creator-shell/src-tauri/tauri.conf.json index 4ea2a7e05..1eb8e0319 100644 --- a/apps/ai-game-creator-shell/src-tauri/tauri.conf.json +++ b/apps/ai-game-creator-shell/src-tauri/tauri.conf.json @@ -24,8 +24,8 @@ } ], "security": { - "csp": "default-src 'self' customprotocol: asset:; img-src 'self' asset: data: blob:; media-src 'self' asset: data: blob:; connect-src 'self' http://127.0.0.1:* ws://127.0.0.1:*; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' http://127.0.0.1:*", - "devCsp": "default-src 'self' customprotocol: asset: http://127.0.0.1:*; img-src 'self' asset: http://127.0.0.1:* data: blob:; media-src 'self' asset: http://127.0.0.1:* data: blob:; connect-src 'self' http://127.0.0.1:* ws://127.0.0.1:*; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' http://127.0.0.1:*" + "csp": "default-src 'self' customprotocol: asset:; img-src 'self' asset: data: blob:; media-src 'self' asset: data: blob:; connect-src 'self' https://agc-dev.oss-rg-china-mainland.aliyuncs.com http://127.0.0.1:* ws://127.0.0.1:*; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' http://127.0.0.1:*", + "devCsp": "default-src 'self' customprotocol: asset: http://127.0.0.1:*; img-src 'self' asset: http://127.0.0.1:* data: blob:; media-src 'self' asset: http://127.0.0.1:* data: blob:; connect-src 'self' https://agc-dev.oss-rg-china-mainland.aliyuncs.com http://127.0.0.1:* ws://127.0.0.1:*; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' http://127.0.0.1:*" } }, "bundle": { diff --git a/apps/ai-game-creator-shell/src/components/AppUpdateNotice.tsx b/apps/ai-game-creator-shell/src/components/AppUpdateNotice.tsx new file mode 100644 index 000000000..7cc1c8444 --- /dev/null +++ b/apps/ai-game-creator-shell/src/components/AppUpdateNotice.tsx @@ -0,0 +1,190 @@ +import { listen } from '@tauri-apps/api/event'; +import { Download, LoaderCircle } from 'lucide-react'; +import { useEffect, useState } from 'react'; + +import { APP_VERSION } from '../app/appMetadata'; +import { + AGC_UPDATE_DOWNLOAD_PROGRESS_EVENT, + type AppUpdateInfo, + checkForAppUpdate, + downloadAppUpdate, + subscribeToAppUpdate, +} from '../services/appUpdate'; + +type DownloadProgress = { + downloadedBytes: number; + totalBytes?: number; +}; + +type DownloadState = 'idle' | 'downloading' | 'completed' | 'error'; + +function formatBytes(bytes: number) { + if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`; + return `${(bytes / 1024 / 1024).toFixed(1)} MB`; +} + +export function AppUpdateNotice() { + const [update, setUpdate] = useState(null); + const [downloadState, setDownloadState] = useState('idle'); + const [downloadProgress, setDownloadProgress] = useState({ + downloadedBytes: 0, + }); + const [downloadError, setDownloadError] = useState(''); + + useEffect(() => { + let mounted = true; + const unsubscribe = subscribeToAppUpdate((result) => { + if (mounted) setUpdate(result); + }); + void checkForAppUpdate().then((result) => { + if (mounted) setUpdate(result); + }); + return () => { + mounted = false; + unsubscribe(); + }; + }, []); + + useEffect(() => { + if (typeof window === 'undefined' || !window.__TAURI__ || !update) return; + let disposed = false; + let unlisten: (() => void) | undefined; + void listen( + AGC_UPDATE_DOWNLOAD_PROGRESS_EVENT, + (event) => { + if (!disposed) setDownloadProgress(event.payload); + }, + ).then((cleanup) => { + if (disposed) cleanup(); + else unlisten = cleanup; + }); + return () => { + disposed = true; + unlisten?.(); + }; + }, [update]); + + if (!update) return null; + const currentUpdate = update; + + const isDownloading = downloadState === 'downloading'; + const totalBytes = downloadProgress.totalBytes ?? currentUpdate.size; + const progress = totalBytes + ? Math.min( + 100, + Math.round((downloadProgress.downloadedBytes / totalBytes) * 100), + ) + : null; + + async function handleDownload() { + if (isDownloading) return; + setDownloadError(''); + setDownloadProgress({ downloadedBytes: 0, totalBytes }); + setDownloadState('downloading'); + try { + await downloadAppUpdate(currentUpdate.downloadUrl, currentUpdate); + setDownloadState('completed'); + } catch (error) { + setDownloadError(error instanceof Error ? error.message : String(error)); + setDownloadState('error'); + } + } + + function dismiss() { + if (isDownloading) return; + setUpdate(null); + setDownloadState('idle'); + } + + return ( + <> + + {downloadState !== 'idle' ? ( +
+
+ +

+ {isDownloading + ? `正在下载 ${currentUpdate.version}` + : downloadState === 'completed' + ? '下载完成' + : '下载失败'} +

+ {isDownloading ? ( + <> +
+ +
+

+ {progress === null + ? '正在获取下载进度…' + : `${progress}% · ${formatBytes(downloadProgress.downloadedBytes)} / ${formatBytes(totalBytes ?? downloadProgress.downloadedBytes)}`} +

+ 下载期间请勿关闭客户端或进行其他操作 + + ) : downloadState === 'completed' ? ( + <> +

安装程序已启动,客户端将自动完成更新。

+ + + ) : ( + <> +

{downloadError || '下载更新失败,请稍后重试。'}

+
+ + +
+ + )} +
+
+ ) : null} + + ); +} diff --git a/apps/ai-game-creator-shell/src/components/WindowChrome.tsx b/apps/ai-game-creator-shell/src/components/WindowChrome.tsx index 77c69f1a0..265de4f43 100644 --- a/apps/ai-game-creator-shell/src/components/WindowChrome.tsx +++ b/apps/ai-game-creator-shell/src/components/WindowChrome.tsx @@ -3,6 +3,7 @@ import { Copy, Minus, Square, X } from 'lucide-react'; import { type ReactNode, useCallback, useEffect, useState } from 'react'; import brandIcon from '../../../../packages/shared/src/icons/taonier-product-ip.png'; +import { AppUpdateNotice } from './AppUpdateNotice'; import { WINDOW_CHROME_DEFAULT_TITLE, WindowChromeContext, @@ -121,6 +122,7 @@ export function WindowChrome({ children }: WindowChromeProps) { return (
+
diff --git a/apps/ai-game-creator-shell/src/features/runtime-config/RuntimeConfigDialog.tsx b/apps/ai-game-creator-shell/src/features/runtime-config/RuntimeConfigDialog.tsx index 386c6d2cf..4d1a1b421 100644 --- a/apps/ai-game-creator-shell/src/features/runtime-config/RuntimeConfigDialog.tsx +++ b/apps/ai-game-creator-shell/src/features/runtime-config/RuntimeConfigDialog.tsx @@ -33,6 +33,7 @@ import { type RuntimeAgentLlmProviderPresetId, type RuntimeLlmProviderPresetId, } from '../../app/types'; +import { checkForAppUpdate } from '../../services/appUpdate'; const runtimeAgentReasoningEffortDefaults = { 'project-supervisor': 'high', @@ -383,6 +384,8 @@ export function RuntimeConfigDialog({ const [activeSection, setActiveSection] = useState('general'); const [expandedAgentIds, setExpandedAgentIds] = useState([]); + const [appUpdateStatus, setAppUpdateStatus] = useState(''); + const [appUpdateChecking, setAppUpdateChecking] = useState(false); const runtimeConfigBusyRef = useRef(false); useEscapeToClose(onClose); @@ -588,6 +591,24 @@ export function RuntimeConfigDialog({ setRuntimeConfigStatus('已恢复默认配置,保存后生效'); } + async function checkAppUpdateManually() { + if (appUpdateChecking) return; + setAppUpdateChecking(true); + setAppUpdateStatus('正在检查更新…'); + try { + const update = await checkForAppUpdate({ force: true }); + setAppUpdateStatus( + update + ? `发现新版本 v${update.version},可在右上角下载` + : '当前已是最新版本', + ); + } catch { + setAppUpdateStatus('检查更新失败,请稍后重试'); + } finally { + setAppUpdateChecking(false); + } + } + const selectedSection = runtimeSettingsSections.find((section) => section.id === activeSection) ?? runtimeSettingsSections[0]; @@ -1308,6 +1329,18 @@ export function RuntimeConfigDialog({
桌面客户端
+
+ + + {appUpdateStatus} + +
) : null}
diff --git a/apps/ai-game-creator-shell/src/services/appUpdate.ts b/apps/ai-game-creator-shell/src/services/appUpdate.ts new file mode 100644 index 000000000..f9021f3d0 --- /dev/null +++ b/apps/ai-game-creator-shell/src/services/appUpdate.ts @@ -0,0 +1,156 @@ +import { fetch as tauriHttpFetch } from '@tauri-apps/plugin-http'; +import { openUrl } from '@tauri-apps/plugin-opener'; + +import { APP_VERSION } from '../app/appMetadata'; +import { resolveTauriInvoke } from '../app/tauri'; + +/** OSS 上的 AGC 更新清单;发布时可覆盖为同一受信任 OSS 域名下的地址。 */ +export const AGC_UPDATE_MANIFEST_URL = + import.meta.env.VITE_AGC_UPDATE_MANIFEST_URL?.trim() || + 'https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/latest.json'; +export const AGC_UPDATE_DOWNLOAD_PROGRESS_EVENT = + 'agc-update-download-progress'; + +export type AppUpdateManifest = { + version: string; + downloadUrl: string; + sha256?: string; + size?: number; + releaseNotes?: string; +}; + +export type AppUpdateInfo = AppUpdateManifest & { + currentVersion: string; +}; + +let updateCheckPromise: Promise | null = null; +const updateListeners = new Set<(update: AppUpdateInfo | null) => void>(); + +function parseVersion(value: string) { + const match = value + .trim() + .replace(/^v/iu, '') + .match(/^(\d+)\.(\d+)(?:\.(\d+))?/u); + return match + ? [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)] + : null; +} + +export function isNewerVersion(candidate: string, current: string) { + const next = parseVersion(candidate); + const installed = parseVersion(current); + if (!next || !installed) return false; + for (let index = 0; index < next.length; index += 1) { + const nextValue = next[index] ?? 0; + const installedValue = installed[index] ?? 0; + if (nextValue !== installedValue) return nextValue > installedValue; + } + return false; +} + +export function parseAppUpdateManifest( + value: unknown, +): AppUpdateManifest | null { + if (!value || typeof value !== 'object') return null; + const record = value as Record; + const version = + typeof record.version === 'string' ? record.version.trim() : ''; + const downloadUrl = + typeof record.downloadUrl === 'string' ? record.downloadUrl.trim() : ''; + if (!version || !downloadUrl) return null; + try { + const url = new URL(downloadUrl); + if (url.protocol !== 'https:') return null; + } catch { + return null; + } + const sha256 = + typeof record.sha256 === 'string' + ? record.sha256.trim().toLowerCase() + : undefined; + if (sha256 && !/^[a-f0-9]{64}$/u.test(sha256)) return null; + const size = + typeof record.size === 'number' && + Number.isSafeInteger(record.size) && + record.size > 0 + ? record.size + : undefined; + const releaseNotes = + typeof record.releaseNotes === 'string' + ? record.releaseNotes.trim() + : undefined; + return { + version, + downloadUrl, + ...(sha256 ? { sha256 } : {}), + ...(size ? { size } : {}), + ...(releaseNotes ? { releaseNotes } : {}), + }; +} + +async function fetchUpdateManifest() { + const response = + typeof window !== 'undefined' && window.__TAURI__ + ? await tauriHttpFetch(AGC_UPDATE_MANIFEST_URL, { + method: 'GET', + headers: { Accept: 'application/json' }, + }) + : await fetch(AGC_UPDATE_MANIFEST_URL, { + headers: { Accept: 'application/json' }, + }); + if (!response.ok) throw new Error(`更新清单请求失败:${response.status}`); + return parseAppUpdateManifest(await response.json()); +} + +/** 同一客户端生命周期内只请求一次,避免 StrictMode 或多窗口重复检测。 */ +export function checkForAppUpdate( + options: { force?: boolean } = {}, +): Promise { + if (options.force) updateCheckPromise = null; + if (!updateCheckPromise) { + updateCheckPromise = fetchUpdateManifest() + .then((manifest) => { + const update = + manifest && isNewerVersion(manifest.version, APP_VERSION) + ? { ...manifest, currentVersion: APP_VERSION } + : null; + updateListeners.forEach((listener) => listener(update)); + return update; + }) + .catch(() => null); + } + return updateCheckPromise; +} + +export function subscribeToAppUpdate( + listener: (update: AppUpdateInfo | null) => void, +) { + updateListeners.add(listener); + return () => updateListeners.delete(listener); +} + +export async function downloadAppUpdate( + downloadUrl: string, + integrity: Pick = {}, +) { + const url = new URL(downloadUrl); + if (url.protocol !== 'https:') throw new Error('更新下载地址必须使用 HTTPS'); + if (typeof window !== 'undefined' && window.__TAURI__) { + const invoke = resolveTauriInvoke(); + if (invoke) { + return await invoke('download_agc_update', { + downloadUrl: url.toString(), + expectedSha256: integrity.sha256, + expectedSize: integrity.size, + }); + } else { + await openUrl(url.toString()); + } + return; + } + window.open(url.toString(), '_blank', 'noopener,noreferrer'); +} + +export function resetAppUpdateCheckForTests() { + updateCheckPromise = null; +} diff --git a/apps/ai-game-creator-shell/src/styles.css b/apps/ai-game-creator-shell/src/styles.css index fa409c287..6ca5b5623 100644 --- a/apps/ai-game-creator-shell/src/styles.css +++ b/apps/ai-game-creator-shell/src/styles.css @@ -22,6 +22,153 @@ body { min-height: 0; } +.app-update-notice { + position: fixed; + z-index: 40; + top: calc(var(--window-chrome-height) + 12px); + right: 16px; + display: flex; + align-items: center; + gap: 16px; + max-width: min(520px, calc(100vw - 32px)); + padding: 12px 14px; + border: 1px solid #efc9ae; + border-radius: 12px; + background: #fffaf5; + box-shadow: 0 8px 24px rgb(100 49 26 / 16%); +} + +.app-update-notice > div { + display: grid; + gap: 3px; + min-width: 0; +} +.app-update-notice strong { + color: #4a220f; + font-size: 13px; +} +.app-update-notice span, +.app-update-notice p { + margin: 0; + color: #8d6a58; + font-size: 11px; +} +.app-update-notice p { + max-width: 320px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.app-update-notice button { + flex: 0 0 auto; + padding: 7px 12px; + border: 0; + border-radius: 8px; + background: #c7653d; + color: white; + cursor: pointer; + font-size: 12px; + font-weight: 700; +} +.app-update-notice button:disabled { + cursor: wait; + opacity: 0.65; +} + +.app-update-overlay { + position: fixed; + z-index: 260; + inset: 0; + display: grid; + padding: 24px; + background: rgb(35 20 12 / 48%); + place-items: center; + pointer-events: auto; +} + +.app-update-progress-dialog { + display: grid; + width: min(420px, calc(100vw - 48px)); + gap: 12px; + padding: 28px; + border: 1px solid #efc9ae; + border-radius: 18px; + background: #fffaf5; + box-shadow: 0 20px 60px rgb(38 18 8 / 28%); + color: #4a220f; + text-align: center; +} + +.app-update-progress-icon { + display: grid; + width: 52px; + height: 52px; + margin: 0 auto; + border-radius: 16px; + background: #f6dfd0; + color: #c7653d; + place-items: center; +} + +.app-update-progress-icon .is-spinning { + animation: app-update-spin 0.9s linear infinite; +} + +@keyframes app-update-spin { + to { + transform: rotate(360deg); + } +} + +.app-update-progress-dialog h2, +.app-update-progress-dialog p, +.app-update-progress-dialog small { + margin: 0; +} + +.app-update-progress-dialog h2 { + font-size: 18px; +} + +.app-update-progress-dialog p, +.app-update-progress-dialog small { + color: #8d6a58; + font-size: 12px; +} + +.app-update-progress-track { + height: 8px; + overflow: hidden; + border-radius: 99px; + background: #f1ded2; +} + +.app-update-progress-track span { + display: block; + height: 100%; + border-radius: inherit; + background: #c7653d; + transition: width 180ms ease; +} + +.app-update-progress-dialog button { + justify-self: center; + min-width: 96px; + padding: 8px 16px; + border: 0; + border-radius: 8px; + background: #c7653d; + color: #fff; + cursor: pointer; + font-weight: 700; +} + +.app-update-progress-actions { + display: flex; + justify-content: center; + gap: 10px; +} + :root { /* 网页内自绘标题栏占用的顶部高度;portal 到 body 的固定弹层也要从它下方开始。 */ --window-chrome-height: 50px; @@ -3361,8 +3508,8 @@ h2 { grid-template-rows: auto minmax(0, 1fr) auto; gap: 0; width: min(1080px, 100%); - height: min(760px, calc(100dvh - 48px)); - max-height: calc(100dvh - 48px); + height: min(760px, calc(100dvh - var(--window-chrome-height) - 48px)); + max-height: calc(100dvh - var(--window-chrome-height) - 48px); padding: 0; overflow: hidden; border-color: var(--platform-modal-border); @@ -3677,6 +3824,32 @@ h2 { font-weight: 800; } +.runtime-settings-about-update { + display: flex; + align-items: center; + gap: 12px; +} + +.runtime-settings-about-update button { + padding: 8px 14px; + border: 0; + border-radius: 8px; + background: var(--platform-accent); + color: #fff; + cursor: pointer; + font-weight: 700; +} + +.runtime-settings-about-update button:disabled { + cursor: wait; + opacity: 0.65; +} + +.runtime-settings-about-update span { + color: var(--platform-text-soft); + font-size: 12px; +} + .runtime-agent-list { grid-column: 1 / -1; display: grid; @@ -4446,6 +4619,7 @@ iframe.preview-frame { @media (max-width: 760px) { .settings-overlay { padding: 0; + overflow: auto; } .runtime-settings-toast { @@ -4457,8 +4631,8 @@ iframe.preview-frame { .runtime-settings-panel { width: 100%; - height: 100dvh; - max-height: 100dvh; + height: calc(100dvh - var(--window-chrome-height)); + max-height: calc(100dvh - var(--window-chrome-height)); border: 0; border-radius: 0; } diff --git a/apps/ai-game-creator-shell/tests/appUpdate.test.ts b/apps/ai-game-creator-shell/tests/appUpdate.test.ts new file mode 100644 index 000000000..1348ce9c2 --- /dev/null +++ b/apps/ai-game-creator-shell/tests/appUpdate.test.ts @@ -0,0 +1,35 @@ +import { afterEach, describe, expect, it } from 'vitest'; + +import { + isNewerVersion, + parseAppUpdateManifest, + resetAppUpdateCheckForTests, +} from '../src/services/appUpdate'; + +afterEach(() => resetAppUpdateCheckForTests()); + +describe('AGC update manifest', () => { + it('compares semantic versions and accepts v prefixes', () => { + expect(isNewerVersion('v0.1.13', '0.1.12')).toBe(true); + expect(isNewerVersion('0.1.12', '0.1.12')).toBe(false); + expect(isNewerVersion('0.1.11', '0.1.12')).toBe(false); + }); + + it('validates an OSS manifest and rejects non-HTTPS downloads', () => { + expect( + parseAppUpdateManifest({ + version: '0.1.13', + downloadUrl: 'https://oss.example/agc.exe', + }), + ).toMatchObject({ + version: '0.1.13', + downloadUrl: 'https://oss.example/agc.exe', + }); + expect( + parseAppUpdateManifest({ + version: '0.1.13', + downloadUrl: 'http://oss.example/agc.exe', + }), + ).toBeNull(); + }); +}); diff --git a/docs/README.md b/docs/README.md index 40195c0ae..50ee0717b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -20,6 +20,7 @@ ## AI 游戏创作与 Agent Runtime - [AI 游戏创作智能体 App 实施计划](./technical/【技术方案】AI游戏创作智能体App实施计划-2026-06-24.md):当前 DirectProject、受控语义工具、UI workflow、资源和运行时合同。 +- [AGC 客户端更新检查与下载](./technical/【技术方案】AGC客户端更新检查与下载-2026-08-31.md):启动版本检测、OSS 清单格式和下载约定。 - [DirectProject 本轮附件路径映射](./technical/【技术方案】DirectProject本轮附件路径映射-2026-08-31.md):Direct 首轮只映射附件原名与项目相对路径,不灌正文、不区别 GDD。 - [Direct 回合行为审计账本](./technical/【技术方案】Direct回合行为审计账本-2026-08-31.md):Direct GUI 回合把 native 读 / MCP / 写文件落成项目内有界时间线,用于判断有没有打开本轮附件。 - [项目开发工作台 PRD](./prd/【AI游戏创作】项目开发工作台PRD-2026-07-20.md):当前工作台页面和验收边界。 diff --git a/docs/technical/【技术方案】AGC客户端更新检查与下载-2026-08-31.md b/docs/technical/【技术方案】AGC客户端更新检查与下载-2026-08-31.md new file mode 100644 index 000000000..0221e9304 --- /dev/null +++ b/docs/technical/【技术方案】AGC客户端更新检查与下载-2026-08-31.md @@ -0,0 +1,63 @@ +# AGC 客户端更新检查与下载 + +## 交付范围 + +AGC 每次启动时由根窗口检查一次公开 OSS 更新清单。清单默认位于 +`https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/latest.json`,构建时可用 +`VITE_AGC_UPDATE_MANIFEST_URL` 覆盖为同一受信任 OSS 域名下的 HTTPS 地址。客户端版本取 +`apps/ai-game-creator-shell/package.json`,通过 `version` 与清单版本比较;只有远端版本更高时显示更新提示。 + +清单格式: + +```json +{ + "version": "0.1.13", + "downloadUrl": "https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/0.1.13/Genarrative-AI-Game-Creator.exe", + "sha256": "<64位十六进制摘要>", + "size": 123456789, + "releaseNotes": "修复与改进" +} +``` + +`downloadUrl` 必须是 HTTPS;如提供 `sha256` / `size`,Tauri 下载时会校验摘要和字节数。点击“下载更新”后,客户端将安装包流式写入系统临时目录并显示进度,校验成功后通过 Windows UAC 提权启动 NSIS 静默安装并退出旧客户端。 + +## 启动与失败策略 + +- 检查挂在 `WindowChrome` 根组件,覆盖首页、工作台和调试窗口;网络错误、格式错误或版本不高于当前版本均静默忽略,不阻塞客户端启动。 +- 更新请求使用单例 Promise,React StrictMode 或同一窗口重复挂载不会重复请求。 +- Tauri HTTP capability 与 CSP 仅放行默认 OSS 域名;若更换域名,需同步更新 `capabilities/main.json`、`tauri.conf.json` 和发布环境配置。 + +## 发布约定 + +当前发布目标固定为 Windows x64 NSIS。执行 `npm run ai-game-creator-shell:build` 会先读取 +`VITE_AGC_UPDATE_MANIFEST_URL`(默认 `https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/latest.json`)的 +`latest.json`,取本地与 OSS 的较高版本并递增一个 patch,然后同步更新 package、Tauri 和 Cargo +版本后再向 Tauri 传入 `--target x86_64-pc-windows-msvc` 构建。OSS 清单首次不存在时按本地版本递增; +OSS 请求失败、清单格式错误或版本无效会终止发布,避免覆盖线上版本。构建完成后自动扫描 `.exe` +安装包,并在 `apps/ai-game-creator-shell/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/latest.json` +生成包含版本、下载地址、大小和 SHA-256 的清单。可通过 `AGC_BUILD_TARGET` 显式覆盖目标(发布仍应使用 +Windows x64),通过 `AGC_UPDATE_ARTIFACT` 指定要发布的安装包,通过 `AGC_UPDATE_OSS_BASE_URL` 指定 +OSS 前缀,通过 `AGC_RELEASE_VERSION` 指定三段版本号(仅在明确需要复现指定版本时使用),通过 +`AGC_UPDATE_RELEASE_NOTES` 写入发布说明;`--no-bundle` smoke 构建不会读取 OSS、修改版本或生成清单。 + +每次发布安装包上传完成后,再上传同一目录生成的 `latest.json`,确保 `downloadUrl` 指向已存在的 OSS 对象;清单和安装包均使用公开可读对象,不在清单中保存凭据、签名或本地路径。构建脚本本身不负责上传 OSS,发布流水线通过 `release:upload` 完成上传。 + +如需一键构建并上传,可执行 `npm run ai-game-creator-shell:release:upload`。该命令要求本机已安装并配置 `ossutil`, +先按上述规则比较 OSS 版本、递增 patch、构建 Windows x64 NSIS,再上传安装包和 `latest.json`。默认上传到 +`agc-dev` / `oss-rg-china-mainland.aliyuncs.com`,也可用 `AGC_OSS_BUCKET`、`AGC_OSS_ENDPOINT` 和 `OSSUTIL_BIN` +覆盖;本机执行时凭据由 ossutil 本机配置读取,不能写入仓库或命令行参数。 + +## Jenkins Windows 构建节点 + +AGC 发布流水线使用 `jenkins/Jenkinsfile.ai-game-creator-shell-build`,当前节点标签为 +`windows && win2022`。节点应为 Windows Server 2022 x64 虚拟机,预装 Node.js 22、npm +10.9.7、Rust 1.96.0、Visual Studio Build Tools(MSVC 与 Windows SDK)、NSIS、Git 和 ossutil; +Jenkins Agent 服务必须能在同一用户环境中找到这些命令。流水线执行根 workspace 的 `npm ci`,然后调用 +`npm run ai-game-creator-shell:release:upload`,并归档 Windows 安装包、`latest.json` 与源码 commit。 + +Jenkins Job 在“Build and upload”阶段通过受保护凭据 ID `AliyunAccessKeyId` 和 +`AliyunaccessKeySecret` 注入 AccessKey,仅在当前进程运行时传给 ossutil,不写入仓库、workspace 或构建日志; +本机运行仍使用 ossutil 配置。凭据必须具备 `PutObject` 权限;OSS 对客户端保持公共读即可,公共读本身不授予 +Jenkins 上传权限。由于版本号取决于 OSS 当前清单,Job 已关闭并发构建;若 Jenkins +上存在多个 AGC 发布 Job,还应使用同一个 Lockable Resource 串行化发布。Job 参数 +`AGC_RELEASE_VERSION` 留空时自动递增,填写后会使用指定版本并更新对应的 `latest.json`,因此回滚或测试旧版本前应确认不会覆盖线上更新入口。 diff --git a/jenkins/Jenkinsfile.ai-game-creator-shell-build b/jenkins/Jenkinsfile.ai-game-creator-shell-build new file mode 100644 index 000000000..e541f2abe --- /dev/null +++ b/jenkins/Jenkinsfile.ai-game-creator-shell-build @@ -0,0 +1,147 @@ +pipeline { + agent { + label 'windows && win2022' + } + + options { + disableConcurrentBuilds() + skipDefaultCheckout(true) + buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '20')) + } + + environment { + GIT_REMOTE_URL = 'ssh://git@192.168.35.82:2222/GenarrativeAI/Genarrative.git' + GIT_REMOTE_CREDENTIAL_ID = 'genarrative-local-gitea-ssh' + GENARRATIVE_NPM_VERSION = '10.9.7' + AGC_OSS_BUCKET = 'agc-dev' + AGC_OSS_ENDPOINT = 'oss-rg-china-mainland.aliyuncs.com' + AGC_WINDOWS_PATH = 'C:\\Tools\\Git\\cmd;C:\\Program Files\\nodejs;C:\\Users\\Administrator\\.cargo\\bin;C:\\Program Files (x86)\\NSIS;C:\\Tools\\ossutil;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\' + } + + parameters { + string(name: 'SOURCE_BRANCH', defaultValue: 'master', description: '源码分支') + string(name: 'COMMIT_HASH', defaultValue: '', description: '可选,指定属于 SOURCE_BRANCH 的 Git commit') + string(name: 'AGC_RELEASE_VERSION', defaultValue: '', description: '可选,指定三段版本号;留空则按 OSS 与本地版本自动递增 patch') + string(name: 'AGC_UPDATE_RELEASE_NOTES', defaultValue: '', description: '可选,写入 latest.json 的发布说明') + string(name: 'OSSUTIL_BIN', defaultValue: 'ossutil', description: 'ossutil 或 ossutil.exe 的绝对路径/命令名') + } + + stages { + stage('Checkout') { + steps { + withCredentials([sshUserPrivateKey(credentialsId: env.GIT_REMOTE_CREDENTIAL_ID, keyFileVariable: 'GIT_SSH_KEY', usernameVariable: 'GIT_SSH_USER')]) { + powershell ''' + $ErrorActionPreference = 'Stop' + $env:GIT_SSH_COMMAND = "ssh -i `"$env:GIT_SSH_KEY`" -o StrictHostKeyChecking=no" + $git = 'C:\\Tools\\Git\\cmd\\git.exe' + if (-not (Test-Path $git)) { throw "找不到 Git: $git" } + if (Test-Path '.git') { + & $git fetch --tags --force --prune origin "+refs/heads/$($env:SOURCE_BRANCH):refs/remotes/origin/$($env:SOURCE_BRANCH)" + if ($LASTEXITCODE -ne 0) { throw 'Git fetch 失败' } + & $git clean -fdx + & $git reset --hard "origin/$($env:SOURCE_BRANCH)" + } else { + & $git clone --no-single-branch $env:GIT_REMOTE_URL . + if ($LASTEXITCODE -ne 0) { throw 'Git clone 失败' } + & $git fetch --tags --force origin "refs/heads/$($env:SOURCE_BRANCH):refs/remotes/origin/$($env:SOURCE_BRANCH)" + if ($LASTEXITCODE -ne 0) { throw 'Git fetch 分支失败' } + & $git checkout --detach "origin/$($env:SOURCE_BRANCH)" + } + $commit = $env:COMMIT_HASH.Trim() + if ($commit) { + if ($commit -notmatch '^[0-9a-fA-F]{7,64}$') { + throw 'COMMIT_HASH 必须是 7-64 位十六进制 Git commit。' + } + & $git cat-file -e "${commit}^{commit}" + if ($LASTEXITCODE -ne 0) { + throw "COMMIT_HASH 不存在: $commit" + } + $branchRef = "refs/remotes/origin/$($env:SOURCE_BRANCH)" + & $git merge-base --is-ancestor $commit $branchRef + if ($LASTEXITCODE -ne 0) { + throw "COMMIT_HASH 不属于 SOURCE_BRANCH: $($env:SOURCE_BRANCH)" + } + & $git checkout --detach $commit + } + $resolved = (& $git rev-parse HEAD).Trim() + Set-Content -Path '.jenkins-source-commit' -Value $resolved -NoNewline + Write-Host "源码 commit=$resolved" + ''' + } + } + } + + stage('Toolchain preflight') { + steps { + withEnv(["PATH=${env.AGC_WINDOWS_PATH}", "OSSUTIL_BIN=${params.OSSUTIL_BIN}"]) { + powershell ''' + $ErrorActionPreference = 'Stop' + $actualNpm = (npm --version).Trim() + if ($actualNpm -ne $env:GENARRATIVE_NPM_VERSION) { + throw "npm 版本不匹配:期望 $($env:GENARRATIVE_NPM_VERSION),实际 $actualNpm" + } + foreach ($commandName in @('node', 'npm', 'rustc', 'cargo', 'makensis')) { + if (-not (Get-Command $commandName -ErrorAction SilentlyContinue)) { + throw "Windows AGC 节点缺少 $commandName,请先安装并加入 Jenkins Agent PATH。" + } + } + $ossutil = $env:OSSUTIL_BIN.Trim() + if (-not $ossutil) { $ossutil = 'ossutil' } + if (-not (Get-Command $ossutil -ErrorAction SilentlyContinue)) { + throw "Windows AGC 节点缺少 ossutil:$ossutil" + } + Write-Host "node=$((node --version).Trim())" + Write-Host "npm=$actualNpm" + Write-Host "rustc=$((rustc --version).Trim())" + Write-Host "cargo=$((cargo --version).Trim())" + Write-Host "makensis=$((makensis -VERSION | Select-Object -First 1).Trim())" + ''' + } + } + } + + stage('Install dependencies') { + steps { + withEnv(["PATH=${env.AGC_WINDOWS_PATH}"]) { + powershell ''' + $ErrorActionPreference = 'Stop' + npm ci --no-audit --no-fund + ''' + } + } + } + + stage('Build and upload') { + steps { + withCredentials([ + string(credentialsId: 'AliyunAccessKeyId', variable: 'AGC_OSS_ACCESS_KEY_ID'), + string(credentialsId: 'AliyunaccessKeySecret', variable: 'AGC_OSS_ACCESS_KEY_SECRET'), + ]) { + withEnv([ + "PATH=${env.AGC_WINDOWS_PATH}", + "OSSUTIL_BIN=${params.OSSUTIL_BIN}", + "AGC_RELEASE_VERSION=${params.AGC_RELEASE_VERSION}", + "AGC_UPDATE_RELEASE_NOTES=${params.AGC_UPDATE_RELEASE_NOTES}", + ]) { + powershell ''' + $ErrorActionPreference = 'Stop' + npm run ai-game-creator-shell:release:upload + ''' + } + } + } + } + + stage('Archive release') { + steps { + archiveArtifacts artifacts: 'apps/ai-game-creator-shell/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/**/*.exe,apps/ai-game-creator-shell/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/latest.json,.jenkins-source-commit', fingerprint: true + } + } + } + + post { + success { + echo 'AGC Windows x64 安装包已构建并上传 OSS。' + } + } +} diff --git a/package.json b/package.json index 5c488bbfa..80aa34e94 100644 --- a/package.json +++ b/package.json @@ -171,6 +171,7 @@ "ai-game-creator-shell:dev": "npm --prefix apps/ai-game-creator-shell run dev", "ai-game-creator-shell:dev-server": "npm --prefix apps/ai-game-creator-shell run dev-server", "ai-game-creator-shell:build": "npm --prefix apps/ai-game-creator-shell run build --", + "ai-game-creator-shell:release:upload": "npm --prefix apps/ai-game-creator-shell run release:upload", "ai-game-creator-shell:llm-status": "npm --prefix apps/ai-game-creator-shell run llm-status --", "ai-game-creator-shell:agent-task": "npm --prefix apps/ai-game-creator-shell run agent-task --", "agc:chat": "npm --prefix apps/ai-game-creator-shell run chat --", diff --git a/scripts/check-npm-workspaces.mjs b/scripts/check-npm-workspaces.mjs index 0c55b3b53..09bee0f04 100644 --- a/scripts/check-npm-workspaces.mjs +++ b/scripts/check-npm-workspaces.mjs @@ -173,12 +173,14 @@ export function collectNpmWorkspaceErrors(rootDir) { `${manifestPath}: name must be ${WORKSPACE_NAMES[workspacePath]}, received ${String(manifest.name)}`, ); } - const expectedWorkspaceVersion = - workspacePath === 'apps/ai-game-creator-shell' ? '0.1.12' : '0.1.0'; - if (manifest.version !== expectedWorkspaceVersion) { - errors.push( - `${manifestPath}: workspace version must be ${expectedWorkspaceVersion}`, - ); + if (workspacePath === 'apps/ai-game-creator-shell') { + if (!/^\d+\.\d+\.\d+$/u.test(manifest.version ?? '')) { + errors.push( + `${manifestPath}: workspace version must be a three-part semver`, + ); + } + } else if (manifest.version !== '0.1.0') { + errors.push(`${manifestPath}: workspace version must be 0.1.0`); } for (const nestedLockfile of findNestedLockfiles(rootDir, workspacePath)) {