diff --git a/.codex/skills/genarrative-external-editor-api/SKILL.md b/.codex/skills/genarrative-external-editor-api/SKILL.md index e4bbafbc2..93c8592bb 100644 --- a/.codex/skills/genarrative-external-editor-api/SKILL.md +++ b/.codex/skills/genarrative-external-editor-api/SKILL.md @@ -32,7 +32,7 @@ Prefer `scripts/genarrative_external_api.py` for runnable REST calls. It uses on - Use stable references such as `objectKey`, project resource ID, or asset ID where each operation permits them. Image edit/redraw is stricter: `sourceReferenceId` accepts only a registered project resource ID or asset ID; upload confirmation alone is not enough. Use `/assets/read-url` only for temporary preview/download access. - Preserve both warning channels after completion. A general `warning` can coexist with `sliceWarning`; do not discard either. - Do not invent missing derivatives. A source-preserved warning means the main source remains usable but requested post-processing failed. A slice warning means the complete transparent sheet is usable but individual slices are absent. -- Icon spritesheet generation accepts `sliceMode="connected-components"` (default alpha-connectivity detection) or `sliceMode="grid"`. Grid mode requires `gridX` and `gridY` (1-32); use `sliceCount` only to constrain connected-component output. +- Icon spritesheet generation requires an explicit `sliceMode` and has no default. Use `sliceMode="grid"` with the `gridX` and `gridY` the requirement actually names (1-32 each) only for equal grid cells or fixed slots; use `sliceMode="connected-components"` for free-form sheets or an open number of subjects, and constrain the count with `sliceCount` instead of inventing grid dimensions. `connected-components` must not carry `gridX`/`gridY`; an omitted, contradictory, or misapplied declaration returns 400 before billing. - For successful `style="pixelArt"`, treat completed-result and nested resource/asset dimensions as the final logical-grid PNG dimensions. They may differ from `size`, `imageSize`, the provider image, and `canvasCompletion.placeholder`; do not rescale or reject the artifact to match those inputs. - Keep generated artifacts in the canvas and asset library together. Character animation accepts `assetFolderId` and `assetLabel`; its completed result directly returns the final `assetKind="character-animation"` resource and asset with formal sequence fields. Do not create a duplicate first-frame record. diff --git a/.codex/skills/genarrative-external-editor-api/references/api-operations.md b/.codex/skills/genarrative-external-editor-api/references/api-operations.md index a744d8589..25c807788 100644 --- a/.codex/skills/genarrative-external-editor-api/references/api-operations.md +++ b/.codex/skills/genarrative-external-editor-api/references/api-operations.md @@ -94,7 +94,7 @@ For image edit/redraw, confirming an upload is not sufficient: create a project The icon-spritesheet primary `referenceId` is intentionally stricter than ordinary image references: it accepts only a current-owner project resource ID or asset ID whose authoritative `assetKind` is `icon-spec`. It does not accept an `objectKey`, URL, Data URL, or Blob URL. -`sliceMode` controls atlas splitting. Use `"connected-components"` (default) to detect independent opaque regions by alpha connectivity, or `"grid"` with positive `gridX` and `gridY` values (maximum 32 each). `sliceCount` optionally constrains the connected-component result. +`sliceMode` is required and has no default, so every request must state it. Use `"connected-components"` to detect independent opaque regions by alpha connectivity, or `"grid"` with positive `gridX` and `gridY` values (maximum 32 each) only when the requirement names equal grid cells or fixed slots; the dimensions must come from that requirement. `connected-components` must not carry `gridX`/`gridY`, and `sliceCount` constrains the connected-component result instead of expressing a grid. Omitting `sliceMode`, or contradicting the declared mode with grid dimensions, returns 400 before pricing, enqueueing, or any provider call. ## Common Values diff --git a/.codex/skills/genarrative-external-editor-api/references/capability-routing.md b/.codex/skills/genarrative-external-editor-api/references/capability-routing.md index af0ee338a..8a48a8347 100644 --- a/.codex/skills/genarrative-external-editor-api/references/capability-routing.md +++ b/.codex/skills/genarrative-external-editor-api/references/capability-routing.md @@ -79,9 +79,9 @@ Keep the existing autonomous-build task graph. Do not add a parallel task system 1. `art-director` generates `assets/art-spec.png` with image generation, `kind: "spec"`, then registers it as `assetKind: "icon-spec"`. This image is the authoritative visual spec; `generationInputs.artSpec` is supporting structured context. 2. `design-foundation` generates `assets/ui-prototype.png` with `kind: "ui-design"`, using the registered art-spec resource ID in `referenceImageSrcs`. -3. `art-asset-plan` generates transparent `assets/art-spritesheet.png` through icon spritesheet generation, using the same registered art-spec resource ID as `referenceId` plus concrete `iconDescriptions`. For a fixed four-category game contract it may send `sliceMode: "grid"`; for free-form assets use `sliceMode: "connected-components"` (the default). +3. `art-asset-plan` generates transparent `assets/art-spritesheet.png` through icon spritesheet generation, using the same registered art-spec resource ID as `referenceId` plus concrete `iconDescriptions`. `sliceMode` is required and has no default: send `sliceMode: "grid"` with `gridX`/`gridY` only when the requirement itself fixes the slots or names the column/row count, and otherwise send `sliceMode: "connected-components"` (with `sliceCount` when a subject count must be constrained); never invent a grid to express "kinds of assets", and never send `gridX`/`gridY` with `connected-components`. -For a playable Canvas game, do not stop at generation. Make `code-prototype` depend on `art-asset-plan` and consume the persisted `iconImageSrcs` slices for core players, blocks or targets, scene obstacles, and feedback. When using the fixed four-category contract, require response `sliceMode: "grid"` and exactly four slices before registering the local runtime sheet; both fewer and extra components fail closed. Treat `art-spec.png` as reference-only. A full-sheet ``, CSS background, path-only mention, guessed equal-grid crop, or code-drawn replacement for core entities is not runtime asset use. If slicing produces `sliceWarning`, keep the complete transparent sheet as a valid editor artifact, but fail the playable game asset gate until real slice files or verified atlas coordinates exist; never invent coordinates or replace the icon-spritesheet route with ordinary image generation. +For a playable Canvas game, do not stop at generation. Make `code-prototype` depend on `art-asset-plan` and consume the persisted `iconImageSrcs` slices for core players, blocks or targets, scene obstacles, and feedback. When the requirement fixes grid slots, require the response `sliceMode` to match the declared `grid` request and exactly `gridX × gridY` slices before registering the local runtime sheet; a connected-components request is instead judged by its own `sliceCount` or by the requirement, and both fewer and extra components fail closed. Treat `art-spec.png` as reference-only. A full-sheet ``, CSS background, path-only mention, guessed equal-grid crop, or code-drawn replacement for core entities is not runtime asset use. If slicing produces `sliceWarning`, keep the complete transparent sheet as a valid editor artifact, but fail the playable game asset gate until real slice files or verified atlas coordinates exist; never invent coordinates or replace the icon-spritesheet route with ordinary image generation. Never use `assets/ui-prototype.png` as the spritesheet visual-spec reference. UI extraction is outside this canonical DAG. diff --git a/.codex/skills/genarrative-external-editor-api/scripts/genarrative_external_api.py b/.codex/skills/genarrative-external-editor-api/scripts/genarrative_external_api.py index c7c0ab33b..bc270fe38 100644 --- a/.codex/skills/genarrative-external-editor-api/scripts/genarrative_external_api.py +++ b/.codex/skills/genarrative-external-editor-api/scripts/genarrative_external_api.py @@ -617,6 +617,7 @@ class GenarrativeExternalClient: self, reference_id: str, icon_descriptions: list[str], + slice_mode: str, **fields: Any, ) -> Any: reference_id = normalize_optional_text(reference_id) @@ -625,6 +626,20 @@ class GenarrativeExternalClient: descriptions = [item.strip() for item in icon_descriptions if item.strip()] if not descriptions: raise GenarrativeApiError("icon_descriptions must contain at least one non-empty item") + slice_mode = normalize_optional_text(slice_mode) + if slice_mode not in ("connected-components", "grid"): + raise GenarrativeApiError( + "slice_mode must be declared explicitly as 'connected-components' or 'grid'; the API has no default" + ) + grid_x = fields.get("gridX") + grid_y = fields.get("gridY") + if slice_mode == "grid": + if grid_x is None or grid_y is None: + raise GenarrativeApiError("slice_mode='grid' requires both gridX and gridY") + elif grid_x is not None or grid_y is not None: + raise GenarrativeApiError( + "slice_mode='connected-components' must not carry gridX/gridY" + ) label = fields.get("assetLabel", "图标图集") self._apply_canvas_session_fields(fields, label, 1024, 1024) fields.setdefault("screenColor", "auto") @@ -635,6 +650,7 @@ class GenarrativeExternalClient: **fields, "referenceId": reference_id, "iconDescriptions": descriptions, + "sliceMode": slice_mode, }, idempotency_key=idempotency_key, ) @@ -879,9 +895,9 @@ def _self_test() -> None: client.generate_icon_spritesheet( "editor-resource-spec", ["蛇头向上", "蛇身直线", "转角", "尾部", "四类食物"], + "connected-components", canvasSession=session, assetLabel="贪吃蛇透明图集", - sliceMode="connected-components", referenceId="must-not-override-explicit-reference", iconDescriptions=["不得覆盖显式图标描述"], ) diff --git a/.env.example b/.env.example index bf06357e1..f11a17f8f 100644 --- a/.env.example +++ b/.env.example @@ -158,6 +158,15 @@ ALIYUN_OSS_POST_EXPIRE_SECONDS="600" ALIYUN_OSS_POST_MAX_SIZE_BYTES="20971520" ALIYUN_OSS_SUCCESS_ACTION_STATUS="200" +# AGC 项目定时快照上传目标。对象只落在服务端私有前缀 +# `agc/project-snapshots/v1/{user}/{project}/` 下,客户端直传票据不覆盖该前缀。 +# bucket 与凭据可以与资源 bucket 分离;凭据未设置时回退使用 ALIYUN_OSS_ACCESS_KEY_*, +# 但 bucket / endpoint 默认指向 AGC 发行 bucket,需要该凭据具备目标 bucket 的 PutObject 权限。 +GENARRATIVE_AGC_PROJECT_SNAPSHOT_OSS_BUCKET="agc-dev" +GENARRATIVE_AGC_PROJECT_SNAPSHOT_OSS_ENDPOINT="oss-rg-china-mainland.aliyuncs.com" +GENARRATIVE_AGC_PROJECT_SNAPSHOT_OSS_ACCESS_KEY_ID="" +GENARRATIVE_AGC_PROJECT_SNAPSHOT_OSS_ACCESS_KEY_SECRET="" + # BgFilter 受限资源 worker。父 api-server / external-generation-worker 与唯一的 # `GENARRATIVE_PROCESS_ROLE=bgfilter-worker` 进程必须使用同一个内部 Token。 # `npm run dev` 与 `npm run dev:api-server` 都会自动带起并验活唯一 worker,不要再开第二个终端重复启动。 diff --git a/apps/ai-game-creator-shell/game-creator.config.json b/apps/ai-game-creator-shell/game-creator.config.json index b6193445f..3c0005da3 100644 --- a/apps/ai-game-creator-shell/game-creator.config.json +++ b/apps/ai-game-creator-shell/game-creator.config.json @@ -15,7 +15,7 @@ "autoCompactTokenLimit": 64000, "toolOutputTokenLimit": 12000, "requestTimeoutMs": 180000, - "maxRetries": 2, + "maxRetries": 10, "retryBackoffMs": 500 }, "agentLlm": {} diff --git a/apps/ai-game-creator-shell/package.json b/apps/ai-game-creator-shell/package.json index ce2317900..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", @@ -57,6 +58,7 @@ "react-colorful": "^5.8.0", "react-dom": "^19.0.0", "react-markdown": "^10.1.0", + "react-window": "^1.8.11", "rehype-highlight": "^7.0.2", "remark-gfm": "^4.0.1", "vite": "^6.2.0", @@ -70,6 +72,7 @@ "@testing-library/user-event": "^14.6.1", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", + "@types/react-window": "^1.8.8", "tailwindcss": "^4.1.14", "typescript": "~5.8.2", "vitest": "^0.34.6" diff --git a/apps/ai-game-creator-shell/scripts/build-release.mjs b/apps/ai-game-creator-shell/scripts/build-release.mjs index e5f153b68..fc4bbc8f4 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 { execFileSync, 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'; @@ -10,6 +11,8 @@ import { } from './cargo-features.mjs'; const appRoot = fileURLToPath(new URL('..', import.meta.url)); +// 提交摘要里的 pathspec 与 `git log` 都以仓库根为基准,不能在应用目录里执行。 +const repoRoot = path.resolve(appRoot, '..', '..'); const defaultReleaseTarget = 'x86_64-pc-windows-msvc'; const releaseTarget = process.env.AGC_BUILD_TARGET?.trim() || defaultReleaseTarget; @@ -28,14 +31,44 @@ 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', +}; + +/** + * 影响 Windows 客户端产物的路径。调度管线的发布范围判定与这里的提交摘要必须 + * 保持一致 —— `build-release.test.mjs` 有守卫用例逐条比对两边。 + */ +export const agcReleasePathPatterns = [ + 'apps/ai-game-creator-shell/', + 'packages/', + 'server-rs/crates/', + 'plugins/agc-cocos-editor/', + 'apps/desktop-shell/src-tauri/icons/', + 'package.json', + 'package-lock.json', +]; + +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 +99,156 @@ 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}`); +} + +/** 旧协议迁移指针:只在迁移窗口内存在,是历史版本高水位的来源。 */ +function legacyBridgeManifestUrl() { + return `${ossBaseUrl()}/latest.json`; +} + +async function fetchManifest(manifestUrl, label) { 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(`读取 ${label} 失败:${error.message}`); } if (response.status === 404) return null; if (!response.ok) { - throw new Error(`读取 OSS 版本清单失败:HTTP ${response.status}`); + throw new Error(`读取 ${label} 失败:HTTP ${response.status}`); } - let manifest; try { - manifest = await response.json(); + return await response.json(); } catch (error) { - throw new Error(`OSS 版本清单不是有效 JSON:${error.message}`); + throw new Error(`${label} 不是有效 JSON:${error.message}`); } - return parseVersion(manifest?.version, 'OSS版本清单 version'); +} + +async function readManifestVersion(manifestUrl, label) { + const manifest = await fetchManifest(manifestUrl, label); + return manifest == null + ? null + : parseVersion(manifest?.version, `${label} version`); +} + +/** 上一次发布的渠道清单:拿版本做高水位、拿 commit 生成自动更新摘要。 */ +async function readRemoteChannelManifest(channel = resolveReleaseChannel()) { + return fetchManifest(updateManifestUrl(channel), 'OSS 渠道清单'); +} + +/** + * 摘要锚点:上次发布对应的提交。 + * + * 首选渠道清单里的 `commit`(发布产物自己的事实来源);清单缺该字段时(首次启用 + * 摘要、或更换渠道后清单还没带过 commit)回退到 CI 传入的 `AGC_UPDATE_PREVIOUS_COMMIT` + * —— 它是上一次成功构建的 COMMIT_HASH,同样指向用户拿到的那个版本。 + */ +export async function resolvePreviousReleaseCommit( + channel = resolveReleaseChannel(), + { override = process.env.AGC_UPDATE_PREVIOUS_COMMIT } = {}, +) { + const explicit = override?.trim(); + if (explicit && /^[0-9a-f]{7,40}$/u.test(explicit)) { + return explicit; + } + try { + const manifest = await readRemoteChannelManifest(channel); + const commit = + typeof manifest?.commit === 'string' ? manifest.commit.trim() : ''; + return /^[0-9a-f]{7,40}$/u.test(commit) ? commit : null; + } catch (error) { + // 摘要只是附注:清单读不到(网络抖动等)不能把发布带崩,降级为「没有锚点」。 + console.warn( + `[ai-game-creator-shell] 读取摘要锚点失败,本次不写自动摘要:${error.message}`, + ); + return null; + } +} + +/** + * 版本高水位:渠道清单与旧协议迁移指针取较大值。 + * + * 只看渠道清单会在「渠道刚启用、旧指针还停在更高版本」时把版本链改小 —— + * 2026-09-17 首次渠道发布就是这样把 0.1.57 退回 0.1.48 的。旧指针只服务 + * Windows 渠道,其它渠道不参与比较;旧指针 404(迁移窗口结束)后自动只剩渠道清单。 + */ +export async function resolveRemoteHighWaterVersion( + channel = resolveReleaseChannel(), +) { + const channelVersion = await readManifestVersion( + updateManifestUrl(channel), + 'OSS 渠道清单', + ); + if (channel !== 'dev-win') return channelVersion; + const legacyVersion = await readManifestVersion( + legacyBridgeManifestUrl(), + 'OSS 迁移指针', + ); + if (channelVersion == null) return legacyVersion; + if (legacyVersion == null) return channelVersion; + return compareVersions(channelVersion, legacyVersion) >= 0 + ? channelVersion + : legacyVersion; } function replaceVersionLine(source, version, pattern, label) { @@ -94,8 +257,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 resolveRemoteHighWaterVersion(channel); const requestedVersion = process.env.AGC_RELEASE_VERSION?.trim(); const nextVersion = requestedVersion ? parseVersion(requestedVersion, '指定版本') @@ -158,8 +322,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 +351,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 +405,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 +435,244 @@ export function selectReleaseArtifact(files) { ); } -export function createUpdateManifest(artifactPath) { - const bytes = fs.readFileSync(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(), + notes = readReleaseNotes(), + commit = readHeadCommit(), + } = {}, +) { + const signature = readUpdaterSignature(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 url = `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(fileName)}`; + const platforms = {}; + for (const key of resolveManifestPlatformKeys(target)) { + platforms[key] = { signature, url }; + } return { version, - downloadUrl: `${baseUrl}/${encodeURIComponent(version)}/${encodedFileName}`, - sha256: createHash('sha256').update(bytes).digest('hex'), - size: bytes.length, - ...(process.env.AGC_UPDATE_RELEASE_NOTES?.trim() - ? { releaseNotes: process.env.AGC_UPDATE_RELEASE_NOTES.trim() } - : {}), + ...(notes ? { notes } : {}), + pub_date: publishedAt, + platforms, + // 非标准字段:更新插件会忽略,发布脚本用它定位下一次自动更新摘要的起点。 + ...(commit ? { commit } : {}), }; } -export function generateUpdateManifest() { +function readHeadCommit() { + try { + return execFileSync('git', ['rev-parse', 'HEAD'], { + cwd: repoRoot, + encoding: 'utf8', + }).trim(); + } catch { + return ''; + } +} + +/** + * 上一次发布到本次之间的客户端相关提交。 + * + * 返回 null 表示无法判定(没有上一次 commit,或本地没有该提交),此时不生成摘要。 + */ +export function collectReleaseCommits( + previousCommit, + headCommit = 'HEAD', + { cwd = repoRoot, paths = agcReleasePathPatterns } = {}, +) { + if (!previousCommit) return null; + try { + for (const revision of [previousCommit, headCommit]) { + execFileSync('git', ['rev-parse', '--verify', `${revision}^{commit}`], { + cwd, + stdio: 'pipe', + }); + } + } catch { + return null; + } + let output; + try { + output = execFileSync( + 'git', + [ + 'log', + '--no-merges', + '--format=%h%x09%s', + `${previousCommit}..${headCommit}`, + '--', + ...paths, + ], + { cwd, encoding: 'utf8' }, + ); + } catch { + return null; + } + return output + .split(/\r?\n/u) + .map((line) => line.trim()) + .filter(Boolean) + .map((line) => { + const [sha = '', ...subject] = line.split('\t'); + return { sha, subject: subject.join('\t') }; + }); +} + +/** 自动更新摘要:逐条列客户端相关改动,超过上限时折叠并整体截断。 */ +export function formatReleaseNotes( + commits, + { limit = 12, subjectLength = 80, maxLength = 900 } = {}, +) { + if (!commits || commits.length === 0) return ''; + const lines = commits.slice(0, limit).map(({ sha, subject }) => { + const trimmed = + subject.length > subjectLength + ? `${subject.slice(0, subjectLength - 1)}…` + : subject; + return `- ${trimmed}(${sha})`; + }); + if (commits.length > limit) { + lines.push(`- 其余 ${commits.length - limit} 项客户端改动省略`); + } + const text = lines.join('\n'); + return text.length > maxLength ? `${text.slice(0, maxLength - 1)}…` : text; +} + +/** 无锚点时的兜底:列出最近的客户端相关提交,并注明可能与上一版重复。 */ +export function collectRecentReleaseCommits({ + cwd = repoRoot, + paths = agcReleasePathPatterns, + limit = 8, +} = {}) { + let output; + try { + output = execFileSync( + 'git', + ['log', '--no-merges', `-n${limit}`, '--format=%h%x09%s', '--', ...paths], + { cwd, encoding: 'utf8' }, + ); + } catch { + return null; + } + const commits = output + .split(/\r?\n/u) + .map((line) => line.trim()) + .filter(Boolean) + .map((line) => { + const [sha = '', ...subject] = line.split('\t'); + return { sha, subject: subject.join('\t') }; + }); + return commits.length > 0 ? commits : null; +} + +export function formatRecentReleaseNotes(commits) { + const notes = formatReleaseNotes(commits, { limit: 8 }); + if (!notes) return ''; + return `最近客户端改动(未定位到上一次发布提交,可能与上一版重复):\n${notes}`; +} + +/** 旧协议(sha256)清单:只用于把已发布客户端带到新渠道协议,一个版本周期后整条删除。 */ +export function createLegacyUpdateManifest( + artifactPath, + { channel = resolveReleaseChannel(), notes = readReleaseNotes() } = {}, +) { + const bytes = fs.readFileSync(artifactPath); + const version = readPackageJson().version; + const fileName = path.basename(artifactPath); + return { + version, + downloadUrl: `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(fileName)}`, + sha256: createHash('sha256').update(bytes).digest('hex'), + size: bytes.length, + ...(notes ? { releaseNotes: notes } : {}), + }; +} + +export async function generateUpdateManifest() { + const channel = resolveReleaseChannel(); const artifact = selectReleaseArtifact(listFiles(bundleRoot)); if (!artifact) { throw new Error(`未找到可发布的 AGC 安装包:${bundleRoot}`); } - const manifest = createUpdateManifest(artifact); + const manualNotes = readReleaseNotes(); + const previousCommit = await resolvePreviousReleaseCommit(channel); + const commits = collectReleaseCommits(previousCommit); + const recentCommits = previousCommit ? null : collectRecentReleaseCommits(); + const notes = + manualNotes || + formatReleaseNotes(commits) || + formatRecentReleaseNotes(recentCommits); + if (!manualNotes && !notes) { + console.log( + `[ai-game-creator-shell] 未生成自动更新摘要(上一发布 commit=${previousCommit ?? '未知'},客户端相关提交=${commits ? commits.length : '不可判定'},最近提交=${recentCommits ? recentCommits.length : '不可判定'})`, + ); + } + const manifest = createUpdateManifest(artifact, { channel, notes }); const manifestPath = path.join(bundleRoot, 'latest.json'); fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); - console.log(`[ai-game-creator-shell] 已生成 ${manifestPath}`); + const notesPath = path.join(bundleRoot, 'release-notes.txt'); + fs.writeFileSync( + notesPath, + notes ? `${notes}\n` : '(本次没有可用的更新摘要)\n', + ); + const legacyManifest = + channel === 'dev-win' + ? createLegacyUpdateManifest(artifact, { channel, notes }) + : 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 }; + console.log( + manualNotes + ? '[ai-game-creator-shell] 更新摘要:使用 AGC_UPDATE_RELEASE_NOTES 手动文案' + : notes && !previousCommit + ? `[ai-game-creator-shell] 更新摘要:无锚点,列出最近 ${recentCommits ? recentCommits.length : 0} 条客户端相关提交` + : `[ai-game-creator-shell] 更新摘要:自动汇总 ${commits ? commits.length : 0} 条客户端相关提交(起点 ${previousCommit ?? '无'})`, + ); + console.log(`[ai-game-creator-shell] 更新摘要文件:${notesPath}`); + if (legacyManifestPath) { + console.log( + `[ai-game-creator-shell] 旧协议迁移清单:${legacyManifestPath}`, + ); + } + return { + channel, + artifact, + manifest, + manifestPath, + notes, + notesPath, + previousCommit, + commits, + legacyManifest, + legacyManifestPath, + }; } if ( @@ -281,5 +682,5 @@ if ( const args = process.argv.slice(2); if (!args.includes('--no-bundle')) await prepareReleaseVersion(); runTauriBuild(args); - if (!args.includes('--no-bundle')) generateUpdateManifest(); + if (!args.includes('--no-bundle')) await generateUpdateManifest(); } diff --git a/apps/ai-game-creator-shell/scripts/build-release.test.mjs b/apps/ai-game-creator-shell/scripts/build-release.test.mjs index d2853082f..de0134267 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,91 @@ import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; +import { execFileSync } from 'node:child_process'; +import { + mkdirSync, + 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 { + agcReleasePathPatterns, + collectRecentReleaseCommits, + collectReleaseCommits, compareVersions, + createChannelConfig, + createLegacyUpdateManifest, createUpdateManifest, + formatRecentReleaseNotes, + formatReleaseNotes, nextPatchVersion, + resolveManifestPlatformKeys, + resolvePreviousReleaseCommit, + resolveReleaseChannel, + resolveRemoteHighWaterVersion, 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 }); + } +} + +function jsonResponse(body, status = 200) { + return { + status, + ok: status >= 200 && status < 300, + json: async () => body, + }; +} + +function withStubbedFetch(handler, run) { + const originalFetch = globalThis.fetch; + globalThis.fetch = async (url) => handler(String(url)); + return Promise.resolve(run()).finally(() => { + globalThis.fetch = originalFetch; + }); +} + +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 +95,392 @@ 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('version high water keeps the legacy pointer during the migration window', async () => { + await withStubbedFetch( + (url) => + url.endsWith('/agc/dev-win/latest.json') + ? jsonResponse({}, 404) + : jsonResponse({ version: '0.1.57' }), + async () => { + assert.equal(await resolveRemoteHighWaterVersion('dev-win'), '0.1.57'); + // 旧指针 0.1.57 已是高水位,下一次发布必须是 0.1.58,不能退回渠道本地版本。 + assert.equal(nextPatchVersion('0.1.47', '0.1.57'), '0.1.58'); + }, + ); +}); + +test('version high water takes the higher of channel and legacy pointer', async () => { + await withStubbedFetch( + (url) => + url.endsWith('/agc/dev-win/latest.json') + ? jsonResponse({ version: '0.1.60' }) + : jsonResponse({ version: '0.1.57' }), + async () => { + assert.equal(await resolveRemoteHighWaterVersion('dev-win'), '0.1.60'); + }, + ); +}); + +test('version high water ignores the windows migration pointer for other channels', async () => { + await withStubbedFetch( + (url) => { + assert.ok( + !url.endsWith('/agc/latest.json'), + 'non-windows channel must not read the windows migration pointer', + ); + return jsonResponse({ version: '0.1.12' }); + }, + async () => { + assert.equal(await resolveRemoteHighWaterVersion('dev-mac'), '0.1.12'); + }, + ); +}); + +test('release notes anchor prefers the explicit commit and falls back to the manifest', async () => { + await withStubbedFetch( + () => jsonResponse({ version: '0.1.61', commit: 'abcdef1234567890' }), + async () => { + assert.equal( + await resolvePreviousReleaseCommit('dev-win', { + override: '6017d46088c04199e99cf89f347b12d67591475e', + }), + '6017d46088c04199e99cf89f347b12d67591475e', + ); + // 覆盖值非法时忽略,继续用清单里的 commit。 + assert.equal( + await resolvePreviousReleaseCommit('dev-win', { + override: 'not-a-sha', + }), + 'abcdef1234567890', + ); + assert.equal( + await resolvePreviousReleaseCommit('dev-win', { override: ' ' }), + 'abcdef1234567890', + ); + }, + ); + + await withStubbedFetch( + () => jsonResponse({ version: '0.1.61' }), + async () => { + assert.equal( + await resolvePreviousReleaseCommit('dev-win', { override: undefined }), + null, + ); + }, + ); +}); + +test('release notes anchor degrades to null when the manifest cannot be read', async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = async () => { + throw new Error('fetch failed'); + }; + try { + assert.equal( + await resolvePreviousReleaseCommit('dev-win', { override: undefined }), + null, + ); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test('recent commit fallback marks that entries may repeat the previous release', () => { + const directory = mkdtempSync(path.join(os.tmpdir(), 'agc-recent-git-')); + const git = (...args) => + execFileSync('git', args, { cwd: directory, encoding: 'utf8' }); + try { + git('init', '--quiet'); + git('config', 'user.email', 'release@example.test'); + git('config', 'user.name', 'release test'); + mkdirSync(path.join(directory, 'apps/ai-game-creator-shell'), { + recursive: true, + }); + for (const name of ['one', 'two']) { + writeFileSync( + path.join(directory, `apps/ai-game-creator-shell/${name}.rs`), + `fn ${name}() {}\n`, + ); + git('add', '.'); + git('commit', '--quiet', '-m', `客户端:${name}`); + } + writeFileSync(path.join(directory, 'README.md'), '# 文档\n'); + git('add', '.'); + git('commit', '--quiet', '-m', '文档:说明'); + + const recent = collectRecentReleaseCommits({ cwd: directory, limit: 5 }); + assert.deepEqual( + recent.map((entry) => entry.subject), + ['客户端:two', '客户端:one'], + ); + const notes = formatRecentReleaseNotes(recent); + assert.match( + notes, + /^最近客户端改动(未定位到上一次发布提交,可能与上一版重复):\n- 客户端:two/u, + ); + assert.equal(formatRecentReleaseNotes([]), ''); + assert.equal(formatRecentReleaseNotes(null), ''); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +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); +}); + +test('release notes list client commits with short sha and bound their size', () => { + const notes = formatReleaseNotes([ + { sha: 'a5fd25f1', subject: '客户端更新切换到官方更新插件' }, + { sha: '55af6014', subject: '修'.repeat(120) }, + ]); + const lines = notes.split('\n'); + assert.equal(lines.length, 2); + assert.match(lines[0], /^- 客户端更新切换到官方更新插件(a5fd25f1)$/u); + const truncatedSubject = lines[1] + .replace(/^- /u, '') + .replace(/(55af6014)$/u, ''); + assert.equal(truncatedSubject.length, 80, `主题应截断到 80 字:${lines[1]}`); + assert.match(truncatedSubject, /…$/u); + assert.match(lines[1], /(55af6014)$/u); + + const many = formatReleaseNotes( + Array.from({ length: 20 }, (_, index) => ({ + sha: `sha${index}`, + subject: `改动 ${index}`, + })), + ); + assert.match(many, /- 其余 8 项客户端改动省略$/u); + assert.equal(formatReleaseNotes([]), ''); + assert.equal(formatReleaseNotes(null), ''); +}); + +test('release commits cover only client paths and skip merge commits', () => { + const directory = mkdtempSync(path.join(os.tmpdir(), 'agc-changelog-git-')); + const git = (...args) => + execFileSync('git', args, { cwd: directory, encoding: 'utf8' }); + try { + git('init', '--quiet'); + git('config', 'user.email', 'release@example.test'); + git('config', 'user.name', 'release test'); + git('commit', '--allow-empty', '--quiet', '-m', '基点'); + const base = git('rev-parse', 'HEAD').trim(); + + mkdirSync(path.join(directory, 'apps/ai-game-creator-shell'), { + recursive: true, + }); + mkdirSync(path.join(directory, 'docs'), { recursive: true }); + writeFileSync( + path.join(directory, 'apps/ai-game-creator-shell/main.rs'), + 'fn main() {}\n', + ); + git('add', '.'); + git('commit', '--quiet', '-m', '客户端:新增更新插件接入'); + + writeFileSync(path.join(directory, 'docs/readme.md'), '# 文档\n'); + git('add', '.'); + git('commit', '--quiet', '-m', '文档:补充说明'); + + writeFileSync( + path.join(directory, 'apps/ai-game-creator-shell/other.rs'), + 'fn other() {}\n', + ); + git('add', '.'); + git('commit', '--quiet', '-m', '客户端:修复版本回退'); + + git('checkout', '--quiet', '-b', 'side'); + writeFileSync( + path.join(directory, 'apps/ai-game-creator-shell/side.rs'), + 'fn side() {}\n', + ); + git('add', '.'); + git('commit', '--quiet', '-m', '客户端:侧分支改动'); + git('checkout', '--quiet', 'master'); + git('merge', '--quiet', '--no-ff', '--no-edit', 'side'); + + const commits = collectReleaseCommits(base, 'HEAD', { cwd: directory }); + assert.ok(commits, '应能在临时仓库里收集提交'); + const subjects = commits.map((entry) => entry.subject); + // 合并提交本身被 --no-merges 排除,但它带入的客户端改动仍然计入。 + assert.deepEqual(subjects, [ + '客户端:侧分支改动', + '客户端:修复版本回退', + '客户端:新增更新插件接入', + ]); + assert.ok(commits.every((entry) => /^[0-9a-f]{7,}$/u.test(entry.sha))); + + assert.equal( + collectReleaseCommits('1234567890abcdef', 'HEAD', { cwd: directory }), + null, + ); + assert.equal(collectReleaseCommits(null, 'HEAD', { cwd: directory }), null); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test('scheduler path filter stays in sync with client release paths', () => { + const jenkinsfile = readFileSync( + new URL( + '../../../jenkins/Jenkinsfile.scheduled-revision-trigger', + import.meta.url, + ), + 'utf8', + ); + const filterLine = jenkinsfile + .split('\n') + .find((line) => line.includes('apps/ai-game-creator-shell/*|')); + assert.ok(filterLine, '调度管线里应存在发布范围过滤模式'); + for (const pattern of agcReleasePathPatterns) { + const bashPattern = pattern.includes('/') ? `${pattern}*` : pattern; + assert.ok( + filterLine.includes(bashPattern), + `调度管线过滤缺少 ${bashPattern}`, + ); + } +}); + +test('scheduler skips the full build only for non-deploy paths', () => { + const jenkinsfile = readFileSync( + new URL( + '../../../jenkins/Jenkinsfile.scheduled-revision-trigger', + import.meta.url, + ), + 'utf8', + ); + const skipLine = jenkinsfile + .split('\n') + .find((line) => line.includes('docs/*|.codex/*|jenkins/*')); + assert.ok(skipLine, '调度管线里应存在 Full Build 跳过模式'); + for (const pattern of [ + 'docs/*', + '.codex/*', + 'jenkins/*', + 'apps/ai-game-creator-shell/*', + 'apps/mobile-shell/*', + 'apps/desktop-shell/*', + 'apps/preview-deployer-web/*', + 'tools/*', + '*.md', + ]) { + assert.ok(skipLine.includes(pattern), `Full Build 跳过模式缺少 ${pattern}`); + } }); diff --git a/apps/ai-game-creator-shell/scripts/check-config.mjs b/apps/ai-game-creator-shell/scripts/check-config.mjs index e32dfb4b7..ab7a0270c 100644 --- a/apps/ai-game-creator-shell/scripts/check-config.mjs +++ b/apps/ai-game-creator-shell/scripts/check-config.mjs @@ -121,6 +121,10 @@ const allowedUncalledTauriCommands = [ 'open_game_creator_launcher_window', 'open_game_creator_workspace_window', 'read_direct_project_conversation', + // 项目定时快照上传只在 Rust 侧触发(周期定时器 / 工作区窗口关闭)与排障调用; + // 按产品口径不做客户端可见界面,因此同 `open_game_creator_*_window` 一样按 native-only 登记。 + 'read_local_project_snapshot_state', + 'sync_local_project_snapshot', 'reset_design_agent_session', 'stop_local_game_preview_if_matches', 'start_game_creator_external_mcp', diff --git a/apps/ai-game-creator-shell/scripts/deterministic-lane-defense-provider.mjs b/apps/ai-game-creator-shell/scripts/deterministic-lane-defense-provider.mjs index fed45aa02..c0a748ad3 100644 --- a/apps/ai-game-creator-shell/scripts/deterministic-lane-defense-provider.mjs +++ b/apps/ai-game-creator-shell/scripts/deterministic-lane-defense-provider.mjs @@ -724,6 +724,7 @@ function canvasAssetCall(agentId) { assetKind: 'art-spritesheet', assetLabel: '游戏首版核心美术素材', replaceExisting: false, + sliceMode: 'connected-components', }); } @@ -2691,7 +2692,7 @@ function createDeterministicCanvasFixture(apiKey) { 'deterministic spritesheet fixture', model: 'deterministic-canvas-v1', provider: 'deterministic-loopback', - sliceLayout: 'grid-2x2', + sliceMode: 'connected-components', spritesheetResource: { resourceId, projectId, 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..3d1cff921 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 } = + await 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 b5cb1f2d2..ba259ccf3 100644 --- a/apps/ai-game-creator-shell/src-tauri/Cargo.toml +++ b/apps/ai-game-creator-shell/src-tauri/Cargo.toml @@ -6,6 +6,9 @@ publish = false [features] default = [] +# 模板库假数据注入(仅本地页面压测/演示用):只有显式开启该 feature 才会编译并在读取清单后 +# 把条目循环补齐成假数据;计数由 AGC_TEMPLATE_LIBRARY_SYNTHETIC_COUNT 控制(默认 1000)。 +template-library-fixtures = [] cocos-editor = ["cocos-editor-bridge/process-discovery"] cocos-editor-execute = ["cocos-editor", "cocos-editor-bridge/windows-bootstrap"] cocos-editor-injection = ["cocos-editor-execute", "cocos-editor-bridge/windows-injection"] @@ -47,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 } @@ -55,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/resources/agc-skills/agc-client-projection/SKILL.md b/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/agc-client-projection/SKILL.md index 4d4862554..84fb51e53 100644 --- a/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/agc-client-projection/SKILL.md +++ b/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/agc-client-projection/SKILL.md @@ -13,7 +13,7 @@ Let the client derive projections from real disk changes and trusted tool result 2. Before using or deriving an existing registered asset, call `agc_list_registered_assets` and select its `localAssetId`. If the user points to an existing project file that is not listed, first call `agc_list_project_files`; only entries with `assetImportable=true` (recognized image, font, audio, video, document, or code files) may be passed to `agc_import_account_assets.localPaths`. Then re-read `agc_list_registered_assets`; never infer a source identity from a filename or fabricate a localAssetId. 3. Keep read scopes separate: `asset.list` is the current project manifest, `asset.library.list` is the signed-in account library, and the web project's canvas resource read model is the authoritative canvas list. The account library is not the complete canvas list. 4. Use `canvas.asset_import` for safe account/canvas asset IDs or project-relative local paths. The client rechecks ownership and validates bytes; host absolute paths require native UI file-picker authorization. -5. When the user explicitly asks to create or derive video, character animation, sound effect, or background music, call `agc_create_or_derive_resource`. Use `create` only for video/audio without a source and `derive` with a registered `sourceLocalAssetId`; character animation is always derived from an image. +5. When the user explicitly asks to create or derive video, character animation, sound effect, or background music, call `agc_create_or_derive_resource`. Use `create` only for video/audio without a source and `derive` with a registered `sourceLocalAssetId`; character animation is always derived from an image. Keep `prompt` inside the per-kind limit that the client really enforces: background music at most 140 characters, sound effect at most 1900, video and character animation at most 4000. A longer prompt is rejected before submission, so write the short version first instead of retrying the same text. 6. When the user explicitly asks to remove an image background, call `agc_remove_background` with a registered image `sourceLocalAssetId` and `assetName`. Optional `backgroundMode` is `complex` (semantic foreground segmentation; default) or `flat` (solid-colour background removal). Prefer `flat` when the background is known to be solid. Only `flat` accepts optional `screenColor`: `auto`, `#RRGGBB`, or omitted for automatic detection by the service. Do not select a colour on behalf of `auto`. The client requires the signed-in account, owns canvas/folder context and task identity, and returns only bounded queue state. 7. Preserve existing relative paths when a small edit is sufficient so client resource identities remain stable. 8. Do not edit `.agent/manifest.json`, revision counters, version records, resource IDs, canvas identities, source provenance, generation ledgers, or browser receipts by hand. diff --git a/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/agc-client-projection/references/projection-contract.md b/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/agc-client-projection/references/projection-contract.md index 87cba6b1a..63ddd9a82 100644 --- a/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/agc-client-projection/references/projection-contract.md +++ b/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/agc-client-projection/references/projection-contract.md @@ -14,4 +14,6 @@ Read scopes remain separate: `asset.list` is the current project's local manifes `agc_create_or_derive_resource` accepts only semantic intent. The client resolves `sourceLocalAssetId`, creates stable request identities, recovers matching pending operations, serializes paid submissions, writes supported media into the current canvas and same-name asset folder, validates downloaded bytes, commits the local manifest transaction, and returns redacted warnings. A tool error or timeout is not permission to generate again with a new identity. +`prompt` limits are per kind and are enforced before any paid submission: background music accepts 1-140 characters, sound effect 1-1900, video and character animation 1-4000, and image editing (`agc_edit_image`) 1-32000. The client composes the submitted request from a fixed prefix plus your prompt, so an over-limit prompt fails locally with the exact limit; shorten the text rather than resubmitting the same value. `agc_edit_image` remains the image path; this tool never generates or edits still images. + `agc_remove_background` accepts a registered image `sourceLocalAssetId`, `assetName`, and optional `backgroundMode` and `screenColor`. `complex` uses semantic segmentation to identify the foreground; `flat` removes a solid-colour background. Prefer `flat` when the background is known to be solid; omitting the mode selects `complex`. Only `flat` accepts a colour: `auto`, `#RRGGBB`, or omitted for automatic service detection. Never infer a concrete colour for `auto`. Empty or invalid values and colour without `flat` are rejected. The client resolves the formal source resource, canvas/folder context, stable operation identity, idempotency key, and authenticated External v1 `/api/external/v1/editor/images/background-removals` call. Mode and colour are part of request identity. Its result is bounded queue state; Codex must not poll internal workers, construct source URLs, or retry with a new identity after an uncertain response. diff --git a/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/manifest.json b/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/manifest.json index c57ea3638..385454c47 100644 --- a/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/manifest.json +++ b/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/manifest.json @@ -1,6 +1,6 @@ { "schemaVersion": "agc-skill-pack.v1", - "version": "2026-08-26.17", + "version": "2026-08-26.19", "skills": [ { "name": "agc-game-production-workflow", @@ -63,7 +63,7 @@ "agents/openai.yaml", "references/platform-art-contract.md" ], - "sha256": "ff3e1645a35fc9bff1ef255aa7bdc2a9729843d68729589b6f2670c84b8130ec" + "sha256": "c6329c6a3cbd17a237d042349d7fd8adcf240287ef56d23b49329923e976d534" }, { "name": "agc-web-game-development", @@ -123,7 +123,7 @@ "agents/openai.yaml", "references/projection-contract.md" ], - "sha256": "a929c27bc5b2b0bee0b7935e5c7b04ddbab1eb1804fe196f8c2537ad040ca5b1" + "sha256": "0700d4a7a18ee6151811f38786211ad416863f2e425fdc2ded67555a0a1923a1" } ] } diff --git a/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/taonier-art-assets/SKILL.md b/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/taonier-art-assets/SKILL.md index d652b4436..c5c036c2b 100644 --- a/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/taonier-art-assets/SKILL.md +++ b/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/taonier-art-assets/SKILL.md @@ -19,9 +19,20 @@ image, UI design image, or publication material; use `agc_edit_image` for an edit of an existing registered image; use `taonier_prepare_game_art` only for the complete game-art package and its canonical slices. -When `agc_generate_image` is used with `kind="art-spritesheet"`, pass -`sliceMode="connected-components"` (the default alpha-connectivity splitter) -or `sliceMode="grid"` with `gridX` and `gridY` (1-32 each). The selected mode is carried +When `agc_generate_image` is used with `kind="art-spritesheet"`, `sliceMode` is +required and has no default, so decide it explicitly: + +- Use `sliceMode="grid"` with `gridX` and `gridY` (1-32 each) only when the user + or brief actually names equal grid cells, fixed slots, or a concrete + column/row count; those dimensions must come from that requirement. +- Use `sliceMode="connected-components"` for free-form sheets, an open number of + subjects, or a request for one sheet; constrain the subject count with + `sliceCount` instead of inventing grid dimensions. + +Never assume `2x2` or any other grid to express "four kinds of assets", never +pass `gridX`/`gridY` together with `connected-components`, and never pass +`sliceMode` for another `kind`. The client rejects a missing, contradictory, or +misapplied declaration instead of choosing for you. The selected mode is carried through the client request and returned result; do not infer it from the number of slices. diff --git a/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/taonier-art-assets/references/platform-art-contract.md b/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/taonier-art-assets/references/platform-art-contract.md index bf0b74481..603b8077b 100644 --- a/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/taonier-art-assets/references/platform-art-contract.md +++ b/apps/ai-game-creator-shell/src-tauri/resources/agc-skills/taonier-art-assets/references/platform-art-contract.md @@ -15,7 +15,8 @@ - On timeout or uncertain delivery, reuse the recorded operation; never create a replacement request. - `postprocess-failed-source-preserved` means the complete provider source remains usable, but the requested transparent derivative is absent. - `sliceWarning` means the complete transparent sheet remains usable, but individual slices are absent. -- For direct `agc_generate_image` spritesheet requests, `sliceMode="connected-components"` selects alpha-connectivity detection and `sliceMode="grid"` uses the caller-provided `gridX` and `gridY` (1-32 each). The client preserves the selected mode and grid dimensions in the request identity and result metadata. +- For direct `agc_generate_image` spritesheet requests, `sliceMode` is required and has no default: `connected-components` selects alpha-connectivity detection, while `grid` uses the caller-provided `gridX` and `gridY` (1-32 each) and is only correct when the requirement names equal grid cells, fixed slots, or a concrete column/row count. `connected-components` must not carry `gridX`/`gridY`, and `sliceMode` must not be sent for another `kind`; the client rejects a missing, contradictory, or misapplied declaration instead of choosing a mode. The client preserves the selected mode and grid dimensions in the request identity and result metadata. +- The client-owned standard art package declares `sliceMode="connected-components"` with `sliceCount=4` because its four canonical slices are mapped to fixed usage paths: the platform must return exactly four slices or fail with an actionable `422` naming the recognized count, and the client refuses to write a usage manifest whose slice count is not exactly four. A `sliceMode` or grid-dimension echo that disagrees with the request also fails closed before local commit. - General and slice warnings can coexist. The tool returns them separately through `warnings` and `sliceWarnings`; callers must preserve every entry and must not downgrade a slice warning into a successful independent-asset claim. - `assetPaths` contains the complete package paths. `slicePaths` contains only slices that the client downloaded, validated, and registered with their platform source identities. - `resources` contains only safe registered identity fields: local asset/path/kind/media type, Canvas project/resource/asset/task IDs, and reference resource IDs. It never exposes prompts, models, provider routes, absolute paths, URLs, tokens, cookies, or API keys. diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/design_runtime.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/design_runtime.rs index 1a5a6e486..9e907c2c0 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/design_runtime.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/design_runtime.rs @@ -1,5 +1,6 @@ use super::design_tools::*; use super::*; +use futures::FutureExt; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::fs::File; @@ -11,6 +12,46 @@ use uuid::Uuid; const DESIGN_ACTIVE_LOCK: &str = ".agent/design-agent/active.lock"; +const DESIGN_PANIC_PUBLIC_ERROR: &str = + "策划运行发生内部错误,本轮已中断,可直接重试;若反复出现请反馈。"; + +// 运行段经 task-local 携带项目根,panic hook 据此把位置和负载写进私有 design_debug。 +// task-local 而非 thread-local:多线程 runtime 下 future 会跨 worker 迁移。 +tokio::task_local! { + static DESIGN_PANIC_ROOT: Option; +} + +fn ensure_design_panic_hook() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + if let Ok(Some(root)) = DESIGN_PANIC_ROOT.try_with(Clone::clone) { + let location = info + .location() + .map(|location| { + format!( + "{}:{}:{}", + location.file(), + location.line(), + location.column() + ) + }) + .unwrap_or_else(|| "未知位置".to_string()); + design_debug( + &root, + "panic", + json!({ + "location": location, + "error": info.payload_as_str().unwrap_or("未知 panic 负载"), + }), + ); + } + previous(info); + })); + }); +} + #[derive(Clone, Debug, Deserialize, Serialize)] #[serde( tag = "type", @@ -421,6 +462,10 @@ fn execute_design_tool( ) -> Result { let args: Value = serde_json::from_str(&call.arguments) .map_err(|error| format!("工具参数不是有效 JSON:{error}"))?; + #[cfg(test)] + if call.name == "design_test__panic" { + panic!("注入的策划工具 panic"); + } match call.name.as_str() { "get_workflow_status" => Ok(design_workflow_status(session)), "list_resources" => resources.list().map(Value::String), @@ -971,7 +1016,20 @@ async fn finish_design_command( Some(design_view(&session, run)), )); if run { - if let Err(error) = run_design_loop(root, resources, &mut session, &mut emit).await { + // panic 边界:运行期 panic 转成普通失败,交给既有错误分支恢复(重读检查点、 + // 写 last_error、发最终 view)。否则 unwind 会杀死 command task,IPC 永不 + // 返回(前端停在工作态),会话停在无错误的 pending,用户只能看到无声的重试。 + ensure_design_panic_hook(); + let run = DESIGN_PANIC_ROOT.scope( + Some(root.to_path_buf()), + run_design_loop(root, resources, &mut session, &mut emit), + ); + let outcome = std::panic::AssertUnwindSafe(run).catch_unwind().await; + let result = match outcome { + Ok(result) => result, + Err(payload) => Err(design_panic_error(payload)), + }; + if let Err(error) = result { // 从最后一个持久检查点恢复,防止写后未记结果被误认为已完成。 session = read_design_session(root)?.ok_or("策划会话丢失")?; session.last_error = Some(redact_agent_runtime_error(root, &error, 1800)); @@ -991,6 +1049,12 @@ async fn finish_design_command( Ok(view) } +// panic 负载可能包含路径或内容片段,公开文案固定;位置和负载由 panic hook 写进私有 +// design_debug(task-local 提供项目根),不进入用户可见消息。 +fn design_panic_error(_payload: Box) -> String { + DESIGN_PANIC_PUBLIC_ERROR.to_string() +} + pub(crate) async fn continue_design_agent_at( root: &Path, resources: &DesignResources, @@ -1632,6 +1696,121 @@ mod tests { .clone() } + // 进程级 env 在同一 binary 的并行用例间共享:持锁串行化修改,drop 时恢复原值, + // 避免 debug 开关泄漏给并发用例。锁中毒时取内部值继续,不让上游失败放大。 + static DESIGN_DEBUG_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + struct DesignDebugEnvGuard { + previous: Option, + _lock: std::sync::MutexGuard<'static, ()>, + } + + impl Drop for DesignDebugEnvGuard { + fn drop(&mut self) { + match &self.previous { + Some(value) => std::env::set_var("GENARRATIVE_AGC_DESIGN_DEBUG", value), + None => std::env::remove_var("GENARRATIVE_AGC_DESIGN_DEBUG"), + } + } + } + + fn enable_design_debug_for_test() -> DesignDebugEnvGuard { + let lock = DESIGN_DEBUG_ENV_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let previous = std::env::var("GENARRATIVE_AGC_DESIGN_DEBUG").ok(); + std::env::set_var("GENARRATIVE_AGC_DESIGN_DEBUG", "1"); + DesignDebugEnvGuard { + previous, + _lock: lock, + } + } + + #[tokio::test(flavor = "current_thread")] + async fn design_tool_panic_becomes_visible_retryable_error() { + let (_temp, root, resources) = init_design_project(); + let _debug_env = enable_design_debug_for_test(); + let panic_call = platform_llm::LlmToolCall { + id: "call-panic".into(), + name: "design_test__panic".into(), + arguments: "{}".into(), + }; + let _fake = fake_provider::install( + vec![ + Ok(fake_response("panic-turn", "", vec![panic_call])), + Ok(fake_response("recovery", "已恢复", Vec::new())), + ], + 0, + ); + let view = continue_design_agent_at( + &root, + &resources, + "turn-panic", + DesignInput::Message { + text: "需求".into(), + }, + |_| {}, + ) + .await + .expect("panic 必须转成可恢复视图而不是向上传播"); + assert!(!view.running); + assert!(view.can_retry); + assert_eq!( + view.session.last_error.as_deref(), + Some(DESIGN_PANIC_PUBLIC_ERROR) + ); + let session = read_design_session(&root) + .expect("read session") + .expect("session exists"); + assert!( + !session.history.iter().any(|item| { + item.get("type").and_then(Value::as_str) == Some("function_call_output") + && item.get("call_id").and_then(Value::as_str) == Some("call-panic") + }), + "panic 不得写半个工具输出" + ); + + // design_debug 经独立线程落盘,轮询等待 panic 记录出现。 + let debug_dir = root.join(".debug/design-agent"); + let mut panic_record = None; + for _ in 0..100 { + panic_record = fs::read_dir(&debug_dir).ok().and_then(|entries| { + entries.flatten().find_map(|entry| { + let path = entry.path(); + let name = path.file_name()?.to_string_lossy().into_owned(); + if name.ends_with("-panic.json") { + fs::read_to_string(path).ok() + } else { + None + } + }) + }); + if panic_record.is_some() { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + let panic_record = panic_record.expect("panic hook 必须把位置和负载写入 design_debug"); + assert!(panic_record.contains("design_runtime.rs")); + assert!(panic_record.contains("注入的策划工具 panic")); + + let view = + continue_design_agent_at(&root, &resources, "turn-retry", DesignInput::Retry, |_| {}) + .await + .expect("panic 后可重试"); + assert!(!view.running); + assert!(!view.can_retry); + assert!(view.session.last_error.is_none()); + let session = read_design_session(&root) + .expect("read session") + .expect("session exists"); + assert!(session.turn.as_ref().is_some_and(|turn| !turn.pending)); + assert!(session.history.iter().any(|item| { + item.get("type").and_then(Value::as_str) == Some("function_call_output") + && item.get("call_id").and_then(Value::as_str) == Some("call-panic") + })); + } + #[test] fn design_request_enables_reasoning_capture_only_for_design_runtime() { let session = new_design_session("project", "quality"); diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/design_tools.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/design_tools.rs index 730d68004..ba4420164 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/design_tools.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/design_tools.rs @@ -380,11 +380,16 @@ pub(crate) fn execute_design_file_tool( } return Err(details.join("\n")); } - let mut updated = content.clone(); - for (index, start, end) in matches.into_iter().rev() { + matches.sort_unstable_by_key(|(_, start, _)| *start); + let mut updated = String::with_capacity(content.len()); + let mut cursor = 0; + for (index, start, end) in matches { let (_, new) = &normalized[index]; - updated.replace_range(start..end, new); + updated.push_str(&content[cursor..start]); + updated.push_str(new); + cursor = end; } + updated.push_str(&content[cursor..]); if updated == content { return Err(format!("没有产生修改:{display}")); } @@ -834,6 +839,35 @@ mod tests { assert!(!root.join("design_artifacts/notes").exists()); } + #[test] + fn patch_file_applies_out_of_order_edits_with_changing_utf8_lengths() { + let temp = test_root(); + let root = temp.path(); + execute_design_file_tool( + root, + "write_file", + &json!({"path":"notes/design.md","content":"开头\n甲\n保留一\n乙乙\n保留二\n丙\n结尾"}), + ) + .expect("write"); + execute_design_file_tool( + root, + "patch_file", + &json!({ + "path":"notes/design.md", + "edits":[ + {"old_text":"丙","new_text":"新的结论"}, + {"old_text":"甲","new_text":"扩展A"}, + {"old_text":"乙乙","new_text":"乙"} + ] + }), + ) + .expect("patch out of order"); + assert_eq!( + fs::read_to_string(root.join("design_artifacts/notes/design.md")).expect("read disk"), + "开头\n扩展A\n保留一\n乙\n保留二\n新的结论\n结尾" + ); + } + #[test] fn phase_context_injects_current_skill_only() { let resources = DesignResources::new(pack_root()).expect("pack"); diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/direct_runtime/mod.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/direct_runtime/mod.rs index f18c6c724..7331497f1 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/direct_runtime/mod.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/direct_runtime/mod.rs @@ -3391,8 +3391,12 @@ async fn generate_direct_taonier_art_asset_at( asset_kind: asset_kind.to_string(), asset_label: asset_label.to_string(), replace_existing: root.join(output_path).is_file(), - slice_count: None, - slice_mode: None, + // 标准美术包必须产出四张 canonical 切片:连通域模式下显式声明目标数量, + // 让平台要么给出四张,要么以可执行的 422 说明实际识别数量。 + slice_count: (asset_kind == "art-spritesheet").then_some(4), + // 切分模式没有默认值:陶泥儿标准美术包按自由排布生成核心图集,因此只在 + // art-spritesheet 阶段显式声明连通域切分。 + slice_mode: (asset_kind == "art-spritesheet").then(|| "connected-components".to_string()), grid_x: None, grid_y: None, reference_asset_ids: Vec::new(), diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tool_bridge.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tool_bridge.rs index 39f75b62e..447a549ab 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tool_bridge.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tool_bridge.rs @@ -24,7 +24,6 @@ const DIRECT_TOOL_BRIDGE_IMAGE_PREVIEW_MAX_DIMENSION: u32 = 1024; const DIRECT_TOOL_BRIDGE_MAX_SEARCH_QUERY_CHARS: usize = 400; const DIRECT_TOOL_BRIDGE_MAX_SEARCH_RESULTS: usize = 5; const DIRECT_TOOL_BRIDGE_SEARCH_URL: &str = "https://www.bing.com/search?format=rss"; -const DIRECT_TOOL_BRIDGE_MAX_RESOURCE_PROMPT_CHARS: usize = 4_000; const DIRECT_TOOL_BRIDGE_MAX_RESOURCE_NAME_CHARS: usize = 120; const DIRECT_TOOL_BRIDGE_MAX_RESOURCE_KIND_CHARS: usize = 80; const DIRECT_TOOL_BRIDGE_MAX_RESOURCE_PAGE_SIZE: usize = 100; @@ -89,7 +88,7 @@ struct DirectToolBridgeRequest { } #[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum DirectResourceGenerationKind { +pub(crate) enum DirectResourceGenerationKind { Image, Video, CharacterAnimation, @@ -98,7 +97,7 @@ enum DirectResourceGenerationKind { } impl DirectResourceGenerationKind { - fn parse(value: &str) -> Result { + pub(crate) fn parse(value: &str) -> Result { match value { "image" => Ok(Self::Image), "video" => Ok(Self::Video), @@ -119,7 +118,7 @@ impl DirectResourceGenerationKind { } } - fn edit_kind(self) -> LocalProjectResourceEditKind { + pub(crate) fn edit_kind(self) -> LocalProjectResourceEditKind { match self { Self::Image => LocalProjectResourceEditKind::ImageReference, Self::Video => LocalProjectResourceEditKind::Video, @@ -128,6 +127,11 @@ impl DirectResourceGenerationKind { Self::BackgroundMusic => LocalProjectResourceEditKind::BackgroundMusic, } } + + /// 提示词上限只从客户端权威口径取值,工具桥与 MCP 层共用同一份数字。 + pub(crate) fn prompt_max_chars(self) -> usize { + resource_edit_prompt_max_chars(&self.edit_kind()) + } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -1036,6 +1040,12 @@ fn bridge_account_asset_import_inputs( Ok((asset_ids, local_paths)) } +/// 源资源身份不在当前项目 manifest 时的统一提示。 +/// +/// 只报「不属于已登记资源」会让模型原地重试;这里必须把下一步可执行动作写清楚: +/// 已登记资源走 `agc_list_registered_assets`,只在项目里存在的文件先登记再重试。 +const DIRECT_TOOL_BRIDGE_UNREGISTERED_SOURCE_MESSAGE: &str = "sourceLocalAssetId 不是当前项目已登记资源:先调用 agc_list_registered_assets 选择已有 localAssetId;若目标图片只在项目里,先用 agc_list_project_files 确认它 assetImportable=true,再用 agc_import_account_assets.localPaths 登记后重试。"; + fn bridge_resource_generation_input( arguments: &Value, ) -> Result { @@ -1054,18 +1064,20 @@ fn bridge_resource_generation_input( "sourceLocalAssetId", DIRECT_TOOL_BRIDGE_MAX_RESOURCE_KIND_CHARS, )?; - let prompt = bridge_bounded_string( - arguments, - "prompt", - DIRECT_TOOL_BRIDGE_MAX_RESOURCE_PROMPT_CHARS, - )?; + // prompt 的形状校验只用信封级上限,真正生效的按 kind 上限由紧随其后的权威判定给出 + // 精确数字;否则通用 4000 会先于「图片编辑 32000 / 音效 1900」误报成安全边界错误。 + let prompt = bridge_bounded_string(arguments, "prompt", DIRECT_TOOL_BRIDGE_MAX_REQUEST_BYTES)?; let asset_name = bridge_bounded_string( arguments, "assetName", DIRECT_TOOL_BRIDGE_MAX_RESOURCE_NAME_CHARS, )?; - if kind == DirectResourceGenerationKind::BackgroundMusic && prompt.chars().count() > 140 { - return Err("背景音乐提示词必须在 1..=140 字符内".to_string()); + let prompt_max_chars = kind.prompt_max_chars(); + if prompt.chars().count() > prompt_max_chars { + return Err(resource_edit_prompt_limit_error( + &kind.edit_kind(), + prompt_max_chars, + )); } match (kind, mode, source_local_asset_id.as_ref()) { (DirectResourceGenerationKind::Image, DirectResourceGenerationMode::Create, _) => { @@ -1806,7 +1818,7 @@ async fn bridge_create_or_derive_resource( .iter() .find(|asset| asset.id == asset_id) .cloned() - .ok_or_else(|| "sourceLocalAssetId 不属于当前项目已登记资源".to_string()) + .ok_or_else(|| DIRECT_TOOL_BRIDGE_UNREGISTERED_SOURCE_MESSAGE.to_string()) }) .transpose()?; let prompt_sha256 = format!("{:x}", Sha256::digest(input.prompt.as_bytes())); @@ -1903,7 +1915,7 @@ async fn bridge_remove_background(state: &DirectToolBridgeState, arguments: &Val .assets .iter() .find(|asset| asset.id == source_asset_id) - .ok_or_else(|| "sourceLocalAssetId 不属于当前项目已登记资源".to_string())?; + .ok_or_else(|| DIRECT_TOOL_BRIDGE_UNREGISTERED_SOURCE_MESSAGE.to_string())?; if !source_asset.media_type.starts_with("image/") { return Err("抠图工具只接受当前项目已登记的图片资源".to_string()); } @@ -2158,6 +2170,36 @@ fn bridge_image_generation_kind(arguments: &Value) -> Result { }) } +/// 切分模式没有默认值:图集必须显式声明,且声明必须与 kind 和网格参数自洽。 +fn validate_generate_image_slice_declaration( + kind: &str, + slice_mode: Option<&str>, + grid_x: Option, + grid_y: Option, + slice_count: Option, +) -> Result<(), String> { + if kind == "art-spritesheet" { + if slice_mode.is_none() { + return Err( + "kind=art-spritesheet 必须显式声明 sliceMode,没有默认值:需求要求等分网格、固定槽位或指定行列数时传 sliceMode=grid 并提供 gridX/gridY;自由排布、数量不定或只要求一张图集时传 sliceMode=connected-components" + .to_string(), + ); + } + if slice_mode == Some("grid") && slice_count.is_some() { + return Err( + "sliceMode=grid 的素材张数由 gridX×gridY 决定,不接受 sliceCount".to_string(), + ); + } + return Ok(()); + } + if slice_mode.is_some() || grid_x.is_some() || grid_y.is_some() || slice_count.is_some() { + return Err(format!( + "工具参数 sliceMode/gridX/gridY 仅对 kind=art-spritesheet 生效,当前 kind={kind}" + )); + } + Ok(()) +} + async fn bridge_generate_image(state: &DirectToolBridgeState, arguments: &Value) -> Value { let result = async { bridge_reject_unknown_fields( @@ -2251,6 +2293,13 @@ async fn bridge_generate_image(state: &DirectToolBridgeState, arguments: &Value) { return Err("工具参数 gridX/gridY 必须在 1 到 32 之间".to_string()); } + validate_generate_image_slice_declaration( + kind.as_str(), + slice_mode.as_deref(), + grid_x, + grid_y, + None, + )?; let options = PlatformArtAssetGenerationOptions { output_path, aspect_ratio, @@ -2299,6 +2348,14 @@ async fn bridge_generate_image(state: &DirectToolBridgeState, arguments: &Value) "resources": resources, "warnings": generated.warning.map(|warning| bridge_safe_warning_messages(&state.root, vec![warning])).unwrap_or_default(), "sliceWarnings": generated.slice_warning.map(|warning| bridge_safe_warning_messages(&state.root, vec![warning])).unwrap_or_default(), + "sliceMode": generated.slice_mode, + "gridX": generated.grid_x, + "gridY": generated.grid_y, + "slicePaths": generated + .slices + .iter() + .map(|slice| slice.local_path.clone()) + .collect::>(), }) .to_string(), images, @@ -2733,6 +2790,55 @@ pub(crate) async fn start_direct_tool_bridge( #[cfg(test)] mod tests { + #[test] + fn generate_image_slice_declaration_is_explicit_and_self_consistent() { + let missing = + validate_generate_image_slice_declaration("art-spritesheet", None, None, None, None) + .expect_err("art-spritesheet without sliceMode must fail closed"); + assert!(missing.contains("没有默认值"), "{missing}"); + assert!(missing.contains("connected-components"), "{missing}"); + + assert!(validate_generate_image_slice_declaration( + "art-spritesheet", + Some("connected-components"), + None, + None, + Some(4), + ) + .is_ok()); + assert!(validate_generate_image_slice_declaration( + "art-spritesheet", + Some("grid"), + Some(3), + Some(2), + None, + ) + .is_ok()); + let grid_with_count = validate_generate_image_slice_declaration( + "art-spritesheet", + Some("grid"), + Some(2), + Some(2), + Some(4), + ) + .expect_err("grid mode must not carry sliceCount"); + assert!(grid_with_count.contains("gridX×gridY"), "{grid_with_count}"); + + let wrong_kind = validate_generate_image_slice_declaration( + "image", + Some("connected-components"), + None, + None, + None, + ) + .expect_err("slice declaration must stay scoped to art-spritesheet"); + assert!( + wrong_kind.contains("仅对 kind=art-spritesheet 生效"), + "{wrong_kind}" + ); + assert!(validate_generate_image_slice_declaration("image", None, None, None, None).is_ok()); + } + #[test] fn remove_background_identity_preserves_default_and_distinguishes_options() { let legacy = "asset-1\0透明图"; @@ -2797,6 +2903,67 @@ mod tests { .contains("x-genarrative-client:")); } + /// 按 kind 的提示词上限只来自客户端权威口径;超限必须在构造工具输入时就被拒绝, + /// 不能再出现写死的数字(2026-09-17 的背景音乐 140 就是写死在桥这一层的)。 + #[test] + fn bridge_resource_prompt_limits_follow_the_client_authority() { + for (kind, edit_kind) in [ + ( + "background-music", + LocalProjectResourceEditKind::BackgroundMusic, + ), + ("sound-effect", LocalProjectResourceEditKind::SoundEffect), + ("video", LocalProjectResourceEditKind::Video), + ( + "character-animation", + LocalProjectResourceEditKind::CharacterAnimation, + ), + ("image", LocalProjectResourceEditKind::ImageReference), + ] { + let authority = resource_edit_prompt_max_chars(&edit_kind); + let mode = if matches!( + edit_kind, + LocalProjectResourceEditKind::ImageReference + | LocalProjectResourceEditKind::CharacterAnimation + ) { + "derive" + } else { + "create" + }; + let mut arguments = json!({ + "kind": kind, + "mode": mode, + "prompt": "字".repeat(authority), + "assetName": "边界名称" + }); + if mode == "derive" { + arguments["sourceLocalAssetId"] = json!("registered-source"); + } + bridge_resource_generation_input(&arguments) + .unwrap_or_else(|error| panic!("{kind} 恰好等于上限必须通过:{error}")); + + arguments["prompt"] = json!("字".repeat(authority + 1)); + let error = match bridge_resource_generation_input(&arguments) { + Ok(_) => panic!("{kind} 超过按 kind 上限的提示词必须被拒绝"), + Err(error) => error, + }; + assert!( + error.contains(&authority.to_string()) && error.contains(kind_label(&edit_kind)), + "{kind} 的拒绝文案必须带上真实上限与类型:{error}" + ); + } + } + + fn kind_label(edit_kind: &LocalProjectResourceEditKind) -> &'static str { + match edit_kind { + LocalProjectResourceEditKind::BackgroundMusic => "背景音乐", + LocalProjectResourceEditKind::SoundEffect => "音效", + LocalProjectResourceEditKind::Video => "视频", + LocalProjectResourceEditKind::CharacterAnimation => "角色动画", + _ => "资源编辑", + } + } + #[test] fn bridge_argument_bounds_are_deterministic() { assert_eq!( diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tools_mcp.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tools_mcp.rs index 8b0cd12a0..f30331490 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tools_mcp.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/direct_tools_mcp.rs @@ -16,7 +16,6 @@ const DIRECT_TOOLS_MCP_MAX_REQUEST_BYTES: usize = 2 * 1024 * 1024; const DIRECT_TOOLS_MCP_MAX_ART_BRIEF_CHARS: usize = 4_000; const DIRECT_TOOLS_MCP_MAX_IMAGE_PROMPT_CHARS: usize = 32_000; const DIRECT_TOOLS_MCP_MAX_SEARCH_QUERY_CHARS: usize = 400; -const DIRECT_TOOLS_MCP_MAX_RESOURCE_PROMPT_CHARS: usize = 4_000; const DIRECT_TOOLS_MCP_MAX_RESOURCE_NAME_CHARS: usize = 120; const DIRECT_TOOLS_MCP_MAX_WRITE_CONTENT_BYTES: usize = 1_500_000; const DIRECT_TOOLS_MCP_MAX_BRIDGE_RESPONSE_BYTES: usize = 32 * 1024 * 1024; @@ -103,6 +102,32 @@ async fn direct_tools_mcp_specs() -> Value { direct_tools_mcp_specs_for(controlled_web_search_enabled(), cocos_editor_available) } +/// 工具 kind(wire 值)对应的提示词上限。 +/// +/// 数字只来自客户端资源编辑权威口径(`resource_edit_prompt_max_chars`);未知 kind 直接 +/// panic,避免 schema 与真实校验静默漂移。 +fn resource_tool_prompt_max_chars(kind: &str) -> usize { + DirectResourceGenerationKind::parse(kind) + .unwrap_or_else(|error| panic!("{kind} 不是受支持的媒体资源类型:{error}")) + .prompt_max_chars() +} + +/// `agc_create_or_derive_resource` 顶层 `prompt.maxLength`:本工具所有受支持 kind 的上限最大值。 +/// +/// 仍然保留顶层上限,供忽略 `allOf` / `oneOf` 的调用方使用;逐 kind 的精确上限在分支里声明。 +fn resource_tool_prompt_schema_max_chars() -> usize { + [ + "background-music", + "sound-effect", + "video", + "character-animation", + ] + .into_iter() + .map(resource_tool_prompt_max_chars) + .max() + .unwrap_or(0) +} + fn direct_tools_mcp_specs_for(controlled_web_search: bool, _cocos_editor_available: bool) -> Value { let tools = vec![ json!({ @@ -248,20 +273,19 @@ fn direct_tools_mcp_specs_for(controlled_web_search: bool, _cocos_editor_availab "sliceMode": { "type": "string", "enum": ["connected-components", "grid"], - "default": "connected-components", - "description": "仅 kind=art-spritesheet 生效:connected-components 按透明像素连通域切分,grid 按 gridX×gridY 网格切分" + "description": "仅 kind=art-spritesheet 生效,且必填、没有默认值:需求明确要求等分网格、固定槽位或指定行列数时传 grid,并用 gridX/gridY 传入来自需求本身的行列数;自由排布、数量不定或只要求一张图集时传 connected-components,需要约束素材张数时用 sliceCount。省略、与 kind 不匹配或与 gridX/gridY 互相矛盾时客户端直接拒绝,不会替你选择" }, "gridX": { "type": "integer", "minimum": 1, "maximum": 32, - "description": "grid 模式横向网格数量" + "description": "grid 模式横向网格数量,只能与 sliceMode=grid 同时提供" }, "gridY": { "type": "integer", "minimum": 1, "maximum": 32, - "description": "grid 模式纵向网格数量" + "description": "grid 模式纵向网格数量,只能与 sliceMode=grid 同时提供" } }, "required": ["prompt"], @@ -407,7 +431,8 @@ fn direct_tools_mcp_specs_for(controlled_web_search: bool, _cocos_editor_availab "prompt": { "type": "string", "minLength": 1, - "maxLength": DIRECT_TOOLS_MCP_MAX_RESOURCE_PROMPT_CHARS + "maxLength": resource_tool_prompt_schema_max_chars(), + "description": "资源描述或改造要求。按 kind 有硬上限,超限会被客户端直接拒绝:background-music 最多 140 字符、sound-effect 最多 1900 字符、video / character-animation 最多 4000 字符。图片编辑走 agc_edit_image。" }, "assetName": { "type": "string", @@ -417,17 +442,47 @@ fn direct_tools_mcp_specs_for(controlled_web_search: bool, _cocos_editor_availab } }, "required": ["kind", "mode", "prompt", "assetName"], - "oneOf": [ + "allOf": [ { - "properties": { - "mode": { "const": "create" }, - "kind": { "enum": ["video", "sound-effect", "background-music"] } - }, - "not": { "required": ["sourceLocalAssetId"] } + "oneOf": [ + { + "properties": { + "mode": { "const": "create" }, + "kind": { "enum": ["video", "sound-effect", "background-music"] } + }, + "not": { "required": ["sourceLocalAssetId"] } + }, + { + "properties": { "mode": { "const": "derive" } }, + "required": ["sourceLocalAssetId"] + } + ] }, { - "properties": { "mode": { "const": "derive" } }, - "required": ["sourceLocalAssetId"] + // 逐 kind 声明真实提示词上限,与 resource_edit_prompt_max_chars 同口径。 + "oneOf": [ + { + "properties": { + "kind": { "const": "background-music" }, + "prompt": { "maxLength": resource_tool_prompt_max_chars("background-music") } + }, + "required": ["kind"] + }, + { + "properties": { + "kind": { "const": "sound-effect" }, + "prompt": { "maxLength": resource_tool_prompt_max_chars("sound-effect") } + }, + "required": ["kind"] + }, + { + "properties": { + "kind": { "enum": ["video", "character-animation"] }, + "prompt": { "maxLength": resource_tool_prompt_max_chars("video") } + }, + "required": ["kind"] + } + ] } ], "additionalProperties": false @@ -850,25 +905,14 @@ fn validate_resource_generation_arguments(arguments: &Value) -> Result<(), Strin &["kind", "mode", "sourceLocalAssetId", "prompt", "assetName"], )?; let kind = bounded_tool_string(arguments, "kind", 80)?; - if ![ - "video", - "character-animation", - "sound-effect", - "background-music", - ] - .contains(&kind.as_str()) - { - return Err("工具参数 kind 不是受支持的媒体资源类型".to_string()); - } + let generation_kind = DirectResourceGenerationKind::parse(&kind)?; let mode = bounded_tool_string(arguments, "mode", 16)?; if !["create", "derive"].contains(&mode.as_str()) { return Err("工具参数 mode 必须是 create 或 derive".to_string()); } - let prompt = bounded_tool_string( - arguments, - "prompt", - DIRECT_TOOLS_MCP_MAX_RESOURCE_PROMPT_CHARS, - )?; + // prompt 的形状校验只用信封级上限,真正生效的按 kind 上限由紧随其后的权威判定给出 + // 精确数字;否则通用 4000 会先于按 kind 上限误报成安全边界错误。 + let prompt = bounded_tool_string(arguments, "prompt", DIRECT_TOOLS_MCP_MAX_REQUEST_BYTES)?; bounded_tool_string( arguments, "assetName", @@ -878,8 +922,12 @@ fn validate_resource_generation_arguments(arguments: &Value) -> Result<(), Strin if source.is_some() { bounded_tool_string(arguments, "sourceLocalAssetId", 80)?; } - if kind == "background-music" && prompt.chars().count() > 140 { - return Err("背景音乐提示词必须在 1..=140 字符内".to_string()); + let prompt_max_chars = generation_kind.prompt_max_chars(); + if prompt.chars().count() > prompt_max_chars { + return Err(resource_edit_prompt_limit_error( + &generation_kind.edit_kind(), + prompt_max_chars, + )); } if kind == "character-animation" && mode == "create" { return Err("角色动画必须基于已登记图片资源派生".to_string()); @@ -2344,6 +2392,20 @@ mod tests { image_tool["inputSchema"]["properties"]["sliceMode"]["enum"], json!(["connected-components", "grid"]) ); + assert!( + image_tool["inputSchema"]["properties"]["sliceMode"] + .get("default") + .is_none(), + "sliceMode must not advertise a default" + ); + assert!( + image_tool["inputSchema"]["properties"]["sliceMode"]["description"] + .as_str() + .is_some_and(|description| description.contains("没有默认值") + && description.contains("gridX") + && description.contains("connected-components")), + "sliceMode description must carry the explicit decision requirement" + ); let edit_tool = specs["tools"] .as_array() .expect("tool array") @@ -2756,4 +2818,686 @@ mod tests { "显式 Codex 返回不能再往项目主对话写 legacy 行" ); } + + // --------------------------------------------------------------------------------------- + // 工具层 → 客户端受控工具桥 → 假平台:媒体工具契约的确定性验收。 + // + // 夹具只回答资源编辑链路真正会发的请求,任何未预期请求直接 panic;源图片的 + // binding 在这里预置,因为「上传票据 → OSS 表单上传 → 对象确认 → 登记项目资源」 + // 子链已有专门用例覆盖,本组只钉工具名 / 参数校验 / 出站请求契约。 + // --------------------------------------------------------------------------------------- + + const TOOL_CHAIN_CANVAS_PROJECT_ID: &str = "remote-canvas-project"; + const TOOL_CHAIN_ASSET_FOLDER_ID: &str = "remote-asset-folder"; + const TOOL_CHAIN_ACCESS_TOKEN: &str = "tool-chain-token"; + const TOOL_CHAIN_MEDIA_ROUTE: &str = "/generated/resource-edit-result"; + + fn tool_chain_png() -> Vec { + let mut bytes = Vec::new(); + image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel( + 2, + 2, + image::Rgba([12, 34, 56, 255]), + )) + .write_to( + &mut std::io::Cursor::new(&mut bytes), + image::ImageFormat::Png, + ) + .expect("encode tool chain png"); + bytes + } + + fn tool_chain_mp3() -> Vec { + let mut bytes = b"ID3\x04\x00\x00\x00\x00\x00\x0a".to_vec(); + bytes.extend_from_slice(&[0_u8; 32]); + bytes + } + + fn tool_chain_image_asset(id: &str, local_path: &str) -> GameCreationAppAssetManifestEntry { + GameCreationAppAssetManifestEntry { + id: id.to_string(), + kind: "image".to_string(), + media_type: "image/png".to_string(), + local_path: local_path.to_string(), + image_sequence_frames: None, + image_sequence_duration_ms: None, + category: game_creation_app_asset_category_for_kind("image"), + tags: Vec::new(), + source: GameCreationAppAssetSource { + kind: GameCreationAppAssetSourceKind::Canvas, + canvas_project_id: Some(TOOL_CHAIN_CANVAS_PROJECT_ID.to_string()), + resource_id: Some("editor-resource-hero".to_string()), + asset_object_id: Some("assetobj-hero".to_string()), + task_id: Some("tool-chain-task".to_string()), + prompt: None, + model: None, + generation_route: None, + generation_kind: None, + reference_resource_ids: Vec::new(), + }, + } + } + + fn tool_chain_accept(listener: &std::net::TcpListener) -> std::net::TcpStream { + listener + .set_nonblocking(true) + .expect("set tool chain listener nonblocking"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + loop { + match listener.accept() { + Ok((stream, _)) => { + stream + .set_nonblocking(false) + .expect("restore tool chain stream blocking mode"); + return stream; + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + assert!( + std::time::Instant::now() < deadline, + "等待工具链夹具请求超时" + ); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + Err(error) => panic!("接受工具链夹具请求失败:{error}"), + } + } + } + + fn tool_chain_read_request(stream: &mut std::net::TcpStream) -> String { + use std::io::Read; + + stream + .set_read_timeout(Some(std::time::Duration::from_secs(5))) + .expect("set tool chain read timeout"); + let mut bytes = Vec::new(); + let mut buffer = [0_u8; 4096]; + let (header_end, content_length) = loop { + let read = stream.read(&mut buffer).expect("read tool chain request"); + assert!(read > 0, "工具链夹具请求在请求头结束前关闭"); + bytes.extend_from_slice(&buffer[..read]); + let Some(header_end) = bytes.windows(4).position(|value| value == b"\r\n\r\n") else { + continue; + }; + let header_text = String::from_utf8_lossy(&bytes[..header_end]); + let content_length = header_text + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().ok()) + .flatten() + }) + .unwrap_or(0); + break (header_end + 4, content_length); + }; + while bytes.len() < header_end + content_length { + let read = stream + .read(&mut buffer) + .expect("read tool chain request body"); + assert!(read > 0, "工具链夹具请求在请求体结束前关闭"); + bytes.extend_from_slice(&buffer[..read]); + } + String::from_utf8_lossy(&bytes).into_owned() + } + + fn tool_chain_write_json(stream: &mut std::net::TcpStream, status: &str, body: Value) { + use std::io::Write; + + let body = body.to_string(); + write!( + stream, + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len(), + ) + .expect("write tool chain json response"); + } + + fn tool_chain_write_media(stream: &mut std::net::TcpStream, media_type: &str, bytes: &[u8]) { + use std::io::Write; + + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: {media_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + bytes.len(), + ) + .expect("write tool chain media headers"); + stream + .write_all(bytes) + .expect("write tool chain media bytes"); + } + + /// 假平台:按固定次数回答资源编辑链路的请求,并回放收到的每个请求正文。 + fn tool_chain_spawn_platform( + listener: std::net::TcpListener, + expected_submission: &'static str, + media_type: &'static str, + media: Vec, + request_count: usize, + ) -> ( + std::thread::JoinHandle>, + std::sync::mpsc::Receiver, + ) { + let media_url = format!( + "http://{}{TOOL_CHAIN_MEDIA_ROUTE}", + listener.local_addr().expect("tool chain fixture address") + ); + let (sender, receiver) = std::sync::mpsc::channel(); + let handle = std::thread::spawn(move || { + let mut requests = Vec::new(); + for _ in 0..request_count { + let mut stream = tool_chain_accept(&listener); + let request = tool_chain_read_request(&mut stream); + let request_line = request.lines().next().unwrap_or_default().to_string(); + let route = request_line + .split_whitespace() + .nth(1) + .unwrap_or_default() + .to_string(); + sender.send(request.clone()).ok(); + requests.push(request); + if route.starts_with("/api/editor/projects") { + tool_chain_write_json( + &mut stream, + "200 OK", + json!({"data": {"projects": [{ + "projectId": TOOL_CHAIN_CANVAS_PROJECT_ID, + "title": "工具链远端画布" + }]}}), + ); + } else if route.starts_with("/api/editor/assets/library") { + tool_chain_write_json( + &mut stream, + "200 OK", + json!({"data": {"library": {"folders": [{ + "folderId": TOOL_CHAIN_ASSET_FOLDER_ID, + "label": "工具链远端目录" + }]}}}), + ); + } else if request_line.starts_with(expected_submission) { + tool_chain_write_json( + &mut stream, + "202 Accepted", + json!({"data": { + "operationId": "tool-chain-operation", + "status": "queued", + "pollAfterMs": 0 + }}), + ); + } else if route.starts_with("/api/runtime/external-generation/jobs/") { + tool_chain_write_json( + &mut stream, + "200 OK", + json!({"data": { + "status": "completed", + "result": {"resource": { + "resourceId": "editor-resource-derived", + "objectKey": "generated/resource-edit-result", + "assetObjectId": "assetobj-derived" + }} + }}), + ); + } else if route.starts_with("/api/assets/read-url") { + tool_chain_write_json( + &mut stream, + "200 OK", + json!({"data": {"read": {"signedUrl": media_url}}}), + ); + } else if route.starts_with(TOOL_CHAIN_MEDIA_ROUTE) { + tool_chain_write_media(&mut stream, media_type, &media); + } else { + panic!("工具链夹具收到未预期请求:{request_line}"); + } + } + requests + }); + (handle, receiver) + } + + /// 真实项目 + 真实工具桥 + 真实 Direct 回合身份。 + async fn tool_chain_start( + root: &Path, + ) -> ( + super::super::direct_tool_bridge::DirectToolBridge, + DirectTaonierActiveInvocationGuard, + ) { + let bridge = super::super::direct_tool_bridge::start_direct_tool_bridge(root, false) + .await + .expect("start tool chain bridge"); + let turn = DirectTaonierActiveInvocationGuard::enter(root, "tool-chain-turn") + .expect("arm tool chain direct turn"); + (bridge, turn) + } + + async fn tool_chain_call( + bridge: &super::super::direct_tool_bridge::DirectToolBridge, + root: &Path, + name: &str, + arguments: Value, + ) -> Value { + EXTERNAL_MCP_BRIDGE_URL + .scope( + bridge.url().to_string(), + handle_direct_tools_mcp_request( + root, + json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": { "name": name, "arguments": arguments } + }), + ), + ) + .await + .expect("mcp response") + } + + fn tool_chain_payload(result: &Value) -> Value { + serde_json::from_str( + result["result"]["content"][0]["text"] + .as_str() + .unwrap_or_else(|| panic!("工具返回不是文本包:{result}")), + ) + .unwrap_or_else(|error| panic!("工具返回不是 JSON:{error};{result}")) + } + + /// P1 门禁:工具 schema 的 per-kind 上限、MCP 校验、工具桥校验与客户端权威口径必须是同一个数字。 + #[test] + fn tool_prompt_limits_agree_with_the_client_authority() { + let specs = direct_tools_mcp_specs_for(false, false); + let resource_tool = specs["tools"] + .as_array() + .expect("tool array") + .iter() + .find(|tool| tool["name"] == "agc_create_or_derive_resource") + .expect("resource tool"); + let schema_branches = resource_tool["inputSchema"]["allOf"] + .as_array() + .and_then(|all_of| all_of.get(1)) + .and_then(|branch| branch["oneOf"].as_array()) + .expect("per-kind prompt limit branches"); + + for (tool_kind, expected_kind) in [ + ( + "background-music", + LocalProjectResourceEditKind::BackgroundMusic, + ), + ("sound-effect", LocalProjectResourceEditKind::SoundEffect), + ("video", LocalProjectResourceEditKind::Video), + ( + "character-animation", + LocalProjectResourceEditKind::CharacterAnimation, + ), + ] { + let authority = resource_edit_prompt_max_chars(&expected_kind); + let generation_kind = DirectResourceGenerationKind::parse(tool_kind) + .unwrap_or_else(|error| panic!("{tool_kind}: {error}")); + assert_eq!( + generation_kind.edit_kind(), + expected_kind, + "{tool_kind} 必须映射到同一客户端类型" + ); + assert_eq!( + generation_kind.prompt_max_chars(), + authority, + "{tool_kind} 的工具桥上限必须来自客户端权威口径" + ); + let branch_limit = schema_branches + .iter() + .find_map(|branch| { + let kind = &branch["properties"]["kind"]; + let covers_kind = kind["const"].as_str() == Some(tool_kind) + || kind["enum"].as_array().is_some_and(|values| { + values.iter().any(|value| value.as_str() == Some(tool_kind)) + }); + covers_kind.then(|| { + branch["properties"]["prompt"]["maxLength"] + .as_u64() + .expect("branch prompt maxLength") + }) + }) + .unwrap_or_else(|| panic!("{tool_kind} 缺少按 kind 声明的提示词上限")); + assert_eq!( + branch_limit as usize, authority, + "{tool_kind} 的 schema 上限必须等于真实生效上限" + ); + assert!( + resource_tool["inputSchema"]["properties"]["prompt"]["description"] + .as_str() + .is_some_and(|text| text.contains(&authority.to_string())), + "{tool_kind} 的上限必须写进 prompt 描述:{authority}" + ); + let over_limit = "字".repeat(authority + 1); + let error = validate_resource_generation_arguments(&json!({ + "kind": tool_kind, + "mode": "create", + "prompt": over_limit, + "assetName": "上限测试" + })) + .expect_err("超过按 kind 上限的提示词必须被拒绝"); + assert!( + error.contains(&authority.to_string()), + "{tool_kind} 的拒绝文案必须带上真实上限:{error}" + ); + } + + // 图片编辑走独立工具,其上限同样是图片类型的权威口径。 + let image_authority = + resource_edit_prompt_max_chars(&LocalProjectResourceEditKind::ImageReference); + assert_eq!(image_authority, DIRECT_TOOLS_MCP_MAX_IMAGE_PROMPT_CHARS); + let edit_tool = specs["tools"] + .as_array() + .expect("tool array") + .iter() + .find(|tool| tool["name"] == "agc_edit_image") + .expect("image edit tool"); + assert_eq!( + edit_tool["inputSchema"]["properties"]["prompt"]["maxLength"], + json!(image_authority) + ); + } + + /// 源资源未登记时必须给出可执行的下一步,而不是只报「不属于已登记资源」。 + #[tokio::test] + async fn unregistered_source_reports_the_registration_follow_up_tools() { + let temporary = crate::tests::canonical_test_tempdir("direct-tools-unregistered-source-"); + let root = temporary.path(); + init_local_game_project_at(root, "direct-tools-unregistered-source", "未登记源资源提示") + .expect("init project"); + let (bridge, _turn_arm) = tool_chain_start(root).await; + let _turn = bridge.begin_user_turn().expect("begin client turn"); + + let result = tool_chain_call( + &bridge, + root, + "agc_edit_image", + json!({ + "sourceLocalAssetId": "missing-image", + "prompt": "把这张图改成夜景", + "assetName": "缺失源图编辑版" + }), + ) + .await; + + assert_eq!(result["result"]["isError"], true, "{result}"); + let message = result["result"]["content"][0]["text"] + .as_str() + .expect("tool error text"); + assert!( + message.contains("agc_list_registered_assets"), + "未登记源资源必须指向已登记资源查询工具:{message}" + ); + assert!( + message.contains("agc_import_account_assets"), + "未登记源资源必须指向登记工具:{message}" + ); + } + + /// 工具层 → 桥 → 假平台:图片快速编辑必须真的落到站内 `/api/editor/images/edits`。 + #[tokio::test] + async fn edit_image_tool_reaches_the_platform_image_edit_route() { + let temporary = crate::tests::canonical_test_tempdir("direct-tools-edit-image-"); + let root = temporary.path(); + init_local_game_project_at(root, "direct-tools-edit-image", "图片快速编辑工具链") + .expect("init project"); + let source_bytes = tool_chain_png(); + std::fs::create_dir_all(root.join("assets")).expect("create assets dir"); + std::fs::write(root.join("assets/hero.png"), &source_bytes).expect("write source png"); + let mut manifest = read_existing_manifest_for_project(root).expect("read manifest"); + manifest + .assets + .push(tool_chain_image_asset("hero-image", "assets/hero.png")); + write_manifest(&root.join(".agent/manifest.json"), &manifest).expect("write manifest"); + + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind fixture"); + let base_url = format!("http://{}", listener.local_addr().expect("fixture address")); + let (server, _requests) = tool_chain_spawn_platform( + listener, + "POST /api/editor/images/edits ", + "image/png", + tool_chain_png(), + 6, + ); + let _session = crate::platform_session::install_test_platform_session( + "tool-chain-owner", + TOOL_CHAIN_ACCESS_TOKEN, + &base_url, + ); + let session = current_platform_session().expect("platform session"); + let access = + ExternalEditorBindingAccess::new(&base_url, &session.access_token, Some(&session)) + .expect("account access"); + let principal = external_editor_binding_principal(&access).expect("account principal"); + let project_binding = new_external_editor_project_binding( + &manifest.project_id, + &principal, + TOOL_CHAIN_CANVAS_PROJECT_ID, + TOOL_CHAIN_ASSET_FOLDER_ID, + unix_timestamp(), + ) + .expect("project binding"); + write_external_editor_project_binding_at(root, &project_binding) + .expect("write project binding"); + let source_identity = new_external_editor_source_identity( + "hero-image", + &format!("{:x}", Sha256::digest(&source_bytes)), + "image/png", + "image", + ) + .expect("source identity"); + let resource_binding = new_external_editor_resource_binding( + &manifest.project_id, + &principal, + TOOL_CHAIN_CANVAS_PROJECT_ID, + &source_identity, + Some("editor-resource-hero"), + "source/hero.png", + "assetobj-hero", + Some(2), + Some(2), + unix_timestamp(), + ) + .expect("resource binding"); + write_external_editor_resource_binding_at(root, &resource_binding) + .expect("write resource binding"); + + let (bridge, _turn_arm) = tool_chain_start(root).await; + let _turn = bridge.begin_user_turn().expect("begin client turn"); + let result = tool_chain_call( + &bridge, + root, + "agc_edit_image", + json!({ + "sourceLocalAssetId": "hero-image", + "prompt": "把这张角色图改成夜景霓虹配色", + "assetName": "英雄-夜霓虹" + }), + ) + .await; + let requests = server.join().expect("join tool chain fixture"); + + assert_eq!(result["result"]["isError"], false, "{result}"); + let payload = tool_chain_payload(&result); + assert_eq!(payload["status"], "completed", "{payload}"); + assert_eq!(payload["kind"], "image"); + assert_eq!(payload["mode"], "derive"); + assert_eq!( + payload["resource"]["referenceResourceIds"], + json!(["local-asset:hero-image"]) + ); + let local_path = payload["resource"]["localPath"] + .as_str() + .expect("derived local path"); + assert!( + root.join(local_path).is_file(), + "派生图片必须落盘:{local_path}" + ); + + assert_eq!(requests.len(), 6, "{requests:?}"); + let submission = requests + .iter() + .find(|request| request.starts_with("POST /api/editor/images/edits ")) + .unwrap_or_else(|| panic!("缺少图片编辑提交请求:{requests:?}")); + let submission_lower = submission.to_ascii_lowercase(); + assert!(submission_lower.contains(&format!( + "authorization: bearer {}", + TOOL_CHAIN_ACCESS_TOKEN.to_ascii_lowercase() + ))); + assert!(submission_lower.contains("idempotency-key:")); + assert!(submission.contains("\"sourceReferenceId\":\"editor-resource-hero\"")); + assert!(submission.contains("\"assetLabel\":\"英雄-夜霓虹\"")); + assert!(submission.contains(&format!("\"projectId\":\"{TOOL_CHAIN_CANVAS_PROJECT_ID}\""))); + assert!(submission.contains(&format!( + "\"assetFolderId\":\"{TOOL_CHAIN_ASSET_FOLDER_ID}\"" + ))); + assert!( + !submission.contains("assetKind"), + "图片编辑请求不得回填 assetKind:{submission}" + ); + assert!(requests.iter().any(|request| request + .starts_with("GET /api/runtime/external-generation/jobs/tool-chain-operation "))); + assert!(requests + .iter() + .any(|request| request.starts_with("GET /api/assets/read-url?"))); + } + + /// 超过已发布上限的背景音乐提示词必须在工具层就被拒绝,且一次桥请求都不发出。 + #[tokio::test] + async fn background_music_prompt_over_the_limit_is_rejected_before_any_bridge_call() { + let temporary = crate::tests::canonical_test_tempdir("direct-tools-bgm-limit-"); + let root = temporary.path(); + init_local_game_project_at(root, "direct-tools-bgm-limit", "背景音乐上限工具链") + .expect("init project"); + let authority = + resource_edit_prompt_max_chars(&LocalProjectResourceEditKind::BackgroundMusic); + + let result = EXTERNAL_MCP_BRIDGE_URL + .scope( + // 故意指向没有服务监听的 loopback 地址:一旦真的发出桥请求,报错文案会变成连接失败。 + "http://127.0.0.1:1/tool-dead".to_string(), + handle_direct_tools_mcp_request( + root, + json!({ + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": { + "name": "agc_create_or_derive_resource", + "arguments": { + "kind": "background-music", + "mode": "create", + "prompt": "字".repeat(authority + 1), + "assetName": "紧张战斗背景音乐" + } + } + }), + ), + ) + .await + .expect("mcp response"); + + assert_eq!(result["result"]["isError"], true, "{result}"); + let message = result["result"]["content"][0]["text"] + .as_str() + .expect("tool error text"); + assert!( + message.contains(&authority.to_string()) && message.contains("背景音乐"), + "必须按发布上限拒绝并说明类型:{message}" + ); + assert!( + !message.contains("连接客户端受控工具桥失败"), + "上限拒绝必须发生在桥请求之前:{message}" + ); + } + + /// 工具层 → 桥 → 假平台:背景音乐 create 必须落到站内音频生成路由。 + #[tokio::test] + async fn background_music_tool_reaches_the_platform_audio_route() { + let temporary = crate::tests::canonical_test_tempdir("direct-tools-bgm-route-"); + let root = temporary.path(); + init_local_game_project_at(root, "direct-tools-bgm-route", "背景音乐工具链") + .expect("init project"); + let manifest = read_existing_manifest_for_project(root).expect("read manifest"); + + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind fixture"); + let base_url = format!("http://{}", listener.local_addr().expect("fixture address")); + let (server, _requests) = tool_chain_spawn_platform( + listener, + "POST /api/editor/audios/background-music/generations ", + "audio/mpeg", + tool_chain_mp3(), + 6, + ); + let _session = crate::platform_session::install_test_platform_session( + "tool-chain-owner", + TOOL_CHAIN_ACCESS_TOKEN, + &base_url, + ); + let session = current_platform_session().expect("platform session"); + let access = + ExternalEditorBindingAccess::new(&base_url, &session.access_token, Some(&session)) + .expect("account access"); + let principal = external_editor_binding_principal(&access).expect("account principal"); + let project_binding = new_external_editor_project_binding( + &manifest.project_id, + &principal, + TOOL_CHAIN_CANVAS_PROJECT_ID, + TOOL_CHAIN_ASSET_FOLDER_ID, + unix_timestamp(), + ) + .expect("project binding"); + write_external_editor_project_binding_at(root, &project_binding) + .expect("write project binding"); + + let (bridge, _turn_arm) = tool_chain_start(root).await; + let _turn = bridge.begin_user_turn().expect("begin client turn"); + let result = tool_chain_call( + &bridge, + root, + "agc_create_or_derive_resource", + json!({ + "kind": "background-music", + "mode": "create", + "prompt": "紧张但克制的八位机战斗循环,鼓点清晰", + "assetName": "紧张战斗背景音乐" + }), + ) + .await; + let requests = server.join().expect("join tool chain fixture"); + + assert_eq!(result["result"]["isError"], false, "{result}"); + let payload = tool_chain_payload(&result); + assert_eq!(payload["status"], "completed", "{payload}"); + assert_eq!(payload["kind"], "background-music"); + assert_eq!(payload["mode"], "create"); + assert_eq!(payload["resource"]["mediaType"], "audio/mpeg"); + + assert_eq!(requests.len(), 6, "{requests:?}"); + let submission = requests + .iter() + .find(|request| { + request.starts_with("POST /api/editor/audios/background-music/generations ") + }) + .unwrap_or_else(|| panic!("缺少背景音乐提交请求:{requests:?}")); + assert!(submission.to_ascii_lowercase().contains(&format!( + "authorization: bearer {}", + TOOL_CHAIN_ACCESS_TOKEN.to_ascii_lowercase() + ))); + assert!(submission.contains("\"makeInstrumental\":true")); + assert!(submission.contains("紧张但克制的八位机战斗循环,鼓点清晰")); + assert!(submission.contains("\"assetLabel\":\"紧张战斗背景音乐\"")); + let body: Value = serde_json::from_str( + submission + .split("\r\n\r\n") + .nth(1) + .unwrap_or_else(|| panic!("背景音乐提交缺少请求体:{submission}")), + ) + .expect("background music submission body"); + let composed = body["gptDescriptionPrompt"] + .as_str() + .expect("composed background music prompt"); + assert!( + composed.starts_with("生成新音频;目标:") && composed.chars().count() < 200, + "create 模式必须使用无源前缀并落在现役接口上限内:{composed}" + ); + } } diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/canvas_generation.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/canvas_generation.rs index 36409b5e9..c3b72acbb 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/generation/canvas_generation.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/generation/canvas_generation.rs @@ -1681,6 +1681,8 @@ pub(in crate::agent) struct PreparedPlatformArtAssetGeneration { slice_warning: Option, slices: Vec, spritesheet_slice_mode: Option, + spritesheet_grid_x: Option, + spritesheet_grid_y: Option, generation_route: String, generation_kind: String, reference_resource_ids: Vec, @@ -2841,6 +2843,31 @@ async fn generate_platform_art_asset_with_runtime_options_and_retention_at( if require_slices && options.asset_kind != "art-spritesheet" { return Err("严格游戏切片生成只允许 art-spritesheet 资产类型".to_string()); } + // 切分模式没有默认值:图集生成必须在客户端显式声明,缺失或自相矛盾都在付费提交前失败。 + if options.asset_kind == "art-spritesheet" { + let Some(slice_mode) = options.slice_mode.as_deref() else { + return Err( + "图集生成必须显式声明 sliceMode:等分网格或固定槽位用 grid 并提供 gridX/gridY,自由排布用 connected-components" + .to_string(), + ); + }; + if !matches!(slice_mode, "connected-components" | "grid") { + return Err(format!("图集切分模式不受支持:{slice_mode}")); + } + if slice_mode == "grid" && (options.grid_x.is_none() || options.grid_y.is_none()) { + return Err("sliceMode=grid 必须同时提供 gridX 与 gridY".to_string()); + } + if slice_mode == "connected-components" + && (options.grid_x.is_some() || options.grid_y.is_some()) + { + return Err( + "sliceMode=connected-components 不接受 gridX/gridY:网格尺寸只能与 grid 同时声明" + .to_string(), + ); + } + } else if options.slice_mode.is_some() || options.grid_x.is_some() || options.grid_y.is_some() { + return Err("sliceMode/gridX/gridY 仅对 art-spritesheet 生效".to_string()); + } if super::external_generation_state::is_standalone_platform_art_generation_runtime_context( runtime_context, ) && game_creator_agent_runtime_external_generation_exists( @@ -3474,6 +3501,16 @@ pub(in crate::agent) async fn request_platform_art_asset_with_runtime_options_at } else { None }; + let spritesheet_grid_x = if is_canonical_art_spritesheet { + json_u32_field(generated, "gridX") + } else { + None + }; + let spritesheet_grid_y = if is_canonical_art_spritesheet { + json_u32_field(generated, "gridY") + } else { + None + }; let resource_id = json_string_field(resource, "resourceId"); let task_id = if is_canonical_art_spritesheet { consistent_canvas_task_id("External Editor 图集主图", &[generated, resource, asset])? @@ -3532,6 +3569,8 @@ pub(in crate::agent) async fn request_platform_art_asset_with_runtime_options_at slice_warning, slices, spritesheet_slice_mode, + spritesheet_grid_x, + spritesheet_grid_y, generation_route, generation_kind, reference_resource_ids, @@ -6862,6 +6901,50 @@ impl PlatformArtSliceContractRollback { } } +fn json_u32_field(value: &serde_json::Value, field: &str) -> Option { + value + .get(field) + .and_then(serde_json::Value::as_u64) + .and_then(|value| u32::try_from(value).ok()) +} + +/// 严格图集必须在请求与响应两端证明同一个切分声明:请求显式声明的模式必须被平台 +/// 原样回显,grid 的行列数也必须一致;否则本地无法判断实际按哪种方式切片。 +fn validate_platform_art_spritesheet_slice_declaration_matches_response( + options: &PlatformArtAssetGenerationOptions, + response_slice_mode: Option<&str>, + response_grid_x: Option, + response_grid_y: Option, +) -> Result<(), String> { + let requested = options + .slice_mode + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .ok_or_else(|| "图集生成缺少显式 sliceMode 声明,已拒绝提交严格图集".to_string())?; + let responded = response_slice_mode + .map(str::trim) + .filter(|value| !value.is_empty()) + .ok_or_else(|| { + "平台图集响应没有回显 sliceMode,无法证明切分方式与请求一致,已在本地落盘前拒绝提交" + .to_string() + })?; + if responded != requested { + return Err(format!( + "平台图集响应回显的 sliceMode={responded} 与请求 {requested} 不一致,已拒绝提交" + )); + } + if requested == "grid" + && (response_grid_x != options.grid_x || response_grid_y != options.grid_y) + { + return Err(format!( + "平台图集响应回显的 gridX/gridY={:?}/{:?} 与请求 {:?}/{:?} 不一致,已拒绝提交", + response_grid_x, response_grid_y, options.grid_x, options.grid_y + )); + } + Ok(()) +} + fn validate_strict_platform_art_spritesheet_contract( slices: &[PreparedPlatformArtAssetSlice], slice_warning: Option<&str>, @@ -6872,7 +6955,6 @@ fn validate_strict_platform_art_spritesheet_contract( task_id: Option<&str>, generation_route: &str, generation_kind: &str, - spritesheet_slice_mode: Option<&str>, reference_resource_ids: &[String], has_transparent_pixels: bool, has_visible_pixels: bool, @@ -6913,7 +6995,6 @@ fn validate_strict_platform_art_spritesheet_contract( { return Err("strict spritesheet 图集生成 route/kind 与严格图集合同不一致".to_string()); } - let _requested_slice_mode = spritesheet_slice_mode; if reference_resource_ids.len() != 1 || reference_resource_ids[0].trim().is_empty() || reference_resource_ids[0].trim() == resource_id @@ -7461,6 +7542,15 @@ fn commit_strict_platform_art_slices_at( "obstacles-and-scene", "feedback-effects", ]; + // 标准图集按用途位置映射到固定路径;数量不一致时必须失败关闭,不能靠 zip 静默截断 + // 或写入用途错位的切片清单。 + if slices.len() != usages.len() { + return Err(format!( + "标准美术图集必须正好包含 {} 张 canonical 切片,平台返回了 {} 张,已拒绝写入以避免用途错位", + usages.len(), + slices.len() + )); + } let mut generated = Vec::with_capacity(slices.len()); let mut registrations = Vec::with_capacity(slices.len()); let mut content_sha256s = Vec::with_capacity(slices.len()); @@ -7676,6 +7766,8 @@ fn commit_prepared_platform_art_asset_with_before_replace_hook( mut slice_warning, slices, spritesheet_slice_mode, + spritesheet_grid_x, + spritesheet_grid_y, generation_route, generation_kind, reference_resource_ids, @@ -7685,6 +7777,12 @@ fn commit_prepared_platform_art_asset_with_before_replace_hook( recover_existing_outputs, } = prepared; if require_complete_core_slices { + validate_platform_art_spritesheet_slice_declaration_matches_response( + options, + spritesheet_slice_mode.as_deref(), + spritesheet_grid_x, + spritesheet_grid_y, + )?; validate_strict_platform_art_spritesheet_contract( &slices, slice_warning.as_deref(), @@ -7695,7 +7793,6 @@ fn commit_prepared_platform_art_asset_with_before_replace_hook( task_id.as_deref(), &generation_route, &generation_kind, - spritesheet_slice_mode.as_deref(), &reference_resource_ids, spritesheet_has_transparent_pixels, spritesheet_has_visible_pixels, @@ -8058,6 +8155,9 @@ fn commit_prepared_platform_art_asset_with_before_replace_hook( })).collect::>(), "generationRoute": generation_route, "generationKind": generation_kind, + "sliceMode": spritesheet_slice_mode.clone(), + "gridX": spritesheet_grid_x, + "gridY": spritesheet_grid_y, "referenceResourceIds": reference_resource_ids, }), ); @@ -8067,6 +8167,9 @@ fn commit_prepared_platform_art_asset_with_before_replace_hook( Ok(GeneratedPlatformArtAsset { asset: registered, slices: generated_slices, + slice_mode: spritesheet_slice_mode.or_else(|| options.slice_mode.clone()), + grid_x: spritesheet_grid_x.or(options.grid_x), + grid_y: spritesheet_grid_y.or(options.grid_y), resource_id, asset_object_id, task_id, @@ -10161,7 +10264,6 @@ mod canvas_generation_tests { Some("spritesheet-task"), "/api/external/v1/editor/icon-spritesheets/generations", "icon-spritesheet", - None, &["art-spec-resource".to_string()], true, true, @@ -10186,7 +10288,6 @@ mod canvas_generation_tests { None, "route", "kind", - None, &[], false, false, @@ -10243,7 +10344,6 @@ mod canvas_generation_tests { Some("spritesheet-task"), "/api/external/v1/editor/icon-spritesheets/generations", "icon-spritesheet", - Some("grid"), &["art-spec-resource".to_string()], true, true, @@ -13043,7 +13143,7 @@ mod canvas_generation_tests { asset_label: "游戏首版核心美术素材".to_string(), replace_existing: true, slice_count: None, - slice_mode: None, + slice_mode: Some("connected-components".to_string()), grid_x: None, grid_y: None, reference_asset_ids: Vec::new(), @@ -13078,7 +13178,9 @@ mod canvas_generation_tests { warning: None, slice_warning: None, slices: Vec::new(), - spritesheet_slice_mode: Some("grid".to_string()), + spritesheet_slice_mode: Some("connected-components".to_string()), + spritesheet_grid_x: None, + spritesheet_grid_y: None, generation_route: "/api/external/v1/editor/icon-spritesheets/generations".to_string(), generation_kind: "icon-spritesheet".to_string(), reference_resource_ids: vec!["art-spec-resource".to_string()], @@ -13402,7 +13504,9 @@ mod canvas_generation_tests { warning: None, slice_warning: None, slices, - spritesheet_slice_mode: Some("grid".to_string()), + spritesheet_slice_mode: Some("connected-components".to_string()), + spritesheet_grid_x: None, + spritesheet_grid_y: None, generation_route: "/api/external/v1/editor/icon-spritesheets/generations".to_string(), generation_kind: "icon-spritesheet".to_string(), reference_resource_ids: vec!["art-spec-resource".to_string()], diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_tools/media.rs b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_tools/media.rs index 1928a439c..7f49ba4ae 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_tools/media.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent/runtime_tools/media.rs @@ -700,6 +700,53 @@ pub(in crate::agent) async fn observe_agent_runtime_platform_art_asset_generatio detail: None, }; } + // 切分模式没有默认值:图集必须显式声明,且声明必须与 assetKind 和网格参数自洽。 + if options.asset_kind == "art-spritesheet" { + if options.slice_mode.is_none() { + return AgentRuntimeToolObservation { + tool: "canvas.asset_generate".to_string(), + status: "failed".to_string(), + summary: "assetKind=art-spritesheet 必须显式声明 sliceMode,没有默认值:需求要求等分网格、固定槽位或指定行列数时用 grid 并提供 gridX/gridY;自由排布时用 connected-components" + .to_string(), + detail: None, + }; + } + if options.slice_mode.as_deref() == Some("connected-components") + && (options.grid_x.is_some() || options.grid_y.is_some()) + { + return AgentRuntimeToolObservation { + tool: "canvas.asset_generate".to_string(), + status: "failed".to_string(), + summary: + "sliceMode=connected-components 不接受 gridX/gridY:网格尺寸只能与 grid 同时声明" + .to_string(), + detail: None, + }; + } + if options.slice_mode.as_deref() == Some("grid") && options.slice_count.is_some() { + return AgentRuntimeToolObservation { + tool: "canvas.asset_generate".to_string(), + status: "failed".to_string(), + summary: "sliceMode=grid 的素材张数由 gridX×gridY 决定,不接受 sliceCount" + .to_string(), + detail: None, + }; + } + } else if options.slice_mode.is_some() + || options.grid_x.is_some() + || options.grid_y.is_some() + || options.slice_count.is_some() + { + return AgentRuntimeToolObservation { + tool: "canvas.asset_generate".to_string(), + status: "failed".to_string(), + summary: format!( + "sliceMode/gridX/gridY/sliceCount 仅对 assetKind=art-spritesheet 生效,当前 assetKind={}", + options.asset_kind + ), + detail: None, + }; + } if !agent_runtime_canvas_asset_kind_is_supported(&options.asset_kind) { return AgentRuntimeToolObservation { tool: "canvas.asset_generate".to_string(), diff --git a/apps/ai-game-creator-shell/src-tauri/src/agent_native_tools.rs b/apps/ai-game-creator-shell/src-tauri/src/agent_native_tools.rs index 45ba5c505..2240b3341 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/agent_native_tools.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/agent_native_tools.rs @@ -1036,7 +1036,7 @@ fn runtime_tool_description(tool: &str) -> &'static str { "preview.validate" => "用真实浏览器验证桌面和移动预览并保存证据。", "image.inspect" => "让视觉模型检查一至两张项目内图片。", "canvas.asset_generate" => { - "通过已配置的 External Editor API 按项目需求生成图片或图集并登记到画布、素材库和项目 assets;可使用已登记资源作为参考,也可通过 sliceCount 指定图集切片数量。" + "通过已配置的 External Editor API 按项目需求生成图片或图集并登记到画布、素材库和项目 assets;可使用已登记资源作为参考。assetKind=art-spritesheet 时 sliceMode 必填且没有默认值:需求要求等分网格、固定槽位或指定行列数时用 grid 并提供来自需求本身的 gridX/gridY;自由排布、数量不定或只要求一张图集时用 connected-components,可用 sliceCount 约束素材张数;其它 assetKind 不得携带 sliceMode/gridX/gridY。" } "ui.workflow.run" => { "先用 discover 从受控 game/ui-pages.json 或页面声明标记自动发现全部功能页面,再把已登记 ui-prototype 与每个页面的设计图桥接成独立 UI JSON State;可同时载入已登记图片、图标和项目字体,执行 Provider 结构识别、多树合并与分批组件绑定、回读阶段,并且只有所有页面已绑定且已应用到 game/ 后才允许 finalize。项目根目录由 Runtime 注入,模型不得传入宿主路径。" @@ -1311,7 +1311,7 @@ fn runtime_tool_input_schema(tool: &str) -> Value { asset_kinds.push(Value::Null); json!({ "type": "object", - "required": ["prompt", "outputPath", "aspectRatio", "imageSize", "assetKind", "assetLabel", "replaceExisting"], + "required": ["prompt", "outputPath", "aspectRatio", "imageSize", "assetKind", "assetLabel", "replaceExisting", "sliceMode", "gridX", "gridY", "sliceCount"], "additionalProperties": false, "properties": { "prompt": { "type": "string", "minLength": 1, "maxLength": 4000 }, @@ -1320,7 +1320,11 @@ fn runtime_tool_input_schema(tool: &str) -> Value { "imageSize": { "type": ["string", "null"], "enum": ["0.5K", "1K", "2K", null] }, "assetKind": { "type": ["string", "null"], "enum": asset_kinds }, "assetLabel": { "type": ["string", "null"], "maxLength": 80 }, - "replaceExisting": { "type": "boolean" } + "replaceExisting": { "type": "boolean" }, + "sliceMode": { "type": ["string", "null"], "enum": ["connected-components", "grid", null], "description": "仅 assetKind=art-spritesheet 生效且必填,没有默认值:等分网格或固定槽位用 grid,自由排布用 connected-components" }, + "gridX": { "type": ["integer", "null"], "minimum": 1, "maximum": 32, "description": "只与 sliceMode=grid 同时提供" }, + "gridY": { "type": ["integer", "null"], "minimum": 1, "maximum": 32, "description": "只与 sliceMode=grid 同时提供" }, + "sliceCount": { "type": ["integer", "null"], "minimum": 1, "maximum": 256, "description": "只与 sliceMode=connected-components 同时提供,用于约束目标素材张数" } } }) } diff --git a/apps/ai-game-creator-shell/src-tauri/src/commands.rs b/apps/ai-game-creator-shell/src-tauri/src/commands.rs index c5ceba53a..83920e1c8 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/commands.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/commands.rs @@ -4656,7 +4656,10 @@ pub(crate) fn prepare_local_project_asset_generation( .unwrap_or_else(|| LOCAL_PROJECT_ASSET_DEFAULT_ASSET_NAME.to_string()), replace_existing: false, slice_count: None, - slice_mode: None, + // 切分模式没有默认值:GUI 快速编辑只按自由排布生成图集,因此仅在 art-spritesheet + // 时显式声明连通域切分;等分网格或固定槽位需求由外部 API 显式传 grid + gridX/gridY。 + slice_mode: (asset_kind == "art-spritesheet") + .then(|| "connected-components".to_string()), grid_x: None, grid_y: None, reference_asset_ids, diff --git a/apps/ai-game-creator-shell/src-tauri/src/config.rs b/apps/ai-game-creator-shell/src-tauri/src/config.rs index 95c7726f6..87608cc7d 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/config.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/config.rs @@ -1198,6 +1198,22 @@ pub(crate) fn prepare_game_creator_project_root_for_read( { WindowsAclRepairScope::UserSelected } else { + #[cfg(all(windows, test))] + if windows_test_temp_path_needs_owner_initialization(path, is_directory) { + // 测试夹具:在提权 shell 里,系统临时目录下新建的目录默认所有者是 + // Administrators 组而不是当前 TokenUser,测试进程无法提权改所有者。 + // 该目录由当前测试进程创建,因此按“本调用创建的对象”初始化所有者后 + // 重试;其它越权所有者、以及临时目录之外的路径仍然失败关闭。 + if windows_path_is_under_test_temp_dir(path) { + secure_windows_game_creator_path_for_current_user_with_owner_policy( + path, + is_directory, + true, + true, + )?; + return Ok(true); + } + } return secure_windows_game_creator_path_for_current_user(path, is_directory, true) .map(|_| true); }; @@ -1720,7 +1736,7 @@ pub(crate) fn prepare_game_creator_private_path_for_read( true, ) } else { - secure_windows_game_creator_path_for_current_user(path, is_directory, true) + verify_game_creator_private_path_or_test_temp_owner(path, is_directory) }; return result.map(|_| true).map_err(|repair_error| { if game_creator_private_path_allows_auto_elevation(path) { @@ -1763,7 +1779,7 @@ pub(crate) fn prepare_game_creator_private_path_for_read( } else { // User-selected external files are never silently adopted. Keep the // strict owner/DACL check, but do not escalate an arbitrary path. - secure_windows_game_creator_path_for_current_user(path, is_directory, true)?; + verify_game_creator_private_path_or_test_temp_owner(path, is_directory)?; } Ok(true) } @@ -2114,6 +2130,68 @@ pub(crate) fn validate_game_creator_runtime_config_dir_outside_project( Ok(()) } +/// 测试夹具专用:判断某个已存在的项目根是否只是“系统临时目录下所有者不是当前用户”。 +/// +/// 部分 Windows 主机(例如以提权 shell 运行测试)在 `%TEMP%` 下新建的目录,默认所有者是 +/// `BUILTIN\Administrators` 组而不是当前 TokenUser;测试进程无法提权改所有者,于是严格 +/// 校验会拒绝一个由测试自己创建、且确实位于系统临时目录的目录。只有测试构建、路径位于 +/// 系统临时目录、并且失败原因确实是所有者不匹配时才返回 true;临时目录之外的越权所有者 +/// 继续失败关闭。 +#[cfg(all(windows, test))] +fn windows_test_temp_path_needs_owner_initialization(path: &Path, is_directory: bool) -> bool { + if !path.is_absolute() { + return false; + } + match secure_windows_game_creator_path_for_current_user(path, is_directory, true) { + Ok(()) => false, + Err(error) => { + error.contains("安全对象不属于当前用户") && windows_path_is_under_test_temp_dir(path) + } + } +} + +/// 严格校验一个既有私有对象;测试构建下对系统临时目录内的所有者偏差做一次性所有者 +/// 初始化重试,其余情况保持严格失败关闭。 +#[cfg(windows)] +fn verify_game_creator_private_path_or_test_temp_owner( + path: &Path, + is_directory: bool, +) -> Result<(), String> { + #[cfg(test)] + if windows_test_temp_path_needs_owner_initialization(path, is_directory) { + return secure_windows_game_creator_path_for_current_user_with_owner_policy( + path, + is_directory, + true, + true, + ); + } + secure_windows_game_creator_path_for_current_user(path, is_directory, true) +} + +#[cfg(all(windows, test))] +fn windows_path_is_under_test_temp_dir(path: &Path) -> bool { + let normalize = |value: &Path| { + value + .to_string_lossy() + .replace('/', "\\") + .trim_end_matches('\\') + .to_ascii_lowercase() + }; + let temp_dir = std::env::temp_dir(); + let mut roots = vec![normalize(&temp_dir)]; + if let Ok(canonical) = temp_dir.canonicalize() { + let root = normalize(&canonical); + if !roots.contains(&root) { + roots.push(root); + } + } + let candidate = normalize(path); + roots + .iter() + .any(|root| candidate == *root || candidate.starts_with(&format!("{root}\\"))) +} + #[cfg(windows)] pub(crate) fn secure_windows_game_creator_path_for_current_user( path: &Path, 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 fe77f4532..60d3113a3 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。 @@ -277,6 +106,7 @@ mod preview; mod process_session; mod process_session_bridge; mod project; +mod project_snapshot; mod provider_handoff; mod provider_retry; mod repository_context; @@ -284,6 +114,7 @@ mod resource_inspect; mod resource_preview_scheduler; mod runner; mod swarm_cli; +mod template_library; mod tool_plan_handoff; mod user_input; mod windows; @@ -318,11 +149,13 @@ use plugin_host::{ use preview::*; use process_session::*; use project::*; +use project_snapshot::*; use repository_context::*; use resource_inspect::*; use resource_preview_scheduler::*; use runner::*; use swarm_cli::*; +use template_library::*; use user_input::*; use windows::*; #[tauri::command] @@ -1279,6 +1112,9 @@ struct GeneratedPlatformArtAssetSlice { struct GeneratedPlatformArtAsset { asset: UploadLocalAssetResult, slices: Vec, + slice_mode: Option, + grid_x: Option, + grid_y: Option, resource_id: Option, asset_object_id: Option, task_id: Option, @@ -1561,7 +1397,7 @@ const DEFAULT_GAME_CREATOR_LLM_REASONING_EFFORT: &str = "high"; const DEFAULT_GAME_CREATOR_LLM_CONTEXT_WINDOW_TOKENS: u64 = 128_000; const DEFAULT_GAME_CREATOR_LLM_AUTO_COMPACT_TOKEN_LIMIT: u64 = 64_000; const DEFAULT_GAME_CREATOR_LLM_TOOL_OUTPUT_TOKEN_LIMIT: u64 = 12_000; -const DEFAULT_GAME_CREATOR_LLM_MAX_RETRIES: u32 = 2; +const DEFAULT_GAME_CREATOR_LLM_MAX_RETRIES: u32 = 10; fn default_game_creator_agent_mode() -> String { GAME_CREATOR_AGENT_MODE_CODEX_APP_SERVER.to_string() @@ -2291,6 +2127,9 @@ where fn handle_game_creator_gui_run_event(event: &tauri::RunEvent) { if matches!(event, tauri::RunEvent::Exit) { + // 窗口关闭时已经按项目触发过一次快照同步;退出路径只负责在有界预算内 + // 等在途同步收尾,不重复发起(此刻窗口已销毁,重新枚举项目只会是空集)。 + wait_for_project_snapshot_syncs_on_exit(); // 退出时统一收尾本地预览:进程内监听线程随进程消失,但 `.agent/manifest.json` // 里的 preview 记录会留在 running 上,下次进项目就照着它渲染打不开的运行界面。 if let Err(error) = @@ -2554,7 +2393,9 @@ 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()) + .on_window_event(|window, event| handle_project_snapshot_window_event(window, event)) .manage(game_creator_preview_registry()) .manage(ProjectResourcePreviewReadManager::default()) .manage(PluginHost::default()) @@ -2583,6 +2424,7 @@ fn main() { setup_log.fail("startup.appdata.resolve.failed details=config-dir-uninitialized"); error })?; + spawn_project_snapshot_scheduler(app.handle().clone()); if let Err(error) = builtin_plugins::initialize(&config_dir) { app_log!("startup.builtin-plugins.initialize.failed: {error}"); } @@ -2660,7 +2502,10 @@ fn main() { start_game_creator_external_mcp, stop_game_creator_external_mcp, create_automatic_local_game_project, + create_automatic_local_game_project_from_template, init_local_game_project, + fetch_game_template_library, + download_game_template, import_local_godot_project, import_local_cocos_project, is_local_project_directory_non_empty, @@ -2836,12 +2681,14 @@ 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, get_pending_error_reports, ack_error_reports, + sync_local_project_snapshot, + read_local_project_snapshot_state, ]) .build(tauri_context); let app = match app { @@ -3008,50 +2855,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/src/project/resource_editor.rs b/apps/ai-game-creator-shell/src-tauri/src/project/resource_editor.rs index 77183a884..46bb81c24 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/project/resource_editor.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/project/resource_editor.rs @@ -728,7 +728,16 @@ fn validate_resource_edit_uuid(value: &str, label: &str) -> Result<(), String> { Ok(()) } -fn resource_edit_prompt_max_chars(edit_kind: &LocalProjectResourceEditKind) -> usize { +/// 资源编辑提示词上限的**唯一口径**。 +/// +/// 三个调用方都必须从这里取数,禁止各自写死数字: +/// 1. 本文件的提交校验(`normalize_resource_edit_prompt`); +/// 2. `agc_tools` MCP 工具层(`direct_tools_mcp.rs` 的参数校验与工具 schema); +/// 3. 客户端受控工具桥(`direct_tool_bridge.rs`)。 +/// +/// 客户端 UI 的 `resourceEditPromptMaxLength`(`resourceEditModel.ts`)是同一份口径的 +/// 前端镜像;改数字必须同时改这里、那里,以及工具 schema 里按 kind 声明 `maxLength`。 +pub(crate) fn resource_edit_prompt_max_chars(edit_kind: &LocalProjectResourceEditKind) -> usize { match edit_kind { LocalProjectResourceEditKind::BackgroundMusic => 140, LocalProjectResourceEditKind::SoundEffect => 1_900, @@ -739,6 +748,24 @@ fn resource_edit_prompt_max_chars(edit_kind: &LocalProjectResourceEditKind) -> u } } +/// 提示词超限的拒绝文案:与上限同一个口径,MCP 层、工具桥和提交校验复用同一条字符串, +/// 保证模型看到的数字就是真实生效的数字。 +pub(crate) fn resource_edit_prompt_limit_error( + edit_kind: &LocalProjectResourceEditKind, + max_chars: usize, +) -> String { + format!( + "{}资源编辑提示词必须在 1..={max_chars} 字符内", + match edit_kind { + LocalProjectResourceEditKind::BackgroundMusic => "背景音乐", + LocalProjectResourceEditKind::SoundEffect => "音效", + LocalProjectResourceEditKind::Video => "视频", + LocalProjectResourceEditKind::CharacterAnimation => "角色动画", + _ => "", + } + ) +} + fn normalize_resource_edit_prompt( edit_kind: &LocalProjectResourceEditKind, value: &str, @@ -746,16 +773,7 @@ fn normalize_resource_edit_prompt( let value = value.trim(); let max_chars = resource_edit_prompt_max_chars(edit_kind); if value.is_empty() || value.chars().count() > max_chars { - return Err(format!( - "{}资源编辑提示词必须在 1..={max_chars} 字符内", - match edit_kind { - LocalProjectResourceEditKind::BackgroundMusic => "背景音乐", - LocalProjectResourceEditKind::SoundEffect => "音效", - LocalProjectResourceEditKind::Video => "视频", - LocalProjectResourceEditKind::CharacterAnimation => "角色动画", - _ => "", - } - )); + return Err(resource_edit_prompt_limit_error(edit_kind, max_chars)); } if value .chars() diff --git a/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/diff.rs b/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/diff.rs new file mode 100644 index 000000000..c6de3f6f1 --- /dev/null +++ b/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/diff.rs @@ -0,0 +1,151 @@ +use super::*; +use std::collections::BTreeSet; + +/// 需要上传的一个文件。摘要与字节数来自本次差异对比,上传阶段不再重新计算。 +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct ProjectSnapshotUploadCandidate { + pub(crate) relative_path: String, + pub(crate) size_bytes: u64, + pub(crate) modified_ms: u64, + pub(crate) checksum: String, + pub(crate) absolute_path: PathBuf, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub(crate) struct ProjectSnapshotDiff { + pub(crate) uploads: Vec, + /// 本地已删除、只在远端清单中需要消失的路径。 + pub(crate) deleted: Vec, + /// 内容与上次同步一致、只有元数据变化的路径;只需刷新本地索引。 + pub(crate) metadata_only: Vec, + pub(crate) skipped: Vec, + /// 本轮因为累计上限没有上传、留给下一次同步的路径。 + pub(crate) deferred: Vec, + /// 同步期间被改写、本轮不参与上传与索引推进的路径。 + pub(crate) pending: Vec, + pub(crate) upload_bytes: u64, + /// 扫描后的完整清单(尚未扣除上传失败与延后项),成功同步后就是新的索引。 + pub(crate) current: BTreeMap, +} + +impl ProjectSnapshotDiff { + pub(crate) fn has_changes(&self) -> bool { + !self.uploads.is_empty() || !self.deleted.is_empty() || !self.metadata_only.is_empty() + } +} + +/// 增量差异对比:先用 `(字节数, 修改时间)` 判定是否需要读盘,只有元数据变化时 +/// 才重新计算摘要,再用摘要判断内容是否真的变了。 +pub(crate) fn compute_project_snapshot_diff( + scan: &ProjectSnapshotScanResult, + previous: &BTreeMap, + max_sync_bytes: u64, +) -> Result { + let mut diff = ProjectSnapshotDiff { + skipped: scan.skipped.clone(), + ..ProjectSnapshotDiff::default() + }; + let mut metadata_only = Vec::new(); + + for file in &scan.files { + let previous_entry = previous.get(&file.relative_path); + if let Some(entry) = previous_entry { + if entry.size_bytes == file.size_bytes + && entry.modified_ms == file.modified_ms + && !entry.checksum.is_empty() + { + diff.current + .insert(file.relative_path.clone(), entry.clone()); + continue; + } + } + + let bytes = read_project_snapshot_file_bytes(&file.absolute_path)?; + // 同步不持项目写锁:读完立刻复核一次,文件在读取期间被改写就留给下一轮, + // 既不把这份内容写进索引,也不上传它。 + if !project_snapshot_file_matches(&file.absolute_path, file.size_bytes, file.modified_ms) { + diff.pending.push(ProjectSnapshotSkippedPath { + relative_path: file.relative_path.clone(), + reason: "同步期间文件发生变化,留到下一次".to_string(), + }); + // 上一轮已同步过这条路径时沿用旧记录:文件仍然存在,只是这一轮读不到 + // 一致版本,所以既不能算删除(会被远端 GC 掉),也不能记成本轮已同步。 + if let Some(entry) = previous_entry { + diff.current + .insert(file.relative_path.clone(), entry.clone()); + } + continue; + } + let checksum = project_snapshot_checksum(&bytes); + match previous_entry { + Some(entry) if entry.checksum == checksum => { + metadata_only.push(file.relative_path.clone()) + } + _ => diff.uploads.push(ProjectSnapshotUploadCandidate { + relative_path: file.relative_path.clone(), + size_bytes: file.size_bytes, + modified_ms: file.modified_ms, + checksum: checksum.clone(), + absolute_path: file.absolute_path.clone(), + }), + } + diff.current.insert( + file.relative_path.clone(), + ProjectSnapshotIndexedFile { + size_bytes: file.size_bytes, + modified_ms: file.modified_ms, + checksum, + }, + ); + } + + diff.deleted = previous + .keys() + .filter(|relative_path| !diff.current.contains_key(*relative_path)) + .cloned() + .collect(); + diff.deleted.sort(); + diff.metadata_only = metadata_only; + + apply_project_snapshot_sync_budget(&mut diff, max_sync_bytes); + Ok(diff) +} + +/// 按路径顺序累计上传体积;超出上限的文件进入延后清单,不静默截断也不上传残缺内容。 +fn apply_project_snapshot_sync_budget(diff: &mut ProjectSnapshotDiff, max_sync_bytes: u64) { + let mut accepted = Vec::new(); + let mut deferred = Vec::new(); + let mut bytes = 0_u64; + for candidate in diff.uploads.drain(..) { + if bytes.saturating_add(candidate.size_bytes) > max_sync_bytes { + deferred.push(ProjectSnapshotSkippedPath { + relative_path: candidate.relative_path, + reason: format!("单次同步超过 {max_sync_bytes} 字节上限,留到下一次"), + }); + continue; + } + bytes = bytes.saturating_add(candidate.size_bytes); + accepted.push(candidate); + } + diff.upload_bytes = bytes; + diff.uploads = accepted; + diff.deferred = deferred; +} + +/// 成功同步后的索引清单:延后项与上传失败项都要剔除,否则下次同步会把它们 +/// 当成"已经同步过"而漏传。 +pub(crate) fn build_project_snapshot_synced_files( + diff: &ProjectSnapshotDiff, + uploaded_paths: &BTreeSet, +) -> BTreeMap { + let mut retained = diff.current.clone(); + for candidate in &diff.uploads { + if !uploaded_paths.contains(&candidate.relative_path) { + retained.remove(&candidate.relative_path); + } + } + for deferred in &diff.deferred { + retained.remove(&deferred.relative_path); + } + retained +} diff --git a/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/index.rs b/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/index.rs new file mode 100644 index 000000000..f81f9e747 --- /dev/null +++ b/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/index.rs @@ -0,0 +1,131 @@ +use super::*; + +/// 本地增量索引里的一条文件记录。 +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ProjectSnapshotIndexedFile { + pub(crate) size_bytes: u64, + pub(crate) modified_ms: u64, + pub(crate) checksum: String, +} + +/// 上次成功同步的快照。索引只在本机 AppData 中,不进入用户项目目录。 +/// +/// `user_id` 是远端前缀的一部分:换号后旧索引不再代表同一个远端命名空间, +/// 因此读取时按用户身份判等,不一致就当作冷启动重新全量对比。 +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ProjectSnapshotIndex { + pub(crate) schema_version: u32, + pub(crate) project_id: String, + pub(crate) user_id: String, + pub(crate) sync_revision: u64, + pub(crate) synced_at_ms: u64, + #[serde(default)] + pub(crate) files: BTreeMap, +} + +pub(crate) fn empty_project_snapshot_index( + project_id: &str, + user_id: &str, +) -> ProjectSnapshotIndex { + ProjectSnapshotIndex { + schema_version: PROJECT_SNAPSHOT_INDEX_SCHEMA_VERSION, + project_id: project_id.to_string(), + user_id: user_id.to_string(), + sync_revision: 0, + synced_at_ms: 0, + files: BTreeMap::new(), + } +} + +/// 项目 ID 同时用作 AppData 目录名与远端键段:这里额外拒绝 `.` 与 `..`,避免 +/// 把索引写到目录之外。 +pub(crate) fn validate_project_snapshot_project_id(project_id: &str) -> Result { + shared_contracts::agc_project_snapshots::validate_agc_project_snapshot_project_id(project_id)?; + if project_id == "." || project_id == ".." { + return Err("项目 ID 不能是相对目录".to_string()); + } + Ok(project_id.to_string()) +} + +pub(crate) fn project_snapshot_index_directory(project_id: &str) -> Result { + let config_dir = game_creator_runtime_config_dir() + .ok_or_else(|| "客户端 AppData 配置目录未初始化".to_string())?; + project_snapshot_index_directory_at(&config_dir, project_id) +} + +pub(crate) fn project_snapshot_index_directory_at( + config_dir: &Path, + project_id: &str, +) -> Result { + let project_id = validate_project_snapshot_project_id(project_id)?; + Ok(config_dir.join(PROJECT_SNAPSHOT_DIRECTORY).join(project_id)) +} + +pub(crate) fn project_snapshot_index_path(project_id: &str) -> Result { + Ok(project_snapshot_index_path_at( + &project_snapshot_index_directory(project_id)?, + )) +} + +pub(crate) fn project_snapshot_index_path_at(directory: &Path) -> PathBuf { + directory.join(PROJECT_SNAPSHOT_INDEX_FILE_NAME) +} + +/// 读取本地索引。索引不存在、版本不符或内容损坏时返回空索引:这种情况下 +/// 全量对比会重新上传所有文件,不会漏传,也不会因为坏索引中断同步。 +pub(crate) fn read_project_snapshot_index( + project_id: &str, +) -> Result { + read_project_snapshot_index_at(&project_snapshot_index_directory(project_id)?, project_id) +} + +pub(crate) fn read_project_snapshot_index_at( + directory: &Path, + project_id: &str, +) -> Result { + let path = project_snapshot_index_path_at(directory); + if !path.exists() { + return Ok(empty_project_snapshot_index(project_id, "")); + } + let content = match read_game_creator_private_file_to_string( + &path, + "项目快照索引", + PROJECT_SNAPSHOT_INDEX_MAX_BYTES, + ) { + Ok(content) => content, + Err(error) => { + app_log!("project_snapshot.index.read.failed: {error}"); + return Ok(empty_project_snapshot_index(project_id, "")); + } + }; + match serde_json::from_str::(&content) { + Ok(index) + if index.schema_version == PROJECT_SNAPSHOT_INDEX_SCHEMA_VERSION + && index.project_id == project_id => + { + Ok(index) + } + Ok(_) => Ok(empty_project_snapshot_index(project_id, "")), + Err(error) => { + app_log!("project_snapshot.index.parse.failed: {error}"); + Ok(empty_project_snapshot_index(project_id, "")) + } + } +} + +pub(crate) fn write_project_snapshot_index(index: &ProjectSnapshotIndex) -> Result<(), String> { + write_project_snapshot_index_at(&project_snapshot_index_directory(&index.project_id)?, index) +} + +pub(crate) fn write_project_snapshot_index_at( + directory: &Path, + index: &ProjectSnapshotIndex, +) -> Result<(), String> { + let path = project_snapshot_index_path_at(directory); + let mut encoded = serde_json::to_vec_pretty(index) + .map_err(|error| format!("序列化项目快照索引失败:{error}"))?; + encoded.push(b'\n'); + write_game_creator_private_file(&path, &encoded, "项目快照索引") +} diff --git a/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/mod.rs b/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/mod.rs new file mode 100644 index 000000000..bcdf2ce21 --- /dev/null +++ b/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/mod.rs @@ -0,0 +1,547 @@ +//! AGC 项目定时快照上传。 +//! +//! 客户端在这里负责三件事:按项目目录扫描与增量差异对比、按触发时机编排上传、 +//! 把已成功同步的清单写回本机索引。远端对象键与存储凭据由 api-server 决定, +//! 客户端不持有 OSS 凭据,也不直连 OSS。 + +use super::*; +use std::collections::BTreeSet; +use std::sync::{Condvar, MutexGuard}; +use std::time::Instant; + +mod diff; +mod index; +mod scan; +mod transport; + +#[cfg(test)] +mod tests; + +pub(crate) use diff::*; +pub(crate) use index::*; +pub(crate) use scan::*; +pub(crate) use transport::*; + +/// 本机项目快照索引在 AppData 配置目录下的位置。 +pub(crate) const PROJECT_SNAPSHOT_DIRECTORY: &str = "project-snapshots"; +const PROJECT_SNAPSHOT_INDEX_FILE_NAME: &str = "index.json"; +const PROJECT_SNAPSHOT_INDEX_SCHEMA_VERSION: u32 = 1; +const PROJECT_SNAPSHOT_INDEX_MAX_BYTES: u64 = 32 * 1024 * 1024; + +pub(crate) const PROJECT_SNAPSHOT_MAX_FILE_BYTES: u64 = + shared_contracts::agc_project_snapshots::AGC_PROJECT_SNAPSHOT_MAX_FILE_BYTES; +pub(crate) const PROJECT_SNAPSHOT_MAX_SYNC_BYTES: u64 = + shared_contracts::agc_project_snapshots::AGC_PROJECT_SNAPSHOT_MAX_SYNC_BYTES; +/// 单项目常驻占用上限。超过时不再尝试上传,直接给出明确失败而不是反复被服务端拒绝。 +pub(crate) const PROJECT_SNAPSHOT_MAX_PROJECT_BYTES: u64 = + shared_contracts::agc_project_snapshots::AGC_PROJECT_SNAPSHOT_MAX_PROJECT_BYTES; + +const PROJECT_SNAPSHOT_FILES_ENDPOINT: &str = "/api/agc/project-snapshots/files"; +const PROJECT_SNAPSHOT_MANIFEST_ENDPOINT: &str = "/api/agc/project-snapshots/manifest"; + +/// 单个请求的完成上限;关闭与退出路径依赖它保持有界。 +const PROJECT_SNAPSHOT_REQUEST_TIMEOUT_SECONDS: u64 = 60; +/// 应用退出前等待在途同步完成的上限。 +const PROJECT_SNAPSHOT_EXIT_BUDGET_SECONDS: u64 = 15; +const PROJECT_SNAPSHOT_DEFAULT_SYNC_INTERVAL_SECONDS: u64 = 300; +const PROJECT_SNAPSHOT_SYNC_INTERVAL_ENV: &str = + "GENARRATIVE_AGC_PROJECT_SNAPSHOT_SYNC_INTERVAL_SECONDS"; +const PROJECT_SNAPSHOT_DISABLED_ENV: &str = "GENARRATIVE_AGC_PROJECT_SNAPSHOT_DISABLED"; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum ProjectSnapshotSyncTrigger { + Periodic, + ProjectClose, + Manual, +} + +impl ProjectSnapshotSyncTrigger { + fn as_str(self) -> &'static str { + match self { + Self::Periodic => "periodic", + Self::ProjectClose => "project-close", + Self::Manual => "manual", + } + } +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ProjectSnapshotFailureView { + pub(crate) relative_path: String, + pub(crate) code: String, + pub(crate) detail: String, +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ProjectSnapshotSyncReport { + pub(crate) project_id: String, + pub(crate) trigger: String, + /// `synced` 全部成功,`partial` 部分成功,`failed` 全部失败,`no-op` 无改动。 + pub(crate) status: String, + pub(crate) sync_revision: u64, + pub(crate) uploaded_files: usize, + pub(crate) uploaded_bytes: u64, + pub(crate) remote_skipped_files: usize, + pub(crate) deleted_files: usize, + pub(crate) deferred_files: usize, + pub(crate) metadata_only_files: usize, + pub(crate) skipped_files: Vec, + /// 同步期间被改写、本轮未参与上传与索引推进的路径。 + pub(crate) pending_files: Vec, + pub(crate) failed_files: Vec, + pub(crate) synced_at_ms: u64, +} + +/// 同步开关。停用时不发起任何请求,也不推进索引。 +pub(crate) fn project_snapshot_sync_enabled() -> bool { + match std::env::var_os(PROJECT_SNAPSHOT_DISABLED_ENV) { + Some(value) => { + let value = value.to_string_lossy().trim().to_ascii_lowercase(); + !matches!(value.as_str(), "1" | "true" | "yes" | "on") + } + None => true, + } +} + +pub(crate) fn project_snapshot_sync_interval() -> Duration { + let seconds = std::env::var(PROJECT_SNAPSHOT_SYNC_INTERVAL_ENV) + .ok() + .and_then(|value| value.trim().parse::().ok()) + .filter(|seconds| *seconds > 0) + .unwrap_or(PROJECT_SNAPSHOT_DEFAULT_SYNC_INTERVAL_SECONDS); + Duration::from_secs(seconds) +} + +/// 同一项目的同步串行执行;周期触发遇到在途同步直接让位,不排队堆积。 +static PROJECT_SNAPSHOT_PROJECT_LOCKS: OnceLock>>>> = + OnceLock::new(); + +struct ProjectSnapshotInFlight { + active: Mutex, + idle: Condvar, +} + +static PROJECT_SNAPSHOT_IN_FLIGHT: OnceLock = OnceLock::new(); + +fn project_snapshot_project_locks() -> &'static Mutex>>> { + PROJECT_SNAPSHOT_PROJECT_LOCKS.get_or_init(|| Mutex::new(BTreeMap::new())) +} + +fn project_snapshot_in_flight() -> &'static ProjectSnapshotInFlight { + PROJECT_SNAPSHOT_IN_FLIGHT.get_or_init(|| ProjectSnapshotInFlight { + active: Mutex::new(0), + idle: Condvar::new(), + }) +} + +fn project_snapshot_project_lock(key: &str) -> Arc> { + let mut locks = project_snapshot_project_locks() + .lock() + .expect("project snapshot lock registry"); + locks + .entry(key.to_string()) + .or_insert_with(|| Arc::new(Mutex::new(()))) + .clone() +} + +struct ProjectSnapshotInFlightGuard; + +impl ProjectSnapshotInFlightGuard { + fn begin() -> Self { + let state = project_snapshot_in_flight(); + let mut active = state + .active + .lock() + .expect("project snapshot in-flight lock"); + *active += 1; + Self + } +} + +impl Drop for ProjectSnapshotInFlightGuard { + fn drop(&mut self) { + let state = project_snapshot_in_flight(); + if let Ok(mut active) = state.active.lock() { + *active = active.saturating_sub(1); + if *active == 0 { + state.idle.notify_all(); + } + } + } +} + +/// 周期触发:已有同项目同步在途时返回 `None`。 +pub(crate) fn try_run_project_snapshot_sync(key: &str, run: impl FnOnce() -> T) -> Option { + let lock = project_snapshot_project_lock(key); + let guard = lock.try_lock().ok()?; + let _in_flight = ProjectSnapshotInFlightGuard::begin(); + let result = run(); + drop(guard); + Some(result) +} + +/// 关闭与手动触发:等待在途同步结束后再执行一次,保证最后一次状态被记录。 +pub(crate) fn run_project_snapshot_sync(key: &str, run: impl FnOnce() -> T) -> T { + let lock = project_snapshot_project_lock(key); + let guard: MutexGuard<'_, ()> = lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let _in_flight = ProjectSnapshotInFlightGuard::begin(); + let result = run(); + drop(guard); + result +} + +/// 退出前等待在途同步收尾。返回是否在预算内全部结束。 +pub(crate) fn wait_for_project_snapshot_syncs(timeout: Duration) -> bool { + let state = project_snapshot_in_flight(); + let deadline = Instant::now() + timeout; + let mut active = state + .active + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + while *active > 0 { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return false; + } + let (guard, _) = state + .idle + .wait_timeout(active, remaining) + .unwrap_or_else(|poisoned| poisoned.into_inner()); + active = guard; + } + true +} + +/// 把项目同步请求交给后台线程:窗口关闭与应用退出路径都不能被网络等待阻塞。 +pub(crate) fn request_project_snapshot_sync( + project_root: PathBuf, + trigger: ProjectSnapshotSyncTrigger, +) { + if !project_snapshot_sync_enabled() { + return; + } + let key = project_snapshot_sync_key(&project_root); + let spawn = std::thread::Builder::new() + .name("agc-project-snapshot".to_string()) + .spawn(move || { + let run = || sync_project_snapshot_blocking(&project_root, trigger); + let outcome = if matches!(trigger, ProjectSnapshotSyncTrigger::Periodic) { + try_run_project_snapshot_sync(&key, run) + } else { + Some(run_project_snapshot_sync(&key, run)) + }; + if let Some(Err(error)) = outcome { + app_log!( + "project_snapshot.sync.failed trigger={}: {error}", + trigger.as_str() + ); + } + }); + if let Err(error) = spawn { + app_log!("project_snapshot.sync.spawn.failed: {error}"); + } +} + +pub(crate) fn project_snapshot_sync_key(project_root: &Path) -> String { + let value = project_root.to_string_lossy().replace('\\', "/"); + #[cfg(windows)] + { + return value.trim_end_matches('/').to_ascii_lowercase(); + } + #[cfg(not(windows))] + { + value.trim_end_matches('/').to_string() + } +} + +fn sync_project_snapshot_blocking( + project_root: &Path, + trigger: ProjectSnapshotSyncTrigger, +) -> Result { + tauri::async_runtime::block_on(sync_project_snapshot_async(project_root, trigger)) +} + +async fn sync_project_snapshot_async( + project_root: &Path, + trigger: ProjectSnapshotSyncTrigger, +) -> Result { + if !project_snapshot_sync_enabled() { + return Err("项目快照同步已停用".to_string()); + } + validate_project_root(project_root)?; + let session = current_platform_session() + .ok_or_else(|| "authentication-required: 请先登录陶泥儿账号".to_string())?; + let manifest = read_existing_manifest_for_project(project_root)?; + let project_id = validate_project_snapshot_project_id(manifest.project_id.trim())?; + + let previous = read_project_snapshot_index(&project_id)?; + let previous = if previous.user_id == session.user_id { + previous + } else { + empty_project_snapshot_index(&project_id, &session.user_id) + }; + + let scan = scan_project_snapshot_files(project_root, PROJECT_SNAPSHOT_MAX_FILE_BYTES)?; + // 项目总量上限在本地先判:超限时明确失败,不再逐个文件上传后被服务端整体拒绝。 + let scan_total_bytes = scan + .files + .iter() + .fold(0_u64, |total, file| total.saturating_add(file.size_bytes)); + if scan_total_bytes > PROJECT_SNAPSHOT_MAX_PROJECT_BYTES { + return Err(format!( + "项目体积 {scan_total_bytes} 字节超过项目快照单项目上限 {PROJECT_SNAPSHOT_MAX_PROJECT_BYTES} 字节" + )); + } + let diff = + compute_project_snapshot_diff(&scan, &previous.files, PROJECT_SNAPSHOT_MAX_SYNC_BYTES)?; + if !diff.has_changes() { + return Ok(ProjectSnapshotSyncReport { + project_id, + trigger: trigger.as_str().to_string(), + status: "no-op".to_string(), + sync_revision: previous.sync_revision, + uploaded_files: 0, + uploaded_bytes: 0, + remote_skipped_files: 0, + deleted_files: 0, + deferred_files: 0, + metadata_only_files: diff.metadata_only.len(), + skipped_files: failure_views(&diff.skipped), + pending_files: failure_views(&diff.pending), + failed_files: Vec::new(), + synced_at_ms: previous.synced_at_ms, + }); + } + + let upload = upload_project_snapshot_diff(&session, &project_id, &diff).await; + let synced_files = build_project_snapshot_synced_files(&diff, &upload.uploaded_paths); + let next_revision = previous.sync_revision.saturating_add(1); + let synced_at_ms = u64::try_from(unix_millis()).unwrap_or(u64::MAX); + let payload = shared_contracts::agc_project_snapshots::AgcProjectSnapshotManifestRequest { + schema_version: + shared_contracts::agc_project_snapshots::AGC_PROJECT_SNAPSHOT_SCHEMA_VERSION, + project_id: project_id.clone(), + sync_revision: next_revision, + synced_at_ms, + files: synced_files + .iter() + .map(|(relative_path, file)| { + shared_contracts::agc_project_snapshots::AgcProjectSnapshotManifestFile { + relative_path: relative_path.clone(), + size_bytes: file.size_bytes, + checksum: file.checksum.clone(), + } + }) + .collect(), + }; + // 清单失败就不推进索引:宁可下一次重算,也不能把本地记成"已同步"。 + upload_project_snapshot_manifest(&session, &payload) + .await + .map_err(|error| error.message())?; + write_project_snapshot_index(&ProjectSnapshotIndex { + schema_version: PROJECT_SNAPSHOT_INDEX_SCHEMA_VERSION, + project_id: project_id.clone(), + user_id: session.user_id.clone(), + sync_revision: next_revision, + synced_at_ms, + files: synced_files, + })?; + + let status = if upload.failures.is_empty() { + "synced" + } else if upload.uploaded_paths.is_empty() { + "failed" + } else { + "partial" + }; + let report = ProjectSnapshotSyncReport { + project_id, + trigger: trigger.as_str().to_string(), + status: status.to_string(), + sync_revision: next_revision, + uploaded_files: upload.uploaded_paths.len(), + uploaded_bytes: upload.uploaded_bytes, + remote_skipped_files: upload.remote_skipped_files, + deleted_files: diff.deleted.len(), + deferred_files: diff.deferred.len(), + metadata_only_files: diff.metadata_only.len(), + skipped_files: failure_views(&diff.skipped), + pending_files: failure_views(&diff.pending), + failed_files: upload + .failures + .iter() + .map(|failure| ProjectSnapshotFailureView { + relative_path: failure.relative_path.clone(), + code: failure.code.clone(), + detail: failure.detail.clone(), + }) + .collect(), + synced_at_ms, + }; + app_log!( + "project_snapshot.sync.completed trigger={} status={} revision={} uploaded={} skippedRemote={} deleted={} deferred={} failed={}", + report.trigger, + report.status, + report.sync_revision, + report.uploaded_files, + report.remote_skipped_files, + report.deleted_files, + report.deferred_files, + report.failed_files.len() + ); + Ok(report) +} + +fn failure_views(skipped: &[ProjectSnapshotSkippedPath]) -> Vec { + skipped + .iter() + .map(|entry| ProjectSnapshotFailureView { + relative_path: entry.relative_path.clone(), + code: "skipped".to_string(), + detail: entry.reason.clone(), + }) + .collect() +} + +/// 从窗口 URL 读取项目路径。只有带 `projectPath` 的窗口才代表打开的项目。 +pub(crate) fn project_snapshot_project_path_from_url(url: &url::Url) -> Option { + url.query_pairs() + .find_map(|(key, value)| (key == "projectPath").then(|| value.into_owned())) + .filter(|value| !value.trim().is_empty()) +} + +fn open_project_snapshot_workspaces(app: &tauri::AppHandle) -> Vec { + let mut paths = BTreeSet::new(); + for window in app.webview_windows().into_values() { + let Ok(url) = window.url() else { + continue; + }; + if let Some(project_path) = project_snapshot_project_path_from_url(&url) { + paths.insert(project_path); + } + } + paths.into_iter().collect() +} + +/// 工作区窗口关闭即视为项目关闭:立刻补一次同步。 +pub(crate) fn handle_project_snapshot_window_event( + window: &tauri::Window, + event: &tauri::WindowEvent, +) { + if !project_snapshot_sync_enabled() { + return; + } + if !matches!(event, tauri::WindowEvent::CloseRequested { .. }) { + return; + } + // `tauri::Window` 不暴露 WebView 地址,按标签取回对应的 WebView 窗口再读 URL。 + let Some(webview) = window.app_handle().get_webview_window(window.label()) else { + return; + }; + let Ok(url) = webview.url() else { + return; + }; + let Some(project_path) = project_snapshot_project_path_from_url(&url) else { + return; + }; + request_project_snapshot_sync( + PathBuf::from(project_path), + ProjectSnapshotSyncTrigger::ProjectClose, + ); +} + +/// 应用退出前等待在途同步收尾。 +/// +/// 退出时刻窗口已销毁,按窗口重新枚举项目只会得到空集,因此这里不重复发起同步: +/// 关窗触发的同步已经在 `CloseRequested` 时启动,退出路径只需要给它一个有界窗口。 +pub(crate) fn wait_for_project_snapshot_syncs_on_exit() { + if !project_snapshot_sync_enabled() { + return; + } + if !wait_for_project_snapshot_syncs(Duration::from_secs(PROJECT_SNAPSHOT_EXIT_BUDGET_SECONDS)) { + app_log!("project_snapshot.sync.exit.budget-exhausted"); + } +} + +/// 周期定时器:只为当前仍打开的项目触发,进程内项目集合由窗口 URL 决定。 +pub(crate) fn spawn_project_snapshot_scheduler(app: tauri::AppHandle) { + if !project_snapshot_sync_enabled() { + app_log!("project_snapshot.scheduler.disabled"); + return; + } + let interval = project_snapshot_sync_interval(); + let spawned = std::thread::Builder::new() + .name("agc-project-snapshot-scheduler".to_string()) + .spawn(move || loop { + std::thread::sleep(interval); + for project_path in open_project_snapshot_workspaces(&app) { + request_project_snapshot_sync( + PathBuf::from(project_path), + ProjectSnapshotSyncTrigger::Periodic, + ); + } + }); + if let Err(error) = spawned { + app_log!("project_snapshot.scheduler.spawn.failed: {error}"); + } +} + +fn resolve_project_snapshot_root(project_path: &str) -> Result { + let trimmed = project_path.trim(); + if trimmed.is_empty() { + return Err("请提供项目绝对路径".to_string()); + } + let root = PathBuf::from(trimmed); + validate_project_root(&root)?; + Ok(root) +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ProjectSnapshotStateView { + project_id: String, + index_path: String, + index_present: bool, + file_count: usize, + sync_revision: u64, + synced_at_ms: u64, + enabled: bool, +} + +/// 手动触发一次项目快照同步。同步本身跑在阻塞工作线程上,不占用窗口线程。 +#[tauri::command] +pub(crate) async fn sync_local_project_snapshot( + project_path: String, +) -> Result { + let root = resolve_project_snapshot_root(&project_path)?; + let key = project_snapshot_sync_key(&root); + tauri::async_runtime::spawn_blocking(move || { + run_project_snapshot_sync(&key, || { + sync_project_snapshot_blocking(&root, ProjectSnapshotSyncTrigger::Manual) + }) + }) + .await + .map_err(|error| format!("项目快照同步任务失败:{error}"))? +} + +#[tauri::command] +pub(crate) fn read_local_project_snapshot_state( + project_path: String, +) -> Result { + let root = resolve_project_snapshot_root(&project_path)?; + let manifest = read_existing_manifest_for_project(&root)?; + let project_id = validate_project_snapshot_project_id(manifest.project_id.trim())?; + let index_path = project_snapshot_index_path(&project_id)?; + let index = read_project_snapshot_index(&project_id)?; + Ok(ProjectSnapshotStateView { + project_id, + index_path: index_path.to_string_lossy().into_owned(), + index_present: index_path.exists(), + file_count: index.files.len(), + sync_revision: index.sync_revision, + synced_at_ms: index.synced_at_ms, + enabled: project_snapshot_sync_enabled(), + }) +} diff --git a/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/scan.rs b/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/scan.rs new file mode 100644 index 000000000..2163c4b24 --- /dev/null +++ b/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/scan.rs @@ -0,0 +1,157 @@ +use super::*; + +/// 扫描阶段的候选文件:只看元数据,不读内容,差异对比阶段才决定是否读盘。 +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct ProjectSnapshotScannedFile { + pub(crate) relative_path: String, + pub(crate) size_bytes: u64, + pub(crate) modified_ms: u64, + pub(crate) absolute_path: PathBuf, +} + +/// 被排除或不参与本次同步的路径。原因只用于本机日志与同步报告,不进入远端。 +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ProjectSnapshotSkippedPath { + pub(crate) relative_path: String, + pub(crate) reason: String, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub(crate) struct ProjectSnapshotScanResult { + pub(crate) files: Vec, + pub(crate) skipped: Vec, +} + +/// 扫描项目目录,复用 checkpoint / 项目索引同一份排除口径: +/// `.agent`、版本控制目录、依赖与构建产物目录、凭据目录、符号链接与重解析点 +/// 都不参与同步,超出单文件上限的文件进入跳过清单而不是静默丢弃。 +pub(crate) fn scan_project_snapshot_files( + root: &Path, + max_file_bytes: u64, +) -> Result { + let mut result = ProjectSnapshotScanResult::default(); + if !root.exists() { + return Ok(result); + } + let root_metadata = + fs::symlink_metadata(root).map_err(|error| format!("读取项目目录元数据失败:{error}"))?; + if root_metadata.file_type().is_symlink() || !root_metadata.is_dir() { + return Err("项目快照只支持普通项目目录".to_string()); + } + + let mut directories = vec![root.to_path_buf()]; + while let Some(directory) = directories.pop() { + let entries = fs::read_dir(&directory) + .map_err(|error| format!("读取项目目录失败:{}: {error}", directory.display()))?; + for entry in entries { + let entry = entry + .map_err(|error| format!("读取项目文件失败:{}: {error}", directory.display()))?; + let path = entry.path(); + // 路径不在项目根内(含符号链接跳转)时直接跳过,不猜测归属。 + let Ok(relative_path) = relative_project_path(root, &path) else { + continue; + }; + let metadata = match fs::symlink_metadata(&path) { + Ok(metadata) => metadata, + Err(error) => { + result.skipped.push(ProjectSnapshotSkippedPath { + relative_path, + reason: format!("读取元数据失败:{error}"), + }); + continue; + } + }; + if should_skip_project_snapshot_path(&relative_path) { + continue; + } + if metadata.file_type().is_symlink() || windows_metadata_is_reparse_point(&metadata) { + result.skipped.push(ProjectSnapshotSkippedPath { + relative_path, + reason: "符号链接或重解析点不参与项目快照".to_string(), + }); + continue; + } + if metadata.is_dir() { + directories.push(path); + continue; + } + if !metadata.is_file() { + result.skipped.push(ProjectSnapshotSkippedPath { + relative_path, + reason: "不是普通文件".to_string(), + }); + continue; + } + if metadata.len() > max_file_bytes { + result.skipped.push(ProjectSnapshotSkippedPath { + relative_path, + reason: format!("单个文件超过 {max_file_bytes} 字节上限"), + }); + continue; + } + result.files.push(ProjectSnapshotScannedFile { + relative_path, + size_bytes: metadata.len(), + modified_ms: project_snapshot_modified_ms(&metadata), + absolute_path: path, + }); + } + } + + result + .files + .sort_by(|left, right| left.relative_path.cmp(&right.relative_path)); + result + .skipped + .sort_by(|left, right| left.relative_path.cmp(&right.relative_path)); + Ok(result) +} + +/// 修改时间缺失或早于 Unix 纪元时返回 0:这样的文件每轮都会重算摘要,不会 +/// 被误判成"未改动"。 +pub(crate) fn project_snapshot_modified_ms(metadata: &fs::Metadata) -> u64 { + metadata + .modified() + .ok() + .and_then(|time| time.duration_since(UNIX_EPOCH).ok()) + .map(|duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)) + .unwrap_or(0) +} + +/// 安全打开并读取项目文件内容。拒绝符号链接、重解析点与硬链接,读取后不再 +/// 按路径名二次访问。 +pub(crate) fn read_project_snapshot_file_bytes(path: &Path) -> Result, String> { + let (mut file, metadata) = open_project_snapshot_regular_file(path, "项目快照文件")?; + let mut bytes = Vec::with_capacity(usize::try_from(metadata.len()).unwrap_or_default()); + file.read_to_end(&mut bytes) + .map_err(|error| format!("读取项目快照文件失败:{}: {error}", path.display()))?; + Ok(bytes) +} + +/// 与项目索引同口径的校验和,便于同一份内容在不同入口之间比较。 +pub(crate) fn project_snapshot_checksum(bytes: &[u8]) -> String { + format!("fnv1a64:{:016x}", fnv1a64(bytes)) +} + +/// 复核文件是否仍是扫描时刻的那一份内容。 +/// +/// 同步不持有项目写锁:Agent 或编辑器可能在扫描之后、读取或上传之前改写文件。 +/// 读取前后都按 `(字节数, 修改时间)` 比对,任一处不一致就判定为"同步期间发生变化", +/// 该文件不计入索引、留给下一次同步,而不是上传一份自相矛盾的快照。 +pub(crate) fn project_snapshot_file_matches( + path: &Path, + size_bytes: u64, + modified_ms: u64, +) -> bool { + let Ok(metadata) = fs::symlink_metadata(path) else { + return false; + }; + if metadata.file_type().is_symlink() || windows_metadata_is_reparse_point(&metadata) { + return false; + } + if !metadata.is_file() { + return false; + } + metadata.len() == size_bytes && project_snapshot_modified_ms(&metadata) == modified_ms +} diff --git a/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/tests.rs b/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/tests.rs new file mode 100644 index 000000000..ff57bdfae --- /dev/null +++ b/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/tests.rs @@ -0,0 +1,590 @@ +use super::*; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +fn fixture_root() -> tempfile::TempDir { + tempfile::tempdir().expect("create project snapshot fixture root") +} + +fn write_fixture_file(root: &Path, relative_path: &str, bytes: &[u8]) { + let path = root.join(relative_path); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).expect("create fixture parent directory"); + } + fs::write(&path, bytes).expect("write fixture file"); +} + +fn scan_fixture(root: &Path) -> ProjectSnapshotScanResult { + scan_project_snapshot_files(root, PROJECT_SNAPSHOT_MAX_FILE_BYTES) + .expect("scan fixture project") +} + +fn paths_of(files: &[ProjectSnapshotUploadCandidate]) -> Vec { + files + .iter() + .map(|candidate| candidate.relative_path.clone()) + .collect() +} + +#[test] +fn project_snapshot_project_id_validation_rejects_paths_and_unsafe_values() { + for value in [ + "", + " ", + ".", + "..", + "../escape", + "a/b", + "a\\b", + "a b", + "-leading", + ".hidden", + ] { + assert!( + validate_project_snapshot_project_id(value).is_err(), + "unsafe project id must be rejected: {value}" + ); + } + assert_eq!( + validate_project_snapshot_project_id("gameagent-1a2b3c4d").expect("stable project id"), + "gameagent-1a2b3c4d" + ); +} + +#[test] +fn project_snapshot_index_round_trips_and_recovers_from_corruption() { + let root = fixture_root(); + let directory = + project_snapshot_index_directory_at(root.path(), "project-1").expect("index directory"); + assert!(read_project_snapshot_index_at(&directory, "project-1") + .expect("missing index reads as empty") + .files + .is_empty()); + + let mut index = empty_project_snapshot_index("project-1", "user-1"); + index.sync_revision = 3; + index.synced_at_ms = 1_700_000_000_000; + index.files.insert( + "game/index.html".to_string(), + ProjectSnapshotIndexedFile { + size_bytes: 13, + modified_ms: 34, + checksum: "fnv1a64:0000000000000001".to_string(), + }, + ); + write_project_snapshot_index_at(&directory, &index).expect("write index"); + assert_eq!( + read_project_snapshot_index_at(&directory, "project-1").expect("read index"), + index + ); + + let path = project_snapshot_index_path_at(&directory); + fs::write(&path, b"{ not json").expect("corrupt index"); + assert!( + read_project_snapshot_index_at(&directory, "project-1") + .expect("corrupt index reads as empty") + .files + .is_empty(), + "损坏索引必须退化为空索引,让下一次同步全量重算" + ); +} + +#[test] +fn project_snapshot_scan_skips_excluded_paths_and_oversized_files() { + let root = fixture_root(); + write_fixture_file(root.path(), "game/index.html", b""); + write_fixture_file(root.path(), "assets/manifest.json", b"{}"); + write_fixture_file(root.path(), ".agent/runtime/state.json", b"{}"); + write_fixture_file(root.path(), ".agent/manifest.json", b"{}"); + write_fixture_file(root.path(), "node_modules/pkg/index.js", b"export {};"); + write_fixture_file(root.path(), "game/dist/bundle.js", b"bundle"); + write_fixture_file(root.path(), "secrets/key.pem", b"private-key"); + write_fixture_file(root.path(), "assets/big.bin", b"0123456789"); + + let scan = scan_project_snapshot_files(root.path(), 4).expect("scan fixture project"); + let scanned = scan + .files + .iter() + .map(|file| file.relative_path.clone()) + .collect::>(); + assert_eq!( + scanned, + vec!["assets/manifest.json".to_string()], + ".agent、node_modules、dist 与凭据目录里的文件不能进入候选集合" + ); + let skipped = scan + .skipped + .iter() + .map(|entry| entry.relative_path.clone()) + .collect::>(); + assert_eq!( + skipped, + vec!["assets/big.bin".to_string(), "game/index.html".to_string()], + "超限文件进入跳过清单,不静默丢弃" + ); +} + +#[test] +fn project_snapshot_diff_reuses_metadata_and_reports_a_single_modification() { + let root = fixture_root(); + write_fixture_file(root.path(), "game/a.txt", b"alpha"); + write_fixture_file(root.path(), "game/b.txt", b"beta!"); + + let first_scan = scan_fixture(root.path()); + let first = compute_project_snapshot_diff( + &first_scan, + &BTreeMap::new(), + PROJECT_SNAPSHOT_MAX_SYNC_BYTES, + ) + .expect("first diff"); + assert_eq!(paths_of(&first.uploads), vec!["game/a.txt", "game/b.txt"]); + assert!(first.deleted.is_empty()); + + // 第二次:元数据未变,必须复用摘要并且不产生上传项。 + let second = + compute_project_snapshot_diff(&first_scan, &first.current, PROJECT_SNAPSHOT_MAX_SYNC_BYTES) + .expect("second diff"); + assert!(second.uploads.is_empty(), "{:?}", second.uploads); + assert!(second.deleted.is_empty()); + assert!(second.metadata_only.is_empty()); + assert!(!second.has_changes()); + assert_eq!(second.current, first.current); + + // 只改一个文件:差异集合恰好包含它。 + write_fixture_file(root.path(), "game/a.txt", b"alpha-changed"); + let third = compute_project_snapshot_diff( + &scan_fixture(root.path()), + &first.current, + PROJECT_SNAPSHOT_MAX_SYNC_BYTES, + ) + .expect("third diff"); + assert_eq!(paths_of(&third.uploads), vec!["game/a.txt"]); + + // 删除文件只体现在清单:没有上传项,但 deleted 里能读到。 + fs::remove_file(root.path().join("game/b.txt")).expect("delete fixture file"); + let fourth = compute_project_snapshot_diff( + &scan_fixture(root.path()), + &third.current, + PROJECT_SNAPSHOT_MAX_SYNC_BYTES, + ) + .expect("fourth diff"); + assert!(fourth.uploads.is_empty()); + assert_eq!(fourth.deleted, vec!["game/b.txt".to_string()]); +} + +#[test] +fn project_snapshot_diff_treats_touched_but_identical_content_as_metadata_only() { + let root = fixture_root(); + write_fixture_file(root.path(), "game/a.txt", b"alpha"); + let scan = scan_fixture(root.path()); + let checksum = project_snapshot_checksum(b"alpha"); + let mut previous = BTreeMap::new(); + previous.insert( + "game/a.txt".to_string(), + ProjectSnapshotIndexedFile { + size_bytes: 5, + // 修改时间不同但内容一致:只能靠摘要判定,不能重复上传。 + modified_ms: scan.files[0].modified_ms.saturating_sub(1_000), + checksum, + }, + ); + let diff = compute_project_snapshot_diff(&scan, &previous, PROJECT_SNAPSHOT_MAX_SYNC_BYTES) + .expect("metadata-only diff"); + assert!(diff.uploads.is_empty()); + assert_eq!(diff.metadata_only, vec!["game/a.txt".to_string()]); + assert!(diff.has_changes()); +} + +#[test] +fn project_snapshot_diff_defers_files_over_the_sync_budget() { + let root = fixture_root(); + write_fixture_file(root.path(), "game/a.txt", b"0123456789"); + write_fixture_file(root.path(), "game/b.txt", b"0123456789"); + let scan = scan_fixture(root.path()); + let diff = compute_project_snapshot_diff(&scan, &BTreeMap::new(), 15).expect("budget diff"); + assert_eq!(paths_of(&diff.uploads), vec!["game/a.txt"]); + assert_eq!( + diff.deferred + .iter() + .map(|entry| entry.relative_path.clone()) + .collect::>(), + vec!["game/b.txt".to_string()] + ); + assert_eq!(diff.upload_bytes, 10); +} + +#[test] +fn project_snapshot_synced_files_exclude_failed_and_deferred_paths() { + let root = fixture_root(); + write_fixture_file(root.path(), "game/a.txt", b"a"); + write_fixture_file(root.path(), "game/b.txt", b"b"); + write_fixture_file(root.path(), "game/c.txt", b"c"); + let scan = scan_fixture(root.path()); + let mut diff = + compute_project_snapshot_diff(&scan, &BTreeMap::new(), PROJECT_SNAPSHOT_MAX_SYNC_BYTES) + .expect("diff"); + diff.deferred.push(ProjectSnapshotSkippedPath { + relative_path: "game/c.txt".to_string(), + reason: "fixture".to_string(), + }); + let uploaded = BTreeSet::from(["game/a.txt".to_string()]); + let synced = build_project_snapshot_synced_files(&diff, &uploaded); + assert_eq!( + synced.keys().cloned().collect::>(), + vec!["game/a.txt".to_string()], + "未成功上传与延后的路径不能进入新索引,否则下一次同步会漏传" + ); +} + +#[test] +fn project_snapshot_sync_is_serialized_per_project() { + let active = Arc::new(AtomicUsize::new(0)); + let peak = Arc::new(AtomicUsize::new(0)); + let key = "c:/fixture/serialized-project"; + let mut handles = Vec::new(); + for _ in 0..3 { + let active = Arc::clone(&active); + let peak = Arc::clone(&peak); + handles.push(std::thread::spawn(move || { + run_project_snapshot_sync(key, || { + let current = active.fetch_add(1, Ordering::SeqCst) + 1; + peak.fetch_max(current, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(30)); + active.fetch_sub(1, Ordering::SeqCst); + }); + })); + } + for handle in handles { + handle.join().expect("join serialized sync thread"); + } + assert_eq!(peak.load(Ordering::SeqCst), 1); +} + +#[test] +fn project_snapshot_periodic_trigger_yields_while_a_sync_is_in_flight() { + let key = "c:/fixture/periodic-project"; + let (started_sender, started_receiver) = mpsc::channel(); + let handle = std::thread::spawn(move || { + run_project_snapshot_sync(key, || { + started_sender.send(()).expect("signal started sync"); + std::thread::sleep(Duration::from_millis(200)); + }); + }); + started_receiver.recv().expect("wait for in-flight sync"); + assert!( + try_run_project_snapshot_sync(key, || ()).is_none(), + "在途同步期间周期触发必须直接让位" + ); + handle.join().expect("join in-flight sync"); + assert!(try_run_project_snapshot_sync(key, || ()).is_some()); +} + +fn read_http_request_with_body(stream: &mut TcpStream) -> String { + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .expect("set fixture read timeout"); + let mut bytes = Vec::new(); + let mut buffer = [0_u8; 4096]; + let header_end = loop { + let read = stream.read(&mut buffer).expect("read fixture request"); + assert!(read > 0, "fixture request closed before headers"); + bytes.extend_from_slice(&buffer[..read]); + if let Some(index) = bytes.windows(4).position(|window| window == b"\r\n\r\n") { + break index + 4; + } + }; + let headers = String::from_utf8_lossy(&bytes[..header_end]).into_owned(); + let content_length = headers + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().ok())? + }) + .unwrap_or(0); + while bytes.len() < header_end + content_length { + let read = stream.read(&mut buffer).expect("read fixture request body"); + if read == 0 { + break; + } + bytes.extend_from_slice(&buffer[..read]); + } + String::from_utf8_lossy(&bytes).into_owned() +} + +fn spawn_snapshot_fixture( + response_status: &'static str, + response_body: String, +) -> (String, std::thread::JoinHandle) { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind fixture listener"); + let address = listener.local_addr().expect("read fixture address"); + let handle = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept fixture request"); + let request = read_http_request_with_body(&mut stream); + let response = format!( + "HTTP/1.1 {response_status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{response_body}", + response_body.len() + ); + stream + .write_all(response.as_bytes()) + .expect("write fixture response"); + request + }); + (format!("http://{address}"), handle) +} + +fn fixture_session(api_base_url: String) -> PlatformSessionSnapshot { + PlatformSessionSnapshot { + user_id: "user-fixture".to_string(), + access_token: "fixture-token".to_string(), + api_base_url, + identity_generation: 1, + revision: 1, + } +} + +fn fixture_candidate( + root: &Path, + relative_path: &str, + bytes: &[u8], +) -> ProjectSnapshotUploadCandidate { + write_fixture_file(root, relative_path, bytes); + let path = root.join(relative_path); + let metadata = fs::symlink_metadata(&path).expect("read fixture metadata"); + ProjectSnapshotUploadCandidate { + relative_path: relative_path.to_string(), + size_bytes: bytes.len() as u64, + // 用真实修改时间:上传前的一致性复核会拿它比对,写死常量会把请求提前挡掉。 + modified_ms: project_snapshot_modified_ms(&metadata), + checksum: project_snapshot_checksum(bytes), + absolute_path: path, + } +} + +#[test] +fn project_snapshot_upload_marks_remote_duplicates_and_sends_marker_headers() { + let root = fixture_root(); + let candidate = fixture_candidate(root.path(), "game/a.txt", b"alpha"); + let body = serde_json::json!({ + "projectId": "project-1", + "relativePath": "game/a.txt", + "objectKey": "agc/project-snapshots/v1/user-fixture/project-1/game/a.txt", + "skipped": true, + "checksum": candidate.checksum, + "sizeBytes": candidate.size_bytes, + }) + .to_string(); + let (base_url, fixture) = spawn_snapshot_fixture("200 OK", body); + let session = fixture_session(base_url); + let diff = ProjectSnapshotDiff { + uploads: vec![candidate], + ..ProjectSnapshotDiff::default() + }; + let report = + tauri::async_runtime::block_on(upload_project_snapshot_diff(&session, "project-1", &diff)); + let request = fixture.join().expect("join fixture"); + + assert!(report.failures.is_empty(), "{:?}", report.failures); + assert_eq!(report.remote_skipped_files, 1); + assert_eq!(report.uploaded_bytes, 5); + assert_eq!( + report.uploaded_paths, + BTreeSet::from(["game/a.txt".to_string()]) + ); + assert!(request.starts_with("POST /api/agc/project-snapshots/files?")); + assert!(request.contains("projectId=project-1")); + assert!(request.contains("relativePath=game%2Fa.txt")); + assert!(request + .to_ascii_lowercase() + .contains("authorization: bearer fixture-token")); + assert!(request + .to_ascii_lowercase() + .contains("x-genarrative-client: agc")); + assert!(request.ends_with("alpha")); +} + +#[test] +fn project_snapshot_file_matches_detects_metadata_drift() { + let root = fixture_root(); + write_fixture_file(root.path(), "game/a.txt", b"alpha"); + let path = root.path().join("game/a.txt"); + let metadata = fs::symlink_metadata(&path).expect("fixture metadata"); + let size = metadata.len(); + let modified = project_snapshot_modified_ms(&metadata); + + assert!(project_snapshot_file_matches(&path, size, modified)); + assert!( + !project_snapshot_file_matches(&path, size + 1, modified), + "字节数变化必须被判为已改写" + ); + assert!( + !project_snapshot_file_matches(&path, size, modified + 1), + "修改时间变化必须被判为已改写" + ); + assert!( + !project_snapshot_file_matches(&root.path().join("game/missing.txt"), size, modified), + "文件消失必须被判为已改写" + ); +} + +#[test] +fn project_snapshot_diff_defers_files_that_changed_while_being_read() { + let root = fixture_root(); + write_fixture_file(root.path(), "game/a.txt", b"alpha"); + let mut previous = BTreeMap::new(); + previous.insert( + "game/a.txt".to_string(), + ProjectSnapshotIndexedFile { + size_bytes: 5, + modified_ms: 42, + checksum: "fnv1a64:00000000000000aa".to_string(), + }, + ); + // 扫描时刻的元数据与磁盘现状不一致:等价于"扫描之后文件被改写"。 + let scan = ProjectSnapshotScanResult { + files: vec![ProjectSnapshotScannedFile { + relative_path: "game/a.txt".to_string(), + size_bytes: 5, + modified_ms: 41, + absolute_path: root.path().join("game/a.txt"), + }], + skipped: Vec::new(), + }; + + let diff = compute_project_snapshot_diff(&scan, &previous, PROJECT_SNAPSHOT_MAX_SYNC_BYTES) + .expect("diff"); + assert!(diff.uploads.is_empty(), "{:?}", diff.uploads); + assert_eq!(diff.pending.len(), 1); + assert_eq!(diff.pending[0].relative_path, "game/a.txt"); + assert!( + diff.deleted.is_empty(), + "同步期间被改写的文件不能被当成删除,否则远端 GC 会误删" + ); + assert!( + diff.current.contains_key("game/a.txt"), + "应沿用上一轮记录,保持清单与远端对象一致" + ); +} + +#[test] +fn project_snapshot_upload_skips_files_that_changed_after_the_diff() { + let root = fixture_root(); + let mut candidate = fixture_candidate(root.path(), "game/a.txt", b"alpha"); + candidate.modified_ms = candidate.modified_ms.saturating_sub(1_000); + // 服务地址故意指向未监听端口:只要请求真的发出去就会出现 transport 失败, + // 因此这里同时证明"没有发出请求"和"分类是 file-changed"。 + let session = fixture_session("http://127.0.0.1:9".to_string()); + let diff = ProjectSnapshotDiff { + uploads: vec![candidate], + ..ProjectSnapshotDiff::default() + }; + + let report = + tauri::async_runtime::block_on(upload_project_snapshot_diff(&session, "project-1", &diff)); + assert!(report.uploaded_paths.is_empty()); + assert_eq!(report.failures.len(), 1); + assert_eq!(report.failures[0].code, "file-changed"); + assert!( + ProjectSnapshotUploadErrorKind::FileChanged.is_retryable(), + "文件被改写不是终态失败,下一次触发应重试" + ); +} + +#[test] +fn project_snapshot_upload_stops_after_a_deterministic_authentication_failure() { + let root = fixture_root(); + let first = fixture_candidate(root.path(), "game/a.txt", b"alpha"); + let second = fixture_candidate(root.path(), "game/b.txt", b"beta!"); + let (base_url, fixture) = spawn_snapshot_fixture("401 Unauthorized", "{}".to_string()); + let session = fixture_session(base_url); + let diff = ProjectSnapshotDiff { + uploads: vec![first, second], + ..ProjectSnapshotDiff::default() + }; + let report = + tauri::async_runtime::block_on(upload_project_snapshot_diff(&session, "project-1", &diff)); + fixture.join().expect("join fixture"); + + assert!(report.uploaded_paths.is_empty()); + assert_eq!(report.failures.len(), 2); + assert_eq!(report.failures[0].code, "authentication-required"); + assert_eq!(report.failures[0].relative_path, "game/a.txt"); + assert_eq!(report.failures[1].relative_path, "game/b.txt"); + assert!( + !ProjectSnapshotUploadErrorKind::Authentication.is_retryable(), + "鉴权失败不能进入自动重试" + ); +} + +#[test] +fn project_snapshot_project_path_is_read_from_window_urls_only() { + let url = url::Url::parse("tauri://localhost/index.html?main&projectPath=C%3A%5Cgames%5Cdemo") + .expect("parse fixture url"); + assert_eq!( + project_snapshot_project_path_from_url(&url), + Some("C:\\games\\demo".to_string()) + ); + let launcher = url::Url::parse("tauri://localhost/index.html?launcher").expect("parse url"); + assert_eq!(project_snapshot_project_path_from_url(&launcher), None); +} + +/// 真实链路冒烟:客户端差异引擎 → 本地 api-server → 真实 OSS。 +/// +/// 默认忽略;需要显式提供目标项目与登录态: +/// +/// ```text +/// $env:GENARRATIVE_AGC_PROJECT_SNAPSHOT_LIVE_PROJECT="<项目绝对路径>" +/// $env:GENARRATIVE_AGC_PROJECT_SNAPSHOT_LIVE_TOKEN="" +/// $env:GENARRATIVE_AGC_PROJECT_SNAPSHOT_LIVE_API_BASE_URL="http://127.0.0.1:8082" +/// cargo test --manifest-path apps/ai-game-creator-shell/src-tauri/Cargo.toml \ +/// project_snapshot_live_sync -- --ignored --nocapture +/// ``` +/// +/// 判定口径:第一次必须 `synced` 且上传数大于 0;紧接着的第二次必须 `no-op` 且上传 0 个文件, +/// 用来证明差异对比在真实服务端与真实 OSS 上确实避免了重复上传。 +/// +/// 另需 `GENARRATIVE_AGC_PROJECT_SNAPSHOT_LIVE_CONFIG_DIR` 指定 AppData 配置目录, +/// 否则测试进程里没有窗口 setup 初始化过该目录,索引无处可写。 +#[test] +#[ignore = "live smoke:需要真实 api-server 与 OSS 凭据"] +fn project_snapshot_live_sync_uploads_once_then_reports_no_op() { + let Ok(project_path) = std::env::var("GENARRATIVE_AGC_PROJECT_SNAPSHOT_LIVE_PROJECT") else { + println!("[skip] 未设置 GENARRATIVE_AGC_PROJECT_SNAPSHOT_LIVE_PROJECT"); + return; + }; + let Ok(access_token) = std::env::var("GENARRATIVE_AGC_PROJECT_SNAPSHOT_LIVE_TOKEN") else { + println!("[skip] 未设置 GENARRATIVE_AGC_PROJECT_SNAPSHOT_LIVE_TOKEN"); + return; + }; + let api_base_url = std::env::var("GENARRATIVE_AGC_PROJECT_SNAPSHOT_LIVE_API_BASE_URL") + .unwrap_or_else(|_| "http://127.0.0.1:8082".to_string()); + let user_id = std::env::var("GENARRATIVE_AGC_PROJECT_SNAPSHOT_LIVE_USER_ID") + .unwrap_or_else(|_| "snapshot-live-smoke-user".to_string()); + let Ok(config_dir) = std::env::var("GENARRATIVE_AGC_PROJECT_SNAPSHOT_LIVE_CONFIG_DIR") else { + println!("[skip] 未设置 GENARRATIVE_AGC_PROJECT_SNAPSHOT_LIVE_CONFIG_DIR"); + return; + }; + set_game_creator_runtime_config_dir(PathBuf::from(config_dir.trim())); + + let _session = install_test_platform_session(&user_id, &access_token, &api_base_url); + let root = PathBuf::from(project_path.trim()); + let first = tauri::async_runtime::block_on(sync_project_snapshot_async( + &root, + ProjectSnapshotSyncTrigger::Manual, + )) + .expect("第一次项目快照同步必须成功"); + println!("第一次同步:{first:#?}"); + assert_eq!(first.status, "synced", "{first:#?}"); + assert!(first.uploaded_files > 0, "{first:#?}"); + assert!(first.failed_files.is_empty(), "{first:#?}"); + + let second = tauri::async_runtime::block_on(sync_project_snapshot_async( + &root, + ProjectSnapshotSyncTrigger::Manual, + )) + .expect("第二次项目快照同步必须成功"); + println!("第二次同步:{second:#?}"); + assert_eq!(second.status, "no-op", "{second:#?}"); + assert_eq!(second.uploaded_files, 0, "{second:#?}"); +} diff --git a/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/transport.rs b/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/transport.rs new file mode 100644 index 000000000..6ff4c226a --- /dev/null +++ b/apps/ai-game-creator-shell/src-tauri/src/project_snapshot/transport.rs @@ -0,0 +1,337 @@ +use super::*; +use std::collections::BTreeSet; + +/// 上传失败的分类。鉴权与权限类失败不重试,其余交给下一次周期或关闭触发。 +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum ProjectSnapshotUploadErrorKind { + Authentication, + Permission, + /// 同步期间文件被改写:本轮跳过该文件,下一次重算即可,不是终态失败。 + FileChanged, + /// 服务端按配额或频率拒绝:等下一次触发再试。 + Throttled, + Rejected, + Upstream, + Transport, +} + +impl ProjectSnapshotUploadErrorKind { + pub(crate) fn code(self) -> &'static str { + match self { + Self::Authentication => "authentication-required", + Self::Permission => "permission-denied", + Self::FileChanged => "file-changed", + Self::Throttled => "throttled", + Self::Rejected => "request-rejected", + Self::Upstream => "upstream-failed", + Self::Transport => "transport-failed", + } + } + + /// 鉴权、权限与请求被拒都是确定性失败;重复提交同样的内容不会变好。 + pub(crate) fn is_retryable(self) -> bool { + matches!( + self, + Self::Upstream | Self::Transport | Self::FileChanged | Self::Throttled + ) + } +} + +#[derive(Clone, Debug)] +pub(crate) struct ProjectSnapshotUploadError { + kind: ProjectSnapshotUploadErrorKind, + detail: String, +} + +impl ProjectSnapshotUploadError { + fn new(kind: ProjectSnapshotUploadErrorKind, detail: impl Into) -> Self { + Self { + kind, + detail: detail.into(), + } + } + + pub(crate) fn kind(&self) -> ProjectSnapshotUploadErrorKind { + self.kind + } + + pub(crate) fn code(&self) -> &'static str { + self.kind.code() + } + + pub(crate) fn message(&self) -> String { + format!("{}: {}", self.kind.code(), self.detail) + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct ProjectSnapshotUploadFailure { + pub(crate) relative_path: String, + pub(crate) code: String, + pub(crate) detail: String, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub(crate) struct ProjectSnapshotUploadReport { + pub(crate) uploaded_paths: BTreeSet, + pub(crate) uploaded_bytes: u64, + pub(crate) remote_skipped_files: usize, + pub(crate) failures: Vec, +} + +impl ProjectSnapshotUploadReport { + fn from_hard_failure(paths: &[String], error: &ProjectSnapshotUploadError) -> Self { + Self { + uploaded_paths: BTreeSet::new(), + uploaded_bytes: 0, + remote_skipped_files: 0, + failures: paths + .iter() + .map(|relative_path| ProjectSnapshotUploadFailure { + relative_path: relative_path.clone(), + code: error.code().to_string(), + detail: error.detail.clone(), + }) + .collect(), + } + } +} + +/// 逐文件上传本次差异集合。单个文件失败只影响该文件;鉴权或权限失败会中止 +/// 后续请求,因为同样的凭据不会在这一次同步里变好。 +pub(crate) async fn upload_project_snapshot_diff( + session: &PlatformSessionSnapshot, + project_id: &str, + diff: &ProjectSnapshotDiff, +) -> ProjectSnapshotUploadReport { + let mut report = ProjectSnapshotUploadReport::default(); + if diff.uploads.is_empty() { + return report; + } + let client = match crate::http_client::agc_main_site_client_builder() + .timeout(Duration::from_secs( + PROJECT_SNAPSHOT_REQUEST_TIMEOUT_SECONDS, + )) + .build() + { + Ok(client) => client, + Err(error) => { + let failure = ProjectSnapshotUploadError::new( + ProjectSnapshotUploadErrorKind::Transport, + format!("创建项目快照上传客户端失败:{error}"), + ); + let paths = diff + .uploads + .iter() + .map(|candidate| candidate.relative_path.clone()) + .collect::>(); + return ProjectSnapshotUploadReport::from_hard_failure(&paths, &failure); + } + }; + + for (index, candidate) in diff.uploads.iter().enumerate() { + match upload_project_snapshot_file(&client, session, project_id, candidate).await { + Ok(skipped_remote) => { + report + .uploaded_paths + .insert(candidate.relative_path.clone()); + report.uploaded_bytes = report.uploaded_bytes.saturating_add(candidate.size_bytes); + if skipped_remote { + report.remote_skipped_files += 1; + } + } + Err(error) => { + let fatal = !error.kind().is_retryable(); + report.failures.push(ProjectSnapshotUploadFailure { + relative_path: candidate.relative_path.clone(), + code: error.code().to_string(), + detail: error.detail.clone(), + }); + if fatal { + for remaining in diff.uploads.iter().skip(index + 1) { + report.failures.push(ProjectSnapshotUploadFailure { + relative_path: remaining.relative_path.clone(), + code: error.code().to_string(), + detail: "上一次请求已确定性失败,本轮不再继续".to_string(), + }); + } + break; + } + } + } + } + report +} + +/// 返回是否为"远端已存在同内容对象"的跳过。 +async fn upload_project_snapshot_file( + client: &reqwest::Client, + session: &PlatformSessionSnapshot, + project_id: &str, + candidate: &ProjectSnapshotUploadCandidate, +) -> Result { + let bytes = read_project_snapshot_file_bytes(&candidate.absolute_path).map_err(|error| { + ProjectSnapshotUploadError::new(ProjectSnapshotUploadErrorKind::Rejected, error) + })?; + if bytes.len() as u64 != candidate.size_bytes { + return Err(ProjectSnapshotUploadError::new( + ProjectSnapshotUploadErrorKind::FileChanged, + format!( + "项目快照文件在同步期间发生变化:{}", + candidate.relative_path + ), + )); + } + // 上传前再复核一次元数据:只比长度会漏掉"改完又改回同样大小"的情况, + // 这种文件本轮不传,也不进入索引。 + if !project_snapshot_file_matches( + &candidate.absolute_path, + candidate.size_bytes, + candidate.modified_ms, + ) { + return Err(ProjectSnapshotUploadError::new( + ProjectSnapshotUploadErrorKind::FileChanged, + format!( + "项目快照文件在同步期间发生变化:{}", + candidate.relative_path + ), + )); + } + let url = project_snapshot_endpoint( + session, + PROJECT_SNAPSHOT_FILES_ENDPOINT, + [ + ("projectId", project_id.to_string()), + ("relativePath", candidate.relative_path.clone()), + ("checksum", candidate.checksum.clone()), + ("sizeBytes", candidate.size_bytes.to_string()), + ], + )?; + let request = client + .post(url) + .bearer_auth(&session.access_token) + .header(reqwest::header::CONTENT_TYPE, "application/octet-stream") + .body(bytes); + let response = crate::http_client::with_agc_main_site_marker(request) + .send() + .await + .map_err(|error| { + ProjectSnapshotUploadError::new( + ProjectSnapshotUploadErrorKind::Transport, + format!("项目快照上传请求失败:{error}"), + ) + })?; + let status = response.status(); + if !status.is_success() { + return Err(project_snapshot_response_error(status, response).await); + } + let parsed = response + .json::() + .await + .map_err(|error| { + ProjectSnapshotUploadError::new( + ProjectSnapshotUploadErrorKind::Upstream, + format!("项目快照上传响应无法解析:{error}"), + ) + })?; + if parsed.relative_path != candidate.relative_path || parsed.checksum != candidate.checksum { + return Err(ProjectSnapshotUploadError::new( + ProjectSnapshotUploadErrorKind::Upstream, + format!("项目快照上传响应与请求不一致:{}", candidate.relative_path), + )); + } + Ok(parsed.skipped) +} + +/// 提交本次同步的远端清单;删除只在这里表达。 +pub(crate) async fn upload_project_snapshot_manifest( + session: &PlatformSessionSnapshot, + payload: &shared_contracts::agc_project_snapshots::AgcProjectSnapshotManifestRequest, +) -> Result<(), ProjectSnapshotUploadError> { + let client = crate::http_client::agc_main_site_client_builder() + .timeout(Duration::from_secs( + PROJECT_SNAPSHOT_REQUEST_TIMEOUT_SECONDS, + )) + .build() + .map_err(|error| { + ProjectSnapshotUploadError::new( + ProjectSnapshotUploadErrorKind::Transport, + format!("创建项目快照上传客户端失败:{error}"), + ) + })?; + let url = project_snapshot_endpoint(session, PROJECT_SNAPSHOT_MANIFEST_ENDPOINT, [])?; + let request = client + .post(url) + .bearer_auth(&session.access_token) + .json(payload); + let response = crate::http_client::with_agc_main_site_marker(request) + .send() + .await + .map_err(|error| { + ProjectSnapshotUploadError::new( + ProjectSnapshotUploadErrorKind::Transport, + format!("项目快照清单上传请求失败:{error}"), + ) + })?; + let status = response.status(); + if !status.is_success() { + return Err(project_snapshot_response_error(status, response).await); + } + Ok(()) +} + +fn project_snapshot_endpoint( + session: &PlatformSessionSnapshot, + path: &str, + query: impl IntoIterator, +) -> Result { + let base_url = session.api_base_url.trim_end_matches('/'); + if base_url.is_empty() { + return Err(ProjectSnapshotUploadError::new( + ProjectSnapshotUploadErrorKind::Authentication, + "登录态缺少 API Server 地址", + )); + } + let mut url = reqwest::Url::parse(&format!("{base_url}{path}")).map_err(|error| { + ProjectSnapshotUploadError::new( + ProjectSnapshotUploadErrorKind::Transport, + format!("项目快照接口地址无效:{error}"), + ) + })?; + { + let mut pairs = url.query_pairs_mut(); + for (key, value) in query { + pairs.append_pair(key, &value); + } + } + Ok(url) +} + +async fn project_snapshot_response_error( + status: reqwest::StatusCode, + response: reqwest::Response, +) -> ProjectSnapshotUploadError { + let kind = match status.as_u16() { + 401 => ProjectSnapshotUploadErrorKind::Authentication, + 403 => ProjectSnapshotUploadErrorKind::Permission, + // 服务端配额与频率闸门:等下一次触发,不做本轮内重试。 + 429 => ProjectSnapshotUploadErrorKind::Throttled, + code if (400..500).contains(&code) => ProjectSnapshotUploadErrorKind::Rejected, + _ => ProjectSnapshotUploadErrorKind::Upstream, + }; + // 上游正文可能带内部信息,只保留状态码与有界摘要。 + let detail = response + .text() + .await + .map(|body| body.chars().take(200).collect::()) + .unwrap_or_default(); + let detail = detail.trim().to_string(); + if detail.is_empty() { + ProjectSnapshotUploadError::new(kind, format!("项目快照接口返回 HTTP {}", status.as_u16())) + } else { + ProjectSnapshotUploadError::new( + kind, + format!("项目快照接口返回 HTTP {}:{detail}", status.as_u16()), + ) + } +} diff --git a/apps/ai-game-creator-shell/src-tauri/src/template_library.rs b/apps/ai-game-creator-shell/src-tauri/src/template_library.rs new file mode 100644 index 000000000..ee2cea8dc --- /dev/null +++ b/apps/ai-game-creator-shell/src-tauri/src/template_library.rs @@ -0,0 +1,1272 @@ +//! AGC 游戏模板库:读取公共 OSS 模板清单、下载模板 zip、安装到本机并据此建项目。 +//! +//! 边界:模板库只做「远端清单 → 本机安装 → 复制进新项目」这条路,不生成模板内容, +//! 也不改写已存在项目。远端对象只允许来自受信任 OSS 主机下的 `templates/` 前缀; +//! 清单、zip 与封面一律先校验再落盘,zip 解压只接受普通文件与目录。 + +use super::*; +use serde::{Deserialize, Serialize}; + +const TEMPLATE_LIBRARY_SCHEMA_VERSION: &str = "agc-template-library.v1"; +const TEMPLATE_LIBRARY_INDEX_KEY: &str = "templates/index.json"; +const TEMPLATE_LIBRARY_OBJECT_PREFIX: &str = "templates/"; +const TEMPLATE_LIBRARY_OSS_HOST: &str = "agc-dev.oss-rg-china-mainland.aliyuncs.com"; +const DEFAULT_TEMPLATE_LIBRARY_BASE_URL: &str = + "https://agc-dev.oss-rg-china-mainland.aliyuncs.com"; +const TEMPLATE_LIBRARY_BASE_URL_ENV: &str = "AGC_TEMPLATE_LIBRARY_BASE_URL"; +const TEMPLATE_CACHE_DIRECTORY_NAME: &str = "templates"; +const TEMPLATE_INSTALLED_DIRECTORY_NAME: &str = "installed"; +const TEMPLATE_INSTALLED_MARKER_FILE: &str = "installed.json"; +const TEMPLATE_INDEX_CACHE_FILE: &str = "index.json"; +const TEMPLATE_LIBRARY_MAX_INDEX_BYTES: u64 = 4 * 1024 * 1024; +const TEMPLATE_ARCHIVE_MAX_BYTES: u64 = 512 * 1024 * 1024; +const TEMPLATE_ARCHIVE_MAX_FILES: usize = 4_096; +const TEMPLATE_ARCHIVE_MAX_FILE_BYTES: u64 = 256 * 1024 * 1024; +const TEMPLATE_ID_MAX_CHARS: usize = 64; +const TEMPLATE_VERSION_MAX_CHARS: usize = 32; + +/// 远端清单里的单个模板条目(`templates/index.json` 中的 `templates[]`)。 +#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub(crate) struct GameTemplateSummary { + pub(crate) id: String, + pub(crate) title: String, + #[serde(default)] + pub(crate) summary: String, + #[serde(default)] + pub(crate) tags: Vec, + #[serde(default)] + pub(crate) runtime: String, + #[serde(default)] + pub(crate) engine: String, + #[serde(default)] + pub(crate) engine_version: String, + pub(crate) template_version: String, + #[serde(default)] + pub(crate) updated_at: String, + #[serde(default)] + pub(crate) entry: String, + pub(crate) zip_key: String, + pub(crate) zip_size_bytes: u64, + pub(crate) zip_sha256: String, + pub(crate) cover_key: String, + #[serde(default)] + pub(crate) cover_width: u32, + #[serde(default)] + pub(crate) cover_height: u32, + #[serde(default)] + pub(crate) cover_sha256: String, + #[serde(default)] + pub(crate) metadata_key: String, +} + +/// `templates/index.json` 的库头信息。 +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub(crate) struct GameTemplateLibraryHeader { + pub(crate) schema_version: String, + #[serde(default)] + pub(crate) library: String, + #[serde(default)] + pub(crate) library_version: u32, + #[serde(default)] + pub(crate) updated_at: String, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +struct GameTemplateLibraryIndex { + #[serde(flatten)] + header: GameTemplateLibraryHeader, + #[serde(default)] + templates: Vec, +} + +/// 返回给前端的模板条目:清单字段 + 远端地址 + 本机安装状态。 +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct GameTemplateEntry { + pub(crate) id: String, + pub(crate) title: String, + pub(crate) summary: String, + pub(crate) tags: Vec, + pub(crate) runtime: String, + pub(crate) engine: String, + pub(crate) engine_version: String, + pub(crate) template_version: String, + pub(crate) updated_at: String, + pub(crate) entry: String, + pub(crate) zip_url: String, + pub(crate) zip_size_bytes: u64, + pub(crate) zip_sha256: String, + pub(crate) cover_url: String, + pub(crate) cover_width: u32, + pub(crate) cover_height: u32, + pub(crate) installed: bool, + pub(crate) installed_version: Option, + pub(crate) installed_at_millis: Option, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct GameTemplateLibrarySnapshot { + pub(crate) schema_version: String, + pub(crate) library: String, + pub(crate) library_version: u32, + pub(crate) updated_at: String, + pub(crate) fetched_at_millis: u64, + /// `network` 或 `cache`:命中本机缓存时前端应提示清单可能不是最新。 + pub(crate) source: String, + pub(crate) templates: Vec, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +struct InstalledGameTemplateRecord { + template_id: String, + template_version: String, + installed_at_millis: u64, + zip_sha256: String, + file_count: usize, + project_dir: String, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct InstalledGameTemplate { + pub(crate) template_id: String, + pub(crate) template_version: String, + pub(crate) installed_at_millis: u64, + pub(crate) zip_sha256: String, + pub(crate) file_count: usize, + pub(crate) project_dir: String, +} + +fn now_millis() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_millis() as u64) + .unwrap_or_default() +} + +fn template_library_base_url() -> String { + std::env::var(TEMPLATE_LIBRARY_BASE_URL_ENV) + .ok() + .map(|value| value.trim().trim_end_matches('/').to_string()) + .filter(|value| !value.is_empty()) + .unwrap_or_else(|| DEFAULT_TEMPLATE_LIBRARY_BASE_URL.to_string()) +} + +/// 只接受受信任 OSS 主机下的 HTTPS 地址;返回去掉尾斜杠的 base。 +pub(crate) fn validated_template_library_base_url(raw: &str) -> Result { + let trimmed = raw.trim().trim_end_matches('/'); + let parsed = url::Url::parse(trimmed).map_err(|_| "模板库地址无效".to_string())?; + if parsed.scheme() != "https" || parsed.host_str() != Some(TEMPLATE_LIBRARY_OSS_HOST) { + return Err("模板库地址必须来自受信任的 OSS".to_string()); + } + if parsed.path() != "/" || parsed.query().is_some() || parsed.fragment().is_some() { + return Err("模板库地址只能包含主机名".to_string()); + } + Ok(trimmed.to_string()) +} + +fn template_library_base() -> Result { + validated_template_library_base_url(&template_library_base_url()) +} + +fn sha256_hex(bytes: &[u8]) -> String { + let mut hasher = sha2::Sha256::new(); + hasher.update(bytes); + format!("{:x}", hasher.finalize()) +} + +fn is_valid_sha256(value: &str) -> bool { + let trimmed = value.trim(); + trimmed.len() == 64 && trimmed.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn validate_template_identifier(value: &str, max_chars: usize, label: &str) -> Result<(), String> { + let trimmed = value.trim(); + if trimmed.is_empty() || trimmed.chars().count() > max_chars { + return Err(format!("{label}无效")); + } + if !trimmed.chars().all(|value| { + value.is_ascii_lowercase() || value.is_ascii_digit() || matches!(value, '-' | '_' | '.') + }) { + return Err(format!("{label}无效")); + } + if trimmed.contains("..") { + return Err(format!("{label}无效")); + } + Ok(()) +} + +/// 远端对象键必须落在 `templates/` 前缀下,且不含绝对路径、上跳或反斜杠。 +pub(crate) fn validate_template_object_key(key: &str) -> Result<(), String> { + let trimmed = key.trim(); + if trimmed.is_empty() || !trimmed.starts_with(TEMPLATE_LIBRARY_OBJECT_PREFIX) { + return Err("模板对象键必须位于 templates/ 前缀下".to_string()); + } + if trimmed.starts_with('/') || trimmed.contains('\\') || trimmed.contains("..") { + return Err("模板对象键无效".to_string()); + } + if trimmed + .chars() + .any(|value| value.is_control() || value == ' ' || value == '?') + { + return Err("模板对象键无效".to_string()); + } + Ok(()) +} + +fn template_object_url(key: &str) -> Result { + validate_template_object_key(key)?; + Ok(format!("{}/{}", template_library_base()?, key.trim())) +} + +fn validate_template_summary(entry: &GameTemplateSummary) -> Result<(), String> { + validate_template_identifier(&entry.id, TEMPLATE_ID_MAX_CHARS, "模板 ID")?; + validate_template_identifier( + &entry.template_version, + TEMPLATE_VERSION_MAX_CHARS, + "模板版本", + )?; + if entry.title.trim().is_empty() || entry.title.chars().count() > 120 { + return Err(format!("模板 {} 的标题无效", entry.id)); + } + if entry.tags.len() > 32 { + return Err(format!("模板 {} 的标签过多", entry.id)); + } + validate_template_object_key(&entry.zip_key)?; + validate_template_object_key(&entry.cover_key)?; + if !entry.metadata_key.trim().is_empty() { + validate_template_object_key(&entry.metadata_key)?; + } + if entry.zip_size_bytes == 0 || entry.zip_size_bytes > TEMPLATE_ARCHIVE_MAX_BYTES { + return Err(format!("模板 {} 的包大小无效", entry.id)); + } + if !is_valid_sha256(&entry.zip_sha256) { + return Err(format!("模板 {} 的包摘要无效", entry.id)); + } + if !entry.cover_sha256.trim().is_empty() && !is_valid_sha256(&entry.cover_sha256) { + return Err(format!("模板 {} 的封面摘要无效", entry.id)); + } + Ok(()) +} + +/// 解析并校验远端清单;任何一条不合法都让整次读取失败,避免前端拿到半可信数据。 +pub(crate) fn parse_game_template_library_index( + body: &str, +) -> Result<(GameTemplateLibraryHeader, Vec), String> { + let index: GameTemplateLibraryIndex = + serde_json::from_str(body).map_err(|error| format!("模板库清单不是有效 JSON:{error}"))?; + if index.header.schema_version != TEMPLATE_LIBRARY_SCHEMA_VERSION { + return Err("模板库清单版本不受支持".to_string()); + } + let mut seen = std::collections::BTreeSet::new(); + for entry in &index.templates { + validate_template_summary(entry)?; + if !seen.insert(entry.id.clone()) { + return Err(format!("模板库清单存在重复模板:{}", entry.id)); + } + } + Ok((index.header, index.templates)) +} + +fn template_cache_root(app: &tauri::AppHandle) -> Result { + app.path() + .app_data_dir() + .map(|root| root.join(TEMPLATE_CACHE_DIRECTORY_NAME)) + .map_err(|error| format!("无法读取 AGC 应用数据目录:{error}")) +} + +fn installed_templates_root(cache_root: &Path) -> PathBuf { + cache_root.join(TEMPLATE_INSTALLED_DIRECTORY_NAME) +} + +fn installed_template_dir( + cache_root: &Path, + template_id: &str, + template_version: &str, +) -> Result { + validate_template_identifier(template_id, TEMPLATE_ID_MAX_CHARS, "模板 ID")?; + validate_template_identifier(template_version, TEMPLATE_VERSION_MAX_CHARS, "模板版本")?; + Ok(installed_templates_root(cache_root) + .join(template_id.trim()) + .join(template_version.trim())) +} + +fn read_installed_record(directory: &Path) -> Option { + let body = fs::read_to_string(directory.join(TEMPLATE_INSTALLED_MARKER_FILE)).ok()?; + serde_json::from_str(&body).ok() +} + +/// 扫描本机已安装模板,返回 `(模板 ID, 安装记录)`;损坏或缺少标记的目录视为未安装。 +fn collect_installed_records(cache_root: &Path) -> Vec { + let root = installed_templates_root(cache_root); + let Ok(template_entries) = fs::read_dir(&root) else { + return Vec::new(); + }; + let mut records = Vec::new(); + for template_entry in template_entries.flatten() { + let Ok(version_entries) = fs::read_dir(template_entry.path()) else { + continue; + }; + for version_entry in version_entries.flatten() { + if let Some(record) = read_installed_record(&version_entry.path()) { + records.push(record); + } + } + } + records +} + +fn installed_record_for( + records: &[InstalledGameTemplateRecord], + template_id: &str, +) -> Option { + records + .iter() + .filter(|record| record.template_id == template_id) + .max_by_key(|record| record.installed_at_millis) + .cloned() +} + +fn to_entry( + summary: &GameTemplateSummary, + installed: Option<&InstalledGameTemplateRecord>, +) -> Result { + Ok(GameTemplateEntry { + id: summary.id.clone(), + title: summary.title.clone(), + summary: summary.summary.clone(), + tags: summary.tags.clone(), + runtime: summary.runtime.clone(), + engine: summary.engine.clone(), + engine_version: summary.engine_version.clone(), + template_version: summary.template_version.clone(), + updated_at: summary.updated_at.clone(), + entry: summary.entry.clone(), + zip_url: template_object_url(&summary.zip_key)?, + zip_size_bytes: summary.zip_size_bytes, + zip_sha256: summary.zip_sha256.to_ascii_lowercase(), + cover_url: template_object_url(&summary.cover_key)?, + cover_width: summary.cover_width, + cover_height: summary.cover_height, + installed: installed.is_some(), + installed_version: installed.map(|record| record.template_version.clone()), + installed_at_millis: installed.map(|record| record.installed_at_millis), + }) +} + +/// 本地假数据注入:只在 `template-library-fixtures` feature(或测试构建)下编译。 +/// +/// 开启时把真实清单循环补齐成假数据(条数见 `fixtures::synthetic_template_count`); +/// 未开启时是恒等透传,正式构建里没有任何注入分支。 +fn apply_template_library_fixtures(entries: Vec) -> Vec { + #[cfg(feature = "template-library-fixtures")] + { + return fixtures::pad_synthetic_templates(entries, fixtures::synthetic_template_count()); + } + #[cfg(not(feature = "template-library-fixtures"))] + { + entries + } +} + +/// 本地假数据注入实现:只在 `template-library-fixtures` feature(或测试构建)下编译。 +/// +/// 位置刻意放在 Rust 侧:模板库的清单校验、安装状态与建项目都在这一侧,TS 只消费快照做渲染; +/// 在这里注入才能压到与真实一致的整条链路。正式构建不含该模块,因此不存在误触发路径。 +#[cfg(any(test, feature = "template-library-fixtures"))] +pub(crate) mod fixtures { + use super::*; + + pub(crate) const SYNTHETIC_COUNT_ENV: &str = "AGC_TEMPLATE_LIBRARY_SYNTHETIC_COUNT"; + pub(crate) const DEFAULT_SYNTHETIC_COUNT: usize = 1_000; + const MAX_SYNTHETIC_COUNT: usize = 20_000; + + /// 假数据条数:环境变量优先,缺省 1000;0 表示不注入。 + pub(crate) fn synthetic_template_count() -> usize { + parse_synthetic_count(std::env::var(SYNTHETIC_COUNT_ENV).ok().as_deref()) + } + + fn parse_synthetic_count(raw: Option<&str>) -> usize { + raw.and_then(|value| value.trim().parse::().ok()) + .unwrap_or(DEFAULT_SYNTHETIC_COUNT) + .min(MAX_SYNTHETIC_COUNT) + } + + /// 把真实清单循环复制成指定条数:id/标题/封面地址唯一,安装态按 1/3 混合。 + pub(crate) fn pad_synthetic_templates( + entries: Vec, + target: usize, + ) -> Vec { + if target <= entries.len() || entries.is_empty() { + return entries; + } + let base = entries.clone(); + let mut padded = entries; + let mut index = padded.len(); + while padded.len() < target { + let source = &base[index % base.len()]; + let installed = index % 3 == 0; + let mut next = source.clone(); + next.id = format!("{}-{:04}", source.id, index); + next.title = format!("{} · 假数据 {index:04}", source.title); + let mut tags = source.tags.clone(); + tags.push(format!("批次-{:02}", index % 20)); + next.tags = tags; + next.cover_url = format!("{}?synthetic={index}", source.cover_url); + next.installed = installed; + next.installed_version = installed.then(|| source.template_version.clone()); + next.installed_at_millis = installed.then(|| now_millis()); + padded.push(next); + index += 1; + } + padded + } + + #[cfg(test)] + mod tests { + use super::*; + + fn base_entry(id: &str, tag: &str) -> GameTemplateEntry { + GameTemplateEntry { + id: id.to_string(), + title: format!("模板 {id}"), + summary: "假数据基础条目".to_string(), + tags: vec![tag.to_string()], + runtime: "html".to_string(), + engine: "phaser".to_string(), + engine_version: "4.2.1".to_string(), + template_version: "0.1.0".to_string(), + updated_at: "2026-09-17T00:00:00Z".to_string(), + entry: "game/index.html".to_string(), + zip_url: format!("https://oss.example/templates/v1/{id}/template.zip"), + zip_size_bytes: 1024, + zip_sha256: "a".repeat(64), + cover_url: format!("https://oss.example/templates/v1/{id}/cover.svg"), + cover_width: 960, + cover_height: 540, + installed: false, + installed_version: None, + installed_at_millis: None, + } + } + + #[test] + fn parses_synthetic_count_from_env_value() { + assert_eq!(parse_synthetic_count(None), DEFAULT_SYNTHETIC_COUNT); + assert_eq!(parse_synthetic_count(Some(" 250 ")), 250); + assert_eq!(parse_synthetic_count(Some("0")), 0); + assert_eq!( + parse_synthetic_count(Some("not-a-number")), + DEFAULT_SYNTHETIC_COUNT + ); + assert_eq!(parse_synthetic_count(Some("999999")), MAX_SYNTHETIC_COUNT); + } + + #[test] + fn pads_entries_with_unique_identity_and_mixed_install_state() { + let base = vec![ + base_entry("blank-web", "空白"), + base_entry("blank-2d", "2d"), + ]; + let padded = pad_synthetic_templates(base.clone(), 9); + assert_eq!(padded.len(), 9); + // 真实条目保持原样排在最前。 + assert_eq!(padded[0].id, "blank-web"); + assert_eq!(padded[1].id, "blank-2d"); + let ids = padded + .iter() + .map(|entry| entry.id.clone()) + .collect::>(); + assert_eq!(ids.len(), 9, "假数据 id 必须唯一"); + let covers = padded + .iter() + .map(|entry| entry.cover_url.clone()) + .collect::>(); + assert_eq!(covers.len(), 9, "假数据封面地址必须唯一"); + assert!(padded.iter().any(|entry| entry.installed)); + assert!(padded.iter().any(|entry| !entry.installed)); + assert!(padded + .iter() + .skip(2) + .all(|entry| entry.tags.iter().any(|tag| tag.starts_with("批次-")))); + } + + #[test] + fn padding_is_a_no_op_without_room_to_fill() { + let base = vec![base_entry("blank-web", "空白")]; + assert_eq!(pad_synthetic_templates(base.clone(), 1).len(), 1); + assert_eq!(pad_synthetic_templates(base.clone(), 0).len(), 1); + assert!(pad_synthetic_templates(Vec::new(), 10).is_empty()); + } + } +} + +fn build_template_library_client() -> reqwest::Client { + reqwest::Client::builder() + .connect_timeout(Duration::from_secs(10)) + .timeout(Duration::from_secs(120)) + .build() + .unwrap_or_else(|_| reqwest::Client::new()) +} + +async fn fetch_limited_bytes( + client: &reqwest::Client, + url: &str, + max_bytes: u64, +) -> Result, String> { + let response = client + .get(url) + .send() + .await + .map_err(|error| format!("请求模板库失败:{error}"))?; + if !response.status().is_success() { + return Err(format!("模板库返回 HTTP {}", response.status().as_u16())); + } + if response + .content_length() + .is_some_and(|length| length > max_bytes) + { + return Err("模板库对象超过大小限制".to_string()); + } + let mut body = Vec::new(); + let mut stream = response.bytes_stream(); + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(|error| format!("读取模板库对象失败:{error}"))?; + if body.len() as u64 + chunk.len() as u64 > max_bytes { + return Err("模板库对象超过大小限制".to_string()); + } + body.extend_from_slice(&chunk); + } + Ok(body) +} + +fn write_cached_index(cache_root: &Path, body: &str) { + let _ = ensure_game_creator_private_directory_tree(cache_root, "模板库缓存目录"); + let _ = write_game_creator_private_file( + &cache_root.join(TEMPLATE_INDEX_CACHE_FILE), + body.as_bytes(), + "模板库清单缓存", + ); +} + +fn read_cached_index(cache_root: &Path) -> Option { + fs::read_to_string(cache_root.join(TEMPLATE_INDEX_CACHE_FILE)).ok() +} + +/// 单个 zip 条目路径:只允许相对普通路径,禁止绝对路径、上跳、反斜杠与盘符。 +pub(crate) fn safe_archive_relative_path(raw: &str) -> Result { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return Err("模板包条目名为空".to_string()); + } + let normalized = trimmed.replace('\\', "/"); + if normalized.starts_with('/') || normalized.contains(':') { + return Err(format!("模板包条目路径无效:{raw}")); + } + let mut path = PathBuf::new(); + for segment in normalized.split('/') { + if segment.is_empty() || segment == "." { + continue; + } + if segment == ".." { + return Err(format!("模板包条目路径无效:{raw}")); + } + path.push(segment); + } + if path.as_os_str().is_empty() { + return Err(format!("模板包条目路径无效:{raw}")); + } + Ok(path) +} + +fn extract_template_archive(bytes: &[u8], destination: &Path) -> Result { + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)) + .map_err(|error| format!("模板包不是有效 zip:{error}"))?; + if archive.len() > TEMPLATE_ARCHIVE_MAX_FILES { + return Err("模板包文件数量超过上限".to_string()); + } + let mut written = 0_usize; + for index in 0..archive.len() { + let mut entry = archive + .by_index(index) + .map_err(|error| format!("读取模板包条目失败:{error}"))?; + if entry + .unix_mode() + .is_some_and(|mode| mode & 0o170000 == 0o120000) + { + return Err("模板包不允许包含符号链接".to_string()); + } + let relative = safe_archive_relative_path(entry.name())?; + let target = destination.join(&relative); + if entry.is_dir() { + ensure_game_creator_private_directory_tree(&target, "模板目录")?; + continue; + } + if entry.size() > TEMPLATE_ARCHIVE_MAX_FILE_BYTES { + return Err(format!("模板包文件超过大小上限:{}", entry.name())); + } + let mut buffer = Vec::with_capacity(entry.size() as usize); + entry + .read_to_end(&mut buffer) + .map_err(|error| format!("读取模板包文件失败:{error}"))?; + if let Some(parent) = target.parent() { + ensure_game_creator_private_directory_tree(parent, "模板目录")?; + } + write_game_creator_private_file(&target, &buffer, "模板文件")?; + written += 1; + } + if written == 0 { + return Err("模板包没有可写入的文件".to_string()); + } + Ok(written) +} + +fn install_template_archive( + cache_root: &Path, + summary: &GameTemplateSummary, + bytes: &[u8], +) -> Result { + if bytes.len() as u64 != summary.zip_size_bytes { + return Err("模板包大小校验失败".to_string()); + } + let actual_sha256 = sha256_hex(bytes); + if actual_sha256 != summary.zip_sha256.trim().to_ascii_lowercase() { + return Err("模板包完整性校验失败".to_string()); + } + let directory = installed_template_dir(cache_root, &summary.id, &summary.template_version)?; + if directory.exists() { + // 只清理本模板自己的安装目录;路径由标识符白名单拼出,不含远端输入。 + let _ = fs::remove_dir_all(&directory); + } + ensure_game_creator_private_directory_tree(&directory, "模板安装目录")?; + let file_count = extract_template_archive(bytes, &directory)?; + let record = InstalledGameTemplateRecord { + template_id: summary.id.clone(), + template_version: summary.template_version.clone(), + installed_at_millis: now_millis(), + zip_sha256: actual_sha256, + file_count, + project_dir: directory.to_string_lossy().into_owned(), + }; + let body = serde_json::to_string_pretty(&record) + .map_err(|error| format!("写入模板安装记录失败:{error}"))?; + write_game_creator_private_file( + &directory.join(TEMPLATE_INSTALLED_MARKER_FILE), + body.as_bytes(), + "模板安装记录", + )?; + Ok(record) +} + +fn copy_template_project(source_dir: &Path, target_root: &Path) -> Result { + let mut copied = 0_usize; + let mut stack = vec![source_dir.to_path_buf()]; + while let Some(directory) = stack.pop() { + let entries = + fs::read_dir(&directory).map_err(|error| format!("读取模板目录失败:{error}"))?; + for entry in entries.flatten() { + let path = entry.path(); + if entry.file_name() == TEMPLATE_INSTALLED_MARKER_FILE { + continue; + } + let metadata = entry + .metadata() + .map_err(|error| format!("读取模板条目失败:{error}"))?; + if metadata.is_dir() { + stack.push(path); + continue; + } + if !metadata.is_file() { + return Err(format!("模板包含不支持的条目:{}", path.display())); + } + let relative = path + .strip_prefix(source_dir) + .map_err(|error| format!("模板条目路径无效:{error}"))?; + let target = target_root.join(relative); + if let Some(parent) = target.parent() { + ensure_game_creator_private_directory_tree(parent, "项目模板目录")?; + } + let bytes = fs::read(&path).map_err(|error| format!("读取模板文件失败:{error}"))?; + write_game_creator_private_file(&target, &bytes, "项目模板文件")?; + copied += 1; + } + } + if copied == 0 { + return Err("模板没有可复制的文件".to_string()); + } + Ok(copied) +} + +fn find_template_summary( + cache_root: &Path, + template_id: &str, + template_version: &str, +) -> Result { + let body = read_cached_index(cache_root).ok_or_else(|| "本机没有模板库清单缓存".to_string())?; + let (_, templates) = parse_game_template_library_index(&body)?; + templates + .into_iter() + .find(|entry| entry.id == template_id && entry.template_version == template_version) + .ok_or_else(|| "模板库清单里没有该模板版本".to_string()) +} + +async fn ensure_template_installed( + cache_root: &Path, + template_id: &str, + template_version: &str, +) -> Result { + let installed_directory = installed_template_dir(cache_root, template_id, template_version)?; + if let Some(record) = read_installed_record(&installed_directory) { + return Ok(record); + } + let summary = find_template_summary(cache_root, template_id, template_version)?; + let client = build_template_library_client(); + let url = template_object_url(&summary.zip_key)?; + let bytes = fetch_limited_bytes(&client, &url, TEMPLATE_ARCHIVE_MAX_BYTES).await?; + install_template_archive(cache_root, &summary, &bytes) +} + +#[tauri::command] +pub(crate) async fn fetch_game_template_library( + app: tauri::AppHandle, +) -> Result { + let cache_root = template_cache_root(&app)?; + ensure_game_creator_private_directory_tree(&cache_root, "模板库缓存目录")?; + let index_url = format!( + "{}/{}", + template_library_base()?, + TEMPLATE_LIBRARY_INDEX_KEY + ); + let client = build_template_library_client(); + let (body, source) = + match fetch_limited_bytes(&client, &index_url, TEMPLATE_LIBRARY_MAX_INDEX_BYTES).await { + Ok(bytes) => { + let body = + String::from_utf8(bytes).map_err(|_| "模板库清单不是有效 UTF-8".to_string())?; + parse_game_template_library_index(&body)?; + write_cached_index(&cache_root, &body); + (body, "network") + } + Err(error) => match read_cached_index(&cache_root) { + Some(cached) => { + parse_game_template_library_index(&cached)?; + (cached, "cache") + } + None => return Err(error), + }, + }; + let (header, templates) = parse_game_template_library_index(&body)?; + let installed = collect_installed_records(&cache_root); + let entries = templates + .iter() + .map(|summary| { + to_entry( + summary, + installed_record_for(&installed, &summary.id).as_ref(), + ) + }) + .collect::, _>>()?; + let entries = apply_template_library_fixtures(entries); + Ok(GameTemplateLibrarySnapshot { + schema_version: header.schema_version, + library: header.library, + library_version: header.library_version, + updated_at: header.updated_at, + fetched_at_millis: now_millis(), + source: source.to_string(), + templates: entries, + }) +} + +#[tauri::command] +pub(crate) async fn download_game_template( + app: tauri::AppHandle, + template_id: String, + template_version: String, +) -> Result { + let cache_root = template_cache_root(&app)?; + ensure_game_creator_private_directory_tree(&cache_root, "模板库缓存目录")?; + let record = + ensure_template_installed(&cache_root, template_id.trim(), template_version.trim()).await?; + Ok(InstalledGameTemplate { + template_id: record.template_id, + template_version: record.template_version, + installed_at_millis: record.installed_at_millis, + zip_sha256: record.zip_sha256, + file_count: record.file_count, + project_dir: record.project_dir, + }) +} + +/// 用已安装模板在自动工作区根目录下建项目:先把模板文件铺进新目录,再走标准项目初始化。 +pub(crate) fn create_project_from_installed_template_at( + projects_root: &Path, + installed_project_dir: &Path, + requested_name: Option<&str>, + planning: bool, +) -> Result { + let requested_name = requested_name + .map(normalize_game_creation_project_name) + .transpose()?; + if projects_root.as_os_str().is_empty() || !projects_root.is_absolute() { + return Err("自动工作区根目录必须是绝对路径".to_string()); + } + if !installed_project_dir.is_dir() { + return Err("模板尚未安装到本机".to_string()); + } + ensure_game_creator_private_directory_tree(projects_root, "自动工作区根目录")?; + prepare_game_creator_private_path_for_read(projects_root, true, "自动工作区根目录")?; + let metadata = fs::symlink_metadata(projects_root).map_err(|error| { + format!( + "读取自动工作区根目录失败:{}: {error}", + projects_root.display() + ) + })?; + if metadata.file_type().is_symlink() || !metadata.is_dir() { + return Err("自动工作区根目录必须是普通文件夹".to_string()); + } + + for _ in 0..16 { + let workspace_id = uuid::Uuid::new_v4().simple().to_string(); + let short_id = &workspace_id[..8]; + let project_name = requested_name.clone().unwrap_or_else(|| { + let prefix = if planning { + "策划项目" + } else { + "GameAgent 项目" + }; + format!("{prefix} {short_id}") + }); + let project_root = projects_root.join(format!("gameagent-{short_id}")); + match fs::create_dir(&project_root) { + Ok(()) => { + let result = (|| { + harden_new_game_creator_private_path(&project_root, true, "自动项目目录")?; + enforce_project_permission_policy(&project_root, "project.create")?; + let _lock = acquire_project_write_lock(&project_root, "project.create")?; + copy_template_project(installed_project_dir, &project_root)?; + init_local_game_project_at( + &project_root, + &format!("gameagent-{workspace_id}"), + &project_name, + ) + })(); + if result.is_err() { + let _ = fs::remove_dir_all(&project_root); + } + return result; + } + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => { + return Err(format!( + "创建自动工作区失败:{}: {error}", + project_root.display() + )); + } + } + } + Err("自动工作区命名冲突,请重试".to_string()) +} + +#[tauri::command] +pub(crate) async fn create_automatic_local_game_project_from_template( + app: tauri::AppHandle, + template_id: String, + template_version: String, + name: Option, + planning: Option, +) -> Result { + let projects_root = app + .path() + .app_data_dir() + .map(|root| root.join("projects")) + .map_err(|error| format!("无法读取 AGC 应用数据目录:{error}"))?; + let cache_root = template_cache_root(&app)?; + ensure_game_creator_private_directory_tree(&cache_root, "模板库缓存目录")?; + let record = + ensure_template_installed(&cache_root, template_id.trim(), template_version.trim()).await?; + create_project_from_installed_template_at( + &projects_root, + Path::new(&record.project_dir), + name.as_deref(), + planning.unwrap_or(false), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_index_body() -> String { + serde_json::json!({ + "schemaVersion": TEMPLATE_LIBRARY_SCHEMA_VERSION, + "library": "agc-game-templates", + "libraryVersion": 1, + "updatedAt": "2026-09-17T00:00:00Z", + "templates": [ + { + "id": "demo-template", + "title": "演示模板", + "summary": "用于测试", + "tags": ["2d", "demo"], + "runtime": "html", + "engine": "phaser", + "engineVersion": "4.2.1", + "templateVersion": "1.0.0", + "updatedAt": "2026-09-17T00:00:00Z", + "entry": "game/index.html", + "zipKey": "templates/v1/demo-template/template.zip", + "zipSizeBytes": 128, + "zipSha256": "0".repeat(64), + "coverKey": "templates/v1/demo-template/cover.png", + "coverWidth": 960, + "coverHeight": 540, + "coverSha256": "1".repeat(64), + "metadataKey": "templates/v1/demo-template/template.json" + } + ] + }) + .to_string() + } + + fn sample_summary() -> GameTemplateSummary { + parse_game_template_library_index(&sample_index_body()) + .expect("parse sample index") + .1 + .remove(0) + } + + fn build_archive(entries: &[(&str, &[u8])]) -> Vec { + let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default(); + for (name, bytes) in entries { + writer.start_file(*name, options).expect("start file"); + writer.write_all(bytes).expect("write file"); + } + writer.finish().expect("finish archive").into_inner() + } + + /// 自动工作区根目录要走私有 DACL 校验,和 `tests::unique_project_path` 一样 + /// 在临时目录下取一个尚未存在的唯一路径,而不是用 tempdir 预先建好的目录。 + fn unique_projects_root() -> PathBuf { + let millis = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock") + .as_millis(); + std::env::temp_dir().join(format!( + "genarrative-agc-template-library-test-{}-{millis}", + std::process::id() + )) + } + + #[test] + fn rejects_index_with_unsupported_schema_or_duplicate_templates() { + let unsupported = + sample_index_body().replace(TEMPLATE_LIBRARY_SCHEMA_VERSION, "agc-template-library.v2"); + assert!(parse_game_template_library_index(&unsupported).is_err()); + + let entry = serde_json::to_string(&sample_summary()).expect("serialize summary"); + let duplicated = serde_json::json!({ + "schemaVersion": TEMPLATE_LIBRARY_SCHEMA_VERSION, + "templates": [ + serde_json::from_str::(&entry).expect("value"), + serde_json::from_str::(&entry).expect("value"), + ] + }) + .to_string(); + let error = parse_game_template_library_index(&duplicated).expect_err("duplicate rejected"); + assert!(error.contains("重复模板"), "{error}"); + } + + #[test] + fn rejects_object_keys_outside_the_templates_prefix() { + assert!(validate_template_object_key("agc/templates/v1/demo/template.zip").is_err()); + assert!(validate_template_object_key("templates/../secret").is_err()); + assert!(validate_template_object_key("/templates/a.zip").is_err()); + assert!(validate_template_object_key("templates\\a.zip").is_err()); + assert!(validate_template_object_key("templates/v1/demo/template.zip").is_ok()); + } + + #[test] + fn rejects_template_base_url_outside_trusted_oss() { + assert!(validated_template_library_base_url( + "https://agc-dev.oss-rg-china-mainland.aliyuncs.com" + ) + .is_ok()); + assert!(validated_template_library_base_url( + "http://agc-dev.oss-rg-china-mainland.aliyuncs.com" + ) + .is_err()); + assert!(validated_template_library_base_url("https://evil.example.com").is_err()); + assert!(validated_template_library_base_url( + "https://agc-dev.oss-rg-china-mainland.aliyuncs.com/other-prefix" + ) + .is_err()); + } + + /// 固定 2026-09-17 实际发布的 `templates/index.json`:客户端解析必须与线上契约一致。 + #[test] + fn parses_the_published_library_index_fixture() { + let body = include_str!("../tests/fixtures/agc-template-library-index.json"); + let (header, templates) = + parse_game_template_library_index(body).expect("parse published index"); + assert_eq!(header.schema_version, TEMPLATE_LIBRARY_SCHEMA_VERSION); + assert_eq!(header.library, "agc-game-templates"); + assert_eq!( + templates + .iter() + .map(|entry| entry.id.as_str()) + .collect::>(), + vec![ + "blank-2d-canvas", + "blank-3d-scene", + "blank-web", + "phaser-2d-starter", + "threejs-3d-starter", + ] + ); + let first = templates + .iter() + .find(|entry| entry.id == "phaser-2d-starter") + .expect("phaser template"); + assert_eq!(first.runtime, "html"); + assert_eq!(first.tags.first().map(String::as_str), Some("起步工程")); + assert!(first.cover_width > 0 && first.cover_height > 0); + + let entry = to_entry(first, None).expect("build entry"); + let base = template_library_base().expect("trusted base"); + assert_eq!( + entry.zip_url, + format!("{base}/templates/v1/phaser-2d-starter/template.zip") + ); + assert_eq!( + entry.cover_url, + format!("{base}/templates/v1/phaser-2d-starter/cover.svg") + ); + assert!(!entry.installed); + } + + #[test] + fn rejects_archive_entries_that_escape_the_destination() { + assert!(safe_archive_relative_path("game/index.html").is_ok()); + assert!(safe_archive_relative_path("./game/index.html").is_ok()); + assert!(safe_archive_relative_path("../escape.txt").is_err()); + assert!(safe_archive_relative_path("game/../../escape.txt").is_err()); + assert!(safe_archive_relative_path("C:/escape.txt").is_err()); + assert!(safe_archive_relative_path("/escape.txt").is_err()); + + let archive = build_archive(&[("../escape.txt", b"nope")]); + let destination = tempfile::tempdir().expect("temp dir"); + assert!(extract_template_archive(&archive, destination.path()).is_err()); + assert!(!destination + .path() + .parent() + .unwrap() + .join("escape.txt") + .exists()); + } + + #[test] + fn installs_template_archive_and_reports_it_as_installed() { + let cache_root = tempfile::tempdir().expect("temp dir"); + let archive = build_archive(&[ + ("game/index.html", b""), + ("game/game.js", b"console.log('demo');"), + ]); + let mut summary = sample_summary(); + summary.zip_size_bytes = archive.len() as u64; + summary.zip_sha256 = sha256_hex(&archive); + + let record = install_template_archive(cache_root.path(), &summary, &archive) + .expect("install template"); + assert_eq!(record.file_count, 2); + let installed = collect_installed_records(cache_root.path()); + assert_eq!(installed.len(), 1); + assert_eq!(installed[0].template_version, "1.0.0"); + + let entry = to_entry( + &summary, + installed_record_for(&installed, &summary.id).as_ref(), + ) + .expect("build entry"); + assert!(entry.installed); + assert_eq!(entry.installed_version.as_deref(), Some("1.0.0")); + assert!(entry.zip_url.starts_with("https://")); + assert!(entry + .cover_url + .ends_with("/templates/v1/demo-template/cover.png")); + } + + #[test] + fn rejects_archive_when_size_or_digest_do_not_match_the_index() { + let cache_root = tempfile::tempdir().expect("temp dir"); + let archive = build_archive(&[("game/index.html", b"")]); + let mut summary = sample_summary(); + summary.zip_size_bytes = archive.len() as u64 + 1; + let error = install_template_archive(cache_root.path(), &summary, &archive) + .expect_err("size mismatch rejected"); + assert!(error.contains("大小校验失败"), "{error}"); + + summary.zip_size_bytes = archive.len() as u64; + summary.zip_sha256 = "f".repeat(64); + let error = install_template_archive(cache_root.path(), &summary, &archive) + .expect_err("digest mismatch rejected"); + assert!(error.contains("完整性校验失败"), "{error}"); + } + + #[test] + fn creates_project_from_installed_template_without_leaking_install_marker() { + let cache_root = tempfile::tempdir().expect("temp dir"); + let projects_root = unique_projects_root(); + let archive = build_archive(&[ + ("game/index.html", b"template"), + ("assets/README.txt", b"template assets"), + ]); + let mut summary = sample_summary(); + summary.zip_size_bytes = archive.len() as u64; + summary.zip_sha256 = sha256_hex(&archive); + let record = install_template_archive(cache_root.path(), &summary, &archive) + .expect("install template"); + + let result = create_project_from_installed_template_at( + &projects_root, + Path::new(&record.project_dir), + Some("模板项目"), + false, + ) + .expect("create project from template"); + assert_eq!(result.manifest.name, "模板项目"); + let project_root = Path::new(&result.project_path); + let index = + fs::read_to_string(project_root.join("game/index.html")).expect("template file copied"); + assert!(index.contains("template")); + assert!(project_root.join("assets/README.txt").is_file()); + assert!(!project_root.join(TEMPLATE_INSTALLED_MARKER_FILE).exists()); + assert!(!project_root.join("game/index.html.orig").exists()); + fs::remove_dir_all(&projects_root).ok(); + } + + #[test] + fn refuses_to_create_project_when_template_is_not_installed() { + let projects_root = tempfile::tempdir().expect("temp dir"); + let missing = projects_root.path().join("missing-template"); + let error = + create_project_from_installed_template_at(projects_root.path(), &missing, None, false) + .expect_err("missing template rejected"); + assert!(error.contains("模板尚未安装"), "{error}"); + } + + /// 正式构建(未开 feature)必须恒等透传:注入路径不能出现在默认产物里。 + #[cfg(not(feature = "template-library-fixtures"))] + #[test] + fn fixtures_are_inert_without_the_feature() { + let index_body = include_str!("../tests/fixtures/agc-template-library-index.json"); + let (_, templates) = + parse_game_template_library_index(index_body).expect("parse fixture index"); + let entries = templates + .iter() + .map(|summary| to_entry(summary, None).expect("entry")) + .collect::>(); + let original = entries.len(); + let applied = apply_template_library_fixtures(entries); + assert_eq!(applied.len(), original, "默认构建不应注入假数据"); + } + + /// 开启 feature 后同一次调用必须补齐到配置条数。 + #[cfg(feature = "template-library-fixtures")] + #[test] + fn fixtures_expand_entries_when_the_feature_is_enabled() { + let index_body = include_str!("../tests/fixtures/agc-template-library-index.json"); + let (_, templates) = + parse_game_template_library_index(index_body).expect("parse fixture index"); + let entries = templates + .iter() + .map(|summary| to_entry(summary, None).expect("entry")) + .collect::>(); + let applied = apply_template_library_fixtures(entries); + assert_eq!(applied.len(), fixtures::synthetic_template_count()); + assert!(applied.len() > templates.len()); + } + + /// 可选的真连检查:`cargo test --bin genarrative-ai-game-creator-shell template_library -- --ignored`。 + /// 默认跳过,避免离线环境因网络失败误报。 + #[tokio::test] + #[ignore = "需要网络:校验客户端能真实读到线上模板库清单与对象键"] + async fn fetches_the_live_template_library_index() { + let base = template_library_base().expect("trusted base"); + let client = build_template_library_client(); + let body = fetch_limited_bytes( + &client, + &format!("{base}/{TEMPLATE_LIBRARY_INDEX_KEY}"), + TEMPLATE_LIBRARY_MAX_INDEX_BYTES, + ) + .await + .expect("fetch live index"); + let body = String::from_utf8(body).expect("utf-8 index"); + let (header, templates) = + parse_game_template_library_index(&body).expect("parse live index"); + assert_eq!(header.schema_version, TEMPLATE_LIBRARY_SCHEMA_VERSION); + assert!(!templates.is_empty(), "线上模板库应当至少有一个模板"); + for entry in &templates { + let zip_url = template_object_url(&entry.zip_key).expect("trusted zip url"); + assert!(zip_url.starts_with(&format!("{base}/"))); + } + } + + /// 可选的真连检查:下载线上模板包并安装到临时目录,证明"清单 → 下载 → 摘要校验 → 解压"整条链路可用。 + #[tokio::test] + #[ignore = "需要网络:下载并安装线上模板包"] + async fn downloads_and_installs_a_live_template() { + let cache_root = tempfile::tempdir().expect("temp dir"); + let base = template_library_base().expect("trusted base"); + let client = build_template_library_client(); + let body = fetch_limited_bytes( + &client, + &format!("{base}/{TEMPLATE_LIBRARY_INDEX_KEY}"), + TEMPLATE_LIBRARY_MAX_INDEX_BYTES, + ) + .await + .expect("fetch live index"); + let body = String::from_utf8(body).expect("utf-8 index"); + let (_, templates) = parse_game_template_library_index(&body).expect("parse live index"); + let entry = templates + .iter() + .find(|template| template.id == "blank-web") + .expect("线上应存在 blank-web 模板"); + let bytes = fetch_limited_bytes( + &client, + &template_object_url(&entry.zip_key).expect("trusted zip url"), + TEMPLATE_ARCHIVE_MAX_BYTES, + ) + .await + .expect("download live template"); + let record = install_template_archive(cache_root.path(), entry, &bytes) + .expect("install live template"); + assert!(record.file_count >= 5, "模板文件数 {}", record.file_count); + let project_root = Path::new(&record.project_dir); + assert!(project_root.join("game/index.html").is_file()); + assert!(project_root.join("game/main.js").is_file()); + assert!(project_root.join(TEMPLATE_INSTALLED_MARKER_FILE).is_file()); + + // 同一条链路继续建项目:线上模板 → 本机安装 → 新项目目录。 + let projects_root = unique_projects_root(); + let created = create_project_from_installed_template_at( + &projects_root, + project_root, + Some("线上模板项目"), + false, + ) + .expect("create project from live template"); + assert_eq!(created.manifest.name, "线上模板项目"); + let created_root = Path::new(&created.project_path); + assert!(created_root.join("game/index.html").is_file()); + assert!(created_root.join("game/main.js").is_file()); + assert!(created_root.join(".agent/manifest.json").is_file()); + fs::remove_dir_all(&projects_root).ok(); + } +} diff --git a/apps/ai-game-creator-shell/src-tauri/src/tests/collaboration/delegation.rs b/apps/ai-game-creator-shell/src-tauri/src/tests/collaboration/delegation.rs index 7dd5c64a7..89a8d46e4 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/tests/collaboration/delegation.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/tests/collaboration/delegation.rs @@ -1587,6 +1587,7 @@ async fn canvas_replacement_rejects_parent_run_that_terminates_during_external_r "prompt": "生成原创晶体与潮汐构装体图集", "outputPath": "assets/art-spritesheet.png", "assetKind": "art-spritesheet", + "sliceMode": "connected-components", "replaceExisting": true }), ), diff --git a/apps/ai-game-creator-shell/src-tauri/src/tests/project.rs b/apps/ai-game-creator-shell/src-tauri/src/tests/project.rs index 135f67701..4faf39ccc 100644 --- a/apps/ai-game-creator-shell/src-tauri/src/tests/project.rs +++ b/apps/ai-game-creator-shell/src-tauri/src/tests/project.rs @@ -1690,6 +1690,7 @@ async fn platform_art_external_request_does_not_hold_project_lock_or_overwrite_m output_path: Some("assets/art-spritesheet.png".to_string()), asset_kind: "art-spritesheet".to_string(), asset_label: "游戏首版核心美术素材".to_string(), + slice_mode: Some("connected-components".to_string()), ..PlatformArtAssetGenerationOptions::default() }, )) 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 1d4c33053..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:; media-src 'self' asset: data: blob:; connect-src 'self' https://agc-dev.oss-rg-china-mainland.aliyuncs.com http://127.0.0.1:* ws://127.0.0.1:*; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' http://127.0.0.1:*", - "devCsp": "default-src 'self' customprotocol: asset: http://127.0.0.1:*; img-src 'self' asset: http://127.0.0.1:* data: blob:; media-src 'self' asset: http://127.0.0.1:* data: blob:; connect-src 'self' https://agc-dev.oss-rg-china-mainland.aliyuncs.com http://127.0.0.1:* ws://127.0.0.1:*; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' http://127.0.0.1:*" + "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-tauri/tests/fixtures/agc-template-library-index.json b/apps/ai-game-creator-shell/src-tauri/tests/fixtures/agc-template-library-index.json new file mode 100644 index 000000000..7cf1b85a7 --- /dev/null +++ b/apps/ai-game-creator-shell/src-tauri/tests/fixtures/agc-template-library-index.json @@ -0,0 +1,133 @@ +{ + "schemaVersion": "agc-template-library.v1", + "library": "agc-game-templates", + "libraryVersion": 1, + "updatedAt": "2026-09-17T03:22:43Z", + "templates": [ + { + "id": "blank-2d-canvas", + "title": "空白二维画布工程", + "summary": "原生 Canvas 二维空白工程:自适应画布、按设备像素比缩放与 requestAnimationFrame 主循环已就绪。", + "tags": [ + "空白", + "起步工程", + "2d", + "canvas" + ], + "runtime": "html", + "engine": "canvas", + "engineVersion": "", + "templateVersion": "0.1.0", + "updatedAt": "2026-09-17T03:22:43Z", + "entry": "game/index.html", + "zipKey": "templates/v1/blank-2d-canvas/template.zip", + "zipSizeBytes": 1534, + "zipSha256": "ff8f84e4793941acaf161738c2795f65c5d5390de8614f51aa9e3a5771767134", + "coverKey": "templates/v1/blank-2d-canvas/cover.svg", + "coverWidth": 960, + "coverHeight": 540, + "coverSha256": "afb753dc6d3de0f9fb6e03ec94f2be7221dd04c9d4ab3cf92311879f0af25192", + "metadataKey": "templates/v1/blank-2d-canvas/template.json" + }, + { + "id": "blank-3d-scene", + "title": "空白三维场景工程", + "summary": "Three.js 空白场景:空场景、透视相机、网格地面与自适应视口已就绪,适合从零搭三维玩法。", + "tags": [ + "空白", + "起步工程", + "3d", + "three.js" + ], + "runtime": "html", + "engine": "three.js", + "engineVersion": "0.180.0", + "templateVersion": "0.1.0", + "updatedAt": "2026-09-17T03:22:43Z", + "entry": "game/index.html", + "zipKey": "templates/v1/blank-3d-scene/template.zip", + "zipSizeBytes": 1644, + "zipSha256": "f3f295f4e5adcf1445d75229dc1b583376a9bc96d3f27a257d69ee3b7cace892", + "coverKey": "templates/v1/blank-3d-scene/cover.svg", + "coverWidth": 960, + "coverHeight": 540, + "coverSha256": "1429232adaf6df4457e45b4fc8d7ee9fab2e6bffce9f3f0016e91b81bb66c6a7", + "metadataKey": "templates/v1/blank-3d-scene/template.json" + }, + { + "id": "blank-web", + "title": "空白网页工程", + "summary": "最小网页工程(HTML + CSS + 原生 JS + Vite),没有任何引擎依赖,适合从零写玩法。", + "tags": [ + "空白", + "起步工程", + "网页", + "原生" + ], + "runtime": "html", + "engine": "none", + "engineVersion": "", + "templateVersion": "0.1.0", + "updatedAt": "2026-09-17T03:22:43Z", + "entry": "game/index.html", + "zipKey": "templates/v1/blank-web/template.zip", + "zipSizeBytes": 1212, + "zipSha256": "6fa4391f30342e8dcbdcf735f990d2534ea50405f119e4fa5879b83e8f00119e", + "coverKey": "templates/v1/blank-web/cover.svg", + "coverWidth": 960, + "coverHeight": 540, + "coverSha256": "326a2753386618971b1311043effa46c2e74bc1cfb116862c0ee4097dcd5086a", + "metadataKey": "templates/v1/blank-web/template.json" + }, + { + "id": "phaser-2d-starter", + "title": "Phaser 2D 起步工程", + "summary": "AGC 新建项目使用的默认二维起步工程(Phaser 4 + Vite),解压后即为可运行项目根。", + "tags": [ + "起步工程", + "2d", + "phaser", + "像素" + ], + "runtime": "html", + "engine": "phaser", + "engineVersion": "4.2.1", + "templateVersion": "0.1.0", + "updatedAt": "2026-09-17T03:22:43Z", + "entry": "game/index.html", + "zipKey": "templates/v1/phaser-2d-starter/template.zip", + "zipSizeBytes": 8770, + "zipSha256": "9026856c3c0b3a42401172e36ce8b450a65e9f11eb9096624d8990d51449d8ce", + "coverKey": "templates/v1/phaser-2d-starter/cover.svg", + "coverWidth": 960, + "coverHeight": 540, + "coverSha256": "fdb422027bf54bf755b2b91cd21fa10fdd7ce3f5c7e3ccd9ac3ffba602b12b96", + "metadataKey": "templates/v1/phaser-2d-starter/template.json" + }, + { + "id": "threejs-3d-starter", + "title": "Three.js 3D 起步工程", + "summary": "网页三维起步工程(Three.js + Vite),自带可旋转立方体场景、方向光与自适应视口。", + "tags": [ + "起步工程", + "3d", + "three.js", + "网页" + ], + "runtime": "html", + "engine": "three.js", + "engineVersion": "0.180.0", + "templateVersion": "0.1.0", + "updatedAt": "2026-09-17T03:22:43Z", + "entry": "game/index.html", + "zipKey": "templates/v1/threejs-3d-starter/template.zip", + "zipSizeBytes": 1697, + "zipSha256": "03096152b17cd6d55e7f6ccd518485136133cb54fd2a5a5d0ac8e0974149155c", + "coverKey": "templates/v1/threejs-3d-starter/cover.svg", + "coverWidth": 960, + "coverHeight": 540, + "coverSha256": "7ba013e8a8b515d7aff7146fe401afe5ba3416b9c69db181179705e1bce01beb", + "metadataKey": "templates/v1/threejs-3d-starter/template.json" + } + ] +} 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 70f9eb496..67d591ffb 100644 --- a/apps/ai-game-creator-shell/src/components/WindowChrome.tsx +++ b/apps/ai-game-creator-shell/src/components/WindowChrome.tsx @@ -1,8 +1,15 @@ import { getCurrentWindow } from '@tauri-apps/api/window'; import { Copy, Minus, Square, X } from 'lucide-react'; -import { type ReactNode, useCallback, useEffect, useState } from 'react'; +import { + type ReactNode, + useCallback, + useEffect, + useMemo, + useState, +} 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'; @@ -49,14 +56,21 @@ export function WindowChrome({ children }: WindowChromeProps) { setTitleState(normalizedTitle || WINDOW_CHROME_DEFAULT_TITLE); }, []); - const contextValue: WindowChromeContextValue = { - isWindowChrome: true, - title, - setTitle, - walletSlot, - activeProjectRuns, - setActiveProjectRuns, - }; + /** + * context value 必须 memo:内联对象会让所有 `useWindowChrome()` 消费方在标题栏 + * 每次渲染时都重新拿到新对象,进而连带重跑它们依赖 context 的 effect。 + */ + const contextValue = useMemo( + () => ({ + isWindowChrome: true, + title, + setTitle, + walletSlot, + activeProjectRuns, + setActiveProjectRuns, + }), + [title, setTitle, walletSlot, activeProjectRuns], + ); const [isMaximized, setIsMaximized] = useState(false); @@ -133,7 +147,7 @@ export function WindowChrome({ children }: WindowChromeProps) { return (
- + {appUpdateCheckEnabled ? : null}
diff --git a/apps/ai-game-creator-shell/src/features/agent-runtime/directActiveTurns.ts b/apps/ai-game-creator-shell/src/features/agent-runtime/directActiveTurns.ts index f859284e1..a9d4c478e 100644 --- a/apps/ai-game-creator-shell/src/features/agent-runtime/directActiveTurns.ts +++ b/apps/ai-game-creator-shell/src/features/agent-runtime/directActiveTurns.ts @@ -38,6 +38,14 @@ export function useDirectActiveTurns({ const [snapshotReadFailed, setSnapshotReadFailed] = useState(false); const mountedRef = useRef(true); const inFlightRef = useRef | null>(null); + /** + * 上一次成功读取到的快照签名。 + * + * 轮询每 5 秒跑一次,如果每次都 `setActiveTurns(新数组)`,即使内容一模一样也会 + * 换掉数组身份:所有依赖 `activeTurns` 的 effect 都会跟着重跑(窗口标题栏的活动项目 + * 面板就是这么被反复重发布的)。这里只在内容真的变了才更新状态。 + */ + const lastSnapshotSignatureRef = useRef(''); const retryTimerRef = useRef(null); useEffect(() => { @@ -72,7 +80,12 @@ export function useDirectActiveTurns({ if (!mountedRef.current) { return; } - setActiveTurns(Array.isArray(turns) ? turns : []); + const nextTurns = Array.isArray(turns) ? turns : []; + const nextSignature = JSON.stringify(nextTurns); + if (nextSignature !== lastSnapshotSignatureRef.current) { + lastSnapshotSignatureRef.current = nextSignature; + setActiveTurns(nextTurns); + } setSnapshotReadFailed(false); inFlightRef.current = null; return; @@ -99,8 +112,10 @@ export function useDirectActiveTurns({ useEffect(() => { if (!enabled || !invoke) { - setActiveTurns([]); - setSnapshotReadFailed(false); + lastSnapshotSignatureRef.current = ''; + // 空态也要保持引用稳定:已经空了就不要再换一个新数组。 + setActiveTurns((current) => (current.length === 0 ? current : [])); + setSnapshotReadFailed((current) => (current ? false : current)); return; } void refreshActiveTurns(); diff --git a/apps/ai-game-creator-shell/src/features/app-shell/WorkspaceLauncher.tsx b/apps/ai-game-creator-shell/src/features/app-shell/WorkspaceLauncher.tsx index d7c064561..85107f7b9 100644 --- a/apps/ai-game-creator-shell/src/features/app-shell/WorkspaceLauncher.tsx +++ b/apps/ai-game-creator-shell/src/features/app-shell/WorkspaceLauncher.tsx @@ -32,8 +32,10 @@ import { type ProjectManifestSnapshotSource, rereadAuthoritativeProjectManifestSnapshot, } from '../../view/project-development/projectResourceLiveUpdateModel'; +import TemplateLibraryView from '../../view/template-library'; import { useDirectActiveTurns } from '../agent-runtime/directActiveTurns'; import { RuntimeConfigDialog } from '../runtime-config/RuntimeConfigDialog'; +import { useTemplateLibrary } from '../template-library/useTemplateLibrary'; import { AccountWalletBar, AccountWalletDialogs } from './AccountWallet'; import { DeveloperAgentDialogs, @@ -90,6 +92,11 @@ export function WorkspaceLauncherShell({ setAgentChatProjectPath: developerAgent.setAgentChatProjectPath, rememberRecentWorkspace, }); + const templateLibrary = useTemplateLibrary({ + onProjectCreated: async (result) => { + await homeProject.enterCreatedTemplateProject(result); + }, + }); const { projectPath, setProjectPath, @@ -222,17 +229,29 @@ export function WorkspaceLauncherShell({ [setProjectPath], ); + /** + * 项目卡片面板发布给窗口标题栏的回调必须走 ref。 + * + * `openProject` 来自 `useHomeProjectCreation` 的普通函数(每次渲染都是新身份), + * 所以 `openActiveProject` 的引用每渲染都变;如果它进 effect 依赖,就会变成 + * 「effect 每渲染重跑 → cleanup/setActiveProjectRuns 改 WindowChrome 状态 → 重新渲染」 + * 的无限 setState 循环(React 报 `Maximum update depth exceeded`)。 + * 这里只让 effect 依赖真正的数据,回调通过 ref 取最新实现。 + */ + const openActiveProjectRef = useRef(openActiveProject); + openActiveProjectRef.current = openActiveProject; + useEffect(() => { setActiveProjectRuns({ activeTurns, currentProjectPath: currentProjectContext?.projectPath ?? null, readFailed: snapshotReadFailed, - onOpenProject: openActiveProject, + onOpenProject: (projectPath: string) => + openActiveProjectRef.current(projectPath), }); }, [ activeTurns, currentProjectContext?.projectPath, - openActiveProject, setActiveProjectRuns, snapshotReadFailed, ]); @@ -580,6 +599,13 @@ export function WorkspaceLauncherShell({ void openProject(path, 'open'); }} onProjectPick={() => void homeProject.pickAndOpenProject()} + templateRecommendations={templateLibrary.templates} + templateLibraryLoading={ + templateLibrary.status === 'loading' || + templateLibrary.status === 'idle' + } + templateLibraryError={templateLibrary.error} + onTemplateLibraryOpen={() => setLauncherView('template-library')} /> ) : launcherView === 'projects' ? ( + ) : launcherView === 'template-library' ? ( + setLauncherView('home')} + /> ) : launcherView === 'agent-chat' ? ( 桌面客户端
-
- - - {appUpdateStatus} - -
+ {appUpdateCheckEnabled ? ( +
+ + + {appUpdateStatus} + +
+ ) : null} ) : null}
diff --git a/apps/ai-game-creator-shell/src/features/template-library/templateLibraryGrid.ts b/apps/ai-game-creator-shell/src/features/template-library/templateLibraryGrid.ts new file mode 100644 index 000000000..539c5b7a8 --- /dev/null +++ b/apps/ai-game-creator-shell/src/features/template-library/templateLibraryGrid.ts @@ -0,0 +1,96 @@ +/** + * 模板库卡片网格的布局计算(纯函数)。 + * + * 页面用 `react-window` 的 `FixedSizeGrid` 做虚拟滚动:只渲染可视区域的行, + * 因此这里负责把「容器宽度 + 条目数」换算成列数、列宽、行高与行数, + * 保证卡片尺寸、封面比例与行高完全确定(虚拟列表要求固定行高)。 + */ + +import type { GameTemplateEntry } from './templateLibraryModel'; + +/** 卡片最小宽度(与 CSS 里旧的 `minmax(250px,1fr)` 口径一致)。 */ +export const TEMPLATE_CARD_MIN_WIDTH = 250; +/** 卡片之间的水平/垂直间隙。 */ +export const TEMPLATE_CARD_GAP = 14; +/** 封面宽高比:16:9。 */ +export const TEMPLATE_CARD_COVER_RATIO = 9 / 16; +/** 卡片封面以下的文字与按钮区固定高度。 */ +export const TEMPLATE_CARD_TEXT_HEIGHT = 150; +/** 额外预渲染的行数,减小快速滚动时的白屏。 */ +export const TEMPLATE_GRID_OVERSCAN_ROWS = 2; + +export type TemplateGridLayout = { + columnCount: number; + /** FixedSizeGrid 的列宽(含卡片右侧间隙)。 */ + columnWidth: number; + /** FixedSizeGrid 的行高(含卡片下方间隙)。 */ + rowHeight: number; + rowCount: number; +}; + +export function computeTemplateGridColumns(containerWidth: number): number { + if (!Number.isFinite(containerWidth) || containerWidth <= 0) { + return 1; + } + const columns = Math.floor( + (containerWidth + TEMPLATE_CARD_GAP) / + (TEMPLATE_CARD_MIN_WIDTH + TEMPLATE_CARD_GAP), + ); + return Math.max(1, columns); +} + +export function computeTemplateRowHeight(columnWidth: number): number { + const cardWidth = Math.max( + TEMPLATE_CARD_MIN_WIDTH, + Math.round(columnWidth) - TEMPLATE_CARD_GAP, + ); + return ( + Math.ceil(cardWidth * TEMPLATE_CARD_COVER_RATIO) + + TEMPLATE_CARD_TEXT_HEIGHT + + TEMPLATE_CARD_GAP + ); +} + +export function computeTemplateGridLayout({ + containerWidth, + itemCount, +}: { + containerWidth: number; + itemCount: number; +}): TemplateGridLayout { + const columnCount = computeTemplateGridColumns(containerWidth); + const columnWidth = Math.max(1, Math.floor(containerWidth / columnCount)); + return { + columnCount, + columnWidth, + rowHeight: computeTemplateRowHeight(columnWidth), + rowCount: Math.max(0, Math.ceil(Math.max(0, itemCount) / columnCount)), + }; +} + +/** 按行切分,行尾补 `null` 占位,保证虚拟列表的列索引与条目一一对应。 */ +export function buildTemplateRows( + templates: readonly GameTemplateEntry[], + columnCount: number, +): Array> { + if (columnCount <= 0) { + return []; + } + const rows: Array> = []; + for (let index = 0; index < templates.length; index += columnCount) { + const row: Array = []; + for (let column = 0; column < columnCount; column += 1) { + row.push(templates[index + column] ?? null); + } + rows.push(row); + } + return rows; +} + +/** 虚拟列表的稳定 key:行内槽位固定,避免筛选后复用错卡片。 */ +export function templateGridItemKey( + rowIndex: number, + columnIndex: number, +): string { + return `template-cell-${rowIndex}-${columnIndex}`; +} diff --git a/apps/ai-game-creator-shell/src/features/template-library/templateLibraryModel.ts b/apps/ai-game-creator-shell/src/features/template-library/templateLibraryModel.ts new file mode 100644 index 000000000..65f460fb9 --- /dev/null +++ b/apps/ai-game-creator-shell/src/features/template-library/templateLibraryModel.ts @@ -0,0 +1,208 @@ +/** + * AGC 模板库的前端模型:清单类型、搜索与筛选的纯函数。 + * + * 真源在 OSS 清单与 Rust 侧(`fetch_game_template_library`);这里只做展示层派生, + * 不缓存业务真相,也不拼远端地址(URL 由 Rust 侧按受信任 OSS 前缀给出)。 + */ + +export type GameTemplateLibrarySource = 'network' | 'cache'; + +export type GameTemplateEntry = { + id: string; + title: string; + summary: string; + tags: string[]; + runtime: string; + engine: string; + engineVersion: string; + templateVersion: string; + updatedAt: string; + entry: string; + zipUrl: string; + zipSizeBytes: number; + zipSha256: string; + coverUrl: string; + coverWidth: number; + coverHeight: number; + installed: boolean; + installedVersion: string | null; + installedAtMillis: number | null; +}; + +export type GameTemplateLibrarySnapshot = { + schemaVersion: string; + library: string; + libraryVersion: number; + updatedAt: string; + fetchedAtMillis: number; + source: GameTemplateLibrarySource; + templates: GameTemplateEntry[]; +}; + +export type InstalledGameTemplate = { + templateId: string; + templateVersion: string; + installedAtMillis: number; + zipSha256: string; + fileCount: number; + projectDir: string; +}; + +export type TemplateLibraryFilters = { + query: string; + tags: readonly string[]; + runtime: string; + installedOnly: boolean; +}; + +export const EMPTY_TEMPLATE_LIBRARY_FILTERS: TemplateLibraryFilters = { + query: '', + tags: [], + runtime: '', + installedOnly: false, +}; + +const RUNTIME_LABELS: Record = { + html: '网页', + unity: 'Unity', + godot: 'Godot', + cocos: 'Cocos', +}; + +export function templateRuntimeLabel(runtime: string): string { + const normalized = runtime.trim().toLowerCase(); + if (!normalized) return '未标注运行时'; + return RUNTIME_LABELS[normalized] ?? runtime.trim(); +} + +/** + * 空白分隔的多个关键词之间是「与」关系:每个词都必须命中标题、简介、标签或引擎, + * 这样「三消 像素」不会退化成命中任意一个就出现的宽泛搜索。 + */ +export function templateMatchesQuery( + template: GameTemplateEntry, + query: string, +): boolean { + const terms = query + .toLowerCase() + .split(/\s+/u) + .filter((term) => term.length > 0); + if (terms.length === 0) { + return true; + } + const haystack = [ + template.title, + template.summary, + template.engine, + template.runtime, + template.tags.join(' '), + ] + .join(' ') + .toLowerCase(); + return terms.every((term) => haystack.includes(term)); +} + +export function filterGameTemplates( + templates: readonly GameTemplateEntry[], + filters: TemplateLibraryFilters, +): GameTemplateEntry[] { + const selectedTags = filters.tags + .map((tag) => tag.trim().toLowerCase()) + .filter((tag) => tag.length > 0); + const runtime = filters.runtime.trim().toLowerCase(); + return templates.filter((template) => { + if (filters.installedOnly && !template.installed) { + return false; + } + if (runtime && template.runtime.trim().toLowerCase() !== runtime) { + return false; + } + if (selectedTags.length > 0) { + const templateTags = template.tags.map((tag) => tag.toLowerCase()); + if (!selectedTags.some((tag) => templateTags.includes(tag))) { + return false; + } + } + return templateMatchesQuery(template, filters.query); + }); +} + +/** 标签按出现次数降序,次数相同按名称排序,保证筛选条顺序稳定。 */ +export function collectGameTemplateTags( + templates: readonly GameTemplateEntry[], +): string[] { + const counts = new Map(); + for (const template of templates) { + for (const tag of template.tags) { + const trimmed = tag.trim(); + if (!trimmed) continue; + counts.set(trimmed, (counts.get(trimmed) ?? 0) + 1); + } + } + return [...counts.entries()] + .sort( + ([leftTag, leftCount], [rightTag, rightCount]) => + rightCount - leftCount || leftTag.localeCompare(rightTag, 'zh-CN'), + ) + .map(([tag]) => tag); +} + +export function collectGameTemplateRuntimes( + templates: readonly GameTemplateEntry[], +): string[] { + const runtimes = new Set(); + for (const template of templates) { + const runtime = template.runtime.trim().toLowerCase(); + if (runtime) runtimes.add(runtime); + } + return [...runtimes].sort((left, right) => + left.localeCompare(right, 'zh-CN'), + ); +} + +export function formatGameTemplateSize(bytes: number): string { + if (!Number.isFinite(bytes) || bytes <= 0) { + return '--'; + } + if (bytes < 1024) { + return `${Math.round(bytes)} B`; + } + if (bytes < 1024 * 1024) { + return `${(bytes / 1024).toFixed(1)} KB`; + } + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +export function isTemplateLibraryFiltersEmpty( + filters: TemplateLibraryFilters, +): boolean { + return ( + !filters.query.trim() && + filters.tags.length === 0 && + !filters.runtime.trim() && + !filters.installedOnly + ); +} + +export function toggleGameTemplateTag( + filters: TemplateLibraryFilters, + tag: string, +): TemplateLibraryFilters { + const exists = filters.tags.includes(tag); + return { + ...filters, + tags: exists + ? filters.tags.filter((value) => value !== tag) + : [...filters.tags, tag], + }; +} + +/** + * 已安装版本低于清单版本时必须重新下载;已安装且版本一致才算可直接使用。 + */ +export function needsTemplateDownload(template: GameTemplateEntry): boolean { + return ( + !template.installed || + template.installedVersion !== template.templateVersion + ); +} diff --git a/apps/ai-game-creator-shell/src/features/template-library/useTemplateLibrary.ts b/apps/ai-game-creator-shell/src/features/template-library/useTemplateLibrary.ts new file mode 100644 index 000000000..aa1ef20a7 --- /dev/null +++ b/apps/ai-game-creator-shell/src/features/template-library/useTemplateLibrary.ts @@ -0,0 +1,243 @@ +/** + * 模板库状态链路:拉取清单、下载模板、用模板建项目。 + * + * 远端真相全在 Rust 侧命令里(受信任 OSS 前缀 + 摘要校验 + 本机安装记录); + * 这里只维护界面状态,并在下载成功后把对应条目的安装状态就地更新, + * 避免为了一个"已下载"徽标再打一次清单请求。 + */ + +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; + +import { resolveTauriInvoke } from '../../app/tauri'; +import type { InitLocalProjectResult } from '../../app/types'; +import { + collectGameTemplateRuntimes, + collectGameTemplateTags, + EMPTY_TEMPLATE_LIBRARY_FILTERS, + filterGameTemplates, + type GameTemplateEntry, + type GameTemplateLibrarySnapshot, + type InstalledGameTemplate, + isTemplateLibraryFiltersEmpty, + needsTemplateDownload, + type TemplateLibraryFilters, + toggleGameTemplateTag, +} from './templateLibraryModel'; + +export type TemplateLibraryStatus = 'idle' | 'loading' | 'ready' | 'error'; +export type TemplateLibraryBusyKind = 'download' | 'create'; + +type UseTemplateLibraryOptions = { + /** 项目已建好:由调用方负责进入项目工作区(模板库不碰工作区状态)。 */ + onProjectCreated: (result: InitLocalProjectResult) => Promise | void; +}; + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +export function useTemplateLibrary({ + onProjectCreated, +}: UseTemplateLibraryOptions) { + const [snapshot, setSnapshot] = useState( + null, + ); + const [status, setStatus] = useState('idle'); + const [error, setError] = useState(''); + const [notice, setNotice] = useState(''); + const [filters, setFilters] = useState( + EMPTY_TEMPLATE_LIBRARY_FILTERS, + ); + const [busyTemplateId, setBusyTemplateId] = useState(null); + const [busyKind, setBusyKind] = useState( + null, + ); + const loadingRef = useRef(false); + + const refresh = useCallback(async () => { + if (loadingRef.current) { + return; + } + const invoke = resolveTauriInvoke(); + if (!invoke) { + setStatus('error'); + setError('需要在陶泥儿客户端内运行'); + return; + } + loadingRef.current = true; + setStatus('loading'); + setError(''); + try { + const next = await invoke( + 'fetch_game_template_library', + ); + setSnapshot(next); + setStatus('ready'); + setNotice( + next.source === 'cache' ? '远端清单暂时读不到,当前展示本机缓存' : '', + ); + } catch (nextError) { + setStatus('error'); + setError(errorMessage(nextError)); + } finally { + loadingRef.current = false; + } + }, []); + + useEffect(() => { + void refresh(); + }, [refresh]); + + const downloadTemplate = useCallback(async (template: GameTemplateEntry) => { + const invoke = resolveTauriInvoke(); + if (!invoke) { + throw new Error('需要在陶泥儿客户端内运行'); + } + setBusyTemplateId(template.id); + setBusyKind('download'); + setError(''); + try { + const installed = await invoke( + 'download_game_template', + { + templateId: template.id, + templateVersion: template.templateVersion, + }, + ); + setSnapshot((current) => + current + ? { + ...current, + templates: current.templates.map((entry) => + entry.id === template.id + ? { + ...entry, + installed: true, + installedVersion: installed.templateVersion, + installedAtMillis: installed.installedAtMillis, + } + : entry, + ), + } + : current, + ); + setNotice(`已下载模板「${template.title}」`); + return installed; + } catch (nextError) { + setError(errorMessage(nextError)); + throw nextError; + } finally { + setBusyTemplateId(null); + setBusyKind(null); + } + }, []); + + const createProjectFromTemplate = useCallback( + async (template: GameTemplateEntry) => { + const invoke = resolveTauriInvoke(); + if (!invoke) { + throw new Error('需要在陶泥儿客户端内运行'); + } + try { + if (needsTemplateDownload(template)) { + await downloadTemplate(template); + } + setBusyTemplateId(template.id); + setBusyKind('create'); + setError(''); + setNotice(`正在用模板「${template.title}」创建项目`); + const result = await invoke( + 'create_automatic_local_game_project_from_template', + { + templateId: template.id, + templateVersion: template.templateVersion, + name: null, + planning: false, + }, + ); + await onProjectCreated(result); + setNotice(`已用模板「${template.title}」创建项目`); + return result; + } catch (nextError) { + setError(errorMessage(nextError)); + throw nextError; + } finally { + setBusyTemplateId(null); + setBusyKind(null); + } + }, + [downloadTemplate, onProjectCreated], + ); + + const templates = useMemo( + () => snapshot?.templates ?? [], + [snapshot?.templates], + ); + const visibleTemplates = useMemo( + () => filterGameTemplates(templates, filters), + [templates, filters], + ); + const tagOptions = useMemo( + () => collectGameTemplateTags(templates), + [templates], + ); + const runtimeOptions = useMemo( + () => collectGameTemplateRuntimes(templates), + [templates], + ); + const installedCount = useMemo( + () => templates.filter((template) => template.installed).length, + [templates], + ); + const filtersActive = !isTemplateLibraryFiltersEmpty(filters); + + const setQuery = useCallback((query: string) => { + setFilters((current) => ({ ...current, query })); + }, []); + + const selectRuntime = useCallback((runtime: string) => { + setFilters((current) => ({ + ...current, + runtime: current.runtime === runtime ? '' : runtime, + })); + }, []); + + const toggleTag = useCallback((tag: string) => { + setFilters((current) => toggleGameTemplateTag(current, tag)); + }, []); + + const setInstalledOnly = useCallback((installedOnly: boolean) => { + setFilters((current) => ({ ...current, installedOnly })); + }, []); + + const clearFilters = useCallback(() => { + setFilters(EMPTY_TEMPLATE_LIBRARY_FILTERS); + }, []); + + return { + snapshot, + status, + error, + notice, + templates, + visibleTemplates, + tagOptions, + runtimeOptions, + installedCount, + filters, + filtersActive, + setQuery, + selectRuntime, + toggleTag, + setInstalledOnly, + clearFilters, + busyTemplateId, + busyKind, + refresh, + downloadTemplate, + createProjectFromTemplate, + clearNotice: useCallback(() => setNotice(''), []), + }; +} + +export type TemplateLibraryController = ReturnType; 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/src/styles.css b/apps/ai-game-creator-shell/src/styles.css index ace34579e..ea92910fb 100644 --- a/apps/ai-game-creator-shell/src/styles.css +++ b/apps/ai-game-creator-shell/src/styles.css @@ -8852,6 +8852,27 @@ iframe.preview-frame { overflow: hidden; } +/* 输入盒的弹层必须能溢出面板:控制排最左侧是「推理档」,它的菜单 + `.conversation-model-menu` 贴着触发钮右缘向左展开,窄布局(视口 ≤1000px 时对话面板 + 只有 280px 宽)下会伸到面板左侧之外;`.game-workbench-chat`、surface、conversation + 这三层 `overflow: hidden` 会沿着各自的溢出边界把它裁掉,档位文字正好落在被裁掉的 + 那半边,于是点开只能看到一个空盒子。所以这里让这三层不再裁切:菜单自身位置、 + 尺寸都不变,只是允许它盖到左侧面板上完整显示。消息列表自带 `overflow-y: auto` + (另一轴按规范计算为 auto),消息内容仍由列表自身裁剪。 */ +.game-workbench-chat:has(.project-supervisor-composer.is-direct-codex) { + overflow: visible; +} + +.game-workbench-chat .project-supervisor-surface.is-direct-codex { + overflow: visible; +} + +.game-workbench-chat + .project-supervisor-surface.is-direct-codex + .project-supervisor-conversation { + overflow: visible; +} + .game-workbench-chat .project-supervisor-message-list { height: 100%; min-height: 96px; diff --git a/apps/ai-game-creator-shell/src/view/home/InspirationGallery.tsx b/apps/ai-game-creator-shell/src/view/home/InspirationGallery.tsx deleted file mode 100644 index dc15824e9..000000000 --- a/apps/ai-game-creator-shell/src/view/home/InspirationGallery.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import { useEffect, useState } from 'react'; -import { createPortal } from 'react-dom'; - -// TODO: 后续改为由服务器下发灵感资源;届时保留此组件的展示与预览交互,移除本地目录扫描。 -const INSPIRATION_IMAGES = Object.entries( - import.meta.glob('./assets/inspiration/*.{webp,png,jpg,jpeg}', { - eager: true, - import: 'default', - query: '?url', - }), -) - .sort(([left], [right]) => - left.localeCompare(right, undefined, { numeric: true }), - ) - .map(([, image]) => image as string); - -export default function InspirationGallery() { - const [selectedImage, setSelectedImage] = useState(null); - - useEffect(() => { - if (!selectedImage) { - return; - } - const previousOverflow = document.body.style.overflow; - document.body.style.overflow = 'hidden'; - const handleKeyDown = (event: KeyboardEvent) => { - if (event.key === 'Escape') { - setSelectedImage(null); - } - }; - window.addEventListener('keydown', handleKeyDown); - return () => { - document.body.style.overflow = previousOverflow; - window.removeEventListener('keydown', handleKeyDown); - }; - }, [selectedImage]); - - return ( - <> -
- {INSPIRATION_IMAGES.map((image, index) => ( - - ))} -
- - {selectedImage - ? createPortal( -
setSelectedImage(null)} - > - 放大的灵感图片 event.stopPropagation()} - /> -
, - document.body, - ) - : null} - - ); -} diff --git a/apps/ai-game-creator-shell/src/view/home/TemplateRecommendations.tsx b/apps/ai-game-creator-shell/src/view/home/TemplateRecommendations.tsx new file mode 100644 index 000000000..56c4b1be6 --- /dev/null +++ b/apps/ai-game-creator-shell/src/view/home/TemplateRecommendations.tsx @@ -0,0 +1,96 @@ +import { BadgeCheck, Loader2, Package } from 'lucide-react'; + +import type { GameTemplateEntry } from '../../features/template-library/templateLibraryModel'; +import { templateRuntimeLabel } from '../../features/template-library/templateLibraryModel'; + +type TemplateRecommendationsProps = { + templates: readonly GameTemplateEntry[]; + loading: boolean; + error: string; + onOpenLibrary: () => void; +}; + +const RECOMMENDATION_LIMIT = 6; + +/** + * 首页模板推荐:只做展示与跳转,下载与建项目都在模板库页面里完成, + * 避免首页的卡片点击直接产生项目副作用。 + */ +export default function TemplateRecommendations({ + templates, + loading, + error, + onOpenLibrary, +}: TemplateRecommendationsProps) { + if (loading && templates.length === 0) { + return ( +
+
+ ); + } + + if (templates.length === 0) { + return ( +
+
+ ); + } + + return ( +
+ {templates.slice(0, RECOMMENDATION_LIMIT).map((template) => ( + + ))} +
+ ); +} diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-01.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-01.webp deleted file mode 100644 index 25821e804..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-01.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-02.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-02.webp deleted file mode 100644 index ce26591db..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-02.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-03.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-03.webp deleted file mode 100644 index 90287a674..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-03.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-04.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-04.webp deleted file mode 100644 index 8fa04357a..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-04.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-05.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-05.webp deleted file mode 100644 index cc657f1ef..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-05.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-06.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-06.webp deleted file mode 100644 index bf922e8d3..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-06.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-07.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-07.webp deleted file mode 100644 index 67048cfb9..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-07.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-08.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-08.webp deleted file mode 100644 index 13f642612..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-08.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-09.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-09.webp deleted file mode 100644 index d98a01ec7..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-09.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-10.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-10.webp deleted file mode 100644 index 4ed427e84..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-10.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-11.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-11.webp deleted file mode 100644 index b147b8ff7..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-11.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-12.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-12.webp deleted file mode 100644 index 084ed36bb..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-12.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-13.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-13.webp deleted file mode 100644 index 7da22fa4f..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-13.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-14.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-14.webp deleted file mode 100644 index 88dcc70cb..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-14.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-15.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-15.webp deleted file mode 100644 index 13315c560..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-15.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-16.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-16.webp deleted file mode 100644 index 4af52bbda..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-16.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-17.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-17.webp deleted file mode 100644 index 87c1ebe09..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-17.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-18.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-18.webp deleted file mode 100644 index cc4bcb6c5..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-18.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-19.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-19.webp deleted file mode 100644 index 413fff72b..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-19.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-20.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-20.webp deleted file mode 100644 index b55594bba..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-20.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-21.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-21.webp deleted file mode 100644 index 31db46017..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-21.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-22.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-22.webp deleted file mode 100644 index 5d2e1fa4e..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-22.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-23.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-23.webp deleted file mode 100644 index f34cd2398..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-23.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-24.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-24.webp deleted file mode 100644 index b23f5e8d1..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-24.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-25.webp b/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-25.webp deleted file mode 100644 index e008db1fc..000000000 Binary files a/apps/ai-game-creator-shell/src/view/home/assets/inspiration/inspiration-25.webp and /dev/null differ diff --git a/apps/ai-game-creator-shell/src/view/home/index.tsx b/apps/ai-game-creator-shell/src/view/home/index.tsx index 16236d779..ed160d88f 100644 --- a/apps/ai-game-creator-shell/src/view/home/index.tsx +++ b/apps/ai-game-creator-shell/src/view/home/index.tsx @@ -14,13 +14,14 @@ import { useRef, useState } from 'react'; import BRAND_ICON from '../../../../../packages/shared/src/icons/taonier-product-ip.png'; import type { ProjectStartMode } from '../../app/types'; import { ConversationModelSelect } from '../../features/project-workspace/ConversationModelSelect'; +import type { GameTemplateEntry } from '../../features/template-library/templateLibraryModel'; import RichInputArea, { UploadButton } from './components/RichInputArea'; import { richTextToAttachments, richTextToPrompt, } from './components/RichInputArea/richTextToPrompt'; import { resolveHomeStartMode } from './homeStartMode'; -import InspirationGallery from './InspirationGallery'; +import TemplateRecommendations from './TemplateRecommendations'; import { type HomeCreationType, type HomeDraft, @@ -113,6 +114,11 @@ type HomeViewProps = { onProjectsOpen: () => void; onProjectOpen: (path: string) => void; onProjectPick: () => void; + /** 模板库推荐位:清单来自 Rust 侧模板库,首页只负责展示与跳转。 */ + templateRecommendations: readonly GameTemplateEntry[]; + templateLibraryLoading: boolean; + templateLibraryError: string; + onTemplateLibraryOpen: () => void; }; export default function HomeView({ @@ -126,6 +132,10 @@ export default function HomeView({ onProjectsOpen, onProjectOpen, onProjectPick, + templateRecommendations, + templateLibraryLoading, + templateLibraryError, + onTemplateLibraryOpen, }: HomeViewProps) { const homeCreationType = useLauncherHomeDraftStore( (state) => state.creationType, @@ -421,12 +431,12 @@ export default function HomeView({

- 灵感推荐 + 模板库

+
- +
); diff --git a/apps/ai-game-creator-shell/src/view/layout.tsx b/apps/ai-game-creator-shell/src/view/layout.tsx index 9974817f5..4464661ce 100644 --- a/apps/ai-game-creator-shell/src/view/layout.tsx +++ b/apps/ai-game-creator-shell/src/view/layout.tsx @@ -3,6 +3,7 @@ import { CircleHelp, FolderKanban, Home, + LayoutTemplate, Plus, Settings, User, @@ -30,6 +31,7 @@ export type LauncherView = | 'guide' | 'contact' | 'news' + | 'template-library' | 'project-development'; type SidebarUserInfo = { @@ -284,6 +286,19 @@ export function Sidebar({ >