perf(user): render cloud pages on first paint

go
codex 4 weeks ago
parent cee8b9a1f5
commit c46203afe9

@ -13,6 +13,8 @@ use App\Services\Cloud\CloudInstancePageService;
use App\Services\Cloud\CloudInvoiceDetailPageService;
use App\Services\Cloud\CloudInvoicePageService;
use App\Services\Cloud\CloudUserIsoFeature;
use App\Services\Cloud\CloudUserIsoService;
use App\Services\Cloud\CloudUserPageView;
use App\Services\Cloud\CloudVpcFeature;
use App\Services\Cloud\CloudVpcService;
use App\Services\UserDrawerService;
@ -136,11 +138,13 @@ final class CloudPageController
}
$defaultLineId = $defaultLineId ?: $firstLineId;
$defaultOfferId = 0;
$defaultOffer = null;
foreach ($offers as $offer) {
if ((int) $offer['region_id'] === $defaultRegionId
&& (int) $offer['line_id'] === $defaultLineId
&& $offer['sellable'] === true) {
$defaultOfferId = (int) $offer['id'];
$defaultOffer = $offer;
break;
}
}
@ -169,6 +173,11 @@ final class CloudPageController
'cloud_deploy_default_region_id' => $defaultRegionId,
'cloud_deploy_default_line_id' => $defaultLineId,
'cloud_deploy_default_offer_id' => $defaultOfferId,
'cloud_deploy_price' => $defaultOffer === null ? ''
: '$' . number_format((float) $defaultOffer['price'], 2, '.', '') . ' USD',
'cloud_deploy_backup_price' => $defaultOffer === null ? ''
: '$' . number_format((float) $defaultOffer['backup_price'], 2, '.', '') . ' USD',
'cloud_deploy_snapshot' => $cloudSnapshot,
'cloud_deploy_catalog_unavailable' => $catalogUnavailable,
'cloud_deploy_bootstrap_json' => $this->safeJson($payload),
]);
@ -188,6 +197,7 @@ final class CloudPageController
$payload['user'] = $this->userBootstrap($user, $actor);
return $this->render($response, 'backups', '云备份', '', '', [
'cloud_backup_view' => CloudUserPageView::backups($payload),
'cloud_backup_bootstrap_json' => $this->safeJson($payload),
]);
}
@ -211,7 +221,8 @@ final class CloudPageController
'云快照',
'',
'',
['cloud_snapshot_bootstrap_json' => $this->safeJson($payload)]
['cloud_snapshot_bootstrap_json' => $this->safeJson($payload),
'cloud_snapshot_view' => CloudUserPageView::cloudSnapshots($payload)]
);
}
@ -223,8 +234,11 @@ final class CloudPageController
)->withStatus(302);
}
$actor = CloudAccess::actor(false);
$user = $request->getAttribute('auth_user') ?? Auth::getUser();
$payload = CloudVpcService::library($actor);
$payload['user'] = $this->userBootstrap($user, $actor);
return $this->render($response, 'vpcs', 'VPC 私网', '', '', [
'cloud_vpc_view' => CloudUserPageView::vpcs($payload, $request->getQueryParams()),
'cloud_vpc_bootstrap_json' => $this->safeJson($payload),
]);
}
@ -234,7 +248,15 @@ final class CloudPageController
if (!CloudUserIsoFeature::enabled()) {
return $response->withHeader('Location', '/user/cloud/instances')->withStatus(302);
}
return $this->render($response, 'isos', 'ISO 镜像');
$actor = CloudAccess::actor(false);
$user = $request->getAttribute('auth_user') ?? Auth::getUser();
$payload = CloudUserIsoService::listing((int) $actor['user_id']);
$payload['can_import'] = (int) $user->enable === 1;
$payload['user'] = $this->userBootstrap($user, $actor);
return $this->render($response, 'isos', 'ISO 镜像', '', '', [
'cloud_iso_view' => CloudUserPageView::isos($payload),
'cloud_iso_bootstrap_json' => $this->safeJson($payload),
]);
}
public function sshKeys($request, $response, $args)
@ -354,6 +376,16 @@ final class CloudPageController
{
$smarty = View::getSmarty('venix');
$smarty->assign('cloud_page', $page);
$smarty->assign('cloud_page_module', [
'instances' => 'instances', 'detail' => 'detail', 'deploy' => 'deploy',
'backups' => 'backups', 'cloud-snapshots' => 'cloud-snapshots',
'vpcs' => 'vpcs', 'isos' => 'iso-images', 'keys' => 'ssh-keys',
'invoices' => 'invoices', 'invoice-detail' => 'invoice-detail',
'reinstall' => 'reinstall',
][$page] ?? '');
$smarty->assign('cloud_uses_runtime', in_array($page, [
'detail', 'deploy', 'backups', 'cloud-snapshots', 'vpcs', 'isos', 'reinstall',
], true));
$smarty->assign('cloud_title', $title);
$smarty->assign('cloud_vm_id', $vmId);
$smarty->assign('cloud_invoice_id', $invoiceId);
@ -391,11 +423,19 @@ final class CloudPageController
$smarty->assign('cloud_deploy_default_region_id', 0);
$smarty->assign('cloud_deploy_default_line_id', 0);
$smarty->assign('cloud_deploy_default_offer_id', 0);
$smarty->assign('cloud_deploy_price', '');
$smarty->assign('cloud_deploy_backup_price', '');
$smarty->assign('cloud_deploy_snapshot', null);
$smarty->assign('cloud_deploy_catalog_unavailable', false);
$smarty->assign('cloud_deploy_bootstrap_json', '{}');
$smarty->assign('cloud_backup_bootstrap_json', '{}');
$smarty->assign('cloud_backup_view', CloudUserPageView::backups([]));
$smarty->assign('cloud_snapshot_bootstrap_json', '{}');
$smarty->assign('cloud_snapshot_view', CloudUserPageView::cloudSnapshots([]));
$smarty->assign('cloud_vpc_bootstrap_json', '{}');
$smarty->assign('cloud_vpc_view', CloudUserPageView::vpcs([], []));
$smarty->assign('cloud_iso_bootstrap_json', '{}');
$smarty->assign('cloud_iso_view', CloudUserPageView::isos([]));
$smarty->assign('cloud_ssh_keys', []);
$smarty->assign('cloud_ssh_keys_bootstrap_json', '{}');
$smarty->assign('cloud_reinstall_vm', []);
@ -902,6 +942,7 @@ final class CloudPageController
'password_label' => $passwordAvailable ? '********' : '未记录',
'password_available' => $passwordAvailable,
'can_operate' => (bool) ($vm['can_operate'] ?? false),
'is_owner' => (bool) ($vm['is_owner'] ?? false),
'can_settings' => (bool) ($vm['is_owner'] ?? false)
&& (bool) ($vm['can_operate'] ?? false)
&& (string) ($vm['os_source'] ?? '') === 'cloud_template',

@ -0,0 +1,198 @@
<?php
namespace App\Services\Cloud;
/** Display-only first paints built from the existing actor-scoped public DTOs. */
final class CloudUserPageView
{
public static function backups(array $payload): array
{
$items = [];
foreach ($payload['items'] ?? [] as $backup) {
$id = (string) ($backup['id'] ?? '');
[$label, $class] = self::state((string) ($backup['state'] ?? ''), [
'ready' => ['可用', 'running'], 'creating' => ['正在备份', 'warning'],
'queued' => ['等待备份', 'warning'], 'failed' => ['备份失败', 'stopped'],
'uncertain' => ['等待核对', 'warning'], 'deleting' => ['正在删除', 'warning'],
'delete_uncertain' => ['删除待核对', 'warning'],
'delete_attention' => ['清理需人工处理', 'stopped'],
]);
$source = $backup['source_instance'] ?? [];
$sourceId = (string) ($source['id'] ?? '');
$deleted = ($source['deleted'] ?? false) === true
|| in_array($source['status'] ?? '', ['deleted', 'missing'], true);
$snapshot = $backup['cloud_snapshot'] ?? [];
$snapshotKey = (string) ($snapshot['snapshot_key'] ?? $snapshot['key'] ?? '');
$items[] = [
'id' => $id, 'name' => self::text($backup['name'] ?? '', '云备份 #' . $id),
'source_label' => $deleted ? '源实例已删除'
: '来源:' . self::text($source['name'] ?? '', $sourceId !== '' ? '实例 #' . $sourceId : '实例未记录'),
'state_label' => $label, 'state_class' => $class,
'date_display' => self::date($backup['ready_at'] ?? $backup['created_at'] ?? null),
'consistency_display' => ($backup['consistency'] ?? '') === 'filesystem' ? '文件系统一致' : '崩溃一致',
'object_display' => self::bytes($backup['object_size_bytes'] ?? null),
'disk_display' => self::bytes($backup['virtual_size_bytes'] ?? null),
'restore_href' => !$deleted && ($backup['can_restore_original'] ?? false) === true
&& preg_match('/^[1-9][0-9]*$/D', $sourceId) === 1
? '/user/cloud/instances/' . $sourceId . '?tab=settings&setting=automatic_backup' : '',
'snapshot_href' => preg_match('/^[a-f0-9]{32}$/D', $snapshotKey) === 1
? '/user/cloud/cloud-snapshots#cloud-snapshot-' . $snapshotKey : '',
'can_promote' => ($backup['can_promote'] ?? false) === true,
];
}
return ['items' => $items, 'pagination' => self::pagination($payload)];
}
public static function cloudSnapshots(array $payload): array
{
$items = [];
foreach ($payload['items'] ?? [] as $snapshot) {
$key = (string) ($snapshot['snapshot_key'] ?? '');
[$label, $class] = self::state((string) ($snapshot['state'] ?? ''), [
'ready' => ['可用', 'running'], 'promoting' => ['正在保存', 'warning'],
'deleting' => ['正在删除', 'warning'], 'delete_uncertain' => ['删除待核对', 'warning'],
'failed' => ['保存失败', 'stopped'],
]);
$source = $snapshot['source_instance'] ?? [];
$sourceName = self::text($source['name'] ?? '', !empty($source['id']) ? '实例 #' . $source['id'] : '来源实例未记录');
$pending = max(0, (int) ($snapshot['active_invoice_count'] ?? 0));
$items[] = [
'key' => $key, 'name' => self::text($snapshot['name'] ?? '', '云快照 ' . substr($key, 0, 8)),
'source_label' => '来源:' . $sourceName . ($pending > 0 ? ' · ' . $pending . ' 张待支付账单' : ''),
'state_label' => $label, 'state_class' => $class,
'date_display' => self::date($snapshot['ready_at'] ?? $snapshot['created_at'] ?? null),
'os_display' => self::text($snapshot['os_name'] ?? '', '系统未记录'),
'object_display' => self::bytes($snapshot['object_size_bytes'] ?? null),
'disk_display' => self::bytes($snapshot['virtual_size_bytes'] ?? null),
'create_href' => ($snapshot['can_create_instance'] ?? false) === true
&& preg_match('/^[a-f0-9]{32}$/D', $key) === 1 ? '/user/cloud/deploy?cloud_snapshot=' . $key : '',
'delete_title' => ($snapshot['can_delete'] ?? false) === true ? ''
: ($pending > 0 ? '存在待支付账单,请先支付或等待账单失效后再删除。' : '云快照当前状态不允许删除。'),
];
}
return ['items' => $items, 'pagination' => self::pagination($payload)];
}
public static function vpcs(array $payload, array $query): array
{
$networks = [];
$current = null;
$key = is_string($query['vpc'] ?? null) ? $query['vpc'] : '';
$view = is_string($query['view'] ?? null) ? $query['view'] : '';
$page = $key !== '' ? 'members' : ($view === 'create' ? 'create' : 'home');
if ((isset($query['vpc']) && preg_match('/^[a-f0-9]{32}$/D', $key) !== 1)
|| (isset($query['view']) && !in_array($view, ['create', 'members', 'join'], true))
|| ($key === '' && in_array($view, ['members', 'join'], true))) {
$page = 'missing';
}
$batches = $payload['membership_batches'] ?? [];
foreach ($payload['items'] ?? [] as $network) {
$networkKey = (string) ($network['vpc_key'] ?? '');
$batch = null;
foreach ($batches as $candidate) {
if (($candidate['vpc_key'] ?? '') === $networkKey) { $batch = $candidate; break; }
}
[$label, $class] = ($network['state'] ?? '') === 'active'
? ['运行正常', 'running'] : [self::text($network['state'] ?? '', '状态未知'), 'other'];
$network['state_label'] = $batch !== null ? '变更中' : $label;
$network['state_class'] = $batch !== null ? 'other' : $class;
$network['members_href'] = '/user/cloud/vpcs?vpc=' . rawurlencode($networkKey);
$network['join_href'] = $network['members_href'] . '&view=join';
$network['batch'] = $batch;
$networks[] = $network;
if ($networkKey === $key) {
$current = $network;
$current['state_label'] = $label;
$current['state_class'] = $class;
}
}
if ($page === 'members' && $current === null) $page = 'missing';
$members = [];
$candidates = [];
foreach ($payload['instances'] ?? [] as $instance) {
if ($current === null) break;
$port = $instance['port'] ?? null;
$joined = is_array($port) && ($port['vpc_key'] ?? '') === $key;
$candidate = $port === null && (int) ($instance['region_id'] ?? 0) === (int) $current['region_id'];
if (!$joined && !$candidate) continue;
[$label, $class] = $candidate
? (($instance['can_attach'] ?? false) === true ? ['可加入', 'running'] : ['暂不可加入', 'other'])
: self::state((string) ($port['state'] ?? ''), [
'preparing' => ['正在连接', 'other'], 'attached' => ['已连接', 'running'],
'detaching' => ['正在断开', 'other'], 'release_pending' => ['等待清理', 'other'],
'released' => ['已断开', 'other'], 'migrating' => ['正在迁移', 'other'],
]);
foreach ($current['batch']['items'] ?? [] as $batchItem) {
if ((string) ($batchItem['instance_id'] ?? '') !== (string) $instance['id']) continue;
[$label, $class] = self::state((string) ($batchItem['state'] ?? ''), [
'waiting_route' => ['等待中', 'other'], 'queued' => ['执行中', 'other'],
'succeeded' => ['已完成', 'running'], 'failed' => ['失败', 'failed'], 'unknown' => ['失败', 'failed'],
]);
break;
}
$instance['state_label'] = $label;
$instance['state_class'] = $class;
$instance['public_ipv4'] = self::text($instance['public_ipv4'] ?? '', '未分配');
if ($joined) $members[] = $instance; else $candidates[] = $instance;
}
return [
'page' => $page, 'joining' => $view === 'join', 'networks' => $networks,
'regions' => $payload['regions'] ?? [], 'current' => $current,
'members' => $view === 'join' ? $candidates : $members,
'member_count' => count($members),
'joinable_count' => count(array_filter($candidates, static fn (array $item): bool => ($item['can_attach'] ?? false) === true)),
'used' => max(0, (int) ($payload['used'] ?? count($networks))),
'maximum' => max(1, (int) ($payload['maximum'] ?? 16)),
];
}
public static function isos(array $payload): array
{
$items = [];
foreach ($payload['isos'] ?? [] as $iso) {
$iso['size_display'] = self::bytes($iso['size_bytes'] ?? null);
$iso['fingerprint_display'] = !empty($iso['sha256']) ? ' · SHA-256 ' . substr((string) $iso['sha256'], 0, 12) . '…' : '';
$items[] = $iso;
}
return ['items' => $items, 'can_import' => ($payload['can_import'] ?? false) === true,
'import_active' => ($payload['active_import_job']['completed'] ?? true) === false];
}
private static function pagination(array $payload): array
{
$value = $payload['pagination'] ?? [];
$page = max(1, (int) ($value['page'] ?? 1));
$pages = max(1, (int) ($value['total_pages'] ?? 1));
return ['page' => $page, 'total_pages' => $pages,
'total' => max(0, (int) ($value['total'] ?? count($payload['items'] ?? []))),
'has_previous' => $page > 1, 'has_next' => $page < $pages];
}
private static function text($value, string $fallback): string
{
$text = trim((string) $value);
return $text !== '' ? $text : $fallback;
}
private static function state(string $value, array $labels): array
{
return $labels[$value] ?? [self::text($value, '状态未知'), 'other'];
}
private static function date($value): string
{
return is_numeric($value) && (float) $value > 0
? date('Y/m/d H:i:s', (int) ((float) $value >= 1e12 ? (float) $value / 1000 : $value)) : '时间未记录';
}
private static function bytes($value): string
{
if (!is_numeric($value) || (float) $value < 0) return '等待完成';
$amount = (float) $value;
$units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
$index = 0;
while ($amount >= 1024 && $index < count($units) - 1) { $amount /= 1024; ++$index; }
$precision = $index === 0 ? 0 : ($amount >= 100 ? 0 : ($amount >= 10 ? 1 : 2));
return number_format($amount, $precision, '.', '') . ' ' . $units[$index];
}
}

@ -31,9 +31,6 @@ function showPageError(message) {
}
async function initializeCloudApp() {
const { initializeTaskCenter } = await import(versionedModuleUrl('./task-center.js'));
initializeTaskCenter();
const modulePath = pageModules[page];
if (!modulePath) {
showPageError('页面类型无效,请返回实例列表。');
@ -41,9 +38,17 @@ async function initializeCloudApp() {
}
const module = await import(versionedModuleUrl(modulePath));
module.initialize();
await module.initialize();
}
// The page and task drawer are independent: a slow drawer must not delay the page.
void import(versionedModuleUrl('./task-center.js')).then(module => {
module.initializeTaskCenter();
}).catch(() => {
const target = document.getElementById('panel-task-state');
if (target) target.textContent = '任务中心暂时无法加载,请刷新页面重试。';
});
initializeCloudApp().catch(error => {
showPageError(error?.message || '页面加载失败,请刷新后重试。');
});

@ -16,7 +16,7 @@ const {
taskSucceededWithoutRecovery,
} = taskObserver;
const {
api, bindPageCleanup, byId, initializeSession, showError, state, toast,
api, bindPageCleanup, byId, initializeSession, readBootstrap, showError, state, toast,
} = runtime;
const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false);
@ -164,27 +164,7 @@ async function loadIsos({ observeActive = true } = {}) {
signal: pageState.loadController.signal,
});
if (epoch !== pageState.loadEpoch || pageState.stopped) return;
pageState.isos = Array.isArray(result?.isos) ? result.isos : [];
pageState.canImport = result?.can_import !== false;
renderIsos();
const job = result?.active_import_job;
const activeJobId = String(job?.task_id || '').trim();
const resumedReceipt = {
task_id: activeJobId,
status_url: `/api/v1/tasks/${encodeURIComponent(activeJobId)}`,
};
const jobId = job?.completed === false && !Object.prototype.hasOwnProperty.call(job, 'status')
&& taskUrl(resumedReceipt) ? activeJobId : '';
if (jobId) {
pageState.activeStatusUrl = jobId;
setImportStatus(job?.phase || '正在远程下载并校验 ISO…');
updateImportAvailability();
if (observeActive) watchImport(resumedReceipt, false);
} else if (!pageState.importObserver) {
pageState.activeStatusUrl = '';
setImportStatus('');
updateImportAvailability();
}
applyIsoPayload(result, observeActive);
return true;
} catch (error) {
if (epoch === pageState.loadEpoch && error.name !== 'AbortError') {
@ -194,6 +174,30 @@ async function loadIsos({ observeActive = true } = {}) {
}
}
function applyIsoPayload(result, observeActive = true) {
pageState.isos = Array.isArray(result?.isos) ? result.isos : [];
pageState.canImport = result?.can_import !== false;
renderIsos();
const job = result?.active_import_job;
const activeJobId = String(job?.task_id || '').trim();
const resumedReceipt = {
task_id: activeJobId,
status_url: `/api/v1/tasks/${encodeURIComponent(activeJobId)}`,
};
const jobId = job?.completed === false && !Object.prototype.hasOwnProperty.call(job, 'status')
&& taskUrl(resumedReceipt) ? activeJobId : '';
if (jobId) {
pageState.activeStatusUrl = jobId;
setImportStatus(job?.phase || '正在远程下载并校验 ISO…');
updateImportAvailability();
if (observeActive) watchImport(resumedReceipt, false);
} else if (!pageState.importObserver) {
pageState.activeStatusUrl = '';
setImportStatus('');
updateImportAvailability();
}
}
function taskFailureMessage(task, fallback) {
const message = task?.error || fallback;
const recoveryNotice = recoveryTaskFailureNotice(task);
@ -291,7 +295,8 @@ async function importIso(event) {
export async function initialize() {
try {
if (!await initializeSession('isos')) return;
const bootstrap = readBootstrap('user-isos-bootstrap');
if (!await initializeSession('isos', bootstrap?.user)) return;
bindPageCleanup();
window.addEventListener('pagehide', () => {
pageState.stopped = true;
@ -306,6 +311,7 @@ export async function initialize() {
void loadIsos();
});
byId('user-iso-form')?.addEventListener('submit', importIso);
await loadIsos();
if (Array.isArray(bootstrap?.isos)) applyIsoPayload(bootstrap);
else await loadIsos();
} catch (error) { showError('cloud-page-error', error.message); }
}

@ -866,10 +866,10 @@ async function selectOffer(offerId) {
async function openCreate(bootstrap = null) {
state.view = 'create'; state.selectedVmId = null; showError('create-error', '');
byId('vm-offer').value = String(bootstrap?.default_offer_id || '');
initializeDeploymentOptions(bootstrap);
if (bootstrap && Array.isArray(bootstrap.offers) && Array.isArray(bootstrap.regions)
&& Array.isArray(bootstrap.lines) && Array.isArray(bootstrap.templates)) {
applySaleCatalog(bootstrap);
initializeDeploymentOptions(bootstrap);
state.templates = bootstrapItems(bootstrap, 'templates', 'cloud_templates');
state.templateCatalogUnavailable = bootstrap.catalog_unavailable === true;
state.sshKeys = bootstrapItems(bootstrap, 'ssh_keys', 'keys');
@ -891,6 +891,7 @@ async function openCreate(bootstrap = null) {
updateCreateAvailability();
return;
}
initializeDeploymentOptions(bootstrap);
state.regions = []; state.lines = []; state.offers = []; state.linesEnabled = false;
state.selectedRegionId = ''; state.selectedLineId = '';
byId('vm-region').value = ''; byId('vm-line').value = '';

@ -199,7 +199,18 @@ function instanceMatchesMemberQuery(instance, query) {
function pageRoute() {
const hash = window.location.hash;
if (!hash || hash === '#' || hash === '#/') return { page: 'home' };
if (!hash || hash === '#') {
const query = new URL(window.location.href).searchParams;
const key = query.getAll('vpc').at(-1) ?? null;
const view = query.getAll('view').at(-1) ?? null;
if ((key !== null && !/^[a-f0-9]{32}$/.test(key))
|| [...query.keys()].some(name => /^(?:vpc|view)\[/.test(name))
|| (view !== null && !['create', 'members', 'join'].includes(view))
|| (!key && ['members', 'join'].includes(view))) return { page: 'missing' };
if (key) return { page: 'members', key, joining: view === 'join' };
return { page: view === 'create' ? 'create' : 'home' };
}
if (hash === '#/') return { page: 'home' };
if (hash === '#/create') return { page: 'create' };
const match = /^#\/([a-f0-9]{32})\/instances(\/join)?$/.exec(hash);
return match ? { page: 'members', key: match[1], joining: Boolean(match[2]) }
@ -207,7 +218,7 @@ function pageRoute() {
}
function membersHref(vpc, joining = false) {
return `#/${vpcKey(vpc)}/instances${joining ? '/join' : ''}`;
return `/user/cloud/vpcs?vpc=${encodeURIComponent(vpcKey(vpc))}${joining ? '&view=join' : ''}`;
}
function currentVpc() {
@ -348,7 +359,7 @@ function renderHome() {
list.replaceChildren();
if (!state.items.length) {
list.append(emptyState('还没有 VPC', '选择一个地区,建立你的第一张私有网络。',
'#/create', '创建 VPC'));
'/user/cloud/vpcs?view=create', '创建 VPC'));
return;
}
const table = element('table', 'cloud-vpc-table cloud-vpc-network-table');
@ -903,7 +914,7 @@ async function submitMembershipBatch(vpc, action, instances) {
selectionForVpc(vpc, action).clear();
observeBatch(batch, true);
if (currentVpc() && vpcKey(currentVpc()) === key) {
window.location.hash = membersHref(vpc);
window.location.href = new URL(membersHref(vpc), window.location.href).href;
}
setPageStatus(`已接收 ${ids.length} 台实例;任务将在服务端并发处理。`);
toast('VPC 批量任务已接收。', 'success');
@ -1058,7 +1069,7 @@ async function createVpc(event) {
state.used += 1;
}
// Keep the confirmed creation visible even if the following refresh fails.
if (pageRoute().page === 'create') window.location.hash = membersHref(created, true);
if (pageRoute().page === 'create') window.location.href = new URL(membersHref(created, true), window.location.href).href;
}
await load(true);
toast('VPC 已创建,可选择需要加入的实例。', 'success');
@ -1089,7 +1100,7 @@ async function removeVpc(vpc) {
});
state.items = state.items.filter(item => vpcKey(item) !== key);
state.used = Math.max(0, state.used - 1);
if (pageRoute().key === key) window.location.hash = '#/';
if (pageRoute().key === key) window.location.href = new URL('/user/cloud/vpcs', window.location.href).href;
await load(true);
toast('VPC 已删除。', 'success');
} catch (error) {

@ -5,6 +5,8 @@
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>{$config["appName"]|escape:"html"} · {$cloud_title|escape:"html"}</title>
{if !empty($cloud_page_module)}<link rel="modulepreload" href="/cloud/{$cloud_page_module|escape:'html'}.js?v={$venix_asset_version}"/>{/if}
{if !empty($cloud_uses_runtime)}<link rel="modulepreload" href="/cloud/runtime.js?v={$venix_asset_version}"/>{/if}
<link rel="shortcut icon" href="/theme/venix/images/favicon.ico" type="image/x-icon"/>
<link rel="stylesheet" href="/theme/venix/css/icons.min.css?v={$venix_asset_version}"/>
<link rel="stylesheet" href="/cloud/styles.css?v={$venix_asset_version}"/>

@ -5,15 +5,26 @@
</div>
<div class="vm-settings-notice cloud-backups-notice"><strong>备份用途说明</strong><span>云备份用于恢复原实例,也可保存为长期保留的云快照;创建新实例请前往“云快照”。</span></div>
<section class="inventory-panel cloud-backups-panel" aria-labelledby="cloud-backups-list-title">
<div class="panel-heading"><div><h2 id="cloud-backups-list-title">全部备份</h2><p>只显示属于当前账户的普通云备份,不包含管理员维护迁移的临时数据。</p></div><span id="cloud-backups-count" class="state-pill other">0 个</span></div>
<p id="cloud-backups-status" class="vm-settings-status" role="status" aria-live="polite">正在读取云备份…</p>
<div id="cloud-backups-list" class="cloud-backups-list" aria-live="polite"></div>
<div class="panel-heading"><div><h2 id="cloud-backups-list-title">全部备份</h2><p>只显示属于当前账户的普通云备份,不包含管理员维护迁移的临时数据。</p></div><span id="cloud-backups-count" class="state-pill other">{$cloud_backup_view.pagination.total|default:0|escape:'html'} 个</span></div>
<p id="cloud-backups-status" class="vm-settings-status" role="status" aria-live="polite" hidden></p>
<div id="cloud-backups-list" class="cloud-backups-list" aria-live="polite">
{foreach $cloud_backup_view.items|default:[] as $backup}
<article class="cloud-backup-card">
<div class="cloud-backup-card-heading"><div class="cloud-backup-title"><span class="cloud-backup-icon">☁</span><div>{$backup.name|escape:'html'}<small>{$backup.source_label|escape:'html'}</small></div></div><span class="state-pill {$backup.state_class|escape:'html'}">{$backup.state_label|escape:'html'}</span></div>
<dl class="cloud-backup-facts"><div><dt>创建时间</dt><dd>{$backup.date_display|escape:'html'}</dd></div><div><dt>一致性</dt><dd>{$backup.consistency_display|escape:'html'}</dd></div><div><dt>对象大小</dt><dd>{$backup.object_display|escape:'html'}</dd></div><div><dt>磁盘容量</dt><dd>{$backup.disk_display|escape:'html'}</dd></div></dl>
<div class="cloud-backup-actions">
{if $backup.restore_href != ''}<a class="button button-outline small" href="{$backup.restore_href|escape:'html'}">恢复原实例</a>{/if}
{if $backup.snapshot_href != ''}<a class="button button-primary small" href="{$backup.snapshot_href|escape:'html'}">查看云快照</a>{elseif $backup.can_promote}<button class="button button-primary small" type="button" disabled>保存为云快照</button>{/if}
</div>
</article>
{foreachelse}<div class="cloud-backups-empty"><strong>还没有云备份</strong><span>购买自动备份后,可在实例详情中设置备份计划。</span></div>{/foreach}
</div>
<nav class="cloud-backups-pagination" aria-label="云备份分页">
<button id="cloud-backups-previous" class="button button-outline small" type="button" disabled>上一页</button>
<span id="cloud-backups-page">第 1 / 1 页</span>
<button id="cloud-backups-next" class="button button-outline small" type="button" disabled>下一页</button>
<button id="cloud-backups-previous" class="button button-outline small" type="button"{if empty($cloud_backup_view.pagination.has_previous)} disabled{/if}>上一页</button>
<span id="cloud-backups-page">第 {$cloud_backup_view.pagination.page|default:1|escape:'html'} / {$cloud_backup_view.pagination.total_pages|default:1|escape:'html'} 页</span>
<button id="cloud-backups-next" class="button button-outline small" type="button"{if empty($cloud_backup_view.pagination.has_next)} disabled{/if}>下一页</button>
</nav>
</section>
<noscript><p class="resource-warning">查看云备份和保存云快照需要启用 JavaScript。</p></noscript>
<noscript><p class="resource-warning">保存云快照和翻页需要启用 JavaScript。</p></noscript>
</div>
<script id="cloud-backups-bootstrap" type="application/json">{$cloud_backup_bootstrap_json|default:'{}' nofilter}</script>

@ -4,15 +4,23 @@
</div>
<div class="vm-settings-notice cloud-snapshots-notice"><strong>与在线快照不同</strong><span>云快照独立存放在对象存储中,不随源实例或自动备份轮换删除;只有手动删除后才会释放其存储对象。</span></div>
<section class="inventory-panel cloud-backups-panel cloud-snapshots-panel" aria-labelledby="cloud-snapshots-list-title">
<div class="panel-heading"><div><h2 id="cloud-snapshots-list-title">全部云快照</h2><p>从云快照创建的新实例会使用新的 UUID、网络标识和公网 IP。</p></div><span id="cloud-snapshots-count" class="state-pill other">0 个</span></div>
<p id="cloud-snapshots-status" class="vm-settings-status" role="status" aria-live="polite">正在读取云快照…</p>
<div id="cloud-snapshots-list" class="cloud-backups-list cloud-snapshots-list" aria-live="polite"></div>
<div class="panel-heading"><div><h2 id="cloud-snapshots-list-title">全部云快照</h2><p>从云快照创建的新实例会使用新的 UUID、网络标识和公网 IP。</p></div><span id="cloud-snapshots-count" class="state-pill other">{$cloud_snapshot_view.pagination.total|default:0|escape:'html'} 个</span></div>
<p id="cloud-snapshots-status" class="vm-settings-status" role="status" aria-live="polite" hidden></p>
<div id="cloud-snapshots-list" class="cloud-backups-list cloud-snapshots-list" aria-live="polite">
{foreach $cloud_snapshot_view.items|default:[] as $snapshot}
<article id="cloud-snapshot-{$snapshot.key|escape:'html'}" class="cloud-backup-card cloud-snapshot-card">
<div class="cloud-backup-card-heading"><div class="cloud-backup-title"><span class="cloud-backup-icon cloud-snapshot-icon">◆</span><div>{$snapshot.name|escape:'html'}<small>{$snapshot.source_label|escape:'html'}</small></div></div><span class="state-pill {$snapshot.state_class|escape:'html'}">{$snapshot.state_label|escape:'html'}</span></div>
<dl class="cloud-backup-facts cloud-snapshot-facts"><div><dt>保存时间</dt><dd>{$snapshot.date_display|escape:'html'}</dd></div><div><dt>操作系统</dt><dd>{$snapshot.os_display|escape:'html'}</dd></div><div><dt>对象大小</dt><dd>{$snapshot.object_display|escape:'html'}</dd></div><div><dt>磁盘容量</dt><dd>{$snapshot.disk_display|escape:'html'}</dd></div></dl>
<div class="cloud-backup-actions cloud-snapshot-actions">{if $snapshot.create_href != ''}<a class="button button-primary small" href="{$snapshot.create_href|escape:'html'}">创建实例</a>{/if}<button class="button button-outline small danger" type="button" title="{$snapshot.delete_title|escape:'html'}" disabled>删除</button></div>
</article>
{foreachelse}<div class="cloud-backups-empty cloud-snapshots-empty"><strong>还没有云快照</strong><span>可前往“云备份”将一份可用备份保存为云快照。</span></div>{/foreach}
</div>
<nav class="cloud-backups-pagination cloud-snapshots-pagination" aria-label="云快照分页">
<button id="cloud-snapshots-previous" class="button button-outline small" type="button" disabled>上一页</button>
<span id="cloud-snapshots-page">第 1 / 1 页</span>
<button id="cloud-snapshots-next" class="button button-outline small" type="button" disabled>下一页</button>
<button id="cloud-snapshots-previous" class="button button-outline small" type="button"{if empty($cloud_snapshot_view.pagination.has_previous)} disabled{/if}>上一页</button>
<span id="cloud-snapshots-page">第 {$cloud_snapshot_view.pagination.page|default:1|escape:'html'} / {$cloud_snapshot_view.pagination.total_pages|default:1|escape:'html'} 页</span>
<button id="cloud-snapshots-next" class="button button-outline small" type="button"{if empty($cloud_snapshot_view.pagination.has_next)} disabled{/if}>下一页</button>
</nav>
</section>
<noscript><p class="resource-warning">查看、创建实例和删除云快照需要启用 JavaScript。</p></noscript>
<noscript><p class="resource-warning">删除云快照和翻页需要启用 JavaScript。</p></noscript>
</div>
<script id="cloud-snapshots-bootstrap" type="application/json">{$cloud_snapshot_bootstrap_json|default:'{}' nofilter}</script>

@ -59,14 +59,14 @@
</div>
</section>
<section id="vm-source-step" class="deployment-step" aria-labelledby="deploy-source-title" aria-disabled="false">
<div class="deployment-step-heading"><span>{if !empty($cloud_deploy_lines_enabled)}4{else}3{/if}</span><h2 id="deploy-source-title">选择系统镜像<span class="deployment-required-mark" aria-hidden="true">*</span><span class="sr-only">(必选)</span></h2></div>
<input id="vm-cloud-snapshot-key" type="hidden" value="" />
<div id="vm-cloud-snapshot-source" class="deployment-backup-source" hidden>
<div class="deployment-step-heading"><span>{if !empty($cloud_deploy_lines_enabled)}4{else}3{/if}</span><h2 id="deploy-source-title">{if !empty($cloud_deploy_snapshot)}云快照来源{else}选择系统镜像{/if}<span class="deployment-required-mark" aria-hidden="true">*</span><span class="sr-only">(必选)</span></h2></div>
<input id="vm-cloud-snapshot-key" type="hidden" value="{$cloud_deploy_snapshot.snapshot_key|default:''|escape:'html'}" />
<div id="vm-cloud-snapshot-source" class="deployment-backup-source"{if empty($cloud_deploy_snapshot)} hidden{/if}>
<span class="deployment-backup-source-icon" aria-hidden="true"><i class="mdi mdi-cloud-check-outline"></i></span>
<div><strong>从云快照创建新实例</strong><small id="vm-cloud-snapshot-source-name">正在核对云快照…</small></div>
<div><strong>从云快照创建新实例</strong><small id="vm-cloud-snapshot-source-name">{$cloud_deploy_snapshot.name|default:'云快照'|escape:'html'},将按所选规格创建新的付费实例。</small></div>
<a class="button button-outline small" href="/user/cloud/cloud-snapshots">重新选择</a>
</div>
<div class="field full" id="vm-template-field"><input id="vm-template" name="template_id" type="hidden" value=""{if empty($cloud_deploy_template_groups)} disabled{/if} /><div id="vm-template-catalog" class="template-catalog" role="group" aria-labelledby="deploy-source-title" aria-required="true">
<div class="field full" id="vm-template-field"{if !empty($cloud_deploy_snapshot)} hidden{/if}><input id="vm-template" name="template_id" type="hidden" value=""{if empty($cloud_deploy_template_groups) || !empty($cloud_deploy_snapshot)} disabled{/if} /><div id="vm-template-catalog" class="template-catalog" role="group" aria-labelledby="deploy-source-title" aria-required="true">
{if empty($cloud_deploy_template_groups)}
<p class="template-catalog-empty">{if !empty($cloud_deploy_catalog_unavailable)}系统镜像目录暂时无法读取,请稍后刷新。{else}暂无可用云镜像,请联系管理员导入模板。{/if}</p>
{else}
@ -91,24 +91,24 @@
<div class="deployment-step-heading"><span>{if !empty($cloud_deploy_lines_enabled)}5{else}4{/if}</span><h2 id="deploy-config-title">实例信息</h2></div>
<div class="form-grid">
<div class="field full"><label for="vm-name">实例名称</label><input id="vm-name" name="name" type="text" maxlength="63" pattern="[a-zA-Z0-9][a-zA-Z0-9._-]*" autocomplete="off" /></div>
<div class="cloud-fields full" id="vm-cloud-fields"><div class="form-grid vm-cloud-auth-fields"><div class="field full"><span class="ssh-key-picker-title">SSH 公钥</span><div id="vm-guest-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="部署实例时选择 SSH 公钥">{if empty($cloud_deploy_ssh_keys)}<p class="muted">暂无公钥,可先到“公钥管理”添加。</p>{else}{foreach $cloud_deploy_ssh_keys as $key}<button class="ssh-key-option" type="button" aria-pressed="false" data-key-id="{$key.id|escape:"html"}" aria-label="选择 SSH 公钥 {$key.name|escape:"html"},指纹 {$key.fingerprint|escape:"html"}"><i class="mdi mdi-key-variant ssh-key-choice-icon" aria-hidden="true"></i><span class="ssh-key-choice-copy"><strong class="ssh-key-choice-label">{$key.name|escape:"html"}</strong><small class="ssh-key-choice-fingerprint" title="{$key.fingerprint|escape:"html"}">{$key.fingerprint|escape:"html"}</small></span><span class="ssh-key-choice-check" aria-hidden="true">&#x2713;</span></button>{/foreach}{/if}</div><a id="vm-open-ssh-keys" class="ssh-key-picker-manage" href="/user/cloud/ssh-keys">管理我的公钥</a></div><div class="field full" id="vm-root-password-field"><label for="vm-root-password">初始 root 密码</label><input id="vm-root-password" name="root_password" type="password" maxlength="128" autocomplete="new-password" spellcheck="false" /></div></div></div>
<div class="cloud-fields full" id="vm-cloud-fields"{if !empty($cloud_deploy_snapshot)} hidden{/if}><div class="form-grid vm-cloud-auth-fields"><div class="field full"><span class="ssh-key-picker-title">SSH 公钥</span><div id="vm-guest-ssh-key-cards" class="ssh-key-picker" role="group" aria-label="部署实例时选择 SSH 公钥">{if empty($cloud_deploy_ssh_keys)}<p class="muted">暂无公钥,可先到“公钥管理”添加。</p>{else}{foreach $cloud_deploy_ssh_keys as $key}<button class="ssh-key-option" type="button" aria-pressed="false" data-key-id="{$key.id|escape:"html"}" aria-label="选择 SSH 公钥 {$key.name|escape:"html"},指纹 {$key.fingerprint|escape:"html"}"><i class="mdi mdi-key-variant ssh-key-choice-icon" aria-hidden="true"></i><span class="ssh-key-choice-copy"><strong class="ssh-key-choice-label">{$key.name|escape:"html"}</strong><small class="ssh-key-choice-fingerprint" title="{$key.fingerprint|escape:"html"}">{$key.fingerprint|escape:"html"}</small></span><span class="ssh-key-choice-check" aria-hidden="true">&#x2713;</span></button>{/foreach}{/if}</div><a id="vm-open-ssh-keys" class="ssh-key-picker-manage" href="/user/cloud/ssh-keys">管理我的公钥</a></div><div class="field full" id="vm-root-password-field"><label for="vm-root-password">初始 root 密码</label><input id="vm-root-password" name="root_password" type="password" maxlength="128" autocomplete="new-password" spellcheck="false"{if !empty($cloud_deploy_snapshot)} disabled{/if} /></div></div></div>
</div>
</section>
<section id="vm-backup-step" class="deployment-step" aria-labelledby="deploy-backup-title">
<div class="deployment-step-heading"><span>{if !empty($cloud_deploy_lines_enabled)}6{else}5{/if}</span><h2 id="deploy-backup-title">自动备份</h2></div>
<label id="vm-automatic-backup-option" class="deployment-addon-option is-disabled">
<input id="vm-automatic-backup" name="automatic_backup" type="checkbox" disabled/>
<span><strong>启用自动备份</strong><small id="vm-automatic-backup-help">选择实例规格后可以启用。</small></span>
<label id="vm-automatic-backup-option" class="deployment-addon-option{if empty($cloud_deploy_price)} is-disabled{/if}">
<input id="vm-automatic-backup" name="automatic_backup" type="checkbox"{if empty($cloud_deploy_price)} disabled{/if}/>
<span><strong>启用自动备份</strong><small id="vm-automatic-backup-help">{if empty($cloud_deploy_price)}选择实例规格后可以启用。{else}购买后可在实例详情的“自动备份”中管理备份计划。{/if}</small></span>
</label>
</section>
<section id="vm-order-summary-step" class="deployment-step deployment-order-summary" aria-labelledby="deploy-order-summary-title">
<div class="deployment-step-heading"><span>{if !empty($cloud_deploy_lines_enabled)}7{else}6{/if}</span><h2 id="deploy-order-summary-title">确认费用</h2></div>
<p id="vm-order-summary-empty" class="muted">选择实例规格后显示本次最终金额。</p>
<dl id="vm-order-summary" aria-live="polite" hidden>
<div><dt>实例费用</dt><dd id="vm-order-instance-price">—</dd></div>
<div id="vm-order-backup-row" hidden><dt>自动备份</dt><dd id="vm-order-backup-price">—</dd></div>
<div class="deployment-order-total"><dt>本次应付</dt><dd id="vm-order-total-price">—</dd></div>
<div><dt>下次续费</dt><dd id="vm-order-renewal-price">—</dd></div>
<p id="vm-order-summary-empty" class="muted"{if !empty($cloud_deploy_price)} hidden{/if}>选择实例规格后显示本次最终金额。</p>
<dl id="vm-order-summary" aria-live="polite"{if empty($cloud_deploy_price)} hidden{/if}>
<div><dt>实例费用</dt><dd id="vm-order-instance-price">{$cloud_deploy_price|default:'—'|escape:'html'}</dd></div>
<div id="vm-order-backup-row" hidden><dt>自动备份</dt><dd id="vm-order-backup-price">{$cloud_deploy_backup_price|default:'—'|escape:'html'}</dd></div>
<div class="deployment-order-total"><dt>本次应付</dt><dd id="vm-order-total-price">{$cloud_deploy_price|default:'—'|escape:'html'}</dd></div>
<div><dt>下次续费</dt><dd id="vm-order-renewal-price">{$cloud_deploy_price|default:'—'|escape:'html'} / 期</dd></div>
</dl>
</section>
<p id="create-error" class="form-error" role="alert" hidden></p>

@ -24,8 +24,8 @@
</dl>
</section>
<div class="vm-detail-operations">
<section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-actions-title"><div class="panel-heading"><div><h2 id="vm-detail-actions-title">日常操作</h2><p>在这里管理这台虚拟机的电源和控制台。</p></div></div><div id="vm-detail-primary-actions" class="vm-detail-actions"><p class="muted">正在读取实时状态…</p></div></section>
<section class="inventory-panel vm-detail-panel vm-danger-panel" aria-labelledby="vm-detail-danger-title"><div class="panel-heading"><div><h2 id="vm-detail-danger-title">维护与危险操作</h2><p>救援会先预挂载 ISO,再尝试正常关机并开机;强制断电可能丢失未保存的数据,重装或删除会清除数据。</p></div></div><div id="vm-detail-danger-actions" class="vm-detail-actions"><p class="muted">实时状态确认后才会启用操作。</p></div></section>
<section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-actions-title"><div class="panel-heading"><div><h2 id="vm-detail-actions-title">日常操作</h2><p>在这里管理这台虚拟机的电源和控制台。</p></div></div><div id="vm-detail-primary-actions" class="vm-detail-actions">{if $cloud_vm_view.can_operate|default:false}<button class="row-button" type="button" disabled>控制台</button><button class="row-button" type="button" disabled>开机</button><button class="row-button" type="button" disabled>正常关机</button><button class="row-button" type="button" disabled>重启</button>{else}<p class="muted">{if $cloud_vm_view.is_owner|default:false || $cloud_vm_view.can_delete|default:false}实例服务已到期或正在执行策略;日常操作暂不可用。{else}这是其他用户的实例;当前管理员账户只有查看权限。{/if}</p>{/if}</div></section>
<section class="inventory-panel vm-detail-panel vm-danger-panel" aria-labelledby="vm-detail-danger-title"{if !$cloud_vm_view.can_operate|default:false && !$cloud_vm_view.can_delete|default:false} hidden{/if}><div class="panel-heading"><div><h2 id="vm-detail-danger-title">维护与危险操作</h2><p>救援会先预挂载 ISO,再尝试正常关机并开机;强制断电可能丢失未保存的数据,重装或删除会清除数据。</p></div></div><div id="vm-detail-danger-actions" class="vm-detail-actions">{if $cloud_vm_view.can_operate|default:false}<button class="row-button danger" type="button" disabled>重装系统</button><button class="row-button danger" type="button" disabled>紧急救援</button><button class="row-button danger" type="button" disabled>强制重置</button><button class="row-button danger" type="button" disabled>强制断电</button>{/if}{if $cloud_vm_view.can_delete|default:false}<button class="row-button danger" type="button" disabled>删除虚拟机</button>{/if}</div></section>
</div>
</div>
</div>

@ -9,16 +9,19 @@
<label for="user-iso-url">HTTPS ISO 直链</label>
<input id="user-iso-url" type="url" maxlength="2048" required inputmode="url" autocomplete="off" spellcheck="false" placeholder="https://example.com/system.iso" />
<small class="user-iso-hint">仅支持无需登录、不会跳转的公网 HTTPS 直链,URL 路径的文件名必须以 .iso 结尾;每个用户最多保存 5 个,个人 ISO 库累计和单文件均不得超过 10 GiB。超出限额会停止下载并提示,离开页面不会取消后台任务。</small>
<p id="user-iso-availability" class="host-test-status warning" role="status" hidden></p>
<p id="user-iso-availability" class="host-test-status warning" role="status"{if !empty($cloud_iso_view.can_import) && empty($cloud_iso_view.import_active)} hidden{/if}>{if !empty($cloud_iso_view.import_active)}已有 ISO 下载任务正在执行,完成前不能再次导入。{elseif empty($cloud_iso_view.can_import)}账户的套餐购买及 ISO 上传服务已被管理员停用。{/if}</p>
<p id="user-iso-form-error" class="form-error" role="alert" hidden></p>
<button id="user-iso-submit" class="button button-primary" type="submit">开始远程下载</button>
<button id="user-iso-submit" class="button button-primary" type="submit" disabled>开始远程下载</button>
</form>
<p id="user-iso-import-status" class="host-test-status" role="status" hidden></p>
</section>
<section class="host-card" aria-labelledby="user-iso-list-title">
<div class="host-card-heading"><span class="host-card-number">◉</span><div><h2 id="user-iso-list-title">我的 ISO</h2><p>这里只显示当前账户的全局 ISO,其他用户无法查看或使用。</p></div></div>
<p id="user-iso-list-error" class="form-error" role="alert" hidden></p>
<div id="user-iso-list" class="user-iso-list" aria-live="polite"><p class="muted">正在加载…</p></div>
<div id="user-iso-list" class="user-iso-list" aria-live="polite">
{foreach $cloud_iso_view.items|default:[] as $iso}<article class="user-iso-row"><div class="user-iso-details"><strong>{$iso.name|escape:'html'}</strong><small>{$iso.size_display|escape:'html'}{$iso.fingerprint_display|escape:'html'}</small></div><button class="row-button user-iso-delete" type="button" disabled>{if $iso.can_delete|default:false}删除{else}不可删除{/if}</button></article>{foreachelse}<p class="muted">还没有个人 ISO 镜像。</p>{/foreach}
</div>
</section>
</div>
</div>
<script id="user-isos-bootstrap" type="application/json">{$cloud_iso_bootstrap_json|default:'{}' nofilter}</script>

@ -1,46 +1,79 @@
<div id="cloud-vpcs-workspace">
<a id="cloud-vpcs-back" class="cloud-vpc-back" href="#/" hidden><span aria-hidden="true">←</span> 返回 VPC 列表</a>
<a id="cloud-vpcs-back" class="cloud-vpc-back" href="/user/cloud/vpcs"{if $cloud_vpc_view.page|default:'home' == 'home'} hidden{/if}><span aria-hidden="true">←</span> 返回 VPC 列表</a>
<p id="cloud-vpcs-status" class="vm-settings-status" role="status" aria-live="polite" hidden></p>
<section id="cloud-vpcs-home" aria-labelledby="cloud-vpcs-title">
<section id="cloud-vpcs-home" aria-labelledby="cloud-vpcs-title"{if $cloud_vpc_view.page|default:'home' != 'home'} hidden{/if}>
<div class="page-heading cloud-vpcs-heading">
<div><h1 id="cloud-vpcs-title" tabindex="-1">VPC 私网</h1><p>管理同地区实例之间的私有网络。</p></div>
<a class="button button-primary" href="#/create">+ 创建 VPC</a>
<a class="button button-primary" href="/user/cloud/vpcs?view=create">+ 创建 VPC</a>
</div>
<div class="cloud-vpc-list-meta"><h2>我的网络</h2><span id="cloud-vpcs-quota">{$cloud_vpc_view.used|default:0|escape:'html'} / {$cloud_vpc_view.maximum|default:16|escape:'html'} 个</span></div>
<div id="cloud-vpcs-list" class="inventory-panel cloud-vpc-list-panel">
{if !empty($cloud_vpc_view.networks)}
<table class="cloud-vpc-table cloud-vpc-network-table" aria-label="VPC 网络列表">
<thead><tr><th scope="col">网络名称 / 地区</th><th scope="col">私网网段</th><th scope="col">实例</th><th scope="col">状态</th><th scope="col"><span class="sr-only">管理</span></th></tr></thead>
<tbody>{foreach $cloud_vpc_view.networks as $network}<tr>
<td class="cloud-vpc-network-name" data-label="网络"><a class="cloud-vpc-name-link" href="{$network.members_href|escape:'html'}">{$network.name|escape:'html'}</a><small>{$network.region_name|escape:'html'}</small></td>
<td class="cloud-vpc-table-address" data-label="私网网段"><code>{$network.cidr|escape:'html'}</code></td>
<td class="cloud-vpc-network-count" data-label="实例">{$network.port_count|default:0|escape:'html'} 台</td>
<td class="cloud-vpc-network-status" data-label="状态"><span class="state-pill {$network.state_class|escape:'html'}">{$network.state_label|escape:'html'}</span></td>
<td class="cloud-vpc-network-actions" data-label="管理"><a class="cloud-vpc-text-button" href="{$network.members_href|escape:'html'}">管理实例 →</a></td>
</tr>{/foreach}</tbody>
</table>
{else}<div class="cloud-vpc-empty"><strong>还没有 VPC</strong><p>选择一个地区,建立你的第一张私有网络。</p><a class="button button-outline" href="/user/cloud/vpcs?view=create">创建 VPC</a></div>{/if}
</div>
<div class="cloud-vpc-list-meta"><h2>我的网络</h2><span id="cloud-vpcs-quota">0 / 16 个</span></div>
<div id="cloud-vpcs-list" class="inventory-panel cloud-vpc-list-panel"></div>
<p class="cloud-vpc-footnote">同一 VPC 内默认互通,实例公网配置保持独立。</p>
</section>
<section id="cloud-vpcs-create" aria-labelledby="cloud-vpc-create-title" hidden>
<section id="cloud-vpcs-create" aria-labelledby="cloud-vpc-create-title"{if $cloud_vpc_view.page|default:'home' != 'create'} hidden{/if}>
<div class="page-heading cloud-vpcs-heading"><div><h1 id="cloud-vpc-create-title" tabindex="-1">创建 VPC</h1><p>先建立网络,再选择需要加入的实例。</p></div></div>
<div class="inventory-panel cloud-vpc-create-panel">
<form id="cloud-vpc-create-form" class="cloud-vpc-create-form">
<h2>基本信息</h2>
<div class="cloud-vpc-create-fields">
<div class="field"><label for="cloud-vpc-name">VPC 名称</label><input id="cloud-vpc-name" maxlength="80" required autocomplete="off" placeholder="例如 production" aria-describedby="cloud-vpc-name-help"><small id="cloud-vpc-name-help">用于识别这张私有网络。</small></div>
<div class="field"><label for="cloud-vpc-region">所属地区</label><select id="cloud-vpc-region" required aria-describedby="cloud-vpc-region-help"></select><small id="cloud-vpc-region-help">只有同地区的实例可以加入。</small></div>
<div class="field"><label for="cloud-vpc-region">所属地区</label><select id="cloud-vpc-region" required aria-describedby="cloud-vpc-region-help"><option value="">{if empty($cloud_vpc_view.regions)}暂无可用地区{else}请选择地区{/if}</option>{foreach $cloud_vpc_view.regions|default:[] as $region}<option value="{$region.id|escape:'html'}">{$region.name|escape:'html'}</option>{/foreach}</select><small id="cloud-vpc-region-help">只有同地区的实例可以加入。</small></div>
</div>
<div class="cloud-vpc-allocation"><span>私网地址</span><div><strong>由系统自动分配</strong><small>创建后显示网段和默认网关。</small></div></div>
<p id="cloud-vpc-create-availability" class="cloud-vpc-footnote" role="status" hidden></p>
<p id="cloud-vpc-create-error" class="form-error" role="alert" hidden></p>
<div class="cloud-vpc-create-footer"><a class="button button-outline" href="#/">取消</a><button id="cloud-vpc-create-submit" class="button button-primary" type="submit">创建并管理实例 →</button></div>
<div class="cloud-vpc-create-footer"><a class="button button-outline" href="/user/cloud/vpcs">取消</a><button id="cloud-vpc-create-submit" class="button button-primary" type="submit" disabled>创建并管理实例 →</button></div>
</form>
</div>
</section>
<section id="cloud-vpcs-members" aria-labelledby="cloud-vpc-members-title" hidden>
<div class="page-heading cloud-vpcs-heading"><div><div class="cloud-vpc-title-row"><h1 id="cloud-vpc-members-title" tabindex="-1"></h1><span id="cloud-vpc-members-state" class="state-pill"></span></div><p>实例成员管理</p></div></div>
<dl id="cloud-vpc-network-summary" class="cloud-vpc-network-summary" aria-label="网络信息"></dl>
<div id="cloud-vpc-batch-status" aria-live="polite"></div>
<section id="cloud-vpcs-members" aria-labelledby="cloud-vpc-members-title"{if $cloud_vpc_view.page|default:'home' != 'members'} hidden{/if}>
<div class="page-heading cloud-vpcs-heading"><div><div class="cloud-vpc-title-row"><h1 id="cloud-vpc-members-title" tabindex="-1">{$cloud_vpc_view.current.name|default:''|escape:'html'}</h1><span id="cloud-vpc-members-state" class="state-pill {$cloud_vpc_view.current.state_class|default:''|escape:'html'}">{$cloud_vpc_view.current.state_label|default:''|escape:'html'}</span></div><p>实例成员管理</p></div></div>
<dl id="cloud-vpc-network-summary" class="cloud-vpc-network-summary" aria-label="网络信息">{if !empty($cloud_vpc_view.current)}<div><dt>地区</dt><dd>{$cloud_vpc_view.current.region_name|escape:'html'}</dd></div><div><dt>私网网段</dt><dd>{$cloud_vpc_view.current.cidr|escape:'html'}</dd></div><div><dt>默认网关</dt><dd>{$cloud_vpc_view.current.gateway|escape:'html'}</dd></div>{/if}</dl>
<div id="cloud-vpc-batch-status" aria-live="polite">{if !empty($cloud_vpc_view.current.batch)}<div class="cloud-vpc-batch-status"><div><strong>正在应用私网变更</strong><small>共 {$cloud_vpc_view.current.batch.total|default:0|escape:'html'} 台 · {$cloud_vpc_view.current.batch.succeeded|default:0|escape:'html'} 台成功。离开页面不会中断任务。</small></div></div>{/if}</div>
<div class="inventory-panel cloud-vpc-members-panel">
<nav class="cloud-vpc-tabs" aria-label="实例管理方式"><a id="cloud-vpc-members-link" href="#/">已加入实例</a><a id="cloud-vpc-join-link" href="#/">加入实例</a></nav>
<div id="cloud-vpc-instance-manager"></div>
<nav class="cloud-vpc-tabs" aria-label="实例管理方式"><a id="cloud-vpc-members-link" href="{$cloud_vpc_view.current.members_href|default:'/user/cloud/vpcs'|escape:'html'}"{if empty($cloud_vpc_view.joining)} aria-current="page"{/if}>已加入实例<span class="cloud-vpc-tab-count">{$cloud_vpc_view.member_count|default:0|escape:'html'}</span></a><a id="cloud-vpc-join-link" href="{$cloud_vpc_view.current.join_href|default:'/user/cloud/vpcs'|escape:'html'}"{if !empty($cloud_vpc_view.joining)} aria-current="page"{/if}>加入实例<span class="cloud-vpc-tab-count">{$cloud_vpc_view.joinable_count|default:0|escape:'html'}</span></a></nav>
<div id="cloud-vpc-instance-manager">
{if !empty($cloud_vpc_view.current)}
<section class="cloud-vpc-instance-manager{if $cloud_vpc_view.joining} joining{/if}" aria-label="{if $cloud_vpc_view.joining}加入实例{else}已加入实例{/if}">
<p class="cloud-vpc-list-hint">{if $cloud_vpc_view.joining}选择同地区实例,一次提交加入;私网 IP 自动分配。{else}勾选实例可批量移出当前 VPC。{/if}</p>
{if !empty($cloud_vpc_view.members)}
{if $cloud_vpc_view.joining}<label class="cloud-vpc-instance-search"><span class="sr-only">搜索实例或公网 IP</span><input type="search" class="cloud-vpc-instance-search-input" placeholder="搜索实例或公网 IP" aria-label="搜索实例或公网 IP" disabled/></label>{/if}
<table class="cloud-vpc-table cloud-vpc-member-table" aria-label="{if $cloud_vpc_view.joining}可加入实例{else}已加入实例{/if}">
<thead><tr><th scope="col"><label class="cloud-vpc-select-all"><input type="checkbox" disabled/><span>{if $cloud_vpc_view.joining}全选可加入实例{else}全选可移出实例{/if}</span></label></th><th scope="col">实例</th><th scope="col">公网 IPv4</th><th scope="col">{if $cloud_vpc_view.joining}私网分配{else}私网 IPv4{/if}</th><th scope="col">状态</th></tr></thead>
<tbody>{foreach $cloud_vpc_view.members as $instance}<tr class="cloud-vpc-instance-row">
<td class="cloud-vpc-instance-select" data-label="选择"><input type="checkbox" aria-label="选择 {$instance.name|escape:'html'}" disabled/></td>
<td class="cloud-vpc-instance-identity" data-label="实例"><a class="cloud-vpc-name-link" href="/user/cloud/instances/{$instance.id|escape:'html'}">{$instance.name|escape:'html'}</a></td>
<td class="cloud-vpc-table-address" data-label="公网 IPv4"><code>{$instance.public_ipv4|escape:'html'}</code></td>
<td class="cloud-vpc-table-address cloud-vpc-private-address" data-label="{if $cloud_vpc_view.joining}私网分配{else}私网 IPv4{/if}">{if $cloud_vpc_view.joining}<span>自动分配</span>{else}<code>{$instance.port.private_ip|default:'待分配'|escape:'html'}</code>{if !empty($instance.port.mac_address)}<details class="cloud-vpc-mac"><summary>MAC 地址</summary><code>{$instance.port.mac_address|escape:'html'}</code></details>{/if}{/if}</td>
<td class="cloud-vpc-instance-status" data-label="状态"><span class="state-pill {$instance.state_class|escape:'html'}">{$instance.state_label|escape:'html'}</span>{if !empty($instance.action_unavailable_reason)}<small>{$instance.action_unavailable_reason|escape:'html'}</small>{/if}</td>
</tr>{/foreach}</tbody>
</table>
<div class="cloud-vpc-batch-toolbar"><span role="status">已选择 0 台</span><button class="button button-primary" type="button" disabled>{if $cloud_vpc_view.joining}加入{else}移出{/if}所选实例</button></div>
{else}<div class="cloud-vpc-empty"><strong>{if $cloud_vpc_view.joining}暂无可加入的实例{else}尚未加入实例{/if}</strong><p>{if $cloud_vpc_view.joining}只显示同地区且尚未加入 VPC 的实例。{else}将同地区实例连接到这张私网。{/if}</p>{if !$cloud_vpc_view.joining}<a class="button button-outline" href="{$cloud_vpc_view.current.join_href|escape:'html'}">加入实例 →</a>{/if}</div>{/if}
</section>
{/if}
</div>
</div>
<div class="cloud-vpc-members-footer"><p id="cloud-vpc-members-note" class="cloud-vpc-footnote"></p><button id="cloud-vpc-delete" class="cloud-vpc-text-button danger" type="button">删除 VPC</button></div>
<div class="cloud-vpc-members-footer"><p id="cloud-vpc-members-note" class="cloud-vpc-footnote">{if !empty($cloud_vpc_view.joining)}加入后,同一 VPC 内的实例默认互通。{else}移出仅解除私网连接,实例和磁盘保留。{/if}</p><button id="cloud-vpc-delete" class="cloud-vpc-text-button danger" type="button" disabled>删除 VPC</button></div>
</section>
<section id="cloud-vpcs-missing" class="inventory-panel cloud-vpc-empty" aria-labelledby="cloud-vpc-missing-title" hidden><h1 id="cloud-vpc-missing-title" tabindex="-1">未找到这张 VPC</h1><p>网络可能已删除,或当前账户无法访问。可刷新后重试。</p><a class="button button-outline" href="#/">返回 VPC 列表</a></section>
<section id="cloud-vpcs-missing" class="inventory-panel cloud-vpc-empty" aria-labelledby="cloud-vpc-missing-title"{if $cloud_vpc_view.page|default:'home' != 'missing'} hidden{/if}><h1 id="cloud-vpc-missing-title" tabindex="-1">未找到这张 VPC</h1><p>网络可能已删除,或当前账户无法访问。可刷新后重试。</p><a class="button button-outline" href="/user/cloud/vpcs">返回 VPC 列表</a></section>
<dialog id="cloud-vpc-confirm" class="cloud-vpc-confirm" aria-labelledby="cloud-vpc-confirm-title" aria-describedby="cloud-vpc-confirm-note">
<form id="cloud-vpc-confirm-form" method="dialog">

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026103006' scope='global'}
{assign var=venix_asset_version value='2026103007' scope='global'}

@ -0,0 +1,126 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
const source = (await readFile(new URL('../public/cloud/app.js', import.meta.url), 'utf8'))
.replaceAll('import.meta.url', JSON.stringify('https://panel.example.test/cloud/app.js?v=fixture'))
.replaceAll('import(', 'loadModule(');
const tick = () => new Promise(resolve => setImmediate(resolve));
const deferred = () => {
let resolve;
const promise = new Promise(done => { resolve = done; });
return { promise, resolve };
};
async function start(taskModule, pageModule) {
const requested = [];
const nodes = new Map(['cloud-page-error', 'panel-task-state'].map(id => [id, { textContent: '', hidden: true }]));
vm.runInNewContext(source, {
URL,
document: { body: { dataset: { cloudPage: 'deploy' } }, getElementById: id => nodes.get(id) },
loadModule: async href => {
const path = new URL(href).pathname;
requested.push(path);
return path === '/cloud/task-center.js' ? taskModule() : pageModule();
},
});
await tick();
return { requested, nodes };
}
{
const task = deferred();
let pageReady = false, taskReady = false;
const test = await start(() => task.promise, () => ({ initialize() { pageReady = true; } }));
assert.equal(pageReady, true, 'A pending task-center module blocks the page.');
assert(test.requested.includes('/cloud/deploy.js'));
task.resolve({ initializeTaskCenter() { taskReady = true; } });
await tick();
assert.equal(taskReady, true);
}
{
let pageReady = false;
const test = await start(() => Promise.reject(new Error('fixture task download failure')),
() => ({ initialize() { pageReady = true; } }));
assert.equal(pageReady, true, 'A failed task-center download prevents page initialization.');
assert.equal(test.nodes.get('cloud-page-error').textContent, '');
assert.match(test.nodes.get('panel-task-state').textContent, /任务中心/);
}
{
let taskReady = false;
const test = await start(() => ({ initializeTaskCenter() { taskReady = true; } }),
() => ({ initialize: async () => { throw new Error('fixture page failure'); } }));
assert.equal(taskReady, true);
assert.equal(test.nodes.get('cloud-page-error').textContent, 'fixture page failure',
'An asynchronous page initialization error escapes the shared error handler.');
}
const runtime = await readFile(new URL('../public/cloud/runtime.js', import.meta.url), 'utf8');
const session = runtime.slice(runtime.indexOf('async function initializeSession('), runtime.indexOf('async function selectVmByApiId('));
{
const vpcs = await readFile(new URL('../public/cloud/vpcs.js', import.meta.url), 'utf8');
const initialize = vpcs.slice(vpcs.indexOf('export async function initialize()')).replace('export ', '');
const bootstrap = { user: { user_id: '7', csrf_token: 'fixture' }, items: [], instances: [], regions: [] };
let rendered = false;
const context = vm.createContext({ state: {}, readBootstrap: () => bootstrap,
applyCloudUser() {}, api() { throw Error('Unexpected first-paint session or library fetch'); },
byId: () => ({ addEventListener() {} }), apply() { rendered = true; },
setPageStatus() {}, bindBatchConfirmation() {}, createVpc() {}, routeChanged() {},
window: { addEventListener() {} }, location: { assign() {} }, showError(id, message) { throw Error(message); },
});
vm.runInContext(session + '\n' + initialize, context);
await vm.runInContext('initialize()', context);
assert.equal(rendered, true, 'VPC bootstrap requires an additional session or library request.');
}
{
const isos = await readFile(new URL('../public/cloud/iso-images.js', import.meta.url), 'utf8');
const apply = isos.slice(isos.indexOf('function applyIsoPayload('), isos.indexOf('function taskFailureMessage('));
const initialize = isos.slice(isos.indexOf('export async function initialize()')).replace('export ', '');
const bootstrap = { user: { user_id: '7' }, isos: [{ id: 'iso-one' }], can_import: false,
active_import_job: { task_id: '41', completed: false } };
const pageState = { isos: [], importObserver: null };
let observed = '', rendered = false;
const context = vm.createContext({ state: {}, pageState, readBootstrap: () => bootstrap,
applyCloudUser() {}, api() { throw Error('Unexpected initial ISO request'); },
byId: () => ({ addEventListener() {} }), bindPageCleanup() {},
renderIsos() { rendered = true; }, taskUrl: receipt => receipt.status_url,
setImportStatus() {}, updateImportAvailability() {}, watchImport(receipt) { observed = receipt.task_id; },
importIso() {}, window: { addEventListener() {} }, location: { assign() {} },
showError(id, message) { throw Error(message); },
});
vm.runInContext(session + '\n' + apply + '\n' + initialize, context);
await vm.runInContext('initialize()', context);
assert.equal(rendered, true);
assert.equal(pageState.canImport, false);
assert.equal(observed, '41', 'ISO hydration failed to observe the original in-flight task.');
}
{
const sales = runtime.slice(runtime.indexOf('function saleRegions('), runtime.indexOf('function setDeploymentStepEnabled('));
const pricing = runtime.slice(runtime.indexOf('function selectedSaleOffer('), runtime.indexOf('function updateCreateAvailability('));
const openCreate = runtime.slice(runtime.indexOf('async function openCreate('), runtime.indexOf('async function loadGlobalTemplates('));
const nodes = new Map();
const byId = id => {
if (!nodes.has(id)) nodes.set(id, { value: '', checked: false, dataset: {}, classList: { toggle() {} }, addEventListener() {} });
return nodes.get(id);
};
byId('vm-automatic-backup').checked = true;
const bootstrap = { regions: [{ id: 1 }], lines: [{ id: 1, region_id: 1, is_default: true }],
offers: [{ id: 1, region_id: 1, line_id: 1, currency: 'USD', sellable: true, price: '10.00', backup_price: '2.00' }],
default_offer_id: 1, templates: [], ssh_keys: [] };
const context = vm.createContext({ state: { regions: [], lines: [], offers: [], templates: [], selectedKeys: {} }, byId,
bootstrapItems: (value, key) => value[key] || [], showError() {},
renderRegionPicker() {}, renderLinePicker() {}, renderOfferPicker() {}, renderTemplateCatalog() {}, renderKeyCards() {},
setDeploymentStepEnabled() {}, updateCreateAvailability() {}, formatUsd: value => `$${Number(value).toFixed(2)} USD`,
});
vm.runInContext(sales + '\n' + pricing + '\n' + openCreate, context);
context.bootstrap = bootstrap;
await vm.runInContext('openCreate(bootstrap)', context);
assert.equal(byId('vm-automatic-backup').checked, true, 'Hydration clears a backup choice made while the module was loading.');
assert.equal(byId('vm-order-total-price').textContent, '$12.00 USD');
}
console.log('Independent page/task boot, embedded VPC/ISO hydration, original task resumption and deployment selection preservation passed.');

@ -0,0 +1,129 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudUserPageView;
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
if (error_reporting() & $severity) throw new ErrorException($message, 0, $severity, $file, $line);
return false;
});
$assert = static function (bool $condition, string $message): void {
if (!$condition) throw new RuntimeException($message);
};
$smarty = new Smarty();
$compileDir = sys_get_temp_dir() . '/virt-user-first-paint-' . bin2hex(random_bytes(6));
mkdir($compileDir);
$smarty->setCompileDir($compileDir);
$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
$render = static function (string $page, array $values) use ($smarty): DOMXPath {
$smarty->clearAllAssign();
$smarty->assign('cloud_vm_bootstrap_json', '{}');
$smarty->assign($values);
$html = $smarty->fetch('cloud/pages/' . $page . '.tpl');
$dom = new DOMDocument();
$old = libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="UTF-8">' . $html);
libxml_clear_errors();
libxml_use_internal_errors($old);
return new DOMXPath($dom);
};
$one = static function (DOMXPath $xpath, string $id): DOMElement {
$node = $xpath->query('//*[@id="' . $id . '"]')->item(0);
if (!$node instanceof DOMElement) throw new RuntimeException('Missing first-paint element ' . $id);
return $node;
};
$unsafe = '<img src=x onerror=alert(1)>';
$backup = ['id' => 9, 'name' => $unsafe, 'state' => 'ready',
'source_instance' => ['id' => '7', 'name' => 'vm-seven', 'status' => 'active'],
'created_at' => 1793404800, 'consistency' => 'filesystem',
'object_size_bytes' => 1024, 'virtual_size_bytes' => 25 * 1073741824,
'can_restore_original' => false, 'can_promote' => true];
$payload = ['items' => [$backup], 'pagination' => ['page' => 2, 'total' => 41, 'total_pages' => 3]];
$xpath = $render('backups', ['cloud_backup_view' => CloudUserPageView::backups($payload)]);
$assert(str_contains($one($xpath, 'cloud-backups-list')->textContent, $unsafe)
&& $xpath->query('//img')->length === 0, 'Backup first paint is empty or contains unescaped names.');
$assert($one($xpath, 'cloud-backups-count')->textContent === '41 个'
&& $one($xpath, 'cloud-backups-page')->textContent === '第 2 / 3 页'
&& $one($xpath, 'cloud-backups-status')->hasAttribute('hidden'), 'Backup count, page or loaded state is incorrect.');
$assert($xpath->query('//a[contains(@href,"setting=automatic_backup")]')->length === 0,
'First paint invented original-restore permission for an ineligible backup.');
$backup['can_restore_original'] = true;
$xpath = $render('backups', ['cloud_backup_view' => CloudUserPageView::backups(['items' => [$backup]])]);
$assert($xpath->query('//a[contains(@href,"/instances/7?tab=settings")]')->length === 1, 'Eligible original restore link is missing.');
$key = str_repeat('a', 32);
$snapshot = ['snapshot_key' => $key, 'name' => 'snapshot-before-js', 'state' => 'ready',
'source_instance' => ['id' => '7', 'name' => 'vm-seven'], 'created_at' => 1793404800,
'can_create_instance' => true, 'can_delete' => false, 'active_invoice_count' => 1];
$xpath = $render('cloud-snapshots', ['cloud_snapshot_view' => CloudUserPageView::cloudSnapshots(['items' => [$snapshot]])]);
$assert(str_contains($one($xpath, 'cloud-snapshots-list')->textContent, 'snapshot-before-js')
&& $xpath->query('//a[@href="/user/cloud/deploy?cloud_snapshot=' . $key . '"]')->length === 1,
'Cloud snapshot first paint lost its name or deployment link.');
$assert($xpath->query('//button[@title="存在待支付账单,请先支付或等待账单失效后再删除。" and @disabled]')->length === 1,
'Snapshot first paint lost pending-invoice deletion protection.');
$vpc = ['vpc_key' => $key, 'name' => 'vpc-before-js', 'region_id' => 1,
'region_name' => '香港', 'cidr' => '10.0.1.0/24', 'gateway' => '10.0.1.1', 'state' => 'active', 'port_count' => 1];
$member = ['id' => '7', 'name' => 'vm-member', 'region_id' => 1, 'public_ipv4' => '192.0.2.7',
'port' => ['vpc_key' => $key, 'state' => 'attached', 'private_ip' => '10.0.1.2', 'mac_address' => '02:11:22:33:44:55']];
$candidate = ['id' => '8', 'name' => 'vm-candidate', 'region_id' => 1, 'public_ipv4' => '192.0.2.8', 'port' => null, 'can_attach' => true];
$elsewhere = $candidate; $elsewhere['id'] = '99'; $elsewhere['name'] = 'other-region'; $elsewhere['region_id'] = 2;
$library = ['items' => [$vpc], 'regions' => [['id' => 1, 'name' => '香港']],
'instances' => [$member, $candidate, $elsewhere], 'used' => 1, 'maximum' => 16];
foreach ([['query' => [], 'page' => 'home'], ['query' => ['view' => 'create'], 'page' => 'create'],
['query' => ['vpc' => $key], 'page' => 'members'],
['query' => ['vpc' => $key, 'view' => 'join'], 'page' => 'members'],
['query' => ['vpc' => str_repeat('b', 32)], 'page' => 'missing'],
['query' => ['vpc' => ['invalid']], 'page' => 'missing']] as $case) {
$view = CloudUserPageView::vpcs($library, $case['query']);
$xpath = $render('vpcs', ['cloud_vpc_view' => $view]);
$assert(!$one($xpath, 'cloud-vpcs-' . $case['page'])->hasAttribute('hidden'), 'VPC initial route is hidden before JavaScript.');
$assert($one($xpath, 'cloud-vpcs-quota')->textContent === '1 / 16 个', 'VPC first paint resets the quota to zero.');
if ($case['page'] === 'home') $assert(str_contains($one($xpath, 'cloud-vpcs-list')->textContent, 'vpc-before-js'), 'VPC list is empty.');
if ($case['page'] === 'create') $assert($xpath->query('//select[@id="cloud-vpc-region"]/option[@value="1"]')->length === 1, 'VPC regions wait for JavaScript.');
if ($case['page'] === 'members') {
$text = $one($xpath, 'cloud-vpc-instance-manager')->textContent;
$joining = ($case['query']['view'] ?? '') === 'join';
$assert(str_contains($text, $joining ? 'vm-candidate' : 'vm-member')
&& !str_contains($text, 'other-region')
&& str_contains($text, $joining ? '192.0.2.8' : '10.0.1.2'), 'VPC members or addresses do not match the requested view.');
}
}
$deploy = ['cloud_deploy_default_region_id' => 1, 'cloud_deploy_default_line_id' => 1,
'cloud_deploy_default_offer_id' => 1, 'cloud_deploy_lines_enabled' => false,
'cloud_deploy_regions' => [['id' => 1, 'name' => '香港']], 'cloud_deploy_lines' => [],
'cloud_deploy_offers' => [['id' => 1, 'name' => 'plan', 'region_id' => 1, 'line_id' => 1,
'sellable' => true, 'cpu_cores' => 1, 'memory_mib' => 1024, 'disk_gib' => 25,
'traffic_gib' => 1024, 'traffic_tib' => '1']], 'cloud_deploy_template_groups' => [],
'cloud_deploy_ssh_keys' => [], 'cloud_deploy_bootstrap_json' => '{}',
'cloud_deploy_price' => '$10.00 USD', 'cloud_deploy_backup_price' => '$2.00 USD', 'cloud_deploy_snapshot' => null];
$xpath = $render('deploy', $deploy);
$assert(!$one($xpath, 'vm-order-summary')->hasAttribute('hidden')
&& $one($xpath, 'vm-order-total-price')->textContent === '$10.00 USD'
&& !$one($xpath, 'vm-automatic-backup')->hasAttribute('disabled'), 'Selected plan pricing or backup availability waits for JavaScript.');
$deploy['cloud_deploy_snapshot'] = ['snapshot_key' => $key, 'name' => $unsafe];
$xpath = $render('deploy', $deploy);
$assert(!$one($xpath, 'vm-cloud-snapshot-source')->hasAttribute('hidden')
&& $one($xpath, 'vm-template-field')->hasAttribute('hidden')
&& $one($xpath, 'vm-cloud-fields')->hasAttribute('hidden')
&& $one($xpath, 'vm-root-password')->hasAttribute('disabled')
&& $one($xpath, 'vm-cloud-snapshot-key')->getAttribute('value') === $key
&& $xpath->query('//img')->length === 0, 'Snapshot deployment first paint shows normal installation controls or unsafe names.');
$xpath = $render('isos', ['cloud_iso_view' => CloudUserPageView::isos(['isos' => [
['id' => 'iso', 'name' => 'iso-before-js', 'size_bytes' => 1024, 'sha256' => str_repeat('a', 64), 'can_delete' => true],
]])]);
$assert(str_contains($one($xpath, 'user-iso-list')->textContent, 'iso-before-js'), 'Personal ISO library waits for JavaScript.');
$xpath = $render('detail', ['cloud_vm_view' => ['can_operate' => true, 'can_delete' => true],
'cloud_detail_has_ssh_keys' => false, 'cloud_detail_no_ssh_keys' => true]);
$assert($xpath->query('//*[@id="vm-detail-primary-actions"]/button[@disabled and @class="row-button"]')->length === 4,
'Instance daily actions wait for JavaScript or use different first-paint styling.');
$xpath = $render('detail', ['cloud_vm_view' => ['can_operate' => false, 'can_delete' => false],
'cloud_detail_has_ssh_keys' => false, 'cloud_detail_no_ssh_keys' => true]);
$assert($xpath->query('//*[@id="vm-detail-primary-actions"]/button')->length === 0,
'Read-only first paint exposes owner power controls.');
echo "User backup, cloud-snapshot, VPC routes, deployment pricing/source, ISO and instance-action first paints passed without JavaScript.\n";

@ -148,6 +148,16 @@ const mutations = t => t.calls.filter(call => call.method);
const plain = value => JSON.parse(JSON.stringify(value));
async function select(t, id) { const node = control(t, `select-${id}`); node.checked = true; await node.fire('change'); }
async function submit(t) { await control(t, 'submit-selection').fire('click'); }
for (const [query, page, joining] of [
['?view=create', 'create', false], [`?vpc=${A}`, 'members', false],
[`?vpc=${A}&view=join`, 'members', true], ['?vpc=invalid', 'missing', false],
['?vpc[]=invalid', 'missing', false], ['?view=join', 'missing', false],
]) {
const t = await setup(query);
assert.equal(t.nodes.get(`cloud-vpcs-${page}`).hidden, false, `Query route is not hydrated: ${query}`);
if (page === 'members') assert.equal(t.nodes.get('cloud-vpc-instance-manager').querySelector('section').classList.contains('joining'), joining);
assert.equal(t.calls.length, 0, 'A valid embedded library triggered an extra list request.');
}
{
const t = await setup();
assert.equal(t.nodes.get('cloud-vpcs-home').hidden, false);
@ -218,7 +228,7 @@ async function submit(t) { await control(t, 'submit-selection').fire('click'); }
assert.deepEqual(plain(request.body), { action: 'attach', instance_ids: [3, 4, 5, 6, 7], confirm_restart: true });
assert.match(request.headers['Idempotency-Key'], /^[a-zA-Z0-9_.-]{16,128}$/);
assert.equal(request.expectedStatus, 202); assert.equal(request.requireTaskReceipt, true);
assert.equal(t.location.hash, href(A));
assert.equal(t.location.search, `?vpc=${A}`);
assert.equal(t.observations.length, 1);
await t.go('#/'); await t.go(`${href(B)}/join`);
assert.equal(t.observations.length, 1, 'Navigation must not duplicate observers');
@ -367,7 +377,7 @@ async function submit(t) { await control(t, 'submit-selection').fire('click'); }
});
t.nodes.get('cloud-vpc-name').value = 'new-vpc'; t.nodes.get('cloud-vpc-region').value = '1';
await t.nodes.get('cloud-vpc-create-form').fire('submit');
assert.equal(t.location.hash, `${href(C)}/join`);
assert.equal(t.location.search, `?vpc=${C}&view=join`);
assert.equal(mutations(t).length, 1, 'Creation must not attach or restart instances');
assert.deepEqual(plain(mutations(t)[0].body), { name: 'new-vpc', region_id: 1 });
}
@ -376,7 +386,8 @@ async function submit(t) { await control(t, 'submit-selection').fire('click'); }
t.respond(async (url, options) => options.method === 'DELETE' ? { deleted: true }
: { ...t.data(), items: t.data().items.filter(item => item.vpc_key !== B), used: 1 });
await t.nodes.get('cloud-vpc-delete').fire('click');
assert.equal(t.location.hash, '#/');
assert.equal(t.location.pathname, '/user/cloud/vpcs');
assert.equal(t.location.search, '');
assert.equal(mutations(t)[0].url, `/api/v1/vpcs/${B}`);
}
{

@ -303,7 +303,7 @@ $assert(str_contains($reinstallTemplate, 'id="reinstall-template-catalog"')
$requiredMarker = '<span class="deployment-required-mark" aria-hidden="true">*</span><span class="sr-only">(必选)</span>';
$assert(str_contains($deployTemplate, 'id="deploy-region-title">选择地区' . $requiredMarker . '</h2>')
&& str_contains($deployTemplate, 'id="deploy-offer-title">选择实例规格' . $requiredMarker . '</h2>')
&& str_contains($deployTemplate, 'id="deploy-source-title">选择系统镜像' . $requiredMarker . '</h2>')
&& str_contains($deployTemplate, '云快照来源{else}选择系统镜像{/if}' . $requiredMarker . '</h2>')
&& substr_count($deployTemplate, $requiredMarker) === 3
&& str_contains($baseStyles, '.deployment-step-heading h2 .deployment-required-mark{margin-left:4px;color:#dc5965;font-size:11px;vertical-align:super}'),
'Region, offer and system headings must expose compact required markers.');

Loading…
Cancel
Save