Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 15774a1c02 | |||
| e3682fd06f |
@@ -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 },
|
||||
];
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -501,6 +501,41 @@ 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) {
|
||||
const signaturePath = `${artifactPath}.sig`;
|
||||
if (!fs.existsSync(signaturePath)) {
|
||||
@@ -521,23 +556,32 @@ export function createUpdateManifest(
|
||||
publishedAt = new Date().toISOString(),
|
||||
notes = readReleaseNotes(),
|
||||
commit = readHeadCommit(),
|
||||
downloadArtifact,
|
||||
} = {},
|
||||
) {
|
||||
validateReleaseTarget(target);
|
||||
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: channel }, target);
|
||||
const signature = readUpdaterSignature(artifactPath);
|
||||
const version = readPackageJson().version;
|
||||
const firstInstallArtifact = selectFirstInstallArtifact(
|
||||
downloadArtifact ? [downloadArtifact] : [],
|
||||
{ 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 platforms = {};
|
||||
const downloads = {};
|
||||
for (const key of resolveManifestPlatformKeys(target)) {
|
||||
platforms[key] = { signature, url };
|
||||
downloads[key] = { url: downloadUrl };
|
||||
}
|
||||
return {
|
||||
version,
|
||||
...(notes ? { notes } : {}),
|
||||
pub_date: publishedAt,
|
||||
platforms,
|
||||
downloads,
|
||||
// 非标准字段:更新插件会忽略,发布脚本用它定位下一次自动更新摘要的起点。
|
||||
...(commit ? { commit } : {}),
|
||||
};
|
||||
@@ -676,10 +720,16 @@ export async function generateUpdateManifest(
|
||||
context = resolveReleaseContext(),
|
||||
) {
|
||||
const { channel, target, bundleRoot } = context;
|
||||
const artifact = selectReleaseArtifact(listFiles(bundleRoot), target);
|
||||
const files = listFiles(bundleRoot);
|
||||
const artifact = selectReleaseArtifact(files, target);
|
||||
if (!artifact) {
|
||||
throw new Error(`未找到可发布的 AGC 安装包:${bundleRoot}`);
|
||||
}
|
||||
const downloadArtifact = selectFirstInstallArtifact(files, {
|
||||
target,
|
||||
version: readPackageJson().version,
|
||||
artifact,
|
||||
});
|
||||
const manualNotes = readReleaseNotes();
|
||||
const previousCommit = await resolvePreviousReleaseCommit(channel);
|
||||
const commits = collectReleaseCommits(previousCommit);
|
||||
@@ -693,7 +743,12 @@ export async function generateUpdateManifest(
|
||||
`[ai-game-creator-shell] 未生成自动更新摘要(上一发布 commit=${previousCommit ?? '未知'},客户端相关提交=${commits ? commits.length : '不可判定'},最近提交=${recentCommits ? recentCommits.length : '不可判定'})`,
|
||||
);
|
||||
}
|
||||
const manifest = createUpdateManifest(artifact, { channel, target, notes });
|
||||
const manifest = createUpdateManifest(artifact, {
|
||||
channel,
|
||||
target,
|
||||
notes,
|
||||
downloadArtifact,
|
||||
});
|
||||
const manifestPath = path.join(bundleRoot, 'latest.json');
|
||||
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
|
||||
const notesPath = path.join(bundleRoot, 'release-notes.txt');
|
||||
@@ -718,6 +773,7 @@ export async function generateUpdateManifest(
|
||||
`[ai-game-creator-shell] 渠道 ${channel}:已生成 ${manifestPath}`,
|
||||
);
|
||||
console.log(`[ai-game-creator-shell] 安装包:${artifact}`);
|
||||
console.log(`[ai-game-creator-shell] 首装包:${downloadArtifact}`);
|
||||
console.log(
|
||||
manualNotes
|
||||
? '[ai-game-creator-shell] 更新摘要:使用 AGC_UPDATE_RELEASE_NOTES 手动文案'
|
||||
@@ -734,6 +790,7 @@ export async function generateUpdateManifest(
|
||||
return {
|
||||
channel,
|
||||
artifact,
|
||||
downloadArtifact,
|
||||
manifest,
|
||||
manifestPath,
|
||||
notes,
|
||||
|
||||
@@ -32,12 +32,23 @@ import {
|
||||
resolveReleaseContext,
|
||||
resolveRemoteHighWaterVersion,
|
||||
runTauriBuild,
|
||||
selectFirstInstallArtifact,
|
||||
selectReleaseArtifact,
|
||||
updateManifestUrl,
|
||||
} from './build-release.mjs';
|
||||
|
||||
const windowsTarget = 'x86_64-pc-windows-msvc';
|
||||
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', () => {
|
||||
assert.throws(() => buildTauriBuildArguments([], universalTarget), /单架构/);
|
||||
@@ -254,7 +265,13 @@ test('explicit macOS target drives version lookup, Tauri endpoint, artifact and
|
||||
),
|
||||
artifact,
|
||||
);
|
||||
const manifest = createUpdateManifest(artifact, context);
|
||||
const manifest = createUpdateManifest(artifact, {
|
||||
...context,
|
||||
downloadArtifact: createDmgFixture(
|
||||
path.dirname(artifact),
|
||||
context.target,
|
||||
),
|
||||
});
|
||||
assert.deepEqual(Object.keys(manifest.platforms), [
|
||||
'darwin-aarch64',
|
||||
]);
|
||||
@@ -272,29 +289,118 @@ test('explicit macOS target drives version lookup, Tauri endpoint, artifact and
|
||||
assert.ok(seenContexts.every((context) => context === seenContexts[0]));
|
||||
});
|
||||
|
||||
test('real manifest writer uses the resolved bundle root and does not emit Windows artifacts', async () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-mac-manifest-'));
|
||||
for (const target of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) {
|
||||
test(`real manifest writer publishes the ${target} updater and first installer separately`, async () => {
|
||||
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 {
|
||||
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');
|
||||
writeFileSync(artifact, 'updater archive');
|
||||
writeFileSync(`${artifact}.sig`, 'signature');
|
||||
const context = {
|
||||
...resolveReleaseContext(['--target=x86_64-apple-darwin'], {}),
|
||||
...resolveReleaseContext(['--target=aarch64-apple-darwin'], {}),
|
||||
bundleRoot: root,
|
||||
};
|
||||
const result = await withStubbedFetch(
|
||||
(url) => {
|
||||
assert.match(url, /\/dev-mac\/latest\.json$/);
|
||||
return jsonResponse({}, 404);
|
||||
},
|
||||
await assert.rejects(
|
||||
() => generateUpdateManifest(context),
|
||||
/首装 DMG 必须唯一匹配/u,
|
||||
);
|
||||
assert.equal(result.artifact, artifact);
|
||||
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\//);
|
||||
assert.throws(() => readFileSync(path.join(root, 'latest.json')), {
|
||||
code: 'ENOENT',
|
||||
});
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
@@ -393,6 +499,9 @@ test('channel manifest carries version, platform keys and signature', () => {
|
||||
assert.equal(manifest.notes, '修复与改进');
|
||||
assert.equal(manifest.pub_date, '2026-09-17T00:00:00.000Z');
|
||||
assert.deepEqual(Object.keys(manifest.platforms), ['windows-x86_64']);
|
||||
assert.deepEqual(manifest.downloads, {
|
||||
'windows-x86_64': { url: manifest.platforms['windows-x86_64'].url },
|
||||
});
|
||||
assert.equal(
|
||||
manifest.platforms['windows-x86_64'].signature,
|
||||
'signature-content',
|
||||
@@ -573,18 +682,18 @@ test('recent commit fallback marks that entries may repeat the previous release'
|
||||
}
|
||||
});
|
||||
|
||||
test('release upload forces overwrite for artifact, signature and channel pointers', () => {
|
||||
test('release entry forwards the built artifacts and dry-run mode to the uploader', () => {
|
||||
const source = readFileSync(
|
||||
new URL('./release-upload.mjs', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.equal(
|
||||
(source.match(/runOssutil\(\[\s*'cp',\s*'--force'/gu) ?? []).length,
|
||||
4,
|
||||
assert.match(
|
||||
source,
|
||||
/const release = await buildRelease\(process\.argv\.slice\(2\)\)/u,
|
||||
);
|
||||
assert.match(source, /agc\/\$\{channel\}\/latest\.json/u);
|
||||
assert.match(source, /agc\/latest\.json/u);
|
||||
assert.match(source, /await buildRelease\(process\.argv\.slice\(2\)\)/u);
|
||||
assert.match(source, /uploadReleaseArtifacts\(release, \{/u);
|
||||
assert.match(source, /const dryRun = readReleaseDryRun\(\);/u);
|
||||
assert.ok(source.includes('\n dryRun,\n'));
|
||||
});
|
||||
|
||||
test('release notes list client commits with short sha and bound their size', () => {
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* 发布上传的 OSS 命令行整理:把 ossutil 参数与凭据整理成可执行或可打印的形式,
|
||||
* 便于在 dry-run 下核对将要执行的上传,同时保证任何输出都不回显凭据明文。
|
||||
@@ -25,3 +28,89 @@ export function formatOssutilCommand({ binary, args, endpoint, credentials }) {
|
||||
}
|
||||
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,8 +1,15 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { test } from 'node:test';
|
||||
|
||||
import { formatOssutilCommand, readReleaseDryRun } from './release-oss.mjs';
|
||||
import {
|
||||
createReleaseUploadPlan,
|
||||
formatOssutilCommand,
|
||||
readReleaseDryRun,
|
||||
uploadReleaseArtifacts,
|
||||
} from './release-oss.mjs';
|
||||
|
||||
test('dry run only accepts explicit truthy values', () => {
|
||||
assert.equal(readReleaseDryRun({}), false);
|
||||
@@ -33,12 +40,158 @@ test('printed upload command keeps arguments and hides credentials', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('uploader gates every ossutil call behind the dry run switch', () => {
|
||||
const source = readFileSync(
|
||||
new URL('./release-upload.mjs', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(source, /const dryRun = readReleaseDryRun\(\);/u);
|
||||
assert.match(source, /if \(dryRun\) \{/u);
|
||||
assert.match(source, /dry-run:未写入任何 OSS 对象/u);
|
||||
function withReleaseFixture(channel, architecture, run) {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-upload-plan-'));
|
||||
try {
|
||||
const artifact = path.join(
|
||||
root,
|
||||
channel === 'dev-win'
|
||||
? '陶泥儿_1.2.3_x64-setup.exe'
|
||||
: '陶泥儿.app.tar.gz',
|
||||
);
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import path from 'node:path';
|
||||
|
||||
import { formatOssutilCommand, readReleaseDryRun } from './release-oss.mjs';
|
||||
import { readReleaseDryRun, uploadReleaseArtifacts } from './release-oss.mjs';
|
||||
|
||||
const bucket = process.env.AGC_OSS_BUCKET?.trim() || 'agc-dev';
|
||||
const endpoint =
|
||||
@@ -14,76 +11,12 @@ const dryRun = readReleaseDryRun();
|
||||
|
||||
const { buildRelease } = await import('./build-release.mjs');
|
||||
|
||||
function runOssutil(args) {
|
||||
const binary = process.env.OSSUTIL_BIN?.trim() || 'ossutil';
|
||||
const accessKeyId = process.env.AGC_OSS_ACCESS_KEY_ID?.trim();
|
||||
const accessKeySecret = process.env.AGC_OSS_ACCESS_KEY_SECRET;
|
||||
if (Boolean(accessKeyId) !== Boolean(accessKeySecret)) {
|
||||
throw new Error('OSS AccessKey ID 和 Secret 必须同时提供');
|
||||
}
|
||||
if (dryRun) {
|
||||
// 演练:只打印将要执行的上传,凭据以占位符呈现,不写入 OSS。
|
||||
console.log(
|
||||
`[dry-run] ${formatOssutilCommand({
|
||||
binary,
|
||||
args,
|
||||
endpoint,
|
||||
credentials: Boolean(accessKeyId),
|
||||
})}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const credentialArgs = accessKeyId
|
||||
? ['--access-key-id', accessKeyId, '--access-key-secret', accessKeySecret]
|
||||
: [];
|
||||
const result = spawnSync(
|
||||
binary,
|
||||
[...args, '--endpoint', endpoint, ...credentialArgs],
|
||||
{
|
||||
stdio: 'inherit',
|
||||
shell: false,
|
||||
},
|
||||
);
|
||||
if (result.error) {
|
||||
throw new Error(`无法执行 ${binary},请先安装并配置 ossutil`);
|
||||
}
|
||||
if (result.status !== 0) process.exit(result.status ?? 1);
|
||||
}
|
||||
|
||||
const { artifact, channel, legacyManifestPath, manifest, manifestPath } =
|
||||
await buildRelease(process.argv.slice(2));
|
||||
const artifactKey = `agc/${channel}/${manifest.version}/${path.basename(artifact)}`;
|
||||
// Jenkins/ossutil 默认会在目标对象已存在时交互询问并按默认值跳过;
|
||||
// 发布清单是固定的 latest 指针,必须显式覆盖,否则流水线会误报成功但远端仍保留旧版本。
|
||||
runOssutil(['cp', '--force', artifact, `oss://${bucket}/${artifactKey}`]);
|
||||
runOssutil([
|
||||
'cp',
|
||||
'--force',
|
||||
`${artifact}.sig`,
|
||||
`oss://${bucket}/${artifactKey}.sig`,
|
||||
]);
|
||||
runOssutil([
|
||||
'cp',
|
||||
'--force',
|
||||
manifestPath,
|
||||
`oss://${bucket}/agc/${channel}/latest.json`,
|
||||
]);
|
||||
console.log(`[ai-game-creator-shell] 已上传 oss://${bucket}/${artifactKey}`);
|
||||
console.log(
|
||||
`[ai-game-creator-shell] 已上传 oss://${bucket}/agc/${channel}/latest.json`,
|
||||
);
|
||||
if (legacyManifestPath) {
|
||||
// 迁移桥:让仍走旧 sha256 清单的已发布客户端升级到新协议,一个版本周期后删除。
|
||||
runOssutil([
|
||||
'cp',
|
||||
'--force',
|
||||
legacyManifestPath,
|
||||
`oss://${bucket}/agc/latest.json`,
|
||||
]);
|
||||
console.log(
|
||||
`[ai-game-creator-shell] 已上传迁移指针 oss://${bucket}/agc/latest.json`,
|
||||
);
|
||||
}
|
||||
if (dryRun) {
|
||||
console.log('[ai-game-creator-shell] dry-run:未写入任何 OSS 对象');
|
||||
}
|
||||
const release = await buildRelease(process.argv.slice(2));
|
||||
uploadReleaseArtifacts(release, {
|
||||
bucket,
|
||||
endpoint,
|
||||
binary: process.env.OSSUTIL_BIN?.trim() || 'ossutil',
|
||||
accessKeyId: process.env.AGC_OSS_ACCESS_KEY_ID?.trim(),
|
||||
accessKeySecret: process.env.AGC_OSS_ACCESS_KEY_SECRET,
|
||||
dryRun,
|
||||
});
|
||||
|
||||
@@ -2723,6 +2723,7 @@ fn main() {
|
||||
ack_error_reports,
|
||||
sync_local_project_snapshot,
|
||||
read_local_project_snapshot_state,
|
||||
set_active_project_snapshot_workspace,
|
||||
])
|
||||
.build(tauri_context);
|
||||
let app = match app {
|
||||
|
||||
@@ -22,6 +22,10 @@ pub(crate) struct ProjectSnapshotIndex {
|
||||
pub(crate) sync_revision: u64,
|
||||
pub(crate) synced_at_ms: u64,
|
||||
#[serde(default)]
|
||||
pub(crate) project_name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub(crate) pending_files: Option<u32>,
|
||||
#[serde(default)]
|
||||
pub(crate) files: BTreeMap<String, ProjectSnapshotIndexedFile>,
|
||||
}
|
||||
|
||||
@@ -35,6 +39,8 @@ pub(crate) fn empty_project_snapshot_index(
|
||||
user_id: user_id.to_string(),
|
||||
sync_revision: 0,
|
||||
synced_at_ms: 0,
|
||||
project_name: None,
|
||||
pending_files: None,
|
||||
files: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
use super::*;
|
||||
|
||||
/// 显式空登记保留在表中,避免返回首页后又从窗口的旧 URL 恢复项目。
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct ProjectSnapshotWorkspaces {
|
||||
windows: BTreeMap<String, Option<String>>,
|
||||
}
|
||||
|
||||
impl ProjectSnapshotWorkspaces {
|
||||
pub(crate) fn project_for_window(
|
||||
&self,
|
||||
label: &str,
|
||||
url_project: Option<String>,
|
||||
) -> Option<String> {
|
||||
self.windows.get(label).cloned().unwrap_or(url_project)
|
||||
}
|
||||
|
||||
pub(crate) fn set_project(
|
||||
&mut self,
|
||||
label: &str,
|
||||
project_path: Option<String>,
|
||||
) -> Vec<(PathBuf, ProjectSnapshotSyncTrigger)> {
|
||||
let previous = self
|
||||
.windows
|
||||
.insert(label.to_string(), project_path.clone())
|
||||
.flatten();
|
||||
let key = |path: &String| project_snapshot_sync_key(Path::new(path));
|
||||
if previous.as_ref().map(key) == project_path.as_ref().map(key) {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut requests = Vec::new();
|
||||
if let Some(previous) = previous {
|
||||
requests.push((
|
||||
PathBuf::from(previous),
|
||||
ProjectSnapshotSyncTrigger::ProjectClose,
|
||||
));
|
||||
}
|
||||
if let Some(project_path) = project_path {
|
||||
requests.push((
|
||||
PathBuf::from(project_path),
|
||||
ProjectSnapshotSyncTrigger::ProjectOpen,
|
||||
));
|
||||
}
|
||||
requests
|
||||
}
|
||||
}
|
||||
|
||||
static PROJECT_SNAPSHOT_WORKSPACES: OnceLock<Mutex<ProjectSnapshotWorkspaces>> = OnceLock::new();
|
||||
|
||||
fn project_snapshot_workspaces() -> &'static Mutex<ProjectSnapshotWorkspaces> {
|
||||
PROJECT_SNAPSHOT_WORKSPACES.get_or_init(|| Mutex::new(ProjectSnapshotWorkspaces::default()))
|
||||
}
|
||||
|
||||
/// 窗口身份由 Tauri 注入,前端只能登记自身已经打开的普通项目目录。
|
||||
#[tauri::command]
|
||||
pub(crate) fn set_active_project_snapshot_workspace(
|
||||
window: tauri::Window,
|
||||
project_path: Option<String>,
|
||||
) -> Result<(), String> {
|
||||
let project_path = project_path
|
||||
.map(|path| {
|
||||
let root = resolve_project_snapshot_root(&path)?;
|
||||
let manifest = read_existing_manifest_for_project(&root)?;
|
||||
validate_project_snapshot_project_id(manifest.project_id.trim())?;
|
||||
Ok::<_, String>(root.to_string_lossy().into_owned())
|
||||
})
|
||||
.transpose()
|
||||
.inspect_err(|_| {
|
||||
app_log!(
|
||||
"project_snapshot.workspace.registration.failed window={} reason=invalid-project",
|
||||
window.label()
|
||||
);
|
||||
})?;
|
||||
let requests = project_snapshot_workspaces()
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
.set_project(window.label(), project_path);
|
||||
for (root, trigger) in requests {
|
||||
request_project_snapshot_sync(root, trigger);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn open_project_snapshot_workspaces(app: &tauri::AppHandle) -> Vec<String> {
|
||||
let registry = project_snapshot_workspaces()
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
.clone();
|
||||
// WebView URL 读取可能回到主线程,不能持登记锁等待它,否则会与关窗/登记互锁。
|
||||
let mut paths = BTreeMap::new();
|
||||
for window in app.webview_windows().into_values() {
|
||||
let url_project = window
|
||||
.url()
|
||||
.ok()
|
||||
.and_then(|url| project_snapshot_project_path_from_url(&url));
|
||||
if let Some(path) = registry.project_for_window(window.label(), url_project) {
|
||||
paths.insert(project_snapshot_sync_key(Path::new(&path)), path);
|
||||
}
|
||||
}
|
||||
paths.into_values().collect()
|
||||
}
|
||||
|
||||
pub(crate) fn handle_project_snapshot_window_event(
|
||||
window: &tauri::Window,
|
||||
event: &tauri::WindowEvent,
|
||||
) {
|
||||
if matches!(event, tauri::WindowEvent::Destroyed) {
|
||||
project_snapshot_workspaces()
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
.windows
|
||||
.remove(window.label());
|
||||
return;
|
||||
}
|
||||
if !matches!(event, tauri::WindowEvent::CloseRequested { .. }) {
|
||||
return;
|
||||
}
|
||||
let url_project = window
|
||||
.app_handle()
|
||||
.get_webview_window(window.label())
|
||||
.and_then(|webview| webview.url().ok())
|
||||
.and_then(|url| project_snapshot_project_path_from_url(&url));
|
||||
let mut registry = project_snapshot_workspaces()
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let project_path = registry.project_for_window(window.label(), url_project);
|
||||
registry.set_project(window.label(), None);
|
||||
drop(registry);
|
||||
if let Some(project_path) = project_path {
|
||||
request_project_snapshot_sync(
|
||||
PathBuf::from(project_path),
|
||||
ProjectSnapshotSyncTrigger::ProjectClose,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use std::time::Instant;
|
||||
|
||||
mod diff;
|
||||
mod index;
|
||||
mod lifecycle;
|
||||
mod scan;
|
||||
mod transport;
|
||||
|
||||
@@ -19,6 +20,7 @@ mod tests;
|
||||
|
||||
pub(crate) use diff::*;
|
||||
pub(crate) use index::*;
|
||||
pub(crate) use lifecycle::*;
|
||||
pub(crate) use scan::*;
|
||||
pub(crate) use transport::*;
|
||||
|
||||
@@ -50,6 +52,7 @@ const PROJECT_SNAPSHOT_DISABLED_ENV: &str = "GENARRATIVE_AGC_PROJECT_SNAPSHOT_DI
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum ProjectSnapshotSyncTrigger {
|
||||
ProjectOpen,
|
||||
Periodic,
|
||||
ProjectClose,
|
||||
Manual,
|
||||
@@ -58,6 +61,7 @@ pub(crate) enum ProjectSnapshotSyncTrigger {
|
||||
impl ProjectSnapshotSyncTrigger {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::ProjectOpen => "project-open",
|
||||
Self::Periodic => "periodic",
|
||||
Self::ProjectClose => "project-close",
|
||||
Self::Manual => "manual",
|
||||
@@ -215,6 +219,19 @@ pub(crate) fn wait_for_project_snapshot_syncs(timeout: Duration) -> bool {
|
||||
}
|
||||
|
||||
/// 把项目同步请求交给后台线程:窗口关闭与应用退出路径都不能被网络等待阻塞。
|
||||
fn spawn_project_snapshot_sync_task(
|
||||
run: impl FnOnce() + Send + 'static,
|
||||
) -> std::io::Result<std::thread::JoinHandle<()>> {
|
||||
// 退出等待必须连已排队但尚未开始执行的线程一起计入。
|
||||
let scheduled = ProjectSnapshotInFlightGuard::begin();
|
||||
std::thread::Builder::new()
|
||||
.name("agc-project-snapshot".to_string())
|
||||
.spawn(move || {
|
||||
let _scheduled = scheduled;
|
||||
run();
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn request_project_snapshot_sync(
|
||||
project_root: PathBuf,
|
||||
trigger: ProjectSnapshotSyncTrigger,
|
||||
@@ -223,22 +240,22 @@ pub(crate) fn request_project_snapshot_sync(
|
||||
return;
|
||||
}
|
||||
let key = project_snapshot_sync_key(&project_root);
|
||||
let spawn = std::thread::Builder::new()
|
||||
.name("agc-project-snapshot".to_string())
|
||||
.spawn(move || {
|
||||
let run = || sync_project_snapshot_blocking(&project_root, trigger);
|
||||
let outcome = if matches!(trigger, ProjectSnapshotSyncTrigger::Periodic) {
|
||||
try_run_project_snapshot_sync(&key, run)
|
||||
} else {
|
||||
Some(run_project_snapshot_sync(&key, run))
|
||||
};
|
||||
if let Some(Err(error)) = outcome {
|
||||
app_log!(
|
||||
"project_snapshot.sync.failed trigger={}: {error}",
|
||||
trigger.as_str()
|
||||
);
|
||||
}
|
||||
});
|
||||
let spawn = spawn_project_snapshot_sync_task(move || {
|
||||
let run = || sync_project_snapshot_blocking(&project_root, trigger);
|
||||
let outcome = if matches!(trigger, ProjectSnapshotSyncTrigger::Periodic) {
|
||||
try_run_project_snapshot_sync(&key, run)
|
||||
} else {
|
||||
Some(run_project_snapshot_sync(&key, run))
|
||||
};
|
||||
if let Some(Err(error)) = outcome {
|
||||
let error = error.replace(project_root.to_string_lossy().as_ref(), "<project>");
|
||||
app_log!(
|
||||
"project_snapshot.sync.failed projectKey={:016x} trigger={}: {error}",
|
||||
fnv1a64(key.as_bytes()),
|
||||
trigger.as_str()
|
||||
);
|
||||
}
|
||||
});
|
||||
if let Err(error) = spawn {
|
||||
app_log!("project_snapshot.sync.spawn.failed: {error}");
|
||||
}
|
||||
@@ -296,7 +313,9 @@ async fn sync_project_snapshot_async(
|
||||
}
|
||||
let diff =
|
||||
compute_project_snapshot_diff(&scan, &previous.files, PROJECT_SNAPSHOT_MAX_SYNC_BYTES)?;
|
||||
if !diff.has_changes() {
|
||||
let project_name = (!manifest.name.trim().is_empty()).then(|| manifest.name.trim().to_string());
|
||||
let pending_files = project_snapshot_pending_file_count(&diff, &[]);
|
||||
if !project_snapshot_manifest_needs_sync(&previous, &diff, &project_name, pending_files) {
|
||||
return Ok(ProjectSnapshotSyncReport {
|
||||
project_id,
|
||||
trigger: trigger.as_str().to_string(),
|
||||
@@ -316,6 +335,7 @@ async fn sync_project_snapshot_async(
|
||||
}
|
||||
|
||||
let upload = upload_project_snapshot_diff(&session, &project_id, &diff).await;
|
||||
let pending_files = project_snapshot_pending_file_count(&diff, &upload.failures);
|
||||
let synced_files = build_project_snapshot_synced_files(&diff, &upload.uploaded_paths);
|
||||
let next_revision = previous.sync_revision.saturating_add(1);
|
||||
let synced_at_ms = u64::try_from(unix_millis()).unwrap_or(u64::MAX);
|
||||
@@ -325,6 +345,8 @@ async fn sync_project_snapshot_async(
|
||||
project_id: project_id.clone(),
|
||||
sync_revision: next_revision,
|
||||
synced_at_ms,
|
||||
project_name: project_name.clone(),
|
||||
pending_files: Some(pending_files),
|
||||
files: synced_files
|
||||
.iter()
|
||||
.map(|(relative_path, file)| {
|
||||
@@ -346,12 +368,14 @@ async fn sync_project_snapshot_async(
|
||||
user_id: session.user_id.clone(),
|
||||
sync_revision: next_revision,
|
||||
synced_at_ms,
|
||||
project_name,
|
||||
pending_files: Some(pending_files),
|
||||
files: synced_files,
|
||||
})?;
|
||||
|
||||
let status = if upload.failures.is_empty() {
|
||||
let status = if pending_files == 0 {
|
||||
"synced"
|
||||
} else if upload.uploaded_paths.is_empty() {
|
||||
} else if !upload.failures.is_empty() && upload.uploaded_paths.is_empty() {
|
||||
"failed"
|
||||
} else {
|
||||
"partial"
|
||||
@@ -381,7 +405,8 @@ async fn sync_project_snapshot_async(
|
||||
synced_at_ms,
|
||||
};
|
||||
app_log!(
|
||||
"project_snapshot.sync.completed trigger={} status={} revision={} uploaded={} skippedRemote={} deleted={} deferred={} failed={}",
|
||||
"project_snapshot.sync.completed projectId={} trigger={} status={} revision={} uploaded={} skippedRemote={} deleted={} deferred={} failed={} pending={}",
|
||||
report.project_id,
|
||||
report.trigger,
|
||||
report.status,
|
||||
report.sync_revision,
|
||||
@@ -389,7 +414,8 @@ async fn sync_project_snapshot_async(
|
||||
report.remote_skipped_files,
|
||||
report.deleted_files,
|
||||
report.deferred_files,
|
||||
report.failed_files.len()
|
||||
report.failed_files.len(),
|
||||
pending_files
|
||||
);
|
||||
Ok(report)
|
||||
}
|
||||
@@ -405,53 +431,39 @@ fn failure_views(skipped: &[ProjectSnapshotSkippedPath]) -> Vec<ProjectSnapshotF
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 从窗口 URL 读取项目路径。只有带 `projectPath` 的窗口才代表打开的项目。
|
||||
fn project_snapshot_pending_file_count(
|
||||
diff: &ProjectSnapshotDiff,
|
||||
failures: &[ProjectSnapshotUploadFailure],
|
||||
) -> u32 {
|
||||
let paths = diff
|
||||
.skipped
|
||||
.iter()
|
||||
.chain(&diff.deferred)
|
||||
.chain(&diff.pending)
|
||||
.map(|entry| entry.relative_path.as_str())
|
||||
.chain(failures.iter().map(|entry| entry.relative_path.as_str()))
|
||||
.collect::<BTreeSet<_>>();
|
||||
u32::try_from(paths.len()).unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
fn project_snapshot_manifest_needs_sync(
|
||||
previous: &ProjectSnapshotIndex,
|
||||
diff: &ProjectSnapshotDiff,
|
||||
project_name: &Option<String>,
|
||||
pending_files: u32,
|
||||
) -> bool {
|
||||
diff.has_changes()
|
||||
|| previous.project_name != *project_name
|
||||
|| previous.pending_files != Some(pending_files)
|
||||
}
|
||||
|
||||
/// 独立 supervisor-chat 窗口尚未登记时,从其 URL 读取项目路径。
|
||||
pub(crate) fn project_snapshot_project_path_from_url(url: &url::Url) -> Option<String> {
|
||||
url.query_pairs()
|
||||
.find_map(|(key, value)| (key == "projectPath").then(|| value.into_owned()))
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
}
|
||||
|
||||
fn open_project_snapshot_workspaces(app: &tauri::AppHandle) -> Vec<String> {
|
||||
let mut paths = BTreeSet::new();
|
||||
for window in app.webview_windows().into_values() {
|
||||
let Ok(url) = window.url() else {
|
||||
continue;
|
||||
};
|
||||
if let Some(project_path) = project_snapshot_project_path_from_url(&url) {
|
||||
paths.insert(project_path);
|
||||
}
|
||||
}
|
||||
paths.into_iter().collect()
|
||||
}
|
||||
|
||||
/// 工作区窗口关闭即视为项目关闭:立刻补一次同步。
|
||||
pub(crate) fn handle_project_snapshot_window_event(
|
||||
window: &tauri::Window,
|
||||
event: &tauri::WindowEvent,
|
||||
) {
|
||||
if !project_snapshot_sync_enabled() {
|
||||
return;
|
||||
}
|
||||
if !matches!(event, tauri::WindowEvent::CloseRequested { .. }) {
|
||||
return;
|
||||
}
|
||||
// `tauri::Window` 不暴露 WebView 地址,按标签取回对应的 WebView 窗口再读 URL。
|
||||
let Some(webview) = window.app_handle().get_webview_window(window.label()) else {
|
||||
return;
|
||||
};
|
||||
let Ok(url) = webview.url() else {
|
||||
return;
|
||||
};
|
||||
let Some(project_path) = project_snapshot_project_path_from_url(&url) else {
|
||||
return;
|
||||
};
|
||||
request_project_snapshot_sync(
|
||||
PathBuf::from(project_path),
|
||||
ProjectSnapshotSyncTrigger::ProjectClose,
|
||||
);
|
||||
}
|
||||
|
||||
/// 应用退出前等待在途同步收尾。
|
||||
///
|
||||
/// 退出时刻窗口已销毁,按窗口重新枚举项目只会得到空集,因此这里不重复发起同步:
|
||||
@@ -465,7 +477,7 @@ pub(crate) fn wait_for_project_snapshot_syncs_on_exit() {
|
||||
}
|
||||
}
|
||||
|
||||
/// 周期定时器:只为当前仍打开的项目触发,进程内项目集合由窗口 URL 决定。
|
||||
/// 周期定时器:只为当前窗口登记的项目触发,不扫描其它本地项目。
|
||||
pub(crate) fn spawn_project_snapshot_scheduler(app: tauri::AppHandle) {
|
||||
if !project_snapshot_sync_enabled() {
|
||||
app_log!("project_snapshot.scheduler.disabled");
|
||||
|
||||
@@ -52,6 +52,9 @@ pub(crate) fn scan_project_snapshot_files(
|
||||
let Ok(relative_path) = relative_project_path(root, &path) else {
|
||||
continue;
|
||||
};
|
||||
if should_skip_project_snapshot_path(&relative_path) {
|
||||
continue;
|
||||
}
|
||||
let metadata = match fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) => {
|
||||
@@ -62,14 +65,8 @@ pub(crate) fn scan_project_snapshot_files(
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if should_skip_project_snapshot_path(&relative_path) {
|
||||
continue;
|
||||
}
|
||||
if metadata.file_type().is_symlink() || windows_metadata_is_reparse_point(&metadata) {
|
||||
result.skipped.push(ProjectSnapshotSkippedPath {
|
||||
relative_path,
|
||||
reason: "符号链接或重解析点不参与项目快照".to_string(),
|
||||
});
|
||||
// 与凭据和构建缓存一样属于明确排除范围,不计入工程缺失数量。
|
||||
continue;
|
||||
}
|
||||
if metadata.is_dir() {
|
||||
|
||||
@@ -280,6 +280,28 @@ fn project_snapshot_periodic_trigger_yields_while_a_sync_is_in_flight() {
|
||||
assert!(try_run_project_snapshot_sync(key, || ()).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_snapshot_exit_wait_includes_scheduled_tasks_waiting_for_the_project_lock() {
|
||||
let key = "snapshot-close-enqueue-exit-test";
|
||||
let lock = project_snapshot_project_lock(key);
|
||||
let held = lock.lock().unwrap();
|
||||
let completed = Arc::new(AtomicUsize::new(0));
|
||||
let observed = completed.clone();
|
||||
let task = spawn_project_snapshot_sync_task(move || {
|
||||
run_project_snapshot_sync(key, || {
|
||||
observed.fetch_add(1, Ordering::SeqCst);
|
||||
});
|
||||
})
|
||||
.expect("enqueue closing sync");
|
||||
// 线程尚未拿到项目锁时,退出也必须等待;不能等开始上传才计入。
|
||||
assert!(!wait_for_project_snapshot_syncs(Duration::from_millis(5)));
|
||||
assert_eq!(completed.load(Ordering::SeqCst), 0);
|
||||
drop(held);
|
||||
task.join().expect("closing sync completed");
|
||||
assert_eq!(completed.load(Ordering::SeqCst), 1);
|
||||
assert!(wait_for_project_snapshot_syncs(Duration::from_secs(2)));
|
||||
}
|
||||
|
||||
fn read_http_request_with_body(stream: &mut TcpStream) -> String {
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
@@ -518,7 +540,7 @@ fn project_snapshot_upload_stops_after_a_deterministic_authentication_failure()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_snapshot_project_path_is_read_from_window_urls_only() {
|
||||
fn project_snapshot_independent_window_url_supplies_a_fallback_project() {
|
||||
let url = url::Url::parse("tauri://localhost/index.html?main&projectPath=C%3A%5Cgames%5Cdemo")
|
||||
.expect("parse fixture url");
|
||||
assert_eq!(
|
||||
@@ -529,6 +551,148 @@ fn project_snapshot_project_path_is_read_from_window_urls_only() {
|
||||
assert_eq!(project_snapshot_project_path_from_url(&launcher), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_snapshot_workspace_lifecycle_tracks_the_single_client_window() {
|
||||
let mut registry = ProjectSnapshotWorkspaces::default();
|
||||
let first = "/projects/first".to_string();
|
||||
let second = "/projects/second".to_string();
|
||||
assert_eq!(registry.project_for_window("client", None), None);
|
||||
assert_eq!(
|
||||
registry.set_project("client", Some(first.clone())),
|
||||
vec![(
|
||||
PathBuf::from(&first),
|
||||
ProjectSnapshotSyncTrigger::ProjectOpen
|
||||
)]
|
||||
);
|
||||
assert_eq!(
|
||||
registry.project_for_window("client", None),
|
||||
Some(first.clone())
|
||||
);
|
||||
assert!(registry
|
||||
.set_project("client", Some(first.clone()))
|
||||
.is_empty());
|
||||
assert_eq!(
|
||||
registry.set_project("client", Some(second.clone())),
|
||||
vec![
|
||||
(
|
||||
PathBuf::from(&first),
|
||||
ProjectSnapshotSyncTrigger::ProjectClose
|
||||
),
|
||||
(
|
||||
PathBuf::from(&second),
|
||||
ProjectSnapshotSyncTrigger::ProjectOpen
|
||||
),
|
||||
]
|
||||
);
|
||||
registry.set_project("other", Some(first.clone()));
|
||||
assert_eq!(
|
||||
registry.set_project("client", None),
|
||||
vec![(
|
||||
PathBuf::from(&second),
|
||||
ProjectSnapshotSyncTrigger::ProjectClose
|
||||
)]
|
||||
);
|
||||
assert_eq!(registry.project_for_window("client", Some(second)), None);
|
||||
assert_eq!(registry.project_for_window("other", None), Some(first));
|
||||
assert!(registry.set_project("client", None).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_snapshot_manifest_metadata_changes_sync_without_content_changes() {
|
||||
let root = fixture_root();
|
||||
write_fixture_file(root.path(), "game/empty.txt", b"");
|
||||
let initial = compute_project_snapshot_diff(
|
||||
&scan_fixture(root.path()),
|
||||
&BTreeMap::new(),
|
||||
PROJECT_SNAPSHOT_MAX_SYNC_BYTES,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(initial.uploads[0].size_bytes, 0);
|
||||
let mut previous = empty_project_snapshot_index("project-1", "user-1");
|
||||
previous.files = initial.current;
|
||||
let mut unchanged = compute_project_snapshot_diff(
|
||||
&scan_fixture(root.path()),
|
||||
&previous.files,
|
||||
PROJECT_SNAPSHOT_MAX_SYNC_BYTES,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!unchanged.has_changes());
|
||||
let name = Some("完整工程".to_string());
|
||||
assert!(project_snapshot_manifest_needs_sync(
|
||||
&previous, &unchanged, &name, 0
|
||||
));
|
||||
previous.project_name = name.clone();
|
||||
previous.pending_files = Some(0);
|
||||
assert!(!project_snapshot_manifest_needs_sync(
|
||||
&previous, &unchanged, &name, 0
|
||||
));
|
||||
assert!(project_snapshot_manifest_needs_sync(
|
||||
&previous,
|
||||
&unchanged,
|
||||
&Some("已改名".to_string()),
|
||||
0
|
||||
));
|
||||
|
||||
unchanged.skipped.push(ProjectSnapshotSkippedPath {
|
||||
relative_path: "assets/large.bin".into(),
|
||||
reason: "单文件超限".into(),
|
||||
});
|
||||
let pending = project_snapshot_pending_file_count(&unchanged, &[]);
|
||||
assert_eq!(pending, 1);
|
||||
assert!(project_snapshot_manifest_needs_sync(
|
||||
&previous, &unchanged, &name, pending
|
||||
));
|
||||
previous.pending_files = Some(pending);
|
||||
assert!(!project_snapshot_manifest_needs_sync(
|
||||
&previous, &unchanged, &name, pending
|
||||
));
|
||||
unchanged.skipped.clear();
|
||||
assert!(project_snapshot_manifest_needs_sync(
|
||||
&previous,
|
||||
&unchanged,
|
||||
&name,
|
||||
project_snapshot_pending_file_count(&unchanged, &[])
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_snapshot_pending_files_include_every_unsynced_path_once() {
|
||||
let skipped = |path: &str| ProjectSnapshotSkippedPath {
|
||||
relative_path: path.into(),
|
||||
reason: "暂未同步".into(),
|
||||
};
|
||||
let diff = ProjectSnapshotDiff {
|
||||
skipped: vec![skipped("assets/large.bin")],
|
||||
deferred: vec![skipped("assets/later.png")],
|
||||
pending: vec![skipped("game/changing.js")],
|
||||
..Default::default()
|
||||
};
|
||||
let failures = vec![
|
||||
ProjectSnapshotUploadFailure {
|
||||
relative_path: "assets/failed.png".into(),
|
||||
code: "transport-failed".into(),
|
||||
detail: "失败".into(),
|
||||
},
|
||||
ProjectSnapshotUploadFailure {
|
||||
relative_path: "game/changing.js".into(),
|
||||
code: "file-changed".into(),
|
||||
detail: "变化".into(),
|
||||
},
|
||||
];
|
||||
assert_eq!(project_snapshot_pending_file_count(&diff, &failures), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_snapshot_legacy_index_keeps_completeness_unknown() {
|
||||
let index: ProjectSnapshotIndex = serde_json::from_value(serde_json::json!({
|
||||
"schemaVersion": 1, "projectId": "project-1", "userId": "user-1",
|
||||
"syncRevision": 1, "syncedAtMs": 1, "files": {}
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(index.project_name, None);
|
||||
assert_eq!(index.pending_files, None);
|
||||
}
|
||||
|
||||
/// 真实链路冒烟:客户端差异引擎 → 本地 api-server → 真实 OSS。
|
||||
///
|
||||
/// 默认忽略;需要显式提供目标项目与登录态:
|
||||
|
||||
@@ -23,14 +23,7 @@ import {
|
||||
normalizeAuthPhoneInput,
|
||||
sendClientPhoneLoginCode,
|
||||
} from '../services/clientAuth';
|
||||
import {
|
||||
type ClientServerPreset,
|
||||
type ClientServerSelection,
|
||||
getClientServerBaseUrl,
|
||||
getClientServerSelection,
|
||||
normalizeClientServerBaseUrl,
|
||||
setClientServerSelection,
|
||||
} from '../services/clientHttp';
|
||||
import { getClientServerBaseUrl } from '../services/clientHttp';
|
||||
import {
|
||||
captureClientError,
|
||||
installWebviewLogBridge,
|
||||
@@ -158,13 +151,6 @@ export function AuthenticatedClient({
|
||||
const [loginBusy, setLoginBusy] = useState(false);
|
||||
const [codeBusy, setCodeBusy] = useState(false);
|
||||
const [codeCooldownSeconds, setCodeCooldownSeconds] = useState(0);
|
||||
const initialServerSelection = getClientServerSelection();
|
||||
const [serverSelection, setServerSelection] = useState<ClientServerSelection>(
|
||||
initialServerSelection,
|
||||
);
|
||||
const [customServerUrl, setCustomServerUrl] = useState(
|
||||
initialServerSelection.customBaseUrl,
|
||||
);
|
||||
useEffect(() => {
|
||||
const uninstallWebviewLogBridge = installWebviewLogBridge();
|
||||
const handleError = (event: ErrorEvent) => {
|
||||
@@ -184,37 +170,6 @@ export function AuthenticatedClient({
|
||||
};
|
||||
}, []);
|
||||
|
||||
function persistServerSelection() {
|
||||
try {
|
||||
const next = setClientServerSelection({
|
||||
preset: serverSelection.preset,
|
||||
customBaseUrl: customServerUrl,
|
||||
});
|
||||
setServerSelection(next);
|
||||
return next;
|
||||
} catch (error) {
|
||||
void captureClientError(error, {
|
||||
source: 'auth-hydrate',
|
||||
action: 'restore-session',
|
||||
});
|
||||
setLoginStatus(error instanceof Error ? error.message : String(error));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function handleServerPresetChange(preset: ClientServerPreset) {
|
||||
if (preset === 'custom') {
|
||||
setServerSelection((current) => ({ ...current, preset }));
|
||||
return;
|
||||
}
|
||||
const next = setClientServerSelection({
|
||||
preset,
|
||||
customBaseUrl: customServerUrl,
|
||||
});
|
||||
setServerSelection(next);
|
||||
setLoginStatus(`已选择 ${preset} 服务器`);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
async function hydrateAuth() {
|
||||
@@ -430,11 +385,7 @@ export function AuthenticatedClient({
|
||||
if (codeBusy || codeCooldownSeconds > 0) {
|
||||
return;
|
||||
}
|
||||
const persistedSelection = persistServerSelection();
|
||||
if (!persistedSelection) {
|
||||
return;
|
||||
}
|
||||
const apiBaseUrl = getClientServerBaseUrl(persistedSelection);
|
||||
const apiBaseUrl = getClientServerBaseUrl();
|
||||
const normalizedPhone = normalizeAuthPhoneInput(phone);
|
||||
if (!normalizedPhone) {
|
||||
setLoginStatus('请输入手机号');
|
||||
@@ -479,11 +430,7 @@ export function AuthenticatedClient({
|
||||
setLoginStatus('请输入密码');
|
||||
return;
|
||||
}
|
||||
const persistedSelection = persistServerSelection();
|
||||
if (!persistedSelection) {
|
||||
return;
|
||||
}
|
||||
const loginApiBaseUrl = getClientServerBaseUrl(persistedSelection);
|
||||
const loginApiBaseUrl = getClientServerBaseUrl();
|
||||
const loginAttempt = (loginAttemptRef.current += 1);
|
||||
setLoginBusy(true);
|
||||
setLoginStatus('正在登录');
|
||||
@@ -635,50 +582,6 @@ export function AuthenticatedClient({
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
<label>
|
||||
服务器
|
||||
<select
|
||||
aria-label="服务器"
|
||||
disabled={loginBusy || codeBusy}
|
||||
value={serverSelection.preset}
|
||||
onChange={(event) =>
|
||||
handleServerPresetChange(
|
||||
event.currentTarget.value as ClientServerPreset,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="release">release</option>
|
||||
<option value="dev">dev</option>
|
||||
<option value="custom">custom</option>
|
||||
</select>
|
||||
</label>
|
||||
{serverSelection.preset === 'custom' ? (
|
||||
<label>
|
||||
自定义服务器地址
|
||||
<input
|
||||
aria-label="自定义服务器地址"
|
||||
disabled={loginBusy || codeBusy}
|
||||
inputMode="url"
|
||||
placeholder="https://example.com"
|
||||
value={customServerUrl}
|
||||
onChange={(event) =>
|
||||
setCustomServerUrl(event.currentTarget.value)
|
||||
}
|
||||
onBlur={() => {
|
||||
if (customServerUrl.trim()) {
|
||||
try {
|
||||
normalizeClientServerBaseUrl(customServerUrl);
|
||||
persistServerSelection();
|
||||
} catch (error) {
|
||||
setLoginStatus(
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
) : null}
|
||||
<div className="client-auth-tabs" role="group" aria-label="登录方式">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -49,6 +49,7 @@ import {
|
||||
DESIGN_ARTIFACTS_BUILD_PROMPT,
|
||||
useHomeProjectCreation,
|
||||
} from './useHomeProjectCreation';
|
||||
import { useProjectSnapshotWorkspace } from './useProjectSnapshotWorkspace';
|
||||
import { useRecentProjects } from './useRecentProjects';
|
||||
|
||||
export function WorkspaceLauncherShell({
|
||||
@@ -115,6 +116,11 @@ export function WorkspaceLauncherShell({
|
||||
homeCreationBusy,
|
||||
homeCreationRecoverableProjectPath,
|
||||
} = homeProject;
|
||||
useProjectSnapshotWorkspace(
|
||||
launcherView === 'project-development'
|
||||
? (currentProjectContext?.projectPath ?? null)
|
||||
: null,
|
||||
);
|
||||
const directInvoke = resolveTauriInvoke();
|
||||
const { activeTurns, snapshotReadFailed } = useDirectActiveTurns({
|
||||
invoke: directInvoke,
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
import { resolveTauriInvoke } from '../../app/tauri';
|
||||
import { projectSnapshotWorkspaceRegistration } from '../../services/projectSnapshotWorkspace';
|
||||
|
||||
export function useProjectSnapshotWorkspace(projectPath: string | null) {
|
||||
const invoke = resolveTauriInvoke();
|
||||
const registration = invoke
|
||||
? projectSnapshotWorkspaceRegistration(invoke)
|
||||
: null;
|
||||
|
||||
useEffect(() => registration?.acquire(), [registration]);
|
||||
useEffect(() => {
|
||||
void registration?.setProject(projectPath);
|
||||
}, [projectPath, registration]);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user