Files
Reims-Go/frontend/src/components/AffinityDialog.tsx
T
Nwflower 847d447d81 refactor(lifecycle): route VM observation and diagnostics
Resolve stats, thumbnails, window actions, SSH, affinity and diagnostic bundles through VMRef-aware VM information. Isolate caches, SSH aliases and frontend pollers for same-name VMs while preserving macOS defaults.
2026-11-30 10:33:06 -07:00

382 lines
13 KiB
TypeScript

import { AlertTriangle, Check, Cpu } from 'lucide-react'
import React, { useEffect, useMemo, useState } from 'react'
import '../i18n/domains/settings.gen'
import { I18nKey, parseAppError, t } from '../i18n'
import { HostReport, Locale, LogicalCPUInfo, VMAffinityMode, VMAffinityStatus } from '../types'
import { Button } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { Segmented, Switch } from '../ui/settings'
import { api } from '../wails'
interface Props {
locale: Locale
vmName: string
driverID: string
vcpus: number
host: HostReport
globalAutoPin: boolean
onClose: () => void
onApplied: (status: VMAffinityStatus) => void
}
function buildTopology(host: HostReport): LogicalCPUInfo[] {
if (host.cpu_topology && host.cpu_topology.length > 0) {
return host.cpu_topology
}
const n = Math.min(Math.max(host.logical_cpus || 1, 1), 64)
return Array.from({ length: n }, (_, i) => ({
index: i,
core_index: i,
tier: 'standard',
smt: false,
}))
}
function maskHexFromCPUs(cpus: number[]): string {
let mask = 0n
for (const idx of cpus) {
if (idx >= 0 && idx < 64) {
mask |= 1n << BigInt(idx)
}
}
return '0x' + mask.toString(16).toUpperCase()
}
function resolveAutoPreview(topology: LogicalCPUInfo[], host: HostReport, globalAutoPin: boolean, vcpus: number): number[] {
const all = topology.map((c) => c.index)
if (!globalAutoPin || !host.has_hybrid_cores) return all
const pCPUs = topology.filter((c) => c.tier === 'p').map((c) => c.index)
if (pCPUs.length >= vcpus + 1 && pCPUs.length > 0) return pCPUs
if ((host.lpe_core_count ?? 0) > 0) {
const nonLPE = topology.filter((c) => c.tier !== 'lpe').map((c) => c.index)
if (nonLPE.length >= vcpus + 1 && nonLPE.length > 0) return nonLPE
}
return all
}
export function formatAffinitySummary(locale: Locale, status: VMAffinityStatus | null): string {
if (!status) return '—'
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const count = status.effective_cpus?.length ?? 0
const mask = status.effective_mask_hex || '0x0'
switch (status.mode) {
case 'all':
return tr('affinitySummaryAll', { count })
case 'pcores':
return tr('affinitySummaryPCores', { count, mask })
case 'non_lpe':
return tr('affinitySummaryNonLPE', { count, mask })
case 'custom':
return tr('affinitySummaryCustom', { count, mask })
default: {
const effLabel = status.effective_mode === 'pcores'
? tr('affinityModePCores')
: status.effective_mode === 'non_lpe'
? tr('affinityModeNonLPE')
: tr('affinityModeAll')
return tr('affinitySummaryAuto', { eff: effLabel, count })
}
}
}
export const AffinityDialog: React.FC<Props> = ({
locale, vmName, driverID, vcpus, host, globalAutoPin, onClose, onApplied,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const topology = useMemo(() => buildTopology(host), [host])
const allIndices = useMemo(() => topology.map((c) => c.index), [topology])
const hasSMT = useMemo(() => topology.some((c) => c.smt), [topology])
const [status, setStatus] = useState<VMAffinityStatus | null>(null)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [err, setErr] = useState('')
const [mode, setMode] = useState<VMAffinityMode>('auto')
const [selected, setSelected] = useState<number[]>(allIndices)
const [disableEcoQoS, setDisableEcoQoS] = useState(true)
useEffect(() => {
let live = true
setLoading(true)
setErr('')
api.GetVMAffinityWithDriver(driverID, vmName)
.then((st) => {
if (!live) return
setStatus(st)
setMode(st.mode || 'auto')
const initial = st.mode === 'custom' && st.cpus?.length > 0
? st.cpus
: (st.effective_cpus?.length > 0 ? st.effective_cpus : allIndices)
setSelected([...initial].sort((a, b) => a - b))
setDisableEcoQoS(st.disable_eco_qos)
})
.catch((e) => {
if (live) setErr(parseAppError(e).summary)
})
.finally(() => {
if (live) setLoading(false)
})
return () => { live = false }
}, [vmName, allIndices])
const selectedSet = useMemo(() => new Set(selected), [selected])
const effectiveVCPUs = status?.vcpus || vcpus
const maskHex = useMemo(() => maskHexFromCPUs(selected), [selected])
const applyPreset = (nextMode: VMAffinityMode) => {
setMode(nextMode)
setErr('')
switch (nextMode) {
case 'all':
setSelected(allIndices)
break
case 'pcores': {
const list = topology.filter((c) => c.tier === 'p').map((c) => c.index)
setSelected(list.length > 0 ? list : allIndices)
break
}
case 'non_lpe': {
const list = topology.filter((c) => c.tier !== 'lpe').map((c) => c.index)
setSelected(list.length > 0 ? list : allIndices)
break
}
case 'auto':
setSelected(resolveAutoPreview(topology, host, globalAutoPin, effectiveVCPUs))
break
case 'custom':
break
}
}
const toggleCPU = (idx: number) => {
setMode('custom')
setErr('')
setSelected((prev) => {
const s = new Set(prev)
if (s.has(idx)) s.delete(idx)
else s.add(idx)
return Array.from(s).sort((a, b) => a - b)
})
}
const pickCustomList = (list: number[]) => {
setMode('custom')
setErr('')
setSelected([...new Set(list)].sort((a, b) => a - b))
}
const physicalOnlyList = useMemo(() => {
const seen = new Set<number>()
const out: number[] = []
for (const c of topology) {
if (!seen.has(c.core_index)) {
seen.add(c.core_index)
out.push(c.index)
}
}
return out
}, [topology])
const modeOptions: { value: VMAffinityMode; label: string }[] = [
{ value: 'auto', label: tr('affinityModeAuto') },
{ value: 'all', label: tr('affinityModeAll') },
...(host.has_hybrid_cores ? [{ value: 'pcores' as const, label: tr('affinityModePCores') }] : []),
...((host.lpe_core_count ?? 0) > 0 ? [{ value: 'non_lpe' as const, label: tr('affinityModeNonLPE') }] : []),
{ value: 'custom', label: tr('affinityModeCustom') },
]
const modeHintKey: Record<VMAffinityMode, I18nKey> = {
auto: 'affinityModeAutoHint',
all: 'affinityModeAllHint',
pcores: 'affinityModePCoresHint',
non_lpe: 'affinityModeNonLPEHint',
custom: 'affinityModeCustomHint',
}
const emptyCustom = mode === 'custom' && selected.length === 0
const oversubscribed = effectiveVCPUs > 0 && selected.length > 0 && selected.length < effectiveVCPUs
const allSelected = selected.length === allIndices.length && allIndices.length > 0
const handleSave = async () => {
if (emptyCustom) {
setErr(tr('affinityNeedOne'))
return
}
setSaving(true)
setErr('')
try {
const updated = await api.SetVMAffinityWithDriver(driverID, vmName, {
mode,
cpus: mode === 'custom' ? selected : [],
disable_eco_qos: disableEcoQoS,
})
onApplied(updated)
} catch (e) {
setErr(parseAppError(e).summary)
} finally {
setSaving(false)
}
}
const subtitle = status?.running && status.pid
? tr('affinitySubtitleRunning', { pid: status.pid, vcpus: effectiveVCPUs })
: tr('affinitySubtitleStopped', { vcpus: effectiveVCPUs })
const tierLabel = (tier: string) => {
if (tier === 'p') return 'P'
if (tier === 'e') return 'E'
if (tier === 'lpe') return 'LP-E'
return ''
}
return (
<Modal
title={`${tr('affinityTitle')} — ${vmName}`}
subtitle={subtitle}
closeLabel={tr('close')}
dismissable={!saving}
onClose={onClose}
className="affinity-dialog"
>
<div className="dialog-body affinity-body">
<div className="affinity-mode-bar">
<Segmented
label={tr('affinityTitle')}
value={mode}
onChange={(m) => applyPreset(m as VMAffinityMode)}
options={modeOptions}
/>
<p className="affinity-hint">{tr(modeHintKey[mode])}</p>
</div>
<div className="affinity-quick-bar">
<button
type="button"
className={`affinity-chip${allSelected ? ' is-active' : ''}`}
disabled={loading || saving}
onClick={() => pickCustomList(allSelected ? [allIndices[0]] : allIndices)}
>
{tr('affinitySelectAll')}
</button>
{hasSMT && (
<button
type="button"
className="affinity-chip"
disabled={loading || saving}
onClick={() => pickCustomList(physicalOnlyList)}
>
{tr('affinityPhysicalOnly')}
</button>
)}
{allIndices.length > 1 && (
<button
type="button"
className="affinity-chip"
disabled={loading || saving}
onClick={() => pickCustomList(allIndices.filter((i) => i !== 0))}
>
{tr('affinityExcludeCPU0')}
</button>
)}
{host.has_hybrid_cores && (
<button
type="button"
className="affinity-chip"
disabled={loading || saving}
onClick={() => pickCustomList(topology.filter((c) => c.tier === 'p').map((c) => c.index))}
>
{tr('affinityOnlyPCores')}
</button>
)}
{(host.lpe_core_count ?? 0) > 0 && (
<button
type="button"
className="affinity-chip"
disabled={loading || saving}
onClick={() => pickCustomList(topology.filter((c) => c.tier !== 'lpe').map((c) => c.index))}
>
{tr('affinityAvoidLPE')}
</button>
)}
</div>
<div className="affinity-grid" role="group" aria-label={tr('affinityTitle')}>
{topology.map((cpu) => {
const checked = selectedSet.has(cpu.index)
const tLabel = tierLabel(cpu.tier)
return (
<button
key={cpu.index}
type="button"
role="checkbox"
aria-checked={checked}
disabled={loading || saving}
className={`affinity-cpu${checked ? ' is-checked' : ''}${cpu.tier === 'lpe' ? ' is-lpe' : ''}`}
onClick={() => toggleCPU(cpu.index)}
>
<span className="affinity-check" aria-hidden="true">
{checked && <Check size={12} strokeWidth={3} />}
</span>
<span className="affinity-cpu-name tnum">CPU {cpu.index}</span>
<span className="affinity-cpu-meta">
{cpu.smt && <span className="affinity-core-tag tnum">C{cpu.core_index}</span>}
{tLabel && <span className={`affinity-tier tier-${cpu.tier}`}>{tLabel}</span>}
</span>
</button>
)
})}
</div>
<div className="affinity-summary">
<span className="mono tnum">
<Cpu size={13} aria-hidden="true" />{' '}
{tr('affinitySelectedSummary', { selected: selected.length, total: topology.length, mask: maskHex })}
</span>
{status?.running && status.live_mask_hex && (
<span className="affinity-live mono tnum">
{tr('affinityLiveMask', { mask: status.live_mask_hex, count: status.live_cpus?.length ?? 0 })}
</span>
)}
</div>
{oversubscribed && (
<div className="notice" role="status">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('affinityOversubWarn', { selected: selected.length, vcpus: effectiveVCPUs })}</span>
</span>
</div>
)}
<div className="affinity-eco-row">
<div className="row-main">
<div className="row-title">{tr('affinityEcoQoS')}</div>
<div className="row-sub">{tr('affinityEcoQoSDesc')}</div>
</div>
<Switch
label={tr('affinityEcoQoS')}
checked={disableEcoQoS}
disabled={loading || saving}
onChange={setDisableEcoQoS}
/>
</div>
{err && <div className="notice notice-error" role="alert">{err}</div>}
</div>
<div className="dialog-foot">
<Button onClick={onClose} disabled={saving}>{tr('cancel')}</Button>
<Button
variant="primary"
busy={saving}
disabled={loading || emptyCustom}
onClick={() => void handleSave()}
>
{status?.running ? tr('affinityApplyNow') : tr('affinitySave')}
</Button>
</div>
</Modal>
)
}