fix(i18n): localize user operation titles

go
codex 1 week ago
parent 6bff12f30c
commit ebf9b58eba

@ -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);

@ -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),
];
}
}

@ -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');
}

@ -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();
}

@ -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) {

@ -1,5 +1,7 @@
<?php
use App\Services\Cloud\CloudOperationCatalog;
$entry = require dirname(__DIR__) . '/entry.php';
$detailSources = [
@ -923,6 +925,21 @@ $reinstallParameters = [
];
$entries = [];
foreach (CloudOperationCatalog::copySources() as $key => $source) {
$entries[] = $entry(
$key,
'common',
'cloud.detail',
$source,
'label',
[],
'required',
false,
null,
'admin',
'cloud.detail'
);
}
foreach ($detailSources as $key => $source) {
$entries[] = $entry(
$key,

@ -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'}

@ -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.');

@ -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');

@ -0,0 +1,47 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudOperationCatalog;
use App\Services\UserCopy\UserCopyManifest;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$sources = CloudOperationCatalog::copySources();
$assert(count($sources) === count(CloudOperationCatalog::kinds()) + 9,
'Operation copy sources do not cover every kind, power action, setting field and separator.');
$entries = array_column(UserCopyManifest::load()['entries'], null, 'key');
foreach ($sources as $copyKey => $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.'
);

@ -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',

@ -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/);

@ -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',

@ -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,

@ -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'}")

Loading…
Cancel
Save