@page "/agents/{Id:guid}" @attribute [Authorize(Policy = "Admin.Users")] @layout MainLayout @inject HeimdallApiClient Api @inject ISnackbar Snackbar @inject NavigationManager Nav @inject UiText Text @inject UiLanguageService Language @implements IAsyncDisposable @Text["AgentDetail_Agent"] @_agent?.Name @if (_loading) { } else if (_agent is null) { @Text["AgentDetail_RetourAuxAgents"] } else { @* ─── Status Bar ─── *@
@Text["AgentDetail_LastHeartbeat"]: @(_agent.LastHeartbeat?.ToString("g", Language.Culture) ?? Text["AgentDetail_Jamais"])
@Text["AgentDetail_Hostname"] @_agent.Hostname @Text["AgentDetail_Version"] @_agent.Version @Text["AgentDetail_Statut"] @GetStatusIcon(_agent.Status) @UiFormat.Status(_agent.Status) @Text["AgentDetail_IpPublique"] @(_agent.PublicIp ?? "-") @Text["AgentDetail_DernierHeartbeat"] @(_agent.LastHeartbeat?.ToString("g", Language.Culture) ?? Text["AgentDetail_Jamais"]) @Text["AgentDetail_EnregistreLe"] @_agent.CreatedAt.ToString("g", Language.Culture) @Text["AgentDetail_Cpu"] @string.Format(Language.Culture, Text["AgentDetail_CpuCoreCount"], _agent.CpuCores) @Text["AgentDetail_Memoire"] @FormatMemory(_agent.MemoryMb, Language.Culture) @Text["AgentDetail_Gpu"] @(_agent.HasGpu ? _agent.GpuType : Text["AgentDetail_NoGpu"]) @* ─── Hardware Inventory ─── *@ @* ─── CPU Inventory ─── *@ @if (_agent.CpuModel is not null) { @Text["AgentDetail_Modele"] @_agent.CpuModel } @if (_agent.CpuVendor is not null) { @Text["AgentDetail_Fabricant"] @_agent.CpuVendor } @if (_agent.CpuArchitecture is not null) { @Text["AgentDetail_Architecture"] @_agent.CpuArchitecture } @if (_agent.PhysicalCores.HasValue) { @Text["AgentDetail_CursPhysiques"] @_agent.PhysicalCores } @if (_agent.LogicalCores.HasValue) { @Text["AgentDetail_CursLogiques"] @_agent.LogicalCores } @if (_agent.ThreadsPerCore.HasValue) { @Text["AgentDetail_ThreadsNoyau"] @_agent.ThreadsPerCore } @if (_agent.CpuFrequencyMhz.HasValue) { @Text["AgentDetail_Frequence"] @($"{_agent.CpuFrequencyMhz.Value.ToString("F0", Language.Culture)} MHz") } @if (_agent.CpuCacheBytes.HasValue && _agent.CpuCacheBytes > 0) { @Text["AgentDetail_Cache"] @FormatBytes(_agent.CpuCacheBytes.Value, Language.Culture) } @if (!string.IsNullOrEmpty(_agent.CpuFlags)) { @Text["AgentDetail_InstructionsCles"]
@foreach (var flag in _agent.CpuFlags.Split(',', StringSplitOptions.RemoveEmptyEntries)) { @flag }
}
@* ─── Memory & Disk Inventory ─── *@ @if (_agent.MemTotalBytes.HasValue) { @Text["AgentDetail_MemoireTotale"] @FormatBytes(_agent.MemTotalBytes.Value, Language.Culture) } @if (_agent.MemAvailableBytes.HasValue) { @Text["AgentDetail_MemoireDispo"] @FormatBytes(_agent.MemAvailableBytes.Value, Language.Culture) } @if (_agent.SwapTotalBytes.HasValue && _agent.SwapTotalBytes > 0) { @Text["AgentDetail_SwapTotal"] @FormatBytes(_agent.SwapTotalBytes.Value, Language.Culture) } @if (_agent.SwapFreeBytes.HasValue && _agent.SwapTotalBytes is > 0) { @Text["AgentDetail_SwapDispo"] @FormatBytes(_agent.SwapFreeBytes.Value, Language.Culture) } @if (_agent.ContainerMemoryLimitBytes.HasValue) { Limite conteneur : @FormatBytes(_agent.ContainerMemoryLimitBytes.Value, Language.Culture) } @if (!string.IsNullOrEmpty(_agent.DiskInventoryJson)) { @Text["AgentDetail_Disques"] @{ var disks = ParseDiskJson(_agent.DiskInventoryJson); } @if (disks.Count > 0) { @Text["AgentDetail_PointDeMontage"] @Text["AgentDetail_Fs"] @Text["AgentDetail_Taille"] @Text["AgentDetail_Utilise"] @Text["AgentDetail_Type"] @context.MountPoint @context.FileSystem @(context.TotalBytes.HasValue ? FormatBytes(context.TotalBytes.Value, Language.Culture) : "-") @(context.UsedBytes.HasValue ? FormatBytes(context.UsedBytes.Value, Language.Culture) : "-") @context.Type } else { @Text["AgentDetail_AucunDisqueDetecte"] } }
@* ─── GPU Inventory ─── *@ @{ var gpus = ParseGpuJson(_agent.GpuInventoryJson); } @if (gpus.Count > 0) { @Text["AgentDetail_Modele"] @Text["AgentDetail_Backend"] @Text["AgentDetail_Vram"] @Text["AgentDetail_Temp"] @Text["AgentDetail_Utilisation"] @Text["AgentDetail_Driver"] @Text["AgentDetail_Encoder"] @(context.Model ?? "-") @(context.Backend ?? "-") @(context.VramBytes.HasValue ? FormatBytes(context.VramBytes.Value, Language.Culture) : "-") @(context.TemperatureCelsius.HasValue ? $"{context.TemperatureCelsius.Value.ToString("F0", Language.Culture)}°C" : "-") @(context.UtilizationPercent.HasValue ? $"{context.UtilizationPercent.Value.ToString("F0", Language.Culture)}%" : "-") @(context.DriverVersion ?? "-") @(context.EncoderSupport ?? "-") } else { @Text["AgentDetail_AucunGpuDetecte"] } @* ─── Host & Container ─── *@ @if (_agent.OsName is not null) { @Text["AgentDetail_Os"] @_agent.OsName } @if (_agent.KernelVersion is not null) { @Text["AgentDetail_Noyau"] @_agent.KernelVersion } @if (_agent.Arch is not null) { @Text["AgentDetail_Architecture"] @_agent.Arch } @if (_agent.UptimeMachineSeconds.HasValue) { @Text["AgentDetail_UptimeMachine"] @FormatUptime(_agent.UptimeMachineSeconds.Value) } @if (_agent.ContainerId is not null) { @Text["AgentDetail_Conteneur"] @(_agent.ContainerImage ?? "Conteneur Docker") ID: @_agent.ContainerId } @if (_agent.ContainerCpuLimit.HasValue) { @Text["AgentDetail_CpuLimit"]: @($"{(_agent.ContainerCpuLimit.Value / 100.0).ToString("F1", Language.Culture)} {Text["AgentDetail_Cores"]}") } @* ─── Network Interfaces ─── *@ @{ var interfaces = ParseNetworkJson(_agent.NetworkInterfacesJson); } @if (interfaces.Count > 0) { @Text["AgentDetail_Interface"] @Text["AgentDetail_AdresseIp"] @Text["AgentDetail_Mac"] @Text["AgentDetail_Debit"] @context.Name @(context.IpAddress ?? "-") @(context.MacAddress ?? "-") @(context.SpeedMbps.HasValue ? $"{context.SpeedMbps} Mbps" : "-") } else { @Text["AgentDetail_AucuneInterfaceReseauDetectee"] } @* ─── Temperature ─── *@ @{ var temps = ParseTemperatureJson(_agent.TemperatureJson); } @if (temps.Count > 0) { @Text["AgentDetail_Zone"] @Text["AgentDetail_Temperature"] @context.Zone @{ Color tempColor; if (context.TemperatureCelsius > 70) tempColor = Color.Error; else if (context.TemperatureCelsius > 50) tempColor = Color.Warning; else tempColor = Color.Default; } @($"{context.TemperatureCelsius.ToString("F1", Language.Culture)}°C") } else { @Text["AgentDetail_AucuneSondeDeTemperatureDetectee"] } @* ─── Agent Settings (globals hérités + overrides) ─── *@ @if (_settingsLoading) { } else if (_settingsError) { @Text["AgentDetail_ErreurLorsDuChargementDeLaConfiguration"] @Text["AgentDetail_Reessayer"] } else if (_globalSettings.Count == 0 && _settings.Count == 0) { @Text["AgentDetail_AucunParametreGlobalExposeAuxAgentsPourLeMoment"] } else { @foreach (var category in _globalSettings.GroupBy(s => s.Category).OrderBy(g => g.Key)) {
@category.Key @category.Count()
@foreach (var setting in category) { var overridden = IsOverridden(setting.Key); var effectiveValue = EffectiveValue(setting.Key, setting.Value);
@(setting.Description ?? HumanizeAgentKey(setting.Key)) @(overridden ? Text["AgentDetail_OverrideValue"] : Text["AgentDetail_GlobalValue"])
@if (overridden) { }
@if (overridden) { @Text["AgentDetail_SurchargePourCetAgent"] } else { @Text["AgentDetail_HeriteGlobal"] } @switch (setting.ValueType.ToLowerInvariant()) { case "boolean": case "bool":
@(effectiveValue?.Equals("true", StringComparison.OrdinalIgnoreCase) == true ? Text["AgentDetail_Enabled"] : Text["AgentDetail_Disabled"])
break; case "number": case "int": case "integer": case "double": break; case "select": case "dropdown": @foreach (var opt in (setting.AllowedValues ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { @opt } break; default: break; }
}
} } @if (_settings.Count > 0) { @_settings.Count réglage(s) surchargé(s) pour cet agent — la valeur globale est ignorée pour ces clés. }
@Text["AgentDetail_HistoriqueDesRessources"] @Text["AgentDetail_24H"] @Text["AgentDetail_7Jours"]
@if (_metricHistoryLoading) { } else if (_metricHistoryError) { @Text["AgentDetail_ImpossibleDeChargerLhistoriqueDesRessources"] } else { @if (_metricHistory.LastOrDefault(point => point.InventoryObservedAtUtc.HasValue) is { } inventoryPoint) { @Text["AgentDetail_LatestInventory"] @inventoryPoint.InventoryObservedAtUtc!.Value.ToLocalTime().ToString("g", Language.Culture). } }
@* ─── Agent Logs ─── *@
@Text["AgentDetail_TousLesNiveaux"] @Text["AgentDetail_Critical"] @Text["AgentDetail_Error"] @Text["AgentDetail_Warning"] @Text["AgentDetail_Information"] @Text["AgentDetail_Debug"] @Text["AgentDetail_Trace"] @Text["AgentDetail_Filtrer"]
@if (_logsLoading) { } else if (_logsError) { @Text["AgentDetail_ErreurLorsDuChargementDesLogs"] @Text["AgentDetail_Reessayer"] } else { @Text["AgentDetail_Date"] @Text["AgentDetail_Niveau"] @Text["AgentDetail_Source"] @Text["AgentDetail_Message"] @context.TimestampUtc.ToLocalTime().ToString("g", Language.Culture) @context.Level @(context.Source ?? "-") @if (!string.IsNullOrEmpty(context.Exception)) { @context.Message } else { @context.Message } @Text["AgentDetail_AucunLog"] @Text["AgentDetail_LAgentNARienRemontePourCesFiltres"]
Page @_logPage sur @_logTotalPages (@_logTotal entrées) @Text["AgentDetail_Precedent"] @Text["AgentDetail_Suivant"]
}
@Text["AgentDetail_AgentsDuSite"] @Text["AgentDetail_TousLesAgents"] @Text["AgentDetail_Supprimer"]
} @* ─── Delete Confirmation Dialog ─── *@ @Text["AgentDetail_ConfirmerLaSuppression"] @Text["AgentDetail_SupprimerLeReglage"] @_deletingKey @Text["AgentDetail_PourCetAgent"] @Text["AgentDetail_LAgentSeraNotifieEnTempsReelViaSignalrEtUtiliseraLaValeurGlobaleParDefaut"] @Text["AgentDetail_Annuler"] @Text["AgentDetail_Supprimer"] @* ─── Delete Agent Confirmation Dialog ─── *@ @Text["AgentDetail_ConfirmerLaSuppression"] @Text["AgentDetail_SupprimerLAgent"] @_agent?.Name ? @Text["AgentDetail_LesCamerasAssocieesSerontDesassigneesMaisPasSupprimees"] @Text["AgentDetail_Annuler"] @Text["AgentDetail_Supprimer"] @* ─── Add / Edit Dialog ─── *@ @(_editingSetting is null ? Text["AgentDetail_AddSetting"] : Text["AgentDetail_EditSetting"]) @Text["AgentDetail_Annuler"] @(_editingSetting is null ? Text["AgentDetail_AddSetting"] : Text["Save"]) @code { [Parameter] public Guid Id { get; set; } private AgentItem? _agent; private bool _loading = true; private List _metricHistory = []; private bool _metricHistoryLoading; private bool _metricHistoryError; private string _metricRange = "24h"; // Updates private LatestReleaseInfo? _updateInfo; // Settings private List _settings = []; private List _globalSettings = []; private bool _settingsLoading; private bool _settingsError; private bool _saving; private AgentSettingItem? _editingSetting; private string _editKey = string.Empty; private string _editValue = string.Empty; private bool _showEditDialog; private bool _confirmDeleteVisible; private string _deletingKey = string.Empty; private bool _deleting; // Delete agent private bool _confirmDeleteAgentVisible; private bool _deletingAgent; // Logs private IReadOnlyList? _logs; private bool _logsLoading; private bool _logsError; private int _logPage = 1; private int _logTotalPages = 1; private int _logTotal; private string? _logLevel; private string? _logSearch; private bool _autoRefresh; private CancellationTokenSource? _refreshCts; private bool _disposed; private readonly DialogOptions _dialogOptions = new() { MaxWidth = MaxWidth.Small, FullWidth = true, CloseButton = true }; protected override async Task OnInitializedAsync() { Language.LanguageChanged += OnLanguageChanged; try { _agent = await Api.GetAgentAsync(Id); if (_agent is not null) { await LoadMetricHistoryAsync(_metricRange); await LoadSettingsAsync(); await LoadLogsAsync(keepPage: false); _ = LoadUpdateInfoAsync(); } } catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } finally { _loading = false; } } private void OnLanguageChanged() => _ = InvokeAsync(StateHasChanged); private async Task LoadMetricHistoryAsync(string range) { _metricRange = range; _metricHistoryLoading = true; _metricHistoryError = false; try { _metricHistory = await Api.GetAgentMetricHistoryAsync(Id, range) ?? []; } catch { _metricHistoryError = true; _metricHistory = []; } finally { _metricHistoryLoading = false; } } private List MetricSeries(Func selector) => _metricHistory.Select(point => new MetricChartPoint(point.TimestampUtc, selector(point))).ToList(); private static double? MemoryUsedPercent(AgentMetricHistoryPoint point) => point.MemoryUsedBytes is { } used && point.MemoryTotalBytes is > 0 ? Math.Clamp(100d * used / point.MemoryTotalBytes.Value, 0, 100) : null; private async Task LoadSettingsAsync() { _settingsError = false; _settingsLoading = true; try { _globalSettings = (await Api.GetSettingsAsync()) .Where(s => s.AgentScoped) .Where(s => !string.Equals(s.Key, "autoupdateenabled", StringComparison.OrdinalIgnoreCase)) .OrderBy(s => s.Category) .ThenBy(s => s.Key) .ToList(); _settings = (await Api.GetAgentSettingsAsync(Id)) .Where(s => !string.Equals(s.Key, "autoupdateenabled", StringComparison.OrdinalIgnoreCase)) .ToList(); } catch { _settingsError = true; _settings = []; _globalSettings = []; } finally { _settingsLoading = false; } } private async Task LoadUpdateInfoAsync() { try { _updateInfo = await Api.GetLatestUpdateAsync(); } catch { _updateInfo = null; } await InvokeAsync(StateHasChanged); } private async Task TriggerUpdateAsync() { try { var result = await Api.TriggerAgentUpdateAsync(Id); if (result is not null) Snackbar.Add(string.Format(Language.Culture, Text["AgentDetail_UpdateStarted"], result.Version), Severity.Success); else Snackbar.Add(Text["AgentDetail_UpdateStartFailed"], Severity.Error); } catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } } private async Task ExecuteDeleteAgentAsync() { _deletingAgent = true; try { _confirmDeleteAgentVisible = false; var error = await Api.DeleteAgentAsync(Id); if (error is null) { Snackbar.Add(string.Format(Language.Culture, Text["AgentDetail_AgentDeleted"], _agent?.Name), Severity.Success); Nav.NavigateTo("/admin/agents"); } else { Snackbar.Add(error, Severity.Error); } } catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } finally { _deletingAgent = false; } } /// Returns the effective value for a global setting key (override wins). private string EffectiveValue(string key, string globalValue) => _settings.FirstOrDefault(s => s.Key == key)?.Value ?? globalValue; /// True when the agent overrides this global key. private bool IsOverridden(string key) => _settings.Any(s => s.Key == key); private async Task SaveGlobalOverrideAsync(AppSettingItem setting, string value) { _saving = true; try { var response = await Api.SetAgentSettingAsync(Id, new SetAgentSettingRequest(setting.Key, value)); if (response.IsSuccessStatusCode) { Snackbar.Add(string.Format(Language.Culture, Text["AgentDetail_OverrideSaved"], setting.Key), Severity.Success); await LoadSettingsAsync(); } else { var error = await response.Content.ReadAsStringAsync(); Snackbar.Add(string.Format(Language.Culture, Text["AgentDetail_ErrorDetails"], error), Severity.Error); } } catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } finally { _saving = false; } } private async Task SaveGlobalOverrideBoolAsync(AppSettingItem setting, bool value) => await SaveGlobalOverrideAsync(setting, value.ToString().ToLowerInvariant()); private void OpenAddDialog() { _editingSetting = null; _editKey = string.Empty; _editValue = string.Empty; _showEditDialog = true; } private void OpenEditDialog(AgentSettingItem setting) { _editingSetting = setting; _editKey = setting.Key; _editValue = setting.Value; _showEditDialog = true; } private async Task SaveSettingAsync() { if (string.IsNullOrWhiteSpace(_editKey)) return; _saving = true; try { var request = new SetAgentSettingRequest(_editKey.Trim(), _editValue); var response = await Api.SetAgentSettingAsync(Id, request); if (response.IsSuccessStatusCode) { Snackbar.Add(Text["AgentDetail_SettingSaved"], Severity.Success); _showEditDialog = false; await LoadSettingsAsync(); } else { var error = await response.Content.ReadAsStringAsync(); Snackbar.Add(string.Format(Language.Culture, Text["AgentDetail_ErrorDetails"], error), Severity.Error); } } catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } finally { _saving = false; } } private void ConfirmRemoveSetting(AgentSettingItem setting) { _deletingKey = setting.Key; _confirmDeleteVisible = true; } private async Task ExecuteRemoveSettingAsync() { _deleting = true; try { var response = await Api.RemoveAgentSettingAsync(Id, _deletingKey); if (response.IsSuccessStatusCode) { _confirmDeleteVisible = false; Snackbar.Add(Text["AgentDetail_SettingDeleted"], Severity.Success); await LoadSettingsAsync(); } else { Snackbar.Add(Text["AgentDetail_DeleteSettingFailed"], Severity.Error); } } catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } finally { _deleting = false; } } private async Task ExecuteRemoveSettingByKey(string key) { _deleting = true; try { var response = await Api.RemoveAgentSettingAsync(Id, key); if (response.IsSuccessStatusCode) { Snackbar.Add(string.Format(Language.Culture, Text["AgentDetail_OverrideReset"], key), Severity.Success); await LoadSettingsAsync(); } else { Snackbar.Add(Text["AgentDetail_ResetSettingFailed"], Severity.Error); } } catch { Snackbar.Add(UiErrors.OperationFailed(), Severity.Error); } finally { _deleting = false; } } private async Task LoadLogsAsync(bool keepPage) { if (!keepPage) _logPage = 1; _logsError = false; _logsLoading = true; try { var result = await Api.GetAgentLogsAsync(Id, _logLevel, _logSearch, _logPage); if (result is not null) { _logs = result.Items; _logTotal = result.TotalCount; _logTotalPages = Math.Max(1, (int)Math.Ceiling(result.TotalCount / (double)result.PageSize)); } } catch { _logsError = true; _logs = []; } finally { _logsLoading = false; if (!_disposed) await InvokeAsync(StateHasChanged); } } private async Task GoToLogPage(int page) { _logPage = page; await LoadLogsAsync(keepPage: true); } private async Task ToggleAutoRefresh(bool enabled) { _autoRefresh = enabled; if (_refreshCts is not null) { await _refreshCts.CancelAsync(); _refreshCts.Dispose(); _refreshCts = null; } if (enabled) { _refreshCts = new CancellationTokenSource(); _ = AutoRefreshLoopAsync(_refreshCts.Token); } } private async Task AutoRefreshLoopAsync(CancellationToken ct) { try { while (!ct.IsCancellationRequested) { await Task.Delay(TimeSpan.FromSeconds(10), ct); if (!_disposed && _agent is not null) await LoadLogsAsync(keepPage: true); } } catch (OperationCanceledException) { /* arrêt volontaire */ } } private static Color GetLogLevelColor(string level) => level switch { "Critical" or "Error" => Color.Error, "Warning" => Color.Warning, "Information" => Color.Info, _ => Color.Default }; public async ValueTask DisposeAsync() { _disposed = true; Language.LanguageChanged -= OnLanguageChanged; if (_refreshCts is not null) { await _refreshCts.CancelAsync(); _refreshCts.Dispose(); _refreshCts = null; } } private static Color GetStatusColor(string status) => status switch { "Online" => Color.Success, "Offline" => Color.Error, "Error" => Color.Warning, _ => Color.Default }; private static string GetStatusIcon(string status) => status switch { "Online" => "●", "Offline" => "○", "Error" => "⚠", _ => "?" }; private static string FormatMemory(long mb, System.Globalization.CultureInfo culture) => mb switch { > 102400 => $"{(mb / 1024d).ToString("F0", culture)} GB", > 0 => $"{mb.ToString(culture)} MB", _ => "-" }; // ─── Settings visual helpers ───────────────────────────────────── private static Color GetAgentTypeColor(string valueType) => valueType.ToLowerInvariant() switch { "boolean" or "bool" => Color.Success, "number" or "int" or "integer" or "double" => Color.Info, "select" or "dropdown" => Color.Warning, _ => Color.Secondary }; private static string GetAgentTypeIcon(string valueType) => valueType.ToLowerInvariant() switch { "boolean" or "bool" => Icons.Material.Filled.ToggleOn, "number" or "int" or "integer" or "double" => Icons.Material.Filled.Tag, "select" or "dropdown" => Icons.Material.Filled.ArrowDropDownCircle, _ => Icons.Material.Filled.TextFields }; private static string GetAgentCategoryIcon(string category) => category.ToLowerInvariant() switch { "detection" => Icons.Material.Filled.Visibility, "recording" => Icons.Material.Filled.Videocam, "logging" or "log" => Icons.Material.Filled.BugReport, "network" => Icons.Material.Filled.Wifi, "storage" => Icons.Material.Filled.Storage, "notification" or "notifications" => Icons.Material.Filled.Notifications, "heartbeat" => Icons.Material.Filled.MonitorHeart, _ => Icons.Material.Filled.Settings }; private static string HumanizeAgentKey(string key) { var parts = key.Split('.', '_', '-'); return string.Join(' ', parts.Select(p => p.Length <= 2 ? p.ToUpperInvariant() : char.ToUpperInvariant(p[0]) + p[1..])); } // ─── Inventory helpers ───────────────────────────────────────── private static string FormatBytes(long bytes, System.Globalization.CultureInfo culture) => bytes switch { >= 1_073_741_824L => $"{(bytes / 1_073_741_824.0).ToString("F1", culture)} GB", >= 1_048_576L => $"{(bytes / 1_048_576.0).ToString("F1", culture)} MB", >= 1024L => $"{(bytes / 1024.0).ToString("F1", culture)} KB", _ => $"{bytes.ToString(culture)} B" }; private string FormatUptime(long seconds) => seconds switch { >= 86400 => string.Format(Language.Culture, Text["AgentDetail_UptimeDays"], seconds / 86400, seconds % 86400 / 3600), >= 3600 => string.Format(Language.Culture, Text["AgentDetail_UptimeHours"], seconds / 3600, seconds % 3600 / 60), >= 60 => string.Format(Language.Culture, Text["AgentDetail_UptimeMinutes"], seconds / 60, seconds % 60), _ => string.Format(Language.Culture, Text["AgentDetail_UptimeSeconds"], seconds) }; private static List ParseDiskJson(string? json) { if (string.IsNullOrWhiteSpace(json)) return []; try { return System.Text.Json.JsonSerializer.Deserialize>(json) ?? []; } catch { return []; } } private static List ParseGpuJson(string? json) { if (string.IsNullOrWhiteSpace(json)) return []; try { return System.Text.Json.JsonSerializer.Deserialize>(json) ?? []; } catch { return []; } } private static List ParseNetworkJson(string? json) { if (string.IsNullOrWhiteSpace(json)) return []; try { return System.Text.Json.JsonSerializer.Deserialize>(json) ?? []; } catch { return []; } } private static List ParseTemperatureJson(string? json) { if (string.IsNullOrWhiteSpace(json)) return []; try { return System.Text.Json.JsonSerializer.Deserialize>(json) ?? []; } catch { return []; } } // DTOs for JSON deserialization private sealed class DiskDto { public string MountPoint { get; init; } = ""; public string FileSystem { get; init; } = ""; public long? TotalBytes { get; init; } = null; public long? UsedBytes { get; init; } = null; public string Type { get; init; } = "Unknown"; } [Serializable] private sealed class GpuDto { [JsonPropertyName("model")] public string? Model { get; init; } [JsonPropertyName("vramBytes")] public long? VramBytes { get; init; } [JsonPropertyName("driverVersion")] public string? DriverVersion { get; init; } [JsonPropertyName("temperatureCelsius")] public double? TemperatureCelsius { get; init; } [JsonPropertyName("utilizationPercent")] public double? UtilizationPercent { get; init; } [JsonPropertyName("backend")] public string? Backend { get; init; } [JsonPropertyName("encoderSupport")] public string? EncoderSupport { get; init; } } [Serializable] private sealed class NetworkDto { public string Name { get; init; } = ""; [JsonPropertyName("ipAddress")] public string? IpAddress { get; init; } [JsonPropertyName("macAddress")] public string? MacAddress { get; init; } [JsonPropertyName("speedMbps")] public long? SpeedMbps { get; init; } } [Serializable] private sealed class TempDto { public string Zone { get; init; } = ""; [JsonPropertyName("temperatureCelsius")] public double TemperatureCelsius { get; init; } } }