@page "/agents/{Id:guid}"
@attribute [Authorize(Policy = "Admin.Users")]
@layout MainLayout
@inject HeimdallApiClient Api
@inject ISnackbar Snackbar
@inject NavigationManager Nav
@implements IAsyncDisposable
Agent : @_agent?.Name
@if (_loading)
{
}
else if (_agent is null)
{
Retour aux agents
}
else
{
@* ─── Status Bar ─── *@
Dernier heartbeat : @(_agent.LastHeartbeat?.ToString("g") ?? "Jamais")
Hostname
@_agent.Hostname
Version
@_agent.Version
Statut
@GetStatusIcon(_agent.Status) @_agent.Status
IP publique
@(_agent.PublicIp ?? "-")
Dernier heartbeat
@(_agent.LastHeartbeat?.ToString("g") ?? "Jamais")
Enregistré le
@_agent.CreatedAt.ToString("g")
CPU
@_agent.CpuCores cœurs
Mémoire
@FormatMemory(_agent.MemoryMb)
GPU
@(_agent.HasGpu ? _agent.GpuType : "Aucun")
@* ─── Hardware Inventory ─── *@
@* ─── CPU Inventory ─── *@
@if (_agent.CpuModel is not null)
{
Modèle
@_agent.CpuModel
}
@if (_agent.CpuVendor is not null)
{
Fabricant
@_agent.CpuVendor
}
@if (_agent.CpuArchitecture is not null)
{
Architecture
@_agent.CpuArchitecture
}
@if (_agent.PhysicalCores.HasValue)
{
Cœurs physiques
@_agent.PhysicalCores
}
@if (_agent.LogicalCores.HasValue)
{
Cœurs logiques
@_agent.LogicalCores
}
@if (_agent.ThreadsPerCore.HasValue)
{
Threads/noyau
@_agent.ThreadsPerCore
}
@if (_agent.CpuFrequencyMhz.HasValue)
{
Fréquence
@($"{_agent.CpuFrequencyMhz:F0} MHz")
}
@if (_agent.CpuCacheBytes.HasValue && _agent.CpuCacheBytes > 0)
{
Cache
@FormatBytes(_agent.CpuCacheBytes.Value)
}
@if (!string.IsNullOrEmpty(_agent.CpuFlags))
{
Instructions clés
@foreach (var flag in _agent.CpuFlags.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
@flag
}
}
@* ─── Memory & Disk Inventory ─── *@
@if (_agent.MemTotalBytes.HasValue)
{
Mémoire totale
@FormatBytes(_agent.MemTotalBytes.Value)
}
@if (_agent.MemAvailableBytes.HasValue)
{
Mémoire dispo
@FormatBytes(_agent.MemAvailableBytes.Value)
}
@if (_agent.SwapTotalBytes.HasValue && _agent.SwapTotalBytes > 0)
{
Swap total
@FormatBytes(_agent.SwapTotalBytes.Value)
}
@if (_agent.SwapFreeBytes.HasValue && _agent.SwapTotalBytes is > 0)
{
Swap dispo
@FormatBytes(_agent.SwapFreeBytes.Value)
}
@if (_agent.ContainerMemoryLimitBytes.HasValue)
{
Limite conteneur : @FormatBytes(_agent.ContainerMemoryLimitBytes.Value)
}
@if (!string.IsNullOrEmpty(_agent.DiskInventoryJson))
{
Disques
@{
var disks = ParseDiskJson(_agent.DiskInventoryJson);
}
@if (disks.Count > 0)
{
Point de montage
FS
Taille
Utilisé
Type
@context.MountPoint
@context.FileSystem
@(context.TotalBytes.HasValue ? FormatBytes(context.TotalBytes.Value) : "-")
@(context.UsedBytes.HasValue ? FormatBytes(context.UsedBytes.Value) : "-")
@context.Type
}
else
{
Aucun disque détecté
}
}
@* ─── GPU Inventory ─── *@
@{
var gpus = ParseGpuJson(_agent.GpuInventoryJson);
}
@if (gpus.Count > 0)
{
Modèle
Backend
VRAM
Temp
Utilisation
Driver
Encoder
@(context.Model ?? "-")
@(context.Backend ?? "-")
@(context.VramBytes.HasValue ? FormatBytes(context.VramBytes.Value) : "-")
@(context.TemperatureCelsius.HasValue ? $"{context.TemperatureCelsius:F0}°C" : "-")
@(context.UtilizationPercent.HasValue ? $"{context.UtilizationPercent:F0}%" : "-")
@(context.DriverVersion ?? "-")
@(context.EncoderSupport ?? "-")
}
else
{
Aucun GPU détecté
}
@* ─── Host & Container ─── *@
@if (_agent.OsName is not null)
{
OS
@_agent.OsName
}
@if (_agent.KernelVersion is not null)
{
Noyau
@_agent.KernelVersion
}
@if (_agent.Arch is not null)
{
Architecture
@_agent.Arch
}
@if (_agent.UptimeMachineSeconds.HasValue)
{
Uptime machine
@FormatUptime(_agent.UptimeMachineSeconds.Value)
}
@if (_agent.ContainerId is not null)
{
Conteneur
@(_agent.ContainerImage ?? "Conteneur Docker")
ID: @_agent.ContainerId
}
@if (_agent.ContainerCpuLimit.HasValue)
{
CPU limite: @($"{_agent.ContainerCpuLimit.Value / 100.0:F1} cores")
}
@* ─── Network Interfaces ─── *@
@{
var interfaces = ParseNetworkJson(_agent.NetworkInterfacesJson);
}
@if (interfaces.Count > 0)
{
Interface
Adresse IP
MAC
Débit
@context.Name
@(context.IpAddress ?? "-")
@(context.MacAddress ?? "-")
@(context.SpeedMbps.HasValue ? $"{context.SpeedMbps} Mbps" : "-")
}
else
{
Aucune interface réseau détectée
}
@* ─── Temperature ─── *@
@{
var temps = ParseTemperatureJson(_agent.TemperatureJson);
}
@if (temps.Count > 0)
{
Zone
Température
@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:F1}°C")
}
else
{
Aucune sonde de température détectée
}
@* ─── Agent Settings (globals hérités + overrides) ─── *@
@if (_settingsLoading)
{
}
else if (_settingsError)
{
Erreur lors du chargement de la configuration
Réessayer
}
else if (_globalSettings.Count == 0 && _settings.Count == 0)
{
Aucun paramètre global exposé aux agents pour le moment.
}
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 ? "Valeur surchargée pour cet agent" : "Valeur globale appliquée")
@if (overridden)
{
}
@if (overridden)
{
Surchargé pour cet agent
}
else
{
Hérité (global)
}
@switch (setting.ValueType.ToLowerInvariant())
{
case "boolean":
case "bool":
@(effectiveValue?.Equals("true", StringComparison.OrdinalIgnoreCase) == true ? "Activé" : "Désactivé")
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.
}
Historique des ressources
24 h
7 jours
@if (_metricHistoryLoading)
{
}
else if (_metricHistoryError)
{
Impossible de charger l’historique des ressources.
}
else
{
@if (_metricHistory.LastOrDefault(point => point.InventoryObservedAtUtc.HasValue) is { } inventoryPoint)
{
Dernier inventaire GPU/température reçu : @inventoryPoint.InventoryObservedAtUtc!.Value.ToLocalTime().ToString("g").
}
}
@* ─── Agent Logs ─── *@
Tous les niveaux
Critical
Error
Warning
Information
Debug
Trace
Filtrer
@if (_logsLoading)
{
}
else if (_logsError)
{
Erreur lors du chargement des logs.
Réessayer
}
else
{
Date
Niveau
Source
Message
@context.TimestampUtc.ToLocalTime().ToString("g")
@context.Level
@(context.Source ?? "-")
@if (!string.IsNullOrEmpty(context.Exception))
{
@context.Message
}
else
{
@context.Message
}
Aucun log
L'agent n'a rien remonté pour ces filtres.
Page @_logPage sur @_logTotalPages (@_logTotal entrées)
← Précédent
Suivant →
}
← Agents du site
← Tous les agents
Supprimer
}
@* ─── Delete Confirmation Dialog ─── *@
Confirmer la suppression
Supprimer le réglage @_deletingKey pour cet agent ?
L'agent sera notifié en temps réel via SignalR et utilisera la valeur globale par défaut.
Annuler
Supprimer
@* ─── Delete Agent Confirmation Dialog ─── *@
Confirmer la suppression
Supprimer l'agent @_agent?.Name ?
Les caméras associées seront désassignées mais pas supprimées.
Annuler
Supprimer
@* ─── Add / Edit Dialog ─── *@
@(_editingSetting is null ? "Ajouter un réglage" : "Modifier le réglage")
Annuler
@(_editingSetting is null ? "Ajouter" : "Enregistrer")
@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()
{
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 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)
.OrderBy(s => s.Category)
.ThenBy(s => s.Key)
.ToList();
_settings = await Api.GetAgentSettingsAsync(Id);
}
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($"Mise à jour vers v{result.Version} déclenchée", Severity.Success);
else
Snackbar.Add("Erreur lors du déclenchement de la mise à jour", 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($"Agent \"{_agent?.Name}\" supprimé", 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($"« {setting.Key} » surchargé pour cet agent — envoyé en temps réel", Severity.Success);
await LoadSettingsAsync();
}
else
{
var error = await response.Content.ReadAsStringAsync();
Snackbar.Add($"Erreur : {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("Réglage enregistré et envoyé à l'agent en temps réel", Severity.Success);
_showEditDialog = false;
await LoadSettingsAsync();
}
else
{
var error = await response.Content.ReadAsStringAsync();
Snackbar.Add($"Erreur : {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("Réglage supprimé, agent notifié en temps réel", Severity.Success);
await LoadSettingsAsync();
}
else
{
Snackbar.Add("Erreur lors de la suppression", 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($"« {key} » réinitialisé à la valeur globale — agent notifié", Severity.Success);
await LoadSettingsAsync();
}
else
{
Snackbar.Add("Erreur lors de la réinitialisation", 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;
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) => mb switch
{
> 102400 => $"{mb / 1024:F0} Go",
> 0 => $"{mb} Mo",
_ => "-"
};
// ─── 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) => bytes switch
{
>= 1_073_741_824L => $"{bytes / 1_073_741_824.0:F1} Go",
>= 1_048_576L => $"{bytes / 1_048_576.0:F1} Mo",
>= 1024L => $"{bytes / 1024.0:F1} Ko",
_ => $"{bytes} o"
};
private static string FormatUptime(long seconds) => seconds switch
{
>= 86400 => $"{seconds / 86400}j {seconds % 86400 / 3600}h",
>= 3600 => $"{seconds / 3600}h {seconds % 3600 / 60}m",
>= 60 => $"{seconds / 60}m {seconds % 60}s",
_ => $"{seconds}s"
};
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; }
}
}