Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 15774a1c02 |
@@ -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;
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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。
|
||||
///
|
||||
/// 默认忽略;需要显式提供目标项目与登录态:
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
type WorkspaceInvoke = (
|
||||
command: string,
|
||||
args?: Record<string, unknown>,
|
||||
) => Promise<unknown>;
|
||||
|
||||
/** 同一 WebView 的登记串行提交;旧请求完成后不能覆盖更新的工程状态。 */
|
||||
export function createProjectSnapshotWorkspaceRegistration(
|
||||
invoke: WorkspaceInvoke,
|
||||
) {
|
||||
let requestedPath: string | null | undefined;
|
||||
let revision = 0;
|
||||
let ownerRevision = 0;
|
||||
let queue = Promise.resolve();
|
||||
|
||||
function setProject(projectPath: string | null) {
|
||||
if (requestedPath === projectPath) return queue;
|
||||
requestedPath = projectPath;
|
||||
const requestRevision = ++revision;
|
||||
queue = queue.then(async () => {
|
||||
try {
|
||||
await invoke('set_active_project_snapshot_workspace', { projectPath });
|
||||
} catch {
|
||||
// 失败不能被记作已登记;下一次相同路径登记仍可重新提交。
|
||||
if (revision === requestRevision) requestedPath = undefined;
|
||||
try {
|
||||
await invoke('append_application_log', {
|
||||
level: 'error',
|
||||
source: 'project-snapshot',
|
||||
message: 'project_snapshot.workspace.registration.failed',
|
||||
});
|
||||
} catch {
|
||||
// 原生桥本身不可用时也不阻断项目创作。
|
||||
}
|
||||
}
|
||||
});
|
||||
return queue;
|
||||
}
|
||||
|
||||
function acquire() {
|
||||
const owner = ++ownerRevision;
|
||||
return () => {
|
||||
// StrictMode 的同轮卸载/重挂以及工作台替换不代表工程真的关闭。
|
||||
queueMicrotask(() => {
|
||||
if (owner === ownerRevision) void setProject(null);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
return { setProject, acquire };
|
||||
}
|
||||
|
||||
const registrations = new WeakMap<
|
||||
WorkspaceInvoke,
|
||||
ReturnType<typeof createProjectSnapshotWorkspaceRegistration>
|
||||
>();
|
||||
|
||||
export function projectSnapshotWorkspaceRegistration(invoke: WorkspaceInvoke) {
|
||||
let registration = registrations.get(invoke);
|
||||
if (!registration) {
|
||||
registration = createProjectSnapshotWorkspaceRegistration(invoke);
|
||||
registrations.set(invoke, registration);
|
||||
}
|
||||
return registration;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/** @vitest-environment jsdom */
|
||||
import { act, cleanup, render, waitFor } from '@testing-library/react';
|
||||
import React, { StrictMode } from 'react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useProjectSnapshotWorkspace } from '../src/features/app-shell/useProjectSnapshotWorkspace';
|
||||
import { createProjectSnapshotWorkspaceRegistration } from '../src/services/projectSnapshotWorkspace';
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
delete window.__TAURI__;
|
||||
});
|
||||
|
||||
describe('项目快照窗口登记', () => {
|
||||
it('在无 projectPath URL 的单窗口登记、切换、离开,StrictMode 不误关项目', async () => {
|
||||
const invoke = vi.fn(async () => undefined);
|
||||
window.__TAURI__ = { core: { invoke: invoke as never } };
|
||||
function Workspace({ path }: { path: string | null }) {
|
||||
useProjectSnapshotWorkspace(path);
|
||||
return null;
|
||||
}
|
||||
const view = (path: string | null) => (
|
||||
<StrictMode>
|
||||
<Workspace path={path} />
|
||||
</StrictMode>
|
||||
);
|
||||
expect(new URL(window.location.href).searchParams.has('projectPath')).toBe(
|
||||
false,
|
||||
);
|
||||
const rendered = render(view('/projects/first'));
|
||||
await waitFor(() => expect(invoke).toHaveBeenCalledTimes(1));
|
||||
expect(invoke).toHaveBeenLastCalledWith(
|
||||
'set_active_project_snapshot_workspace',
|
||||
{ projectPath: '/projects/first' },
|
||||
);
|
||||
rendered.rerender(view('/projects/first'));
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(invoke).toHaveBeenCalledTimes(1);
|
||||
rendered.rerender(view('/projects/second'));
|
||||
await waitFor(() => expect(invoke).toHaveBeenCalledTimes(2));
|
||||
expect(invoke).toHaveBeenLastCalledWith(
|
||||
'set_active_project_snapshot_workspace',
|
||||
{ projectPath: '/projects/second' },
|
||||
);
|
||||
rendered.rerender(view(null));
|
||||
await waitFor(() => expect(invoke).toHaveBeenCalledTimes(3));
|
||||
expect(invoke).toHaveBeenLastCalledWith(
|
||||
'set_active_project_snapshot_workspace',
|
||||
{ projectPath: null },
|
||||
);
|
||||
rendered.rerender(view('/projects/third'));
|
||||
await waitFor(() => expect(invoke).toHaveBeenCalledTimes(4));
|
||||
rendered.unmount();
|
||||
await waitFor(() => expect(invoke).toHaveBeenCalledTimes(5));
|
||||
expect(invoke).toHaveBeenLastCalledWith(
|
||||
'set_active_project_snapshot_workspace',
|
||||
{ projectPath: null },
|
||||
);
|
||||
});
|
||||
|
||||
it('原生登记未完成时顺序提交后续切换,不让迟到回包覆盖新项目', async () => {
|
||||
let release!: () => void;
|
||||
const first = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const invoke = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => first)
|
||||
.mockResolvedValue(undefined);
|
||||
const registration = createProjectSnapshotWorkspaceRegistration(invoke);
|
||||
void registration.setProject('/projects/first');
|
||||
void registration.setProject('/projects/second');
|
||||
const idle = registration.setProject(null);
|
||||
await Promise.resolve();
|
||||
expect(invoke).toHaveBeenCalledTimes(1);
|
||||
release();
|
||||
await idle;
|
||||
expect(invoke.mock.calls.map((call) => call[1]?.projectPath)).toEqual([
|
||||
'/projects/first',
|
||||
'/projects/second',
|
||||
null,
|
||||
]);
|
||||
});
|
||||
|
||||
it('失败写固定诊断并允许再次登记,不能泄漏原生错误中的路径和凭据', async () => {
|
||||
const invoke = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error('C:\\private\\project token=secret'))
|
||||
.mockResolvedValue(undefined);
|
||||
const registration = createProjectSnapshotWorkspaceRegistration(invoke);
|
||||
await expect(
|
||||
registration.setProject('/projects/first'),
|
||||
).resolves.toBeUndefined();
|
||||
expect(invoke).toHaveBeenLastCalledWith('append_application_log', {
|
||||
level: 'error',
|
||||
source: 'project-snapshot',
|
||||
message: 'project_snapshot.workspace.registration.failed',
|
||||
});
|
||||
await registration.setProject('/projects/first');
|
||||
expect(invoke).toHaveBeenCalledTimes(3);
|
||||
expect(invoke).toHaveBeenLastCalledWith(
|
||||
'set_active_project_snapshot_workspace',
|
||||
{ projectPath: '/projects/first' },
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -108,6 +108,8 @@ function installInvokeMock() {
|
||||
return null;
|
||||
case 'list_game_creator_direct_active_turns':
|
||||
return [];
|
||||
case 'set_active_project_snapshot_workspace':
|
||||
return undefined;
|
||||
case 'read_project_permission_policy':
|
||||
return {
|
||||
projectPath: PROJECT_PATH,
|
||||
@@ -204,6 +206,30 @@ describe('清单快照被拒收时的用户可见性与恢复', () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('真实启动器打开项目后登记原生快照工作区,返回首页补交关闭', async () => {
|
||||
const invoke = installInvokeMock();
|
||||
await openProjectThroughLauncher();
|
||||
await waitFor(() =>
|
||||
expect(invoke).toHaveBeenCalledWith(
|
||||
'set_active_project_snapshot_workspace',
|
||||
{ projectPath: PROJECT_PATH },
|
||||
),
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: '首页' }));
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
invoke.mock.calls
|
||||
.filter(
|
||||
([command]) => command === 'set_active_project_snapshot_workspace',
|
||||
)
|
||||
.at(-1),
|
||||
).toEqual([
|
||||
'set_active_project_snapshot_workspace',
|
||||
{ projectPath: null },
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('shows a rejection notice, rereads disk truth and adopts the new asset', async () => {
|
||||
const invoke = installInvokeMock();
|
||||
await openProjectThroughLauncher();
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# 项目自动上传与后台工程下载实施计划
|
||||
|
||||
| 字段 | 值 |
|
||||
| --- | --- |
|
||||
| Milestone | `docs/project-memory/plans/【里程碑】项目自动上传与后台工程下载-2026-09-19.md` |
|
||||
| Status | implemented-awaiting-runtime-validation |
|
||||
| Owner | 当前任务 Agent |
|
||||
|
||||
## 修改边界
|
||||
|
||||
- 客户端 project_snapshot 与实际窗口生命周期、相关定向测试。
|
||||
- shared-contracts 快照清单及后台 DTO、platform-oss 的受控清单枚举、api-server 管理员列表与 ZIP 下载、后台权限映射。
|
||||
- api-server 快照存储配置解析:默认目标与素材 bucket 分离,只有凭据可回退;不变更部署配置或搬迁对象。
|
||||
- admin-web 项目列表、现有路由/导航/API client 与相应测试。
|
||||
- 主规范、运维说明及必要共享约定。不修改 SpacetimeDB、External API、用户会话权威或线上配置。
|
||||
|
||||
## 实现顺序
|
||||
|
||||
1. 评审主规范与本里程碑,复现客户端项目枚举故障。
|
||||
2. 并行实现后台列表/ZIP、后台 UI;客户端只修已证实上传缺陷并补清单元数据。
|
||||
3. 集成契约、运行定向测试和 UI smoke,核查真实清单可还原目录;按证据更新验收状态。
|
||||
|
||||
## 验证命令
|
||||
|
||||
- `cargo test --locked -p platform-oss`、`cargo test --locked -p api-server project_snapshot`、`cargo test --locked -p shared-contracts`(server-rs)。
|
||||
- `cargo test --locked --manifest-path apps/ai-game-creator-shell/src-tauri/Cargo.toml project_snapshot`。
|
||||
- `npm run admin-web:typecheck`、`npm run admin-web:build`、后台相关 Vitest。
|
||||
- `npm run check:encoding`、`npm run check:doc-index`、`git diff --check`。
|
||||
|
||||
## 风险与回滚
|
||||
|
||||
旧清单无完整性声明,只能标记未知;完整工程含项目源码、素材和配置,排除依赖/构建缓存、凭据、会话与运行日志。下载失败不修改 OSS 或清单。本轮按用户授权提交推送,不部署;代码可独立回退。
|
||||
@@ -0,0 +1,55 @@
|
||||
# 项目自动上传与后台工程下载
|
||||
|
||||
| 字段 | 值 |
|
||||
| --- | --- |
|
||||
| Version | 1.0 |
|
||||
| Status | implemented-awaiting-runtime-validation |
|
||||
| Date | 2026-09-19 |
|
||||
| Parent Spec | `docs/technical/【技术方案】AI游戏创作智能体App实施计划-2026-06-24.md` 的项目快照上传与后台工程下载合同 |
|
||||
|
||||
## 目标与范围
|
||||
|
||||
修复实际项目自动上传的已证实故障,并让有权限的后台管理员按项目查看远端快照、一键下载按原始目录还原的工程 ZIP。
|
||||
|
||||
## 不在范围内
|
||||
|
||||
客户端上传 UI、跨设备恢复、版本历史、数据库 schema、线上部署、自动补传全部未打开项目。
|
||||
|
||||
## 依赖与前置条件
|
||||
|
||||
延续现有私有 OSS 项目快照、平台会话与后台权限。真实 bucket 已只读确认只有两份历史模板清单;上传根因必须经确定性复现后修正。
|
||||
|
||||
## 验收标准
|
||||
|
||||
- [ ] 正式项目窗口可被同步调度识别;周期与关闭触发保持有界,失败有项目级诊断。
|
||||
- [ ] 未单独配置快照目标时仍使用 agc-dev,只复用资源存储凭据;显式快照目标保持有效,不迁移现存对象。
|
||||
- [ ] 后台列表显示项目名/ID、用户 ID、同步时间、文件数、体积和完整性,支持刷新与分页。
|
||||
- [ ] ZIP 按清单还原相对路径;不含对象存储摘要目录;空文件可上传与导出。
|
||||
- [ ] 清单名称/完整性变化在无内容差异时也提交,partial 可恢复 ready,历史缺字段不冒充 ready。
|
||||
- [ ] 缺失、损坏、越界路径和非完整清单失败关闭;历史未声明完整性的清单明确标记,允许导出已有文件但不称为完整工程。
|
||||
- [ ] 无后台权限不能读取项目或 ZIP;不泄漏凭据;ZIP 构建有体积、并发和临时文件清理边界。
|
||||
- [ ] 定向 Rust 测试、后台类型检查/构建、UI smoke、编码、文档索引和 diff 检查完成,运行时证据与未验证部分分别列出。
|
||||
|
||||
## 证据要求
|
||||
|
||||
自动化覆盖窗口身份、上传零字节、清单统计、目录还原、路径与校验和校验、后台路由权限。运行时优先只读现有 OSS 清单;测试不上传真实用户工程、不修改线上数据。
|
||||
|
||||
## 已取得证据
|
||||
|
||||
| 层次 | 结果 |
|
||||
| --- | --- |
|
||||
| 客户端 Rust `project_snapshot` | 22 通过、1 忽略(写入式真实上传 smoke 未运行);含排队退出等待回归 |
|
||||
| 客户端前端生命周期与启动器 | 3 文件、10 测试通过;完整 AGC typecheck、skill-pack、check-config 通过 |
|
||||
| 后台页面、API client、路由与样式 | 44 测试通过;admin-web typecheck/build 通过 |
|
||||
| 后端快照与权限 | 14 定向测试通过;未认证路由矩阵与页签映射 2 测试通过 |
|
||||
| 默认存储目标 | 真实 AppConfig::from_env 配置回归 1 通过 |
|
||||
| OSS 存储层 | 全量 55 测试通过,含签名、特殊字符路径、读取上限与零字节 |
|
||||
| 真实 OSS 只读导出 | `project_snapshots_live_readonly_list_and_archive` 通过;limit=1 分页、2 清单、12 文件、73,424 字节,ZIP 解压路径/长度/摘要全匹配、临时文件清理通过;两份均为历史 unverified |
|
||||
| 浏览器 smoke | 模拟 API 的 1280 桌面与 390 窄屏通过;下载按钮可见,无整页横向溢出;中文 ZIP 文件名、Authorization、409 错误呈现通过 |
|
||||
| 通用门禁 | 编码、文档索引、production-ops、Rust 格式、客户端 Prettier 与 diff 检查通过 |
|
||||
|
||||
## 剩余验证与环境边界
|
||||
|
||||
`npm run dev:api-server -- --api-port 4198 --bgfilter-worker-port 4199 --api-timeout-seconds 600` 编译成功,但当前工作区配置的本地数据库 `xushi-p4wfr` 在 `127.0.0.1:3101` 返回 404,启动认证投影无法完成,故 `/healthz` 及完整 HTTP smoke 未通过。仅本任务启动的 API/worker 已停止;没有清库、迁移数据库、改 `.env` 或替换其它项目的验证目标。
|
||||
|
||||
尚未替换安装版、构建新客户端发布包或部署;提交推送按用户本轮授权执行。当前条款已有上述自动化与只读存储证据,最终验收仍等待当前工作区数据库就绪后的 HTTP 联调,以及新客户端的隔离实机自动上传验证;完成后再关闭里程碑并清理两份计划。
|
||||
@@ -1,5 +1,11 @@
|
||||
# 踩坑与排障记录
|
||||
|
||||
## AGC 自动同步必须绑定真实项目生命周期
|
||||
|
||||
- 正式客户端在单窗口中用 React 状态打开/切换工程,窗口 URL 不代表当前工程。原生后台同步应读取由当前窗口显式登记的活动工程;首次打开、离开、切换、关窗及退出等待分别验证,不能只用携带 `projectPath` 的独立测试窗口证明正式入口可用。
|
||||
- 增量文件没有变化不等于远端清单没有变化。项目名和完整性元数据也参与提交判据,避免临时跳过恢复后永久停留在 partial,或新出现超限文件后仍显示 ready。历史清单缺少完整性字段属于未知,不能默认成完整。
|
||||
- ZIP 导出按一次冻结清单恢复相对路径并逐文件核验;直接下载内容寻址的 OSS 目录不能得到可用工程。源码/素材归档不包含依赖缓存、凭据和 AGC 对话运行状态。
|
||||
|
||||
## 2026-09-19 资源 kind 词汇收敛后,前端判据与 fixture 必须一起按 canonical 成员重写
|
||||
|
||||
- **现象**:工具栏入口的 `assetKind` 换成共享 `GameCreationAppAssetKind`(图集从平台词 `art-spritesheet` 改成 `icon-spritesheet`)后,「图集不接受用户参考」的判据仍写在旧的 `['art-spritesheet']` 字符串清单里,判据恒假:生成面板重新给图集渲染参考图选择器,原生提交再按合同显式拒绝多余参考。
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user