Compare commits
116 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 38ad2ce256 | |||
| 65f8e44a88 | |||
| ade1b7803e | |||
| 71000b6df1 | |||
| c047543825 | |||
| 34b3af1d2a | |||
| f7cba30b6b | |||
| 273f12633c | |||
| 5f5aa17152 | |||
| 3a57d9fbdf | |||
| 382b925ab9 | |||
| c1482012c6 | |||
| c3a17a6efc | |||
| 1bfdc3a760 | |||
| 1e27cd229d | |||
| 774710452f | |||
| aaecb82622 | |||
| 64ad24ac77 | |||
| 75ec3361dc | |||
| bc1dc868a1 | |||
| 50204ff7aa | |||
| 70fa160819 | |||
| 2e78cbf152 | |||
| 840baf208f | |||
| d8af0fa882 | |||
| faed0ec251 | |||
| 6e63a118e0 | |||
| 4ae5ab14fa | |||
| b73a329b2c | |||
| 06004bfeea | |||
| ecea7b4ad3 | |||
| b1e82d64cb | |||
| b7622f4a24 | |||
| cb840c6e8c | |||
| 0a9cdf6395 | |||
| e382d23892 | |||
| 37ae7508b8 | |||
| 1ae6c6cd06 | |||
| 459f8a60e5 | |||
| 63c495dab0 | |||
| b37d91882c | |||
| dd339638cc | |||
| 0caf998227 | |||
| 6eed6bd13f | |||
| b543a060b7 | |||
| 9993b2feb5 | |||
| d348cf9064 | |||
| e640219243 | |||
| da2ad83c3b | |||
| ad19c9475e | |||
| 975a2e577c | |||
| 1b40f030e7 | |||
| 098693636a | |||
| e17af3008e | |||
| 64bd006981 | |||
| 6a4cb2bc18 | |||
| 1b3a3b003f | |||
| ff8e517c8e | |||
| d874a13a92 | |||
| 5eba53a5cc | |||
| 33ddb5de27 | |||
| bf8f96c115 | |||
| e469831543 | |||
| 869abad879 | |||
| 280a2dc5d1 | |||
| 3c6e084a41 | |||
| ed3369a494 | |||
| fdc48fe725 | |||
| 2748468d12 | |||
| 09ad0073fe | |||
| 42b702d362 | |||
| edfd1f9143 | |||
| 423f2d7184 | |||
| 656c89e4b2 | |||
| aa9076c95c | |||
| 0ec1179bf1 | |||
| 2938a49cac | |||
| ae0f9376c9 | |||
| 29d0cbb4df | |||
| 41366dd71d | |||
| 721e45f01b | |||
| f4b496caca | |||
| fc0fd846f9 | |||
| fa99d9ad62 | |||
| 64a52005f8 | |||
| 645d806fed | |||
| 0b9d16e8f1 | |||
| d5c4e0e780 | |||
| 30e27abc60 | |||
| b607501916 | |||
| 46e3cd9744 | |||
| 5fb3db662b | |||
| 87b798322e | |||
| ec286b3480 | |||
| 35733f0e33 | |||
| 3c7b02b9f8 | |||
| f2030a616f | |||
| b3b5d77990 | |||
| 1da106af7d | |||
| cd2edd6966 | |||
| 22e830ff93 | |||
| c266ae7b50 | |||
| a543b75cf7 | |||
| f213987f9a | |||
| 2c623bb577 | |||
| 3353906e6f | |||
| 17716347e2 | |||
| 9ad66a67a3 | |||
| ba3aa3ccdb | |||
| 2b38eaafba | |||
| 7d5b9071e7 | |||
| 9e83f1d88c | |||
| 7e35d7c344 | |||
| 5ec40c8b83 | |||
| 948a80fc49 | |||
| dfd6fadedf |
@@ -23,6 +23,3 @@
|
|||||||
*.meta text
|
*.meta text
|
||||||
*.anim text
|
*.anim text
|
||||||
*.controller text
|
*.controller text
|
||||||
|
|
||||||
# Rust ts-rs 生成的共享契约:保留在仓库中供 TS 消费,但不作为手写源文件统计。
|
|
||||||
packages/shared/src/contracts/generated/** linguist-generated=true
|
|
||||||
|
|||||||
@@ -221,7 +221,8 @@ jobs:
|
|||||||
- name: Run AI game creator shell agent-run smoke
|
- name: Run AI game creator shell agent-run smoke
|
||||||
run: npm run check:native-shells:agc-rust-smoke
|
run: npm run check:native-shells:agc-rust-smoke
|
||||||
|
|
||||||
# AGC 壳依赖的共享 / 平台和编辑器插件 crate 各自预热独立 manifest,再运行对应测试。
|
# AGC 壳依赖的共享 / 平台 crate 测试用的是 server-rs workspace 与两个无锁独立 crate
|
||||||
|
# 的 manifest,属另一套依赖图,因此单独一个 job 预热、单独跑。
|
||||||
ai-game-creator-shell-rust-crates:
|
ai-game-creator-shell-rust-crates:
|
||||||
name: AI game creator shell Rust crates
|
name: AI game creator shell Rust crates
|
||||||
runs-on: genarrative-ci
|
runs-on: genarrative-ci
|
||||||
@@ -262,15 +263,13 @@ jobs:
|
|||||||
# `cargo test --manifest-path` 单独跑这两个 crate。不在这里预热的话,这两条测试
|
# `cargo test --manifest-path` 单独跑这两个 crate。不在这里预热的话,这两条测试
|
||||||
# 会在测试阶段自己 `Updating crates.io index`,crates.io 一抖动整条 job 就红
|
# 会在测试阶段自己 `Updating crates.io index`,crates.io 一抖动整条 job 就红
|
||||||
# (见 #327 / PR #316 run 1950)。
|
# (见 #327 / PR #316 run 1950)。
|
||||||
# Cocos 插件也使用独立且未提交的锁文件,一并预热。
|
# 两个 crate 都没有提交 Cargo.lock,所以这里只能做不带锁标志的 fetch:
|
||||||
# 这些 crate 都没有提交 Cargo.lock,所以这里只能做不带锁标志的 fetch:
|
|
||||||
# 加锁标志会因为缺少锁文件直接失败。生成的 Cargo.lock 落在两个 crate 目录内,
|
# 加锁标志会因为缺少锁文件直接失败。生成的 Cargo.lock 落在两个 crate 目录内,
|
||||||
# 已被各自的 .gitignore 忽略,只留在容器里;随后的测试阶段因此能用锁定版本
|
# 已被各自的 .gitignore 忽略,只留在容器里;随后的测试阶段因此能用锁定版本
|
||||||
# 解析,不再触碰 registry index。
|
# 解析,不再触碰 registry index。
|
||||||
for manifest_path in \
|
for manifest_path in \
|
||||||
server-rs/crates/agent-runtime-core/Cargo.toml \
|
server-rs/crates/agent-runtime-core/Cargo.toml \
|
||||||
server-rs/crates/agent-runtime-orchestration/Cargo.toml \
|
server-rs/crates/agent-runtime-orchestration/Cargo.toml; do
|
||||||
plugins/agc-cocos-editor/native/cocos-editor-bridge/Cargo.toml; do
|
|
||||||
for attempt in $(seq 1 5); do
|
for attempt in $(seq 1 5); do
|
||||||
if cargo fetch \
|
if cargo fetch \
|
||||||
--target x86_64-unknown-linux-gnu \
|
--target x86_64-unknown-linux-gnu \
|
||||||
@@ -285,40 +284,6 @@ jobs:
|
|||||||
done
|
done
|
||||||
done
|
done
|
||||||
|
|
||||||
- name: Prepare Unity plugin Rust dependencies
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
for attempt in $(seq 1 5); do
|
|
||||||
if cargo fetch --locked \
|
|
||||||
--target x86_64-unknown-linux-gnu \
|
|
||||||
--manifest-path plugins/agc-unity-editor/native/unity-editor-bridge/Cargo.toml; then
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
if [[ "${attempt}" -eq 5 ]]; then
|
|
||||||
echo 'Unity plugin Cargo dependency fetch failed after 5 attempts.' >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
sleep $((attempt * 2))
|
|
||||||
done
|
|
||||||
|
|
||||||
- name: Prepare Godot plugin Rust dependencies
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
for attempt in $(seq 1 5); do
|
|
||||||
if cargo fetch --locked \
|
|
||||||
--target x86_64-unknown-linux-gnu \
|
|
||||||
--manifest-path plugins/agc-godot-editor/native/godot-editor-bridge/Cargo.toml; then
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
if [[ "${attempt}" -eq 5 ]]; then
|
|
||||||
echo 'Godot plugin Cargo dependency fetch failed after 5 attempts.' >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
sleep $((attempt * 2))
|
|
||||||
done
|
|
||||||
|
|
||||||
- name: Run AI game creator shell shared crate gates
|
- name: Run AI game creator shell shared crate gates
|
||||||
run: npm run check:native-shells:agc-rust-crates
|
run: npm run check:native-shells:agc-rust-crates
|
||||||
|
|
||||||
|
|||||||
@@ -48,10 +48,6 @@ temp*build*/
|
|||||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/manifest.json
|
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/manifest.json
|
||||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/NOTICE.md
|
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/NOTICE.md
|
||||||
/plugins/agc-cocos-editor/native/payload/
|
/plugins/agc-cocos-editor/native/payload/
|
||||||
/plugins/agc-unity-editor/dotnet/**/bin/
|
|
||||||
/plugins/agc-unity-editor/dotnet/**/obj/
|
|
||||||
/plugins/agc-unity-editor/dotnet/publish/
|
|
||||||
/plugins/agc-unity-editor/dotnet/native-build/
|
|
||||||
/apps/ai-game-creator-shell/logs/
|
/apps/ai-game-creator-shell/logs/
|
||||||
/apps/ai-game-creator-shell/.llm-drafts/
|
/apps/ai-game-creator-shell/.llm-drafts/
|
||||||
/apps/ai-game-creator-shell/game-creator.config.local.json
|
/apps/ai-game-creator-shell/game-creator.config.local.json
|
||||||
|
|||||||
+1
-10
@@ -1,14 +1,5 @@
|
|||||||
{
|
{
|
||||||
"singleQuote": true,
|
"singleQuote": true,
|
||||||
"semi": true,
|
"semi": true,
|
||||||
"trailingComma": "all",
|
"trailingComma": "all"
|
||||||
"overrides": [
|
|
||||||
{
|
|
||||||
"files": "packages/shared/src/contracts/generated/**/*.ts",
|
|
||||||
"options": {
|
|
||||||
"printWidth": 1000,
|
|
||||||
"singleQuote": false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -174,6 +174,14 @@ _Avoid_: mock 先行堆积、前后端各自发散、先做排行榜 UI
|
|||||||
|
|
||||||
## 项目开发对话(DirectProject)
|
## 项目开发对话(DirectProject)
|
||||||
|
|
||||||
|
**DirectProject 专属聊天模块**:
|
||||||
|
AGC 普通项目聊天的独立容器,拥有 DirectProject 的聊天状态、运行态订阅、历史读取、发送队列、附件和中止交互,并把聊天投影交给专属表现层渲染;它不承接 Supervisor、Design Agent 或 Planning V2 的运行态。
|
||||||
|
_Avoid_: 把 DirectProject 作为项目总控聊天的一个布尔分支、把四种 Agent 会话抽象成同一事实源
|
||||||
|
|
||||||
|
**项目工作台布局**:
|
||||||
|
承载本地项目的资源工作区、项目级工具和独立聊天产品路径的外层界面;布局拥有跨面板的账户/钱包入口,聊天模块只负责项目对话,不嵌套账户展示。
|
||||||
|
_Avoid_: 把钱包入口塞进聊天设置、让聊天组件拥有工作台级账户状态
|
||||||
|
|
||||||
**项目对话历史**:
|
**项目对话历史**:
|
||||||
AGC 本地项目内 Codex 原始对话条目的持久集合,是聊天展示、工具卡片和线程恢复注入的唯一持久事实源。
|
AGC 本地项目内 Codex 原始对话条目的持久集合,是聊天展示、工具卡片和线程恢复注入的唯一持久事实源。
|
||||||
_Avoid_: 会话缓存、展示态历史、按 UI 需要另存的对话副本
|
_Avoid_: 会话缓存、展示态历史、按 UI 需要另存的对话副本
|
||||||
|
|||||||
@@ -32,8 +32,6 @@ import type {
|
|||||||
AdminLoginResponse,
|
AdminLoginResponse,
|
||||||
AdminMeResponse,
|
AdminMeResponse,
|
||||||
AdminOverviewResponse,
|
AdminOverviewResponse,
|
||||||
AdminProjectSnapshotListQuery,
|
|
||||||
AdminProjectSnapshotListResponse,
|
|
||||||
AdminRechargeOrderListQuery,
|
AdminRechargeOrderListQuery,
|
||||||
AdminRechargeOrderListResponse,
|
AdminRechargeOrderListResponse,
|
||||||
AdminRechargeRefundActionResponse,
|
AdminRechargeRefundActionResponse,
|
||||||
@@ -200,92 +198,6 @@ export function listAdminAccounts(token: string) {
|
|||||||
return request<AdminAccountListResponse>('/admin/api/accounts', { token });
|
return request<AdminAccountListResponse>('/admin/api/accounts', { token });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function listAdminProjectSnapshots(
|
|
||||||
token: string,
|
|
||||||
query: AdminProjectSnapshotListQuery = {},
|
|
||||||
signal?: AbortSignal,
|
|
||||||
) {
|
|
||||||
const params = new URLSearchParams();
|
|
||||||
if (query.cursor) params.set('cursor', query.cursor);
|
|
||||||
params.set('limit', String(query.limit ?? 20));
|
|
||||||
return request<AdminProjectSnapshotListResponse>(
|
|
||||||
`/admin/api/project-snapshots?${params.toString()}`,
|
|
||||||
{ token, signal },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function downloadAdminProjectSnapshot(
|
|
||||||
token: string,
|
|
||||||
userId: string,
|
|
||||||
projectId: string,
|
|
||||||
signal?: AbortSignal,
|
|
||||||
) {
|
|
||||||
const path = `/admin/api/project-snapshots/${encodeURIComponent(userId)}/${encodeURIComponent(projectId)}/download`;
|
|
||||||
const response = await fetch(buildRequestUrl(path), {
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${token.trim()}`,
|
|
||||||
Accept: 'application/zip',
|
|
||||||
[API_RESPONSE_ENVELOPE_HEADER]: 'v1',
|
|
||||||
},
|
|
||||||
signal,
|
|
||||||
});
|
|
||||||
if (!response.ok) {
|
|
||||||
const responseText = await response.text();
|
|
||||||
throw buildAdminApiError(
|
|
||||||
response,
|
|
||||||
parseJsonResponse(responseText),
|
|
||||||
responseText,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const contentType = response.headers
|
|
||||||
.get('content-type')
|
|
||||||
?.split(';')[0]
|
|
||||||
?.trim()
|
|
||||||
.toLowerCase();
|
|
||||||
if (contentType !== 'application/zip') {
|
|
||||||
await response.body?.cancel();
|
|
||||||
throw new AdminApiError({
|
|
||||||
message: '下载失败:服务端未返回 ZIP 工程文件',
|
|
||||||
status: response.status,
|
|
||||||
code: 'INVALID_PROJECT_ARCHIVE_RESPONSE',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
blob: await response.blob(),
|
|
||||||
filename: projectArchiveFilename(
|
|
||||||
response.headers.get('content-disposition'),
|
|
||||||
),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function projectArchiveFilename(contentDisposition: string | null): string {
|
|
||||||
const extended = contentDisposition?.match(
|
|
||||||
/(?:^|;)\s*filename\*=UTF-8'[^']*'([^;]+)/i,
|
|
||||||
);
|
|
||||||
const ordinary = contentDisposition?.match(
|
|
||||||
/(?:^|;)\s*filename=(?:"((?:[^"\\]|\\.)*)"|([^;]+))/i,
|
|
||||||
);
|
|
||||||
let filename =
|
|
||||||
ordinary?.[1]?.replace(/\\(.)/g, '$1') ?? ordinary?.[2]?.trim() ?? '';
|
|
||||||
if (extended?.[1]) {
|
|
||||||
try {
|
|
||||||
filename = decodeURIComponent(extended[1].trim());
|
|
||||||
} catch {
|
|
||||||
// 非法扩展编码继续使用普通文件名。
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const safeName = Array.from(filename, (character) => {
|
|
||||||
const code = character.charCodeAt(0);
|
|
||||||
return code < 32 || code === 127 ? '_' : character;
|
|
||||||
})
|
|
||||||
.join('')
|
|
||||||
.replace(/[<>:"/\\|?*]/g, '_')
|
|
||||||
.trim()
|
|
||||||
.replace(/[. ]+$/, '');
|
|
||||||
if (!safeName || safeName.length > 240) return 'project.zip';
|
|
||||||
return /\.zip$/i.test(safeName) ? safeName : `${safeName}.zip`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createAdminAccount(
|
export function createAdminAccount(
|
||||||
token: string,
|
token: string,
|
||||||
payload: AdminCreateAccountRequest,
|
payload: AdminCreateAccountRequest,
|
||||||
|
|||||||
@@ -96,27 +96,6 @@ export interface AdminMeResponse {
|
|||||||
admin: AdminSessionPayload;
|
admin: AdminSessionPayload;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AdminProjectSnapshotEntry {
|
|
||||||
userId: string;
|
|
||||||
projectId: string;
|
|
||||||
projectName: string | null;
|
|
||||||
syncRevision: number;
|
|
||||||
syncedAtMs: number;
|
|
||||||
fileCount: number;
|
|
||||||
totalBytes: number;
|
|
||||||
status: 'ready' | 'partial' | 'unverified';
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AdminProjectSnapshotListQuery {
|
|
||||||
cursor?: string | null;
|
|
||||||
limit?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AdminProjectSnapshotListResponse {
|
|
||||||
items: AdminProjectSnapshotEntry[];
|
|
||||||
nextCursor: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AdminErrorReportEntry {
|
export interface AdminErrorReportEntry {
|
||||||
batchId: string;
|
batchId: string;
|
||||||
eventCount: number;
|
eventCount: number;
|
||||||
|
|||||||
@@ -1,128 +0,0 @@
|
|||||||
import { afterEach, expect, test, vi } from 'vitest';
|
|
||||||
|
|
||||||
import {
|
|
||||||
downloadAdminProjectSnapshot,
|
|
||||||
listAdminProjectSnapshots,
|
|
||||||
} from './adminApiClient';
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
vi.unstubAllGlobals();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('项目列表携带分页与后台授权,解析标准响应', async () => {
|
|
||||||
const payload = { items: [], nextCursor: 'next' };
|
|
||||||
const fetchMock = vi
|
|
||||||
.fn()
|
|
||||||
.mockResolvedValue(
|
|
||||||
new Response(JSON.stringify({ ok: true, data: payload })),
|
|
||||||
);
|
|
||||||
vi.stubGlobal('fetch', fetchMock);
|
|
||||||
const controller = new AbortController();
|
|
||||||
expect(
|
|
||||||
await listAdminProjectSnapshots(
|
|
||||||
'admin-token',
|
|
||||||
{ cursor: 'user/a+项目', limit: 20 },
|
|
||||||
controller.signal,
|
|
||||||
),
|
|
||||||
).toEqual(payload);
|
|
||||||
expect(fetchMock).toHaveBeenCalledWith(
|
|
||||||
'/admin/api/project-snapshots?cursor=user%2Fa%2B%E9%A1%B9%E7%9B%AE&limit=20',
|
|
||||||
expect.objectContaining({
|
|
||||||
headers: expect.objectContaining({ Authorization: 'Bearer admin-token' }),
|
|
||||||
signal: controller.signal,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('ZIP 下载以授权请求读取并优先保留中文附件名', async () => {
|
|
||||||
const fetchMock = vi.fn().mockResolvedValue(
|
|
||||||
new Response('PK\u0003\u0004', {
|
|
||||||
headers: {
|
|
||||||
'content-type': 'application/zip',
|
|
||||||
'content-disposition':
|
|
||||||
"attachment; filename=project.zip; filename*=UTF-8''%E4%B8%89%E6%B6%88-r2.zip",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
vi.stubGlobal('fetch', fetchMock);
|
|
||||||
const controller = new AbortController();
|
|
||||||
const archive = await downloadAdminProjectSnapshot(
|
|
||||||
'admin-token',
|
|
||||||
'user/a',
|
|
||||||
'project/b',
|
|
||||||
controller.signal,
|
|
||||||
);
|
|
||||||
expect(archive.filename).toBe('三消-r2.zip');
|
|
||||||
expect(archive.blob.type).toBe('application/zip');
|
|
||||||
expect(fetchMock).toHaveBeenCalledWith(
|
|
||||||
'/admin/api/project-snapshots/user%2Fa/project%2Fb/download',
|
|
||||||
expect.objectContaining({
|
|
||||||
headers: expect.objectContaining({
|
|
||||||
Authorization: 'Bearer admin-token',
|
|
||||||
Accept: 'application/zip',
|
|
||||||
}),
|
|
||||||
signal: controller.signal,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test.each([
|
|
||||||
['attachment; filename="工程.zip"; filename*=UTF-8\'\'%broken', '工程.zip'],
|
|
||||||
['attachment; filename="../secret.zip"', '.._secret.zip'],
|
|
||||||
["attachment; filename*=UTF-8''unsafe%00%1F%7F.zip", 'unsafe___.zip'],
|
|
||||||
[null, 'project.zip'],
|
|
||||||
])('ZIP 附件名兼容安全回退 %s', async (header, expected) => {
|
|
||||||
const headers: Record<string, string> = { 'content-type': 'application/zip' };
|
|
||||||
// Response 的 Headers 只接受 Latin-1;真实 UTF-8 文件名使用 filename*。
|
|
||||||
if (header)
|
|
||||||
headers['content-disposition'] = header.replace('工程', 'project');
|
|
||||||
vi.stubGlobal(
|
|
||||||
'fetch',
|
|
||||||
vi.fn().mockResolvedValue(new Response('PK', { headers })),
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
(await downloadAdminProjectSnapshot('token', 'user', 'project')).filename,
|
|
||||||
).toBe(expected.replace('工程', 'project'));
|
|
||||||
});
|
|
||||||
|
|
||||||
test.each([401, 403, 409, 500])(
|
|
||||||
'下载 HTTP %s 保留后台错误,不返回 ZIP',
|
|
||||||
async (status) => {
|
|
||||||
vi.stubGlobal(
|
|
||||||
'fetch',
|
|
||||||
vi.fn().mockResolvedValue(
|
|
||||||
new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
ok: false,
|
|
||||||
error: { code: 'SNAPSHOT_FAILURE', message: '工程尚未同步完成' },
|
|
||||||
}),
|
|
||||||
{
|
|
||||||
status,
|
|
||||||
headers: { 'content-type': 'application/json' },
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await expect(
|
|
||||||
downloadAdminProjectSnapshot('token', 'user', 'project'),
|
|
||||||
).rejects.toMatchObject({
|
|
||||||
status,
|
|
||||||
code: 'SNAPSHOT_FAILURE',
|
|
||||||
message: '工程尚未同步完成',
|
|
||||||
});
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
test('200 JSON 或 HTML 不能被保存为成功 ZIP', async () => {
|
|
||||||
vi.stubGlobal(
|
|
||||||
'fetch',
|
|
||||||
vi.fn().mockResolvedValue(
|
|
||||||
new Response('{"ok":false}', {
|
|
||||||
headers: { 'content-type': 'application/json' },
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await expect(
|
|
||||||
downloadAdminProjectSnapshot('token', 'user', 'project'),
|
|
||||||
).rejects.toMatchObject({ code: 'INVALID_PROJECT_ARCHIVE_RESPONSE' });
|
|
||||||
});
|
|
||||||
@@ -31,7 +31,6 @@ import { AdminInviteCodePage } from '../pages/AdminInviteCodePage';
|
|||||||
import { AdminLoginPage } from '../pages/AdminLoginPage';
|
import { AdminLoginPage } from '../pages/AdminLoginPage';
|
||||||
import { AdminOverviewPage } from '../pages/AdminOverviewPage';
|
import { AdminOverviewPage } from '../pages/AdminOverviewPage';
|
||||||
import { AdminProfileWalletConfigPage } from '../pages/AdminProfileWalletConfigPage';
|
import { AdminProfileWalletConfigPage } from '../pages/AdminProfileWalletConfigPage';
|
||||||
import { AdminProjectSnapshotsPage } from '../pages/AdminProjectSnapshotsPage';
|
|
||||||
import { AdminRechargeOrderPage } from '../pages/AdminRechargeOrderPage';
|
import { AdminRechargeOrderPage } from '../pages/AdminRechargeOrderPage';
|
||||||
import { AdminRechargeProductPage } from '../pages/AdminRechargeProductPage';
|
import { AdminRechargeProductPage } from '../pages/AdminRechargeProductPage';
|
||||||
import { AdminRedeemCodePage } from '../pages/AdminRedeemCodePage';
|
import { AdminRedeemCodePage } from '../pages/AdminRedeemCodePage';
|
||||||
@@ -309,12 +308,6 @@ export function AdminApp() {
|
|||||||
{activeRouteId === 'accounts' ? (
|
{activeRouteId === 'accounts' ? (
|
||||||
<AdminAccountsPage token={token} onUnauthorized={handleUnauthorized} />
|
<AdminAccountsPage token={token} onUnauthorized={handleUnauthorized} />
|
||||||
) : null}
|
) : null}
|
||||||
{activeRouteId === 'project-snapshots' ? (
|
|
||||||
<AdminProjectSnapshotsPage
|
|
||||||
token={token}
|
|
||||||
onUnauthorized={handleUnauthorized}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
</AdminShell>
|
</AdminShell>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import {
|
|||||||
Bug,
|
Bug,
|
||||||
Coins,
|
Coins,
|
||||||
Database,
|
Database,
|
||||||
FolderArchive,
|
|
||||||
GitBranch,
|
GitBranch,
|
||||||
Images,
|
Images,
|
||||||
LayoutDashboard,
|
LayoutDashboard,
|
||||||
@@ -50,7 +49,6 @@ const routeIcons = {
|
|||||||
'editor-generation-pricing': Coins,
|
'editor-generation-pricing': Coins,
|
||||||
'editor-showcase': Star,
|
'editor-showcase': Star,
|
||||||
'editor-assets': Images,
|
'editor-assets': Images,
|
||||||
'project-snapshots': FolderArchive,
|
|
||||||
accounts: Users,
|
accounts: Users,
|
||||||
'agc-models': ListChecks,
|
'agc-models': ListChecks,
|
||||||
} satisfies Record<AdminRouteId, typeof LayoutDashboard>;
|
} satisfies Record<AdminRouteId, typeof LayoutDashboard>;
|
||||||
|
|||||||
@@ -122,28 +122,3 @@ test('零权限 member 不回落到 Dashboard', () => {
|
|||||||
expect(routes).toEqual([]);
|
expect(routes).toEqual([]);
|
||||||
expect(resolveAccessibleAdminRoute('#dashboard', routes)).toBeNull();
|
expect(resolveAccessibleAdminRoute('#dashboard', routes)).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('项目工程入口对 owner 与已授权 member 开放且可分配权限', () => {
|
|
||||||
const route = {
|
|
||||||
id: 'project-snapshots',
|
|
||||||
label: '项目工程',
|
|
||||||
hash: '#project-snapshots',
|
|
||||||
};
|
|
||||||
expect(adminRoutes.filter((item) => !item.ownerOnly)).toContainEqual(route);
|
|
||||||
expect(resolveAdminRoute('#project-snapshots')).toBe('project-snapshots');
|
|
||||||
expect(
|
|
||||||
getAccessibleAdminRoutes({ accountRole: 'owner', tabPermissions: [] }),
|
|
||||||
).toContainEqual(route);
|
|
||||||
expect(
|
|
||||||
getAccessibleAdminRoutes({
|
|
||||||
accountRole: 'member',
|
|
||||||
tabPermissions: ['project-snapshots'],
|
|
||||||
}),
|
|
||||||
).toEqual([route]);
|
|
||||||
expect(
|
|
||||||
getAccessibleAdminRoutes({
|
|
||||||
accountRole: 'member',
|
|
||||||
tabPermissions: ['tracking'],
|
|
||||||
}),
|
|
||||||
).not.toContainEqual(route);
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ export type AdminRouteId =
|
|||||||
| 'editor-generation-pricing'
|
| 'editor-generation-pricing'
|
||||||
| 'editor-showcase'
|
| 'editor-showcase'
|
||||||
| 'editor-assets'
|
| 'editor-assets'
|
||||||
| 'project-snapshots'
|
|
||||||
| 'agc-models'
|
| 'agc-models'
|
||||||
| 'accounts';
|
| 'accounts';
|
||||||
|
|
||||||
@@ -55,7 +54,6 @@ export const adminRoutes: AdminRouteDefinition[] = [
|
|||||||
{ id: 'agc-models', label: 'AGC 模型', hash: '#agc-models', ownerOnly: true },
|
{ id: 'agc-models', label: 'AGC 模型', hash: '#agc-models', ownerOnly: true },
|
||||||
{ id: 'editor-showcase', label: '精选审核', hash: '#editor-showcase' },
|
{ id: 'editor-showcase', label: '精选审核', hash: '#editor-showcase' },
|
||||||
{ id: 'editor-assets', label: '素材查询', hash: '#editor-assets' },
|
{ id: 'editor-assets', label: '素材查询', hash: '#editor-assets' },
|
||||||
{ id: 'project-snapshots', label: '项目工程', hash: '#project-snapshots' },
|
|
||||||
{ id: 'accounts', label: '账号管理', hash: '#accounts', ownerOnly: true },
|
{ id: 'accounts', label: '账号管理', hash: '#accounts', ownerOnly: true },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -1,288 +0,0 @@
|
|||||||
// @vitest-environment jsdom
|
|
||||||
import {
|
|
||||||
act,
|
|
||||||
cleanup,
|
|
||||||
fireEvent,
|
|
||||||
render,
|
|
||||||
screen,
|
|
||||||
waitFor,
|
|
||||||
within,
|
|
||||||
} from '@testing-library/react';
|
|
||||||
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
|
|
||||||
|
|
||||||
import {
|
|
||||||
AdminApiError,
|
|
||||||
downloadAdminProjectSnapshot,
|
|
||||||
listAdminProjectSnapshots,
|
|
||||||
} from '../api/adminApiClient';
|
|
||||||
import type { AdminProjectSnapshotEntry } from '../api/adminApiTypes';
|
|
||||||
import { AdminProjectSnapshotsPage } from './AdminProjectSnapshotsPage';
|
|
||||||
|
|
||||||
vi.mock('../api/adminApiClient', async () => ({
|
|
||||||
...(await vi.importActual<typeof import('../api/adminApiClient')>(
|
|
||||||
'../api/adminApiClient',
|
|
||||||
)),
|
|
||||||
downloadAdminProjectSnapshot: vi.fn(),
|
|
||||||
listAdminProjectSnapshots: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
const entry: AdminProjectSnapshotEntry = {
|
|
||||||
userId: 'user-1',
|
|
||||||
projectId: 'project-1',
|
|
||||||
projectName: '三消工程',
|
|
||||||
syncRevision: 3,
|
|
||||||
syncedAtMs: 1_700_000_000_000,
|
|
||||||
fileCount: 12,
|
|
||||||
totalBytes: 2048,
|
|
||||||
status: 'ready',
|
|
||||||
};
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.mocked(listAdminProjectSnapshots)
|
|
||||||
.mockReset()
|
|
||||||
.mockResolvedValue({ items: [entry], nextCursor: null });
|
|
||||||
vi.mocked(downloadAdminProjectSnapshot).mockReset();
|
|
||||||
});
|
|
||||||
afterEach(() => {
|
|
||||||
cleanup();
|
|
||||||
vi.restoreAllMocks();
|
|
||||||
vi.unstubAllGlobals();
|
|
||||||
vi.useRealTimers();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('按项目展示完整性并限制未完成工程下载', async () => {
|
|
||||||
vi.mocked(listAdminProjectSnapshots).mockResolvedValue({
|
|
||||||
items: [
|
|
||||||
entry,
|
|
||||||
{
|
|
||||||
...entry,
|
|
||||||
projectId: 'partial-project',
|
|
||||||
projectName: '未完成工程',
|
|
||||||
status: 'partial',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
...entry,
|
|
||||||
projectId: 'legacy-project',
|
|
||||||
projectName: null,
|
|
||||||
status: 'unverified',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
nextCursor: null,
|
|
||||||
});
|
|
||||||
render(<AdminProjectSnapshotsPage token="token" onUnauthorized={vi.fn()} />);
|
|
||||||
const completeRow = (await screen.findByText('三消工程')).closest('tr')!;
|
|
||||||
expect(within(completeRow).getByText('2 KiB')).toBeTruthy();
|
|
||||||
expect(
|
|
||||||
within(completeRow)
|
|
||||||
.getByRole('button', { name: '下载完整工程' })
|
|
||||||
.hasAttribute('disabled'),
|
|
||||||
).toBe(false);
|
|
||||||
expect(
|
|
||||||
screen.getByRole('button', { name: '同步未完成' }).hasAttribute('disabled'),
|
|
||||||
).toBe(true);
|
|
||||||
expect(screen.getByText('完整性未知')).toBeTruthy();
|
|
||||||
expect(
|
|
||||||
screen
|
|
||||||
.getByRole('button', { name: '下载已存文件' })
|
|
||||||
.hasAttribute('disabled'),
|
|
||||||
).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('加载更多合并项目,刷新失败保留列表和错误,重试从首页开始', async () => {
|
|
||||||
vi.mocked(listAdminProjectSnapshots)
|
|
||||||
.mockResolvedValueOnce({ items: [entry], nextCursor: 'page-2' })
|
|
||||||
.mockResolvedValueOnce({
|
|
||||||
items: [{ ...entry, projectId: 'project-2', projectName: '第二工程' }],
|
|
||||||
nextCursor: null,
|
|
||||||
})
|
|
||||||
.mockRejectedValueOnce(new Error('远端清单读取失败'))
|
|
||||||
.mockResolvedValueOnce({ items: [], nextCursor: null });
|
|
||||||
render(<AdminProjectSnapshotsPage token="token" onUnauthorized={vi.fn()} />);
|
|
||||||
fireEvent.click(await screen.findByRole('button', { name: '加载更多' }));
|
|
||||||
await screen.findByText('第二工程');
|
|
||||||
expect(listAdminProjectSnapshots).toHaveBeenNthCalledWith(
|
|
||||||
2,
|
|
||||||
'token',
|
|
||||||
{ cursor: 'page-2', limit: 20 },
|
|
||||||
expect.any(AbortSignal),
|
|
||||||
);
|
|
||||||
expect(screen.getByText('三消工程')).toBeTruthy();
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '刷新' }));
|
|
||||||
await screen.findByRole('alert');
|
|
||||||
expect(screen.getByText('第二工程')).toBeTruthy();
|
|
||||||
expect(screen.queryByText('暂无已上传项目')).toBeNull();
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '刷新' }));
|
|
||||||
await screen.findByText('暂无已上传项目');
|
|
||||||
expect(listAdminProjectSnapshots).toHaveBeenLastCalledWith(
|
|
||||||
'token',
|
|
||||||
{ cursor: null, limit: 20 },
|
|
||||||
expect.any(AbortSignal),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('下载使用返回的中文文件名,随后释放对象 URL', async () => {
|
|
||||||
const createObjectURL = vi.fn(() => 'blob:archive');
|
|
||||||
const revokeObjectURL = vi.fn();
|
|
||||||
vi.stubGlobal(
|
|
||||||
'URL',
|
|
||||||
class extends URL {
|
|
||||||
static createObjectURL = createObjectURL;
|
|
||||||
static revokeObjectURL = revokeObjectURL;
|
|
||||||
},
|
|
||||||
);
|
|
||||||
let savedFilename = '';
|
|
||||||
let savedHref = '';
|
|
||||||
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (
|
|
||||||
this: HTMLAnchorElement,
|
|
||||||
) {
|
|
||||||
savedFilename = this.download;
|
|
||||||
savedHref = this.href;
|
|
||||||
});
|
|
||||||
const blob = new Blob(['PK'], { type: 'application/zip' });
|
|
||||||
vi.mocked(downloadAdminProjectSnapshot).mockResolvedValue({
|
|
||||||
blob,
|
|
||||||
filename: '三消工程-r3.zip',
|
|
||||||
});
|
|
||||||
render(<AdminProjectSnapshotsPage token="token" onUnauthorized={vi.fn()} />);
|
|
||||||
const button = await screen.findByRole('button', { name: '下载完整工程' });
|
|
||||||
vi.useFakeTimers();
|
|
||||||
await act(async () => {
|
|
||||||
fireEvent.click(button);
|
|
||||||
});
|
|
||||||
expect(savedFilename).toBe('三消工程-r3.zip');
|
|
||||||
expect(savedHref).toBe('blob:archive');
|
|
||||||
expect(createObjectURL).toHaveBeenCalledWith(blob);
|
|
||||||
expect(downloadAdminProjectSnapshot).toHaveBeenCalledWith(
|
|
||||||
'token',
|
|
||||||
'user-1',
|
|
||||||
'project-1',
|
|
||||||
expect.any(AbortSignal),
|
|
||||||
);
|
|
||||||
act(() => vi.advanceTimersByTime(1000));
|
|
||||||
expect(revokeObjectURL).toHaveBeenCalledWith('blob:archive');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('取消下载中止请求且不显示错误,卸载中止列表请求', async () => {
|
|
||||||
vi.mocked(downloadAdminProjectSnapshot).mockImplementation(
|
|
||||||
(_token, _user, _project, signal) =>
|
|
||||||
new Promise((_resolve, reject) => {
|
|
||||||
signal?.addEventListener('abort', () =>
|
|
||||||
reject(new DOMException('Aborted', 'AbortError')),
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const view = render(
|
|
||||||
<AdminProjectSnapshotsPage token="token" onUnauthorized={vi.fn()} />,
|
|
||||||
);
|
|
||||||
fireEvent.click(await screen.findByRole('button', { name: '下载完整工程' }));
|
|
||||||
fireEvent.click(await screen.findByRole('button', { name: '取消下载' }));
|
|
||||||
expect(
|
|
||||||
vi.mocked(downloadAdminProjectSnapshot).mock.calls[0]?.[3]?.aborted,
|
|
||||||
).toBe(true);
|
|
||||||
await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
|
|
||||||
vi.mocked(listAdminProjectSnapshots).mockReturnValue(new Promise(() => {}));
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '刷新' }));
|
|
||||||
const signal = vi.mocked(listAdminProjectSnapshots).mock.calls.at(-1)?.[2];
|
|
||||||
view.unmount();
|
|
||||||
expect(signal?.aborted).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('下载登录失效走现有会话处理,403 错误保留页面', async () => {
|
|
||||||
const onUnauthorized = vi.fn();
|
|
||||||
vi.mocked(downloadAdminProjectSnapshot)
|
|
||||||
.mockRejectedValueOnce(
|
|
||||||
new AdminApiError({ status: 403, message: '无项目工程权限' }),
|
|
||||||
)
|
|
||||||
.mockRejectedValueOnce(
|
|
||||||
new AdminApiError({ status: 401, message: '已过期' }),
|
|
||||||
);
|
|
||||||
render(
|
|
||||||
<AdminProjectSnapshotsPage token="token" onUnauthorized={onUnauthorized} />,
|
|
||||||
);
|
|
||||||
fireEvent.click(await screen.findByRole('button', { name: '下载完整工程' }));
|
|
||||||
expect(await screen.findByText('无项目工程权限')).toBeTruthy();
|
|
||||||
expect(onUnauthorized).not.toHaveBeenCalled();
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '下载完整工程' }));
|
|
||||||
await waitFor(() =>
|
|
||||||
expect(onUnauthorized).toHaveBeenCalledWith('登录状态已失效'),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('首次列表失败显示错误而非空项目,401 失效回到会话处理', async () => {
|
|
||||||
const onUnauthorized = vi.fn();
|
|
||||||
vi.mocked(listAdminProjectSnapshots)
|
|
||||||
.mockRejectedValueOnce(new Error('清单存储不可用'))
|
|
||||||
.mockRejectedValueOnce(
|
|
||||||
new AdminApiError({ status: 401, message: '已过期' }),
|
|
||||||
);
|
|
||||||
render(
|
|
||||||
<AdminProjectSnapshotsPage token="token" onUnauthorized={onUnauthorized} />,
|
|
||||||
);
|
|
||||||
await screen.findByText('清单存储不可用');
|
|
||||||
expect(screen.queryByText('暂无已上传项目')).toBeNull();
|
|
||||||
fireEvent.click(screen.getByRole('button', { name: '刷新' }));
|
|
||||||
await waitFor(() =>
|
|
||||||
expect(onUnauthorized).toHaveBeenCalledWith('登录状态已失效'),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('更换登录令牌丢弃旧列表和晚返回请求', async () => {
|
|
||||||
let finishOldRequest!: (value: {
|
|
||||||
items: AdminProjectSnapshotEntry[];
|
|
||||||
nextCursor: null;
|
|
||||||
}) => void;
|
|
||||||
vi.mocked(listAdminProjectSnapshots)
|
|
||||||
.mockReturnValueOnce(
|
|
||||||
new Promise((resolve) => {
|
|
||||||
finishOldRequest = resolve;
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.mockResolvedValueOnce({
|
|
||||||
items: [{ ...entry, projectName: '新账号工程' }],
|
|
||||||
nextCursor: null,
|
|
||||||
});
|
|
||||||
const onUnauthorized = vi.fn();
|
|
||||||
const view = render(
|
|
||||||
<AdminProjectSnapshotsPage
|
|
||||||
token="old-token"
|
|
||||||
onUnauthorized={onUnauthorized}
|
|
||||||
/>,
|
|
||||||
);
|
|
||||||
const oldSignal = vi.mocked(listAdminProjectSnapshots).mock.calls[0]?.[2];
|
|
||||||
view.rerender(
|
|
||||||
<AdminProjectSnapshotsPage
|
|
||||||
token="new-token"
|
|
||||||
onUnauthorized={onUnauthorized}
|
|
||||||
/>,
|
|
||||||
);
|
|
||||||
await screen.findByText('新账号工程');
|
|
||||||
expect(oldSignal?.aborted).toBe(true);
|
|
||||||
await act(async () => {
|
|
||||||
finishOldRequest({ items: [entry], nextCursor: null });
|
|
||||||
});
|
|
||||||
expect(screen.queryByText('三消工程')).toBeNull();
|
|
||||||
expect(screen.getByText('新账号工程')).toBeTruthy();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('卸载后完成的下载不会创建浏览器文件', async () => {
|
|
||||||
let finishDownload!: (value: { blob: Blob; filename: string }) => void;
|
|
||||||
vi.mocked(downloadAdminProjectSnapshot).mockReturnValue(
|
|
||||||
new Promise((resolve) => {
|
|
||||||
finishDownload = resolve;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const click = vi
|
|
||||||
.spyOn(HTMLAnchorElement.prototype, 'click')
|
|
||||||
.mockImplementation(() => {});
|
|
||||||
const view = render(
|
|
||||||
<AdminProjectSnapshotsPage token="token" onUnauthorized={vi.fn()} />,
|
|
||||||
);
|
|
||||||
fireEvent.click(await screen.findByRole('button', { name: '下载完整工程' }));
|
|
||||||
const signal = vi.mocked(downloadAdminProjectSnapshot).mock.calls[0]?.[3];
|
|
||||||
view.unmount();
|
|
||||||
expect(signal?.aborted).toBe(true);
|
|
||||||
await act(async () => {
|
|
||||||
finishDownload({ blob: new Blob(['PK']), filename: 'old.zip' });
|
|
||||||
});
|
|
||||||
expect(click).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
@@ -1,270 +0,0 @@
|
|||||||
import { Download, RefreshCcw, X } from 'lucide-react';
|
|
||||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
||||||
|
|
||||||
import {
|
|
||||||
downloadAdminProjectSnapshot,
|
|
||||||
listAdminProjectSnapshots,
|
|
||||||
} from '../api/adminApiClient';
|
|
||||||
import type { AdminProjectSnapshotEntry } from '../api/adminApiTypes';
|
|
||||||
import { handlePageError } from './pageUtils';
|
|
||||||
|
|
||||||
interface AdminProjectSnapshotsPageProps {
|
|
||||||
token: string;
|
|
||||||
onUnauthorized: (message?: string) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
const snapshotStatuses = {
|
|
||||||
ready: {
|
|
||||||
label: '已同步',
|
|
||||||
className: 'admin-status-ok',
|
|
||||||
action: '下载完整工程',
|
|
||||||
},
|
|
||||||
partial: {
|
|
||||||
label: '同步未完成',
|
|
||||||
className: 'admin-status-pending',
|
|
||||||
action: '同步未完成',
|
|
||||||
},
|
|
||||||
unverified: {
|
|
||||||
label: '完整性未知',
|
|
||||||
className: 'admin-status-pending',
|
|
||||||
action: '下载已存文件',
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export function AdminProjectSnapshotsPage({
|
|
||||||
token,
|
|
||||||
onUnauthorized,
|
|
||||||
}: AdminProjectSnapshotsPageProps) {
|
|
||||||
const [items, setItems] = useState<AdminProjectSnapshotEntry[]>([]);
|
|
||||||
const [nextCursor, setNextCursor] = useState<string | null>(null);
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [hasLoaded, setHasLoaded] = useState(false);
|
|
||||||
const [errorMessage, setErrorMessage] = useState('');
|
|
||||||
const [downloadingKey, setDownloadingKey] = useState<string | null>(null);
|
|
||||||
const listController = useRef<AbortController | null>(null);
|
|
||||||
const downloadController = useRef<AbortController | null>(null);
|
|
||||||
|
|
||||||
const loadPage = useCallback(
|
|
||||||
async (cursor: string | null = null) => {
|
|
||||||
listController.current?.abort();
|
|
||||||
const controller = new AbortController();
|
|
||||||
listController.current = controller;
|
|
||||||
setIsLoading(true);
|
|
||||||
setErrorMessage('');
|
|
||||||
try {
|
|
||||||
const response = await listAdminProjectSnapshots(
|
|
||||||
token,
|
|
||||||
{ cursor, limit: 20 },
|
|
||||||
controller.signal,
|
|
||||||
);
|
|
||||||
if (controller.signal.aborted) return;
|
|
||||||
setItems((current) => {
|
|
||||||
if (!cursor) return response.items;
|
|
||||||
const entries = new Map(
|
|
||||||
current.map((entry) => [snapshotKey(entry), entry]),
|
|
||||||
);
|
|
||||||
response.items.forEach((entry) =>
|
|
||||||
entries.set(snapshotKey(entry), entry),
|
|
||||||
);
|
|
||||||
return [...entries.values()];
|
|
||||||
});
|
|
||||||
setNextCursor(response.nextCursor);
|
|
||||||
setHasLoaded(true);
|
|
||||||
} catch (error: unknown) {
|
|
||||||
if (!controller.signal.aborted)
|
|
||||||
handlePageError(error, onUnauthorized, setErrorMessage);
|
|
||||||
} finally {
|
|
||||||
if (listController.current === controller) {
|
|
||||||
listController.current = null;
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[token, onUnauthorized],
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setItems([]);
|
|
||||||
setNextCursor(null);
|
|
||||||
setHasLoaded(false);
|
|
||||||
setDownloadingKey(null);
|
|
||||||
void loadPage();
|
|
||||||
return () => {
|
|
||||||
listController.current?.abort();
|
|
||||||
listController.current = null;
|
|
||||||
downloadController.current?.abort();
|
|
||||||
downloadController.current = null;
|
|
||||||
};
|
|
||||||
}, [loadPage]);
|
|
||||||
|
|
||||||
async function downloadProject(entry: AdminProjectSnapshotEntry) {
|
|
||||||
if (downloadController.current || entry.status === 'partial') return;
|
|
||||||
const controller = new AbortController();
|
|
||||||
downloadController.current = controller;
|
|
||||||
setDownloadingKey(snapshotKey(entry));
|
|
||||||
setErrorMessage('');
|
|
||||||
try {
|
|
||||||
const archive = await downloadAdminProjectSnapshot(
|
|
||||||
token,
|
|
||||||
entry.userId,
|
|
||||||
entry.projectId,
|
|
||||||
controller.signal,
|
|
||||||
);
|
|
||||||
if (controller.signal.aborted) return;
|
|
||||||
const objectUrl = URL.createObjectURL(archive.blob);
|
|
||||||
const link = document.createElement('a');
|
|
||||||
link.href = objectUrl;
|
|
||||||
link.download = archive.filename;
|
|
||||||
document.body.append(link);
|
|
||||||
try {
|
|
||||||
link.click();
|
|
||||||
} finally {
|
|
||||||
link.remove();
|
|
||||||
// 给浏览器时间接管下载,随后释放临时 URL。
|
|
||||||
setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
|
|
||||||
}
|
|
||||||
} catch (error: unknown) {
|
|
||||||
if (!controller.signal.aborted)
|
|
||||||
handlePageError(error, onUnauthorized, setErrorMessage);
|
|
||||||
} finally {
|
|
||||||
if (downloadController.current === controller) {
|
|
||||||
downloadController.current = null;
|
|
||||||
setDownloadingKey(null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function cancelDownload() {
|
|
||||||
downloadController.current?.abort();
|
|
||||||
downloadController.current = null;
|
|
||||||
setDownloadingKey(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<section className="admin-page admin-page-wide">
|
|
||||||
<div className="admin-page-heading">
|
|
||||||
<h2>项目工程</h2>
|
|
||||||
<button
|
|
||||||
className="admin-secondary-button"
|
|
||||||
disabled={isLoading}
|
|
||||||
type="button"
|
|
||||||
onClick={() => void loadPage()}
|
|
||||||
>
|
|
||||||
<RefreshCcw size={17} aria-hidden="true" />
|
|
||||||
<span>{isLoading ? '加载中' : '刷新'}</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{errorMessage ? (
|
|
||||||
<div className="admin-alert" role="alert">
|
|
||||||
{errorMessage}
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
<section
|
|
||||||
className="admin-panel admin-stack"
|
|
||||||
aria-label="项目工程列表"
|
|
||||||
aria-busy={isLoading}
|
|
||||||
>
|
|
||||||
<div className="admin-table-wrap">
|
|
||||||
<table className="admin-table admin-project-snapshot-table">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>项目</th>
|
|
||||||
<th>用户 ID</th>
|
|
||||||
<th>同步时间</th>
|
|
||||||
<th>文件数</th>
|
|
||||||
<th>体积</th>
|
|
||||||
<th>完整性</th>
|
|
||||||
<th>操作</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{items.map((entry) => {
|
|
||||||
const status = snapshotStatuses[entry.status];
|
|
||||||
const isDownloading = downloadingKey === snapshotKey(entry);
|
|
||||||
return (
|
|
||||||
<tr key={snapshotKey(entry)}>
|
|
||||||
<td data-label="项目">
|
|
||||||
<strong>{entry.projectName || entry.projectId}</strong>
|
|
||||||
<small>{entry.projectId}</small>
|
|
||||||
</td>
|
|
||||||
<td data-label="用户 ID">{entry.userId}</td>
|
|
||||||
<td data-label="同步时间">
|
|
||||||
<span>
|
|
||||||
{new Date(entry.syncedAtMs).toLocaleString('zh-CN', {
|
|
||||||
hour12: false,
|
|
||||||
})}
|
|
||||||
<small>版本 {entry.syncRevision}</small>
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td data-label="文件数">
|
|
||||||
{entry.fileCount.toLocaleString('zh-CN')}
|
|
||||||
</td>
|
|
||||||
<td data-label="体积">{formatBytes(entry.totalBytes)}</td>
|
|
||||||
<td data-label="完整性">
|
|
||||||
<span className={`admin-status ${status.className}`}>
|
|
||||||
{status.label}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td data-label="操作">
|
|
||||||
{isDownloading ? (
|
|
||||||
<button
|
|
||||||
className="admin-secondary-button"
|
|
||||||
type="button"
|
|
||||||
onClick={cancelDownload}
|
|
||||||
>
|
|
||||||
<X size={16} aria-hidden="true" />
|
|
||||||
<span>取消下载</span>
|
|
||||||
</button>
|
|
||||||
) : (
|
|
||||||
<button
|
|
||||||
className="admin-secondary-button"
|
|
||||||
disabled={
|
|
||||||
entry.status === 'partial' ||
|
|
||||||
downloadingKey !== null
|
|
||||||
}
|
|
||||||
type="button"
|
|
||||||
onClick={() => void downloadProject(entry)}
|
|
||||||
>
|
|
||||||
<Download size={16} aria-hidden="true" />
|
|
||||||
<span>{status.action}</span>
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
{hasLoaded && items.length === 0 && !errorMessage ? (
|
|
||||||
<p className="admin-muted-text">暂无已上传项目</p>
|
|
||||||
) : null}
|
|
||||||
{nextCursor ? (
|
|
||||||
<div className="admin-action-row">
|
|
||||||
<button
|
|
||||||
className="admin-secondary-button"
|
|
||||||
disabled={isLoading}
|
|
||||||
type="button"
|
|
||||||
onClick={() => void loadPage(nextCursor)}
|
|
||||||
>
|
|
||||||
{isLoading ? '加载中' : '加载更多'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</section>
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function snapshotKey(entry: AdminProjectSnapshotEntry) {
|
|
||||||
return `${entry.userId}/${entry.projectId}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatBytes(bytes: number) {
|
|
||||||
const units = ['B', 'KiB', 'MiB', 'GiB'];
|
|
||||||
const unit = Math.min(
|
|
||||||
Math.floor(Math.log2(Math.max(1, bytes)) / 10),
|
|
||||||
units.length - 1,
|
|
||||||
);
|
|
||||||
return `${(bytes / 1024 ** unit).toLocaleString('zh-CN', { maximumFractionDigits: 1 })} ${units[unit]}`;
|
|
||||||
}
|
|
||||||
@@ -1452,112 +1452,6 @@ button:disabled {
|
|||||||
min-width: 1180px;
|
min-width: 1180px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.admin-project-snapshot-table {
|
|
||||||
min-width: 0;
|
|
||||||
table-layout: fixed;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table th,
|
|
||||||
.admin-project-snapshot-table td {
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table th:first-child {
|
|
||||||
width: 20%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table th:nth-child(2) {
|
|
||||||
width: 14%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table th:nth-child(3) {
|
|
||||||
width: 18%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table th:nth-child(4) {
|
|
||||||
width: 7%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table th:nth-child(5) {
|
|
||||||
width: 9%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table th:nth-child(6) {
|
|
||||||
width: 12%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table th:last-child {
|
|
||||||
width: 20%;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 1200px) {
|
|
||||||
.admin-project-snapshot-table,
|
|
||||||
.admin-project-snapshot-table tbody {
|
|
||||||
display: block;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table thead {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table tr {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
|
||||||
gap: 10px 16px;
|
|
||||||
border-bottom: 1px solid #eaded2;
|
|
||||||
padding: 18px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table tr:first-child {
|
|
||||||
padding-top: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table tr:last-child {
|
|
||||||
border-bottom: 0;
|
|
||||||
padding-bottom: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table td {
|
|
||||||
display: flex;
|
|
||||||
min-width: 0;
|
|
||||||
align-items: baseline;
|
|
||||||
gap: 8px;
|
|
||||||
border: 0;
|
|
||||||
padding: 0;
|
|
||||||
font-size: 14px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table td::before {
|
|
||||||
flex-shrink: 0;
|
|
||||||
color: #8f7868;
|
|
||||||
font-size: 12px;
|
|
||||||
content: attr(data-label);
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table td:first-child,
|
|
||||||
.admin-project-snapshot-table td:nth-child(2),
|
|
||||||
.admin-project-snapshot-table td:nth-child(3),
|
|
||||||
.admin-project-snapshot-table td:nth-child(6),
|
|
||||||
.admin-project-snapshot-table td:last-child {
|
|
||||||
grid-column: 1 / -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table td:first-child {
|
|
||||||
display: block;
|
|
||||||
font-size: 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table td:first-child::before,
|
|
||||||
.admin-project-snapshot-table td:last-child::before {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-project-snapshot-table td:last-child button {
|
|
||||||
width: 100%;
|
|
||||||
justify-content: center;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.admin-recharge-table {
|
.admin-recharge-table {
|
||||||
min-width: 1080px;
|
min-width: 1080px;
|
||||||
table-layout: fixed;
|
table-layout: fixed;
|
||||||
|
|||||||
@@ -676,11 +676,11 @@ async function runSelfTest() {
|
|||||||
designFoundationAssetCall?.arguments?.input?.outputPath ===
|
designFoundationAssetCall?.arguments?.input?.outputPath ===
|
||||||
'assets/ui-prototype.png' &&
|
'assets/ui-prototype.png' &&
|
||||||
designFoundationAssetCall.arguments.input.aspectRatio === '16:9' &&
|
designFoundationAssetCall.arguments.input.aspectRatio === '16:9' &&
|
||||||
designFoundationAssetCall.arguments.input.assetKind === 'ui-design' &&
|
designFoundationAssetCall.arguments.input.assetKind === 'ui-prototype' &&
|
||||||
artAssetPlanAssetCall?.arguments?.input?.outputPath ===
|
artAssetPlanAssetCall?.arguments?.input?.outputPath ===
|
||||||
'assets/art-spritesheet.png' &&
|
'assets/art-spritesheet.png' &&
|
||||||
artAssetPlanAssetCall.arguments.input.aspectRatio === '1:1' &&
|
artAssetPlanAssetCall.arguments.input.aspectRatio === '1:1' &&
|
||||||
artAssetPlanAssetCall.arguments.input.assetKind === 'icon-spritesheet',
|
artAssetPlanAssetCall.arguments.input.assetKind === 'art-spritesheet',
|
||||||
'self-test-visual-assets-invalid',
|
'self-test-visual-assets-invalid',
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ const requiredFormalArtifactSpecs = [
|
|||||||
{ path: 'game/balance.json', kind: 'json' },
|
{ path: 'game/balance.json', kind: 'json' },
|
||||||
{ path: 'assets/manifest.art.json', kind: 'json' },
|
{ path: 'assets/manifest.art.json', kind: 'json' },
|
||||||
{ path: 'assets/manifest.audio.json', kind: 'json' },
|
{ path: 'assets/manifest.audio.json', kind: 'json' },
|
||||||
{ path: 'game/index.html', kind: 'file' },
|
{ path: 'game/index.html', kind: 'game-entry' },
|
||||||
{ path: 'exports/README.md', kind: 'file' },
|
{ path: 'exports/README.md', kind: 'file' },
|
||||||
];
|
];
|
||||||
const editorImageArtifactSpecs = [
|
const editorImageArtifactSpecs = [
|
||||||
|
|||||||
@@ -105,8 +105,6 @@ export const agcReleasePathPatterns = [
|
|||||||
'packages/',
|
'packages/',
|
||||||
'server-rs/crates/',
|
'server-rs/crates/',
|
||||||
'plugins/agc-cocos-editor/',
|
'plugins/agc-cocos-editor/',
|
||||||
'plugins/agc-unity-editor/',
|
|
||||||
'plugins/agc-godot-editor/',
|
|
||||||
'apps/desktop-shell/src-tauri/icons/',
|
'apps/desktop-shell/src-tauri/icons/',
|
||||||
'package.json',
|
'package.json',
|
||||||
'package-lock.json',
|
'package-lock.json',
|
||||||
@@ -502,41 +500,6 @@ export function selectReleaseArtifact(files, target = defaultTarget()) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function selectFirstInstallArtifact(
|
|
||||||
files,
|
|
||||||
{ target, version, artifact },
|
|
||||||
) {
|
|
||||||
validateReleaseTarget(target);
|
|
||||||
let selected;
|
|
||||||
if (target.includes('windows')) {
|
|
||||||
selected = artifact;
|
|
||||||
if (!selected?.endsWith('.exe')) {
|
|
||||||
throw new Error('Windows 首装包必须复用本次 NSIS .exe 更新包');
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Tauri DMG 文件名使用 aarch64 / x64,而 updater 的 Intel 平台键是 x86_64。
|
|
||||||
const architecture = target.startsWith('aarch64') ? 'aarch64' : 'x64';
|
|
||||||
const suffix = `_${version}_${architecture}.dmg`;
|
|
||||||
const candidates = files.filter((file) =>
|
|
||||||
path.basename(file).endsWith(suffix),
|
|
||||||
);
|
|
||||||
if (candidates.length !== 1) {
|
|
||||||
throw new Error(
|
|
||||||
`首装 DMG 必须唯一匹配本次版本 ${version} 和架构 ${architecture},找到 ${candidates.length} 个`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
selected = candidates[0];
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
!fs.existsSync(selected) ||
|
|
||||||
!fs.statSync(selected).isFile() ||
|
|
||||||
fs.statSync(selected).size === 0
|
|
||||||
) {
|
|
||||||
throw new Error(`首装包不存在或为空:${selected}`);
|
|
||||||
}
|
|
||||||
return selected;
|
|
||||||
}
|
|
||||||
|
|
||||||
function readUpdaterSignature(artifactPath) {
|
function readUpdaterSignature(artifactPath) {
|
||||||
const signaturePath = `${artifactPath}.sig`;
|
const signaturePath = `${artifactPath}.sig`;
|
||||||
if (!fs.existsSync(signaturePath)) {
|
if (!fs.existsSync(signaturePath)) {
|
||||||
@@ -557,32 +520,23 @@ export function createUpdateManifest(
|
|||||||
publishedAt = new Date().toISOString(),
|
publishedAt = new Date().toISOString(),
|
||||||
notes = readReleaseNotes(),
|
notes = readReleaseNotes(),
|
||||||
commit = readHeadCommit(),
|
commit = readHeadCommit(),
|
||||||
downloadArtifact,
|
|
||||||
} = {},
|
} = {},
|
||||||
) {
|
) {
|
||||||
validateReleaseTarget(target);
|
validateReleaseTarget(target);
|
||||||
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: channel }, target);
|
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: channel }, target);
|
||||||
const signature = readUpdaterSignature(artifactPath);
|
const signature = readUpdaterSignature(artifactPath);
|
||||||
const version = readPackageJson().version;
|
const version = readPackageJson().version;
|
||||||
const firstInstallArtifact = selectFirstInstallArtifact(
|
|
||||||
downloadArtifact ? [downloadArtifact] : [],
|
|
||||||
{ target, version, artifact: artifactPath },
|
|
||||||
);
|
|
||||||
const fileName = path.basename(artifactPath);
|
const fileName = path.basename(artifactPath);
|
||||||
const url = `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(fileName)}`;
|
const url = `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(fileName)}`;
|
||||||
const downloadUrl = `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(path.basename(firstInstallArtifact))}`;
|
|
||||||
const platforms = {};
|
const platforms = {};
|
||||||
const downloads = {};
|
|
||||||
for (const key of resolveManifestPlatformKeys(target)) {
|
for (const key of resolveManifestPlatformKeys(target)) {
|
||||||
platforms[key] = { signature, url };
|
platforms[key] = { signature, url };
|
||||||
downloads[key] = { url: downloadUrl };
|
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
version,
|
version,
|
||||||
...(notes ? { notes } : {}),
|
...(notes ? { notes } : {}),
|
||||||
pub_date: publishedAt,
|
pub_date: publishedAt,
|
||||||
platforms,
|
platforms,
|
||||||
downloads,
|
|
||||||
// 非标准字段:更新插件会忽略,发布脚本用它定位下一次自动更新摘要的起点。
|
// 非标准字段:更新插件会忽略,发布脚本用它定位下一次自动更新摘要的起点。
|
||||||
...(commit ? { commit } : {}),
|
...(commit ? { commit } : {}),
|
||||||
};
|
};
|
||||||
@@ -721,16 +675,10 @@ export async function generateUpdateManifest(
|
|||||||
context = resolveReleaseContext(),
|
context = resolveReleaseContext(),
|
||||||
) {
|
) {
|
||||||
const { channel, target, bundleRoot } = context;
|
const { channel, target, bundleRoot } = context;
|
||||||
const files = listFiles(bundleRoot);
|
const artifact = selectReleaseArtifact(listFiles(bundleRoot), target);
|
||||||
const artifact = selectReleaseArtifact(files, target);
|
|
||||||
if (!artifact) {
|
if (!artifact) {
|
||||||
throw new Error(`未找到可发布的 AGC 安装包:${bundleRoot}`);
|
throw new Error(`未找到可发布的 AGC 安装包:${bundleRoot}`);
|
||||||
}
|
}
|
||||||
const downloadArtifact = selectFirstInstallArtifact(files, {
|
|
||||||
target,
|
|
||||||
version: readPackageJson().version,
|
|
||||||
artifact,
|
|
||||||
});
|
|
||||||
const manualNotes = readReleaseNotes();
|
const manualNotes = readReleaseNotes();
|
||||||
const previousCommit = await resolvePreviousReleaseCommit(channel);
|
const previousCommit = await resolvePreviousReleaseCommit(channel);
|
||||||
const commits = collectReleaseCommits(previousCommit);
|
const commits = collectReleaseCommits(previousCommit);
|
||||||
@@ -744,12 +692,7 @@ export async function generateUpdateManifest(
|
|||||||
`[ai-game-creator-shell] 未生成自动更新摘要(上一发布 commit=${previousCommit ?? '未知'},客户端相关提交=${commits ? commits.length : '不可判定'},最近提交=${recentCommits ? recentCommits.length : '不可判定'})`,
|
`[ai-game-creator-shell] 未生成自动更新摘要(上一发布 commit=${previousCommit ?? '未知'},客户端相关提交=${commits ? commits.length : '不可判定'},最近提交=${recentCommits ? recentCommits.length : '不可判定'})`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const manifest = createUpdateManifest(artifact, {
|
const manifest = createUpdateManifest(artifact, { channel, target, notes });
|
||||||
channel,
|
|
||||||
target,
|
|
||||||
notes,
|
|
||||||
downloadArtifact,
|
|
||||||
});
|
|
||||||
const manifestPath = path.join(bundleRoot, 'latest.json');
|
const manifestPath = path.join(bundleRoot, 'latest.json');
|
||||||
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
|
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
|
||||||
const notesPath = path.join(bundleRoot, 'release-notes.txt');
|
const notesPath = path.join(bundleRoot, 'release-notes.txt');
|
||||||
@@ -774,7 +717,6 @@ export async function generateUpdateManifest(
|
|||||||
`[ai-game-creator-shell] 渠道 ${channel}:已生成 ${manifestPath}`,
|
`[ai-game-creator-shell] 渠道 ${channel}:已生成 ${manifestPath}`,
|
||||||
);
|
);
|
||||||
console.log(`[ai-game-creator-shell] 安装包:${artifact}`);
|
console.log(`[ai-game-creator-shell] 安装包:${artifact}`);
|
||||||
console.log(`[ai-game-creator-shell] 首装包:${downloadArtifact}`);
|
|
||||||
console.log(
|
console.log(
|
||||||
manualNotes
|
manualNotes
|
||||||
? '[ai-game-creator-shell] 更新摘要:使用 AGC_UPDATE_RELEASE_NOTES 手动文案'
|
? '[ai-game-creator-shell] 更新摘要:使用 AGC_UPDATE_RELEASE_NOTES 手动文案'
|
||||||
@@ -791,7 +733,6 @@ export async function generateUpdateManifest(
|
|||||||
return {
|
return {
|
||||||
channel,
|
channel,
|
||||||
artifact,
|
artifact,
|
||||||
downloadArtifact,
|
|
||||||
manifest,
|
manifest,
|
||||||
manifestPath,
|
manifestPath,
|
||||||
notes,
|
notes,
|
||||||
|
|||||||
@@ -32,23 +32,12 @@ import {
|
|||||||
resolveReleaseContext,
|
resolveReleaseContext,
|
||||||
resolveRemoteHighWaterVersion,
|
resolveRemoteHighWaterVersion,
|
||||||
runTauriBuild,
|
runTauriBuild,
|
||||||
selectFirstInstallArtifact,
|
|
||||||
selectReleaseArtifact,
|
selectReleaseArtifact,
|
||||||
updateManifestUrl,
|
updateManifestUrl,
|
||||||
} from './build-release.mjs';
|
} from './build-release.mjs';
|
||||||
|
|
||||||
const windowsTarget = 'x86_64-pc-windows-msvc';
|
const windowsTarget = 'x86_64-pc-windows-msvc';
|
||||||
const universalTarget = 'universal-apple-darwin';
|
const universalTarget = 'universal-apple-darwin';
|
||||||
const packageVersion = JSON.parse(
|
|
||||||
readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
|
|
||||||
).version;
|
|
||||||
|
|
||||||
function createDmgFixture(root, target, version = packageVersion) {
|
|
||||||
const architecture = target.startsWith('aarch64') ? 'aarch64' : 'x64';
|
|
||||||
const dmg = path.join(root, `陶泥儿_${version}_${architecture}.dmg`);
|
|
||||||
writeFileSync(dmg, 'first installation disk image');
|
|
||||||
return dmg;
|
|
||||||
}
|
|
||||||
|
|
||||||
test('native sidecar builds reject universal targets and accept each macOS architecture', () => {
|
test('native sidecar builds reject universal targets and accept each macOS architecture', () => {
|
||||||
assert.throws(() => buildTauriBuildArguments([], universalTarget), /单架构/);
|
assert.throws(() => buildTauriBuildArguments([], universalTarget), /单架构/);
|
||||||
@@ -265,13 +254,7 @@ test('explicit macOS target drives version lookup, Tauri endpoint, artifact and
|
|||||||
),
|
),
|
||||||
artifact,
|
artifact,
|
||||||
);
|
);
|
||||||
const manifest = createUpdateManifest(artifact, {
|
const manifest = createUpdateManifest(artifact, context);
|
||||||
...context,
|
|
||||||
downloadArtifact: createDmgFixture(
|
|
||||||
path.dirname(artifact),
|
|
||||||
context.target,
|
|
||||||
),
|
|
||||||
});
|
|
||||||
assert.deepEqual(Object.keys(manifest.platforms), [
|
assert.deepEqual(Object.keys(manifest.platforms), [
|
||||||
'darwin-aarch64',
|
'darwin-aarch64',
|
||||||
]);
|
]);
|
||||||
@@ -289,118 +272,29 @@ test('explicit macOS target drives version lookup, Tauri endpoint, artifact and
|
|||||||
assert.ok(seenContexts.every((context) => context === seenContexts[0]));
|
assert.ok(seenContexts.every((context) => context === seenContexts[0]));
|
||||||
});
|
});
|
||||||
|
|
||||||
for (const target of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) {
|
test('real manifest writer uses the resolved bundle root and does not emit Windows artifacts', async () => {
|
||||||
test(`real manifest writer publishes the ${target} updater and first installer separately`, async () => {
|
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-mac-manifest-'));
|
||||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-mac-manifest-'));
|
|
||||||
try {
|
|
||||||
const artifact = path.join(root, '陶泥儿.app.tar.gz');
|
|
||||||
writeFileSync(artifact, 'mac package');
|
|
||||||
writeFileSync(`${artifact}.sig`, 'mac signature');
|
|
||||||
writeFileSync(path.join(root, 'windows.exe'), 'wrong platform');
|
|
||||||
const downloadArtifact = createDmgFixture(root, target);
|
|
||||||
const context = {
|
|
||||||
...resolveReleaseContext([`--target=${target}`], {}),
|
|
||||||
bundleRoot: root,
|
|
||||||
};
|
|
||||||
const result = await withStubbedFetch(
|
|
||||||
(url) => {
|
|
||||||
assert.match(url, /\/dev-mac\/latest\.json$/);
|
|
||||||
return jsonResponse({}, 404);
|
|
||||||
},
|
|
||||||
() => generateUpdateManifest(context),
|
|
||||||
);
|
|
||||||
assert.equal(result.artifact, artifact);
|
|
||||||
assert.equal(result.downloadArtifact, downloadArtifact);
|
|
||||||
assert.equal(result.manifestPath, path.join(root, 'latest.json'));
|
|
||||||
assert.equal(result.legacyManifestPath, null);
|
|
||||||
const key = target.startsWith('aarch64')
|
|
||||||
? 'darwin-aarch64'
|
|
||||||
: 'darwin-x86_64';
|
|
||||||
assert.deepEqual(Object.keys(result.manifest.platforms), [key]);
|
|
||||||
assert.deepEqual(Object.keys(result.manifest.downloads), [key]);
|
|
||||||
assert.match(
|
|
||||||
result.manifest.platforms[key].url,
|
|
||||||
/\/dev-mac\/.*\.app\.tar\.gz$/,
|
|
||||||
);
|
|
||||||
assert.equal(
|
|
||||||
decodeURIComponent(
|
|
||||||
new URL(result.manifest.downloads[key].url).pathname,
|
|
||||||
),
|
|
||||||
`/agc/dev-mac/${packageVersion}/${path.basename(downloadArtifact)}`,
|
|
||||||
);
|
|
||||||
assert.deepEqual(
|
|
||||||
JSON.parse(readFileSync(result.manifestPath, 'utf8')),
|
|
||||||
result.manifest,
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
rmSync(root, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
test('DMG selection ignores other versions and architectures but rejects missing, empty and ambiguous current packages', () => {
|
|
||||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-dmg-selection-'));
|
|
||||||
try {
|
|
||||||
const target = 'aarch64-apple-darwin';
|
|
||||||
const options = {
|
|
||||||
target,
|
|
||||||
version: '2.3.4',
|
|
||||||
artifact: path.join(root, '陶泥儿.app.tar.gz'),
|
|
||||||
};
|
|
||||||
const oldVersion = createDmgFixture(root, target, '2.3.3');
|
|
||||||
const wrongArchitecture = createDmgFixture(
|
|
||||||
root,
|
|
||||||
'x86_64-apple-darwin',
|
|
||||||
'2.3.4',
|
|
||||||
);
|
|
||||||
assert.throws(() => selectFirstInstallArtifact([], options), /找到 0 个/u);
|
|
||||||
assert.throws(
|
|
||||||
() =>
|
|
||||||
selectFirstInstallArtifact([oldVersion, wrongArchitecture], options),
|
|
||||||
/找到 0 个/u,
|
|
||||||
);
|
|
||||||
const current = createDmgFixture(root, target, '2.3.4');
|
|
||||||
assert.equal(
|
|
||||||
selectFirstInstallArtifact(
|
|
||||||
[oldVersion, wrongArchitecture, current],
|
|
||||||
options,
|
|
||||||
),
|
|
||||||
current,
|
|
||||||
);
|
|
||||||
writeFileSync(current, '');
|
|
||||||
assert.throws(
|
|
||||||
() => selectFirstInstallArtifact([current], options),
|
|
||||||
/不存在或为空/u,
|
|
||||||
);
|
|
||||||
writeFileSync(current, 'valid dmg');
|
|
||||||
const second = path.join(root, '另一包_2.3.4_aarch64.dmg');
|
|
||||||
writeFileSync(second, 'ambiguous dmg');
|
|
||||||
assert.throws(
|
|
||||||
() => selectFirstInstallArtifact([current, second], options),
|
|
||||||
/找到 2 个/u,
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
rmSync(root, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('manifest writer refuses to create latest when the current Mac DMG is missing', async () => {
|
|
||||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-missing-dmg-'));
|
|
||||||
try {
|
try {
|
||||||
const artifact = path.join(root, '陶泥儿.app.tar.gz');
|
const artifact = path.join(root, '陶泥儿.app.tar.gz');
|
||||||
writeFileSync(artifact, 'updater archive');
|
writeFileSync(artifact, 'mac package');
|
||||||
writeFileSync(`${artifact}.sig`, 'signature');
|
writeFileSync(`${artifact}.sig`, 'mac signature');
|
||||||
|
writeFileSync(path.join(root, 'windows.exe'), 'wrong platform');
|
||||||
const context = {
|
const context = {
|
||||||
...resolveReleaseContext(['--target=aarch64-apple-darwin'], {}),
|
...resolveReleaseContext(['--target=x86_64-apple-darwin'], {}),
|
||||||
bundleRoot: root,
|
bundleRoot: root,
|
||||||
};
|
};
|
||||||
await assert.rejects(
|
const result = await withStubbedFetch(
|
||||||
|
(url) => {
|
||||||
|
assert.match(url, /\/dev-mac\/latest\.json$/);
|
||||||
|
return jsonResponse({}, 404);
|
||||||
|
},
|
||||||
() => generateUpdateManifest(context),
|
() => generateUpdateManifest(context),
|
||||||
/首装 DMG 必须唯一匹配/u,
|
|
||||||
);
|
);
|
||||||
assert.throws(() => readFileSync(path.join(root, 'latest.json')), {
|
assert.equal(result.artifact, artifact);
|
||||||
code: 'ENOENT',
|
assert.equal(result.manifestPath, path.join(root, 'latest.json'));
|
||||||
});
|
assert.equal(result.legacyManifestPath, null);
|
||||||
|
assert.deepEqual(Object.keys(result.manifest.platforms), ['darwin-x86_64']);
|
||||||
|
assert.match(result.manifest.platforms['darwin-x86_64'].url, /\/dev-mac\//);
|
||||||
} finally {
|
} finally {
|
||||||
rmSync(root, { recursive: true, force: true });
|
rmSync(root, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
@@ -450,11 +344,7 @@ test('Windows remains the default and explicit Windows overrides macOS environme
|
|||||||
context,
|
context,
|
||||||
{
|
{
|
||||||
spawn: (_binary, command) => {
|
spawn: (_binary, command) => {
|
||||||
assert.ok(
|
assert.ok(command.includes('--features=cocos-editor-execute'));
|
||||||
command.includes(
|
|
||||||
'--features=cocos-editor-execute,unity-editor-execute,godot-editor-execute',
|
|
||||||
),
|
|
||||||
);
|
|
||||||
assert.ok(command.includes('user-config.json'));
|
assert.ok(command.includes('user-config.json'));
|
||||||
const configIndex = command.lastIndexOf('--config');
|
const configIndex = command.lastIndexOf('--config');
|
||||||
const config = JSON.parse(
|
const config = JSON.parse(
|
||||||
@@ -499,9 +389,6 @@ test('channel manifest carries version, platform keys and signature', () => {
|
|||||||
assert.equal(manifest.notes, '修复与改进');
|
assert.equal(manifest.notes, '修复与改进');
|
||||||
assert.equal(manifest.pub_date, '2026-09-17T00:00:00.000Z');
|
assert.equal(manifest.pub_date, '2026-09-17T00:00:00.000Z');
|
||||||
assert.deepEqual(Object.keys(manifest.platforms), ['windows-x86_64']);
|
assert.deepEqual(Object.keys(manifest.platforms), ['windows-x86_64']);
|
||||||
assert.deepEqual(manifest.downloads, {
|
|
||||||
'windows-x86_64': { url: manifest.platforms['windows-x86_64'].url },
|
|
||||||
});
|
|
||||||
assert.equal(
|
assert.equal(
|
||||||
manifest.platforms['windows-x86_64'].signature,
|
manifest.platforms['windows-x86_64'].signature,
|
||||||
'signature-content',
|
'signature-content',
|
||||||
@@ -682,18 +569,18 @@ test('recent commit fallback marks that entries may repeat the previous release'
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('release entry forwards the built artifacts and dry-run mode to the uploader', () => {
|
test('release upload forces overwrite for artifact, signature and channel pointers', () => {
|
||||||
const source = readFileSync(
|
const source = readFileSync(
|
||||||
new URL('./release-upload.mjs', import.meta.url),
|
new URL('./release-upload.mjs', import.meta.url),
|
||||||
'utf8',
|
'utf8',
|
||||||
);
|
);
|
||||||
assert.match(
|
assert.equal(
|
||||||
source,
|
(source.match(/runOssutil\(\[\s*'cp',\s*'--force'/gu) ?? []).length,
|
||||||
/const release = await buildRelease\(process\.argv\.slice\(2\)\)/u,
|
4,
|
||||||
);
|
);
|
||||||
assert.match(source, /uploadReleaseArtifacts\(release, \{/u);
|
assert.match(source, /agc\/\$\{channel\}\/latest\.json/u);
|
||||||
assert.match(source, /const dryRun = readReleaseDryRun\(\);/u);
|
assert.match(source, /agc\/latest\.json/u);
|
||||||
assert.ok(source.includes('\n dryRun,\n'));
|
assert.match(source, /await buildRelease\(process\.argv\.slice\(2\)\)/u);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('release notes list client commits with short sha and bound their size', () => {
|
test('release notes list client commits with short sha and bound their size', () => {
|
||||||
|
|||||||
@@ -19,6 +19,6 @@ export function withDefaultCargoFeatures(argv, features) {
|
|||||||
|
|
||||||
export function defaultEditorFeatures(target) {
|
export function defaultEditorFeatures(target) {
|
||||||
return target === 'win32' || target.includes('windows')
|
return target === 'win32' || target.includes('windows')
|
||||||
? ['cocos-editor-execute', 'unity-editor-execute', 'godot-editor-execute']
|
? ['cocos-editor-execute']
|
||||||
: [];
|
: [];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ test('Windows release includes the same editor feature as development', () => {
|
|||||||
buildTauriBuildArguments([], 'x86_64-pc-windows-msvc', 'win32'),
|
buildTauriBuildArguments([], 'x86_64-pc-windows-msvc', 'win32'),
|
||||||
[
|
[
|
||||||
'build',
|
'build',
|
||||||
'--features=cocos-editor-execute,unity-editor-execute,godot-editor-execute',
|
'--features=cocos-editor-execute',
|
||||||
'--target',
|
'--target',
|
||||||
'x86_64-pc-windows-msvc',
|
'x86_64-pc-windows-msvc',
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -127,7 +127,8 @@ const allowedUncalledTauriCommands = [
|
|||||||
'open_game_creator_launcher_window',
|
'open_game_creator_launcher_window',
|
||||||
'open_game_creator_workspace_window',
|
'open_game_creator_workspace_window',
|
||||||
'read_direct_project_conversation',
|
'read_direct_project_conversation',
|
||||||
// 前端登记工程生命周期,上传由 Rust 调度;以下两个命令仅供本机排障。
|
// 项目定时快照上传只在 Rust 侧触发(周期定时器 / 工作区窗口关闭)与排障调用;
|
||||||
|
// 按产品口径不做客户端可见界面,因此同 `open_game_creator_*_window` 一样按 native-only 登记。
|
||||||
'read_local_project_snapshot_state',
|
'read_local_project_snapshot_state',
|
||||||
'sync_local_project_snapshot',
|
'sync_local_project_snapshot',
|
||||||
'reset_design_agent_session',
|
'reset_design_agent_session',
|
||||||
@@ -142,6 +143,7 @@ const allowedUncalledTauriCommands = [
|
|||||||
'reload_agc_plugin',
|
'reload_agc_plugin',
|
||||||
'call_agc_plugin',
|
'call_agc_plugin',
|
||||||
'read_agc_plugin_panel',
|
'read_agc_plugin_panel',
|
||||||
|
'set_agc_plugin_project_path',
|
||||||
'set_agc_plugin_enabled',
|
'set_agc_plugin_enabled',
|
||||||
];
|
];
|
||||||
const sourceExtensions = new Set([
|
const sourceExtensions = new Set([
|
||||||
|
|||||||
@@ -290,7 +290,7 @@ function deterministicArtManifest(
|
|||||||
{
|
{
|
||||||
id: 'garden-guardians-spritesheet',
|
id: 'garden-guardians-spritesheet',
|
||||||
path: 'assets/art-spritesheet.png',
|
path: 'assets/art-spritesheet.png',
|
||||||
kind: 'icon-spritesheet',
|
kind: 'art-spritesheet',
|
||||||
usage: ['defenders', 'enemies', 'battlefield-ui'],
|
usage: ['defenders', 'enemies', 'battlefield-ui'],
|
||||||
source: 'canvas',
|
source: 'canvas',
|
||||||
status: 'ready',
|
status: 'ready',
|
||||||
@@ -710,7 +710,7 @@ function canvasAssetCall(agentId) {
|
|||||||
outputPath: 'assets/ui-prototype.png',
|
outputPath: 'assets/ui-prototype.png',
|
||||||
aspectRatio: '16:9',
|
aspectRatio: '16:9',
|
||||||
imageSize: '2K',
|
imageSize: '2K',
|
||||||
assetKind: 'ui-design',
|
assetKind: 'ui-prototype',
|
||||||
assetLabel: '游戏横屏界面原型图',
|
assetLabel: '游戏横屏界面原型图',
|
||||||
replaceExisting: false,
|
replaceExisting: false,
|
||||||
});
|
});
|
||||||
@@ -721,7 +721,7 @@ function canvasAssetCall(agentId) {
|
|||||||
outputPath: 'assets/art-spritesheet.png',
|
outputPath: 'assets/art-spritesheet.png',
|
||||||
aspectRatio: '1:1',
|
aspectRatio: '1:1',
|
||||||
imageSize: '1K',
|
imageSize: '1K',
|
||||||
assetKind: 'icon-spritesheet',
|
assetKind: 'art-spritesheet',
|
||||||
assetLabel: '游戏首版核心美术素材',
|
assetLabel: '游戏首版核心美术素材',
|
||||||
replaceExisting: false,
|
replaceExisting: false,
|
||||||
sliceMode: 'connected-components',
|
sliceMode: 'connected-components',
|
||||||
@@ -830,12 +830,12 @@ function missingGeneratedVisualAssetObservation(context, agentId) {
|
|||||||
},
|
},
|
||||||
'design-foundation': {
|
'design-foundation': {
|
||||||
path: 'assets/ui-prototype.png',
|
path: 'assets/ui-prototype.png',
|
||||||
kind: 'ui-design',
|
kind: 'ui-prototype',
|
||||||
summary: '策划界面原型图尚未按正式视觉流程生成并登记,不能完成任务',
|
summary: '策划界面原型图尚未按正式视觉流程生成并登记,不能完成任务',
|
||||||
},
|
},
|
||||||
'art-asset-plan': {
|
'art-asset-plan': {
|
||||||
path: 'assets/art-spritesheet.png',
|
path: 'assets/art-spritesheet.png',
|
||||||
kind: 'icon-spritesheet',
|
kind: 'art-spritesheet',
|
||||||
summary: '首版美术素材图尚未按正式视觉流程生成并登记,不能完成任务',
|
summary: '首版美术素材图尚未按正式视觉流程生成并登记,不能完成任务',
|
||||||
},
|
},
|
||||||
}[agentId];
|
}[agentId];
|
||||||
@@ -2667,7 +2667,7 @@ function createDeterministicCanvasFixture(apiKey) {
|
|||||||
asset: {
|
asset: {
|
||||||
assetId: `asset-${sliceImageId}`,
|
assetId: `asset-${sliceImageId}`,
|
||||||
assetObjectId: sliceAssetObjectId,
|
assetObjectId: sliceAssetObjectId,
|
||||||
assetKind: 'icon',
|
assetKind: 'art-spritesheet-slice',
|
||||||
projectId,
|
projectId,
|
||||||
taskId,
|
taskId,
|
||||||
},
|
},
|
||||||
@@ -2707,7 +2707,7 @@ function createDeterministicCanvasFixture(apiKey) {
|
|||||||
spritesheetAsset: {
|
spritesheetAsset: {
|
||||||
assetId: `asset-${imageId}`,
|
assetId: `asset-${imageId}`,
|
||||||
assetObjectId,
|
assetObjectId,
|
||||||
assetKind: 'icon-spritesheet',
|
assetKind: 'art-spritesheet',
|
||||||
projectId,
|
projectId,
|
||||||
taskId,
|
taskId,
|
||||||
},
|
},
|
||||||
@@ -2749,7 +2749,7 @@ function createDeterministicCanvasFixture(apiKey) {
|
|||||||
const assetObjectId = `asset-object-${imageId}`;
|
const assetObjectId = `asset-object-${imageId}`;
|
||||||
const resourceId = `resource-${imageId}`;
|
const resourceId = `resource-${imageId}`;
|
||||||
const assetKind =
|
const assetKind =
|
||||||
typeof body?.assetKind === 'string' ? body.assetKind : 'image';
|
typeof body?.assetKind === 'string' ? body.assetKind : 'game-art';
|
||||||
images.set(imageId, {
|
images.set(imageId, {
|
||||||
...image,
|
...image,
|
||||||
objectKey,
|
objectKey,
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
import { spawnSync } from 'node:child_process';
|
|
||||||
import path from 'node:path';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 发布上传的 OSS 命令行整理:把 ossutil 参数与凭据整理成可执行或可打印的形式,
|
* 发布上传的 OSS 命令行整理:把 ossutil 参数与凭据整理成可执行或可打印的形式,
|
||||||
* 便于在 dry-run 下核对将要执行的上传,同时保证任何输出都不回显凭据明文。
|
* 便于在 dry-run 下核对将要执行的上传,同时保证任何输出都不回显凭据明文。
|
||||||
@@ -28,89 +25,3 @@ export function formatOssutilCommand({ binary, args, endpoint, credentials }) {
|
|||||||
}
|
}
|
||||||
return parts.map(quoteArgument).join(' ');
|
return parts.map(quoteArgument).join(' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createReleaseUploadPlan(
|
|
||||||
{
|
|
||||||
artifact,
|
|
||||||
downloadArtifact,
|
|
||||||
channel,
|
|
||||||
manifest,
|
|
||||||
manifestPath,
|
|
||||||
legacyManifestPath,
|
|
||||||
},
|
|
||||||
bucket,
|
|
||||||
) {
|
|
||||||
if (!artifact || !downloadArtifact || !manifestPath || !manifest?.version) {
|
|
||||||
throw new Error('发布结果缺少更新包、首装包或清单');
|
|
||||||
}
|
|
||||||
const prefix = `oss://${bucket}/agc/${channel}`;
|
|
||||||
const artifacts = [
|
|
||||||
...new Set(
|
|
||||||
[artifact, `${artifact}.sig`, downloadArtifact].map((file) =>
|
|
||||||
path.resolve(file),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
];
|
|
||||||
const plan = artifacts.map((source) => ({
|
|
||||||
source,
|
|
||||||
destination: `${prefix}/${manifest.version}/${path.basename(source)}`,
|
|
||||||
}));
|
|
||||||
plan.push({ source: manifestPath, destination: `${prefix}/latest.json` });
|
|
||||||
if (legacyManifestPath) {
|
|
||||||
plan.push({
|
|
||||||
source: legacyManifestPath,
|
|
||||||
destination: `oss://${bucket}/agc/latest.json`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return plan;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function uploadReleaseArtifacts(
|
|
||||||
release,
|
|
||||||
{
|
|
||||||
bucket,
|
|
||||||
endpoint,
|
|
||||||
binary = 'ossutil',
|
|
||||||
accessKeyId,
|
|
||||||
accessKeySecret,
|
|
||||||
dryRun = false,
|
|
||||||
spawn = spawnSync,
|
|
||||||
log = console.log,
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
if (Boolean(accessKeyId) !== Boolean(accessKeySecret)) {
|
|
||||||
throw new Error('OSS AccessKey ID 和 Secret 必须同时提供');
|
|
||||||
}
|
|
||||||
const plan = createReleaseUploadPlan(release, bucket);
|
|
||||||
for (const { source, destination } of plan) {
|
|
||||||
// 全部安装对象成功后才执行 latest 指针;失败立即终止,不发布悬空链接。
|
|
||||||
const args = ['cp', '--force', source, destination];
|
|
||||||
if (dryRun) {
|
|
||||||
log(
|
|
||||||
`[dry-run] ${formatOssutilCommand({ binary, args, endpoint, credentials: Boolean(accessKeyId) })}`,
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const credentials = accessKeyId
|
|
||||||
? ['--access-key-id', accessKeyId, '--access-key-secret', accessKeySecret]
|
|
||||||
: [];
|
|
||||||
const result = spawn(
|
|
||||||
binary,
|
|
||||||
[...args, '--endpoint', endpoint, ...credentials],
|
|
||||||
{
|
|
||||||
stdio: 'inherit',
|
|
||||||
shell: false,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (result.error)
|
|
||||||
throw new Error(`无法执行 ${binary},请先安装并配置 ossutil`);
|
|
||||||
if (result.status !== 0) {
|
|
||||||
throw new Error(
|
|
||||||
`OSS 上传失败(退出码 ${result.status ?? 1}):${destination}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
log(`[ai-game-creator-shell] 已上传 ${destination}`);
|
|
||||||
}
|
|
||||||
if (dryRun) log('[ai-game-creator-shell] dry-run:未写入任何 OSS 对象');
|
|
||||||
return plan;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,15 +1,8 @@
|
|||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
import { readFileSync } from 'node:fs';
|
||||||
import os from 'node:os';
|
|
||||||
import path from 'node:path';
|
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
|
|
||||||
import {
|
import { formatOssutilCommand, readReleaseDryRun } from './release-oss.mjs';
|
||||||
createReleaseUploadPlan,
|
|
||||||
formatOssutilCommand,
|
|
||||||
readReleaseDryRun,
|
|
||||||
uploadReleaseArtifacts,
|
|
||||||
} from './release-oss.mjs';
|
|
||||||
|
|
||||||
test('dry run only accepts explicit truthy values', () => {
|
test('dry run only accepts explicit truthy values', () => {
|
||||||
assert.equal(readReleaseDryRun({}), false);
|
assert.equal(readReleaseDryRun({}), false);
|
||||||
@@ -40,158 +33,12 @@ test('printed upload command keeps arguments and hides credentials', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
function withReleaseFixture(channel, architecture, run) {
|
test('uploader gates every ossutil call behind the dry run switch', () => {
|
||||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-upload-plan-'));
|
const source = readFileSync(
|
||||||
try {
|
new URL('./release-upload.mjs', import.meta.url),
|
||||||
const artifact = path.join(
|
'utf8',
|
||||||
root,
|
);
|
||||||
channel === 'dev-win'
|
assert.match(source, /const dryRun = readReleaseDryRun\(\);/u);
|
||||||
? '陶泥儿_1.2.3_x64-setup.exe'
|
assert.match(source, /if \(dryRun\) \{/u);
|
||||||
: '陶泥儿.app.tar.gz',
|
assert.match(source, /dry-run:未写入任何 OSS 对象/u);
|
||||||
);
|
|
||||||
const downloadArtifact =
|
|
||||||
channel === 'dev-win'
|
|
||||||
? artifact
|
|
||||||
: path.join(root, `陶泥儿_1.2.3_${architecture}.dmg`);
|
|
||||||
const manifestPath = path.join(root, 'latest.json');
|
|
||||||
const legacyManifestPath =
|
|
||||||
channel === 'dev-win' ? path.join(root, 'legacy-latest.json') : null;
|
|
||||||
for (const file of [
|
|
||||||
artifact,
|
|
||||||
`${artifact}.sig`,
|
|
||||||
downloadArtifact,
|
|
||||||
manifestPath,
|
|
||||||
legacyManifestPath,
|
|
||||||
].filter(Boolean)) {
|
|
||||||
writeFileSync(file, 'fixture');
|
|
||||||
}
|
|
||||||
return run({
|
|
||||||
artifact,
|
|
||||||
downloadArtifact,
|
|
||||||
channel,
|
|
||||||
manifest: { version: '1.2.3' },
|
|
||||||
manifestPath,
|
|
||||||
legacyManifestPath,
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
rmSync(root, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const uploadOptions = {
|
|
||||||
bucket: 'agc-dev',
|
|
||||||
endpoint: 'oss-rg-china-mainland.aliyuncs.com',
|
|
||||||
log: () => {},
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const architecture of ['aarch64', 'x64']) {
|
|
||||||
test(`uploads every ${architecture} Mac object before the channel pointer`, () => {
|
|
||||||
withReleaseFixture('dev-mac', architecture, (release) => {
|
|
||||||
const calls = [];
|
|
||||||
uploadReleaseArtifacts(release, {
|
|
||||||
...uploadOptions,
|
|
||||||
spawn: (binary, args, options) => {
|
|
||||||
assert.equal(binary, 'ossutil');
|
|
||||||
assert.equal(options.shell, false);
|
|
||||||
assert.deepEqual(args.slice(0, 2), ['cp', '--force']);
|
|
||||||
calls.push({ source: args[2], destination: args[3] });
|
|
||||||
return { status: 0 };
|
|
||||||
},
|
|
||||||
});
|
|
||||||
assert.deepEqual(
|
|
||||||
calls.map(({ source }) => source),
|
|
||||||
[
|
|
||||||
release.artifact,
|
|
||||||
`${release.artifact}.sig`,
|
|
||||||
release.downloadArtifact,
|
|
||||||
release.manifestPath,
|
|
||||||
],
|
|
||||||
);
|
|
||||||
assert.equal(
|
|
||||||
calls[2].destination,
|
|
||||||
`oss://agc-dev/agc/dev-mac/1.2.3/陶泥儿_1.2.3_${architecture}.dmg`,
|
|
||||||
);
|
|
||||||
assert.equal(
|
|
||||||
calls[3].destination,
|
|
||||||
'oss://agc-dev/agc/dev-mac/latest.json',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
test('Windows uploads the shared installer once and publishes migration metadata last', () => {
|
|
||||||
withReleaseFixture('dev-win', 'x64', (release) => {
|
|
||||||
const plan = createReleaseUploadPlan(release, 'agc-dev');
|
|
||||||
assert.deepEqual(
|
|
||||||
plan.map(({ source }) => source),
|
|
||||||
[
|
|
||||||
release.artifact,
|
|
||||||
`${release.artifact}.sig`,
|
|
||||||
release.manifestPath,
|
|
||||||
release.legacyManifestPath,
|
|
||||||
],
|
|
||||||
);
|
|
||||||
assert.equal(plan.at(-1).destination, 'oss://agc-dev/agc/latest.json');
|
|
||||||
const calls = [];
|
|
||||||
uploadReleaseArtifacts(release, {
|
|
||||||
...uploadOptions,
|
|
||||||
spawn: (_binary, args) => {
|
|
||||||
assert.deepEqual(args.slice(0, 2), ['cp', '--force']);
|
|
||||||
calls.push(args[3]);
|
|
||||||
return { status: 0 };
|
|
||||||
},
|
|
||||||
});
|
|
||||||
assert.deepEqual(
|
|
||||||
calls,
|
|
||||||
plan.map(({ destination }) => destination),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const failedArtifactIndex of [0, 1, 2]) {
|
|
||||||
test(`failed Mac object ${failedArtifactIndex} prevents both later objects and latest publication`, () => {
|
|
||||||
withReleaseFixture('dev-mac', 'aarch64', (release) => {
|
|
||||||
const destinations = [];
|
|
||||||
assert.throws(
|
|
||||||
() =>
|
|
||||||
uploadReleaseArtifacts(release, {
|
|
||||||
...uploadOptions,
|
|
||||||
spawn: (_binary, args) => {
|
|
||||||
destinations.push(args[3]);
|
|
||||||
return {
|
|
||||||
status: destinations.length - 1 === failedArtifactIndex ? 1 : 0,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
/OSS 上传失败/u,
|
|
||||||
);
|
|
||||||
assert.equal(destinations.length, failedArtifactIndex + 1);
|
|
||||||
assert.ok(
|
|
||||||
destinations.every(
|
|
||||||
(destination) => !destination.endsWith('/latest.json'),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
test('dry run prints the complete plan without spawning uploads or exposing credentials', () => {
|
|
||||||
withReleaseFixture('dev-mac', 'aarch64', (release) => {
|
|
||||||
const output = [];
|
|
||||||
uploadReleaseArtifacts(release, {
|
|
||||||
...uploadOptions,
|
|
||||||
dryRun: true,
|
|
||||||
accessKeyId: 'fixture-id',
|
|
||||||
accessKeySecret: 'fixture-secret',
|
|
||||||
spawn: () => assert.fail('dry run must never execute ossutil'),
|
|
||||||
log: (line) => output.push(line),
|
|
||||||
});
|
|
||||||
assert.equal(
|
|
||||||
output.filter((line) => line.startsWith('[dry-run]')).length,
|
|
||||||
4,
|
|
||||||
);
|
|
||||||
assert.match(output.join('\n'), /\.dmg/u);
|
|
||||||
assert.match(output.at(-1), /未写入任何 OSS 对象/u);
|
|
||||||
assert.doesNotMatch(output.join('\n'), /fixture-id|fixture-secret|已上传/u);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user