Files
Heimdall/src/Heimdall.Web/Components/Pages/AgentDetail.razor
T
Arnaud Dartois 8d35518d1a
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Failing after 2m11s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 3s
feat(agent): add Pangolin-style native installs and updates
2026-10-26 11:38:29 +01:00

1375 lines
65 KiB
Plaintext

@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
<MudText Typo="Typo.h1" Class="mb-6">
<MudIcon Icon="@Icons.Material.Filled.Dns" Class="mr-2" />
@Text["AgentDetail_Agent"] @_agent?.Name
</MudText>
@if (_loading)
{
<LoadingSkeleton LineCount="6" />
}
else if (_agent is null)
{
<EmptyState Icon="@Icons.Material.Filled.Dns"
Title="@Text["AgentDetail_AgentIntrouvable"]"
Description="@Text["AgentDetail_LAgentDemandeNExistePasOuAEteSupprime"]">
<ActionContent>
<MudButton Variant="Variant.Outlined" Color="Color.Primary"
OnClick="@(() => Nav.NavigateTo("/admin/agents"))">
<MudIcon Icon="@Icons.Material.Filled.ArrowBack" Class="mr-1" /> @Text["AgentDetail_RetourAuxAgents"]
</MudButton>
</ActionContent>
</EmptyState>
}
else
{
@* ─── Status Bar ─── *@
<div class="d-flex align-center mb-4">
<StatusChip Text="@UiFormat.Status(_agent.Status)"
Color="@GetStatusColor(_agent.Status)"
Icon="@GetStatusIcon(_agent.Status)"
Size="Size.Medium" />
<MudSpacer />
<MudText Typo="Typo.body2" Color="Color.Secondary">
@Text["AgentDetail_LastHeartbeat"]: @(_agent.LastHeartbeat?.ToString("g", Language.Culture) ?? Text["AgentDetail_Jamais"])
</MudText>
</div>
<MudGrid>
<MudItem xs="12" md="6">
<SectionCard Title="@Text["AgentDetail_Informations"]" Icon="@Icons.Material.Filled.Info" Elevation="2">
<MudGrid>
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Hostname"]</MudText>
<MudText Typo="Typo.body1">@_agent.Hostname</MudText>
</MudItem>
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Version"]</MudText>
<MudText Typo="Typo.body1">@_agent.Version</MudText>
</MudItem>
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Statut"]</MudText>
<MudText Color="@GetStatusColor(_agent.Status)" Typo="Typo.body1">
@GetStatusIcon(_agent.Status) @UiFormat.Status(_agent.Status)
</MudText>
</MudItem>
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_IpPublique"]</MudText>
<MudText Typo="Typo.body1">@(_agent.PublicIp ?? "-")</MudText>
</MudItem>
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_DernierHeartbeat"]</MudText>
<MudText Typo="Typo.body1">@(_agent.LastHeartbeat?.ToString("g", Language.Culture) ?? Text["AgentDetail_Jamais"])</MudText>
</MudItem>
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_EnregistreLe"]</MudText>
<MudText Typo="Typo.body1">@_agent.CreatedAt.ToString("g", Language.Culture)</MudText>
</MudItem>
</MudGrid>
</SectionCard>
</MudItem>
<MudItem xs="12" md="6">
<SectionCard Title="@Text["AgentDetail_Capacites"]" Icon="@Icons.Material.Filled.Dns" Elevation="2">
<MudGrid>
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Cpu"]</MudText>
<MudText Typo="Typo.body1">@string.Format(Language.Culture, Text["AgentDetail_CpuCoreCount"], _agent.CpuCores)</MudText>
</MudItem>
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Memoire"]</MudText>
<MudText Typo="Typo.body1">@FormatMemory(_agent.MemoryMb, Language.Culture)</MudText>
</MudItem>
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Gpu"]</MudText>
<MudText Typo="Typo.body1">
<MudIcon Icon="@(_agent.HasGpu ? Icons.Material.Filled.CheckCircle : Icons.Material.Filled.Cancel)"
Color="@(_agent.HasGpu ? Color.Success : Color.Default)" Size="Size.Small" />
@(_agent.HasGpu ? _agent.GpuType : Text["AgentDetail_NoGpu"])
</MudText>
</MudItem>
</MudGrid>
</SectionCard>
</MudItem>
</MudGrid>
@* ─── Hardware Inventory ─── *@
<MudGrid Class="mt-4">
@* ─── CPU Inventory ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="@Text["AgentDetail_Processeur"]" Icon="@Icons.Material.Filled.Memory" Elevation="2">
<MudGrid>
@if (_agent.CpuModel is not null)
{
<MudItem xs="12">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Modele"]</MudText>
<MudText Typo="Typo.body1" Class="font-weight-medium">@_agent.CpuModel</MudText>
</MudItem>
}
@if (_agent.CpuVendor is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Fabricant"]</MudText>
<MudText Typo="Typo.body1">@_agent.CpuVendor</MudText>
</MudItem>
}
@if (_agent.CpuArchitecture is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Architecture"]</MudText>
<MudText Typo="Typo.body1">@_agent.CpuArchitecture</MudText>
</MudItem>
}
@if (_agent.PhysicalCores.HasValue)
{
<MudItem xs="4">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_CursPhysiques"]</MudText>
<MudText Typo="Typo.body1">@_agent.PhysicalCores</MudText>
</MudItem>
}
@if (_agent.LogicalCores.HasValue)
{
<MudItem xs="4">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_CursLogiques"]</MudText>
<MudText Typo="Typo.body1">@_agent.LogicalCores</MudText>
</MudItem>
}
@if (_agent.ThreadsPerCore.HasValue)
{
<MudItem xs="4">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_ThreadsNoyau"]</MudText>
<MudText Typo="Typo.body1">@_agent.ThreadsPerCore</MudText>
</MudItem>
}
@if (_agent.CpuFrequencyMhz.HasValue)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Frequence"]</MudText>
<MudText Typo="Typo.body1">@($"{_agent.CpuFrequencyMhz.Value.ToString("F0", Language.Culture)} MHz")</MudText>
</MudItem>
}
@if (_agent.CpuCacheBytes.HasValue && _agent.CpuCacheBytes > 0)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Cache"]</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.CpuCacheBytes.Value, Language.Culture)</MudText>
</MudItem>
}
@if (!string.IsNullOrEmpty(_agent.CpuFlags))
{
<MudItem xs="12" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_InstructionsCles"]</MudText>
<div class="d-flex flex-wrap gap-1 mt-1">
@foreach (var flag in _agent.CpuFlags.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
<MudChip T="string" Size="Size.Small" Color="Color.Info" Variant="Variant.Outlined">@flag</MudChip>
}
</div>
</MudItem>
}
</MudGrid>
</SectionCard>
</MudItem>
@* ─── Memory & Disk Inventory ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="@Text["AgentDetail_MemoireStockage"]" Icon="@Icons.Material.Filled.Storage" Elevation="2">
<MudGrid>
@if (_agent.MemTotalBytes.HasValue)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_MemoireTotale"]</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.MemTotalBytes.Value, Language.Culture)</MudText>
</MudItem>
}
@if (_agent.MemAvailableBytes.HasValue)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_MemoireDispo"]</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.MemAvailableBytes.Value, Language.Culture)</MudText>
</MudItem>
}
@if (_agent.SwapTotalBytes.HasValue && _agent.SwapTotalBytes > 0)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_SwapTotal"]</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.SwapTotalBytes.Value, Language.Culture)</MudText>
</MudItem>
}
@if (_agent.SwapFreeBytes.HasValue && _agent.SwapTotalBytes is > 0)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_SwapDispo"]</MudText>
<MudText Typo="Typo.body1">@FormatBytes(_agent.SwapFreeBytes.Value, Language.Culture)</MudText>
</MudItem>
}
@if (_agent.ContainerMemoryLimitBytes.HasValue)
{
<MudItem xs="12" Class="mt-2">
<MudChip T="string" Size="Size.Small" Color="Color.Warning">
Limite conteneur : @FormatBytes(_agent.ContainerMemoryLimitBytes.Value, Language.Culture)
</MudChip>
</MudItem>
}
@if (!string.IsNullOrEmpty(_agent.DiskInventoryJson))
{
<MudItem xs="12" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Disques"]</MudText>
@{
var disks = ParseDiskJson(_agent.DiskInventoryJson);
}
@if (disks.Count > 0)
{
<MudTable Items="@disks" Dense="true" Hover="true" Elevation="0" Class="mt-1">
<HeaderContent>
<MudTh>@Text["AgentDetail_PointDeMontage"]</MudTh>
<MudTh>@Text["AgentDetail_Fs"]</MudTh>
<MudTh>@Text["AgentDetail_Taille"]</MudTh>
<MudTh>@Text["AgentDetail_Utilise"]</MudTh>
<MudTh>@Text["AgentDetail_Type"]</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="@Text["AgentDetail_PointDeMontage"]">
<MudText Typo="Typo.body2">@context.MountPoint</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Fs"]">
<MudText Typo="Typo.body2">@context.FileSystem</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Taille"]">
<MudText Typo="Typo.body2">@(context.TotalBytes.HasValue ? FormatBytes(context.TotalBytes.Value, Language.Culture) : "-")</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Utilise"]">
<MudText Typo="Typo.body2">@(context.UsedBytes.HasValue ? FormatBytes(context.UsedBytes.Value, Language.Culture) : "-")</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Type"]">
<MudChip T="string" Size="Size.Small"
Color="@(context.Type == "SSD" ? Color.Success : Color.Default)">
@context.Type
</MudChip>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-1">@Text["AgentDetail_AucunDisqueDetecte"]</MudText>
}
</MudItem>
}
</MudGrid>
</SectionCard>
</MudItem>
</MudGrid>
<MudGrid Class="mt-4">
@* ─── GPU Inventory ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="@Text["AgentDetail_Gpu"]" Icon="@Icons.Material.Filled.Videocam" Elevation="2">
@{
var gpus = ParseGpuJson(_agent.GpuInventoryJson);
}
@if (gpus.Count > 0)
{
<MudTable Items="@gpus" Dense="true" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>@Text["AgentDetail_Modele"]</MudTh>
<MudTh>@Text["AgentDetail_Backend"]</MudTh>
<MudTh>@Text["AgentDetail_Vram"]</MudTh>
<MudTh>@Text["AgentDetail_Temp"]</MudTh>
<MudTh>@Text["AgentDetail_Utilisation"]</MudTh>
<MudTh>@Text["AgentDetail_Driver"]</MudTh>
<MudTh>@Text["AgentDetail_Encoder"]</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="@Text["AgentDetail_Modele"]">
<MudText Typo="Typo.body2" Class="font-weight-medium">@(context.Model ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Backend"]">
<MudChip T="string" Size="Size.Small" Color="Color.Info">@(context.Backend ?? "-")</MudChip>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Vram"]">
<MudText Typo="Typo.body2">@(context.VramBytes.HasValue ? FormatBytes(context.VramBytes.Value, Language.Culture) : "-")</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Temp"]">
<MudText Typo="Typo.body2">@(context.TemperatureCelsius.HasValue ? $"{context.TemperatureCelsius.Value.ToString("F0", Language.Culture)}°C" : "-")</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Utilisation"]">
<MudText Typo="Typo.body2">@(context.UtilizationPercent.HasValue ? $"{context.UtilizationPercent.Value.ToString("F0", Language.Culture)}%" : "-")</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Driver"]">
<MudText Typo="Typo.body2">@(context.DriverVersion ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Encoder"]">
<MudText Typo="Typo.body2">@(context.EncoderSupport ?? "-")</MudText>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_AucunGpuDetecte"]</MudText>
}
</SectionCard>
</MudItem>
@* ─── Host & Container ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="@Text["AgentDetail_SystemContainer"]" Icon="@Icons.Material.Filled.Computer" Elevation="2">
<MudGrid>
@if (_agent.OsName is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Os"]</MudText>
<MudText Typo="Typo.body1">@_agent.OsName</MudText>
</MudItem>
}
@if (_agent.KernelVersion is not null)
{
<MudItem xs="6">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Noyau"]</MudText>
<MudText Typo="Typo.body1">@_agent.KernelVersion</MudText>
</MudItem>
}
@if (_agent.Arch is not null)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Architecture"]</MudText>
<MudText Typo="Typo.body1">@_agent.Arch</MudText>
</MudItem>
}
@if (_agent.UptimeMachineSeconds.HasValue)
{
<MudItem xs="6" Class="mt-2">
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_UptimeMachine"]</MudText>
<MudText Typo="Typo.body1">@FormatUptime(_agent.UptimeMachineSeconds.Value)</MudText>
</MudItem>
}
@if (_agent.ContainerId is not null)
{
<MudItem xs="12" Class="mt-2">
<MudDivider Class="mb-2" />
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_Conteneur"]</MudText>
<MudText Typo="Typo.body1">
<MudIcon Icon="@Icons.Material.Filled.CheckCircle" Color="Color.Success" Size="Size.Small" Class="mr-1" />
@(_agent.ContainerImage ?? "Conteneur Docker")
</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">ID: @_agent.ContainerId</MudText>
</MudItem>
}
@if (_agent.ContainerCpuLimit.HasValue)
{
<MudItem xs="6" Class="mt-2">
<MudChip T="string" Size="Size.Small" Color="Color.Warning">
@Text["AgentDetail_CpuLimit"]: @($"{(_agent.ContainerCpuLimit.Value / 100.0).ToString("F1", Language.Culture)} {Text["AgentDetail_Cores"]}")
</MudChip>
</MudItem>
}
</MudGrid>
</SectionCard>
</MudItem>
</MudGrid>
<MudGrid Class="mt-4">
@* ─── Network Interfaces ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="@Text["AgentDetail_Network"]" Icon="@Icons.Material.Filled.Wifi" Elevation="2">
@{
var interfaces = ParseNetworkJson(_agent.NetworkInterfacesJson);
}
@if (interfaces.Count > 0)
{
<MudTable Items="@interfaces" Dense="true" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>@Text["AgentDetail_Interface"]</MudTh>
<MudTh>@Text["AgentDetail_AdresseIp"]</MudTh>
<MudTh>@Text["AgentDetail_Mac"]</MudTh>
<MudTh>@Text["AgentDetail_Debit"]</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="@Text["AgentDetail_Interface"]">
<MudText Typo="Typo.body2" Class="font-weight-medium">@context.Name</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_AdresseIp"]">
<MudText Typo="Typo.body2">@(context.IpAddress ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Mac"]">
<MudText Typo="Typo.body2">@(context.MacAddress ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Debit"]">
<MudText Typo="Typo.body2">@(context.SpeedMbps.HasValue ? $"{context.SpeedMbps} Mbps" : "-")</MudText>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_AucuneInterfaceReseauDetectee"]</MudText>
}
</SectionCard>
</MudItem>
@* ─── Temperature ─── *@
<MudItem xs="12" md="6">
<SectionCard Title="@Text["AgentDetail_Temperatures"]" Icon="@Icons.Material.Filled.Thermostat" Elevation="2">
@{
var temps = ParseTemperatureJson(_agent.TemperatureJson);
}
@if (temps.Count > 0)
{
<MudTable Items="@temps" Dense="true" Hover="true" Elevation="0">
<HeaderContent>
<MudTh>@Text["AgentDetail_Zone"]</MudTh>
<MudTh>@Text["AgentDetail_Temperature"]</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="@Text["AgentDetail_Zone"]">
<MudText Typo="Typo.body2">@context.Zone</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Temperature"]">
@{
Color tempColor;
if (context.TemperatureCelsius > 70)
tempColor = Color.Error;
else if (context.TemperatureCelsius > 50)
tempColor = Color.Warning;
else
tempColor = Color.Default;
}
<MudText Typo="Typo.body2" Color="@tempColor">
@($"{context.TemperatureCelsius.ToString("F1", Language.Culture)}°C")
</MudText>
</MudTd>
</RowTemplate>
</MudTable>
}
else
{
<MudText Typo="Typo.body2" Color="Color.Secondary">@Text["AgentDetail_AucuneSondeDeTemperatureDetectee"]</MudText>
}
</SectionCard>
</MudItem>
</MudGrid>
@* ─── Agent Settings (globals hérités + overrides) ─── *@
<SectionCard Title="@Text["AgentDetail_Configuration"]"
Icon="@Icons.Material.Filled.Tune"
Elevation="2"
HelpText="@Text["AgentDetail_ParametresGlobauxHeritesParCetAgentModifiablesPourCeSiteUniquementEnvoyesEnTempsReelViaSignalr"]">
@if (_settingsLoading)
{
<MudProgressCircular Indeterminate="true" Size="Size.Small" />
}
else if (_settingsError)
{
<MudAlert Severity="Severity.Error" Class="mb-4">
@Text["AgentDetail_ErreurLorsDuChargementDeLaConfiguration"]
<MudButton OnClick="@LoadSettingsAsync" Size="Size.Small" Variant="Variant.Text" Class="ml-2">@Text["AgentDetail_Reessayer"]</MudButton>
</MudAlert>
}
else if (_globalSettings.Count == 0 && _settings.Count == 0)
{
<MudAlert Severity="Severity.Info" Class="mb-4">
@Text["AgentDetail_AucunParametreGlobalExposeAuxAgentsPourLeMoment"]
</MudAlert>
}
else
{
@foreach (var category in _globalSettings.GroupBy(s => s.Category).OrderBy(g => g.Key))
{
<div class="settings-category mb-4" @key="category.Key">
<div class="d-flex align-center mb-2 mt-2">
<MudText Typo="Typo.h6" Class="flex-grow-1">
<MudIcon Icon="@GetAgentCategoryIcon(category.Key)" Size="Size.Small" Class="mr-1" />
@category.Key
</MudText>
<MudChip T="string" Size="Size.Small" Variant="Variant.Outlined">@category.Count()</MudChip>
</div>
<MudGrid>
@foreach (var setting in category)
{
var overridden = IsOverridden(setting.Key);
var effectiveValue = EffectiveValue(setting.Key, setting.Value);
<MudItem xs="12" sm="6" lg="4" @key="setting.Key">
<MudPaper Elevation="1" Class="pa-4 settings-card" Style="border-radius: 12px; height: 100%;">
<div class="d-flex align-center mb-2">
<MudIcon Icon="@GetAgentTypeIcon(setting.ValueType)" Size="Size.Small"
Color="@GetAgentTypeColor(setting.ValueType)" Class="mr-2" />
<div class="flex-grow-1">
<MudText Typo="Typo.body1" Class="font-weight-medium settings-label">
@(setting.Description ?? HumanizeAgentKey(setting.Key))
</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">
@(overridden ? Text["AgentDetail_OverrideValue"] : Text["AgentDetail_GlobalValue"])
</MudText>
</div>
@if (overridden)
{
<MudTooltip Text="@Text["AgentDetail_ReinitialiserALaValeurGlobale"]">
<MudIconButton Icon="@Icons.Material.Filled.Restore" Size="Size.Small" aria-label="@Text["AgentDetail_Restaurer"]"
Color="Color.Warning" OnClick="@(() => ExecuteRemoveSettingByKey(setting.Key))" />
</MudTooltip>
}
</div>
@if (overridden)
{
<MudChip T="string" Size="Size.Small" Color="Color.Warning" Class="mb-2">
@Text["AgentDetail_SurchargePourCetAgent"]
</MudChip>
}
else
{
<MudChip T="string" Size="Size.Small" Color="Color.Info" Class="mb-2">
@Text["AgentDetail_HeriteGlobal"]
</MudChip>
}
@switch (setting.ValueType.ToLowerInvariant())
{
case "boolean":
case "bool":
<div class="d-flex align-center">
<MudSwitch T="bool"
Value="@(effectiveValue?.Equals("true", StringComparison.OrdinalIgnoreCase) == true)"
ValueChanged="@(v => SaveGlobalOverrideBoolAsync(setting, v))"
Color="Color.Primary" Class="flex-grow-1" />
<MudText Typo="Typo.body2" Color="Color.Primary" Class="font-weight-medium">
@(effectiveValue?.Equals("true", StringComparison.OrdinalIgnoreCase) == true ? Text["AgentDetail_Enabled"] : Text["AgentDetail_Disabled"])
</MudText>
</div>
break;
case "number":
case "int":
case "integer":
case "double":
<MudTextField T="string" Value="@effectiveValue" Variant="Variant.Outlined" Dense="true"
ValueChanged="@(v => SaveGlobalOverrideAsync(setting, v))"
Label="@Text["AgentDetail_Valeur"]" Type="InputType.Number" />
break;
case "select":
case "dropdown":
<MudSelect T="string" Value="@effectiveValue" Variant="Variant.Outlined" Dense="true"
ValueChanged="@(v => SaveGlobalOverrideAsync(setting, v))" Label="@Text["AgentDetail_Valeur"]">
@foreach (var opt in (setting.AllowedValues ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
<MudSelectItem Value="@opt" @key="opt">@opt</MudSelectItem>
}
</MudSelect>
break;
default:
<MudTextField T="string" Value="@effectiveValue" Variant="Variant.Outlined" Dense="true"
ValueChanged="@(v => SaveGlobalOverrideAsync(setting, v))" Label="@Text["AgentDetail_Valeur"]" />
break;
}
</MudPaper>
</MudItem>
}
</MudGrid>
</div>
}
}
@if (_settings.Count > 0)
{
<MudAlert Severity="Severity.Warning" Class="mt-2">
@_settings.Count réglage(s) surchargé(s) pour cet agent — la valeur globale est ignorée pour ces clés.
</MudAlert>
}
</SectionCard>
<MudPaper Elevation="2" Class="pa-6 mb-6" Style="border-radius: 12px;">
<div class="d-flex flex-wrap justify-space-between align-center mb-4">
<MudText Typo="Typo.h6">@Text["AgentDetail_HistoriqueDesRessources"]</MudText>
<MudButtonGroup Variant="Variant.Outlined" Color="Color.Primary">
<MudButton OnClick="@(() => LoadMetricHistoryAsync("24h"))" Disabled="@(_metricHistoryLoading || _metricRange == "24h")">@Text["AgentDetail_24H"]</MudButton>
<MudButton OnClick="@(() => LoadMetricHistoryAsync("7d"))" Disabled="@(_metricHistoryLoading || _metricRange == "7d")">@Text["AgentDetail_7Jours"]</MudButton>
</MudButtonGroup>
</div>
@if (_metricHistoryLoading)
{
<MudProgressLinear Indeterminate="true" />
}
else if (_metricHistoryError)
{
<MudAlert Severity="Severity.Error">@Text["AgentDetail_ImpossibleDeChargerLhistoriqueDesRessources"]</MudAlert>
}
else
{
@if (_metricHistory.LastOrDefault(point => point.InventoryObservedAtUtc.HasValue) is { } inventoryPoint)
{
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mb-3">
@Text["AgentDetail_LatestInventory"] @inventoryPoint.InventoryObservedAtUtc!.Value.ToLocalTime().ToString("g", Language.Culture).
</MudText>
}
<MudGrid>
<MudItem xs="12" md="6"><MetricHistoryChart Title="@Text["AgentDetail_CpuUtilise"]" Points="@MetricSeries(point => point.CpuUsagePercent)" Minimum="0" Maximum="100" /></MudItem>
<MudItem xs="12" md="6"><MetricHistoryChart Title="@Text["AgentDetail_MemoireSystemeUtilisee"]" Points="@MetricSeries(MemoryUsedPercent)" Minimum="0" Maximum="100" /></MudItem>
<MudItem xs="12" md="6"><MetricHistoryChart Title="@Text["AgentDetail_DisqueUtilise"]" Points="@MetricSeries(point => point.DiskUsagePercent)" Minimum="0" Maximum="100" /></MudItem>
<MudItem xs="12" md="6"><MetricHistoryChart Title="@Text["AgentDetail_TemperatureGpuMoyenne"]" Points="@MetricSeries(point => point.GpuTemperatureCelsius)" Unit=" °C" /></MudItem>
</MudGrid>
}
</MudPaper>
@* ─── Agent Logs ─── *@
<SectionCard Title="@Text["AgentDetail_Logs"]"
Icon="@Icons.Material.Filled.ReceiptLong"
Elevation="2"
HelpText="@Text["AgentDetail_LogsRemontesParLAgentPurgesQuotidiennementRetention7Jours"]">
<ChildContent>
<div class="d-flex flex-wrap gap-2 mb-4">
<MudSelect T="string" @bind-Value="_logLevel" Label="@Text["AgentDetail_Niveau"]" Variant="Variant.Outlined"
Dense="true" Clearable="true" Class="logs-level-filter" Immediate="true">
<MudSelectItem T="string" Value="@null">@Text["AgentDetail_TousLesNiveaux"]</MudSelectItem>
<MudSelectItem Value="@("Critical")">@Text["AgentDetail_Critical"]</MudSelectItem>
<MudSelectItem Value="@("Error")">@Text["AgentDetail_Error"]</MudSelectItem>
<MudSelectItem Value="@("Warning")">@Text["AgentDetail_Warning"]</MudSelectItem>
<MudSelectItem Value="@("Information")">@Text["AgentDetail_Information"]</MudSelectItem>
<MudSelectItem Value="@("Debug")">@Text["AgentDetail_Debug"]</MudSelectItem>
<MudSelectItem Value="@("Trace")">@Text["AgentDetail_Trace"]</MudSelectItem>
</MudSelect>
<MudTextField T="string" @bind-Value="_logSearch" Label="@Text["AgentDetail_Recherche"]" Variant="Variant.Outlined"
Dense="true" Immediate="true" Class="logs-search-filter"
Placeholder="@Text["AgentDetail_MessageOuSource"]" />
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => LoadLogsAsync(keepPage: false))"
StartIcon="@Icons.Material.Filled.Search" Class="align-self-center">
@Text["AgentDetail_Filtrer"]
</MudButton>
</div>
@if (_logsLoading)
{
<MudPaper Elevation="1" Class="pa-4" Style="border-radius: 8px;">
<MudSkeleton Width="100%" Height="40px" />
<MudSkeleton Width="100%" Height="40px" Class="mt-1" />
<MudSkeleton Width="100%" Height="40px" Class="mt-1" />
</MudPaper>
}
else if (_logsError)
{
<MudAlert Severity="Severity.Error" Class="mb-4" Variant="Variant.Filled">
<MudText>@Text["AgentDetail_ErreurLorsDuChargementDesLogs"]</MudText>
<MudButton Variant="Variant.Text" Color="Color.Inherit"
OnClick="@(() => LoadLogsAsync(keepPage: true))" Class="mt-2">
<MudIcon Icon="@Icons.Material.Filled.Refresh" Class="mr-1" Size="Size.Small" /> @Text["AgentDetail_Reessayer"]
</MudButton>
</MudAlert>
}
else
{
<MudTable Items="@_logs" Hover="true" Striped="true" Elevation="2" Dense="true">
<HeaderContent>
<MudTh>@Text["AgentDetail_Date"]</MudTh>
<MudTh>@Text["AgentDetail_Niveau"]</MudTh>
<MudTh>@Text["AgentDetail_Source"]</MudTh>
<MudTh>@Text["AgentDetail_Message"]</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="@Text["AgentDetail_Date"]">
<MudTooltip Text="@context.TimestampUtc.ToLocalTime().ToString("F", Language.Culture)">
<MudText Typo="Typo.body2">@context.TimestampUtc.ToLocalTime().ToString("g", Language.Culture)</MudText>
</MudTooltip>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Niveau"]">
<MudChip T="string" Size="Size.Small" Color="@GetLogLevelColor(context.Level)">
@context.Level
</MudChip>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Source"]">
<MudText Typo="Typo.body2" Color="Color.Secondary">@(context.Source ?? "-")</MudText>
</MudTd>
<MudTd DataLabel="@Text["AgentDetail_Message"]">
@if (!string.IsNullOrEmpty(context.Exception))
{
<MudTooltip Text="@context.Exception">
<MudText Typo="Typo.body2" Class="logs-message">@context.Message</MudText>
</MudTooltip>
}
else
{
<MudText Typo="Typo.body2" Class="logs-message">@context.Message</MudText>
}
</MudTd>
</RowTemplate>
<NoRecordsContent>
<MudPaper Class="pa-8 text-center" Style="border-radius: 12px;">
<MudIcon Icon="@Icons.Material.Filled.ReceiptLong" Size="Size.Large" Color="Color.Secondary" />
<MudText Typo="Typo.h6" Color="Color.Secondary" Class="mt-4">@Text["AgentDetail_AucunLog"]</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary">
@Text["AgentDetail_LAgentNARienRemontePourCesFiltres"]
</MudText>
</MudPaper>
</NoRecordsContent>
</MudTable>
<div class="d-flex align-center pa-4 mt-4" Style="border-radius: 8px;">
<MudText Typo="Typo.body2" Class="mr-4">
Page @_logPage sur @_logTotalPages (@_logTotal entrées)
</MudText>
<MudSpacer />
<MudButton Variant="Variant.Outlined" Size="Size.Small" Class="mr-2"
Disabled="@(_logPage <= 1)" OnClick="@(() => GoToLogPage(_logPage - 1))">
@Text["AgentDetail_Precedent"]
</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small"
Disabled="@(_logPage >= _logTotalPages)" OnClick="@(() => GoToLogPage(_logPage + 1))">
@Text["AgentDetail_Suivant"]
</MudButton>
</div>
}
</ChildContent>
<Actions>
<MudSwitch T="bool" Value="@_autoRefresh" ValueChanged="@ToggleAutoRefresh"
Color="Color.Primary" Class="mr-2" AdornmentLabel="@Text["AgentDetail_AutoRefresh"]"
Label="@Text["AgentDetail_AutoRefresh"]" />
<MudTooltip Text="@Text["AgentDetail_Rafraichir"]">
<MudIconButton Icon="@Icons.Material.Filled.Refresh" Size="Size.Small"
OnClick="@(() => LoadLogsAsync(keepPage: true))" aria-label="@Text["AgentDetail_ActualiserLesLogs"]" />
</MudTooltip>
</Actions>
</SectionCard>
<div class="d-flex gap-4 mt-4">
<MudButton Variant="Variant.Outlined" Color="Color.Default"
OnClick="@(() => Nav.NavigateTo($"/sites/{_agent.SiteId}/agents"))">
@Text["AgentDetail_AgentsDuSite"]
</MudButton>
<MudButton Variant="Variant.Text" Color="Color.Default"
OnClick="@(() => Nav.NavigateTo("/admin/agents"))">
@Text["AgentDetail_TousLesAgents"]
</MudButton>
<MudSpacer />
<MudTooltip Text="@Text["AgentDetail_SupprimerCetAgent"]">
<MudButton Variant="Variant.Outlined" Color="Color.Error"
StartIcon="@Icons.Material.Filled.Delete"
OnClick="@(() => _confirmDeleteAgentVisible = true)">
@Text["AgentDetail_Supprimer"]
</MudButton>
</MudTooltip>
</div>
}
@* ─── Delete Confirmation Dialog ─── *@
<MudDialog @bind-Visible="_confirmDeleteVisible" Options="_dialogOptions">
<TitleContent>
<MudText Typo="Typo.h6">
<MudIcon Icon="@Icons.Material.Filled.Warning" Color="Color.Warning" Class="mr-2" />
@Text["AgentDetail_ConfirmerLaSuppression"]
</MudText>
</TitleContent>
<DialogContent>
<MudText>@Text["AgentDetail_SupprimerLeReglage"] <strong>@_deletingKey</strong> @Text["AgentDetail_PourCetAgent"]</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-2">
@Text["AgentDetail_LAgentSeraNotifieEnTempsReelViaSignalrEtUtiliseraLaValeurGlobaleParDefaut"]
</MudText>
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _confirmDeleteVisible = false)">@Text["AgentDetail_Annuler"]</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Error"
OnClick="@ExecuteRemoveSettingAsync"
Loading="@_deleting"
Disabled="@_deleting">@Text["AgentDetail_Supprimer"]</MudButton>
</DialogActions>
</MudDialog>
@* ─── Delete Agent Confirmation Dialog ─── *@
<MudDialog @bind-Visible="_confirmDeleteAgentVisible">
<TitleContent>
<MudText Typo="Typo.h6">
<MudIcon Icon="@Icons.Material.Filled.Warning" Color="Color.Warning" Class="mr-2" />
@Text["AgentDetail_ConfirmerLaSuppression"]
</MudText>
</TitleContent>
<DialogContent>
<MudText>@Text["AgentDetail_SupprimerLAgent"] <strong>@_agent?.Name</strong> ?</MudText>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mt-2">
@Text["AgentDetail_LesCamerasAssocieesSerontDesassigneesMaisPasSupprimees"]
</MudText>
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _confirmDeleteAgentVisible = false)">@Text["AgentDetail_Annuler"]</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Error"
OnClick="@ExecuteDeleteAgentAsync" Loading="@_deletingAgent" Disabled="@_deletingAgent">
@Text["AgentDetail_Supprimer"]
</MudButton>
</DialogActions>
</MudDialog>
@* ─── Add / Edit Dialog ─── *@
<MudDialog @bind-Visible="_showEditDialog" Options="_dialogOptions">
<TitleContent>
<MudText Typo="Typo.h6">@(_editingSetting is null ? Text["AgentDetail_AddSetting"] : Text["AgentDetail_EditSetting"])</MudText>
</TitleContent>
<DialogContent>
<MudGrid>
<MudItem xs="12">
<MudTextField Label="@Text["AgentDetail_Cle"]"
@bind-Value="_editKey"
Disabled="@(_editingSetting is not null)"
For="@(() => _editKey)"
Required="true"
HelperText="@Text["AgentDetail_ExHeartbeatIntervalSeconds"]" />
</MudItem>
<MudItem xs="12">
<MudTextField Label="@Text["AgentDetail_Valeur"]"
@bind-Value="_editValue"
For="@(() => _editValue)"
Required="true" />
</MudItem>
</MudGrid>
</DialogContent>
<DialogActions>
<MudButton Variant="Variant.Text" OnClick="@(() => _showEditDialog = false)">@Text["AgentDetail_Annuler"]</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Primary"
OnClick="@SaveSettingAsync"
Disabled="@_saving"
Loading="@_saving">
@(_editingSetting is null ? Text["AgentDetail_AddSetting"] : Text["Save"])
</MudButton>
</DialogActions>
</MudDialog>
@code {
[Parameter] public Guid Id { get; set; }
private AgentItem? _agent;
private bool _loading = true;
private List<AgentMetricHistoryPoint> _metricHistory = [];
private bool _metricHistoryLoading;
private bool _metricHistoryError;
private string _metricRange = "24h";
// Updates
private LatestReleaseInfo? _updateInfo;
// Settings
private List<AgentSettingItem> _settings = [];
private List<AppSettingItem> _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<AgentLogItem>? _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<MetricChartPoint> MetricSeries(Func<AgentMetricHistoryPoint, double?> 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; }
}
/// <summary>Returns the effective value for a global setting key (override wins).</summary>
private string EffectiveValue(string key, string globalValue)
=> _settings.FirstOrDefault(s => s.Key == key)?.Value ?? globalValue;
/// <summary>True when the agent overrides this global key.</summary>
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<DiskDto> ParseDiskJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<DiskDto>>(json) ?? [];
}
catch { return []; }
}
private static List<GpuDto> ParseGpuJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<GpuDto>>(json) ?? [];
}
catch { return []; }
}
private static List<NetworkDto> ParseNetworkJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<NetworkDto>>(json) ?? [];
}
catch { return []; }
}
private static List<TempDto> ParseTemperatureJson(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return [];
try
{
return System.Text.Json.JsonSerializer.Deserialize<List<TempDto>>(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; }
}
}