From a5fd25f10a30912d26dcaa02d02ac4e65c8407ab Mon Sep 17 00:00:00 2001 From: kdletters <61648117+kdletters@users.noreply.github.com> Date: Thu, 17 Sep 2026 17:51:53 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=A2=E6=88=B7=E7=AB=AF=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E5=88=87=E6=8D=A2=E5=88=B0=E5=AE=98=E6=96=B9=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E6=8F=92=E4=BB=B6=E5=B9=B6=E6=8C=89=E6=B8=A0=E9=81=93=E5=88=86?= =?UTF-8?q?=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 客户端接入 tauri-plugin-updater:原生侧注册插件,删除自研更新下载命令、下载进度事件与安装器启动逻辑 - 客户端更新服务与更新提示改走官方插件接口,删除自研清单解析、版本比较与下载实现 - 更新能力只授予客户端主窗口,移除只为自研清单放行的 OSS 白名单与 CSP 连接项 - 新增构建期更新检查开关:开发态默认关闭,agc 启动不请求更新清单、不显示更新入口 - 发布脚本按渠道生成官方更新插件清单与签名,universal macOS 产物同时挂两个平台键,缺签名失败关闭 - 发布脚本按渠道上传安装包、签名与渠道清单,并为 dev-win 生成旧协议 sha256 迁移清单 - 构建期按渠道注入更新端点配置,渠道与目标平台不匹配时发布失败关闭 - Jenkins 流水线新增渠道参数与签名凭据注入,归档补充签名与迁移清单 - 新增发布上传 dry-run 开关,只打印 ossutil 命令且不回显凭据 - 更新技术方案与开发运维文档,登记 macOS 渠道落地待办 --- apps/ai-game-creator-shell/package.json | 1 + .../scripts/build-release.mjs | 244 ++++++++++++++--- .../scripts/build-release.test.mjs | 177 ++++++++++--- .../scripts/dev-feature-flags.mjs | 20 ++ .../scripts/release-oss.mjs | 27 ++ .../scripts/release-oss.test.mjs | 44 +++ .../scripts/release-upload.mjs | 52 +++- .../scripts/start-dev-server.mjs | 3 +- .../scripts/start-dev-stack.mjs | 6 +- .../src-tauri/Cargo.lock | 250 +++++++++++++++++- .../src-tauri/Cargo.toml | 2 +- .../src-tauri/capabilities/main.json | 2 +- .../src-tauri/src/main.rs | 232 +--------------- .../src-tauri/tauri.conf.json | 16 +- .../src/app/featureFlags.ts | 32 +++ .../src/components/AppUpdateNotice.tsx | 40 +-- .../src/components/WindowChrome.tsx | 3 +- .../runtime-config/RuntimeConfigDialog.tsx | 27 +- .../src/services/appUpdate.ts | 185 +++++-------- .../tests/appUpdate.test.ts | 164 +++++++++--- .../tests/dev-feature-flags.test.ts | 24 ++ .../tests/featureFlags.test.ts | 23 ++ ...】AGC客户端更新切换到官方更新插件-2026-09-17.md | 37 +++ ...施计划】AGC更新发布管线渠道化-2026-09-17.md | 37 +++ ...里程碑】AGC macOS渠道更新落地-2026-09-17.md | 46 ++++ ...AGC客户端更新切换到官方更新插件-2026-09-17.md | 45 ++++ ...里程碑】AGC更新发布管线渠道化-2026-09-17.md | 47 ++++ ...方案】AGC客户端更新检查与下载-2026-08-31.md | 159 +++++++---- ...发运维】本地开发验证与生产运维-2026-05-15.md | 2 +- .../Jenkinsfile.ai-game-creator-shell-build | 12 +- package-lock.json | 19 ++ 31 files changed, 1411 insertions(+), 567 deletions(-) create mode 100644 apps/ai-game-creator-shell/scripts/dev-feature-flags.mjs create mode 100644 apps/ai-game-creator-shell/scripts/release-oss.mjs create mode 100644 apps/ai-game-creator-shell/scripts/release-oss.test.mjs create mode 100644 apps/ai-game-creator-shell/src/app/featureFlags.ts create mode 100644 apps/ai-game-creator-shell/tests/dev-feature-flags.test.ts create mode 100644 apps/ai-game-creator-shell/tests/featureFlags.test.ts create mode 100644 docs/project-memory/plans/【实施计划】AGC客户端更新切换到官方更新插件-2026-09-17.md create mode 100644 docs/project-memory/plans/【实施计划】AGC更新发布管线渠道化-2026-09-17.md create mode 100644 docs/project-memory/plans/【里程碑】AGC macOS渠道更新落地-2026-09-17.md create mode 100644 docs/project-memory/plans/【里程碑】AGC客户端更新切换到官方更新插件-2026-09-17.md create mode 100644 docs/project-memory/plans/【里程碑】AGC更新发布管线渠道化-2026-09-17.md diff --git a/apps/ai-game-creator-shell/package.json b/apps/ai-game-creator-shell/package.json index fcaf78727..442b1342e 100644 --- a/apps/ai-game-creator-shell/package.json +++ b/apps/ai-game-creator-shell/package.json @@ -47,6 +47,7 @@ "@tauri-apps/plugin-dialog": "^2.7.2", "@tauri-apps/plugin-http": "^2.5.9", "@tauri-apps/plugin-opener": "~2", + "@tauri-apps/plugin-updater": "2.11.0", "@vitejs/plugin-react": "^5.0.4", "focus-trap-react": "^12.0.3", "lexical": "^0.47.0", diff --git a/apps/ai-game-creator-shell/scripts/build-release.mjs b/apps/ai-game-creator-shell/scripts/build-release.mjs index e5f153b68..2bfce8d02 100644 --- a/apps/ai-game-creator-shell/scripts/build-release.mjs +++ b/apps/ai-game-creator-shell/scripts/build-release.mjs @@ -1,6 +1,7 @@ import { 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'; import { fileURLToPath } from 'node:url'; @@ -28,14 +29,30 @@ 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`; + +/** + * 发布渠道 → 目标平台。渠道名会进入 OSS 路径并烘焙进客户端端点, + * 一旦发布就不能改名(改名等于已发布客户端再也找不到更新)。 + */ +const releaseChannels = { + 'dev-win': 'windows', + 'dev-mac': 'darwin', +}; + +function ossBaseUrl() { + return ( + process.env.AGC_UPDATE_OSS_BASE_URL?.trim() || defaultOssBaseUrl + ).replace(/\/+$/u, ''); +} function readPackageJson() { return JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); } +function readReleaseNotes() { + return process.env.AGC_UPDATE_RELEASE_NOTES?.trim() || ''; +} + export function compareVersions(left, right) { const leftParts = left.split('.').map(Number); const rightParts = right.split('.').map(Number); @@ -66,26 +83,87 @@ export function nextPatchVersion(localVersion, remoteVersion) { return `${major}.${minor}.${patch + 1}`; } -async function readRemoteVersion() { +export function resolveReleasePlatform(target = releaseTarget) { + if (target.includes('windows')) return 'windows'; + if (target.includes('apple-darwin')) return 'darwin'; + if (target.includes('linux')) return 'linux'; + throw new Error(`不支持的发布目标:${target}`); +} + +export function resolveReleaseChannel( + env = process.env, + target = releaseTarget, +) { + const platform = resolveReleasePlatform(target); + const requested = env.AGC_UPDATE_CHANNEL?.trim(); + if (requested) { + const channelPlatform = releaseChannels[requested]; + if (!channelPlatform) { + throw new Error( + `未知发布渠道 ${requested};当前支持:${Object.keys(releaseChannels).join('、')}`, + ); + } + if (channelPlatform !== platform) { + throw new Error( + `渠道 ${requested} 只能用于 ${channelPlatform} 目标,当前构建目标为 ${target}`, + ); + } + return requested; + } + const defaultChannel = Object.entries(releaseChannels).find( + ([, channelPlatform]) => channelPlatform === platform, + )?.[0]; + if (!defaultChannel) { + throw new Error( + `目标 ${target} 没有默认发布渠道,请显式设置 AGC_UPDATE_CHANNEL`, + ); + } + return defaultChannel; +} + +export function updateManifestUrl(channel = resolveReleaseChannel()) { + return `${ossBaseUrl()}/${channel}/latest.json`; +} + +/** + * 更新插件按运行时平台键查找清单条目:universal macOS 包同时挂 + * `darwin-aarch64` 与 `darwin-x86_64`,单架构目标只挂对应键。 + */ +export function resolveManifestPlatformKeys(target = releaseTarget) { + if (target === 'universal-apple-darwin') { + return ['darwin-aarch64', 'darwin-x86_64']; + } + if (target === 'aarch64-apple-darwin') return ['darwin-aarch64']; + if (target === 'x86_64-apple-darwin') return ['darwin-x86_64']; + if (target.includes('windows')) { + return [ + target.startsWith('aarch64') ? 'windows-aarch64' : 'windows-x86_64', + ]; + } + throw new Error(`不支持的发布目标:${target}`); +} + +async function readRemoteVersion(channel = resolveReleaseChannel()) { + const manifestUrl = updateManifestUrl(channel); let response; try { - response = await fetch(updateManifestUrl, { + response = await fetch(manifestUrl, { headers: { Accept: 'application/json' }, }); } catch (error) { - throw new Error(`读取 OSS 版本清单失败:${error.message}`); + throw new Error(`读取 OSS 渠道清单失败:${error.message}`); } if (response.status === 404) return null; if (!response.ok) { - throw new Error(`读取 OSS 版本清单失败:HTTP ${response.status}`); + throw new Error(`读取 OSS 渠道清单失败:HTTP ${response.status}`); } let manifest; try { manifest = await response.json(); } catch (error) { - throw new Error(`OSS 版本清单不是有效 JSON:${error.message}`); + throw new Error(`OSS 渠道清单不是有效 JSON:${error.message}`); } - return parseVersion(manifest?.version, 'OSS版本清单 version'); + return parseVersion(manifest?.version, 'OSS渠道清单 version'); } function replaceVersionLine(source, version, pattern, label) { @@ -94,8 +172,9 @@ function replaceVersionLine(source, version, pattern, label) { } export async function prepareReleaseVersion() { + const channel = resolveReleaseChannel(); const localVersion = parseVersion(readPackageJson().version, '本地版本'); - const remoteVersion = await readRemoteVersion(); + const remoteVersion = await readRemoteVersion(channel); const requestedVersion = process.env.AGC_RELEASE_VERSION?.trim(); const nextVersion = requestedVersion ? parseVersion(requestedVersion, '指定版本') @@ -158,8 +237,8 @@ export async function prepareReleaseVersion() { console.log( requestedVersion - ? `[ai-game-creator-shell] 使用指定版本 ${nextVersion}(本地 ${localVersion} / OSS ${remoteVersion ?? '不存在'})` - : `[ai-game-creator-shell] 版本 ${localVersion} / OSS ${remoteVersion ?? '不存在'} -> ${nextVersion}`, + ? `[ai-game-creator-shell] 渠道 ${channel} 使用指定版本 ${nextVersion}(本地 ${localVersion} / OSS ${remoteVersion ?? '不存在'})` + : `[ai-game-creator-shell] 渠道 ${channel} 版本 ${localVersion} / OSS ${remoteVersion ?? '不存在'} -> ${nextVersion}`, ); return nextVersion; } @@ -187,18 +266,43 @@ export function buildTauriBuildArguments( ]; } +/** 渠道端点必须由构建期注入:官方更新插件的端点配置不支持运行期改渠道。 */ +export function createChannelConfig(channel = resolveReleaseChannel()) { + return { + plugins: { + updater: { + endpoints: [updateManifestUrl(channel)], + }, + }, + }; +} + +function writeChannelConfigFile(channel) { + const configPath = path.join( + os.tmpdir(), + `agc-tauri-channel-${channel}.json`, + ); + fs.writeFileSync( + configPath, + `${JSON.stringify(createChannelConfig(channel), null, 2)}\n`, + ); + 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); + } const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm'; const result = spawnSync( npmCommand, - [ - '--prefix', - '../..', - 'exec', - 'tauri', - '--', - ...buildTauriBuildArguments(args), - ], + ['--prefix', '../..', 'exec', 'tauri', '--', ...tauriArguments], { cwd: appRoot, stdio: 'inherit', shell: process.platform === 'win32' }, ); if (result.error) throw result.error; @@ -216,10 +320,14 @@ function listFiles(root) { 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; + // 更新链路要的是 updater 产物(macOS 为 .app.tar.gz),dmg 只作人工分发。 + if (releaseTarget.includes('apple-darwin')) { + return name.endsWith('.app.tar.gz') ? 0 : 99; + } + if (name.endsWith('.appimage.tar.gz')) return 0; + if (name.endsWith('.appimage')) return 1; + if (name.endsWith('.deb')) return 2; + if (name.endsWith('.rpm')) return 3; return 99; } @@ -242,36 +350,100 @@ export function selectReleaseArtifact(files) { ); } -export function createUpdateManifest(artifactPath) { +function readUpdaterSignature(artifactPath) { + const signaturePath = `${artifactPath}.sig`; + if (!fs.existsSync(signaturePath)) { + throw new Error( + `缺少更新包签名:${signaturePath};需要 bundle.createUpdaterArtifacts 与签名私钥(TAURI_SIGNING_PRIVATE_KEY / TAURI_SIGNING_PRIVATE_KEY_PATH)`, + ); + } + const signature = fs.readFileSync(signaturePath, 'utf8').trim(); + if (!signature) throw new Error(`更新包签名为空:${signaturePath}`); + return signature; +} + +export function createUpdateManifest( + artifactPath, + { + channel = resolveReleaseChannel(), + target = releaseTarget, + publishedAt = new Date().toISOString(), + } = {}, +) { + const signature = readUpdaterSignature(artifactPath); + const version = readPackageJson().version; + const fileName = path.basename(artifactPath); + const url = `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(fileName)}`; + const platforms = {}; + for (const key of resolveManifestPlatformKeys(target)) { + platforms[key] = { signature, url }; + } + const notes = readReleaseNotes(); + return { + version, + ...(notes ? { notes } : {}), + pub_date: publishedAt, + platforms, + }; +} + +/** 旧协议(sha256)清单:只用于把已发布客户端带到新渠道协议,一个版本周期后整条删除。 */ +export function createLegacyUpdateManifest( + artifactPath, + { channel = resolveReleaseChannel() } = {}, +) { 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, '/'); + const notes = readReleaseNotes(); return { version, - downloadUrl: `${baseUrl}/${encodeURIComponent(version)}/${encodedFileName}`, + downloadUrl: `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(fileName)}`, 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() } - : {}), + ...(notes ? { releaseNotes: notes } : {}), }; } export function generateUpdateManifest() { + const channel = resolveReleaseChannel(); const artifact = selectReleaseArtifact(listFiles(bundleRoot)); if (!artifact) { throw new Error(`未找到可发布的 AGC 安装包:${bundleRoot}`); } - const manifest = createUpdateManifest(artifact); + const manifest = createUpdateManifest(artifact, { channel }); const manifestPath = path.join(bundleRoot, 'latest.json'); fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); - console.log(`[ai-game-creator-shell] 已生成 ${manifestPath}`); + const legacyManifest = + channel === 'dev-win' + ? createLegacyUpdateManifest(artifact, { channel }) + : null; + const legacyManifestPath = legacyManifest + ? path.join(bundleRoot, 'legacy-latest.json') + : null; + if (legacyManifest && legacyManifestPath) { + fs.writeFileSync( + legacyManifestPath, + `${JSON.stringify(legacyManifest, null, 2)}\n`, + ); + } + console.log( + `[ai-game-creator-shell] 渠道 ${channel}:已生成 ${manifestPath}`, + ); console.log(`[ai-game-creator-shell] 安装包:${artifact}`); - return { artifact, manifestPath, manifest }; + if (legacyManifestPath) { + console.log( + `[ai-game-creator-shell] 旧协议迁移清单:${legacyManifestPath}`, + ); + } + return { + channel, + artifact, + manifest, + manifestPath, + legacyManifest, + legacyManifestPath, + }; } if ( diff --git a/apps/ai-game-creator-shell/scripts/build-release.test.mjs b/apps/ai-game-creator-shell/scripts/build-release.test.mjs index d2853082f..904bb079f 100644 --- a/apps/ai-game-creator-shell/scripts/build-release.test.mjs +++ b/apps/ai-game-creator-shell/scripts/build-release.test.mjs @@ -1,24 +1,61 @@ import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; import { compareVersions, + createChannelConfig, + createLegacyUpdateManifest, createUpdateManifest, nextPatchVersion, + resolveManifestPlatformKeys, + resolveReleaseChannel, selectReleaseArtifact, + updateManifestUrl, } 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; +const windowsTarget = 'x86_64-pc-windows-msvc'; +const universalTarget = 'universal-apple-darwin'; + +function withEnv(overrides, run) { + const previous = new Map(); + for (const [key, value] of Object.entries(overrides)) { + previous.set(key, process.env[key]); + if (value === undefined) delete process.env[key]; + else process.env[key] = value; } + try { + return run(); + } finally { + for (const [key, value] of previous) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + } +} + +function withSignedArtifact(fileName, run) { + const directory = mkdtempSync(path.join(os.tmpdir(), 'agc-release-test-')); + try { + const artifact = path.join(directory, fileName); + writeFileSync(artifact, 'installation package'); + writeFileSync(`${artifact}.sig`, 'signature-content\n'); + return run(artifact); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +test('selects an explicit release artifact when configured', () => { + const artifactPath = fileURLToPath( + new URL('../package.json', import.meta.url), + ); + withEnv({ AGC_UPDATE_ARTIFACT: artifactPath }, () => { + assert.equal(selectReleaseArtifact([]), artifactPath); + }); }); test('does not select unsupported files', () => { @@ -28,47 +65,123 @@ test('does not select unsupported files', () => { ); }); -test('manifest contains version, download URL and integrity fields', () => { - const manifest = createUpdateManifest( - new URL('../package.json', import.meta.url).pathname, +test('resolves the channel from the target platform and rejects mismatches', () => { + assert.equal(resolveReleaseChannel({}, windowsTarget), 'dev-win'); + assert.equal(resolveReleaseChannel({}, universalTarget), 'dev-mac'); + assert.equal( + resolveReleaseChannel({ AGC_UPDATE_CHANNEL: 'dev-mac' }, universalTarget), + 'dev-mac', ); - assert.match(manifest.version, /^\d+\.\d+\.\d+$/u); - assert.match( - manifest.downloadUrl, - new RegExp(`/agc/${manifest.version}/package\\.json$`, 'u'), + assert.throws( + () => + resolveReleaseChannel({ AGC_UPDATE_CHANNEL: 'dev-mac' }, windowsTarget), + /只能用于 darwin 目标/u, + ); + assert.throws( + () => + resolveReleaseChannel({ AGC_UPDATE_CHANNEL: 'beta-win' }, windowsTarget), + /未知发布渠道/u, ); - assert.equal(manifest.sha256.length, 64); - assert.equal(typeof manifest.size, 'number'); }); -test('manifest preserves multiline release notes', () => { - const previous = process.env.AGC_UPDATE_RELEASE_NOTES; - process.env.AGC_UPDATE_RELEASE_NOTES = '第一行\n第二行\r\n第三行'; - try { - const manifest = createUpdateManifest( - new URL('../package.json', import.meta.url).pathname, +test('channel manifest URL and build-time endpoint follow the channel', () => { + withEnv({ AGC_UPDATE_OSS_BASE_URL: undefined }, () => { + assert.equal( + updateManifestUrl('dev-win'), + 'https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/dev-win/latest.json', + ); + assert.deepEqual(createChannelConfig('dev-mac'), { + plugins: { + updater: { + endpoints: [ + 'https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/dev-mac/latest.json', + ], + }, + }, + }); + }); +}); + +test('universal macOS builds publish one artifact under both platform keys', () => { + assert.deepEqual(resolveManifestPlatformKeys(universalTarget), [ + 'darwin-aarch64', + 'darwin-x86_64', + ]); + assert.deepEqual(resolveManifestPlatformKeys(windowsTarget), [ + 'windows-x86_64', + ]); +}); + +test('channel manifest carries version, platform keys and signature', () => { + withSignedArtifact('陶泥儿_0.1.48_x64-setup.exe', (artifact) => { + withEnv({ AGC_UPDATE_RELEASE_NOTES: '修复与改进' }, () => { + const manifest = createUpdateManifest(artifact, { + channel: 'dev-win', + target: windowsTarget, + publishedAt: '2026-09-17T00:00:00.000Z', + }); + assert.match(manifest.version, /^\d+\.\d+\.\d+$/u); + assert.equal(manifest.notes, '修复与改进'); + assert.equal(manifest.pub_date, '2026-09-17T00:00:00.000Z'); + assert.deepEqual(Object.keys(manifest.platforms), ['windows-x86_64']); + assert.equal( + manifest.platforms['windows-x86_64'].signature, + 'signature-content', + ); + assert.match( + manifest.platforms['windows-x86_64'].url, + new RegExp(`/agc/dev-win/${manifest.version}/`, 'u'), + ); + }); + }); +}); + +test('missing signature fails the channel manifest closed', () => { + const directory = mkdtempSync(path.join(os.tmpdir(), 'agc-release-test-')); + try { + const artifact = path.join(directory, '陶泥儿_0.1.48_x64-setup.exe'); + writeFileSync(artifact, 'installation package'); + assert.throws( + () => + createUpdateManifest(artifact, { + channel: 'dev-win', + target: windowsTarget, + }), + /缺少更新包签名/u, ); - assert.equal(manifest.releaseNotes, '第一行\n第二行\r\n第三行'); } finally { - if (previous === undefined) delete process.env.AGC_UPDATE_RELEASE_NOTES; - else process.env.AGC_UPDATE_RELEASE_NOTES = previous; + rmSync(directory, { recursive: true, force: true }); } }); -test('next release version follows the higher local or OSS version', () => { +test('legacy manifest keeps the sha256 contract of published clients', () => { + withSignedArtifact('陶泥儿_0.1.48_x64-setup.exe', (artifact) => { + const legacy = createLegacyUpdateManifest(artifact, { + channel: 'dev-win', + }); + assert.match(legacy.version, /^\d+\.\d+\.\d+$/u); + assert.equal(legacy.sha256.length, 64); + assert.equal(legacy.size, 'installation package'.length); + assert.match(legacy.downloadUrl, /\/agc\/dev-win\/[\d.]+\//u); + }); +}); + +test('next release version follows the higher local or channel 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'); }); -test('release upload forces overwrite for versioned artifact and latest pointer', () => { +test('release upload forces overwrite for artifact, signature and channel pointers', () => { const source = readFileSync( new URL('./release-upload.mjs', import.meta.url), 'utf8', ); assert.equal( - (source.match(/runOssutil\(\['cp', '--force'/gu) ?? []).length, - 2, + (source.match(/runOssutil\(\[\s*'cp',\s*'--force'/gu) ?? []).length, + 4, ); + assert.match(source, /agc\/\$\{channel\}\/latest\.json/u); + assert.match(source, /agc\/latest\.json/u); }); diff --git a/apps/ai-game-creator-shell/scripts/dev-feature-flags.mjs b/apps/ai-game-creator-shell/scripts/dev-feature-flags.mjs new file mode 100644 index 000000000..1158c4e69 --- /dev/null +++ b/apps/ai-game-creator-shell/scripts/dev-feature-flags.mjs @@ -0,0 +1,20 @@ +/** + * `agc` 开发启动下发给 Vite 的客户端特性开关默认值。 + * + * 开发态默认关闭客户端更新检查:`npm run agc` / `agc:serve` 启动的客户端不请求 OSS + * 更新清单,也不显示更新入口。需要联调更新流程时显式传 + * `VITE_AGC_ENABLE_APP_UPDATE_CHECK=1`;此处不覆盖已经显式配置的取值。 + */ +const agcAppUpdateCheckEnvKey = 'VITE_AGC_ENABLE_APP_UPDATE_CHECK'; + +function withAgcDevFeatureFlags(env = process.env) { + if (String(env[agcAppUpdateCheckEnvKey] ?? '').trim()) { + return env; + } + return { + ...env, + [agcAppUpdateCheckEnvKey]: '0', + }; +} + +export { agcAppUpdateCheckEnvKey, withAgcDevFeatureFlags }; diff --git a/apps/ai-game-creator-shell/scripts/release-oss.mjs b/apps/ai-game-creator-shell/scripts/release-oss.mjs new file mode 100644 index 000000000..0e19ee81b --- /dev/null +++ b/apps/ai-game-creator-shell/scripts/release-oss.mjs @@ -0,0 +1,27 @@ +/** + * 发布上传的 OSS 命令行整理:把 ossutil 参数与凭据整理成可执行或可打印的形式, + * 便于在 dry-run 下核对将要执行的上传,同时保证任何输出都不回显凭据明文。 + */ +const redactedCredential = ''; + +export function readReleaseDryRun(env = process.env) { + const value = env.AGC_RELEASE_DRY_RUN?.trim().toLowerCase(); + return value === '1' || value === 'true'; +} + +function quoteArgument(value) { + return /[\s"']/u.test(value) ? JSON.stringify(value) : value; +} + +export function formatOssutilCommand({ binary, args, endpoint, credentials }) { + const parts = [binary, ...args, '--endpoint', endpoint]; + if (credentials) { + parts.push( + '--access-key-id', + redactedCredential, + '--access-key-secret', + redactedCredential, + ); + } + return parts.map(quoteArgument).join(' '); +} diff --git a/apps/ai-game-creator-shell/scripts/release-oss.test.mjs b/apps/ai-game-creator-shell/scripts/release-oss.test.mjs new file mode 100644 index 000000000..0e38efc9d --- /dev/null +++ b/apps/ai-game-creator-shell/scripts/release-oss.test.mjs @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { test } from 'node:test'; + +import { formatOssutilCommand, readReleaseDryRun } from './release-oss.mjs'; + +test('dry run only accepts explicit truthy values', () => { + assert.equal(readReleaseDryRun({}), false); + assert.equal(readReleaseDryRun({ AGC_RELEASE_DRY_RUN: '1' }), true); + assert.equal(readReleaseDryRun({ AGC_RELEASE_DRY_RUN: ' true ' }), true); + assert.equal(readReleaseDryRun({ AGC_RELEASE_DRY_RUN: '0' }), false); + assert.equal(readReleaseDryRun({ AGC_RELEASE_DRY_RUN: '' }), false); +}); + +test('printed upload command keeps arguments and hides credentials', () => { + const command = formatOssutilCommand({ + binary: 'ossutil', + args: [ + 'cp', + '--force', + '陶泥儿 0.1.48.exe', + 'oss://agc-dev/agc/dev-win/x.exe', + ], + endpoint: 'oss-rg-china-mainland.aliyuncs.com', + credentials: true, + }); + assert.match(command, /^ossutil cp --force /u); + assert.match(command, /"陶泥儿 0\.1\.48\.exe"/u); + assert.match(command, /oss:\/\/agc-dev\/agc\/dev-win\/x\.exe/u); + assert.match( + command, + /--access-key-id --access-key-secret /u, + ); +}); + +test('uploader gates every ossutil call behind the dry run switch', () => { + const source = readFileSync( + new URL('./release-upload.mjs', import.meta.url), + 'utf8', + ); + assert.match(source, /const dryRun = readReleaseDryRun\(\);/u); + assert.match(source, /if \(dryRun\) \{/u); + assert.match(source, /dry-run:未写入任何 OSS 对象/u); +}); diff --git a/apps/ai-game-creator-shell/scripts/release-upload.mjs b/apps/ai-game-creator-shell/scripts/release-upload.mjs index ee5af4452..08c83c5dd 100644 --- a/apps/ai-game-creator-shell/scripts/release-upload.mjs +++ b/apps/ai-game-creator-shell/scripts/release-upload.mjs @@ -1,6 +1,8 @@ import { spawnSync } from 'node:child_process'; import path from 'node:path'; +import { formatOssutilCommand, readReleaseDryRun } from './release-oss.mjs'; + const bucket = process.env.AGC_OSS_BUCKET?.trim() || 'agc-dev'; const endpoint = process.env.AGC_OSS_ENDPOINT?.trim() || 'oss-rg-china-mainland.aliyuncs.com'; @@ -8,6 +10,7 @@ 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 dryRun = readReleaseDryRun(); const { generateUpdateManifest, prepareReleaseVersion, runTauriBuild } = await import('./build-release.mjs'); @@ -19,6 +22,18 @@ function runOssutil(args) { if (Boolean(accessKeyId) !== Boolean(accessKeySecret)) { throw new Error('OSS AccessKey ID 和 Secret 必须同时提供'); } + if (dryRun) { + // 演练:只打印将要执行的上传,凭据以占位符呈现,不写入 OSS。 + console.log( + `[dry-run] ${formatOssutilCommand({ + binary, + args, + endpoint, + credentials: Boolean(accessKeyId), + })}`, + ); + return; + } const credentialArgs = accessKeyId ? ['--access-key-id', accessKeyId, '--access-key-secret', accessKeySecret] : []; @@ -38,11 +53,40 @@ function runOssutil(args) { await prepareReleaseVersion(); runTauriBuild([]); -const { artifact, manifestPath, manifest } = generateUpdateManifest(); -const artifactKey = `agc/${manifest.version}/${path.basename(artifact)}`; +const { artifact, channel, legacyManifestPath, manifest, manifestPath } = + generateUpdateManifest(); +const artifactKey = `agc/${channel}/${manifest.version}/${path.basename(artifact)}`; // Jenkins/ossutil 默认会在目标对象已存在时交互询问并按默认值跳过; // 发布清单是固定的 latest 指针,必须显式覆盖,否则流水线会误报成功但远端仍保留旧版本。 runOssutil(['cp', '--force', artifact, `oss://${bucket}/${artifactKey}`]); -runOssutil(['cp', '--force', manifestPath, `oss://${bucket}/agc/latest.json`]); +runOssutil([ + 'cp', + '--force', + `${artifact}.sig`, + `oss://${bucket}/${artifactKey}.sig`, +]); +runOssutil([ + 'cp', + '--force', + manifestPath, + `oss://${bucket}/agc/${channel}/latest.json`, +]); console.log(`[ai-game-creator-shell] 已上传 oss://${bucket}/${artifactKey}`); -console.log(`[ai-game-creator-shell] 已上传 oss://${bucket}/agc/latest.json`); +console.log( + `[ai-game-creator-shell] 已上传 oss://${bucket}/agc/${channel}/latest.json`, +); +if (legacyManifestPath) { + // 迁移桥:让仍走旧 sha256 清单的已发布客户端升级到新协议,一个版本周期后删除。 + runOssutil([ + 'cp', + '--force', + legacyManifestPath, + `oss://${bucket}/agc/latest.json`, + ]); + console.log( + `[ai-game-creator-shell] 已上传迁移指针 oss://${bucket}/agc/latest.json`, + ); +} +if (dryRun) { + console.log('[ai-game-creator-shell] dry-run:未写入任何 OSS 对象'); +} diff --git a/apps/ai-game-creator-shell/scripts/start-dev-server.mjs b/apps/ai-game-creator-shell/scripts/start-dev-server.mjs index db7c8d42c..0bf51e6e6 100644 --- a/apps/ai-game-creator-shell/scripts/start-dev-server.mjs +++ b/apps/ai-game-creator-shell/scripts/start-dev-server.mjs @@ -3,6 +3,7 @@ import http from 'node:http'; import net from 'node:net'; import { fileURLToPath } from 'node:url'; +import { withAgcDevFeatureFlags } from './dev-feature-flags.mjs'; import { resolveAgcDevEndpoint, withAgcDevEndpointEnv } from './dev-port.mjs'; const appRoot = fileURLToPath(new URL('..', import.meta.url)); @@ -104,7 +105,7 @@ const child = spawn( ], { cwd: appRoot, - env: withAgcDevEndpointEnv(endpoint), + env: withAgcDevFeatureFlags(withAgcDevEndpointEnv(endpoint)), stdio: 'inherit', // Node 18.20+/20+/24 on Windows rejects spawning .cmd (npm.cmd) without a shell (EINVAL). shell: true, diff --git a/apps/ai-game-creator-shell/scripts/start-dev-stack.mjs b/apps/ai-game-creator-shell/scripts/start-dev-stack.mjs index 9c5c9e54d..20cf4a1ea 100644 --- a/apps/ai-game-creator-shell/scripts/start-dev-stack.mjs +++ b/apps/ai-game-creator-shell/scripts/start-dev-stack.mjs @@ -11,6 +11,7 @@ import { stopWindowsProcessTree, stopWindowsWorktreeProcesses, } from '../../../scripts/dev-windows-process.mjs'; +import { withAgcDevFeatureFlags } from './dev-feature-flags.mjs'; import { agcVitePortEnvKey, readAgcDevEndpoint, @@ -978,7 +979,10 @@ async function startVite(apiTarget, endpoint = readAgcDevEndpoint()) { '--port', String(endpoint.port), ], - { cwd: appRoot, env: withAgcDevEndpointEnv(endpoint) }, + { + cwd: appRoot, + env: withAgcDevFeatureFlags(withAgcDevEndpointEnv(endpoint)), + }, ); } diff --git a/apps/ai-game-creator-shell/src-tauri/Cargo.lock b/apps/ai-game-creator-shell/src-tauri/Cargo.lock index 7dd55a0f6..42699068e 100644 --- a/apps/ai-game-creator-shell/src-tauri/Cargo.lock +++ b/apps/ai-game-creator-shell/src-tauri/Cargo.lock @@ -814,6 +814,16 @@ dependencies = [ "url", ] +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -837,7 +847,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" dependencies = [ "bitflags 2.13.0", - "core-foundation", + "core-foundation 0.10.1", "core-graphics-types", "foreign-types 0.5.0", "libc", @@ -850,7 +860,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" dependencies = [ "bitflags 2.13.0", - "core-foundation", + "core-foundation 0.10.1", "libc", ] @@ -1405,6 +1415,16 @@ dependencies = [ "winapi", ] +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1747,7 +1767,6 @@ dependencies = [ "oxc_parser", "oxc_semantic", "oxc_span", - "percent-encoding", "platform-agent", "platform-llm", "portable-pty", @@ -1766,6 +1785,7 @@ dependencies = [ "tauri-plugin-dialog", "tauri-plugin-http", "tauri-plugin-opener", + "tauri-plugin-updater", "tempfile", "tokio", "toml 0.8.2", @@ -1776,7 +1796,7 @@ dependencies = [ "url", "uuid", "windows-sys 0.61.2", - "zip", + "zip 2.4.2", ] [[package]] @@ -2220,9 +2240,11 @@ dependencies = [ "percent-encoding", "pin-project-lite", "socket2", + "system-configuration", "tokio", "tower-service", "tracing", + "windows-registry", ] [[package]] @@ -2506,6 +2528,36 @@ dependencies = [ "windows-sys 0.45.0", ] +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.18", + "walkdir", + "windows-link 0.2.1", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.118", +] + [[package]] name = "jni-sys" version = "0.3.1" @@ -2819,6 +2871,12 @@ dependencies = [ "unicase", ] +[[package]] +name = "minisign-verify" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22f9645cb765ea72b8111f36c522475d2daa0d22c957a9826437e97534bc4e9e" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -3234,6 +3292,18 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-osa-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0" +dependencies = [ + "bitflags 2.13.0", + "objc2", + "objc2-app-kit", + "objc2-foundation", +] + [[package]] name = "objc2-quartz-core" version = "0.3.2" @@ -3378,6 +3448,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "osakit" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b" +dependencies = [ + "objc2", + "objc2-foundation", + "objc2-osa-kit", + "serde", + "serde_json", + "thiserror 2.0.18", +] + [[package]] name = "outref" version = "0.5.2" @@ -4360,15 +4444,20 @@ dependencies = [ "http-body", "http-body-util", "hyper", + "hyper-rustls", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", "serde", "serde_json", "sync_wrapper", "tokio", + "tokio-rustls", "tokio-util", "tower", "tower-http", @@ -4482,6 +4571,33 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni 0.22.4", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" + [[package]] name = "rustls-webpki" version = "0.103.13" @@ -4609,7 +4725,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ "bitflags 2.13.0", - "core-foundation", + "core-foundation 0.10.1", "core-foundation-sys", "libc", "security-framework-sys", @@ -4952,6 +5068,22 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "similar" version = "2.7.0" @@ -5175,6 +5307,27 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.0", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "system-deps" version = "6.2.2" @@ -5196,7 +5349,7 @@ checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9" dependencies = [ "bitflags 2.13.0", "block2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics", "crossbeam-channel", "dbus", @@ -5206,7 +5359,7 @@ dependencies = [ "gdkwayland-sys", "gdkx11-sys", "gtk", - "jni", + "jni 0.21.1", "libc", "log", "ndk", @@ -5239,6 +5392,17 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "target-lexicon" version = "0.12.16" @@ -5262,7 +5426,7 @@ dependencies = [ "gtk", "heck 0.5.0", "http", - "jni", + "jni 0.21.1", "libc", "log", "mime", @@ -5477,6 +5641,39 @@ dependencies = [ "zbus", ] +[[package]] +name = "tauri-plugin-updater" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b28d8cabdeb0564f03ae261963de4bc3d98321cd3d213e76a81b7d344e5df606" +dependencies = [ + "base64 0.22.1", + "dirs", + "flate2", + "futures-util", + "http", + "infer", + "log", + "minisign-verify", + "osakit", + "percent-encoding", + "reqwest 0.13.4", + "rustls", + "semver", + "serde", + "serde_json", + "tar", + "tauri", + "tauri-plugin", + "tempfile", + "thiserror 2.0.18", + "time", + "tokio", + "url", + "windows-sys 0.60.2", + "zip 4.6.1", +] + [[package]] name = "tauri-runtime" version = "2.11.3" @@ -5487,7 +5684,7 @@ dependencies = [ "dpi", "gtk", "http", - "jni", + "jni 0.21.1", "objc2", "objc2-ui-kit", "objc2-web-kit", @@ -5510,7 +5707,7 @@ checksum = "fe41e015bf8fc4d6477ff4926a0ef769dc64ff34c7b0038b6f7cacae892acb5c" dependencies = [ "gtk", "http", - "jni", + "jni 0.21.1", "log", "objc2", "objc2-app-kit", @@ -6586,6 +6783,15 @@ dependencies = [ "system-deps", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webpki-roots" version = "1.0.9" @@ -7192,7 +7398,7 @@ dependencies = [ "gtk", "http", "javascriptcore-rs", - "jni", + "jni 0.21.1", "libc", "ndk", "objc2", @@ -7256,6 +7462,16 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix", +] + [[package]] name = "yoke" version = "0.8.3" @@ -7437,6 +7653,18 @@ dependencies = [ "zopfli", ] +[[package]] +name = "zip" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1" +dependencies = [ + "arbitrary", + "crc32fast", + "indexmap 2.14.0", + "memchr", +] + [[package]] name = "zmij" version = "1.0.21" diff --git a/apps/ai-game-creator-shell/src-tauri/Cargo.toml b/apps/ai-game-creator-shell/src-tauri/Cargo.toml index 4dd833d85..ba259ccf3 100644 --- a/apps/ai-game-creator-shell/src-tauri/Cargo.toml +++ b/apps/ai-game-creator-shell/src-tauri/Cargo.toml @@ -50,7 +50,6 @@ 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"] } regex = "1" shared-contracts = { path = "../../../server-rs/crates/shared-contracts", default-features = false } @@ -58,6 +57,7 @@ tauri = { version = "2.11.2", features = [] } tauri-plugin-dialog = "2.7.1" tauri-plugin-http = { version = "2.5.9", default-features = false, features = ["charset", "cookies", "http2", "rustls-tls"] } tauri-plugin-opener = "2" +tauri-plugin-updater = "2.11.0" tempfile = "3" toml = "0.8" ttf-parser = "0.25.1" 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 43257763a..b62ed9e70 100644 --- a/apps/ai-game-creator-shell/src-tauri/capabilities/main.json +++ b/apps/ai-game-creator-shell/src-tauri/capabilities/main.json @@ -14,13 +14,13 @@ "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:*/*" } ] }, "opener:default", + "updater:default", "dialog:allow-open", "dialog:allow-save" ] 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 cdfafff99..a9b1ccfff 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/main.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/main.rs @@ -12,6 +12,8 @@ use std::sync::{mpsc, Arc, Mutex, OnceLock}; use std::thread; use std::time::{Duration, SystemTime, UNIX_EPOCH}; +// crate 根的 trait 导入会被 `use super::*` 的子模块继承(template_library 的流式下载依赖 +// `StreamExt`,通知与 Agent 事件依赖 `Emitter`),不要因为根模块自身不再直接用到就删掉。 use futures::StreamExt; use platform_agent::{ build_game_creation_seed_task_graph, plan_game_creation_agent_pass, @@ -45,189 +47,16 @@ use shared_contracts::game_creation_app::{ GAME_CREATION_AGENT_TOOL_CALL_MAX, GAME_CREATION_APP_COMMANDS, GAME_CREATION_APP_LIMITED_RUN_COMMANDS, GAME_CREATION_RESOURCE_LAYOUT_SCHEMA_VERSION, }; +// `Emitter` 同时被 `use super::*` 的子模块依赖(通知、Agent 事件等都从 crate 根取该 trait), +// 不要因为根模块自身不再直接 `.emit(..)` 就删掉它。 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"; - -fn build_agc_update_download_client() -> reqwest::Client { - reqwest::Client::new() -} - -#[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}")) -} - +/// 更新完成后的进程重启:Windows 由 NSIS 安装程序代为重启,macOS / Linux 由客户端在安装后调用。 #[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 = build_agc_update_download_client() - .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()) +fn restart_agc_app(app: tauri::AppHandle) { + app.restart(); } /// Rust 侧普通文本日志:保留 stderr 输出,同时将同一行持久化到 AppData。 @@ -2556,6 +2385,7 @@ fn main() { .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_http::init()) .plugin(tauri_plugin_clipboard_manager::init()) + .plugin(tauri_plugin_updater::Builder::new().build()) .plugin(context_menu::init()) .manage(game_creator_preview_registry()) .manage(ProjectResourcePreviewReadManager::default()) @@ -2841,7 +2671,7 @@ fn main() { replace_local_project_version_resource, get_local_game_project_revision, get_local_game_manifest, - download_agc_update, + restart_agc_app, append_application_log, read_diagnostic_logs, report_client_error, @@ -3013,50 +2843,6 @@ mod diagnostic_log_tests { } } -#[cfg(test)] -mod update_client_tests { - use super::*; - use std::io::{Read, Write}; - - #[tokio::test] - async fn update_download_client_omits_agc_marker() { - let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind update fixture"); - let address = listener.local_addr().expect("update fixture address"); - let server = std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept update request"); - stream - .set_read_timeout(Some(std::time::Duration::from_secs(2))) - .expect("set update fixture timeout"); - let mut bytes = Vec::new(); - let mut buffer = [0_u8; 1024]; - while !bytes.windows(4).any(|window| window == b"\r\n\r\n") { - let read = stream.read(&mut buffer).expect("read update request"); - assert!(read > 0, "update request closed before headers"); - bytes.extend_from_slice(&buffer[..read]); - } - stream - .write_all( - b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", - ) - .expect("write update response"); - String::from_utf8_lossy(&bytes).into_owned() - }); - - let client = build_agc_update_download_client(); - let response = client - .get(format!("http://{address}/update.exe")) - .send() - .await - .expect("send update request"); - let request = server.join().expect("join update fixture"); - - assert_eq!(response.status(), reqwest::StatusCode::NO_CONTENT); - assert!(!request - .to_ascii_lowercase() - .contains("x-genarrative-client:")); - } -} - #[cfg(test)] mod tests; pub mod ui_editor; 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 f27f09c66..2c8833ab9 100644 --- a/apps/ai-game-creator-shell/src-tauri/tauri.conf.json +++ b/apps/ai-game-creator-shell/src-tauri/tauri.conf.json @@ -24,13 +24,14 @@ } ], "security": { - "csp": "default-src 'self' customprotocol: asset:; img-src 'self' asset: data: blob: https://agc-dev.oss-rg-china-mainland.aliyuncs.com; 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: https://agc-dev.oss-rg-china-mainland.aliyuncs.com; 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:*" + "csp": "default-src 'self' customprotocol: asset:; img-src 'self' asset: data: blob: https://agc-dev.oss-rg-china-mainland.aliyuncs.com; 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: https://agc-dev.oss-rg-china-mainland.aliyuncs.com; 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": { "active": true, "targets": "all", + "createUpdaterArtifacts": true, "resources": { "design-agent": "design-agent" }, @@ -50,5 +51,16 @@ "../../desktop-shell/src-tauri/icons/icon.ico", "../../desktop-shell/src-tauri/icons/icon.png" ] + }, + "plugins": { + "updater": { + "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDRFN0NFOEUzNDczNDg4Q0IKUldUTGlEUkg0K2g4VGpaQ3FiTXdoNnJTV0JDSWU4VjQrTkcrMkovS2RleFloUXVhdWZIVGpMOTYK", + "endpoints": [ + "https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/dev-win/latest.json" + ], + "windows": { + "installMode": "quiet" + } + } } } diff --git a/apps/ai-game-creator-shell/src/app/featureFlags.ts b/apps/ai-game-creator-shell/src/app/featureFlags.ts new file mode 100644 index 000000000..32c8c77f6 --- /dev/null +++ b/apps/ai-game-creator-shell/src/app/featureFlags.ts @@ -0,0 +1,32 @@ +/** + * AGC 客户端构建期特性开关。 + * + * 开关只读取 `VITE_*` 构建期变量,运行时不改变;未显式配置时按运行环境回落: + * 开发态(`npm run agc` / `agc:serve` 的 Vite dev server 提供前端)取 `devValue`, + * 正式包取反。 + */ +function resolveFeatureFlag( + flag: string | undefined, + { devValue, dev }: { devValue: boolean; dev: boolean }, +) { + const value = flag?.trim(); + if (value === '1') return true; + if (value === '0') return false; + return dev ? devValue : !devValue; +} + +/** + * 客户端更新检查(启动时的更新提示与“关于”里的手动检查)总开关。 + * + * 开发态默认关闭:`agc` 启动的客户端不请求 OSS 更新清单,也不显示更新入口。 + * 需要联调更新流程时用 `VITE_AGC_ENABLE_APP_UPDATE_CHECK=1` 显式打开, + * 正式包也可用 `=0` 关闭。 + */ +export function resolveAppUpdateCheckEnabled( + flag: string | undefined = import.meta.env.VITE_AGC_ENABLE_APP_UPDATE_CHECK, + dev: boolean = import.meta.env.DEV, +) { + return resolveFeatureFlag(flag, { devValue: false, dev }); +} + +export const appUpdateCheckEnabled = resolveAppUpdateCheckEnabled(); diff --git a/apps/ai-game-creator-shell/src/components/AppUpdateNotice.tsx b/apps/ai-game-creator-shell/src/components/AppUpdateNotice.tsx index 858442126..421f50db0 100644 --- a/apps/ai-game-creator-shell/src/components/AppUpdateNotice.tsx +++ b/apps/ai-game-creator-shell/src/components/AppUpdateNotice.tsx @@ -3,21 +3,12 @@ import { useEffect, useState } from 'react'; import { APP_VERSION } from '../app/appMetadata'; import { - AGC_UPDATE_DOWNLOAD_PROGRESS_EVENT, type AppUpdateInfo, + type AppUpdateProgress, checkForAppUpdate, - downloadAppUpdate, + installAppUpdate, subscribeToAppUpdate, } from '../services/appUpdate'; -import { - canSubscribeTauriEvents, - subscribeTauriEvent, -} from '../services/tauriEventSubscription'; - -type DownloadProgress = { - downloadedBytes: number; - totalBytes?: number; -}; type DownloadState = 'idle' | 'downloading' | 'completed' | 'error'; @@ -29,7 +20,7 @@ function formatBytes(bytes: number) { export function AppUpdateNotice() { const [update, setUpdate] = useState(null); const [downloadState, setDownloadState] = useState('idle'); - const [downloadProgress, setDownloadProgress] = useState({ + const [downloadProgress, setDownloadProgress] = useState({ downloadedBytes: 0, }); const [downloadError, setDownloadError] = useState(''); @@ -48,30 +39,11 @@ export function AppUpdateNotice() { }; }, []); - useEffect(() => { - if (!canSubscribeTauriEvents() || !update) return; - let disposed = false; - let unlisten: (() => void) | undefined; - void subscribeTauriEvent( - 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 totalBytes = downloadProgress.totalBytes; const progress = totalBytes ? Math.min( 100, @@ -82,10 +54,10 @@ export function AppUpdateNotice() { async function handleDownload() { if (isDownloading) return; setDownloadError(''); - setDownloadProgress({ downloadedBytes: 0, totalBytes }); + setDownloadProgress({ downloadedBytes: 0 }); setDownloadState('downloading'); try { - await downloadAppUpdate(currentUpdate.downloadUrl, currentUpdate); + await installAppUpdate(setDownloadProgress); setDownloadState('completed'); } catch (error) { setDownloadError(error instanceof Error ? error.message : String(error)); diff --git a/apps/ai-game-creator-shell/src/components/WindowChrome.tsx b/apps/ai-game-creator-shell/src/components/WindowChrome.tsx index b82edbc3f..67d591ffb 100644 --- a/apps/ai-game-creator-shell/src/components/WindowChrome.tsx +++ b/apps/ai-game-creator-shell/src/components/WindowChrome.tsx @@ -9,6 +9,7 @@ import { } from 'react'; import brandIcon from '../../../../packages/shared/src/icons/taonier-product-ip.png'; +import { appUpdateCheckEnabled } from '../app/featureFlags'; import { ActiveProjectRunsPanel } from '../features/app-shell/ActiveProjectRunsPanel'; import { subscribeTauriEvent } from '../services/tauriEventSubscription'; import { AppUpdateNotice } from './AppUpdateNotice'; @@ -146,7 +147,7 @@ export function WindowChrome({ children }: WindowChromeProps) { return (
- + {appUpdateCheckEnabled ? : null}
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 16feb1f76..48980e2ab 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 @@ -22,6 +22,7 @@ import { closeDialogOnEscape, useEscapeToClose, } from '../../app/dialogs'; +import { appUpdateCheckEnabled } from '../../app/featureFlags'; import { resolveTauriInvoke } from '../../app/tauri'; import { type AgcPluginPanel, @@ -1332,18 +1333,20 @@ export function RuntimeConfigDialog({
桌面客户端
-
- - - {appUpdateStatus} - -
+ {appUpdateCheckEnabled ? ( +
+ + + {appUpdateStatus} + +
+ ) : null} ) : null}
diff --git a/apps/ai-game-creator-shell/src/services/appUpdate.ts b/apps/ai-game-creator-shell/src/services/appUpdate.ts index f9021f3d0..188909bc8 100644 --- a/apps/ai-game-creator-shell/src/services/appUpdate.ts +++ b/apps/ai-game-creator-shell/src/services/appUpdate.ts @@ -1,124 +1,58 @@ -import { fetch as tauriHttpFetch } from '@tauri-apps/plugin-http'; -import { openUrl } from '@tauri-apps/plugin-opener'; +import { + check, + type DownloadEvent, + type Update, +} from '@tauri-apps/plugin-updater'; -import { APP_VERSION } from '../app/appMetadata'; +import { appUpdateCheckEnabled } from '../app/featureFlags'; 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 = { +/** 更新提示所需的元数据;清单请求、版本比较、下载、校验与安装都由官方更新插件在原生侧完成。 */ +export type AppUpdateInfo = { version: string; - downloadUrl: string; - sha256?: string; - size?: number; + currentVersion: string; releaseNotes?: string; }; -export type AppUpdateInfo = AppUpdateManifest & { - currentVersion: string; +export type AppUpdateProgress = { + downloadedBytes: number; + totalBytes?: number; }; +let pendingUpdate: Update | null = null; 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; +function toAppUpdateInfo(update: Update): AppUpdateInfo { return { - version, - downloadUrl, - ...(sha256 ? { sha256 } : {}), - ...(size ? { size } : {}), - ...(releaseNotes ? { releaseNotes } : {}), + version: update.version, + currentVersion: update.currentVersion, + ...(update.body ? { releaseNotes: update.body } : {}), }; } -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()); +async function runAppUpdateCheck(): Promise { + try { + const update = await check(); + pendingUpdate = update; + const info = update ? toAppUpdateInfo(update) : null; + updateListeners.forEach((listener) => listener(info)); + return info; + } catch { + // 清单 404、渠道缺少当前平台条目、网络或签名错误都按“无更新”收口,不阻塞启动。 + pendingUpdate = null; + return null; + } } -/** 同一客户端生命周期内只请求一次,避免 StrictMode 或多窗口重复检测。 */ +/** 同一客户端生命周期内只请求一次清单;`force` 供「关于」页手动检查使用。 */ export function checkForAppUpdate( options: { force?: boolean } = {}, ): Promise { + // 开发态(`agc` 启动)默认关闭更新检查:不请求清单,也不显示更新入口。 + if (!appUpdateCheckEnabled) return Promise.resolve(null); 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); - } + updateCheckPromise ??= runAppUpdateCheck(); return updateCheckPromise; } @@ -129,28 +63,45 @@ export function subscribeToAppUpdate( return () => updateListeners.delete(listener); } -export async function downloadAppUpdate( - downloadUrl: string, - integrity: Pick = {}, +/** + * 下载并安装最近一次检测到的更新。 + * + * Windows 上安装程序接管后客户端退出并由安装程序重启;macOS / Linux 在安装完成后由本函数重启进程。 + */ +export async function installAppUpdate( + onProgress: (progress: AppUpdateProgress) => void = () => undefined, ) { - 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()); + const update = pendingUpdate; + if (!update) throw new Error('没有可安装的更新'); + let downloadedBytes = 0; + let totalBytes: number | undefined; + const report = () => + onProgress({ + downloadedBytes, + ...(totalBytes ? { totalBytes } : {}), + }); + await update.downloadAndInstall((event: DownloadEvent) => { + if (event.event === 'Started') { + downloadedBytes = 0; + totalBytes = event.data.contentLength; + } else if (event.event === 'Progress') { + downloadedBytes += event.data.chunkLength; } - return; - } - window.open(url.toString(), '_blank', 'noopener,noreferrer'); + report(); + }); + // 失败时保留待装更新,让「重试」仍能走同一条安装链路。 + pendingUpdate = null; + restartAppAfterUpdate(); +} + +function restartAppAfterUpdate() { + const invoke = resolveTauriInvoke(); + if (!invoke) return; + // Windows 的 install 已在启动安装程序后退出进程,这里只覆盖 macOS / Linux 的重启收敛。 + void invoke('restart_agc_app').catch(() => undefined); } export function resetAppUpdateCheckForTests() { + pendingUpdate = null; updateCheckPromise = null; } diff --git a/apps/ai-game-creator-shell/tests/appUpdate.test.ts b/apps/ai-game-creator-shell/tests/appUpdate.test.ts index 8bbe1e596..bd89c3a3a 100644 --- a/apps/ai-game-creator-shell/tests/appUpdate.test.ts +++ b/apps/ai-game-creator-shell/tests/appUpdate.test.ts @@ -1,47 +1,137 @@ -import { afterEach, describe, expect, it } from 'vitest'; +import { check } from '@tauri-apps/plugin-updater'; +import { afterEach, describe, expect, it, vi } from 'vitest'; -import { - isNewerVersion, - parseAppUpdateManifest, - resetAppUpdateCheckForTests, -} from '../src/services/appUpdate'; +vi.mock('@tauri-apps/plugin-updater', () => ({ check: vi.fn() })); -afterEach(() => resetAppUpdateCheckForTests()); +const checkMock = vi.mocked(check); -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); +type FakeDownloadEvent = + | { event: 'Started'; data: { contentLength?: number } } + | { event: 'Progress'; data: { chunkLength: number } } + | { event: 'Finished' }; + +function fakeUpdate() { + return { + version: '99.0.0', + currentVersion: '0.1.47', + body: '修复与改进', + downloadAndInstall: vi.fn( + async (onEvent: (event: FakeDownloadEvent) => void) => { + onEvent({ event: 'Started', data: { contentLength: 100 } }); + onEvent({ event: 'Progress', data: { chunkLength: 40 } }); + onEvent({ event: 'Progress', data: { chunkLength: 60 } }); + onEvent({ event: 'Finished' }); + }, + ), + }; +} + +function stubTauriWindow() { + const invoke = vi.fn(async () => undefined); + vi.stubGlobal('window', { __TAURI__: { core: { invoke } } }); + return invoke; +} + +afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + vi.resetModules(); + checkMock.mockReset(); +}); + +describe('AGC 客户端更新', () => { + it('开发态开关关闭时不请求清单', async () => { + vi.stubEnv('VITE_AGC_ENABLE_APP_UPDATE_CHECK', '0'); + vi.resetModules(); + const { checkForAppUpdate, resetAppUpdateCheckForTests } = await import( + '../src/services/appUpdate' + ); + + await expect(checkForAppUpdate()).resolves.toBeNull(); + expect(checkMock).not.toHaveBeenCalled(); + resetAppUpdateCheckForTests(); }); - 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', + it('开关打开时把插件返回的更新映射给界面,且同一生命周期只查一次', async () => { + vi.stubEnv('VITE_AGC_ENABLE_APP_UPDATE_CHECK', '1'); + vi.resetModules(); + checkMock.mockResolvedValue(fakeUpdate() as never); + const { checkForAppUpdate, resetAppUpdateCheckForTests } = await import( + '../src/services/appUpdate' + ); + + await expect(checkForAppUpdate()).resolves.toEqual({ + version: '99.0.0', + currentVersion: '0.1.47', + releaseNotes: '修复与改进', }); - expect( - parseAppUpdateManifest({ - version: '0.1.13', - downloadUrl: 'http://oss.example/agc.exe', - }), - ).toBeNull(); + await checkForAppUpdate(); + expect(checkMock).toHaveBeenCalledTimes(1); + resetAppUpdateCheckForTests(); }); - it('preserves multiline release notes', () => { - expect( - parseAppUpdateManifest({ - version: '0.1.13', - downloadUrl: 'https://oss.example/agc.exe', - releaseNotes: '第一行\n第二行\r\n第三行', - }), - ).toMatchObject({ - releaseNotes: '第一行\n第二行\r\n第三行', - }); + it('清单缺失或网络失败时静默按无更新收口', async () => { + vi.stubEnv('VITE_AGC_ENABLE_APP_UPDATE_CHECK', '1'); + vi.resetModules(); + checkMock.mockRejectedValue(new Error('updater: manifest 404')); + const { checkForAppUpdate, resetAppUpdateCheckForTests } = await import( + '../src/services/appUpdate' + ); + + await expect(checkForAppUpdate()).resolves.toBeNull(); + resetAppUpdateCheckForTests(); + }); + + it('安装时按下载事件上报进度并在完成后重启进程', async () => { + vi.stubEnv('VITE_AGC_ENABLE_APP_UPDATE_CHECK', '1'); + vi.resetModules(); + const invoke = stubTauriWindow(); + const update = fakeUpdate(); + checkMock.mockResolvedValue(update as never); + const { checkForAppUpdate, installAppUpdate, resetAppUpdateCheckForTests } = + await import('../src/services/appUpdate'); + + await checkForAppUpdate(); + const progress: Array<{ downloadedBytes: number; totalBytes?: number }> = + []; + await installAppUpdate((value) => progress.push(value)); + + expect(update.downloadAndInstall).toHaveBeenCalledTimes(1); + expect(progress).toEqual([ + { downloadedBytes: 0, totalBytes: 100 }, + { downloadedBytes: 40, totalBytes: 100 }, + { downloadedBytes: 100, totalBytes: 100 }, + { downloadedBytes: 100, totalBytes: 100 }, + ]); + expect(invoke).toHaveBeenCalledWith('restart_agc_app'); + resetAppUpdateCheckForTests(); + }); + + it('没有待安装更新时安装请求失败关闭', async () => { + vi.stubEnv('VITE_AGC_ENABLE_APP_UPDATE_CHECK', '1'); + vi.resetModules(); + const { installAppUpdate, resetAppUpdateCheckForTests } = await import( + '../src/services/appUpdate' + ); + + await expect(installAppUpdate()).rejects.toThrow('没有可安装的更新'); + resetAppUpdateCheckForTests(); + }); + + it('下载失败后仍可重试安装', async () => { + vi.stubEnv('VITE_AGC_ENABLE_APP_UPDATE_CHECK', '1'); + vi.resetModules(); + const update = fakeUpdate(); + update.downloadAndInstall.mockRejectedValue(new Error('下载更新失败')); + checkMock.mockResolvedValue(update as never); + const { checkForAppUpdate, installAppUpdate, resetAppUpdateCheckForTests } = + await import('../src/services/appUpdate'); + + await checkForAppUpdate(); + await expect(installAppUpdate()).rejects.toThrow('下载更新失败'); + // 重试仍能拿到待装更新,而不是报“没有可安装的更新”。 + await expect(installAppUpdate()).rejects.toThrow('下载更新失败'); + expect(update.downloadAndInstall).toHaveBeenCalledTimes(2); + resetAppUpdateCheckForTests(); }); }); diff --git a/apps/ai-game-creator-shell/tests/dev-feature-flags.test.ts b/apps/ai-game-creator-shell/tests/dev-feature-flags.test.ts new file mode 100644 index 000000000..0f93e5095 --- /dev/null +++ b/apps/ai-game-creator-shell/tests/dev-feature-flags.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, test } from 'vitest'; + +import { + agcAppUpdateCheckEnvKey, + withAgcDevFeatureFlags, +} from '../scripts/dev-feature-flags.mjs'; + +describe('AGC dev 特性开关环境', () => { + test('未显式配置时下发关闭检测更新的默认值', () => { + expect(withAgcDevFeatureFlags({ KEEP_ME: 'yes' })).toMatchObject({ + KEEP_ME: 'yes', + [agcAppUpdateCheckEnvKey]: '0', + }); + }); + + test('保留显式配置的开关取值,忽略空白取值', () => { + expect( + withAgcDevFeatureFlags({ [agcAppUpdateCheckEnvKey]: '1' }), + ).toMatchObject({ [agcAppUpdateCheckEnvKey]: '1' }); + expect( + withAgcDevFeatureFlags({ [agcAppUpdateCheckEnvKey]: ' ' }), + ).toMatchObject({ [agcAppUpdateCheckEnvKey]: '0' }); + }); +}); diff --git a/apps/ai-game-creator-shell/tests/featureFlags.test.ts b/apps/ai-game-creator-shell/tests/featureFlags.test.ts new file mode 100644 index 000000000..1ee1092b4 --- /dev/null +++ b/apps/ai-game-creator-shell/tests/featureFlags.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; + +import { resolveAppUpdateCheckEnabled } from '../src/app/featureFlags'; + +describe('AGC 客户端特性开关', () => { + it('开发态(agc 启动)默认关闭检测更新', () => { + expect(resolveAppUpdateCheckEnabled('', true)).toBe(false); + }); + + it('正式包默认开启检测更新', () => { + expect(resolveAppUpdateCheckEnabled('', false)).toBe(true); + }); + + it('显式配置的开关优先于环境默认值', () => { + expect(resolveAppUpdateCheckEnabled('1', true)).toBe(true); + expect(resolveAppUpdateCheckEnabled('0', false)).toBe(false); + }); + + it('忽略无法识别的开关取值并回落到环境默认值', () => { + expect(resolveAppUpdateCheckEnabled('2', true)).toBe(false); + expect(resolveAppUpdateCheckEnabled(' ', false)).toBe(true); + }); +}); diff --git a/docs/project-memory/plans/【实施计划】AGC客户端更新切换到官方更新插件-2026-09-17.md b/docs/project-memory/plans/【实施计划】AGC客户端更新切换到官方更新插件-2026-09-17.md new file mode 100644 index 000000000..4e93b3844 --- /dev/null +++ b/docs/project-memory/plans/【实施计划】AGC客户端更新切换到官方更新插件-2026-09-17.md @@ -0,0 +1,37 @@ +# 【实施计划】AGC 客户端更新切换到官方更新插件 + +| 字段 | 值 | +| --------- | ----------------------------------------------------------------------------------- | +| Milestone | `docs/project-memory/plans/【里程碑】AGC客户端更新切换到官方更新插件-2026-09-17.md` | +| Status | ready | +| Owner | Codex | + +## 修改边界 + +- 允许修改:AGC 客户端原生侧(依赖、插件注册、更新相关命令与其测试)、AGC 前端更新服务与更新提示、「关于」页检查入口、capability 与 Tauri 配置、AGC 客户端测试、主规范与开发运维文档。 +- 明确不修改:发布脚本与 Jenkins(渠道化属于下一个里程碑)、OSS 对象布局、SpacetimeDB、`/api/external/v1`、网站与其它 App。 + +## 实现顺序 + +1. 生成发布签名密钥对:私钥落在仓库外 `%USERPROFILE%\.tauri\`,公钥写入客户端配置(公钥发布后不可更换)。 +2. 原生侧:加入官方更新插件依赖并注册;删除自研更新下载命令、下载进度事件、安装器启动逻辑与其专属测试;新增供 macOS 安装后重启的应用命令。 +3. 配置与权限:打开更新产物生成,写入公钥、渠道端点(默认 Windows 渠道)与 Windows 静默安装模式;capability 增加更新权限,并移除只为自研清单放行的 OSS 白名单与 CSP 连接项。 +4. 前端:更新服务改为调用官方插件(检查、下载、进度、安装、重启收敛),删除自研清单解析、版本比较与下载实现;更新提示改用插件进度回调;保留开发态特性开关语义。 +5. 测试:改写更新服务定向用例(开关关闭不发请求、更新元数据映射、失败静默、进度与重启、无待装更新时失败关闭)。 +6. 文档:更新技术方案与开发运维说明,删除自研链路描述。 + +## 验证命令 + +1. `npm --prefix apps/ai-game-creator-shell run typecheck`(含 `check-config.mjs` 与 skill-pack 校验) +2. `npx vitest run apps/ai-game-creator-shell/tests/appUpdate.test.ts apps/ai-game-creator-shell/tests/featureFlags.test.ts apps/ai-game-creator-shell/tests/dev-feature-flags.test.ts` +3. `cargo check --manifest-path apps/ai-game-creator-shell/src-tauri/Cargo.toml` +4. `npx eslint` / `npx prettier --check`(改动文件) +5. `npm run check:encoding`、`npm run check:doc-index`、`git diff --check` +6. 运行时:`npm run agc` 启动不产生更新清单请求;检索确认自研命令、事件与白名单条目无残留。 + +## 风险与回滚点 + +- 公钥不可更换:密钥已生成但尚未发布任何签名版本,若需要带密码的私钥仍可在首次发布前重新生成。 +- Windows 安装模式由插件配置决定(本里程碑固定 `quiet`,与旧 PowerShell `/S` 一致);若改为 `passive` 会多出安装进度条 UI。 +- 插件在 Windows 上安装成功后自行退出进程,前端不再有机会更新界面;提示面板的完成态只在 macOS / Linux 可见。 +- 回滚点:改动集中在客户端与配置,回滚后即可退回自研链路;旧 OSS `agc/latest.json` 在发布管线渠道化前不删除。 diff --git a/docs/project-memory/plans/【实施计划】AGC更新发布管线渠道化-2026-09-17.md b/docs/project-memory/plans/【实施计划】AGC更新发布管线渠道化-2026-09-17.md new file mode 100644 index 000000000..94fb23092 --- /dev/null +++ b/docs/project-memory/plans/【实施计划】AGC更新发布管线渠道化-2026-09-17.md @@ -0,0 +1,37 @@ +# 【实施计划】AGC 更新发布管线渠道化 + +| 字段 | 值 | +| --------- | ------------------------------------------------------------------------- | +| Milestone | `docs/project-memory/plans/【里程碑】AGC更新发布管线渠道化-2026-09-17.md` | +| Status | ready | +| Owner | Codex | + +## 修改边界 + +- 允许修改:AGC 发布脚本(`apps/ai-game-creator-shell/scripts/build-release.mjs`、`release-upload.mjs` 及其测试)、AGC 发布流水线 `jenkins/Jenkinsfile.ai-game-creator-shell-build`、开发运维与技术方案文档。 +- 明确不修改:客户端插件接入与前端更新服务(上一里程碑已完成)、SpacetimeDB、`/api/external/v1`、网站与其它 App、其它 Jenkins Job。 +- 不执行 OSS 上传:本里程碑只交付脚本、流水线定义与本地可验证产物;真实发布需要单独授权与凭据。 + +## 实现顺序 + +1. 发布脚本:解析并校验渠道(渠道与目标平台绑定,未显式指定时按平台取默认渠道),把渠道写进远端清单地址与构建期端点配置。 +2. 清单生成:按渠道产出官方更新插件清单(版本、发布说明、发布时间、平台键与签名),universal macOS 产物同时挂两个平台键;缺少签名或签名为空时失败关闭。 +3. 迁移桥:Windows 渠道额外产出旧协议 sha256 清单,指向同一渠道的最新安装包,供已发布客户端升级到新协议。 +4. 上传:按渠道写版本目录(安装包与签名)与渠道 latest 指针,旧协议指针单独覆盖写。 +5. 流水线:新增渠道参数与签名凭据注入,归档安装包、签名、渠道清单与 commit。 +6. 测试与文档:更新发布脚本单测(渠道校验、清单结构、签名缺失失败关闭、旧协议清单),同步开发运维与技术方案。 + +## 验证命令 + +1. `node --test apps/ai-game-creator-shell/scripts/build-release.test.mjs apps/ai-game-creator-shell/scripts/cargo-features.test.mjs` +2. 本地清单 smoke:伪造 bundle 目录 + 真实签名私钥,断言渠道清单与旧协议清单结构、缺少签名时失败关闭 +3. `npm --prefix apps/ai-game-creator-shell run typecheck` +4. `npm run ai-game-creator-shell:build -- --no-bundle`(渠道端点注入后的构建 smoke;不改版本、不读远端清单、不生成清单) +5. `npm run check:encoding`、`npm run check:doc-index`、`git diff --check`、prettier 与 eslint(改动文件) + +## 风险与回滚点 + +- 版本递增按渠道独立:`dev-win` 与 `dev-mac` 的清单地址不同,互不影响;旧协议指针只由 `dev-win` 写入。 +- 签名缺失即失败关闭:构建机未注入签名私钥时发布中止,不产生半成品清单。 +- 渠道端点写进产物:渠道名一旦发布不可改名(改名等于已发布客户端再也找不到更新)。 +- 回滚点:发布脚本与流水线都在本里程碑内,回滚后客户端仍可用原先的自研清单协议;迁移桥可独立停用。 diff --git a/docs/project-memory/plans/【里程碑】AGC macOS渠道更新落地-2026-09-17.md b/docs/project-memory/plans/【里程碑】AGC macOS渠道更新落地-2026-09-17.md new file mode 100644 index 000000000..b9b84ef2e --- /dev/null +++ b/docs/project-memory/plans/【里程碑】AGC macOS渠道更新落地-2026-09-17.md @@ -0,0 +1,46 @@ +# 【里程碑】AGC macOS 渠道更新落地 + +| 字段 | 值 | +| ----------- | ------------------------------------------------------------------ | +| Version | 1.0 | +| Status | deferred | +| Date | 2026-09-17 | +| Parent Spec | `docs/technical/【技术方案】AGC客户端更新检查与下载-2026-08-31.md` | + +## 目标 + +`dev-mac` 渠道可产出并发布 macOS 更新包,客户端在 macOS 上完成检查、安装与重启接管新版本。 + +## 范围 + +- macOS 更新产物:按 universal 目标构建(Intel 与 Apple Silicon 共用一个包),更新包与其签名按渠道约定生成并上传,清单把同一对象挂到两个 macOS 平台键。 +- macOS 安装后的重启收敛:安装完成后由客户端重启进程运行新版本,不依赖安装程序代为重启。 +- macOS 代码签名与公证依赖的确认与记录:未签名或未公证的产物视为不可发布。 +- macOS 构建执行环境(本机 mac 或新增 macOS 节点)与渠道发布的衔接方式。 + +## 不在范围内 + +- Windows 渠道行为调整。 +- 微软商店或 App Store 分发。 +- 更新包体积优化与增量更新。 + +## 依赖与前置条件 + +- 客户端插件化与发布管线渠道化两个里程碑已验收。 +- macOS 签名证书与公证凭据可用;若不满足,本里程碑只能交付构建与清单能力,并明确标注未验证项。 +- macOS 通用包所需的双架构工具链(两个 darwin 目标)在构建机上可用。 + +本里程碑暂缓执行:macOS 构建机与签名 / 公证凭据尚未就绪,改由后续独立变更承接;暂缓期间 dev-mac 渠道不发布。 + +## 验收标准 + +- [ ] `dev-mac` 渠道清单包含两个 macOS 平台条目且指向同一个 universal 安装包与签名,对象在 OSS 上一致可下载。 +- [ ] macOS 客户端能完成一次真实更新:检查、下载、安装、重启后运行新版本,且升级后产物仍是 universal 包。 +- [ ] 覆盖写渠道 latest 指针后,旧版本 macOS 客户端可升级到新版本;Windows 与 macOS 渠道互不干扰。 +- [ ] 未签名或未公证产物在发布阶段失败关闭,或在不满足条件时明确记录为未验证项而非静默通过。 + +## 证据要求 + +- 自动化:macOS 更新产物选择与清单生成用例、仓库门禁。 +- 运行时:macOS 上一次真实更新闭环(含重启后版本核对),OSS 对象与清单核对。 +- 边界:签名校验失败、公证缺失、渠道缺少 macOS 平台条目、跨架构不匹配时的表现。 diff --git a/docs/project-memory/plans/【里程碑】AGC客户端更新切换到官方更新插件-2026-09-17.md b/docs/project-memory/plans/【里程碑】AGC客户端更新切换到官方更新插件-2026-09-17.md new file mode 100644 index 000000000..48930772e --- /dev/null +++ b/docs/project-memory/plans/【里程碑】AGC客户端更新切换到官方更新插件-2026-09-17.md @@ -0,0 +1,45 @@ +# 【里程碑】AGC 客户端更新切换到官方更新插件 + +| 字段 | 值 | +| ----------- | ------------------------------------------------------------------ | +| Version | 1.0 | +| Status | approved | +| Date | 2026-09-17 | +| Parent Spec | `docs/technical/【技术方案】AGC客户端更新检查与下载-2026-08-31.md` | + +## 目标 + +客户端自动更新的检查、下载、签名校验与安装改由 Tauri 官方更新插件承担,前端只保留触发与展示,并按渠道读取清单;开发态继续不检查更新。 + +## 范围 + +- 官方更新插件在客户端两侧接入:原生侧注册与配置,前端调用官方 API 替代自研检查与下载。 +- 渠道作为构建期常量进入客户端:每个渠道的产物只读该渠道清单,运行期不切换渠道。 +- 保留并复核现有开发态特性开关语义:开发态不检查更新、不显示更新入口。 +- 更新能力只授予客户端主窗口。 + +## 不在范围内 + +- 发布管线与 OSS 对象布局的渠道化改造。 +- macOS 产物落地、签名与公证。 +- 旧客户端迁移桥(是否保留旧清单指针)。 + +## 依赖与前置条件 + +- 发布签名公钥可用;公钥写入客户端配置,来源见主规范未决问题。 +- 渠道清单地址与对象布局按主规范约定确定,渠道集合固定为 `dev-win` 与 `dev-mac`。 +- 官方插件版本与当前 Tauri 主版本兼容。 + +## 验收标准 + +- [ ] 正式包走官方更新插件的检查与安装路径;更新包校验失败时必须拒绝安装并清理临时文件。 +- [ ] 客户端只请求本渠道清单,且不因清单缺失、格式错误或网络失败阻塞启动。 +- [ ] 开发态启动不产生任何更新清单请求,也不显示更新入口。 +- [ ] 更新能力只授予客户端主窗口,其它窗口调用被拒绝。 +- [ ] 自研清单解析、下载命令、下载进度事件与相应的 CSP / HTTP 白名单放行整条删除,无残留兼容分支。 + +## 证据要求 + +- 自动化:前端定向用例(渠道映射、开发态开关、失败关闭)、原生侧定向用例、类型检查与仓库门禁。 +- 运行时:`agc` 开发启动无清单请求;使用测试渠道清单完成一次真实检查与安装闭环(含升级后重启)。 +- 边界:签名不匹配、下载中断、清单 404、渠道缺少当前平台条目、非主窗口调用。 diff --git a/docs/project-memory/plans/【里程碑】AGC更新发布管线渠道化-2026-09-17.md b/docs/project-memory/plans/【里程碑】AGC更新发布管线渠道化-2026-09-17.md new file mode 100644 index 000000000..5191b0129 --- /dev/null +++ b/docs/project-memory/plans/【里程碑】AGC更新发布管线渠道化-2026-09-17.md @@ -0,0 +1,47 @@ +# 【里程碑】AGC 更新发布管线渠道化 + +| 字段 | 值 | +| ----------- | ------------------------------------------------------------------ | +| Version | 1.0 | +| Status | approved | +| Date | 2026-09-17 | +| Parent Spec | `docs/technical/【技术方案】AGC客户端更新检查与下载-2026-08-31.md` | + +## 目标 + +构建与发布管线按渠道产出官方更新插件要求的清单与签名产物并上传到渠道路径,发布入口可通过渠道参数在渠道之间切换。 + +## 范围 + +- 构建期按渠道生成清单:版本按渠道独立递增,清单包含该渠道平台的下载地址与签名;`dev-mac` 的 universal 包按同一地址与签名同时写入 `darwin-aarch64` 与 `darwin-x86_64`。 +- 构建期生成更新产物签名,并在缺少签名私钥或私钥不可用时失败关闭。 +- 渠道参数与目标平台绑定校验:Windows 目标只能发布 `dev-win`,macOS 目标只能发布 `dev-mac`;未显式指定时按目标平台取默认渠道。 +- 上传按渠道落位:安装包与签名进版本目录,清单覆盖写渠道路径的 latest 指针。 +- Jenkins 流水线增加渠道参数与签名凭据注入,凭据不落盘、不进日志、不进归档。 + +## 不在范围内 + +- 客户端侧的更新链路改造。 +- macOS 构建环境建设与 mac 产物签名、公证。 +- 旧客户端迁移桥;若决定保留,作为本里程碑的可选增量单独评审。 + +## 依赖与前置条件 + +- 客户端切换到官方更新插件的里程碑已验收:清单格式、公钥与客户端期望一致。 +- 签名密钥对已生成并进入构建凭据,公钥已写入客户端配置。 +- OSS 上传凭据与既有发布入口可复用。 + +## 验收标准 + +- [ ] 指定渠道发布时该渠道清单版本按渠道独立递增,另一个渠道清单不受影响。 +- [ ] 渠道与目标平台不匹配、缺少签名私钥或私钥密码错误时发布失败关闭,不产生半成品清单。 +- [ ] 发布后 OSS 上安装包、签名与渠道清单三者一致:清单内地址指向已存在的对象,签名与安装包匹配。 +- [ ] universal macOS 产物的两个平台键指向同一对象同一签名,不存在只挂单一架构键或指向不存在对象的情况。 +- [ ] Jenkins 归档与日志中不出现签名私钥内容,凭据只注入构建进程。 +- [ ] 未显式指定渠道时按目标平台取默认渠道,且 `--no-bundle` smoke 路径仍不读远端版本、不改版本、不生成清单。 + +## 证据要求 + +- 自动化:发布脚本单测(渠道解析与校验、版本递增、清单结构、签名缺失失败关闭)、仓库门禁。 +- 运行时:一次真实渠道发布加 OSS 对象核对(清单、安装包、签名),并用该清单触发一次客户端更新闭环。 +- 边界:渠道与平台不匹配、签名密钥缺失、远端清单 404、远端清单格式非法、重复发布时的 latest 覆盖。 diff --git a/docs/technical/【技术方案】AGC客户端更新检查与下载-2026-08-31.md b/docs/technical/【技术方案】AGC客户端更新检查与下载-2026-08-31.md index 29eae7a7f..a20a900f1 100644 --- a/docs/technical/【技术方案】AGC客户端更新检查与下载-2026-08-31.md +++ b/docs/technical/【技术方案】AGC客户端更新检查与下载-2026-08-31.md @@ -1,68 +1,129 @@ # AGC 客户端更新检查与下载 -## 交付范围 +更新时间:`2026-09-17` -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` 与清单版本比较;只有远端版本更高时显示更新提示。 +本文件是 AGC 客户端自动更新的主规范:更新能力由 Tauri 官方插件 `tauri-plugin-updater` 承担,并按下文渠道分发。 -清单格式: +## 目标 + +- 客户端自动更新改用 Tauri 官方 `tauri-plugin-updater`:清单请求、版本比较、更新包下载、签名校验、安装与退出全部在原生侧完成;前端只负责触发、展示和渠道选择。 +- 更新按渠道分发。当前渠道集合为 `dev-win`(Windows x64)与 `dev-mac`(macOS);构建管线按渠道产出并上传清单,客户端只读取自己渠道的清单。 +- 更新链路的信任来源从「清单里的 sha256 + 受信域名」升级为「发布签名 + 受信域名」:清单里的 `signature` 由构建期私钥生成,客户端用内置公钥校验,校验不过就拒绝安装。 + +## 非目标 + +- 不做灰度放量、分批更新、强制更新和自动回滚;渠道只决定「取哪份清单」。 +- 不做后台静默自动安装:是否下载安装始终由用户在更新提示里确认(仅「是否显示提示」受渠道与开发态开关影响)。 +- 不支持应用商店分发(Microsoft Store / App Store)、移动端更新和企业内网自建更新服务。 +- 不为自研 sha256 清单协议保留长期实现;迁移桥(见「契约与迁移」)只用于把已发布客户端带到新协议,随后整条删除。 + +## 入口与边界 + +- 用户入口: + - 客户端启动时在根窗口检查一次渠道清单,发现新版本时显示更新提示,用户可下载并安装。 + - 运行时设置「关于」页提供手动检查更新(强制刷新)。 +- 涉及模块:AGC 客户端(Rust `src-tauri`、前端 `src/`)、AGC 构建与发布脚本(`apps/ai-game-creator-shell/scripts/`)、Jenkins 发布流水线、OSS 对象布局。 +- 正式状态来源: + - 客户端当前版本以 Tauri app version 为唯一权威来源(`tauri.conf.json`,由发布脚本与 `package.json`、`Cargo.toml`、`Cargo.lock` 同步递增)。 + - 远端最新版本取自当前渠道的 `latest.json`。 +- 信任边界:清单地址在构建期确定并烘焙进产物;客户端不接受用户输入、后端响应或项目文件提供的更新地址,也不回退到其它渠道或旧协议地址。 + +## 必须成立的行为 + +### 正常路径 + +- 正式包启动时检查一次渠道清单;仅当清单版本高于当前版本时显示更新提示,提示包含目标版本与发布说明。 +- 用户确认后下载更新包:下载期间显示进度与已下载字节数;下载完成后按平台安装。 +- Windows 使用静默安装模式(NSIS `quiet`),安装启动成功后客户端退出并由安装程序重启新版本;macOS 由客户端在安装完成后重启进程接管新版本。 +- 渠道在构建期确定并烘焙进产物:`dev-win` 产物只读 `dev-win` 清单,`dev-mac` 产物只读 `dev-mac` 清单,同一份二进制不会在运行期跨渠道切换。 +- 开发态(`npm run agc` / `agc:serve` 由 Vite dev server 提供前端)不检查更新、不显示更新入口,也不下载任何更新包。 + +### 失败、重试与幂等 + +- 清单请求失败均静默忽略,不阻塞客户端启动:网络错误、TLS 错误、404(渠道尚未发布版本)、格式非法、渠道没有当前平台条目、远端版本不高于当前版本。 +- 同一客户端生命周期内只自动检查一次;手动检查可强制刷新。 +- 签名校验失败、下载中断或写入失败必须失败关闭:删除临时文件、不启动安装程序,并给出可读错误文案;不接受「校验失败但继续安装」。 +- 重复点击下载或安装不产生并发安装;安装开始后客户端不再接受新的更新操作。 + +### 权限、归属与数据边界 + +- 更新能力通过 Tauri capability 显式授予客户端主窗口,其它窗口(调试窗口等)不得授予。 +- 客户端只允许访问渠道清单声明的地址,只允许安装清单声明且签名校验通过的对象。 +- 清单与安装包在 OSS 上保持公开可读;签名私钥与 OSS 凭据只存在于构建环境(Jenkins 凭据、本机发布配置),不写入仓库、日志、构建产物或客户端包。 +- 客户端不记录更新地址以外的敏感信息;失败文案不回显凭据、绝对路径或响应正文。 + +## 契约与迁移 + +- 清单格式(Tauri updater v2): ```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": "修复与改进" + "version": "0.1.48", + "notes": "发布说明,可为空", + "pub_date": "2026-09-17T00:00:00Z", + "platforms": { + "windows-x86_64": { + "signature": "<.sig 文件内容>", + "url": "https:///agc/dev-win/0.1.48/<安装包文件名>" + } + } } ``` -`downloadUrl` 必须是 HTTPS;如提供 `sha256` / `size`,Tauri 下载时会校验摘要和字节数。点击“下载更新”后,客户端将安装包流式写入系统临时目录并显示进度,校验成功后通过 Windows UAC 提权启动 NSIS 静默安装并退出旧客户端。 +- 渠道与平台映射: -## 启动与失败策略 +| 渠道 | 构建目标 | 清单平台键 | 更新包 | 清单地址 | +| --------- | ------------------------ | ---------------------------------------------- | ------------------------ | ------------------------------------ | +| `dev-win` | `x86_64-pc-windows-msvc` | `windows-x86_64` | NSIS `.exe` + `.exe.sig` | `/agc/dev-win/latest.json` | +| `dev-mac` | `universal-apple-darwin` | `darwin-aarch64` + `darwin-x86_64`(同一对象) | `*.app.tar.gz` + `.sig` | `/agc/dev-mac/latest.json` | -- 检查挂在 `WindowChrome` 根组件,覆盖首页、工作台和调试窗口;网络错误、格式错误或版本不高于当前版本均静默忽略,不阻塞客户端启动。 -- 更新请求使用单例 Promise,React StrictMode 或同一窗口重复挂载不会重复请求。 -- Tauri HTTP capability 与 CSP 仅放行默认 OSS 域名;若更换域名,需同步更新 `capabilities/main.json`、`tauri.conf.json` 和发布环境配置。 +- 对象布局:清单固定写成 `agc//latest.json`;安装包与签名写成 `agc///` 与 `.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,否则清单里这一项永远不会被读取。 +- 构建期要求:打开 `bundle.createUpdaterArtifacts` 以生成 `.sig`;构建环境提供签名私钥与密码(私钥内容不得入库);公钥写入客户端配置。公钥在首个带更新能力的版本发布后不可更换,更换等于放弃自动更新(只能手动重装)。 +- 版本递增按渠道独立进行:发布脚本读取该渠道远端 `latest.json` 的 `version`,与本地版本取较高者递增 patch;两个渠道的版本号互不影响。 +- 迁移(旧协议 → 渠道清单): + - 迁移起点:已发布客户端(含当前线上版本)内置自研清单地址 `agc/latest.json`(sha256 格式),下载与安装由自研 Rust 命令完成。 + - 迁移策略见「未决问题与决策」。迁移完成后,自研清单解析、下载命令、下载进度事件以及为此放行的 CSP / HTTP 白名单条目按「四不写」整条删除,不留兼容分支与墓碑说明。 -## 发布约定 +## 构建与发布 -当前发布目标固定为 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、修改版本或生成清单。 +- 发布入口:`npm run ai-game-creator-shell:release:upload`(构建 + 按渠道上传);仅构建不发布的 smoke 使用 `--no-bundle` 分支,不读远端版本、不改版本、不生成清单。 +- 渠道由构建参数显式指定,并按目标平台校验:Windows 目标只允许 `dev-win`,macOS 目标只允许 `dev-mac`;未显式指定时按目标平台取默认渠道。 +- 上传:安装包与 `.sig` 上传到 `agc///`,清单以 `--force` 覆盖上传到 `agc//latest.json`,保证 latest 指针与清单内 URL 指向已存在的对象。 +- Jenkins 流水线需要新增渠道参数与签名凭据;签名私钥与密码只以受保护凭据注入当前进程,不写入 workspace、日志或归档产物。 +- 归档证据:安装包、`.sig`、渠道清单与源码 commit。 -每次发布安装包上传完成后,再使用 ossutil 的 `--force` 覆盖上传同一目录生成的 `latest.json`,确保固定的 latest 指针和 `downloadUrl` 指向已存在的 OSS 对象;未显式强制覆盖时,ossutil 在目标已存在时会交互询问并按默认值跳过,不能作为 Jenkins 非交互发布方式。清单和安装包均使用公开可读对象,不在清单中保存凭据、签名或本地路径。构建脚本本身不负责上传 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 构建节点 +| 条款 | 验收方式 | 证据 | +| ------------------------ | ----------------------------------------------------------------------- | ----------------------------------------------------------- | +| 渠道与端点映射、渠道校验 | `node --test apps/ai-game-creator-shell/scripts/build-release.test.mjs` | 通过(默认渠道、错配失败关闭、未知渠道失败关闭) | +| universal 包挂两个平台键 | 同上 + 本地发布烟测(伪造 bundle) | 通过(两键同 URL 同签名,不生成迁移清单) | +| 缺签名时失败关闭 | 同上 | 通过 | +| 开发态不检查更新 | `vitest run apps/ai-game-creator-shell/tests/appUpdate.test.ts` | 通过(开关关闭时不请求清单) | +| 旧自研链路整条删除 | 代码检索无残留命令、事件与白名单条目 | 通过(`download_agc_update` / 下载事件 / 清单常量均无残留) | -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)、Git 和 ossutil; -Jenkins Agent 服务必须能在同一用户环境中找到这些命令。Tauri Windows bundler 使用 -`tauri.windows.conf.json` 中的 `bundle.useLocalToolsDir: true`,把固定版本的 NSIS 工具缓存到 -`src-tauri/target/.tauri/NSIS`,不依赖 Jenkins 服务账户的 `%LOCALAPPDATA%\tauri` 或 PATH 中的系统 NSIS。 -Jenkins Checkout 的 `git clean -fdx` 会清理该构建目录,因此每次全新工作区可能重新下载 NSIS;这只影响构建耗时,不改变工具来源或执行权限要求。 -流水线参数 `AGC_UPDATE_RELEASE_NOTES` 使用 Jenkins `text` 类型,可直接输入多行发布说明;执行根 workspace 的 `npm ci`,然后调用 -`npm run ai-game-creator-shell:release:upload`,并归档 Windows 安装包、`latest.json` 与源码 commit。 -流水线会将未导出的空参数按空字符串处理:`COMMIT_HASH` 留空时沿用 Jenkins SCM 当前提交,`OSSUTIL_BIN` 留空时使用节点 PATH 中的 `ossutil`,不会因 PowerShell 对空环境变量调用 `.Trim()` 而提前失败。 +待执行证据(首次渠道发布后回填): -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`,因此回滚或测试旧版本前应确认不会覆盖线上更新入口。 +| 条款 | 验收方式 | 证据 | +| ---------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------- | +| 清单与对象布局符合渠道约定 | `ossutil ls oss://agc-dev/agc/dev-win//`;`ossutil cat .../dev-win/latest.json` | 待执行:URL 指向已存在安装包,签名与 `.sig` 内容一致 | +| 旧协议迁移桥 | `ossutil cat oss://agc-dev/agc/latest.json` | 待执行:`sha256` / `size` 与同一安装包匹配 | +| 真实更新闭环(含升级后重启) | 0.1.47 客户端升级到新版本,再启动不再提示;`npm run agc` 仍无更新入口 | 待执行 | +| 签名校验失败拒绝安装 | 渠道清单签名与实际安装包不匹配时的表现 | 待执行(需要真实渠道清单) | + +## 未决问题与决策 + +已决策: + +- macOS 采用 universal 包,同一产物同时挂 `darwin-aarch64` 与 `darwin-x86_64` 两个清单键(见「契约与迁移」)。 +- 旧客户端迁移桥:保留一个版本周期。渠道清单上线后,发布管线同时把旧的 `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 代码签名与公证凭据未确认前,相关闭环记为未验证项,不静默通过。 + +待办: + +- macOS `dev-mac` 渠道落地(macOS 构建机、签名与公证、安装后重启验证、是否接入 Jenkins macOS 节点)暂缓,由后续独立变更单独完成;在此之前 `dev-mac` 渠道只有构建与清单能力,不发布。 diff --git a/docs/【开发运维】本地开发验证与生产运维-2026-05-15.md b/docs/【开发运维】本地开发验证与生产运维-2026-05-15.md index 0d1af4ab8..38285c41a 100644 --- a/docs/【开发运维】本地开发验证与生产运维-2026-05-15.md +++ b/docs/【开发运维】本地开发验证与生产运维-2026-05-15.md @@ -70,7 +70,7 @@ Linux 本机多用户并发开发时,`npm run dev`、`npm run dev:*` 单模块 后端日志默认写入 `logs/api-server/`,独立 BgFilter worker 日志默认写入 `logs/bgfilter-worker/`。后端 API smoke 使用 `npm run dev:api-server`,先检查 BgFilter worker `/readyz`,再检查 API `/healthz`;需要确认 API 实例可接生产流量时检查 API `/readyz`。不要使用旧 `api-server:maincloud` 或任何 `GENARRATIVE_SPACETIME_MAINCLOUD_*` 口径。 -AI 游戏创作客户端使用 `npm run agc`。该入口由 `apps/ai-game-creator-shell/scripts/start-tauri-dev.mjs` 解析 AGC Vite 实际端口:Linux 默认取当前用户端口段的 `start + 5`,占用时只在本用户段内漂移;Windows / macOS 保留 `3080` 为兼容首选并允许统一漂移。最终端口通过 `GENARRATIVE_AGC_VITE_PORT` 传给 `beforeDevCommand` 和配套后端端口解析器,通过 Tauri CLI 动态 `build.devUrl` 配置传给 WebView,并通过 Vite CLI `--port` 启动严格监听;Vite 继续使用 `strictPort`,任何一层都不得自行改到另一个端口。AGC 配套后端的 `backend` 模式启动 SpacetimeDB、独立 `bgfilter-worker` 和 `api-server`,并在复用现有后端前同时检查三者状态及 `/v1/ping`、`/readyz`、`/healthz`;worker 缺失时不得把不完整的 API/数据库组合误判为 ready。任一配套服务在启动阶段进入 `failed` 时,外层启动器必须立即报告具体服务和退出原因,不能继续等待前端地址超时。端口健康不等于归属正确:复用前还必须证明端口上的监听进程属于当前工作树(Windows 按 `server-rs/target/debug/api-server.exe` 绝对路径与 SpacetimeDB `--data-dir` 校验,探测不可用时退化为旧行为),无法证明归属时一律不复用,改为启动本工作树自己的后端并在需要时端口漂移;否则上个工作树 Ctrl+C 残留的后端会被当成自己的后端复用,改了数据库的工作树会连到旧库。启动器在创建原生窗口前预检最终地址;AGC Vite marker 同时提供 `repoRoot + processId + port`,与 `.app/dev-stack.json` 的 `instanceId` 和 API target 交叉核对;若竞态中该地址被 AGC Vite、无响应监听器或其它服务占用,一律失败关闭,不复用、也不擅自终止无法证明归属的进程。 +AI 游戏创作客户端使用 `npm run agc`。该入口由 `apps/ai-game-creator-shell/scripts/start-tauri-dev.mjs` 解析 AGC Vite 实际端口:Linux 默认取当前用户端口段的 `start + 5`,占用时只在本用户段内漂移;Windows / macOS 保留 `3080` 为兼容首选并允许统一漂移。最终端口通过 `GENARRATIVE_AGC_VITE_PORT` 传给 `beforeDevCommand` 和配套后端端口解析器,通过 Tauri CLI 动态 `build.devUrl` 配置传给 WebView,并通过 Vite CLI `--port` 启动严格监听;Vite 继续使用 `strictPort`,任何一层都不得自行改到另一个端口。AGC 配套后端的 `backend` 模式启动 SpacetimeDB、独立 `bgfilter-worker` 和 `api-server`,并在复用现有后端前同时检查三者状态及 `/v1/ping`、`/readyz`、`/healthz`;worker 缺失时不得把不完整的 API/数据库组合误判为 ready。任一配套服务在启动阶段进入 `failed` 时,外层启动器必须立即报告具体服务和退出原因,不能继续等待前端地址超时。端口健康不等于归属正确:复用前还必须证明端口上的监听进程属于当前工作树(Windows 按 `server-rs/target/debug/api-server.exe` 绝对路径与 SpacetimeDB `--data-dir` 校验,探测不可用时退化为旧行为),无法证明归属时一律不复用,改为启动本工作树自己的后端并在需要时端口漂移;否则上个工作树 Ctrl+C 残留的后端会被当成自己的后端复用,改了数据库的工作树会连到旧库。启动器在创建原生窗口前预检最终地址;AGC Vite marker 同时提供 `repoRoot + processId + port`,与 `.app/dev-stack.json` 的 `instanceId` 和 API target 交叉核对;若竞态中该地址被 AGC Vite、无响应监听器或其它服务占用,一律失败关闭,不复用、也不擅自终止无法证明归属的进程。开发态客户端不检查更新:启动器给 AGC Vite 注入 `VITE_AGC_ENABLE_APP_UPDATE_CHECK=0`,客户端不请求 OSS 更新清单、也不显示更新入口;需要联调更新流程时显式传 `VITE_AGC_ENABLE_APP_UPDATE_CHECK=1`。 AGC 开发态还会按后台 Web 的端口约定额外拉起 `apps/admin-web`:Linux 用当前用户端口段的 `start + 3` 槽位,非 Linux 以 `3102` 为兼容首选并允许统一漂移,`ADMIN_WEB_PORT` 可显式指定且必须避开已解析的 AGC Vite 端口;设置 `AGC_DEV_ADMIN_WEB=0` 可关闭。后台 Vite 与 AGC Vite 一样由 `start-dev-stack.mjs` 直接持有并随启动器退出收束,不走 `npm run dev:admin-web`——后者会整体重写 `.app/dev-stack.json`,覆盖本次配套后端的归属状态;后台 Web 的端口解析、启动失败或运行中意外退出都只打印告警,不阻断也不连带停止 AGC 客户端与配套后端。前端与配套后端就绪后,启动器会打印一行 `[ai-game-creator-shell] 启动汇总:`,依次给出前端、后端、后台、数据库与 `bgfilter-worker` 的实际地址;端口漂移或默认端口被其它工作树占用时,以这一行为准。 diff --git a/jenkins/Jenkinsfile.ai-game-creator-shell-build b/jenkins/Jenkinsfile.ai-game-creator-shell-build index 3e304cf63..5bd728af0 100644 --- a/jenkins/Jenkinsfile.ai-game-creator-shell-build +++ b/jenkins/Jenkinsfile.ai-game-creator-shell-build @@ -21,8 +21,9 @@ pipeline { 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') - text(name: 'AGC_UPDATE_RELEASE_NOTES', defaultValue: '', description: '可选,支持多行文本,写入 latest.json 的发布说明') + string(name: 'AGC_RELEASE_VERSION', defaultValue: '', description: '可选,指定三段版本号;留空则按该渠道 OSS 与本地版本自动递增 patch') + choice(name: 'AGC_UPDATE_CHANNEL', choices: ['dev-win', 'dev-mac'], description: 'AGC 发布渠道;dev-win 在 Windows 节点执行,dev-mac 需在 macOS 构建机本地执行') + text(name: 'AGC_UPDATE_RELEASE_NOTES', defaultValue: '', description: '可选,支持多行文本,写入渠道清单的发布说明') string(name: 'OSSUTIL_BIN', defaultValue: 'ossutil', description: 'ossutil 或 ossutil.exe 的绝对路径/命令名') } @@ -123,11 +124,14 @@ pipeline { withCredentials([ string(credentialsId: 'AliyunAccessKeyId', variable: 'AGC_OSS_ACCESS_KEY_ID'), string(credentialsId: 'AliyunaccessKeySecret', variable: 'AGC_OSS_ACCESS_KEY_SECRET'), + string(credentialsId: 'AgcUpdaterSigningKey', variable: 'TAURI_SIGNING_PRIVATE_KEY'), + string(credentialsId: 'AgcUpdaterSigningKeyPassword', variable: 'TAURI_SIGNING_PRIVATE_KEY_PASSWORD'), ]) { withEnv([ "PATH=${env.AGC_WINDOWS_PATH}", "OSSUTIL_BIN=${params.OSSUTIL_BIN}", "AGC_RELEASE_VERSION=${params.AGC_RELEASE_VERSION}", + "AGC_UPDATE_CHANNEL=${params.AGC_UPDATE_CHANNEL}", "AGC_UPDATE_RELEASE_NOTES=${params.AGC_UPDATE_RELEASE_NOTES}", ]) { powershell ''' @@ -153,14 +157,14 @@ pipeline { 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 + 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/**/*.sig,apps/ai-game-creator-shell/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/latest.json,apps/ai-game-creator-shell/src-tauri/target/x86_64-pc-windows-msvc/release/bundle/legacy-latest.json,.jenkins-source-commit', fingerprint: true } } } post { success { - echo 'AGC Windows x64 安装包已构建并上传 OSS。' + echo "AGC ${params.AGC_UPDATE_CHANNEL} 渠道安装包、签名与渠道清单已构建并上传 OSS。" } } } diff --git a/package-lock.json b/package-lock.json index 4f7ddc219..ccb4be9ec 100644 --- a/package-lock.json +++ b/package-lock.json @@ -108,6 +108,7 @@ "@tauri-apps/plugin-dialog": "^2.7.2", "@tauri-apps/plugin-http": "^2.5.9", "@tauri-apps/plugin-opener": "~2", + "@tauri-apps/plugin-updater": "2.11.0", "@vitejs/plugin-react": "^5.0.4", "focus-trap-react": "^12.0.3", "lexical": "^0.47.0", @@ -8093,6 +8094,15 @@ "@tauri-apps/api": "^2.11.0" } }, + "node_modules/@tauri-apps/plugin-updater": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-updater/-/plugin-updater-2.11.0.tgz", + "integrity": "sha512-AE36XkOoSna24G40jZMY15nzAnkXEPL/73tGoseGrtGOHuI/cZwWzHpZFLjKXDPgzYZ435z1gHu28LgrsBwIxQ==", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@tauri-apps/api": "^2.11.0" + } + }, "node_modules/@testing-library/dom": { "version": "10.4.1", "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz", @@ -26459,6 +26469,7 @@ "@tauri-apps/plugin-dialog": "^2.7.2", "@tauri-apps/plugin-http": "^2.5.9", "@tauri-apps/plugin-opener": "~2", + "@tauri-apps/plugin-updater": "2.11.0", "@testing-library/react": "^16.3.2", "@testing-library/user-event": "^14.6.1", "@types/react": "^19.2.14", @@ -28226,6 +28237,14 @@ "@tauri-apps/api": "^2.11.0" } }, + "@tauri-apps/plugin-updater": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-updater/-/plugin-updater-2.11.0.tgz", + "integrity": "sha512-AE36XkOoSna24G40jZMY15nzAnkXEPL/73tGoseGrtGOHuI/cZwWzHpZFLjKXDPgzYZ435z1gHu28LgrsBwIxQ==", + "requires": { + "@tauri-apps/api": "^2.11.0" + } + }, "@testing-library/dom": { "version": "10.4.1", "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz",