import { useCallback, useEffect, useMemo, useState, type ReactNode, } from 'react'; import { t, tf } from '../i18n'; import { appStore, safeCall, toast } from '../lib/app'; import { confirmDialog, promptDialog } from '../lib/dialog'; import { rpc } from '../lib/rpc'; import { useStore } from '../lib/store'; import { cloneUpdateConfig, configForSave, isValidSourceId, normalizeUpdateConfig, normalizeUpdateStatus, type ComponentUpdatePolicy, type ComponentUpdateStatus, type PluginUpdateStatus, type UpdateCandidate, type UpdateComponent, type UpdateConfig, type UpdateSourceConfig, type UpdateStatus, } from '../lib/updates'; const COMPONENTS: readonly UpdateComponent[] = [ 'runtime', 'core', 'plugins', ]; function componentLabel(component: UpdateComponent): string { if (component === 'runtime') return t('Runtime bundle'); if (component === 'core') return t('Core'); return t('Plugins'); } function formatTimestamp(value?: string | number): string { if (value === undefined || value === '') return t('Never'); const numeric = typeof value === 'number' ? value : Number(value); const date = Number.isFinite(numeric) ? new Date(numeric < 10_000_000_000 ? numeric * 1000 : numeric) : new Date(value); return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString(); } function stateTone(state?: string): string { const value = (state || '').toLowerCase(); if ( value.includes('fail') || value.includes('error') || value.includes('quarantine') ) return 'danger'; if ( value.includes('ready') || value.includes('healthy') || value.includes('current') || value.includes('success') ) return 'success'; if ( value.includes('pending') || value.includes('stage') || value.includes('download') || value.includes('wait') ) return 'warning'; return 'neutral'; } function looksLikeStatusPayload(payload: unknown): boolean { if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { return false; } const value = payload as Record; return ( 'components' in value || 'runtime' in value || 'core' in value || ('status' in value && typeof value.status === 'object') ); } function StatusBadge(props: { children: ReactNode; tone?: string }) { return ( {props.children} ); } function CandidateBadges({ candidate }: { candidate: UpdateCandidate }) { return (
{candidate.signed === false ? t('Unsigned') : t('Signed')} {candidate.downgrade && ( {t('Downgrade')} )} {candidate.compatible === false && ( {t('Incompatible')} )} {candidate.requiresRestart && ( {t('Restart required')} )}
); } function ComponentCard(props: { status: ComponentUpdateStatus; busy: boolean; onApply: () => void; onRollback: () => void; }) { const candidate = props.status.candidate; const component = props.status.component; return (

{componentLabel(component)}

{props.status.source || t('default source')} ·{' '} {props.status.channel || t('stable')}

{props.status.state || t('Idle')}
{t('Installed')} {props.status.currentVersion || '—'}
{t('Available')} {candidate?.version || t('Up to date')}
{candidate && } {(candidate?.message || props.status.message) && (

{candidate?.message || props.status.message}

)}
); } function PolicyEditor(props: { component: UpdateComponent; policy: ComponentUpdatePolicy; sourceIds: string[]; onChange: (policy: ComponentUpdatePolicy) => void; }) { const label = componentLabel(props.component); return (
{label}
); } function SourceEditor(props: { id: string; source: UpdateSourceConfig; canDelete: boolean; onChange: (source: UpdateSourceConfig) => void; onDelete: () => void; }) { function updateKey(index: number, field: 'id' | 'ed25519', value: string) { const keys = props.source.publicKeys.map((key, keyIndex) => keyIndex === index ? { ...key, [field]: value } : key ); props.onChange({ ...props.source, publicKeys: keys }); } return (
{props.id} {props.id === 'official' && ( {t('Build default')} )}
{t('Ed25519 trust keys')}

{t('Only public verification keys belong here.')}

{props.source.publicKeys.length ? ( props.source.publicKeys.map((key, index) => (
)) ) : (

{t('No custom keys; the build-injected keyring is used when available.')}

)}
{props.canDelete && (
)}
); } function PluginRow(props: { plugin: PluginUpdateStatus; busy: boolean; onApply: () => void; onRollback: () => void; }) { const candidate = props.plugin.candidate; return (
{props.plugin.name || props.plugin.id} {props.plugin.id}
{props.plugin.managed ? t('Managed') : t('Unmanaged')}
{props.plugin.currentVersion || '—'} {candidate && <> → {candidate.version}}
{props.plugin.managed && candidate && ( )} {props.plugin.managed && props.plugin.rollbackVersion && ( )}
); } export function UpdatesView() { const app = useStore(appStore); const isAdmin = !!app.identity?.isAdmin; const [status, setStatus] = useState(null); const [config, setConfig] = useState(null); const [draft, setDraft] = useState(null); const [dirty, setDirty] = useState(false); const [loading, setLoading] = useState(false); const [busy, setBusy] = useState(''); const loadStatus = useCallback(async () => { const payload = await safeCall('GetUpdateStatus'); if (payload !== null) setStatus(normalizeUpdateStatus(payload)); }, []); const loadConfig = useCallback(async () => { const payload = await safeCall('GetUpdateConfig'); if (payload === null) return; const next = normalizeUpdateConfig(payload); setConfig(next); setDraft(cloneUpdateConfig(next)); setDirty(false); }, []); const loadAll = useCallback(async () => { setLoading(true); await Promise.all([loadStatus(), loadConfig()]); setLoading(false); }, [loadConfig, loadStatus]); useEffect(() => { if (!isAdmin) return; void loadAll(); return rpc.on('updates.changed', (payload) => { if (looksLikeStatusPayload(payload)) { setStatus(normalizeUpdateStatus(payload)); } else { void loadStatus(); } }); }, [isAdmin, loadAll, loadStatus]); const sourceIds = useMemo( () => Object.keys(draft?.sources || {}), [draft?.sources] ); function changeDraft(next: UpdateConfig) { setDraft(next); setDirty(true); } function changePolicy( component: UpdateComponent, policy: ComponentUpdatePolicy ) { if (!draft) return; if (component === 'plugins') { changeDraft({ ...draft, plugins: { ...draft.plugins, ...policy }, }); return; } changeDraft({ ...draft, [component]: policy }); } async function checkForUpdates() { setBusy('check'); const payload = await safeCall('CheckForUpdates'); if (payload !== null) { await loadStatus(); toast(t('Update check completed')); } setBusy(''); } async function confirmCandidate( component: UpdateComponent, candidate: UpdateCandidate, pluginId?: string ): Promise { let confirmationToken: string | undefined; if (candidate.signed === false) { const phrase = `UNSIGNED ${candidate.version}`; const entered = await promptDialog({ title: t('Confirm unsigned update'), message: tf( 'This artifact has no trusted signature. Type {0} to authorize this exact candidate.', phrase ), placeholder: phrase, confirmLabel: t('Authorize unsigned candidate'), }); if (entered !== phrase) return null; const approval = await safeCall<{ confirmationToken?: string }>( 'ConfirmUnsignedUpdate', { component, pluginId, candidateId: candidate.id || candidate.version, version: candidate.version, confirmation: phrase, } ); if (approval === null) return null; confirmationToken = approval.confirmationToken; } if (candidate.downgrade) { const entered = await promptDialog({ title: t('Confirm downgrade'), message: t('A downgrade may make saved state incompatible. Type DOWNGRADE to continue.'), placeholder: 'DOWNGRADE', confirmLabel: t('Continue with downgrade'), }); if (entered !== 'DOWNGRADE') return null; } if (component === 'runtime' || candidate.requiresRestart) { const confirmed = await confirmDialog({ title: t('Restart Echoion'), message: t('Applying this update restarts Echoion after it becomes idle. Continue?'), confirmLabel: t('Apply and restart'), }); if (!confirmed) return null; } return confirmationToken; } async function applyUpdate( component: UpdateComponent, candidate?: UpdateCandidate, pluginId?: string ) { if (!candidate || candidate.compatible === false) return; const confirmationToken = await confirmCandidate( component, candidate, pluginId ); if (confirmationToken === null) return; const key = `apply:${component}:${pluginId || ''}`; setBusy(key); const payload = await safeCall('ApplyUpdate', { component, pluginId, candidateId: candidate.id || candidate.version, version: candidate.version, confirmationToken, }); if (payload !== null) { await loadStatus(); toast(tf('{0} update queued', pluginId || componentLabel(component))); } setBusy(''); } async function rollbackUpdate( component: UpdateComponent, version?: string, pluginId?: string ) { if (!version) return; const confirmed = await confirmDialog({ title: t('Confirm rollback'), message: tf('Roll back {0} to {1}?', pluginId || componentLabel(component), version), confirmLabel: t('Rollback'), danger: true, }); if (!confirmed) return; const key = `rollback:${component}:${pluginId || ''}`; setBusy(key); const payload = await safeCall('RollbackUpdate', { component, pluginId, version, }); if (payload !== null) { await loadStatus(); toast(t('Rollback queued')); } setBusy(''); } async function saveConfig() { if (!draft || !config) return; const newlyUnsigned = Object.entries(draft.sources) .filter( ([id, source]) => source.allowUnsigned && !config.sources[id]?.allowUnsigned ) .map(([id]) => id); if (newlyUnsigned.length) { const entered = await promptDialog({ title: t('Enable unsigned update policy'), message: tf( 'Unsigned staging will be permitted for: {0}. Type ENABLE UNSIGNED to save this policy.', newlyUnsigned.join(', ') ), placeholder: 'ENABLE UNSIGNED', confirmLabel: t('Save unsafe policy'), }); if (entered !== 'ENABLE UNSIGNED') return; } setBusy('save'); const payload = await safeCall('SetUpdateConfig', { config: configForSave(draft), }); if (payload !== null) { await loadConfig(); toast(t('Update policy saved')); await loadStatus(); } setBusy(''); } async function addSource() { if (!draft) return; const id = await promptDialog({ title: t('Add update source'), message: t('Use a short ID made from letters, numbers, dots, dashes, or underscores.'), placeholder: 'private-stable', confirmLabel: t('Add source'), }); if (!id) return; if (!isValidSourceId(id)) { toast(t('Invalid source ID')); return; } if (draft.sources[id]) { toast(t('That source already exists')); return; } changeDraft({ ...draft, sources: { ...draft.sources, [id]: { url: '', publicKeys: [], allowUnsigned: false, bearerTokenEnv: '', }, }, }); } async function removeSource(id: string) { if (!draft) return; const used = COMPONENTS.some( (component) => draft[component].source === id ) || Object.values(draft.plugins.overrides).some( (override) => override.source === id ); if (used) { toast(t('Move every component off this source before removing it')); return; } if ( !(await confirmDialog({ title: t('Remove update source'), message: tf('Remove source {0} and its public keys?', id), confirmLabel: t('Remove source'), danger: true, })) ) return; const sources = { ...draft.sources }; delete sources[id]; changeDraft({ ...draft, sources }); } async function addPluginOverride() { if (!draft) return; const id = await promptDialog({ title: t('Add plugin channel override'), message: t('Enter the exact managed plugin ID.'), placeholder: 'plugin.id', confirmLabel: t('Add override'), }); if (!id) return; if (draft.plugins.overrides[id]) { toast(t('That plugin override already exists')); return; } changeDraft({ ...draft, plugins: { ...draft.plugins, overrides: { ...draft.plugins.overrides, [id]: { source: draft.plugins.source, channel: draft.plugins.channel, autoApply: draft.plugins.autoApply, }, }, }, }); } if (!isAdmin) { return (

{t('Administrator authentication required')}

{t('Update policy, trust keys, and activation controls are restricted to administrators.')}

); } return (
{loading ? t('Loading update state…') : status?.message || ''}
{status && COMPONENTS.map((component) => ( void applyUpdate( component, status.components[component].candidate ) } onRollback={() => void rollbackUpdate( component, status.components[component].rollbackVersion ) } /> ))}

{t('Installed plugins')}

{t('Only managed plugins participate in update activation.')}

{status?.plugins.filter((plugin) => plugin.managed).length || 0} {t('managed')}
{status?.plugins.length ? status.plugins.map((plugin) => ( void applyUpdate('plugins', plugin.candidate, plugin.id) } onRollback={() => void rollbackUpdate( 'plugins', plugin.rollbackVersion, plugin.id ) } /> )) : (

{t('No installed plugins reported')}

)}

{t('Update history')}

{t('Checks, staging, activation, and rollback outcomes')}

{status?.history.length ? status.history.slice(0, 100).map((entry, index) => ( )) : ( )}
{t('When')} {t('Target')} {t('Action')} {t('Result')}
{formatTimestamp(entry.timestamp)} {entry.pluginId || entry.component || '—'} {entry.version && {entry.version}} {entry.action || '—'} {entry.result || t('Recorded')}
{t('No update history yet')}
{draft && config && (
{ event.preventDefault(); void saveConfig(); }} >
{t('POLICY DECK')}

{t('Automation and trust')}

{t('Configure timing, independent channels, feeds, and public trust roots.')}

{t('Component channels')}

{t('Selections remain independent; incompatible cohorts stay staged.')}

{COMPONENTS.map((component) => ( changePolicy(component, policy)} /> ))}

{t('Plugin channel overrides')}

{t('Pin individual managed plugins to another source or channel.')}

{Object.entries(draft.plugins.overrides).length ? Object.entries(draft.plugins.overrides).map(([id, policy]) => (
{id} changeDraft({ ...draft, plugins: { ...draft.plugins, overrides: { ...draft.plugins.overrides, [id]: { ...policy, channel: event.target.value }, }, }, }) } />
)) : (

{t('No plugin overrides')}

)}

{t('Sources and trust roots')}

{t('Secret values stay in the service environment and are never returned here.')}

{Object.entries(draft.sources).map(([id, source]) => ( 1} onChange={(next) => changeDraft({ ...draft, sources: { ...draft.sources, [id]: next }, }) } onDelete={() => void removeSource(id)} /> ))}
)}
); }