From ebf9b58eba2ca7456fcb7475b689afd6852d8f9e Mon Sep 17 00:00:00 2001 From: codex Date: Sat, 7 Nov 2026 22:06:30 +0800 Subject: [PATCH] fix(i18n): localize user operation titles --- web/app/Services/Cloud/CloudJobService.php | 4 +- .../Services/Cloud/CloudOperationCatalog.php | 43 ++++++++++++++ web/public/cloud/detail.js | 18 +++++- web/public/cloud/operation-presentation.js | 19 +++++++ web/public/cloud/task-center.js | 18 +++--- .../entries/detail-reinstall.entries.php | 17 ++++++ web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/CloudAssetVersionContractTest.php | 2 +- ...CloudOperationPresentationBehaviorTest.mjs | 57 +++++++++++++++++++ .../CloudOperationUserCopyContractTest.php | 47 +++++++++++++++ web/tests/CloudSnapshotWorkflowTest.php | 33 +++++++++-- web/tests/CloudTaskObserverBehaviorTest.mjs | 14 ++++- web/tests/UserCopyCompleteCoverageTest.php | 1 + web/tests/UserCopyManifestContractTest.php | 2 +- web/tests/VirtualizationAssetsTest.php | 14 +++-- 15 files changed, 265 insertions(+), 26 deletions(-) create mode 100644 web/public/cloud/operation-presentation.js create mode 100644 web/tests/CloudOperationPresentationBehaviorTest.mjs create mode 100644 web/tests/CloudOperationUserCopyContractTest.php diff --git a/web/app/Services/Cloud/CloudJobService.php b/web/app/Services/Cloud/CloudJobService.php index ce319d36..2fbbf0de 100644 --- a/web/app/Services/Cloud/CloudJobService.php +++ b/web/app/Services/Cloud/CloudJobService.php @@ -2886,8 +2886,9 @@ final class CloudJobService && in_array((string) $job->outcome, ['succeeded', 'failed'], true); $action = self::action($job); + $settingsFields = self::settingsFields($job); $labels = CloudOperationCatalog::labels((string) $job->kind, $action, - self::settingsFields($job)); + $settingsFields); $base = [ 'id' => (string) $job->id, 'operation_id' => (string) $job->operation_id, @@ -2899,6 +2900,7 @@ final class CloudJobService 'action' => $action, 'kind_label' => $labels['kind_label'], 'action_label' => $labels['action_label'], + 'operation_copy_keys' => $labels['copy_keys'], ]; if (!$completed) { $recovery = self::recoveryPresentation($job, $administrator); diff --git a/web/app/Services/Cloud/CloudOperationCatalog.php b/web/app/Services/Cloud/CloudOperationCatalog.php index 3771b312..dac89035 100644 --- a/web/app/Services/Cloud/CloudOperationCatalog.php +++ b/web/app/Services/Cloud/CloudOperationCatalog.php @@ -11,6 +11,8 @@ namespace App\Services\Cloud; */ final class CloudOperationCatalog { + private const COPY_PREFIX = 'common.operation.'; + private const KINDS = [ 'create' => '创建实例', 'action' => '电源操作', @@ -123,6 +125,46 @@ final class CloudOperationCatalog return $options; } + /** Source-language copy owned by the canonical operation catalog. */ + public static function copySources(): array + { + $sources = [self::COPY_PREFIX . 'list_separator' => '、']; + foreach (self::KINDS as $kind => $label) { + $sources[self::COPY_PREFIX . 'kind.' . $kind] = $label; + } + foreach (self::POWER_ACTIONS as $action => $label) { + $sources[self::COPY_PREFIX . 'action.' . $action] = $label; + } + foreach (self::INSTANCE_SETTING_FIELDS as $field => $label) { + $sources[self::COPY_PREFIX . 'setting.' . $field] = $label; + } + return $sources; + } + + /** Stable UserCopy keys for one job; no localized label crosses this seam. */ + public static function copyKeys(?string $kind, ?string $action = null, + array $settingsFields = []): array + { + $kind = (string) $kind; + if ($kind === 'action' && $action !== null + && self::isPowerAction($action)) { + return [self::COPY_PREFIX . 'action.' . $action]; + } + if ($kind === 'instance_settings') { + $keys = []; + foreach (self::INSTANCE_SETTING_FIELDS as $field => $_label) { + if (in_array($field, $settingsFields, true)) { + $keys[] = self::COPY_PREFIX . 'setting.' . $field; + } + } + if ($keys !== []) { + return $keys; + } + } + return array_key_exists($kind, self::KINDS) + ? [self::COPY_PREFIX . 'kind.' . $kind] : []; + } + public static function isPowerAction(string $action): bool { return array_key_exists($action, self::POWER_ACTIONS); @@ -174,6 +216,7 @@ final class CloudOperationCatalog return [ 'kind_label' => self::kindLabel($kind, $action, $settingsFields), 'action_label' => self::actionLabel($action), + 'copy_keys' => self::copyKeys($kind, $action, $settingsFields), ]; } } diff --git a/web/public/cloud/detail.js b/web/public/cloud/detail.js index f4be8610..2af16426 100644 --- a/web/public/cloud/detail.js +++ b/web/public/cloud/detail.js @@ -7,10 +7,11 @@ function versionedModuleUrl(path) { return url.href; } -const [taskObserver, runtime, firewallInput] = await Promise.all([ +const [taskObserver, runtime, firewallInput, operationPresentation] = await Promise.all([ import(versionedModuleUrl('./task-observer.js')), import(versionedModuleUrl('/cloud/runtime.js')), import(versionedModuleUrl('./firewall-input.js')), + import(versionedModuleUrl('./operation-presentation.js')), ]); const { announceTaskAccepted, normalizeTask, observeTask, @@ -26,6 +27,7 @@ const { stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp, } = runtime; const { firewallPresetRules, validFirewallCidr } = firewallInput; +const { operationTitle } = operationPresentation; const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false); const i18n = globalThis.VenixUserCopy; const t = (key, parameters = {}) => i18n.text(key, parameters); @@ -194,7 +196,11 @@ function operationLogElement(tag, className, value = '') { } function operationKindLabel(entry) { - return entry?.kind_label || entry?.action_label || entry?.display?.kind || t('instance_detail.operation_log.category.instance'); + return operationTitle( + entry, + t, + 'instance_detail.operation_log.category.instance', + ); } function operationStatusInfo(value) { @@ -1207,7 +1213,13 @@ function renderVmSnapshots(vmId, payload = snapshotPayload) { } else if (snapshotMutation) { setSnapshotStatus(t('instance_detail.snapshots.task_running', { action: snapshotActionLabel(snapshotMutation.action) })); } else if (busy) { - setSnapshotStatus(t('instance_detail.snapshots.other_task_running', { task: payload?.active_job?.kind_label || t('instance_detail.operation_log.category.other') }), 'warning'); + setSnapshotStatus(t('instance_detail.snapshots.other_task_running', { + task: operationTitle( + payload?.active_job, + t, + 'instance_detail.operation_log.category.other', + ), + }), 'warning'); } else if (operationsUnavailable) { setSnapshotStatus(t('instance_detail.snapshot.error.operation_not_allowed'), 'warning'); } diff --git a/web/public/cloud/operation-presentation.js b/web/public/cloud/operation-presentation.js new file mode 100644 index 00000000..a5ef04e5 --- /dev/null +++ b/web/public/cloud/operation-presentation.js @@ -0,0 +1,19 @@ +const COPY_KEY_PATTERN = /^common\.operation\.(?:kind|action|setting)\.[a-z0-9_]+$/; + +/** Render a user-facing operation title exclusively from stable copy keys. */ +export function operationTitle(entry, text, fallbackKey) { + const translate = typeof text === 'function' ? text : () => ''; + const keys = Array.isArray(entry?.operation_copy_keys) + ? entry.operation_copy_keys.filter(key => ( + typeof key === 'string' && COPY_KEY_PATTERN.test(key) + )) : []; + const labels = keys.map(key => String(translate(key) || '').trim()) + .filter((label, index) => label && label !== keys[index]); + if (labels.length) { + const separator = String( + translate('common.operation.list_separator') || ', ', + ); + return labels.join(separator); + } + return String(translate(fallbackKey) || '').trim(); +} diff --git a/web/public/cloud/task-center.js b/web/public/cloud/task-center.js index f100ae68..281e0a95 100644 --- a/web/public/cloud/task-center.js +++ b/web/public/cloud/task-center.js @@ -7,9 +7,14 @@ function versionedModuleUrl(path) { return url.href; } +const [taskObserver, operationPresentation] = await Promise.all([ + import(versionedModuleUrl('./task-observer.js')), + import(versionedModuleUrl('./operation-presentation.js')), +]); const { normalizeTask, recoveryTaskFailureNotice, resolvedTaskFailureNotice, -} = await import(versionedModuleUrl('./task-observer.js')); +} = taskObserver; +const { operationTitle } = operationPresentation; const REFRESH_MS = 10000; // Covers the longest server-side absolute task deadline (145 minutes) while @@ -151,12 +156,11 @@ async function markPresentedRead(items) { } export function taskTitle(task) { - for (const value of [ - task?.kind_label, task?.action_label, task?.title, task?.label, task?.summary, - ]) { - if (typeof value === 'string' && value.trim()) return value.trim(); - } - return i18n.text('common.tasks.fallback_title'); + return operationTitle( + task, + (key, parameters = {}) => i18n.text(key, parameters), + 'common.tasks.fallback_title', + ); } function statusText(task) { diff --git a/web/resources/user-copy/entries/detail-reinstall.entries.php b/web/resources/user-copy/entries/detail-reinstall.entries.php index 7ca77fe4..3b28db3d 100644 --- a/web/resources/user-copy/entries/detail-reinstall.entries.php +++ b/web/resources/user-copy/entries/detail-reinstall.entries.php @@ -1,5 +1,7 @@ $source) { + $entries[] = $entry( + $key, + 'common', + 'cloud.detail', + $source, + 'label', + [], + 'required', + false, + null, + 'admin', + 'cloud.detail' + ); +} foreach ($detailSources as $key => $source) { $entries[] = $entry( $key, diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 36665373..a5f29608 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026110714' scope='global'} +{assign var=venix_asset_version value='2026110715' scope='global'} diff --git a/web/tests/CloudAssetVersionContractTest.php b/web/tests/CloudAssetVersionContractTest.php index d786c73b..9dd97036 100644 --- a/web/tests/CloudAssetVersionContractTest.php +++ b/web/tests/CloudAssetVersionContractTest.php @@ -15,7 +15,7 @@ $assert = static function (bool $condition, string $message): void { }; $assert(is_string($assets) - && str_contains($assets, "venix_asset_version value='2026110714'") + && str_contains($assets, "venix_asset_version value='2026110715'") && is_string($cloudShell) && str_contains($cloudShell, '/cloud/app.js?v={$venix_asset_version}'), 'The cloud application entry must use the shared Venix asset version.'); diff --git a/web/tests/CloudOperationPresentationBehaviorTest.mjs b/web/tests/CloudOperationPresentationBehaviorTest.mjs new file mode 100644 index 00000000..2dabda68 --- /dev/null +++ b/web/tests/CloudOperationPresentationBehaviorTest.mjs @@ -0,0 +1,57 @@ +import assert from 'node:assert/strict'; + +const presentationUrl = new URL( + '../public/cloud/operation-presentation.js', + import.meta.url, +); +const { operationTitle } = await import( + `${presentationUrl.href}?test=${Date.now()}` +); + +const translations = { + 'common.operation.kind.service_compensation': 'Instance Availability Compensation', + 'common.operation.action.shutdown': 'Shut Down', + 'common.operation.kind.firewall_apply': 'Apply Firewall', + 'common.operation.setting.hostname': 'Change Hostname', + 'common.operation.setting.password': 'Reset root Password', + 'common.operation.list_separator': ', ', + 'common.tasks.fallback_title': 'Background Task', + 'instance_detail.operation_log.category.instance': 'Instance Operation', +}; +const text = key => translations[key] || key; + +for (const [entry, expected] of [ + [{ + kind: 'service_compensation', kind_label: '实例可用时间补偿', + operation_copy_keys: ['common.operation.kind.service_compensation'], + }, 'Instance Availability Compensation'], + [{ + kind: 'action', action: 'shutdown', kind_label: '关机', action_label: '关机', + operation_copy_keys: ['common.operation.action.shutdown'], + }, 'Shut Down'], + [{ + kind: 'firewall_apply', kind_label: '应用防火墙', + operation_copy_keys: ['common.operation.kind.firewall_apply'], + }, 'Apply Firewall'], +]) { + const actual = operationTitle( + entry, + text, + 'instance_detail.operation_log.category.instance', + ); + assert.equal(actual, expected); + assert.doesNotMatch(actual, /[\u3400-\u9fff]/u); +} + +assert.equal(operationTitle({ + kind: 'instance_settings', kind_label: '修改主机名、重置 root 密码', + operation_copy_keys: [ + 'common.operation.setting.hostname', + 'common.operation.setting.password', + ], +}, text, 'instance_detail.operation_log.category.instance'), +'Change Hostname, Reset root Password'); + +assert.equal(operationTitle({ + kind: 'unknown_internal_job', kind_label: '未知内部任务', +}, text, 'common.tasks.fallback_title'), 'Background Task'); diff --git a/web/tests/CloudOperationUserCopyContractTest.php b/web/tests/CloudOperationUserCopyContractTest.php new file mode 100644 index 00000000..d5ff9d26 --- /dev/null +++ b/web/tests/CloudOperationUserCopyContractTest.php @@ -0,0 +1,47 @@ + $source) { + $entry = $entries[$copyKey] ?? null; + $assert(is_array($entry) + && ($entry['source'] ?? null) === $source + && ($entry['scope'] ?? null) === 'common' + && ($entry['page'] ?? null) === 'cloud.detail' + && ($entry['editor_surface'] ?? null) === 'admin', + 'Operation copy entry is absent or has the wrong runtime/editor owner: ' + . $copyKey); +} + +foreach (array_keys(CloudOperationCatalog::kinds()) as $kind) { + $keys = CloudOperationCatalog::copyKeys($kind); + $assert($keys !== [] && isset($entries[$keys[0]]), + 'Operation kind lacks a stable UserCopy key: ' . $kind); +} + +$assert( + CloudOperationCatalog::copyKeys('action', 'shutdown') + === ['common.operation.action.shutdown'] + && CloudOperationCatalog::copyKeys('instance_settings', null, [ + 'hostname', 'password', + ]) === [ + 'common.operation.setting.hostname', + 'common.operation.setting.password', + ] + && CloudOperationCatalog::copyKeys('unknown_internal_job') === [], + 'Operation presentation keys do not fail closed around stable catalog codes.' +); diff --git a/web/tests/CloudSnapshotWorkflowTest.php b/web/tests/CloudSnapshotWorkflowTest.php index a2335c6f..d5ca9a06 100644 --- a/web/tests/CloudSnapshotWorkflowTest.php +++ b/web/tests/CloudSnapshotWorkflowTest.php @@ -350,7 +350,12 @@ namespace { && !array_key_exists('settings_fields', $hostnameSettingsPayload['body'] ?? []) && CloudJobService::display($settingsWithSnapshot)['kind_label'] - === '修改主机名', + === '修改主机名' + && CloudJobService::display( + $settingsWithSnapshot + )['operation_copy_keys'] === [ + 'common.operation.setting.hostname', + ], 'A ready snapshot blocked settings or hostname task presentation was not persisted safely.'); $terminalize($settingsWithSnapshot, 'failed', false, true); $legacyHostnamePayload = $hostnameSettingsPayload; @@ -379,7 +384,12 @@ namespace { && !array_key_exists('root_password', $passwordSafePayload['body'] ?? []) && CloudJobService::display($passwordSettings)['kind_label'] - === '重置 root 密码', + === '重置 root 密码' + && CloudJobService::display( + $passwordSettings + )['operation_copy_keys'] === [ + 'common.operation.setting.password', + ], 'Password settings lost their safe detail label or retained the password.'); $legacyPasswordPayload = $passwordSettingsPayload; unset($legacyPasswordPayload['settings_fields']); @@ -403,7 +413,12 @@ namespace { ); $assert($legacyPasswordActiveLabel === '重置 root 密码' && CloudJobService::display($legacyPassword)['kind_label'] - === '实例设置', + === '实例设置' + && CloudJobService::display( + $legacyPassword + )['operation_copy_keys'] === [ + 'common.operation.kind.instance_settings', + ], 'Legacy settings labels were guessed after secret redaction.'); $sshBlob = pack('N', strlen('ssh-ed25519')) . 'ssh-ed25519' @@ -440,7 +455,14 @@ namespace { $assert(($multiSettingsPayload['settings_fields'] ?? null) === ['hostname', 'password', 'ssh_key'] && CloudJobService::display($multiSettings)['kind_label'] - === '修改主机名、重置 root 密码、更新 SSH 公钥', + === '修改主机名、重置 root 密码、更新 SSH 公钥' + && CloudJobService::display( + $multiSettings + )['operation_copy_keys'] === [ + 'common.operation.setting.hostname', + 'common.operation.setting.password', + 'common.operation.setting.ssh_key', + ], 'Multi-field settings lost their stable order or detailed presentation.'); $terminalize($multiSettings, 'failed', false, true); @@ -681,7 +703,8 @@ namespace { CloudJobService::operationLogs($instance, 1, 50)['items'], 'id' ); $assert(CloudOperationCatalog::instanceLogKinds() === [ - 'action', 'reinstall', 'instance_settings', 'network_change', + 'action', 'reinstall', 'instance_settings', 'service_compensation', + 'network_change', 'instance_upgrade', 'firewall_apply', 'snapshot_create', 'snapshot_restore', 'snapshot_delete', 'backup_create', 'backup_workspace_cleanup', 'backup_restore', 'backup_recover', diff --git a/web/tests/CloudTaskObserverBehaviorTest.mjs b/web/tests/CloudTaskObserverBehaviorTest.mjs index b5024194..ec700033 100644 --- a/web/tests/CloudTaskObserverBehaviorTest.mjs +++ b/web/tests/CloudTaskObserverBehaviorTest.mjs @@ -16,6 +16,10 @@ const copyFixture = { 'common.tasks.duration.minute': '{count} 分钟', 'common.tasks.duration.second': '{count} 秒', 'common.tasks.fallback_title': '后台任务', + 'common.operation.list_separator': '、', + 'common.operation.kind.instance_settings': '实例设置', + 'common.operation.setting.password': '重置 root 密码', + 'common.operation.action.start': '开机', }; globalThis.VenixUserCopy = { locale: 'zh-CN', @@ -476,19 +480,21 @@ const protocolFailure = task => { assert.equal(taskDurationText(100, undefined), ''); } -// Task titles must use the server-owned Chinese presentation label. Internal -// protocol identifiers are useful for diagnostics, but must never leak into -// the ordinary drawer title when the label is absent or malformed. +// Task titles use server-owned stable copy keys. Localized PHP labels and +// internal protocol identifiers must never leak into the ordinary drawer. { assert.equal(taskTitle({ kind: 'instance_settings', kind_label: '实例设置', + operation_copy_keys: ['common.operation.kind.instance_settings'], }), '实例设置'); assert.equal(taskTitle({ kind: 'instance_settings', kind_label: '重置 root 密码', action: 'instance_settings', action_label: null, + operation_copy_keys: ['common.operation.setting.password'], }), '重置 root 密码'); assert.equal(taskTitle({ kind: 'action', kind_label: '开机', action: 'start', action_label: '开机', + operation_copy_keys: ['common.operation.action.start'], }), '开机'); assert.equal(taskTitle({ kind: 'unknown_internal_job', action: 'unknown_internal_action', type: 'legacy_type', @@ -532,6 +538,8 @@ const protocolFailure = task => { assert.match(source, /common\.tasks\.details\.duration/); assert.match(source, /common\.tasks\.error\.execution_failed/); assert.match(source, /common\.tasks\.error\.unavailable_http/); + assert.match(source, /operation-presentation\.js/); + assert.doesNotMatch(source, /task\?\.kind_label|task\?\.action_label/); assert.match(source, /recoveryTaskFailureNotice\(task\)/); assert.doesNotMatch(source, /task\.error(?!_)/); assert.doesNotMatch(source, /task\.recovery\.message/); diff --git a/web/tests/UserCopyCompleteCoverageTest.php b/web/tests/UserCopyCompleteCoverageTest.php index dd090c02..fd386a8c 100644 --- a/web/tests/UserCopyCompleteCoverageTest.php +++ b/web/tests/UserCopyCompleteCoverageTest.php @@ -93,6 +93,7 @@ $browserPaths = [ 'web/public/cloud/invoice-detail.js', 'web/public/cloud/invoices.js', 'web/public/cloud/iso-images.js', + 'web/public/cloud/operation-presentation.js', 'web/public/cloud/reinstall.js', 'web/public/cloud/runtime.js', 'web/public/cloud/ssh-keys.js', diff --git a/web/tests/UserCopyManifestContractTest.php b/web/tests/UserCopyManifestContractTest.php index 5ab6c1e2..0923e6f4 100644 --- a/web/tests/UserCopyManifestContractTest.php +++ b/web/tests/UserCopyManifestContractTest.php @@ -44,7 +44,7 @@ $surfaceCounts = array_count_values(array_column( ksort($surfaceCounts, SORT_STRING); $assert($surfaceCounts === [ 'accessibility' => 102, - 'admin' => 54, + 'admin' => 112, 'dialog' => 56, 'feedback' => 610, 'page' => 1462, diff --git a/web/tests/VirtualizationAssetsTest.php b/web/tests/VirtualizationAssetsTest.php index be49715f..7e895344 100644 --- a/web/tests/VirtualizationAssetsTest.php +++ b/web/tests/VirtualizationAssetsTest.php @@ -86,6 +86,8 @@ $api = file_get_contents($root . '/app/Controllers/CloudApiController.php'); $middleware = file_get_contents($root . '/app/Middleware/CloudApi.php'); $cloudJobService = file_get_contents($root . '/app/Services/Cloud/CloudJobService.php'); $cloudOperationCatalog = file_get_contents($root . '/app/Services/Cloud/CloudOperationCatalog.php'); +$operationPresentation = file_get_contents($public . '/operation-presentation.js'); +$taskCenterScript = file_get_contents($public . '/task-center.js'); $cloudSchema = file_get_contents($root . '/sql/cloud.sql'); $adminBillingTemplate = $views . '/admin/billing.tpl'; $adminBillingScript = $public . '/admin-billing.js'; @@ -869,12 +871,16 @@ $assert(is_string($cloudOperationCatalog) && str_contains($cloudOperationCatalog, "'network_change' => '更换公网 IP'") && str_contains($cloudOperationCatalog, "'poweroff' => '强制断电'") && str_contains($cloudJobService, 'CloudOperationCatalog::isPowerAction') - && str_contains($clientScript, 'action_label') - && !str_contains($clientScript, 'POWER_ACTION_LABELS') - && !str_contains($clientScript, 'function jobKind(') + && str_contains($cloudJobService, "'operation_copy_keys' =>") + && str_contains($cloudOperationCatalog, 'public static function copyKeys(') + && str_contains($clientScript, "operation-presentation.js") + && str_contains($taskCenterScript, "operation-presentation.js") + && str_contains($operationPresentation, 'entry?.operation_copy_keys') + && !str_contains($operationPresentation, 'kind_label') + && !str_contains($operationPresentation, 'action_label') && str_contains($adminBillingRuntime, 'task.kind_label') && str_contains($adminInstanceScript, 'job.kind_label'), - 'Panel task labels must come from the canonical PHP operation catalog without client-side action maps.'); + 'User task labels must localize stable PHP catalog keys while administrator labels retain the canonical fallback.'); $assert(str_contains($clientScript, '/traffic/daily?days=30') && str_contains($cloudTemplate, "{user_copy key='instance_detail.traffic.daily_title'}")