From 5f6df6146c5577bad6bb37eb72c43ea284457d33 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 17:41:14 +0100 Subject: [PATCH 1/7] test(qa): cover agent event notification flow end to end --- src/Heimdall.Web/Hubs/NotificationsHub.cs | 13 +- .../Services/NotificationsHubClient.cs | 19 +- .../Pages/DetectionFlowTests.cs | 229 ++++++++++++++++++ todo.md | 2 +- 4 files changed, 251 insertions(+), 12 deletions(-) create mode 100644 tests/Heimdall.E2E.Tests/Pages/DetectionFlowTests.cs diff --git a/src/Heimdall.Web/Hubs/NotificationsHub.cs b/src/Heimdall.Web/Hubs/NotificationsHub.cs index f546c1c..415edee 100644 --- a/src/Heimdall.Web/Hubs/NotificationsHub.cs +++ b/src/Heimdall.Web/Hubs/NotificationsHub.cs @@ -20,9 +20,16 @@ public class NotificationsHub : Hub private readonly ILogger _logger; private readonly ResourceAccess _access; private readonly LiveSubscriptions _subscriptions; + private readonly INotificationService _notifications; - public NotificationsHub(ILogger logger, ResourceAccess access, LiveSubscriptions subscriptions) - { _logger = logger; _access = access; _subscriptions = subscriptions; } + public NotificationsHub(ILogger logger, ResourceAccess access, + LiveSubscriptions subscriptions, INotificationService notifications) + { + _logger = logger; + _access = access; + _subscriptions = subscriptions; + _notifications = notifications; + } /// /// Clients call this to join their personal notification channel. @@ -36,6 +43,8 @@ public class NotificationsHub : Hub var userId = requester.Id.ToString(); _subscriptions.Join("notifications", Context.ConnectionId, userId, Context.User!); _logger.LogDebug("Client {ConnectionId} joined personal notifications for user {UserId}", Context.ConnectionId, userId); + var unreadCount = await _notifications.GetUnreadCountAsync(requester.Id, Context.ConnectionAborted); + await Clients.Caller.SendAsync("UnreadCount", new { count = unreadCount }, Context.ConnectionAborted); } public Task LeavePersonalNotifications() diff --git a/src/Heimdall.Web/Services/NotificationsHubClient.cs b/src/Heimdall.Web/Services/NotificationsHubClient.cs index fef44e2..b610c65 100644 --- a/src/Heimdall.Web/Services/NotificationsHubClient.cs +++ b/src/Heimdall.Web/Services/NotificationsHubClient.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.SignalR.Client; @@ -52,18 +53,18 @@ public class NotificationsHubClient : IAsyncDisposable, IDisposable .WithAutomaticReconnect() .Build(); - _connection.On("UnreadCount", (payload) => + _connection.On("UnreadCount", (payload) => { - try + if (payload.ValueKind != JsonValueKind.Object || + !payload.TryGetProperty("count", out var countElement) || + !countElement.TryGetInt32(out var count) || count < 0) { - var count = (int)((IDictionary)payload)["count"]; - UnreadCount = count; - UnreadCountChanged?.Invoke(count); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "NotificationsHubClient: UnreadCount payload inattendu"); + _logger.LogWarning("NotificationsHubClient: unread count payload inattendu"); + return; } + + UnreadCount = count; + UnreadCountChanged?.Invoke(count); }); _connection.On("NewNotification", (_) => diff --git a/tests/Heimdall.E2E.Tests/Pages/DetectionFlowTests.cs b/tests/Heimdall.E2E.Tests/Pages/DetectionFlowTests.cs new file mode 100644 index 0000000..4894ca6 --- /dev/null +++ b/tests/Heimdall.E2E.Tests/Pages/DetectionFlowTests.cs @@ -0,0 +1,229 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; +using Heimdall.TestCommon; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Playwright; +using Shouldly; + +namespace Heimdall.E2E.Tests.Pages; + +public sealed class DetectionFlowTests(PostgreSqlContainerFixture postgres) : E2ETestBase(postgres) +{ + private const string SnapshotJpegBase64 = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAgADADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAb/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCCAWkoAAAAAAAAAB//2Q=="; + + [Fact] + public async Task Assigned_agent_event_is_stored_notified_and_visible_only_with_camera_access() + { + var storageRoot = Path.Combine(Path.GetTempPath(), $"heimdall-e2e-storage-{Guid.NewGuid():N}"); + var admin = new HttpClient { BaseAddress = new Uri(BaseUrl) }; + admin.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await LoginViaApiAsync()); + string? originalStoragePath = null; + string? originalStorageProvider = null; + + try + { + var storedPath = await admin.GetAsync("api/settings/storage.local.path"); + storedPath.StatusCode.ShouldBe(HttpStatusCode.OK); + var setting = await storedPath.Content.ReadFromJsonAsync(); + originalStoragePath = setting.GetProperty("value").GetString(); + var providerResponse = await admin.GetAsync("api/settings/storage.provider"); + providerResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var providerSetting = await providerResponse.Content.ReadFromJsonAsync(); + originalStorageProvider = providerSetting.GetProperty("value").GetString(); + (await admin.PutAsJsonAsync("api/settings/storage.provider", new { value = "Local" })) + .StatusCode.ShouldBe(HttpStatusCode.OK); + (await admin.PutAsJsonAsync("api/settings/storage.local.path", new { value = storageRoot })) + .StatusCode.ShouldBe(HttpStatusCode.OK); + var initialUnreadResponse = await admin.GetAsync("api/notifications/unread-count"); + initialUnreadResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var initialUnread = (await initialUnreadResponse.Content.ReadFromJsonAsync()) + .GetProperty("count").GetInt32(); + + var siteId = await CreateSiteAsync(admin, "QA source"); + var otherSiteId = await CreateSiteAsync(admin, "QA other"); + var agent = await RegisterOnlineAgentAsync(admin, siteId); + var assignedCameraId = await CreateCameraAsync(admin, siteId, "QA assigned camera"); + var otherCameraId = await CreateCameraAsync(admin, otherSiteId, "QA other-site camera"); + (await admin.PostAsJsonAsync("api/assignments", new { cameraId = assignedCameraId, agentId = agent.Id })) + .StatusCode.ShouldBe(HttpStatusCode.OK); + + var viewerEmail = $"qa-flow-{Guid.NewGuid():N}@heimdall.test"; + const string viewerPassword = "QaFlowViewer123!"; + var userResponse = await admin.PostAsJsonAsync("api/users", new + { + email = viewerEmail, + password = viewerPassword, + displayName = "QA Flow Viewer", + roles = new[] { "Viewer" } + }); + userResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var viewerUserId = (await userResponse.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + await ConfirmUserAsync(viewerEmail); + using var viewer = new HttpClient { BaseAddress = new Uri(BaseUrl) }; + viewer.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( + "Bearer", await LoginViaApiAsync(viewerEmail, viewerPassword)); + + (await viewer.GetAsync($"api/cameras/{assignedCameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden); + (await viewer.GetAsync($"api/cameras/{otherCameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden); + var grant = await admin.PostAsJsonAsync("api/user-camera-access", new + { + userId = viewerUserId, + siteId, + cameraId = assignedCameraId + }); + grant.StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/cameras/{assignedCameraId}")).StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/cameras/{otherCameraId}")).StatusCode.ShouldBe(HttpStatusCode.Forbidden); + + using var agentClient = AgentClient(agent.ApiKey); + var occurredAt = DateTime.UtcNow; + var eventId = Guid.NewGuid(); + var label = $"qa-flow-{Guid.NewGuid():N}"; + var eventRequest = new + { + cameraId = assignedCameraId, + type = (int)EventType.PersonDetected, + confidence = 0.97, + label, + occurredAt, + eventId + }; + (await agentClient.PostAsJsonAsync("api/events", new + { + cameraId = otherCameraId, + type = (int)EventType.PersonDetected, + confidence = 0.9, + label = "wrong-site" + })).StatusCode.ShouldBe(HttpStatusCode.Forbidden); + + var createdEvent = await agentClient.PostAsJsonAsync("api/events", eventRequest); + createdEvent.StatusCode.ShouldBe(HttpStatusCode.OK); + var eventResponse = await createdEvent.Content.ReadFromJsonAsync(); + eventResponse.GetProperty("id").GetGuid().ShouldBe(eventId); + + // The agent outbox may retry an accepted event. Its deterministic ID must + // preserve a single event and a single in-app notification per recipient. + (await agentClient.PostAsJsonAsync("api/events", eventRequest)).StatusCode.ShouldBe(HttpStatusCode.OK); + + using var image = new ByteArrayContent(Convert.FromBase64String(SnapshotJpegBase64)); + image.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); + var uploaded = await agentClient.PutAsync($"api/events/{eventId:D}/snapshot/content", image); + uploaded.StatusCode.ShouldBe(HttpStatusCode.OK); + + foreach (var client in new[] { admin, viewer }) + { + var notificationsResponse = await client.GetAsync("api/notifications?isRead=false&page=1&pageSize=100"); + notificationsResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var notifications = await notificationsResponse.Content.ReadFromJsonAsync(); + var matchingNotifications = notifications.GetProperty("items").EnumerateArray() + .Where(item => item.GetProperty("cameraId").GetGuid() == assignedCameraId) + .ToArray(); + matchingNotifications.Length.ShouldBe(1); + matchingNotifications[0].GetProperty("eventType").GetString().ShouldBe(nameof(EventType.PersonDetected)); + } + + (await viewer.GetAsync($"api/events/{eventId:D}")).StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/events/{eventId:D}/snapshot/content")).StatusCode.ShouldBe(HttpStatusCode.OK); + (await viewer.GetAsync($"api/events/{Guid.NewGuid():D}/snapshot/content")).StatusCode + .ShouldBe(HttpStatusCode.Forbidden); + + await LoginViaUiAsync(); + await Page.Locator(".mud-badge").WaitForAsync(new() { Timeout = 15000 }); + (await Page.Locator(".mud-badge").First.TextContentAsync()).ShouldContain((initialUnread + 1).ToString()); + await GotoWithCircuitAsync("/events"); + await Page.GetByText(label, new() { Exact = true }).WaitForAsync(new() { Timeout = 15000 }); + } + finally + { + if (originalStorageProvider is not null) + { + try + { + var restore = await admin.PutAsJsonAsync("api/settings/storage.provider", + new { value = originalStorageProvider }); + restore.Dispose(); + } + catch { /* Keep test cleanup from hiding the original failure. */ } + } + if (originalStoragePath is not null) + { + try + { + var restore = await admin.PutAsJsonAsync("api/settings/storage.local.path", + new { value = originalStoragePath }); + restore.Dispose(); + } + catch { /* Keep test cleanup from hiding the original failure. */ } + } + admin.Dispose(); + if (Directory.Exists(storageRoot)) Directory.Delete(storageRoot, recursive: true); + } + } + + private async Task CreateSiteAsync(HttpClient admin, string name) + { + var response = await admin.PostAsJsonAsync("api/sites", new { name = $"{name} {Guid.NewGuid():N}", timezone = "UTC" }); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + return (await response.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + } + + private async Task CreateCameraAsync(HttpClient admin, Guid siteId, string name) + { + var response = await admin.PostAsJsonAsync("api/cameras", new + { + siteId, + name, + rtspUrl = $"rtsp://127.0.0.1/{Guid.NewGuid():N}" + }); + response.StatusCode.ShouldBe(HttpStatusCode.OK); + return (await response.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); + } + + private async Task<(Guid Id, string ApiKey)> RegisterOnlineAgentAsync(HttpClient admin, Guid siteId) + { + var tokenResponse = await admin.PostAsync($"api/sites/{siteId}/tokens", null); + tokenResponse.StatusCode.ShouldBe(HttpStatusCode.OK); + var token = (await tokenResponse.Content.ReadFromJsonAsync()).GetProperty("token").GetString()!; + var registration = await admin.PostAsJsonAsync("api/agents/register", new + { + token, + hostname = $"qa-flow-agent-{Guid.NewGuid():N}", + version = "1.0.0-test" + }); + registration.StatusCode.ShouldBe(HttpStatusCode.OK); + var agent = await registration.Content.ReadFromJsonAsync(); + var id = agent.GetProperty("agentId").GetGuid(); + var apiKey = agent.GetProperty("apiKey").GetString()!; + using var agentClient = AgentClient(apiKey); + var heartbeat = await agentClient.PostAsJsonAsync($"api/agents/{id:D}/heartbeat", new + { + publicIp = "127.0.0.1", + cpuCores = 4, + memoryMb = 4096 + }); + heartbeat.StatusCode.ShouldBe(HttpStatusCode.OK); + return (id, apiKey); + } + + private async Task ConfirmUserAsync(string email) + { + await using var scope = App.Services.CreateAsyncScope(); + var dbFactory = scope.ServiceProvider.GetRequiredService>(); + await using var db = await dbFactory.CreateDbContextAsync(); + var user = await db.Users.SingleAsync(candidate => candidate.Email == email); + user.EmailConfirmed = true; + await db.SaveChangesAsync(); + } + + private HttpClient AgentClient(string apiKey) + { + var client = new HttpClient { BaseAddress = new Uri(BaseUrl) }; + client.DefaultRequestHeaders.Add("X-API-Key", apiKey); + return client; + } +} diff --git a/todo.md b/todo.md index 68a392a..ce6e62a 100644 --- a/todo.md +++ b/todo.md @@ -30,7 +30,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif. - [ ] **Toggle caméra #59/#199** L’interface détail empêche maintenant les doubles clics pendant le POST et garde un verrou côté méthode. Restent à prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l’état survit au redémarrage. - [ ] **Accès caméra #141** La PR #65 ajoute les scénarios API de grant caméra direct, refus cross-camera, suppression logique et restrictions des routes groupes, ainsi que les tests du filtre d’affectations et des hubs après suppression logique ; sa CI est passée. La PR #88 ajoute le remplacement UI atomique, le chargement complet paginé, la protection du brouillon, et la révocation individuelle des accès excédant la limite de 500. La PR #100 ajoute un gate CI strict (>80 % de lignes par classe ciblée) et étend les tests Application, Infrastructure et Web. Le run PR #319 a mesuré : `CameraAccessService` 100 %, `ResourceAccess` 88,46 %, `ResourceAccessFilter` 82,54 %, `UserCameraAccessController` 83,33 % ; handlers/queries/mapping Application de 90 % à 100 %. Restent la validation produit des accès directs/groupes (#133/#134). -- [ ] **QA-01** Ajouter scénarios transversaux API → Agent → stockage → événement → UI → notification, dont périmètres de site et droits caméra ; mesurer couverture utile sans compter les tests ignorés comme succès. +- [ ] **QA-01** Un parcours E2E Playwright est en préparation : Agent enregistré simulé, événement et reprise idempotente, snapshot dans un stockage local temporaire, notification persistée, droit caméra accordé/refusé selon le périmètre, puis affichage de l’événement et du compteur initial dans l’UI. La PR qui ajoute ce scénario et le chargement du compteur à la connexion du hub doit encore passer la CI ; ses sorties distinguent les tests ignorés des tests réussis. - [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée. ## P2 — fonctionnalités et exploitation -- 2.54.1 From 7b6f887b2eeb8a1500df7aaa65de4cd4f32c55df Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 17:47:13 +0100 Subject: [PATCH 2/7] fix(qa): address E2E analyzer failures --- tests/Heimdall.E2E.Tests/Pages/DetectionFlowTests.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/Heimdall.E2E.Tests/Pages/DetectionFlowTests.cs b/tests/Heimdall.E2E.Tests/Pages/DetectionFlowTests.cs index 4894ca6..c048f75 100644 --- a/tests/Heimdall.E2E.Tests/Pages/DetectionFlowTests.cs +++ b/tests/Heimdall.E2E.Tests/Pages/DetectionFlowTests.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; @@ -134,7 +135,8 @@ public sealed class DetectionFlowTests(PostgreSqlContainerFixture postgres) : E2 await LoginViaUiAsync(); await Page.Locator(".mud-badge").WaitForAsync(new() { Timeout = 15000 }); - (await Page.Locator(".mud-badge").First.TextContentAsync()).ShouldContain((initialUnread + 1).ToString()); + (await Page.Locator(".mud-badge").First.TextContentAsync() ?? string.Empty) + .ShouldContain((initialUnread + 1).ToString(CultureInfo.InvariantCulture)); await GotoWithCircuitAsync("/events"); await Page.GetByText(label, new() { Exact = true }).WaitForAsync(new() { Timeout = 15000 }); } @@ -165,14 +167,14 @@ public sealed class DetectionFlowTests(PostgreSqlContainerFixture postgres) : E2 } } - private async Task CreateSiteAsync(HttpClient admin, string name) + private static async Task CreateSiteAsync(HttpClient admin, string name) { var response = await admin.PostAsJsonAsync("api/sites", new { name = $"{name} {Guid.NewGuid():N}", timezone = "UTC" }); response.StatusCode.ShouldBe(HttpStatusCode.OK); return (await response.Content.ReadFromJsonAsync()).GetProperty("id").GetGuid(); } - private async Task CreateCameraAsync(HttpClient admin, Guid siteId, string name) + private static async Task CreateCameraAsync(HttpClient admin, Guid siteId, string name) { var response = await admin.PostAsJsonAsync("api/cameras", new { -- 2.54.1 From 14afaee0d195adb52a90623d8776d5e66aa1a6fb Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 18:01:15 +0100 Subject: [PATCH 3/7] fix(pwa): start notification hub after login --- .../Components/Shared/NotificationBadge.razor | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/Heimdall.Web/Components/Shared/NotificationBadge.razor b/src/Heimdall.Web/Components/Shared/NotificationBadge.razor index 0fd3064..eb9e939 100644 --- a/src/Heimdall.Web/Components/Shared/NotificationBadge.razor +++ b/src/Heimdall.Web/Components/Shared/NotificationBadge.razor @@ -2,6 +2,7 @@ @implements IAsyncDisposable @inject NotificationsHubClient Hub @inject NavigationManager Navigation +@inject AuthenticationStateProvider AuthenticationStateProvider @inject Heimdall.Web.Services.UiText Text @@ -18,14 +19,27 @@ protected override async Task OnInitializedAsync() { Hub.UnreadCountChanged += OnUnreadChanged; + AuthenticationStateProvider.AuthenticationStateChanged += OnAuthenticationStateChanged; await Hub.StartAsync(); } + private void OnAuthenticationStateChanged(Task authenticationStateTask) + { + _ = InvokeAsync(async () => + { + var authenticationState = await authenticationStateTask; + if (authenticationState.User.Identity?.IsAuthenticated == true) + await Hub.StartAsync(); + StateHasChanged(); + }); + } + private void OnUnreadChanged(int _) => InvokeAsync(StateHasChanged); public async ValueTask DisposeAsync() { Hub.UnreadCountChanged -= OnUnreadChanged; + AuthenticationStateProvider.AuthenticationStateChanged -= OnAuthenticationStateChanged; await Hub.DisposeAsync(); } } -- 2.54.1 From 653030488793378d0a356d7521fd41ddd17e9005 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 18:15:45 +0100 Subject: [PATCH 4/7] fix(pwa): load notification count on badge mount --- .../Components/Shared/NotificationBadge.razor | 4 ++++ .../Services/HeimdallApiClient.cs | 10 +++++++++ .../Services/NotificationsHubClient.cs | 22 ++++++++++++++++--- 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/Heimdall.Web/Components/Shared/NotificationBadge.razor b/src/Heimdall.Web/Components/Shared/NotificationBadge.razor index eb9e939..9eee40b 100644 --- a/src/Heimdall.Web/Components/Shared/NotificationBadge.razor +++ b/src/Heimdall.Web/Components/Shared/NotificationBadge.razor @@ -21,6 +21,7 @@ Hub.UnreadCountChanged += OnUnreadChanged; AuthenticationStateProvider.AuthenticationStateChanged += OnAuthenticationStateChanged; await Hub.StartAsync(); + await Hub.RefreshUnreadCountAsync(); } private void OnAuthenticationStateChanged(Task authenticationStateTask) @@ -29,7 +30,10 @@ { var authenticationState = await authenticationStateTask; if (authenticationState.User.Identity?.IsAuthenticated == true) + { await Hub.StartAsync(); + await Hub.RefreshUnreadCountAsync(); + } StateHasChanged(); }); } diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index d465f96..1b96cae 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -124,6 +124,16 @@ public class HeimdallApiClient : IDisposable return await client.GetFromJsonAsync("api/users/me", Json); } + public async Task GetUnreadNotificationCountAsync() + { + using var response = await CreateClient().GetAsync("api/notifications/unread-count"); + if (!response.IsSuccessStatusCode) + return 0; + + var result = await response.Content.ReadFromJsonAsync(Json); + return result?.Count ?? 0; + } + public async Task UpdateMyProfileAsync(string displayName, string? theme, string? language) { var client = CreateClient(); diff --git a/src/Heimdall.Web/Services/NotificationsHubClient.cs b/src/Heimdall.Web/Services/NotificationsHubClient.cs index b610c65..177296d 100644 --- a/src/Heimdall.Web/Services/NotificationsHubClient.cs +++ b/src/Heimdall.Web/Services/NotificationsHubClient.cs @@ -7,13 +7,13 @@ namespace Heimdall.Web.Services; /// /// Client hub SignalR pour les notifications temps réel (badge compteur). /// S'abonne au groupe personnel "notif_{userId}" et expose l'événement -/// . Le polling est le fallback : si la -/// connexion échoue (pas de JWT en session cookie, hub indisponible), le -/// badge reste silencieux sans casser l'UI. +/// . Un chargement API initial garantit le +/// compteur même si la connexion temps réel n'est pas encore disponible. /// public class NotificationsHubClient : IAsyncDisposable, IDisposable { private readonly AuthState _authState; + private readonly HeimdallApiClient _api; private readonly NavigationManager _navigation; private readonly ILogger _logger; private HubConnection? _connection; @@ -21,10 +21,12 @@ public class NotificationsHubClient : IAsyncDisposable, IDisposable public NotificationsHubClient( AuthState authState, + HeimdallApiClient api, NavigationManager navigation, ILogger logger) { _authState = authState; + _api = api; _navigation = navigation; _logger = logger; } @@ -34,6 +36,20 @@ public class NotificationsHubClient : IAsyncDisposable, IDisposable public event Action? UnreadCountChanged; + public async Task RefreshUnreadCountAsync() + { + try + { + var count = await _api.GetUnreadNotificationCountAsync(); + UnreadCount = count; + UnreadCountChanged?.Invoke(count); + } + catch (Exception ex) + { + _logger.LogDebug(ex, "NotificationsHubClient: chargement initial du compteur impossible"); + } + } + public async Task StartAsync() { if (_started || !_authState.IsLoggedIn) -- 2.54.1 From 53084ce4db0656924668e127c73a3fb0cae3afc1 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 18:18:50 +0100 Subject: [PATCH 5/7] test(web): wire api client into notification hub fixture --- tests/Heimdall.Web.Tests/Components/Pages/PageTestBase.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/Heimdall.Web.Tests/Components/Pages/PageTestBase.cs b/tests/Heimdall.Web.Tests/Components/Pages/PageTestBase.cs index 9f41f8b..fd7a7ba 100644 --- a/tests/Heimdall.Web.Tests/Components/Pages/PageTestBase.cs +++ b/tests/Heimdall.Web.Tests/Components/Pages/PageTestBase.cs @@ -63,6 +63,7 @@ public abstract class PageTestBase : MudTestBase Services.AddScoped(_ => Environment); Services.AddScoped(sp => new NotificationsHubClient( AuthState, + Api, Services.GetRequiredService(), Substitute.For>())); } -- 2.54.1 From 0d3907640f592b09e89f3416d0636618182555bb Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 18:33:40 +0100 Subject: [PATCH 6/7] fix(web): render notification badge around button --- .../Components/Shared/NotificationBadge.razor | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/Heimdall.Web/Components/Shared/NotificationBadge.razor b/src/Heimdall.Web/Components/Shared/NotificationBadge.razor index 9eee40b..c38e9fa 100644 --- a/src/Heimdall.Web/Components/Shared/NotificationBadge.razor +++ b/src/Heimdall.Web/Components/Shared/NotificationBadge.razor @@ -6,13 +6,12 @@ @inject Heimdall.Web.Services.UiText Text - - @if (Hub.UnreadCount > 0) - { - - } - + + + @code { -- 2.54.1 From db3496e57d17875b00d3d926ba84ed0c36886ee6 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sun, 25 Oct 2026 18:56:39 +0100 Subject: [PATCH 7/7] docs(qa): record end-to-end flow validation --- todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/todo.md b/todo.md index ce6e62a..af8ebe0 100644 --- a/todo.md +++ b/todo.md @@ -30,7 +30,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif. - [ ] **Toggle caméra #59/#199** L’interface détail empêche maintenant les doubles clics pendant le POST et garde un verrou côté méthode. Restent à prouver sur Agent connecté que OFF arrête capture et libère les ressources en moins de 2 s, ON reprend avec backoff en moins de 10 s, et que l’état survit au redémarrage. - [ ] **Accès caméra #141** La PR #65 ajoute les scénarios API de grant caméra direct, refus cross-camera, suppression logique et restrictions des routes groupes, ainsi que les tests du filtre d’affectations et des hubs après suppression logique ; sa CI est passée. La PR #88 ajoute le remplacement UI atomique, le chargement complet paginé, la protection du brouillon, et la révocation individuelle des accès excédant la limite de 500. La PR #100 ajoute un gate CI strict (>80 % de lignes par classe ciblée) et étend les tests Application, Infrastructure et Web. Le run PR #319 a mesuré : `CameraAccessService` 100 %, `ResourceAccess` 88,46 %, `ResourceAccessFilter` 82,54 %, `UserCameraAccessController` 83,33 % ; handlers/queries/mapping Application de 90 % à 100 %. Restent la validation produit des accès directs/groupes (#133/#134). -- [ ] **QA-01** Un parcours E2E Playwright est en préparation : Agent enregistré simulé, événement et reprise idempotente, snapshot dans un stockage local temporaire, notification persistée, droit caméra accordé/refusé selon le périmètre, puis affichage de l’événement et du compteur initial dans l’UI. La PR qui ajoute ce scénario et le chargement du compteur à la connexion du hub doit encore passer la CI ; ses sorties distinguent les tests ignorés des tests réussis. +- [x] **QA-01** Parcours E2E Playwright complet : Agent enregistré simulé, événement et reprise idempotente, snapshot dans un stockage local temporaire, notification persistée, droits caméra accordé/refusé par périmètre, puis affichage de l’événement et du compteur initial dans l’UI. Le run PR #313 a réussi les 35 E2E sans test ignoré, ainsi que les tests web et d’intégration affectés, le build et les scans des deux images. Le badge charge le compteur par API à l’initialisation et suit ensuite les mises à jour SignalR. Restent les validations caméra et Agent en environnement réel. - [ ] Tester une restauration isolée PostgreSQL, objets et clés Data Protection ; fixer RPO/RTO et documenter la procédure mesurée. ## P2 — fonctionnalités et exploitation -- 2.54.1