From 2d132d2806ac3d0df7f898c1dde4a137753bc3f2 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 29 Jul 2026 01:29:01 +0300 Subject: [PATCH] Web: render component update transactions --- frontend/src/i18n/ru.ts | 30 +++ frontend/src/lib/auditMethods.ts | 4 + frontend/src/lib/rpc.ts | 6 +- frontend/src/lib/updates.ts | 119 +++++++++-- frontend/src/views/UpdatesView.tsx | 311 ++++++++++++++++++++++++++--- 5 files changed, 425 insertions(+), 45 deletions(-) diff --git a/frontend/src/i18n/ru.ts b/frontend/src/i18n/ru.ts index 9544bce..61a6942 100644 --- a/frontend/src/i18n/ru.ts +++ b/frontend/src/i18n/ru.ts @@ -53,12 +53,22 @@ export const ru: Record = { 'Downgrade': 'Понижение версии', 'Incompatible': 'Несовместимо', 'Restart required': 'Нужен перезапуск', + 'Local only': 'Только локально', 'Apply {0}': 'Применить {0}', + 'Apply Echoion {0}': 'Применить Echoion {0}', + 'Echoion {0}': 'Echoion {0}', 'No update': 'Нет обновления', 'Rollback to {0}': 'Откатить до {0}', + 'Rollback: {0}': 'Откат: {0}', + 'Rollback target: {0}': 'Цель отката: {0}', 'No rollback': 'Откат недоступен', + 'No prior healthy generation was reported.': + 'Предыдущее исправное поколение не найдено.', 'Enabled': 'Включено', 'Source': 'Источник', + 'Source layout': 'Схема источника', + 'Component catalogs always require signatures.': + 'Каталоги компонентов всегда требуют подписи.', 'Channel': 'Канал', '{0} source': 'Источник: {0}', '{0} channel': 'Канал: {0}', @@ -89,7 +99,11 @@ export const ru: Record = { 'Managed': 'Управляемый', 'Unmanaged': 'Неуправляемый', 'Apply': 'Применить', + 'Apply transaction': 'Применить транзакцию', 'Rollback': 'Откатить', + 'Restore previous': 'Восстановить предыдущее', + 'Restore generation': 'Восстановить поколение', + 'Restore healthy generation': 'Восстановить исправное поколение', 'Never': 'Никогда', 'Automatic updates armed': 'Автоматические обновления активны', 'Automatic updates paused': 'Автоматические обновления приостановлены', @@ -98,6 +112,18 @@ export const ru: Record = { 'Check now': 'Проверить сейчас', 'Checking…': 'Проверка…', 'Loading update state…': 'Загрузка состояния обновлений…', + 'TRANSACTION PREVIEW': 'ПРЕДПРОСМОТР ТРАНЗАКЦИИ', + 'Stage transaction': 'Подготовить транзакцию', + 'Stage and restart': 'Подготовить и перезапустить', + 'Reloadable modules will be quiesced before activation.': + 'Перезагружаемые модули будут приостановлены перед активацией.', + 'Echoion will restart and run a 30 second local health check.': + 'Echoion перезапустится и выполнит локальную проверку состояния в течение 30 секунд.', + 'Desktop is listed for this release but must update itself locally.': + 'Desktop входит в этот выпуск, но должен обновиться локально.', + '{0} server components · {1}': 'Компоненты сервера: {0} · {1}', + 'components': 'компоненты', + 'none': 'нет', 'Installed plugins': 'Установленные плагины', 'Only managed plugins participate in update activation.': 'В активации обновлений участвуют только управляемые плагины.', @@ -153,9 +179,13 @@ export const ru: Record = { 'После перехода в режим ожидания Echoion будет перезапущен для применения обновления. Продолжить?', 'Apply and restart': 'Применить и перезапустить', '{0} update queued': 'Обновление {0} поставлено в очередь', + 'Component transaction queued': 'Транзакция компонентов поставлена в очередь', 'Confirm rollback': 'Подтвердите откат', 'Roll back {0} to {1}?': 'Откатить {0} до {1}?', + 'Atomically restore generation {0} and validate it locally?': + 'Атомарно восстановить поколение {0} и проверить его локально?', 'Rollback queued': 'Откат поставлен в очередь', + 'Generation rollback queued': 'Откат поколения поставлен в очередь', 'Enable unsigned update policy': 'Разрешить политику обновлений без подписи', 'Unsigned staging will be permitted for: {0}. Type ENABLE UNSIGNED to save this policy.': 'Подготовка без подписи будет разрешена для: {0}. Введите ENABLE UNSIGNED, чтобы сохранить политику.', diff --git a/frontend/src/lib/auditMethods.ts b/frontend/src/lib/auditMethods.ts index 3fb3813..f498c40 100644 --- a/frontend/src/lib/auditMethods.ts +++ b/frontend/src/lib/auditMethods.ts @@ -101,6 +101,10 @@ const RPC_METHOD_BY_INDEX: readonly string[] = [ 'ApplyUpdate', 'RollbackUpdate', 'ConfirmUnsignedUpdate', // 95 + 'PreviewUpdateTransaction', + 'ApplyUpdateTransaction', + 'RollbackUpdateGeneration', + 'GetUpdateHistory', // 99 ]; export function auditMethodName(method: number): string { diff --git a/frontend/src/lib/rpc.ts b/frontend/src/lib/rpc.ts index ee23d90..df0a7e0 100644 --- a/frontend/src/lib/rpc.ts +++ b/frontend/src/lib/rpc.ts @@ -87,7 +87,11 @@ export type RpcMethodName = | 'CheckForUpdates' | 'ApplyUpdate' | 'RollbackUpdate' - | 'ConfirmUnsignedUpdate'; + | 'ConfirmUnsignedUpdate' + | 'PreviewUpdateTransaction' + | 'ApplyUpdateTransaction' + | 'RollbackUpdateGeneration' + | 'GetUpdateHistory'; type Pending = { diff --git a/frontend/src/lib/updates.ts b/frontend/src/lib/updates.ts index 17e4ad1..223b392 100644 --- a/frontend/src/lib/updates.ts +++ b/frontend/src/lib/updates.ts @@ -1,4 +1,4 @@ -export type UpdateComponent = 'runtime' | 'core' | 'plugins'; +export type UpdateComponent = string; export interface UpdatePublicKey { id: string; @@ -6,6 +6,7 @@ export interface UpdatePublicKey { } export interface UpdateSourceConfig { + kind: 'direct' | 'component-layout'; url: string; publicKeys: UpdatePublicKey[]; allowUnsigned: boolean; @@ -77,10 +78,48 @@ export interface ComponentUpdateStatus { source?: string; candidate?: UpdateCandidate; rollbackVersion?: string; + rollbackGeneration?: string; + activationMode?: string; + requiresRestart?: boolean; + localOnly?: boolean; + downloadSize?: number; + dependencies?: Record; lastChangedAt?: string | number; [key: string]: unknown; } +export interface UpdateTransactionComponent { + componentId: string; + pluginId?: string; + kind?: string; + currentVersion?: string; + version: string; + candidate?: boolean; + activationMode?: string; + localOnly?: boolean; + requiresRestart?: boolean; + downloadSize?: number; + dependencies?: Record; + [key: string]: unknown; +} + +export interface UpdateTransaction { + id: string; + source?: string; + channel?: string; + sequence?: number; + productVersion?: string; + activeGeneration?: string; + rollbackGeneration?: string; + downloadSize?: number; + desktopDownloadSize?: number; + requiresRestart?: boolean; + compatible?: boolean; + applying?: boolean; + components: UpdateTransactionComponent[]; + [key: string]: unknown; +} + export interface PluginUpdateStatus { id: string; name?: string; @@ -112,9 +151,10 @@ export interface UpdateStatus { checking: boolean; lastCheckAt?: string | number; nextCheckAt?: string | number; - components: Record; + components: Record; plugins: PluginUpdateStatus[]; history: UpdateHistoryEntry[]; + transaction?: UpdateTransaction; message?: string; [key: string]: unknown; } @@ -138,6 +178,7 @@ export const DEFAULT_UPDATE_CONFIG: UpdateConfig = { retainHealthyVersions: 2, sources: { official: { + kind: 'component-layout', url: '', publicKeys: [], allowUnsigned: false, @@ -232,6 +273,10 @@ export function normalizeUpdateConfig(payload: unknown): UpdateConfig { : []; sources[id] = { ...safeSource, + kind: + source.kind === 'component-layout' + ? 'component-layout' + : 'direct', url: stringValue(source.url), publicKeys: rawKeys.map((key) => { const rawKey = record(key); @@ -335,7 +380,7 @@ function normalizeCandidate(value: unknown): UpdateCandidate | undefined { } function normalizeComponent( - component: UpdateComponent, + component: string, value: unknown ): ComponentUpdateStatus { const raw = record(value); @@ -370,6 +415,48 @@ function normalizeComponent( }; } +function normalizeTransaction(value: unknown): UpdateTransaction | undefined { + const raw = record(value); + const id = stringValue(raw.id || raw.transactionId); + if (!id) return undefined; + const components: UpdateTransactionComponent[] = Array.isArray(raw.components) + ? raw.components + .flatMap((value): UpdateTransactionComponent[] => { + const component = record(value); + const componentId = stringValue(component.componentId); + const version = stringValue(component.version); + if (!componentId || !version) return []; + return [{ + ...component, + componentId, + version, + pluginId: stringValue(component.pluginId) || undefined, + dependencies: record(component.dependencies) as Record< + string, + string + >, + }]; + }) + : []; + return { + ...raw, + id, + components, + source: stringValue(raw.source) || undefined, + channel: stringValue(raw.channel) || undefined, + productVersion: stringValue(raw.productVersion) || undefined, + activeGeneration: stringValue(raw.activeGeneration) || undefined, + rollbackGeneration: stringValue(raw.rollbackGeneration) || undefined, + sequence: numberValue(raw.sequence, 0) || undefined, + downloadSize: numberValue(raw.downloadSize, 0) || undefined, + desktopDownloadSize: + numberValue(raw.desktopDownloadSize, 0) || undefined, + requiresRestart: booleanValue(raw.requiresRestart, false), + compatible: booleanValue(raw.compatible, true), + applying: booleanValue(raw.applying, false), + }; +} + function normalizePlugin(value: unknown): PluginUpdateStatus | null { const raw = record(value); const id = stringValue(raw.id || raw.pluginId); @@ -413,6 +500,18 @@ export function normalizeUpdateStatus(payload: unknown): UpdateStatus { (Array.isArray(pluginComponent.items) && pluginComponent.items) || []; const rawHistory = Array.isArray(raw.history) ? raw.history : []; + const components: Record = {}; + for (const [component, value] of Object.entries(rawComponents)) { + components[component] = normalizeComponent(component, value); + } + for (const component of ['runtime', 'core', 'plugins']) { + components[component] ||= normalizeComponent( + component, + component === 'plugins' + ? pluginComponent + : raw[component] + ); + } return { ...raw, @@ -428,18 +527,12 @@ export function normalizeUpdateStatus(payload: unknown): UpdateStatus { typeof raw.nextCheckAt === 'number' ? raw.nextCheckAt : undefined, - components: { - runtime: normalizeComponent( - 'runtime', - rawComponents.runtime || raw.runtime - ), - core: normalizeComponent('core', rawComponents.core || raw.core), - plugins: normalizeComponent('plugins', pluginComponent), - }, + components, plugins: rawPluginEntries .map(normalizePlugin) .filter((plugin): plugin is PluginUpdateStatus => plugin !== null), history: rawHistory.map((entry) => record(entry) as UpdateHistoryEntry), + transaction: normalizeTransaction(raw.transaction), message: stringValue(raw.message) || undefined, }; } @@ -451,8 +544,10 @@ export function configForSave(config: UpdateConfig): UpdateConfig { const { bearerTokenPresent: _present, ...writable } = source; sources[id] = { ...sourceFieldsWithoutSecrets(writable), + kind: source.kind, url: source.url.trim(), - allowUnsigned: source.allowUnsigned, + allowUnsigned: + source.kind === 'component-layout' ? false : source.allowUnsigned, bearerTokenEnv: source.bearerTokenEnv.trim(), publicKeys: source.publicKeys .map((key) => ({ diff --git a/frontend/src/views/UpdatesView.tsx b/frontend/src/views/UpdatesView.tsx index 39e2df4..99c57a4 100644 --- a/frontend/src/views/UpdatesView.tsx +++ b/frontend/src/views/UpdatesView.tsx @@ -24,18 +24,40 @@ import { type UpdateConfig, type UpdateSourceConfig, type UpdateStatus, + type UpdateTransaction, } from '../lib/updates'; -const COMPONENTS: readonly UpdateComponent[] = [ - 'runtime', - 'core', - 'plugins', -]; +const COMPONENTS = ['runtime', 'core', 'plugins'] as const; +type PolicyComponent = (typeof COMPONENTS)[number]; -function componentLabel(component: UpdateComponent): string { +function componentLabel(component: string): string { if (component === 'runtime') return t('Runtime bundle'); if (component === 'core') return t('Core'); - return t('Plugins'); + if (component === 'plugins') return t('Plugins'); + const labels: Record = { + EchoionApi: 'API SDK', + EchoionHost: 'Host', + EchoionCore: 'Core', + EchoionWeb: 'Web', + EchoionStandalone: 'Standalone', + EchoionUpdater: 'Updater', + EchoionDesktop: 'Desktop', + EchoionPluginUrlShortenerInternal: 'URL shortener · internal', + EchoionPluginUrlShortenerExternal: 'URL shortener · external', + }; + return labels[component] || component.replace(/([a-z])([A-Z])/g, '$1 $2'); +} + +function formatBytes(value?: number): string { + if (!value || value < 0) return '0 B'; + const units = ['B', 'KiB', 'MiB', 'GiB']; + let size = value; + let unit = 0; + while (size >= 1024 && unit < units.length - 1) { + size /= 1024; + unit += 1; + } + return `${size.toFixed(unit ? 1 : 0)} ${units[unit]}`; } function formatTimestamp(value?: string | number): string { @@ -117,11 +139,13 @@ function ComponentCard(props: { }) { const candidate = props.status.candidate; const component = props.status.component; + const rollback = + props.status.rollbackGeneration || props.status.rollbackVersion; return (
- + {status?.transaction && ( +
+
+
+ {t('TRANSACTION PREVIEW')} +

+ {tf( + 'Echoion {0}', + status.transaction.productVersion || '—' + )} +

+

+ {status.transaction.source} · {status.transaction.channel} ·{' '} + {formatBytes(status.transaction.downloadSize)} +

+
+
+ {status.transaction.rollbackGeneration && ( + + )} + +
+
+
+ + {status.transaction.components.length} {t('components')} + + {status.transaction.requiresRestart && ( + {t('Restart required')} + )} + + {tf( + 'Rollback: {0}', + status.transaction.rollbackGeneration || t('none') + )} + +
+
+ )} +
- {status && COMPONENTS.map((component) => ( + {componentStatuses.map((componentStatus) => ( - void applyUpdate( - component, - status.components[component].candidate - ) - } - onRollback={() => - void rollbackUpdate( - component, - status.components[component].rollbackVersion - ) - } + onApply={() => { + if ( + status?.transaction && + !COMPONENTS.some( + (component) => component === componentStatus.component + ) + ) { + void applyComponentTransaction(status.transaction); + } else { + void applyUpdate( + componentStatus.component, + componentStatus.candidate + ); + } + }} + onRollback={() => { + if (componentStatus.rollbackGeneration) { + void rollbackGeneration( + componentStatus.rollbackGeneration + ); + } else { + void rollbackUpdate( + componentStatus.component, + componentStatus.rollbackVersion + ); + } + }} /> ))}