Merge remote-tracking branch 'origin/master' into feat/jenkins-mac-build
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Failing after 11s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Failing after 11s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Failing after 11s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Failing after 12s
Project CI / AI game creator shell Rust smoke (pull_request) Failing after 12s
Project CI / AI game creator shell Rust crates (pull_request) Failing after 11s
Project CI / Backend tests (pull_request) Failing after 11s
Project CI / Native shell tests (pull_request) Failing after 14s
Project CI / Frontend tests (pull_request) Failing after 6s
Project CI / Repository checks (pull_request) Failing after 13s
Project CI / AI game creator shell web tests (pull_request) Failing after 12s
Project CI / AI game creator shell Rust shard 1/4 (pull_request) Failing after 11s
Project CI / AI game creator shell Rust shard 2/4 (pull_request) Failing after 11s
Project CI / AI game creator shell Rust shard 3/4 (pull_request) Failing after 11s
Project CI / AI game creator shell Rust shard 4/4 (pull_request) Failing after 12s
Project CI / AI game creator shell Rust smoke (pull_request) Failing after 12s
Project CI / AI game creator shell Rust crates (pull_request) Failing after 11s
Project CI / Backend tests (pull_request) Failing after 11s
Project CI / Native shell tests (pull_request) Failing after 14s
Project CI / Frontend tests (pull_request) Failing after 6s
Project CI / Repository checks (pull_request) Failing after 13s
Project CI / AI game creator shell web tests (pull_request) Failing after 12s
# Conflicts: # docs/technical/【技术方案】AGC客户端更新检查与下载-2026-08-31.md
This commit is contained in:
@@ -235,6 +235,10 @@ VITE_DEBUG_MODE=""
|
||||
# This is read by api-server and exposed through /api/runtime/frontend-config.
|
||||
GENARRATIVE_ENABLE_IMAGE_EDITOR_AGENT_SIDEBAR="false"
|
||||
|
||||
# 官网客户端下载检测渠道:dev、release 或自定义渠道;修改后重启 API 服务。
|
||||
# Windows/macOS 是系统维度,不填写 dev-win/dev-mac。
|
||||
GENARRATIVE_CLIENT_DOWNLOAD_CHANNEL="dev"
|
||||
|
||||
# Optional: official VikingDB credentials for regenerating build-tag similarities
|
||||
# with the Python embedding script. The script auto-loads `.env.local` and uses
|
||||
# the fixed `bge-large-zh` embedding model.
|
||||
|
||||
@@ -4,12 +4,13 @@
|
||||
|
||||
- 本文件只保留 Agent 进入仓库后必须立即遵守的最高优先级规则;完整执行细则见 [`docs/【协作规范】Agent工作入口与执行准则-2026-06-22.md`](docs/【协作规范】Agent工作入口与执行准则-2026-06-22.md)。
|
||||
- 团队级长期项目记忆位于 [`docs/project-memory/`](docs/project-memory/),供 3 名开发人员和各自本地 Agent 通过 Git 同步。
|
||||
- [`.codex/`](.codex/) 只保存仓库级 Codex 工具资源,例如 skills、plugins、hooks 和配置模板;长期项目知识不要写入 `.codex/`。
|
||||
- [`.codex/`](.codex/) 保存仓库级 Codex 工具资源,例如 skills、plugins、hooks 和配置模板;长期项目知识写入 `docs/` 与 `docs/project-memory/`。
|
||||
- 若 `docs/project-memory/shared-memory/` 与当前代码或最新 `docs/` 冲突,以代码和最新 `docs/` 为准,并同步修正过期共享记忆。
|
||||
|
||||
## 开始任务前
|
||||
|
||||
- 先写清一句话交付结果、验收判据和不做项,再按“必须项 / 风险项 / 可选项”排序;优先完成修改、定向验证和边界检查组成的最小闭环。设置时间盒和检查点,新增发现只有在影响交付判据时才扩大范围,否则记录为后续事项;工具探测、历史整理或验证便利不能自行改变任务目标。
|
||||
- 先写清一句话交付结果、验收判据和修改范围,再按“必须项 / 风险项 / 可选项”排序;优先完成修改、定向验证和边界检查组成的最小闭环。设置时间盒和检查点,新增发现只有在影响交付判据时才扩大范围,其余记录为后续事项。
|
||||
- Agent 可见内容直接描述当前任务、输入和成功条件,细节按调用需要提供。
|
||||
- 简单自包含任务可以直接执行;复杂开发、跨模块修改、后端 / UI / 文档体系调整前,按顺序读取:
|
||||
1. 本文件。
|
||||
2. [`docs/【协作规范】Agent工作入口与执行准则-2026-06-22.md`](docs/【协作规范】Agent工作入口与执行准则-2026-06-22.md)。
|
||||
@@ -23,24 +24,20 @@
|
||||
|
||||
- 禁止提交个人 `~/.codex` 配置、`.env`、API Key、Token、Cookie、会话记录、认证文件、本地私密路径、构建产物、日志、缓存和数据库 dump。
|
||||
- 不要在 `.gitignore` 中新增 `.env.local`。
|
||||
- 不要擅自把现有中文文案、注释、剧情或文档改写成英文;看到中文乱码时先确认真实编码,不要沿用乱码或用英文替换。
|
||||
- 修改包含中文的文件时优先局部补丁,避免整文件重写;修改后优先运行仓库编码检查。
|
||||
- 后续新增 Markdown 文档文件名必须以分类标签开头,格式为 `【标签名】中文标题-日期.md`;历史文档不要求批量重命名,除非本次任务明确涉及。
|
||||
- 现有中文文案、注释、剧情和文档保持中文;看到乱码时先确认真实编码并恢复正确中文。
|
||||
- 修改包含中文的文件时优先局部补丁;修改后优先运行仓库编码检查。
|
||||
- 新增 Markdown 文档文件名必须以分类标签开头,格式为 `【标签名】中文标题-日期.md`。
|
||||
- 工程修改要同步更新对应 `docs/` 文档;产生长期有效的架构约定、接口变化、排障经验、开发流程或协作规则时,同步更新 `docs/project-memory/shared-memory/`。
|
||||
- 默认保持系统简洁:优先复用、修改、扩展现有系统、页面和公共组件,不新建平行系统或平行页面。
|
||||
- UI 开发优先复用现有公共组件;发现跨页面或跨端重复的视觉/交互模式时,先抽取到 `packages/shared` 共享组件库并让现有页面迁移使用,禁止在业务页复制同类 UI。共享组件只承载通用表现与交互,不下沉领域规则、后端副作用或正式业务状态。
|
||||
- 对已明确退役且不存在现役调用方、公开契约、持久化数据、活跃实例或迁移要求的对象,坚持“四不写”:
|
||||
1. 不写历史兼容代码。
|
||||
2. 不写用于维持退役行为的防御性兼容测试。
|
||||
3. 不写仅说明其曾存在或已删除的墓碑注释。
|
||||
4. 不写仅记录其已删除的墓碑文档;直接将权威文档更新为当前状态。
|
||||
- 公开 API、持久化数据、SpacetimeDB schema、跨版本重放、活跃实例和正式迁移不适用“四不写”;必要兼容应最小化、白名单化并配套契约或迁移测试,迁移完成后同步删除兼容实现与对应测试。
|
||||
- UI 面板中不要默认写功能说明、规则描述或开发解释文案;移动端优先,同时保证网页端可正常显示和操作。
|
||||
- 点击按钮弹出独立面板的设计,不要实现成在当前面板下面追加内容。
|
||||
- 默认保持系统简洁:优先复用、修改、扩展现有系统、页面和公共组件。
|
||||
- UI 开发优先复用现有公共组件;发现跨页面或跨端重复的视觉/交互模式时,先抽取到 `packages/shared` 共享组件库并让现有页面迁移使用。共享组件承载通用表现与交互,领域规则、后端副作用和正式业务状态由后端负责。
|
||||
- 对已明确退役且不存在现役调用方、公开契约、持久化数据、活跃实例或迁移要求的对象,直接清理实现、专属测试和说明,将权威文档更新为当前状态;历史由 Git 保存。
|
||||
- 公开 API、持久化数据、SpacetimeDB schema、跨版本重放、活跃实例和正式迁移按实际需求保留最小、白名单化的兼容,并配套契约或迁移测试;迁移完成后同步删除兼容实现与对应测试。
|
||||
- UI 面板优先呈现任务内容与操作,说明按当前操作需要提供;移动端优先,同时保证网页端可正常显示和操作。
|
||||
- 点击按钮弹出的独立面板使用弹窗、抽屉、popover 或页面级 portal。
|
||||
|
||||
## 任务路由
|
||||
|
||||
- Issue 使用自托管 Gitea;优先用 Gitea UI/API 或 `tea` CLI,不使用 GitHub `gh` 或 GitLab `glab`,除非仓库已迁移。默认 triage 标签:`needs-triage`、`needs-info`、`ready-for-agent`、`ready-for-human`、`wontfix`。
|
||||
- Issue 使用自托管 Gitea;优先用 Gitea UI/API 或 `tea` CLI。默认 triage 标签:`needs-triage`、`needs-info`、`ready-for-agent`、`ready-for-human`、`wontfix`。
|
||||
- 需要仓库级 Codex skills/plugins 时,再读取 [`.codex/README.md`](.codex/README.md)。
|
||||
- 涉及 AI 游戏创作独立 App、多智能体 Runtime、本地项目产物或本地 HTTP 预览时,先读取 [`docs/technical/【技术方案】AI游戏创作智能体App实施计划-2026-06-24.md`](docs/technical/【技术方案】AI游戏创作智能体App实施计划-2026-06-24.md)。
|
||||
- 新增、补齐、迁移或重构玩法入口、玩法类型、创作工作台、生成页、结果页、发布、运行态、作品架、广场或公开 read model 前,必须读取并按 [`genarrative-play-type-integration`](.codex/skills/genarrative-play-type-integration/SKILL.md) 执行。
|
||||
@@ -50,10 +47,10 @@
|
||||
## 后端红线
|
||||
|
||||
- 后端最新技术约束以 [`docs/【后端架构】server-rs与SpacetimeDB数据契约-2026-05-15.md`](docs/【后端架构】server-rs与SpacetimeDB数据契约-2026-05-15.md) 为准。
|
||||
- 后端路线固定为 `server-rs + Axum + SpacetimeDB`;旧 `server-node`、Express、PostgreSQL、Go 服务端、`maincloud` / `Maincloud` / `MAINCLOUD` 只作为历史残留,不作为兼容目标。
|
||||
- 后端路线固定为 `server-rs + Axum + SpacetimeDB`。
|
||||
- DDD 分层边界按总纲执行:领域规则沉到 `module-*`,SpacetimeDB 表和事务编排留在 `spacetime-module`,后端访问 SpacetimeDB 统一经 `spacetime-client` facade,HTTP/SSE/BFF 留在 `api-server`,外部副作用留在 `platform-*`,前后端 DTO 留在 `shared-contracts`。
|
||||
- 前端只做表现、交互和临时 UI 状态,不承接正式业务真相,不绕过后端投影或后端 API 直接实现业务规则。
|
||||
- 契约、路由、DTO 去留和 breaking change 以当前后端架构文档、`server-rs/crates/api-server/src/app.rs`、`shared-contracts` 和 `packages/shared` 为准;不得在前端、`api-server` 或临时兼容层中重新发明旧接口。
|
||||
- 前端负责表现、交互和临时 UI 状态;正式业务状态与规则以后端投影和后端 API 为准。
|
||||
- 契约、路由、DTO 去留和 breaking change 以当前后端架构文档、`server-rs/crates/api-server/src/app.rs`、`shared-contracts` 和 `packages/shared` 为准。
|
||||
- 凡修改 `/api/external/v1` 的路由、HTTP 方法、请求 / 响应 DTO、请求头、状态码、鉴权或异步语义,必须在同一次变更中同步更新权威契约 [`docs/openapi/genarrative-external-v1.openapi.json`](docs/openapi/genarrative-external-v1.openapi.json) 及对应契约测试;Rust 实现与 OpenAPI 未保持一致时任务不得视为完成。
|
||||
- SpacetimeDB 已有表新增字段时,字段必须放在 Rust 表结构体最后,并设置明确默认值;需要删除、改名、重排或改类型时,必须先询问用户并确认迁移计划。
|
||||
- 修改 SpacetimeDB schema 后必须同步 `migration.rs`、表目录和生成绑定,并运行 `npm run check:spacetime-schema`。
|
||||
|
||||
@@ -32,6 +32,8 @@ import type {
|
||||
AdminLoginResponse,
|
||||
AdminMeResponse,
|
||||
AdminOverviewResponse,
|
||||
AdminProjectSnapshotListQuery,
|
||||
AdminProjectSnapshotListResponse,
|
||||
AdminRechargeOrderListQuery,
|
||||
AdminRechargeOrderListResponse,
|
||||
AdminRechargeRefundActionResponse,
|
||||
@@ -198,6 +200,92 @@ export function listAdminAccounts(token: string) {
|
||||
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(
|
||||
token: string,
|
||||
payload: AdminCreateAccountRequest,
|
||||
|
||||
@@ -96,6 +96,27 @@ export interface AdminMeResponse {
|
||||
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 {
|
||||
batchId: string;
|
||||
eventCount: number;
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
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,6 +31,7 @@ import { AdminInviteCodePage } from '../pages/AdminInviteCodePage';
|
||||
import { AdminLoginPage } from '../pages/AdminLoginPage';
|
||||
import { AdminOverviewPage } from '../pages/AdminOverviewPage';
|
||||
import { AdminProfileWalletConfigPage } from '../pages/AdminProfileWalletConfigPage';
|
||||
import { AdminProjectSnapshotsPage } from '../pages/AdminProjectSnapshotsPage';
|
||||
import { AdminRechargeOrderPage } from '../pages/AdminRechargeOrderPage';
|
||||
import { AdminRechargeProductPage } from '../pages/AdminRechargeProductPage';
|
||||
import { AdminRedeemCodePage } from '../pages/AdminRedeemCodePage';
|
||||
@@ -308,6 +309,12 @@ export function AdminApp() {
|
||||
{activeRouteId === 'accounts' ? (
|
||||
<AdminAccountsPage token={token} onUnauthorized={handleUnauthorized} />
|
||||
) : null}
|
||||
{activeRouteId === 'project-snapshots' ? (
|
||||
<AdminProjectSnapshotsPage
|
||||
token={token}
|
||||
onUnauthorized={handleUnauthorized}
|
||||
/>
|
||||
) : null}
|
||||
</AdminShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
Bug,
|
||||
Coins,
|
||||
Database,
|
||||
FolderArchive,
|
||||
GitBranch,
|
||||
Images,
|
||||
LayoutDashboard,
|
||||
@@ -49,6 +50,7 @@ const routeIcons = {
|
||||
'editor-generation-pricing': Coins,
|
||||
'editor-showcase': Star,
|
||||
'editor-assets': Images,
|
||||
'project-snapshots': FolderArchive,
|
||||
accounts: Users,
|
||||
'agc-models': ListChecks,
|
||||
} satisfies Record<AdminRouteId, typeof LayoutDashboard>;
|
||||
|
||||
@@ -122,3 +122,28 @@ test('零权限 member 不回落到 Dashboard', () => {
|
||||
expect(routes).toEqual([]);
|
||||
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,6 +16,7 @@ export type AdminRouteId =
|
||||
| 'editor-generation-pricing'
|
||||
| 'editor-showcase'
|
||||
| 'editor-assets'
|
||||
| 'project-snapshots'
|
||||
| 'agc-models'
|
||||
| 'accounts';
|
||||
|
||||
@@ -54,6 +55,7 @@ export const adminRoutes: AdminRouteDefinition[] = [
|
||||
{ id: 'agc-models', label: 'AGC 模型', hash: '#agc-models', ownerOnly: true },
|
||||
{ id: 'editor-showcase', label: '精选审核', hash: '#editor-showcase' },
|
||||
{ id: 'editor-assets', label: '素材查询', hash: '#editor-assets' },
|
||||
{ id: 'project-snapshots', label: '项目工程', hash: '#project-snapshots' },
|
||||
{ id: 'accounts', label: '账号管理', hash: '#accounts', ownerOnly: true },
|
||||
];
|
||||
|
||||
|
||||
@@ -154,6 +154,27 @@ test('灰度发布页可通过功能入口生成画布 Agent Gate Key', async ()
|
||||
);
|
||||
});
|
||||
|
||||
test('灰度发布页可选择模板库并默认启用零比例灰度', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<AdminGrayReleaseConfigPage token="admin-token" onUnauthorized={vi.fn()} />,
|
||||
);
|
||||
await screen.findByRole('button', { name: 'editor.new-toolbar' });
|
||||
await user.selectOptions(screen.getByLabelText('Gate Key 前缀'), ['agc']);
|
||||
expect((screen.getByLabelText('Gate Key') as HTMLInputElement).value).toBe(
|
||||
'agc:template-library',
|
||||
);
|
||||
expect(
|
||||
(screen.getByLabelText('Gate Key 目标') as HTMLSelectElement).value,
|
||||
).toBe('template-library');
|
||||
expect((screen.getByLabelText('启用') as HTMLInputElement).checked).toBe(
|
||||
true,
|
||||
);
|
||||
expect((screen.getByLabelText('灰度比例') as HTMLInputElement).value).toBe(
|
||||
'0',
|
||||
);
|
||||
});
|
||||
|
||||
test('灰度发布页保存时转换数组和百分比', async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(upsertAdminFeatureGateConfig).mockResolvedValueOnce({
|
||||
|
||||
@@ -27,9 +27,17 @@ interface GateTargetOption {
|
||||
|
||||
const GATE_PREFIX_LABELS: Record<string, string> = {
|
||||
'image-editor': '画布',
|
||||
agc: '客户端',
|
||||
};
|
||||
|
||||
const FIXED_GATE_TARGETS: GateTargetOption[] = [
|
||||
{
|
||||
prefix: 'agc',
|
||||
suffix: 'template-library',
|
||||
key: 'agc:template-library',
|
||||
label: '模板库',
|
||||
description: '客户端模板库灰度',
|
||||
},
|
||||
{
|
||||
prefix: 'image-editor',
|
||||
suffix: 'agent-sidebar',
|
||||
@@ -180,7 +188,7 @@ export function AdminGrayReleaseConfigPage({
|
||||
setSelectedGateKey('');
|
||||
setGatePrefix(option.prefix);
|
||||
setGateKey(option.key);
|
||||
setEnabled(false);
|
||||
setEnabled(option.key === 'agc:template-library');
|
||||
setRolloutPercent('0');
|
||||
setAllowUserIds('');
|
||||
setAllowUserTags('');
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
// @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();
|
||||
});
|
||||
@@ -0,0 +1,270 @@
|
||||
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,6 +1452,112 @@ button:disabled {
|
||||
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 {
|
||||
min-width: 1080px;
|
||||
table-layout: fixed;
|
||||
|
||||
@@ -957,9 +957,6 @@ async function runInteractiveCargo(cliArguments, setActiveChild) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// 立项策划跑 standard 档,`agent.delegate` 这类动作按项目权限策略必须逐个确认,
|
||||
// 而确认和问询都只从 CLI 的 stdin 读。自主构建档没有这一步,所以只有 --plan 需要
|
||||
// 一个把「人坐在终端前敲 approve」自动化掉的应答器;判据本身仍然走后端确认命令。
|
||||
const swarmConfirmationPromptPattern = /输入 approve 或 reject:$/u;
|
||||
const swarmUserInputPromptPattern = /请选择 1-\d+,或直接输入其他答案:$/u;
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
generateUpdateManifest,
|
||||
prepareReleaseVersion,
|
||||
resolveReleaseContext,
|
||||
resolveReleasePartition,
|
||||
runTauriBuild,
|
||||
} from './build-release.mjs';
|
||||
import { readReleaseDryRun, uploadReleaseArtifacts } from './release-oss.mjs';
|
||||
@@ -19,8 +20,8 @@ import {
|
||||
} from './verify-updater-signature.mjs';
|
||||
|
||||
/**
|
||||
* AGC macOS 渠道(dev-mac)发布入口:构建 universal 包 → 双架构 smoke → 生成 universal DMG
|
||||
* → 生成渠道清单 latest.json → 用产物内烘焙的公钥验签 → 按 dry-run 决定是否上传 OSS。
|
||||
* AGC macOS 分区(`<channel>-mac`)发布入口:构建 universal 包 → 双架构 smoke → 生成 universal DMG
|
||||
* → 生成分区清单 latest.json → 用产物内烘焙的公钥验签 → 按 dry-run 决定是否上传 OSS。
|
||||
*
|
||||
* 边界:
|
||||
* - Apple 签名与公证暂缺,产物为未签名 + 未公证(`--no-sign`),必须显式记录而非静默通过;
|
||||
@@ -69,6 +70,7 @@ const dryRun = readReleaseDryRun();
|
||||
|
||||
process.env.CARGO_TARGET_DIR = path.join(appRoot, 'src-tauri/target');
|
||||
const context = resolveReleaseContext(['--target=universal-apple-darwin']);
|
||||
const partition = resolveReleasePartition(context.channel, context.target);
|
||||
const version = await prepareReleaseVersion(context);
|
||||
|
||||
const args = [
|
||||
@@ -192,7 +194,8 @@ fs.writeFileSync(
|
||||
oss: {
|
||||
bucket,
|
||||
endpoint,
|
||||
latest: `oss://${bucket}/agc/${context.channel}/latest.json`,
|
||||
partition,
|
||||
latest: `oss://${bucket}/agc/${partition}/latest.json`,
|
||||
objects: uploadPlan.map(({ destination }) => destination),
|
||||
},
|
||||
artifacts: {
|
||||
@@ -213,6 +216,6 @@ fs.writeFileSync(
|
||||
);
|
||||
console.log(
|
||||
dryRun
|
||||
? `[agc-macos] dry-run 完成:${context.channel} 渠道产物与清单已生成,未写入 OSS`
|
||||
: `[agc-macos] ${context.channel} 渠道更新包、签名、首装包与清单已上传 OSS`,
|
||||
? `[agc-macos] dry-run 完成:${partition} 分区产物与清单已生成,未写入 OSS`
|
||||
: `[agc-macos] ${partition} 分区更新包、签名、首装包与清单已上传 OSS`,
|
||||
);
|
||||
|
||||
@@ -64,7 +64,7 @@ export function resolveReleaseContext(args = [], env = process.env) {
|
||||
);
|
||||
return Object.freeze({
|
||||
target,
|
||||
channel: resolveReleaseChannel(env, target),
|
||||
channel: resolveReleaseChannel(env),
|
||||
bundleRoot: path.join(
|
||||
appRoot,
|
||||
'src-tauri',
|
||||
@@ -83,14 +83,14 @@ const cargoLockPath = path.join(appRoot, 'src-tauri', 'Cargo.lock');
|
||||
const defaultOssBaseUrl =
|
||||
'https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc';
|
||||
|
||||
/**
|
||||
* 发布渠道 → 目标平台。渠道名会进入 OSS 路径并烘焙进客户端端点,
|
||||
* 一旦发布就不能改名(改名等于已发布客户端再也找不到更新)。
|
||||
*/
|
||||
const releaseChannels = {
|
||||
'dev-win': 'windows',
|
||||
'dev-mac': 'darwin',
|
||||
};
|
||||
const reservedChannelNames = new Set([
|
||||
'win',
|
||||
'mac',
|
||||
'windows',
|
||||
'macos',
|
||||
'darwin',
|
||||
'linux',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 影响 Windows 客户端产物的路径。调度管线的发布范围判定与这里的提交摘要必须
|
||||
@@ -158,39 +158,36 @@ export function resolveReleasePlatform(target = defaultTarget()) {
|
||||
throw new Error(`不支持的发布目标:${target}`);
|
||||
}
|
||||
|
||||
export function resolveReleaseChannel(
|
||||
env = process.env,
|
||||
target = defaultTarget(),
|
||||
) {
|
||||
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) {
|
||||
export function resolveReleaseChannel(env = process.env) {
|
||||
const channel = env.AGC_UPDATE_CHANNEL?.trim() ?? 'dev';
|
||||
if (
|
||||
!/^[a-z][a-z0-9-]{0,31}$/u.test(channel) ||
|
||||
channel.endsWith('-') ||
|
||||
reservedChannelNames.has(channel) ||
|
||||
/-(win|mac)$/u.test(channel)
|
||||
) {
|
||||
throw new Error(
|
||||
`目标 ${target} 没有默认发布渠道,请显式设置 AGC_UPDATE_CHANNEL`,
|
||||
'发布渠道无效:请使用 dev、release 或最多 32 位的小写字母、数字和连字符名称,系统名称不属于渠道',
|
||||
);
|
||||
}
|
||||
return defaultChannel;
|
||||
return channel;
|
||||
}
|
||||
|
||||
export function updateManifestUrl(channel = resolveReleaseChannel()) {
|
||||
return `${ossBaseUrl()}/${channel}/latest.json`;
|
||||
/** 系统分区延续已发布客户端端点,渠道本身不包含系统。 */
|
||||
export function resolveReleasePartition(
|
||||
channel = resolveReleaseChannel(),
|
||||
target = defaultTarget(),
|
||||
) {
|
||||
channel = resolveReleaseChannel({ AGC_UPDATE_CHANNEL: channel });
|
||||
validateReleaseTarget(target);
|
||||
return `${channel}-${resolveReleasePlatform(target) === 'windows' ? 'win' : 'mac'}`;
|
||||
}
|
||||
|
||||
export function updateManifestUrl(
|
||||
channel = resolveReleaseChannel(),
|
||||
target = defaultTarget(),
|
||||
) {
|
||||
return `${ossBaseUrl()}/${resolveReleasePartition(channel, target)}/latest.json`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -243,8 +240,8 @@ async function readManifestVersion(manifestUrl, label) {
|
||||
}
|
||||
|
||||
/** 上一次发布的渠道清单:拿版本做高水位、拿 commit 生成自动更新摘要。 */
|
||||
async function readRemoteChannelManifest(channel = resolveReleaseChannel()) {
|
||||
return fetchManifest(updateManifestUrl(channel), 'OSS 渠道清单');
|
||||
async function readRemoteChannelManifest(channel, target) {
|
||||
return fetchManifest(updateManifestUrl(channel, target), 'OSS 渠道清单');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -256,14 +253,17 @@ async function readRemoteChannelManifest(channel = resolveReleaseChannel()) {
|
||||
*/
|
||||
export async function resolvePreviousReleaseCommit(
|
||||
channel = resolveReleaseChannel(),
|
||||
{ override = process.env.AGC_UPDATE_PREVIOUS_COMMIT } = {},
|
||||
{
|
||||
override = process.env.AGC_UPDATE_PREVIOUS_COMMIT,
|
||||
target = defaultTarget(),
|
||||
} = {},
|
||||
) {
|
||||
const explicit = override?.trim();
|
||||
if (explicit && /^[0-9a-f]{7,40}$/u.test(explicit)) {
|
||||
return explicit;
|
||||
}
|
||||
try {
|
||||
const manifest = await readRemoteChannelManifest(channel);
|
||||
const manifest = await readRemoteChannelManifest(channel, target);
|
||||
const commit =
|
||||
typeof manifest?.commit === 'string' ? manifest.commit.trim() : '';
|
||||
return /^[0-9a-f]{7,40}$/u.test(commit) ? commit : null;
|
||||
@@ -285,12 +285,14 @@ export async function resolvePreviousReleaseCommit(
|
||||
*/
|
||||
export async function resolveRemoteHighWaterVersion(
|
||||
channel = resolveReleaseChannel(),
|
||||
target = defaultTarget(),
|
||||
) {
|
||||
const channelVersion = await readManifestVersion(
|
||||
updateManifestUrl(channel),
|
||||
updateManifestUrl(channel, target),
|
||||
'OSS 渠道清单',
|
||||
);
|
||||
if (channel !== 'dev-win') return channelVersion;
|
||||
if (channel !== 'dev' || resolveReleasePlatform(target) !== 'windows')
|
||||
return channelVersion;
|
||||
const legacyVersion = await readManifestVersion(
|
||||
legacyBridgeManifestUrl(),
|
||||
'OSS 迁移指针',
|
||||
@@ -308,9 +310,9 @@ function replaceVersionLine(source, version, pattern, label) {
|
||||
}
|
||||
|
||||
export async function prepareReleaseVersion(context = resolveReleaseContext()) {
|
||||
const { channel } = context;
|
||||
const { channel, target } = context;
|
||||
const localVersion = parseVersion(readPackageJson().version, '本地版本');
|
||||
const remoteVersion = await resolveRemoteHighWaterVersion(channel);
|
||||
const remoteVersion = await resolveRemoteHighWaterVersion(channel, target);
|
||||
const requestedVersion = process.env.AGC_RELEASE_VERSION?.trim();
|
||||
const nextVersion = requestedVersion
|
||||
? parseVersion(requestedVersion, '指定版本')
|
||||
@@ -399,24 +401,27 @@ export function buildTauriBuildArguments(
|
||||
}
|
||||
|
||||
/** 渠道端点必须由构建期注入:官方更新插件的端点配置不支持运行期改渠道。 */
|
||||
export function createChannelConfig(channel = resolveReleaseChannel()) {
|
||||
export function createChannelConfig(
|
||||
channel = resolveReleaseChannel(),
|
||||
target = defaultTarget(),
|
||||
) {
|
||||
return {
|
||||
plugins: {
|
||||
updater: {
|
||||
endpoints: [updateManifestUrl(channel)],
|
||||
endpoints: [updateManifestUrl(channel, target)],
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function writeChannelConfigFile(channel) {
|
||||
function writeChannelConfigFile(channel, target) {
|
||||
const configPath = path.join(
|
||||
os.tmpdir(),
|
||||
`agc-tauri-channel-${channel}.json`,
|
||||
`agc-tauri-channel-${channel}-${target}.json`,
|
||||
);
|
||||
fs.writeFileSync(
|
||||
configPath,
|
||||
`${JSON.stringify(createChannelConfig(channel), null, 2)}\n`,
|
||||
`${JSON.stringify(createChannelConfig(channel, target), null, 2)}\n`,
|
||||
);
|
||||
return configPath;
|
||||
}
|
||||
@@ -433,8 +438,8 @@ export function runTauriBuild(
|
||||
throw new Error('构建参数与发布上下文目标不一致');
|
||||
}
|
||||
const tauriArguments = buildTauriBuildArguments(args, context.target);
|
||||
const { channel } = context;
|
||||
const configPath = writeChannelConfigFile(channel);
|
||||
const { channel, target } = context;
|
||||
const configPath = writeChannelConfigFile(channel, target);
|
||||
console.log(
|
||||
`[ai-game-creator-shell] 渠道 ${channel} 端点配置:${configPath}`,
|
||||
);
|
||||
@@ -562,7 +567,7 @@ export function createUpdateManifest(
|
||||
artifactPath,
|
||||
{
|
||||
target = defaultTarget(),
|
||||
channel = resolveReleaseChannel(process.env, target),
|
||||
channel = resolveReleaseChannel(),
|
||||
publishedAt = new Date().toISOString(),
|
||||
notes = readReleaseNotes(),
|
||||
commit = readHeadCommit(),
|
||||
@@ -570,7 +575,7 @@ export function createUpdateManifest(
|
||||
} = {},
|
||||
) {
|
||||
validateReleaseTarget(target);
|
||||
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: channel }, target);
|
||||
const partition = resolveReleasePartition(channel, target);
|
||||
const signature = readUpdaterSignature(artifactPath);
|
||||
const version = readPackageJson().version;
|
||||
const firstInstallArtifact = selectFirstInstallArtifact(
|
||||
@@ -578,8 +583,8 @@ export function createUpdateManifest(
|
||||
{ target, version, artifact: artifactPath },
|
||||
);
|
||||
const fileName = path.basename(artifactPath);
|
||||
const url = `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(fileName)}`;
|
||||
const downloadUrl = `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(path.basename(firstInstallArtifact))}`;
|
||||
const url = `${ossBaseUrl()}/${partition}/${encodeURIComponent(version)}/${encodeURIComponent(fileName)}`;
|
||||
const downloadUrl = `${ossBaseUrl()}/${partition}/${encodeURIComponent(version)}/${encodeURIComponent(path.basename(firstInstallArtifact))}`;
|
||||
const platforms = {};
|
||||
const downloads = {};
|
||||
for (const key of resolveManifestPlatformKeys(target)) {
|
||||
@@ -712,14 +717,22 @@ export function formatRecentReleaseNotes(commits) {
|
||||
/** 旧协议(sha256)清单:只用于把已发布客户端带到新渠道协议,一个版本周期后整条删除。 */
|
||||
export function createLegacyUpdateManifest(
|
||||
artifactPath,
|
||||
{ channel = resolveReleaseChannel(), notes = readReleaseNotes() } = {},
|
||||
{
|
||||
channel = resolveReleaseChannel(),
|
||||
target = defaultTarget(),
|
||||
notes = readReleaseNotes(),
|
||||
} = {},
|
||||
) {
|
||||
const partition = resolveReleasePartition(channel, target);
|
||||
if (partition !== 'dev-win') {
|
||||
throw new Error('旧协议迁移清单只属于 dev 渠道的 Windows 系统');
|
||||
}
|
||||
const bytes = fs.readFileSync(artifactPath);
|
||||
const version = readPackageJson().version;
|
||||
const fileName = path.basename(artifactPath);
|
||||
return {
|
||||
version,
|
||||
downloadUrl: `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(fileName)}`,
|
||||
downloadUrl: `${ossBaseUrl()}/${partition}/${encodeURIComponent(version)}/${encodeURIComponent(fileName)}`,
|
||||
sha256: createHash('sha256').update(bytes).digest('hex'),
|
||||
size: bytes.length,
|
||||
...(notes ? { releaseNotes: notes } : {}),
|
||||
@@ -741,7 +754,9 @@ export async function generateUpdateManifest(
|
||||
artifact,
|
||||
});
|
||||
const manualNotes = readReleaseNotes();
|
||||
const previousCommit = await resolvePreviousReleaseCommit(channel);
|
||||
const previousCommit = await resolvePreviousReleaseCommit(channel, {
|
||||
target,
|
||||
});
|
||||
const commits = collectReleaseCommits(previousCommit);
|
||||
const recentCommits = previousCommit ? null : collectRecentReleaseCommits();
|
||||
const notes =
|
||||
@@ -767,8 +782,8 @@ export async function generateUpdateManifest(
|
||||
notes ? `${notes}\n` : '(本次没有可用的更新摘要)\n',
|
||||
);
|
||||
const legacyManifest =
|
||||
channel === 'dev-win'
|
||||
? createLegacyUpdateManifest(artifact, { channel, notes })
|
||||
channel === 'dev' && resolveReleasePlatform(target) === 'windows'
|
||||
? createLegacyUpdateManifest(artifact, { channel, target, notes })
|
||||
: null;
|
||||
const legacyManifestPath = legacyManifest
|
||||
? path.join(bundleRoot, 'legacy-latest.json')
|
||||
@@ -799,6 +814,7 @@ export async function generateUpdateManifest(
|
||||
}
|
||||
return {
|
||||
channel,
|
||||
target,
|
||||
artifact,
|
||||
downloadArtifact,
|
||||
manifest,
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
resolvePreviousReleaseCommit,
|
||||
resolveReleaseChannel,
|
||||
resolveReleaseContext,
|
||||
resolveReleasePartition,
|
||||
resolveRemoteHighWaterVersion,
|
||||
runTauriBuild,
|
||||
selectFirstInstallArtifact,
|
||||
@@ -129,32 +130,60 @@ test('does not select unsupported files', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('resolves the channel from the target platform and rejects mismatches', () => {
|
||||
assert.equal(resolveReleaseChannel({}, windowsTarget), 'dev-win');
|
||||
assert.equal(resolveReleaseChannel({}, universalTarget), 'dev-mac');
|
||||
test('channels are independent of platform and accept release and custom names', () => {
|
||||
assert.equal(resolveReleaseChannel({}), 'dev');
|
||||
for (const channel of ['dev', 'release', 'beta-2', 'a'.repeat(32)]) {
|
||||
assert.equal(
|
||||
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: channel }),
|
||||
channel,
|
||||
);
|
||||
assert.equal(
|
||||
resolveReleasePartition(channel, windowsTarget),
|
||||
`${channel}-win`,
|
||||
);
|
||||
assert.equal(
|
||||
resolveReleasePartition(channel, 'aarch64-apple-darwin'),
|
||||
`${channel}-mac`,
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: 'dev-mac' }, universalTarget),
|
||||
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: ' release ' }),
|
||||
'release',
|
||||
);
|
||||
for (const channel of [
|
||||
'',
|
||||
' ',
|
||||
'win',
|
||||
'mac',
|
||||
'windows',
|
||||
'macos',
|
||||
'darwin',
|
||||
'linux',
|
||||
'dev-win',
|
||||
'dev-mac',
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: 'dev-mac' }, windowsTarget),
|
||||
/只能用于 darwin 目标/u,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: 'beta-win' }, windowsTarget),
|
||||
/未知发布渠道/u,
|
||||
);
|
||||
'Release',
|
||||
'../dev',
|
||||
'a/b',
|
||||
'a_b',
|
||||
'-beta',
|
||||
'beta-',
|
||||
'1beta',
|
||||
'a'.repeat(33),
|
||||
]) {
|
||||
assert.throws(
|
||||
() => resolveReleaseChannel({ AGC_UPDATE_CHANNEL: channel }),
|
||||
/发布渠道无效/u,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('channel manifest URL and build-time endpoint follow the channel', () => {
|
||||
withEnv({ AGC_UPDATE_OSS_BASE_URL: undefined }, () => {
|
||||
assert.equal(
|
||||
updateManifestUrl('dev-win'),
|
||||
updateManifestUrl('dev', windowsTarget),
|
||||
'https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/dev-win/latest.json',
|
||||
);
|
||||
assert.deepEqual(createChannelConfig('dev-mac'), {
|
||||
assert.deepEqual(createChannelConfig('dev', 'aarch64-apple-darwin'), {
|
||||
plugins: {
|
||||
updater: {
|
||||
endpoints: [
|
||||
@@ -163,6 +192,15 @@ test('channel manifest URL and build-time endpoint follow the channel', () => {
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.equal(
|
||||
updateManifestUrl('release', windowsTarget),
|
||||
'https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/release-win/latest.json',
|
||||
);
|
||||
assert.equal(
|
||||
createChannelConfig('beta-2', 'x86_64-apple-darwin').plugins.updater
|
||||
.endpoints[0],
|
||||
'https://agc-dev.oss-rg-china-mainland.aliyuncs.com/agc/beta-2-mac/latest.json',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -191,7 +229,7 @@ test('release context resolves explicit targets before environment/default and f
|
||||
for (const env of [{}, { AGC_BUILD_TARGET: windowsTarget }]) {
|
||||
const context = resolveReleaseContext(args, env);
|
||||
assert.equal(context.target, 'aarch64-apple-darwin');
|
||||
assert.equal(context.channel, 'dev-mac');
|
||||
assert.equal(context.channel, 'dev');
|
||||
assert.match(
|
||||
context.bundleRoot.replaceAll('\\', '/'),
|
||||
/target\/aarch64-apple-darwin\/release\/bundle$/,
|
||||
@@ -200,14 +238,14 @@ test('release context resolves explicit targets before environment/default and f
|
||||
}
|
||||
assert.throws(
|
||||
() => resolveReleaseContext(args, { AGC_UPDATE_CHANNEL: 'dev-win' }),
|
||||
/只能用于 windows/,
|
||||
/发布渠道无效/,
|
||||
);
|
||||
}
|
||||
assert.equal(resolveReleaseContext([], {}).target, windowsTarget);
|
||||
assert.equal(
|
||||
resolveReleaseContext([], { AGC_BUILD_TARGET: 'x86_64-apple-darwin' })
|
||||
.channel,
|
||||
'dev-mac',
|
||||
'dev',
|
||||
);
|
||||
for (const args of [
|
||||
['--target'],
|
||||
@@ -236,7 +274,10 @@ test('explicit macOS target drives version lookup, Tauri endpoint, artifact and
|
||||
prepareVersion: async (context) => {
|
||||
seenContexts.push(context);
|
||||
assert.equal(
|
||||
await resolveRemoteHighWaterVersion(context.channel),
|
||||
await resolveRemoteHighWaterVersion(
|
||||
context.channel,
|
||||
context.target,
|
||||
),
|
||||
'0.1.67',
|
||||
);
|
||||
},
|
||||
@@ -411,7 +452,7 @@ test('manifest writer refuses to create latest when the current Mac DMG is missi
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid target or mismatched channel fails before any release side effect', async () => {
|
||||
test('invalid target or platform used as channel fails before any release side effect', async () => {
|
||||
let touched = false;
|
||||
const sideEffects = {
|
||||
prepareVersion: () => {
|
||||
@@ -431,7 +472,7 @@ test('invalid target or mismatched channel fails before any release side effect'
|
||||
await withEnv({ AGC_UPDATE_CHANNEL: 'dev-win' }, () =>
|
||||
assert.rejects(
|
||||
() => buildRelease(['--target=aarch64-apple-darwin'], sideEffects),
|
||||
/只能用于 windows/,
|
||||
/发布渠道无效/,
|
||||
),
|
||||
);
|
||||
assert.equal(touched, false);
|
||||
@@ -441,7 +482,12 @@ test('universal uses the Mac channel and the same signed artifact for both archi
|
||||
const context = resolveReleaseContext(['--target', universalTarget], {
|
||||
AGC_BUILD_TARGET: windowsTarget,
|
||||
});
|
||||
assert.equal(context.channel, 'dev-mac');
|
||||
// 渠道本身不含系统:分区由渠道 + 目标推导,二者不能混为一谈。
|
||||
assert.equal(context.channel, 'dev');
|
||||
assert.equal(
|
||||
resolveReleasePartition(context.channel, context.target),
|
||||
'dev-mac',
|
||||
);
|
||||
assert.ok(context.bundleRoot.includes(universalTarget));
|
||||
withSignedArtifact('陶泥儿.app.tar.gz', (artifact) => {
|
||||
const manifest = createUpdateManifest(artifact, {
|
||||
@@ -477,7 +523,7 @@ test('Windows remains the default and explicit Windows overrides macOS environme
|
||||
AGC_BUILD_TARGET: 'aarch64-apple-darwin',
|
||||
}),
|
||||
]) {
|
||||
assert.equal(context.channel, 'dev-win');
|
||||
assert.equal(context.channel, 'dev');
|
||||
assert.equal(
|
||||
selectReleaseArtifact(files, context.target),
|
||||
'/tmp/windows.exe',
|
||||
@@ -521,14 +567,14 @@ test('no-bundle smoke skips version writes and manifest generation', async () =>
|
||||
steps.push('manifest');
|
||||
},
|
||||
});
|
||||
assert.deepEqual(steps, ['dev-mac']);
|
||||
assert.deepEqual(steps, ['dev']);
|
||||
});
|
||||
|
||||
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',
|
||||
channel: 'dev',
|
||||
target: windowsTarget,
|
||||
publishedAt: '2026-09-17T00:00:00.000Z',
|
||||
});
|
||||
@@ -559,7 +605,7 @@ test('missing signature fails the channel manifest closed', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
createUpdateManifest(artifact, {
|
||||
channel: 'dev-win',
|
||||
channel: 'dev',
|
||||
target: windowsTarget,
|
||||
}),
|
||||
/缺少更新包签名/u,
|
||||
@@ -572,7 +618,7 @@ test('missing signature fails the channel manifest closed', () => {
|
||||
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',
|
||||
channel: 'dev',
|
||||
});
|
||||
assert.match(legacy.version, /^\d+\.\d+\.\d+$/u);
|
||||
assert.equal(legacy.sha256.length, 64);
|
||||
@@ -588,6 +634,86 @@ test('next release version follows the higher local or channel version', () => {
|
||||
assert.equal(nextPatchVersion('0.1.12', null), '0.1.13');
|
||||
});
|
||||
|
||||
for (const channel of ['release', 'beta-2']) {
|
||||
for (const target of [windowsTarget, 'aarch64-apple-darwin']) {
|
||||
test(`${channel} ${target} freezes its endpoint, version source and published objects`, async () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-channel-manifest-'));
|
||||
try {
|
||||
const windows = target === windowsTarget;
|
||||
const partition = `${channel}-${windows ? 'win' : 'mac'}`;
|
||||
const artifact = path.join(
|
||||
root,
|
||||
windows ? '陶泥儿_x64-setup.exe' : '陶泥儿.app.tar.gz',
|
||||
);
|
||||
writeFileSync(artifact, 'updater package');
|
||||
writeFileSync(`${artifact}.sig`, 'updater signature');
|
||||
if (!windows) createDmgFixture(root, target);
|
||||
const context = {
|
||||
...resolveReleaseContext([`--target=${target}`], {
|
||||
AGC_UPDATE_CHANNEL: channel,
|
||||
}),
|
||||
bundleRoot: root,
|
||||
};
|
||||
const requests = [];
|
||||
const result = await withStubbedFetch(
|
||||
(url) => {
|
||||
requests.push(url);
|
||||
assert.ok(url.endsWith(`/agc/${partition}/latest.json`));
|
||||
return jsonResponse({
|
||||
version: '2.3.4',
|
||||
commit: 'abcdef1234567890',
|
||||
});
|
||||
},
|
||||
async () => {
|
||||
assert.equal(
|
||||
await resolveRemoteHighWaterVersion(
|
||||
context.channel,
|
||||
context.target,
|
||||
),
|
||||
'2.3.4',
|
||||
);
|
||||
runTauriBuild([`--target=${target}`], context, {
|
||||
spawn: (_binary, command) => {
|
||||
const config = JSON.parse(
|
||||
readFileSync(
|
||||
command[command.lastIndexOf('--config') + 1],
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
config.plugins.updater.endpoints[0].endsWith(
|
||||
`/agc/${partition}/latest.json`,
|
||||
),
|
||||
);
|
||||
return { status: 0 };
|
||||
},
|
||||
});
|
||||
return generateUpdateManifest(context);
|
||||
},
|
||||
);
|
||||
assert.equal(result.channel, channel);
|
||||
assert.equal(result.target, target);
|
||||
assert.equal(result.manifest.version, packageVersion);
|
||||
assert.equal(result.legacyManifestPath, null);
|
||||
assert.equal(result.legacyManifest, null);
|
||||
assert.equal(requests.length, 2);
|
||||
for (const entry of [
|
||||
...Object.values(result.manifest.platforms),
|
||||
...Object.values(result.manifest.downloads),
|
||||
]) {
|
||||
assert.ok(entry.url.includes(`/agc/${partition}/${packageVersion}/`));
|
||||
}
|
||||
assert.throws(
|
||||
() => createLegacyUpdateManifest(artifact, { channel, target }),
|
||||
/只属于 dev 渠道/u,
|
||||
);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('version high water keeps the legacy pointer during the migration window', async () => {
|
||||
await withStubbedFetch(
|
||||
(url) =>
|
||||
@@ -595,7 +721,10 @@ test('version high water keeps the legacy pointer during the migration window',
|
||||
? jsonResponse({}, 404)
|
||||
: jsonResponse({ version: '0.1.57' }),
|
||||
async () => {
|
||||
assert.equal(await resolveRemoteHighWaterVersion('dev-win'), '0.1.57');
|
||||
assert.equal(
|
||||
await resolveRemoteHighWaterVersion('dev', windowsTarget),
|
||||
'0.1.57',
|
||||
);
|
||||
// 旧指针 0.1.57 已是高水位,下一次发布必须是 0.1.58,不能退回渠道本地版本。
|
||||
assert.equal(nextPatchVersion('0.1.47', '0.1.57'), '0.1.58');
|
||||
},
|
||||
@@ -609,7 +738,10 @@ test('version high water takes the higher of channel and legacy pointer', async
|
||||
? jsonResponse({ version: '0.1.60' })
|
||||
: jsonResponse({ version: '0.1.57' }),
|
||||
async () => {
|
||||
assert.equal(await resolveRemoteHighWaterVersion('dev-win'), '0.1.60');
|
||||
assert.equal(
|
||||
await resolveRemoteHighWaterVersion('dev', windowsTarget),
|
||||
'0.1.60',
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -624,7 +756,16 @@ test('version high water ignores the windows migration pointer for other channel
|
||||
return jsonResponse({ version: '0.1.12' });
|
||||
},
|
||||
async () => {
|
||||
assert.equal(await resolveRemoteHighWaterVersion('dev-mac'), '0.1.12');
|
||||
for (const [channel, target] of [
|
||||
['dev', 'aarch64-apple-darwin'],
|
||||
['release', windowsTarget],
|
||||
['beta-2', windowsTarget],
|
||||
]) {
|
||||
assert.equal(
|
||||
await resolveRemoteHighWaterVersion(channel, target),
|
||||
'0.1.12',
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -634,20 +775,20 @@ test('release notes anchor prefers the explicit commit and falls back to the man
|
||||
() => jsonResponse({ version: '0.1.61', commit: 'abcdef1234567890' }),
|
||||
async () => {
|
||||
assert.equal(
|
||||
await resolvePreviousReleaseCommit('dev-win', {
|
||||
await resolvePreviousReleaseCommit('dev', {
|
||||
override: '6017d46088c04199e99cf89f347b12d67591475e',
|
||||
}),
|
||||
'6017d46088c04199e99cf89f347b12d67591475e',
|
||||
);
|
||||
// 覆盖值非法时忽略,继续用清单里的 commit。
|
||||
assert.equal(
|
||||
await resolvePreviousReleaseCommit('dev-win', {
|
||||
await resolvePreviousReleaseCommit('dev', {
|
||||
override: 'not-a-sha',
|
||||
}),
|
||||
'abcdef1234567890',
|
||||
);
|
||||
assert.equal(
|
||||
await resolvePreviousReleaseCommit('dev-win', { override: ' ' }),
|
||||
await resolvePreviousReleaseCommit('dev', { override: ' ' }),
|
||||
'abcdef1234567890',
|
||||
);
|
||||
},
|
||||
@@ -657,7 +798,7 @@ test('release notes anchor prefers the explicit commit and falls back to the man
|
||||
() => jsonResponse({ version: '0.1.61' }),
|
||||
async () => {
|
||||
assert.equal(
|
||||
await resolvePreviousReleaseCommit('dev-win', { override: undefined }),
|
||||
await resolvePreviousReleaseCommit('dev', { override: undefined }),
|
||||
null,
|
||||
);
|
||||
},
|
||||
@@ -671,7 +812,7 @@ test('release notes anchor degrades to null when the manifest cannot be read', a
|
||||
};
|
||||
try {
|
||||
assert.equal(
|
||||
await resolvePreviousReleaseCommit('dev-win', { override: undefined }),
|
||||
await resolvePreviousReleaseCommit('dev', { override: undefined }),
|
||||
null,
|
||||
);
|
||||
} finally {
|
||||
|
||||
@@ -127,8 +127,7 @@ const allowedUncalledTauriCommands = [
|
||||
'open_game_creator_launcher_window',
|
||||
'open_game_creator_workspace_window',
|
||||
'read_direct_project_conversation',
|
||||
// 项目定时快照上传只在 Rust 侧触发(周期定时器 / 工作区窗口关闭)与排障调用;
|
||||
// 按产品口径不做客户端可见界面,因此同 `open_game_creator_*_window` 一样按 native-only 登记。
|
||||
// 前端登记工程生命周期,上传由 Rust 调度;以下两个命令仅供本机排障。
|
||||
'read_local_project_snapshot_state',
|
||||
'sync_local_project_snapshot',
|
||||
'reset_design_agent_session',
|
||||
|
||||
@@ -53,7 +53,7 @@ test('archive traversal and non-package entries fail closed', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('CI pipeline is manual, publishes the dev-mac channel and never reuses a developer workspace', () => {
|
||||
test('CI pipeline is manual, publishes the macOS partition and never reuses a developer workspace', () => {
|
||||
const pipeline = fs.readFileSync(
|
||||
new URL(
|
||||
'../../../jenkins/Jenkinsfile.ai-game-creator-shell-macos-build',
|
||||
@@ -68,7 +68,8 @@ test('CI pipeline is manual, publishes the dev-mac channel and never reuses a de
|
||||
'StrictHostKeyChecking=yes',
|
||||
'git merge-base --is-ancestor',
|
||||
'allowEmptyArchive: false',
|
||||
"AGC_UPDATE_CHANNEL = 'dev-mac'",
|
||||
"string(name: 'AGC_UPDATE_CHANNEL', defaultValue: 'dev'",
|
||||
'AGC_UPDATE_CHANNEL=${params.AGC_UPDATE_CHANNEL}',
|
||||
"string(credentialsId: 'AgcUpdaterSigningKey'",
|
||||
"string(credentialsId: 'AgcUpdaterSigningKeyPassword'",
|
||||
"string(credentialsId: 'AliyunAccessKeyId'",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import path from 'node:path';
|
||||
|
||||
import { resolveReleasePartition } from './build-release.mjs';
|
||||
|
||||
/**
|
||||
* 发布上传的 OSS 命令行整理:把 ossutil 参数与凭据整理成可执行或可打印的形式,
|
||||
* 便于在 dry-run 下核对将要执行的上传,同时保证任何输出都不回显凭据明文。
|
||||
@@ -34,16 +36,28 @@ export function createReleaseUploadPlan(
|
||||
artifact,
|
||||
downloadArtifact,
|
||||
channel,
|
||||
target,
|
||||
manifest,
|
||||
manifestPath,
|
||||
legacyManifestPath,
|
||||
},
|
||||
bucket,
|
||||
) {
|
||||
if (!artifact || !downloadArtifact || !manifestPath || !manifest?.version) {
|
||||
throw new Error('发布结果缺少更新包、首装包或清单');
|
||||
if (
|
||||
!artifact ||
|
||||
!downloadArtifact ||
|
||||
!manifestPath ||
|
||||
!manifest?.version ||
|
||||
!channel ||
|
||||
!target
|
||||
) {
|
||||
throw new Error('发布结果缺少渠道、构建目标、更新包、首装包或清单');
|
||||
}
|
||||
const prefix = `oss://${bucket}/agc/${channel}`;
|
||||
const partition = resolveReleasePartition(channel, target);
|
||||
if (legacyManifestPath && partition !== 'dev-win') {
|
||||
throw new Error('旧协议迁移清单只属于 dev 渠道的 Windows 系统');
|
||||
}
|
||||
const prefix = `oss://${bucket}/agc/${partition}`;
|
||||
const artifacts = [
|
||||
...new Set(
|
||||
[artifact, `${artifact}.sig`, downloadArtifact].map((file) =>
|
||||
|
||||
@@ -40,22 +40,24 @@ test('printed upload command keeps arguments and hides credentials', () => {
|
||||
);
|
||||
});
|
||||
|
||||
function withReleaseFixture(channel, architecture, run) {
|
||||
function withReleaseFixture(channel, architecture, run, platform = 'macos') {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-upload-plan-'));
|
||||
try {
|
||||
const artifact = path.join(
|
||||
root,
|
||||
channel === 'dev-win'
|
||||
platform === 'windows'
|
||||
? '陶泥儿_1.2.3_x64-setup.exe'
|
||||
: '陶泥儿.app.tar.gz',
|
||||
);
|
||||
const downloadArtifact =
|
||||
channel === 'dev-win'
|
||||
platform === 'windows'
|
||||
? 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;
|
||||
channel === 'dev' && platform === 'windows'
|
||||
? path.join(root, 'legacy-latest.json')
|
||||
: null;
|
||||
for (const file of [
|
||||
artifact,
|
||||
`${artifact}.sig`,
|
||||
@@ -69,6 +71,10 @@ function withReleaseFixture(channel, architecture, run) {
|
||||
artifact,
|
||||
downloadArtifact,
|
||||
channel,
|
||||
target:
|
||||
platform === 'windows'
|
||||
? 'x86_64-pc-windows-msvc'
|
||||
: `${architecture === 'aarch64' ? 'aarch64' : 'x86_64'}-apple-darwin`,
|
||||
manifest: { version: '1.2.3' },
|
||||
manifestPath,
|
||||
legacyManifestPath,
|
||||
@@ -86,7 +92,7 @@ const uploadOptions = {
|
||||
|
||||
for (const architecture of ['aarch64', 'x64']) {
|
||||
test(`uploads every ${architecture} Mac object before the channel pointer`, () => {
|
||||
withReleaseFixture('dev-mac', architecture, (release) => {
|
||||
withReleaseFixture('dev', architecture, (release) => {
|
||||
const calls = [];
|
||||
uploadReleaseArtifacts(release, {
|
||||
...uploadOptions,
|
||||
@@ -120,37 +126,42 @@ for (const architecture of ['aarch64', 'x64']) {
|
||||
}
|
||||
|
||||
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),
|
||||
);
|
||||
});
|
||||
withReleaseFixture(
|
||||
'dev',
|
||||
'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),
|
||||
);
|
||||
},
|
||||
'windows',
|
||||
);
|
||||
});
|
||||
|
||||
for (const failedArtifactIndex of [0, 1, 2]) {
|
||||
test(`failed Mac object ${failedArtifactIndex} prevents both later objects and latest publication`, () => {
|
||||
withReleaseFixture('dev-mac', 'aarch64', (release) => {
|
||||
withReleaseFixture('dev', 'aarch64', (release) => {
|
||||
const destinations = [];
|
||||
assert.throws(
|
||||
() =>
|
||||
@@ -176,7 +187,7 @@ for (const failedArtifactIndex of [0, 1, 2]) {
|
||||
}
|
||||
|
||||
test('dry run prints the complete plan without spawning uploads or exposing credentials', () => {
|
||||
withReleaseFixture('dev-mac', 'aarch64', (release) => {
|
||||
withReleaseFixture('dev', 'aarch64', (release) => {
|
||||
const output = [];
|
||||
uploadReleaseArtifacts(release, {
|
||||
...uploadOptions,
|
||||
@@ -195,3 +206,32 @@ test('dry run prints the complete plan without spawning uploads or exposing cred
|
||||
assert.doesNotMatch(output.join('\n'), /fixture-id|fixture-secret|已上传/u);
|
||||
});
|
||||
});
|
||||
|
||||
for (const channel of ['release', 'beta-2']) {
|
||||
for (const platform of ['windows', 'macos']) {
|
||||
test(`${channel} ${platform} uploads only its own partition and cannot write the dev bridge`, () => {
|
||||
withReleaseFixture(
|
||||
channel,
|
||||
'x64',
|
||||
(release) => {
|
||||
const plan = createReleaseUploadPlan(release, 'agc-dev');
|
||||
const suffix = platform === 'windows' ? 'win' : 'mac';
|
||||
const prefix = `oss://agc-dev/agc/${channel}-${suffix}/`;
|
||||
assert.ok(
|
||||
plan.every(({ destination }) => destination.startsWith(prefix)),
|
||||
);
|
||||
assert.equal(plan.at(-1).destination, `${prefix}latest.json`);
|
||||
assert.throws(
|
||||
() =>
|
||||
createReleaseUploadPlan(
|
||||
{ ...release, legacyManifestPath: release.manifestPath },
|
||||
'agc-dev',
|
||||
),
|
||||
/只属于 dev 渠道/u,
|
||||
);
|
||||
},
|
||||
platform,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,8 @@ struct PromptBundleManifest {
|
||||
version: String,
|
||||
#[serde(deserialize_with = "deserialize_unique_string_map")]
|
||||
sections: BTreeMap<String, String>,
|
||||
#[serde(default, deserialize_with = "deserialize_unique_string_map")]
|
||||
text_catalogs: BTreeMap<String, String>,
|
||||
compositions: PromptCompositions,
|
||||
variants: PromptVariants,
|
||||
#[serde(default)]
|
||||
@@ -121,6 +123,11 @@ struct AgentRole {
|
||||
brief_path_name: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TextCatalog(
|
||||
#[serde(deserialize_with = "deserialize_unique_string_map")] BTreeMap<String, String>,
|
||||
);
|
||||
|
||||
fn deserialize_unique_string_map<'de, D>(
|
||||
deserializer: D,
|
||||
) -> Result<BTreeMap<String, String>, D::Error>
|
||||
@@ -212,6 +219,13 @@ pub fn compile_manifest(manifest_path: &Path) -> Result<CompiledPromptBundle, St
|
||||
dependencies.insert(path);
|
||||
sections.insert(section_id.clone(), content);
|
||||
}
|
||||
let texts = read_text_catalogs(
|
||||
&manifest.text_catalogs,
|
||||
base,
|
||||
&canonical_base,
|
||||
&mut section_paths,
|
||||
&mut dependencies,
|
||||
)?;
|
||||
validate_registered_markdown_files(base, §ion_paths, &mut dependencies)?;
|
||||
|
||||
validate_composition(
|
||||
@@ -365,7 +379,8 @@ pub fn compile_manifest(manifest_path: &Path) -> Result<CompiledPromptBundle, St
|
||||
));
|
||||
}
|
||||
}
|
||||
let rust_source = render_rust(&manifest, §ions);
|
||||
let mut rust_source = render_rust(&manifest, §ions);
|
||||
rust_source.push_str(&render_text_macro(&texts));
|
||||
let specialist_nodes = manifest
|
||||
.agent_catalog
|
||||
.groups
|
||||
@@ -554,9 +569,13 @@ fn validate_section_reference(
|
||||
}
|
||||
|
||||
fn validate_section_path(path: &str) -> Result<(), String> {
|
||||
validate_prompt_path(path, ".md")
|
||||
}
|
||||
|
||||
fn validate_prompt_path(path: &str, extension: &str) -> Result<(), String> {
|
||||
if path.is_empty()
|
||||
|| path.contains('\\')
|
||||
|| !path.ends_with(".md")
|
||||
|| !path.ends_with(extension)
|
||||
|| path.split('/').any(|segment| {
|
||||
segment.is_empty()
|
||||
|| !segment.chars().all(|character| {
|
||||
@@ -577,6 +596,61 @@ fn validate_section_path(path: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_text_catalogs(
|
||||
catalogs: &BTreeMap<String, String>,
|
||||
base: &Path,
|
||||
canonical_base: &Path,
|
||||
registered_paths: &mut BTreeSet<String>,
|
||||
dependencies: &mut BTreeSet<PathBuf>,
|
||||
) -> Result<BTreeMap<String, String>, String> {
|
||||
let mut texts = BTreeMap::new();
|
||||
for (catalog_id, relative_path) in catalogs {
|
||||
validate_identifier(catalog_id, "text catalog id", false)?;
|
||||
validate_prompt_path(relative_path, ".json")?;
|
||||
if relative_path == "manifest.json"
|
||||
|| !registered_paths.insert(portable_section_path_key(relative_path))
|
||||
{
|
||||
return Err(format!("Prompt 文本目录路径重复:{relative_path}"));
|
||||
}
|
||||
validate_no_symlink_components(base, relative_path)?;
|
||||
let path = base.join(relative_path);
|
||||
let canonical_path = fs::canonicalize(&path)
|
||||
.map_err(|error| format!("解析 Prompt 文本目录路径失败 {relative_path}:{error}"))?;
|
||||
if !canonical_path.starts_with(canonical_base) || !path.is_file() {
|
||||
return Err(format!(
|
||||
"Prompt 文本目录必须是 Bundle 内的普通文件:{relative_path}"
|
||||
));
|
||||
}
|
||||
let content = fs::read_to_string(&path)
|
||||
.map_err(|error| format!("读取 Prompt 文本目录失败 {relative_path}:{error}"))?;
|
||||
let TextCatalog(entries) = serde_json::from_str(&content)
|
||||
.map_err(|error| format!("解析 Prompt 文本目录失败 {relative_path}:{error}"))?;
|
||||
if entries.is_empty() {
|
||||
return Err(format!("Prompt 文本目录不能为空:{catalog_id}"));
|
||||
}
|
||||
for (key, text) in entries {
|
||||
validate_identifier(&key, "text key", true)?;
|
||||
validate_nonempty(&text, "prompt text")?;
|
||||
texts.insert(format!("{catalog_id}.{key}"), text);
|
||||
}
|
||||
dependencies.insert(path);
|
||||
}
|
||||
Ok(texts)
|
||||
}
|
||||
|
||||
fn render_text_macro(texts: &BTreeMap<String, String>) -> String {
|
||||
let mut output = String::from("\n#[allow(unused_macros)]\nmacro_rules! prompt_text {\n");
|
||||
for (key, text) in texts {
|
||||
output.push_str(&format!(
|
||||
" ({}) => {{ {} }};\n",
|
||||
rust_literal(key),
|
||||
rust_literal(text),
|
||||
));
|
||||
}
|
||||
output.push_str("}\n");
|
||||
output
|
||||
}
|
||||
|
||||
fn portable_section_path_key(path: &str) -> String {
|
||||
path.to_ascii_lowercase()
|
||||
}
|
||||
@@ -590,9 +664,12 @@ fn validate_registered_markdown_files(
|
||||
collect_markdown_files(base, base, &mut discovered_paths, dependencies)?;
|
||||
for path in discovered_paths {
|
||||
if !registered_paths.contains(&path) {
|
||||
return Err(format!(
|
||||
"Prompt Bundle 存在未登记的 Markdown section:{path}"
|
||||
));
|
||||
let kind = if path.ends_with(".json") {
|
||||
"文本目录"
|
||||
} else {
|
||||
"Markdown section"
|
||||
};
|
||||
return Err(format!("Prompt Bundle 存在未登记的 {kind}:{path}"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -626,7 +703,10 @@ fn collect_markdown_files(
|
||||
|| !path
|
||||
.extension()
|
||||
.and_then(|extension| extension.to_str())
|
||||
.is_some_and(|extension| extension.eq_ignore_ascii_case("md"))
|
||||
.is_some_and(|extension| {
|
||||
extension.eq_ignore_ascii_case("md") || extension.eq_ignore_ascii_case("json")
|
||||
})
|
||||
|| path == base.join("manifest.json")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -647,7 +727,12 @@ fn collect_markdown_files(
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?
|
||||
.join("/");
|
||||
validate_section_path(&relative)?;
|
||||
let extension = if relative.ends_with(".json") {
|
||||
".json"
|
||||
} else {
|
||||
".md"
|
||||
};
|
||||
validate_prompt_path(&relative, extension)?;
|
||||
discovered_paths.insert(portable_section_path_key(&relative));
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
- project/analysis.md
|
||||
- project/决策台账.md
|
||||
- project/dialog.md
|
||||
不要把正式产物写在工作区根目录,也不要等审批失败后再迁移。
|
||||
阶段审批工具:当你判断本阶段必需产物已完成时,必须提交阶段审批。用户批准后 Runtime 自动进入下一阶段;你不能自行切换阶段。
|
||||
正式产物使用当前阶段指定的相对路径。
|
||||
五个策划阶段的审批:当你判断当前策划阶段必需产物已完成时,必须提交阶段审批。用户批准后 Runtime 自动进入下一阶段。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
顾问阶段不需要继续自主推动项目或主动安排下一步;遵照用户的具体指示行动。
|
||||
顾问阶段遵照用户的具体指示行动。
|
||||
根据用户指示回答问题、读取相关文档、修改工作区文件,并说明改动可能影响的已有产物。
|
||||
涉及方向性变化或多个可行方案时,先向用户说明影响并等待用户决定;不要替用户做决定。
|
||||
顾问阶段没有下一层,也不需要提交阶段审批。
|
||||
涉及方向性变化或多个可行方案时,先向用户说明影响并等待用户决定。
|
||||
顾问阶段以完成用户当前请求并汇报结果为结束点。
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user