From 143c70616848432793e9e96e7669bcfb336b4d06 Mon Sep 17 00:00:00 2001 From: Beenu Arora Date: Thu, 19 Nov 2026 22:41:06 +1100 Subject: [PATCH 1/3] release: v23.5.3 (#1975) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## v23.5.3 — connector data completeness, community end to end Both defects were reported with failing tests by @pavancharak **against the shipped v23.5.2 tag** ([#1970](https://github.com/beenuar/AiSOC/issues/1970), [#1971](https://github.com/beenuar/AiSOC/issues/1971)); both fixed by first-time contributor @Varshith-Kali in [#1973](https://github.com/beenuar/AiSOC/pull/1973). Fixing `main` fixes no tag — deployments pulling v23.5.2 keep silently losing rows on these paths until a release carries the fix, which is the bar for this patch. ### What the tag gets 1. **Checkpoint cursors compare instants, not text** — `…10:00:00.500Z` no longer drops against a `…10:00:00Z` cursor (`.` sorts before `Z`), offset-written cursors no longer drop later rows, the staged cursor names the newest instant with id tie-breaks, and an unparseable time keeps its row rather than losing it. 2. **Huntress / Cisco Secure Endpoint / Sophos Central stop losing scheduler-skipped intervals** — each persists an event-time cursor (Huntress on `sent_at`, preserving raise-once), overlaps one poll interval so a single skipped run is covered before any cursor exists, and skips are logged (`connector.scheduler.poll_skipped`). Overlap re-reads drop against the cursor: a re-request, never a duplicate or a loss. **Verified, not asserted:** 449 connector tests pass on the fix; the new instant-ordering suite fails 5/8 against the pre-fix tree. ### Mechanics `VERSION` 23.5.3 · CHANGELOG `[23.5.3]` cut (entries landed in #1974) · RELEASES.md TL;DR + What's-new · README badge · chart `7.24.3`/`v23.5.3` · `apps/web/package.json` · scoreboard refreshed (0.97, pinned to `420c707f`) · llms/openapi regenerated · changelog-frozen, single-version, readme-gates, papers, competitor gates green locally. **No breaking changes.** One observable note: the three converted connectors emit batches oldest-first by event time rather than page order. Tag goes on the merge commit; release.yml publishes; registry verified after. Co-authored-by: beenuar --- CHANGELOG.md | 4 ++++ README.md | 2 +- RELEASES.md | 20 ++++++++++++++++++-- VERSION | 2 +- apps/docs/static/data/scoreboard.json | 4 ++-- apps/docs/static/llms-full.txt | 4 ++-- apps/docs/static/llms.txt | 2 +- apps/web/package.json | 2 +- docs/openapi.yaml | 2 +- infra/helm/aisoc/Chart.yaml | 4 ++-- 10 files changed, 33 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b3073b8d8..4f64cfe2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +_Nothing yet._ + +## [23.5.3] - 2026-11-19 + ### Fixed - **Checkpoint cursors order and compare the instant a timestamp names, not diff --git a/README.md b/README.md index 5ab50c402..8ce4449ea 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ **An open-source, self-hostable AI Security Operations Center.** It ingests your security telemetry, detects and correlates threats, investigates them with AI agents whose reasoning is fully auditable, and proposes responses a human approves. -[![License: MIT](https://img.shields.io/badge/License-MIT-22c55e.svg?style=flat-square)](https://opensource.org/licenses/MIT) [![Version](https://img.shields.io/badge/version-23.5.2-f59e0b?style=flat-square)](CHANGELOG.md) [![CI](https://img.shields.io/github/actions/workflow/status/beenuar/AiSOC/ci.yml?branch=main&label=CI&style=flat-square)](https://github.com/beenuar/AiSOC/actions/workflows/ci.yml) +[![License: MIT](https://img.shields.io/badge/License-MIT-22c55e.svg?style=flat-square)](https://opensource.org/licenses/MIT) [![Version](https://img.shields.io/badge/version-23.5.3-f59e0b?style=flat-square)](CHANGELOG.md) [![CI](https://img.shields.io/github/actions/workflow/status/beenuar/AiSOC/ci.yml?branch=main&label=CI&style=flat-square)](https://github.com/beenuar/AiSOC/actions/workflows/ci.yml) [![CodeQL](https://img.shields.io/github/actions/workflow/status/beenuar/AiSOC/codeql.yml?branch=main&label=CodeQL&style=flat-square)](https://github.com/beenuar/AiSOC/actions/workflows/codeql.yml) [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/beenuar/AiSOC/badge)](https://securityscorecards.dev/viewer/?uri=github.com/beenuar/AiSOC) [![Technical Guide](https://img.shields.io/badge/Technical%20Guide-28%20page%20PDF-dc2626?style=flat-square)](https://raw.githubusercontent.com/beenuar/AiSOC/main/apps/web/public/papers/aisoc-technical-guide.pdf) **[Technical Guide (PDF)](https://raw.githubusercontent.com/beenuar/AiSOC/main/apps/web/public/papers/aisoc-technical-guide.pdf)** · [Docs](https://beenuar.github.io/AiSOC/) · [Architecture](docs/architecture/README.md) · [What actually works](docs/audit/REPOSITORY_REALITY.md) · [Discussions](https://github.com/beenuar/AiSOC/discussions) diff --git a/RELEASES.md b/RELEASES.md index d1e537b22..fef0faafd 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -2,7 +2,9 @@ This file mirrors what used to live in the "What's new" section of [`README.md`](README.md). The complete, machine-readable inventory (with file paths, env-var diffs, and per-release test counts) lives in [`CHANGELOG.md`](CHANGELOG.md). -> **TL;DR for first-time visitors:** AiSOC is on `v23.5.2`, released 2026-11-19. **The patch that undoes a silent revert the previous two tags shipped.** A stale-base push had serialized an old tree over `main`: the #1933 merge (an unrelated cases fix) quietly rolled back the #1904 security work, so v23.5.0 and v23.5.1 shipped a **fail-open** threat-actor attribution enforcer (unset token → warn once and allow every caller) while both releases' notes described 503 — and managed-tenant provisioning once again published the known-password demo administrator into every newly promoted tenant. Both are fixed here, each the better way: [@knowlet](https://github.com/knowlet)'s #1966 removes the demo identity from provisioning **structurally** (managed tenants get labelled starter content, never a login; `_ensure_user` itself refuses any tenant but the canonical demo tenant; migration 163 retires demo admins already published into managed tenants — deactivated, sessions revoked, hash replaced, role demoted; a live negative control re-weakens both layers and asserts the suite fails), and #1967 restores the fail-closed enforcer (unset token → 503 unless `AISOC_THREATINTEL_ALLOW_UNAUTHENTICATED=1` is set deliberately), its tests, the deleted compose token gate — now one of **two** detectors for that contract — and Dependabot #1928's reverted realtime OpenTelemetry bump. Every merge in the window was audited for the revert signature: exactly two bad merges, both now remediated, and the push tooling that caused them refuses stale worktrees outright. The withdrawn `picomatch` advisory (GHSA-fc5q-39xc-vjpf, retracted upstream 2026-11-18) was dismissed as inaccurate, taking the Dependabot queue to zero. **2 defects were fixed in this release** (the fail-open enforcer and the provisioning identity, counted as shipped-tag defects; the OTel re-apply is a dependency restoration). **No breaking changes**, with one behavioural note: migration 163 retires `demo@example.com` admin rows in managed tenants — the canonical demo tenant is untouched, and an operator who deliberately wants the demo identity re-runs the demo seeder against that tenant. **Neither `stable` channel moves.** The chart publishes as **`7.24.2`** — an `appVersion`-only move carrying v23.5.2. Everything below describes v23.5.1 and earlier, which this release does not change. +> **TL;DR for first-time visitors:** AiSOC is on `v23.5.3`, released 2026-11-19. **The connector data-completeness patch, community end to end: both defects reported with failing tests by [@pavancharak](https://github.com/pavancharak), both fixed by first-time contributor [@Varshith-Kali](https://github.com/Varshith-Kali), verified against the shipped tag.** The sharper one is in the shared checkpoint machinery every cursored connector uses: `apply_checkpoint` ordered and compared vendor timestamps as **text**, and text order is not time order — `…10:00:00.500Z` is half a second *after* a cursor of `…10:00:00Z` but sorts before it (`.` < `Z`), and a cursor written `…11:00:00+05:00` (06:00Z) drops a row at `…10:00:00Z`, four hours later. Rows newer than the cursor were silently dropped as already read, and the staged cursor could name the wrong row. The cursor now orders and compares the parsed UTC instant with the id breaking ties; a timestamp that does not parse keeps its row (an unparseable time is never a reason to drop data) and falls back to the old text comparison. The second defect: **Huntress, Cisco Secure Endpoint and Sophos Central polled bare clock windows** — and the scheduler drops a run when the previous poll overruns (`max_instances=1`), so the interval behind a skipped run was never requested by any later poll, invisibly, because a skip sets no `last_outage_at`. All three now persist an event-time cursor (Huntress on `sent_at` — delivery, preserving raise-once semantics), overlap one poll interval so a single skipped run is covered before any cursor exists, and skipped runs are logged (`connector.scheduler.poll_skipped`). The overlap re-reads are dropped against the cursor, so the cost is a re-request, never a duplicate or a lost row. **Verified, not asserted:** 449 connector tests pass on the fix; the new instant-ordering suite fails 5 of 8 against the pre-fix tree, pinning the defect it claims to fix. **2 defects fixed in this release** (both in the v23.5.2 tag; the reporter pinned them there). **No breaking changes**, with one observable note: batches from the three converted connectors now leave ordered oldest-first by event time rather than page order. **Neither `stable` channel moves.** The chart publishes as **`7.24.3`** — an `appVersion`-only move carrying v23.5.3. Everything below describes v23.5.2 and earlier, which this release does not change. +> +> **Previously:** AiSOC was on `v23.5.2`, released 2026-11-19. **The patch that undoes a silent revert the previous two tags shipped.** A stale-base push had serialized an old tree over `main`: the #1933 merge (an unrelated cases fix) quietly rolled back the #1904 security work, so v23.5.0 and v23.5.1 shipped a **fail-open** threat-actor attribution enforcer (unset token → warn once and allow every caller) while both releases' notes described 503 — and managed-tenant provisioning once again published the known-password demo administrator into every newly promoted tenant. Both are fixed here, each the better way: [@knowlet](https://github.com/knowlet)'s #1966 removes the demo identity from provisioning **structurally** (managed tenants get labelled starter content, never a login; `_ensure_user` itself refuses any tenant but the canonical demo tenant; migration 163 retires demo admins already published into managed tenants — deactivated, sessions revoked, hash replaced, role demoted; a live negative control re-weakens both layers and asserts the suite fails), and #1967 restores the fail-closed enforcer (unset token → 503 unless `AISOC_THREATINTEL_ALLOW_UNAUTHENTICATED=1` is set deliberately), its tests, the deleted compose token gate — now one of **two** detectors for that contract — and Dependabot #1928's reverted realtime OpenTelemetry bump. Every merge in the window was audited for the revert signature: exactly two bad merges, both now remediated, and the push tooling that caused them refuses stale worktrees outright. The withdrawn `picomatch` advisory (GHSA-fc5q-39xc-vjpf, retracted upstream 2026-11-18) was dismissed as inaccurate, taking the Dependabot queue to zero. **2 defects were fixed in this release** (the fail-open enforcer and the provisioning identity, counted as shipped-tag defects; the OTel re-apply is a dependency restoration). **No breaking changes**, with one behavioural note: migration 163 retires `demo@example.com` admin rows in managed tenants — the canonical demo tenant is untouched, and an operator who deliberately wants the demo identity re-runs the demo seeder against that tenant. **Neither `stable` channel moves.** The chart publishes as **`7.24.2`** — an `appVersion`-only move carrying v23.5.2. Everything below describes v23.5.1 and earlier, which this release does not change. > > **Previously:** AiSOC was on `v23.5.1`, released 2026-11-18. **The patch that makes v23.5.0's own release note true.** v23.5.0 said its "sixteenth secret" — the threat-actor attribution service token — was generated and wired to both ends; on the tag it was neither, so a fresh `make up` answered **503 for every `/api/v1/actors/*` call** with every secret apparently in place. The generator (`ensure_env`) never minted `AISOC_THREATINTEL_SERVICE_TOKEN`, and compose delivered it only to the API, not to the `threatintel` container that enforces the fail-closed gate nor the `agents` container that sends it. This release actually generates it (the generated-secret count moves 15 → 16) and forwards it to both ends, pinned by a gate that discovers the token's readers from source and asserts compose delivers to each — so the generator and the wiring cannot drift apart again. Two more fixes ride along: **`GET /cases?status=open` matches the open caseload again** (it string-matched the write-path alias literally and returned zero rows, which left the console's "add to existing case" picker permanently empty), and **the documentation portal builds again** (a generated connector page shipped `.huntress.io`, which MDX parses as an unclosed tag, failing every GitHub Pages deploy for six days while per-PR CI stayed green). The README screenshots and the walkthrough video were also re-captured against a live v23.5.0 stack — real local-model verdicts, the real KEV feed, a genuine full-profile attack graph, and two new tiles for the entity-risk-hosts and related-cases features — but that is documentation, not a runtime change. **3 defects were fixed in this release**, all found by exercising the shipped tag rather than reading the diff. **No breaking changes.** **Neither `stable` channel moves.** The chart publishes as **`7.24.1`** — an `appVersion`-only move carrying v23.5.1. Everything below describes v23.5.0 and earlier, which this release does not change. > @@ -56,7 +58,21 @@ This file mirrors what used to live in the "What's new" section of [`README.md`] ## What's new -`VERSION` is `23.5.2`. The **v23.5.2** patch (2026-11-19) undoes a silent +`VERSION` is `23.5.3`. The **v23.5.3** patch (2026-11-19) is the connector +data-completeness fix, community end to end: @pavancharak reported two silent +data-loss defects against the shipped v23.5.2 tag with failing tests, and +first-time contributor @Varshith-Kali fixed both. The shared checkpoint cursor +compared vendor timestamps as text — dropping rows newer than the cursor when +the same instant was written with fractional seconds or a UTC offset — and now +orders by the parsed instant with id tie-breaks, keeping any row whose time +does not parse. Huntress, Cisco Secure Endpoint and Sophos Central polled bare +clock windows that lost the interval behind a scheduler-skipped run; all three +now persist an event-time cursor, overlap one interval, and skipped runs are +logged. 449 connector tests pass; the new suite fails 5/8 on the pre-fix tree. +2 defects fixed; no breaking changes; neither `stable` channel moves; chart +`7.24.3`. + +`VERSION` was `23.5.2`. The **v23.5.2** patch (2026-11-19) undoes a silent stale-base revert the previous two tags shipped: the #1933 merge had quietly rolled back #1904, so v23.5.0/v23.5.1 carried a fail-open threat-actor attribution enforcer (warn-and-allow when the token is unset) against release diff --git a/VERSION b/VERSION index b8ea52af9..44b4a50aa 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -23.5.2 +23.5.3 diff --git a/apps/docs/static/data/scoreboard.json b/apps/docs/static/data/scoreboard.json index 727e58d93..e4054828d 100644 --- a/apps/docs/static/data/scoreboard.json +++ b/apps/docs/static/data/scoreboard.json @@ -4,8 +4,8 @@ "rows": [ { "date": "2026-11-19", - "agent_version": "v23.5.2", - "commit_sha": "308280d6", + "agent_version": "v23.5.3", + "commit_sha": "420c707f", "substrate": true, "eval_mode": "substrate-only", "mitre_accuracy": 0.97, diff --git a/apps/docs/static/llms-full.txt b/apps/docs/static/llms-full.txt index c7d90da11..f2eb4606f 100644 --- a/apps/docs/static/llms-full.txt +++ b/apps/docs/static/llms-full.txt @@ -3,7 +3,7 @@ > AiSOC is an open-source, self-hostable AI Security Operations Center, MIT -> licensed and maintained by the AiSOC community. Version 23.5.2. +> licensed and maintained by the AiSOC community. Version 23.5.3. > Repository: https://github.com/beenuar/AiSOC. Documentation: https://beenuar.github.io/AiSOC/. This file exists so an automated reader can answer questions about AiSOC @@ -127,7 +127,7 @@ plans/ Historical prototype subtree — reference only, never edited Every number in this file is generated from the artefact that owns it. If you need to state one, re-derive it rather than quoting a figure from prose — -including from this file, which is a snapshot of version 23.5.2. +including from this file, which is a snapshot of version 23.5.3. ``` python3 scripts/generate_corpus_stats.py --check # executable + on-disk rules diff --git a/apps/docs/static/llms.txt b/apps/docs/static/llms.txt index a381ab905..f3dd1b456 100644 --- a/apps/docs/static/llms.txt +++ b/apps/docs/static/llms.txt @@ -6,7 +6,7 @@ > security telemetry from 97 first-party connectors, normalises it to OCSF, > correlates it into alerts, and runs LLM agents that triage and investigate them. > Every agent decision is written to an investigation ledger, so the reasoning -> behind a verdict can be replayed step by step. MIT licensed. Current version 23.5.2. +> behind a verdict can be replayed step by step. MIT licensed. Current version 23.5.3. AiSOC is built and maintained by the AiSOC community. It is a complete SOC platform rather than a single tool: ingestion, detection, correlation, agent diff --git a/apps/web/package.json b/apps/web/package.json index b06c95366..d8050e77d 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "@aisoc/web", - "version": "23.5.2", + "version": "23.5.3", "private": true, "description": "AiSOC SOC Console - Next.js 14 Frontend", "license": "MIT", diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 57cdccb43..facefe416 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -3,7 +3,7 @@ info: title: AiSOC Platform API description: AiSOC — open-source AI Security Operations Center. Autonomous threat detection, investigation, and response. - version: 23.5.2 + version: 23.5.3 paths: /api/v1/auth/login: post: diff --git a/infra/helm/aisoc/Chart.yaml b/infra/helm/aisoc/Chart.yaml index 7a198b4d1..502cba01d 100644 --- a/infra/helm/aisoc/Chart.yaml +++ b/infra/helm/aisoc/Chart.yaml @@ -34,13 +34,13 @@ type: application # version naming a different application is the v13.0.0 defect the chart # gate refuses. # 7.23.0: the same appVersion-only move, carrying v23.4.0. -version: 7.24.2 +version: 7.24.3 # Used as the image tag wherever a `tag:` in values.yaml is left empty, so # it has to be a tag the registry actually holds — it read "5.2.0", which # exists for no image, so every pod of a default install would have gone to # ImagePullBackOff. scripts/check_published_images.py resolves it the same # way the templates do and fails when it names nothing. -appVersion: "v23.5.2" +appVersion: "v23.5.3" keywords: - security From 6d520eb70514edb50d1c7b2b6d539e0ba783c612 Mon Sep 17 00:00:00 2001 From: Albert Hsieh Date: Thu, 19 Nov 2026 22:37:58 +0800 Subject: [PATCH 2/3] feat(console): drill down from operations alert posture counts Make Total, New (24h), Critical open, and severity/disposition counts navigate to a filtered alert grid, with query-driven tab selection and removable filter chips. Preserve canonical unresolved-status semantics and filter creation-time windows using the same column as the KPI. Add regression tests, OpenAPI schema updates, and documentation. Preserve unknown backend statuses' true labels in filtered results. Signed-off-by: Albert Hsieh --- .../docs/docs/console/operations-dashboard.md | 8 + apps/web/src/app/(app)/alerts/page.tsx | 48 +++++- .../alerts/AlertsDrilldown.test.tsx | 141 ++++++++++++++++++ apps/web/src/components/alerts/AlertsView.tsx | 58 ++++++- .../operations/AlertPosturePanel.tsx | 82 ++++++---- .../operations/OperationsDashboard.test.tsx | 25 ++++ apps/web/src/lib/api.ts | 14 +- docs/openapi.yaml | 19 +++ services/api/app/api/v1/endpoints/alerts.py | 15 +- .../api/tests/test_alerts_tenant_isolation.py | 52 ++++++- 10 files changed, 423 insertions(+), 39 deletions(-) create mode 100644 apps/web/src/components/alerts/AlertsDrilldown.test.tsx diff --git a/apps/docs/docs/console/operations-dashboard.md b/apps/docs/docs/console/operations-dashboard.md index e94748136..9b17665c3 100644 --- a/apps/docs/docs/console/operations-dashboard.md +++ b/apps/docs/docs/console/operations-dashboard.md @@ -44,6 +44,14 @@ Grouped by reason, so the fix is visible from the panel. "Nothing rejected" rend Total, new in 24h, critical still open, plus severity and disposition distributions. +All three counters and every severity/status breakdown entry are links to +the alert-centric grid at `/alerts?view=alerts`, with the relevant filters +preselected. `Critical open` combines `severity=critical` with the same +canonical unresolved-status predicate used by the statistics endpoint; +`New (24h)` filters on alert `created_at`, not the event timestamp. +The drill-down's extra filters appear as removable chips above the grid. +Tenant scope still comes from the logged-in principal, never URL parameters. + This is a **snapshot, not a trend**, and the panel says so. No endpoint in the tree buckets disposition over time, so there is no series to draw. Period-over-period movement is published by `/metrics/funnel` and rendered by the funnel strip at the top of the page; nothing here duplicates it with an arrow it cannot source. ### Detection coverage diff --git a/apps/web/src/app/(app)/alerts/page.tsx b/apps/web/src/app/(app)/alerts/page.tsx index de53bc4eb..654dc8179 100644 --- a/apps/web/src/app/(app)/alerts/page.tsx +++ b/apps/web/src/app/(app)/alerts/page.tsx @@ -1,9 +1,53 @@ import { AlertsView } from '@/components/alerts/AlertsView'; +import type { AlertFilters } from '@/lib/api'; export const metadata = { title: 'Alerts', }; -export default function AlertsPage() { - return ; +type SearchParams = Record; + +export default async function AlertsPage({ + searchParams, +}: { + searchParams?: Promise; +}) { + // Read the deep link on the server so the first render selects the alert + // grid, not the default entity queue. Do not trust tenant IDs in the URL: + // API tenant scoping comes from the authenticated principal. + const params = (await searchParams) ?? {}; + const value = (key: string) => { + const item = params[key]; + return Array.isArray(item) ? item[0] : item; + }; + const severity = value('severity'); + const status = value('status'); + const hours = value('created_within_hours'); + const parsedHours = hours && /^\d{1,4}$/.test(hours) ? Number(hours) : undefined; + const createdWithinHours = + parsedHours !== undefined && parsedHours >= 1 && parsedHours <= 8760 + ? parsedHours + : undefined; + const unresolvedOnly = value('unresolved_only') === 'true'; + + const initialFilters: Partial = { + ...(severity && /^(critical|high|medium|low|info)$/.test(severity) ? { severity } : {}), + ...(status && /^[a-z_]{1,40}$/.test(status) ? { status } : {}), + ...(unresolvedOnly ? { unresolvedOnly: true } : {}), + ...(createdWithinHours !== undefined ? { createdWithinHours } : {}), + }; + const initialViewMode = + value('view') === 'alerts' || Object.keys(initialFilters).length > 0 + ? 'alerts' + : 'entities'; + + // A new deep link must replace a previously mounted alert grid (including + // its local pagination and filters) when navigating within the app. + return ( + + ); } diff --git a/apps/web/src/components/alerts/AlertsDrilldown.test.tsx b/apps/web/src/components/alerts/AlertsDrilldown.test.tsx new file mode 100644 index 000000000..e736bcf43 --- /dev/null +++ b/apps/web/src/components/alerts/AlertsDrilldown.test.tsx @@ -0,0 +1,141 @@ +/** + * Exercises the real /alerts page → AlertsView boundary, not just a query + * parser. A posture link must open the alert grid and send its filters to the + * SWR key that the actual alertsApi.list fetcher consumes. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +const requestedKeys = vi.hoisted(() => [] as unknown[]); +const alertState = vi.hoisted(() => ({ data: undefined as unknown })); + +vi.mock('swr', () => ({ + __esModule: true, + useSWRConfig: () => ({ mutate: vi.fn() }), + default: (key: unknown) => { + requestedKeys.push(key); + const data = Array.isArray(key) && key[0] === 'alerts' ? alertState.data : undefined; + return { data, error: undefined, isLoading: false, mutate: vi.fn() }; + }, +})); + +vi.mock('@/components/alerts/EntityRiskQueue', () => ({ + EntityRiskQueue: () =>
, +})); + +import AlertsPage from '@/app/(app)/alerts/page'; + +function requestedFilters() { + const keys = requestedKeys.filter( + (key): key is [string, Record] => + Array.isArray(key) && key[0] === 'alerts', + ); + return keys[keys.length - 1]?.[1]; +} + +beforeEach(() => { + requestedKeys.length = 0; + alertState.data = undefined; +}); +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +describe('operations posture links open the filtered alert grid', () => { + it('shows the unresolved critical queue, including non-new open statuses', async () => { + const page = await AlertsPage({ + searchParams: Promise.resolve({ + view: 'alerts', + severity: 'critical', + unresolved_only: 'true', + }), + }); + render(page); + + expect(screen.getByRole('tab', { name: 'Alerts' }).getAttribute('aria-selected')).toBe('true'); + expect(screen.getByRole('button', { name: 'Remove unresolved-only filter' })).toBeTruthy(); + expect(requestedFilters()).toMatchObject({ + severity: 'critical', + unresolvedOnly: true, + page: 1, + sort: 'priority', + }); + }); + + it('uses creation time for the 24h filter and allows removing it', async () => { + const page = await AlertsPage({ + searchParams: Promise.resolve({ view: 'alerts', created_within_hours: '24' }), + }); + render(page); + + expect(requestedFilters()?.createdWithinHours).toBe(24); + await userEvent.click(screen.getByRole('button', { name: 'Remove created-within-hours filter' })); + await waitFor(() => expect(requestedFilters()?.createdWithinHours).toBeUndefined()); + expect(requestedFilters()?.sort).toBe('priority'); + }); + + it('opens the status breakdown in the alert grid, not the entity queue', async () => { + const page = await AlertsPage({ + searchParams: Promise.resolve({ view: 'alerts', status: 'false_positive' }), + }); + render(page); + + expect(screen.getByRole('tab', { name: 'Alerts' }).getAttribute('aria-selected')).toBe('true'); + expect(requestedFilters()?.status).toBe('false_positive'); + expect(screen.queryByTestId('entity-queue')).toBeNull(); + }); + + it('shows the real status for a breakdown that is not in the quick-filter buttons', async () => { + alertState.data = { + alerts: [{ + id: 'a1', + title: 'Escalated endpoint alert', + description: '', + severity: 'critical', + status: 'escalated', + source: 'connector', + tenantId: 'default', + createdAt: '2026-11-18T10:00:00Z', + updatedAt: '2026-11-18T10:00:00Z', + tags: [], + iocs: [], + mitreAttack: [], + }], + total: 1, + page: 1, + pageSize: 25, + facets: { bySeverity: { critical: 1 }, byStatus: { escalated: 1 }, unresolved: 1 }, + }; + const page = await AlertsPage({ + searchParams: Promise.resolve({ view: 'alerts', status: 'escalated' }), + }); + render(page); + + expect(screen.getByText('Escalated')).toBeTruthy(); + expect(requestedFilters()?.status).toBe('escalated'); + }); + + it('preserves the default entities tab when no drilldown is supplied', async () => { + const page = await AlertsPage({ searchParams: Promise.resolve({}) }); + render(page); + + expect(screen.getByRole('tab', { name: 'Entities' }).getAttribute('aria-selected')).toBe('true'); + expect(screen.getByTestId('entity-queue')).toBeTruthy(); + }); + + it('does not send invalid time windows or unexpected status strings to the API', async () => { + const page = await AlertsPage({ + searchParams: Promise.resolve({ + view: 'alerts', + created_within_hours: '-50', + status: 'new%26tenant_id%3Dother', + }), + }); + render(page); + + expect(requestedFilters()?.createdWithinHours).toBeUndefined(); + expect(requestedFilters()?.status).toBeUndefined(); + }); +}); diff --git a/apps/web/src/components/alerts/AlertsView.tsx b/apps/web/src/components/alerts/AlertsView.tsx index 8d91ed1fb..d23b502bd 100644 --- a/apps/web/src/components/alerts/AlertsView.tsx +++ b/apps/web/src/components/alerts/AlertsView.tsx @@ -185,10 +185,17 @@ function SeverityBadge({ severity }: { severity: string }) { } function StatusBadge({ status }: { status: string }) { - const cfg = STATUS_CONFIG[status as keyof typeof STATUS_CONFIG] || STATUS_CONFIG.new; + const cfg = STATUS_CONFIG[status as keyof typeof STATUS_CONFIG]; + // The operations disposition breakdown includes worker/vendor statuses not + // represented by the quick-filter buttons. Never label these as "New": + // the actual server status is what the operator clicked to inspect. + const label = cfg?.label ?? status.replace(/_/g, ' ').replace(/^\w/, (c) => c.toUpperCase()); return ( - - {cfg.label} + + {label} ); } @@ -240,6 +247,36 @@ function FiltersBar({ ))}
+ {filters.unresolvedOnly && ( + + )} + {filters.createdWithinHours && ( + + )} + {filters.status && !statuses.includes(filters.status as typeof statuses[number]) && ( + + )} {total} total ); @@ -342,7 +379,13 @@ function AlertRow({ // ─── Main View ──────────────────────────────────────────────────────────────── -export function AlertsView() { +export function AlertsView({ + initialFilters, + initialViewMode = 'entities', +}: { + initialFilters?: Partial; + initialViewMode?: ViewMode; +} = {}) { // `sort: 'priority'` because the API defaults to reverse-chronological for // its SDK clients, and in a console that is the wrong default: a noisy // low-severity source emitting faster than an analyst pages pushes a @@ -351,11 +394,12 @@ export function AlertsView() { page: 1, pageSize: 25, sort: 'priority', + ...initialFilters, }); // Default to the entity-centric queue — that's the whole point of Wave 1's // RBA work. Analysts can flip back to the raw alert grid for legacy // workflows or when triaging a specific alert ID. - const [viewMode, setViewMode] = useState('entities'); + const [viewMode, setViewMode] = useState(initialViewMode); const { t } = useLocale(); const { data, error, isLoading } = useSWR( @@ -686,14 +730,14 @@ function AlertsTableGrid({ filter-aware copy is the difference between an analyst thinking "the system is broken" and "I should clear my filters". */} - {filters.severity || filters.status ? ( + {filters.severity || filters.status || filters.unresolvedOnly || filters.createdWithinHours ? ( onFilterChange({ page: 1, pageSize: filters.pageSize ?? 25 })} + onClick={() => onFilterChange({ page: 1, pageSize: filters.pageSize ?? 25, sort: filters.sort })} className="text-xs px-3 py-1.5 rounded-md border border-blue-500/40 bg-blue-500/10 text-blue-300 hover:bg-blue-500/20 transition-colors" > Clear filters diff --git a/apps/web/src/components/dashboard/operations/AlertPosturePanel.tsx b/apps/web/src/components/dashboard/operations/AlertPosturePanel.tsx index 0a3e8f473..9a3bd4890 100644 --- a/apps/web/src/components/dashboard/operations/AlertPosturePanel.tsx +++ b/apps/web/src/components/dashboard/operations/AlertPosturePanel.tsx @@ -16,6 +16,7 @@ */ import useSWR from 'swr'; +import Link from 'next/link'; import { clsx } from 'clsx'; import { operationsApi } from '@/lib/api'; import { EmptyState } from '@/components/ui/EmptyState'; @@ -23,6 +24,12 @@ import { ErrorState } from '@/components/ui/ErrorState'; const SEVERITY_ORDER = ['critical', 'high', 'medium', 'low', 'info'] as const; +type BreakdownFilter = 'severity' | 'status'; + +function breakdownHref(filter: BreakdownFilter, key: string): string { + return `/alerts?view=alerts&${filter}=${encodeURIComponent(key)}`; +} + const SEVERITY_COLOR: Record = { critical: 'bg-red-500', high: 'bg-orange-500', @@ -104,39 +111,53 @@ export function AlertPosturePanel() { ) : (
-
-

Total

-

+ + Total + {data.total.toLocaleString()} -

-
-
-

New (24h)

-

+ + + + New (24h) + {data.new_last_24h.toLocaleString()} -

-
-
-

Critical open

-

+ + + Critical open + 0 ? 'text-red-300' : 'text-gray-100', )} > {data.critical_open.toLocaleString()} -

-
+ +
SEVERITY_COLOR[k] ?? 'bg-slate-600'} /> (k === 'false_positive' ? 'bg-violet-500' : 'bg-teal-500')} @@ -149,11 +170,13 @@ export function AlertPosturePanel() { function StackedBar({ label, + filter, entries, total, colorFor, }: { label: string; + filter: BreakdownFilter; entries: Array<[string, number]>; total: number; colorFor: (key: string) => string; @@ -172,23 +195,30 @@ function StackedBar({

{label}

{entries.map(([key, n]) => ( -
` separators injected during - // SSR that the client does not reproduce (React #418). title={`${humanise(key)}: ${n}`} - /> + > + {`${humanise(key)}: ${n}`} + ))}
    {entries.map(([key, n]) => ( -
  • -
  • + +
  • ))}
diff --git a/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx b/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx index 5c07d8583..00e1195d4 100644 --- a/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx +++ b/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx @@ -295,6 +295,31 @@ describe('panels render real API values', () => { expect(screen.getByText('False positive')).toBeTruthy(); }); + it('links every alert posture counter and breakdown to the matching alert filter', async () => { + renderDashboard(); + await screen.findByText('128'); + const panel = within(screen.getByRole('region', { name: 'Alert posture' })); + + expect(panel.getByRole('link', { name: 'View all 128 alerts' }).getAttribute('href')) + .toBe('/alerts?view=alerts'); + expect(panel.getByRole('link', { name: 'View 22 alerts created in the last 24 hours' }).getAttribute('href')) + .toBe('/alerts?view=alerts&created_within_hours=24'); + expect(panel.getByRole('link', { name: 'View 3 critical open alerts' }).getAttribute('href')) + .toBe('/alerts?view=alerts&severity=critical&unresolved_only=true'); + + // Both the bar segment and the legend count offer the same drill-down. + const critical = panel.getAllByRole('link', { name: 'View 3 Critical alerts' }); + expect(critical.length).toBe(2); + for (const link of critical) { + expect(link.getAttribute('href')).toBe('/alerts?view=alerts&severity=critical'); + } + const falsePositives = panel.getAllByRole('link', { name: 'View 17 False positive alerts' }); + expect(falsePositives.length).toBe(2); + for (const link of falsePositives) { + expect(link.getAttribute('href')).toBe('/alerts?view=alerts&status=false_positive'); + } + }); + it('labels agent throughput as runs, which is what the endpoint measures', async () => { renderDashboard(); diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 45b457360..59d38b8e2 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -2120,6 +2120,10 @@ function normalizeAlertFacets(raw: unknown): AlertFacets | undefined { export interface AlertFilters { severity?: string; status?: string; + /** Apply the shared unresolved-alert predicate used by critical_open. */ + unresolvedOnly?: boolean; + /** Filter by created_at, not event_time; powers the 24-hour posture KPI. */ + createdWithinHours?: number; source?: string; assignee?: string; startTime?: string; @@ -2163,6 +2167,7 @@ export interface AlertUpdate { export const alertsApi = { list: async (filters: AlertFilters = {}) => { + const { unresolvedOnly, createdWithinHours, pageSize, startTime, endTime, ...rest } = filters; const raw = await request<{ items?: unknown[]; alerts?: unknown[]; @@ -2172,7 +2177,14 @@ export const alertsApi = { pageSize?: number; facets?: unknown; }>("/api/v1/alerts", { - params: filters as Record, + params: { + ...rest, + page_size: pageSize, + event_since: startTime, + event_until: endTime, + unresolved_only: unresolvedOnly, + created_within_hours: createdWithinHours, + }, }); // `AlertListResponse` puts the rows under `items`, not `alerts` // (services/api/app/api/v1/endpoints/alerts.py). Reading only `alerts` diff --git a/docs/openapi.yaml b/docs/openapi.yaml index facefe416..dbb904441 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -776,6 +776,25 @@ paths: - type: string - type: 'null' title: Status + - name: unresolved_only + in: query + required: false + schema: + type: boolean + default: false + title: Unresolved Only + - name: created_within_hours + in: query + required: false + schema: + anyOf: + - type: integer + maximum: 8760 + minimum: 1 + - type: 'null' + description: Alerts created within the last N hours (created_at, not event_time). + title: Created Within Hours + description: Alerts created within the last N hours (created_at, not event_time). - name: disposition in: query required: false diff --git a/services/api/app/api/v1/endpoints/alerts.py b/services/api/app/api/v1/endpoints/alerts.py index be9573927..8fc6b4d61 100644 --- a/services/api/app/api/v1/endpoints/alerts.py +++ b/services/api/app/api/v1/endpoints/alerts.py @@ -4,7 +4,7 @@ import logging import re import uuid -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from typing import Annotated, Any, Literal from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, status @@ -802,6 +802,11 @@ async def list_alerts( ), severity: str | None = Query(default=None), status: str | None = Query(default=None), + unresolved_only: bool = False, + created_within_hours: Annotated[ + int | None, + Query(ge=1, le=8760, description="Alerts created within the last N hours (created_at, not event_time)."), + ] = None, disposition: str | None = Query( default=None, description="Exact-match on the triage disposition (e.g. 'needs_review'). " @@ -878,6 +883,13 @@ async def list_alerts( filters.append(Alert.severity == severity) if status: filters.append(Alert.status == status) + if unresolved_only: + # Same predicate as /alerts/stats critical_open, including unknown statuses. + filters.append(unresolved_filter(Alert.status)) + if created_within_hours is not None: + # Same timestamp column as /alerts/stats new_last_24h; event_since + # intentionally filters event_time and cannot represent this counter. + filters.append(Alert.created_at >= datetime.now(UTC) - timedelta(hours=created_within_hours)) if disposition: filters.append(Alert.disposition == disposition) if category: @@ -959,7 +971,6 @@ async def get_alert_stats( db: DBSession, ) -> AlertStatsResponse: """Get alert statistics for the dashboard.""" - from datetime import timedelta tenant_filter = Alert.tenant_id == current_user.tenant_id diff --git a/services/api/tests/test_alerts_tenant_isolation.py b/services/api/tests/test_alerts_tenant_isolation.py index 0e2d38a72..802d21065 100644 --- a/services/api/tests/test_alerts_tenant_isolation.py +++ b/services/api/tests/test_alerts_tenant_isolation.py @@ -35,7 +35,7 @@ import re import uuid -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from typing import Any from unittest.mock import AsyncMock, MagicMock @@ -349,6 +349,56 @@ async def test_list_alerts_with_filters_keeps_tenant_scope() -> None: assert "tenant_id" in normalized, f"alerts statement missing tenant_id: {sql}" +@pytest.mark.asyncio +async def test_list_alerts_posture_drilldown_uses_the_same_open_and_created_predicates() -> None: + """The critical-open and new-24h links must select the rows counted by stats. + + Open is NOT status == 'new': triaged and unknown non-terminal statuses + are also unresolved. 24h filtering is on created_at, NOT event_time. + """ + user = _user() + db = _mk_db([0, [], [], []]) + await list_alerts( + current_user=user, + db=db, + http_request=_http_request(), + **{ + **_LIST_ALERTS_DEFAULTS, + "severity": "critical", + "unresolved_only": True, + "created_within_hours": 24, + }, + ) + + assert len(db.executed) == 4 + _assert_tenant_scoped(db.executed, user.tenant_id) + for sql, params in db.executed: + assert "alerts.severity" in sql + assert "alerts.status NOT IN" in sql + assert "alerts.status IS NULL" in sql + assert "alerts.created_at >=" in sql + + # Canonical unresolved_filter includes all terminal states. + terminal_groups = [v for v in params.values() if isinstance(v, tuple)] + assert any("false_positive" in group and "resolved" in group for group in terminal_groups) + cutoffs = [v for v in params.values() if isinstance(v, datetime)] + assert len(cutoffs) == 1 + expected = datetime.now(UTC) - timedelta(hours=24) + assert abs((cutoffs[0] - expected).total_seconds()) < 10 + + +@pytest.mark.asyncio +async def test_list_alerts_posture_drilldown_filters_are_opt_in() -> None: + """Ordinary /alerts callers must not inherit a hidden 24h/open filter.""" + user = _user() + db = _mk_db([0, [], [], []]) + await list_alerts(current_user=user, db=db, http_request=_http_request(), **_LIST_ALERTS_DEFAULTS) + + for sql, _params in db.executed: + assert "alerts.status NOT IN" not in sql + assert "alerts.created_at >=" not in sql + + @pytest.mark.asyncio async def test_list_alerts_rejects_invalid_confidence_label() -> None: """The 400 for confidence_label must fire before any DB call (cheap input gate).""" From a3f3a238334b0db302a7c31209b15291aad77220 Mon Sep 17 00:00:00 2001 From: Albert Hsieh Date: Thu, 19 Nov 2026 22:38:04 +0800 Subject: [PATCH 3/3] fix(console): keep alert drilldowns consistent across navigation Synchronize filter changes with the URL and read validated live query parameters when history restores cached page props. Preserve explicit drilldowns over automatic saved-view defaults while allowing manual presets. Improve empty-state guidance and keyboard focus. Fix the link mock and SQLAlchemy collection assertions, test the alerts HTTP parameter contract, and add reload/history and saved-view regressions with an Unreleased changelog entry. Signed-off-by: Albert Hsieh --- CHANGELOG.md | 18 +- .../docs/docs/console/operations-dashboard.md | 4 + .../web/e2e/journeys/alerts-drilldown.spec.ts | 230 ++++++++++++++++++ apps/web/src/app/(app)/alerts/page.tsx | 32 +-- .../alerts/AlertsDrilldown.test.tsx | 165 ++++++++++++- apps/web/src/components/alerts/AlertsView.tsx | 43 +++- .../operations/AlertPosturePanel.tsx | 4 +- .../operations/OperationsDashboard.test.tsx | 4 +- .../saved-views/SavedViewsBar.test.tsx | 52 ++++ .../components/saved-views/SavedViewsBar.tsx | 12 +- apps/web/src/lib/alertDrilldown.ts | 25 ++ apps/web/src/lib/api.alerts-list.test.ts | 74 ++++++ .../api/tests/test_alerts_tenant_isolation.py | 8 +- 13 files changed, 630 insertions(+), 41 deletions(-) create mode 100644 apps/web/e2e/journeys/alerts-drilldown.spec.ts create mode 100644 apps/web/src/lib/alertDrilldown.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f64cfe2b..21ecbf7c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -_Nothing yet._ +### Added + +- Operations dashboard alert-posture counters and severity/status breakdowns + now open the corresponding filtered alert grid. Critical-open links use the + canonical unresolved-status predicate; the 24-hour view uses alert creation + time. Tenant scope continues to come from the authenticated principal. + +### Fixed + +- Alert drill-down filters now stay in sync with the URL when changed or + cleared, so reloading or restoring browser history does not revive removed + filters. Explicit drill-downs take precedence over default saved views while + preserving manual preset selection. Empty-state guidance + includes unresolved-only and creation-time filters, and posture bar links + have a visible keyboard-focus indicator. Regression tests preserve link + accessibility attributes, accept SQLAlchemy's expanding collection binds, + and verify the alerts client's HTTP query parameter names. ## [23.5.3] - 2026-11-19 diff --git a/apps/docs/docs/console/operations-dashboard.md b/apps/docs/docs/console/operations-dashboard.md index 9b17665c3..156caad87 100644 --- a/apps/docs/docs/console/operations-dashboard.md +++ b/apps/docs/docs/console/operations-dashboard.md @@ -50,6 +50,10 @@ preselected. `Critical open` combines `severity=critical` with the same canonical unresolved-status predicate used by the statistics endpoint; `New (24h)` filters on alert `created_at`, not the event timestamp. The drill-down's extra filters appear as removable chips above the grid. +Changing or clearing filters updates the URL, so reloading keeps the current +selection and stays in the alert grid even after the final filter is removed. +Explicit drill-down links take precedence over a default saved view; a saved +view can still be selected manually from the toolbar. Tenant scope still comes from the logged-in principal, never URL parameters. This is a **snapshot, not a trend**, and the panel says so. No endpoint in the tree buckets disposition over time, so there is no series to draw. Period-over-period movement is published by `/metrics/funnel` and rendered by the funnel strip at the top of the page; nothing here duplicates it with an arrow it cannot source. diff --git a/apps/web/e2e/journeys/alerts-drilldown.spec.ts b/apps/web/e2e/journeys/alerts-drilldown.spec.ts new file mode 100644 index 000000000..6c1977f8c --- /dev/null +++ b/apps/web/e2e/journeys/alerts-drilldown.spec.ts @@ -0,0 +1,230 @@ +/** + * Exercise alert drilldowns through the real Next router and browser history. + * Backend responses are synthetic transport fixtures; API/PostgreSQL filter + * semantics are covered separately from these navigation regressions. + */ +import { expect, test, type Page } from "@playwright/test"; + +const NOW = Date.now(); +const FIXTURES = [ + ["critical-new", "critical", "new", 2], + ["critical-escalated", "critical", "escalated", 3], + ["critical-resolved", "critical", "resolved", 4], + ["critical-old", "critical", "triaged", 48], + ["high-recent", "high", "investigating", 5], + ["low-old", "low", "new", 72], + ["medium-false-positive", "medium", "false_positive", 6], + ["info-new", "info", "new", 8], +] as const; + +const ALERTS = FIXTURES.map(([label, severity, status, age], index) => ({ + id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`, + title: `Synthetic drilldown fixture: ${label}`, + severity, + status, + created_at: new Date(NOW - age * 3_600_000).toISOString(), + updated_at: new Date(NOW - age * 3_600_000).toISOString(), + event_time: new Date(NOW - age * 3_600_000).toISOString(), + tags: [], + mitre_tactics: [], + mitre_techniques: [], + affected_ips: [], + affected_hosts: [], + affected_users: [], +})); + +function counts(rows: typeof ALERTS, field: "severity" | "status") { + return rows.reduce>((result, row) => { + result[row[field]] = (result[row[field]] ?? 0) + 1; + return result; + }, {}); +} + +async function mockBackend(page: Page) { + const alertRequests: URLSearchParams[] = []; + await page.route("**/api/v1/**", async (route) => { + const url = new URL(route.request().url()); + if (url.pathname === "/api/v1/alerts") { + const params = url.searchParams; + alertRequests.push(new URLSearchParams(params)); + const rows = ALERTS.filter((row) => + (!params.has("severity") || row.severity === params.get("severity")) && + (!params.has("status") || row.status === params.get("status")) && + (params.get("unresolved_only") !== "true" || + !["resolved", "false_positive"].includes(row.status)) && + (!params.has("created_within_hours") || + Date.parse(row.created_at) >= NOW - Number(params.get("created_within_hours")) * 3_600_000), + ); + await route.fulfill({ json: { + items: rows, + total: rows.length, + page: 1, + page_size: Number(params.get("page_size") ?? 25), + facets: { + by_severity: counts(rows, "severity"), + by_status: counts(rows, "status"), + unresolved: rows.filter((row) => !["resolved", "false_positive"].includes(row.status)).length, + }, + } }); + return; + } + + const fixtures: Record = { + "/api/v1/auth/me": { + id: "drilldown-test-user", + email: "analyst@example.com", + role: "soc_analyst", + tenant_id: "drilldown-test-tenant", + preferences: {}, + }, + "/api/v1/alerts/stats": { + total: 8, + new_last_24h: 6, + critical_open: 3, + by_severity: counts(ALERTS, "severity"), + by_status: counts(ALERTS, "status"), + }, + // A saved default must not override an explicit drilldown, including + // the unfiltered Total link and the URL left after clearing all chips. + "/api/v1/saved-views": [{ + id: "drilldown-default", + view_type: "alerts", + name: "Synthetic low-severity default", + filters: { severity: "low" }, + columns: null, + is_default: true, + created_at: new Date(NOW).toISOString(), + updated_at: new Date(NOW).toISOString(), + }], + }; + if (Object.hasOwn(fixtures, url.pathname)) { + await route.fulfill({ json: fixtures[url.pathname] }); + return; + } + await route.fulfill({ + status: 503, + json: { detail: "Auxiliary service unavailable in drilldown navigation fixture" }, + }); + }); + return alertRequests; +} + +async function expectRows(page: Page, labels: readonly string[]) { + await expect(page.getByRole("tab", { name: "Alerts", exact: true })).toHaveAttribute("aria-selected", "true"); + await expect(page.getByTestId("saved-view-chip-drilldown-default")).toHaveAttribute("aria-pressed", "false"); + await expect(page.getByRole("link", { name: /Synthetic drilldown fixture:/ })).toHaveCount(labels.length); + for (const label of labels) { + await expect(page.getByText(`Synthetic drilldown fixture: ${label}`, { exact: true })).toBeVisible(); + } +} + +test("removing every drilldown chip survives reload and retains unrelated URL state", async ({ page }) => { + const requests = await mockBackend(page); + await page.goto("/alerts?view=alerts&severity=critical&status=escalated&unresolved_only=true&created_within_hours=24&keep=a&keep=b#queue"); + await expectRows(page, ["critical-escalated"]); + await expect(page.getByText("Escalated", { exact: true })).toBeVisible(); + + await page.getByRole("button", { name: "Remove status filter", exact: true }).click(); + await expectRows(page, ["critical-new", "critical-escalated"]); + await expect(page).toHaveURL((url) => !url.searchParams.has("status")); + await page.getByRole("button", { name: "Remove unresolved-only filter", exact: true }).click(); + await expectRows(page, ["critical-new", "critical-escalated", "critical-resolved"]); + await expect(page).toHaveURL((url) => !url.searchParams.has("unresolved_only")); + + await page.reload(); + await expectRows(page, ["critical-new", "critical-escalated", "critical-resolved"]); + await expect(page.getByRole("button", { name: "Remove unresolved-only filter" })).toHaveCount(0); + await page.getByRole("button", { name: "Remove created-within-hours filter", exact: true }).click(); + await expectRows(page, ["critical-new", "critical-escalated", "critical-resolved", "critical-old"]); + await page.getByRole("button", { name: "All severities", exact: true }).click(); + await expectRows(page, FIXTURES.map(([label]) => label)); + await expect(page).toHaveURL((url) => + url.searchParams.get("view") === "alerts" && + ["severity", "status", "unresolved_only", "created_within_hours"].every((key) => !url.searchParams.has(key)) && + url.searchParams.getAll("keep").join(",") === "a,b" && url.hash === "#queue", + ); + await page.reload(); + await expectRows(page, FIXTURES.map(([label]) => label)); + expect(requests.at(-1)?.get("page_size")).toBe("25"); + expect(requests.at(-1)?.get("pageSize")).toBeNull(); +}); + +test("a removed filter stays removed after leaving the route and traversing history", async ({ page }) => { + await mockBackend(page); + await page.goto("/alerts?view=alerts&severity=critical&unresolved_only=true"); + await expectRows(page, ["critical-new", "critical-escalated", "critical-old"]); + await page.getByRole("button", { name: "Remove unresolved-only filter", exact: true }).click(); + const criticalRows = ["critical-new", "critical-escalated", "critical-resolved", "critical-old"]; + await expectRows(page, criticalRows); + await page.getByRole("link", { name: "SOC Operations", exact: true }).click(); + await expect(page.getByRole("heading", { name: "SOC operations", exact: true })).toBeVisible(); + + await page.goBack(); + await expectRows(page, criticalRows); + await expect(page).toHaveURL((url) => url.pathname === "/alerts" && !url.searchParams.has("unresolved_only")); + await expect(page.getByRole("button", { name: "Remove unresolved-only filter" })).toHaveCount(0); + await page.goForward(); + await expect(page.getByRole("heading", { name: "SOC operations", exact: true })).toBeVisible(); + await page.goBack(); + await expectRows(page, criticalRows); +}); + +test("clear filters on an empty drilldown keeps the unfiltered alerts queue after reload", async ({ page }) => { + await mockBackend(page); + await page.goto("/alerts?view=alerts&status=resolved&unresolved_only=true&created_within_hours=24&keep=empty#queue"); + await expect(page.getByText("No alerts match these filters", { exact: true })).toBeVisible(); + await page.getByRole("button", { name: "Clear filters", exact: true }).click(); + await expectRows(page, FIXTURES.map(([label]) => label)); + await expect(page).toHaveURL((url) => + url.searchParams.get("view") === "alerts" && url.searchParams.get("keep") === "empty" && + !url.searchParams.has("status") && !url.searchParams.has("unresolved_only") && + !url.searchParams.has("created_within_hours") && url.hash === "#queue", + ); + await page.reload(); + await expectRows(page, FIXTURES.map(([label]) => label)); +}); + +test("posture links navigate with their accessible names and visible keyboard focus", async ({ page }) => { + await mockBackend(page); + await page.goto("/dashboards/operations"); + const posture = page.getByRole("region", { name: "Alert posture", exact: true }); + const total = posture.getByRole("link", { name: "View all 8 alerts", exact: true }); + await total.click(); + await expectRows(page, FIXTURES.map(([label]) => label)); + await page.goBack(); + + await posture.getByRole("link", { name: "View 6 alerts created in the last 24 hours", exact: true }).click(); + await expectRows(page, ["critical-new", "critical-escalated", "critical-resolved", "high-recent", "medium-false-positive", "info-new"]); + await page.goBack(); + const criticalOpen = posture.getByRole("link", { name: "View 3 critical open alerts", exact: true }); + await criticalOpen.click(); + await expectRows(page, ["critical-new", "critical-escalated", "critical-old"]); + await page.goBack(); + + // The first Critical link is the small segment; the second is its legend. + const criticalSegment = posture.getByRole("link", { name: "View 4 Critical alerts", exact: true }).first(); + await criticalOpen.focus(); + await page.keyboard.press("Tab"); + await expect(criticalSegment).toBeFocused(); + await expect(criticalSegment).toHaveCSS("outline-style", "solid"); + await expect(criticalSegment).toHaveCSS("outline-width", "2px"); + await expect(criticalSegment).toHaveCSS("outline-offset", "2px"); + expect(await criticalSegment.evaluate((link) => getComputedStyle(link.parentElement!).overflow)).toBe("visible"); + await page.keyboard.press("Enter"); + await expectRows(page, ["critical-new", "critical-escalated", "critical-resolved", "critical-old"]); + await page.goBack(); + await posture.getByRole("link", { name: "View 1 Escalated alerts", exact: true }).last().click(); + await expectRows(page, ["critical-escalated"]); + await expect(page.getByText("Escalated", { exact: true })).toBeVisible(); +}); + +test("invalid URL filters are omitted from the alerts request", async ({ page }) => { + const requests = await mockBackend(page); + await page.goto("/alerts?view=alerts&severity=urgent&status=bad%20status&unresolved_only=maybe&created_within_hours=0"); + await expectRows(page, FIXTURES.map(([label]) => label)); + const lastRequest = requests.at(-1); + expect(lastRequest).toBeDefined(); + for (const key of ["severity", "status", "unresolved_only", "created_within_hours"]) { + expect(lastRequest?.has(key), key).toBe(false); + } +}); diff --git a/apps/web/src/app/(app)/alerts/page.tsx b/apps/web/src/app/(app)/alerts/page.tsx index 654dc8179..ea75b0ad3 100644 --- a/apps/web/src/app/(app)/alerts/page.tsx +++ b/apps/web/src/app/(app)/alerts/page.tsx @@ -1,5 +1,5 @@ import { AlertsView } from '@/components/alerts/AlertsView'; -import type { AlertFilters } from '@/lib/api'; +import { readAlertDrilldown } from '@/lib/alertDrilldown'; export const metadata = { title: 'Alerts', @@ -16,30 +16,12 @@ export default async function AlertsPage({ // grid, not the default entity queue. Do not trust tenant IDs in the URL: // API tenant scoping comes from the authenticated principal. const params = (await searchParams) ?? {}; - const value = (key: string) => { - const item = params[key]; - return Array.isArray(item) ? item[0] : item; - }; - const severity = value('severity'); - const status = value('status'); - const hours = value('created_within_hours'); - const parsedHours = hours && /^\d{1,4}$/.test(hours) ? Number(hours) : undefined; - const createdWithinHours = - parsedHours !== undefined && parsedHours >= 1 && parsedHours <= 8760 - ? parsedHours - : undefined; - const unresolvedOnly = value('unresolved_only') === 'true'; - - const initialFilters: Partial = { - ...(severity && /^(critical|high|medium|low|info)$/.test(severity) ? { severity } : {}), - ...(status && /^[a-z_]{1,40}$/.test(status) ? { status } : {}), - ...(unresolvedOnly ? { unresolvedOnly: true } : {}), - ...(createdWithinHours !== undefined ? { createdWithinHours } : {}), - }; - const initialViewMode = - value('view') === 'alerts' || Object.keys(initialFilters).length > 0 - ? 'alerts' - : 'entities'; + const { filters: initialFilters, viewMode: initialViewMode } = readAlertDrilldown({ + get: (key) => { + const item = params[key]; + return Array.isArray(item) ? item[0] : item; + }, + }); // A new deep link must replace a previously mounted alert grid (including // its local pagination and filters) when navigating within the app. diff --git a/apps/web/src/components/alerts/AlertsDrilldown.test.tsx b/apps/web/src/components/alerts/AlertsDrilldown.test.tsx index e736bcf43..769ae208f 100644 --- a/apps/web/src/components/alerts/AlertsDrilldown.test.tsx +++ b/apps/web/src/components/alerts/AlertsDrilldown.test.tsx @@ -4,18 +4,22 @@ * SWR key that the actual alertsApi.list fetcher consumes. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen, waitFor } from '@testing-library/react'; +import { act, cleanup, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; +import { NavigationTestProvider } from '@/test/NavigationTestProvider'; const requestedKeys = vi.hoisted(() => [] as unknown[]); const alertState = vi.hoisted(() => ({ data: undefined as unknown })); +const savedViewsState = vi.hoisted(() => ({ data: undefined as unknown })); vi.mock('swr', () => ({ __esModule: true, useSWRConfig: () => ({ mutate: vi.fn() }), default: (key: unknown) => { requestedKeys.push(key); - const data = Array.isArray(key) && key[0] === 'alerts' ? alertState.data : undefined; + const data = Array.isArray(key) && key[0] === 'alerts' + ? alertState.data + : Array.isArray(key) && key[0] === 'saved-views' ? savedViewsState.data : undefined; return { data, error: undefined, isLoading: false, mutate: vi.fn() }; }, })); @@ -34,9 +38,18 @@ function requestedFilters() { return keys[keys.length - 1]?.[1]; } +async function renderCurrentUrl() { + const searchParams = Object.fromEntries(new URLSearchParams(window.location.search)); + return render(await AlertsPage({ searchParams: Promise.resolve(searchParams) }), { + wrapper: NavigationTestProvider, + }); +} + beforeEach(() => { requestedKeys.length = 0; alertState.data = undefined; + savedViewsState.data = undefined; + window.history.replaceState(null, '', '/alerts'); }); afterEach(() => { cleanup(); @@ -44,6 +57,14 @@ afterEach(() => { }); describe('operations posture links open the filtered alert grid', () => { + const defaultSavedView = { + id: 'default-alerts', + view_type: 'alerts', + name: 'Low resolved alerts', + is_default: true, + filters: { severity: 'low', status: 'resolved' }, + }; + it('shows the unresolved critical queue, including non-new open statuses', async () => { const page = await AlertsPage({ searchParams: Promise.resolve({ @@ -76,6 +97,146 @@ describe('operations posture links open the filtered alert grid', () => { expect(requestedFilters()?.sort).toBe('priority'); }); + it.each([ + ['unresolved_only', 'true', 'Remove unresolved-only filter', 'unresolvedOnly'], + ['created_within_hours', '24', 'Remove created-within-hours filter', 'createdWithinHours'], + ['status', 'escalated', 'Remove status filter', 'status'], + ])('removes %s from the URL so reloading does not restore it', async (param, value, label, filter) => { + window.history.replaceState(null, '', `/alerts?${param}=${value}&tag=one&tag=two#queue`); + const { unmount } = await renderCurrentUrl(); + const historyLength = window.history.length; + + await userEvent.click(screen.getByRole('button', { name: label })); + + const url = new URL(window.location.href); + expect(url.searchParams.has(param)).toBe(false); + expect(url.searchParams.get('view')).toBe('alerts'); + expect(url.searchParams.getAll('tag')).toEqual(['one', 'two']); + expect(url.hash).toBe('#queue'); + expect(window.history.length).toBe(historyLength); + expect(requestedFilters()?.[filter]).toBeUndefined(); + expect(requestedFilters()?.sort).toBe('priority'); + + unmount(); + await renderCurrentUrl(); + expect(screen.queryByRole('button', { name: label })).toBeNull(); + expect(screen.getByRole('tab', { name: 'Alerts' })).toHaveAttribute('aria-selected', 'true'); + expect(requestedFilters()?.[filter]).toBeUndefined(); + }); + + it('keeps the remaining drilldown filters when removing one chip', async () => { + window.history.replaceState(null, '', '/alerts?view=alerts&severity=critical&status=escalated&unresolved_only=true&created_within_hours=24'); + await renderCurrentUrl(); + + await userEvent.click(screen.getByRole('button', { name: 'Remove unresolved-only filter' })); + + expect(Object.fromEntries(new URLSearchParams(window.location.search))).toEqual({ + view: 'alerts', severity: 'critical', status: 'escalated', created_within_hours: '24', + }); + expect(requestedFilters()).toMatchObject({ + severity: 'critical', status: 'escalated', createdWithinHours: 24, page: 1, sort: 'priority', + }); + }); + + it('updates the URL when changing the severity and status quick filters', async () => { + window.history.replaceState(null, '', '/alerts?view=alerts&severity=critical&status=new&unresolved_only=true'); + await renderCurrentUrl(); + + await userEvent.click(screen.getByRole('button', { name: 'High' })); + await userEvent.click(screen.getByRole('button', { name: 'Investigating' })); + expect(Object.fromEntries(new URLSearchParams(window.location.search))).toEqual({ + view: 'alerts', severity: 'high', status: 'investigating', unresolved_only: 'true', + }); + + await userEvent.click(screen.getByRole('button', { name: 'All severities' })); + await userEvent.click(screen.getByRole('button', { name: 'All statuses' })); + expect(Object.fromEntries(new URLSearchParams(window.location.search))).toEqual({ + view: 'alerts', unresolved_only: 'true', + }); + }); + + it('explains the new filters in the empty state and clears them from the URL', async () => { + window.history.replaceState(null, '', '/alerts?severity=critical&status=escalated&unresolved_only=true&created_within_hours=24'); + const { unmount } = await renderCurrentUrl(); + + expect(screen.getByText(/severity, status, unresolved-only, or creation-time filters/i)).toBeInTheDocument(); + await userEvent.click(screen.getByRole('button', { name: 'Clear filters' })); + expect(window.location.search).toBe('?view=alerts'); + expect(requestedFilters()).toEqual({ page: 1, pageSize: 25, sort: 'priority' }); + + unmount(); + await renderCurrentUrl(); + expect(screen.queryByRole('button', { name: 'Clear filters' })).toBeNull(); + expect(screen.getByRole('tab', { name: 'Alerts' })).toHaveAttribute('aria-selected', 'true'); + }); + + it('keeps the drilldown instead of automatically applying a saved default, while allowing manual selection', async () => { + savedViewsState.data = [defaultSavedView]; + window.history.replaceState(null, '', '/alerts?view=alerts&severity=critical&unresolved_only=true'); + await renderCurrentUrl(); + + expect(requestedFilters()).toMatchObject({ severity: 'critical', unresolvedOnly: true, sort: 'priority' }); + expect(new URLSearchParams(window.location.search).get('severity')).toBe('critical'); + const preset = screen.getByRole('button', { name: /Low resolved alerts/, pressed: false }); + expect(preset).toHaveAttribute('aria-pressed', 'false'); + + await userEvent.click(preset); + expect(requestedFilters()).toMatchObject({ severity: 'low', status: 'resolved' }); + expect(requestedFilters()?.unresolvedOnly).toBeUndefined(); + expect(Object.fromEntries(new URLSearchParams(window.location.search))).toEqual({ + view: 'alerts', severity: 'low', status: 'resolved', + }); + expect(preset).toHaveAttribute('aria-pressed', 'true'); + }); + + it('shows all alerts from the Total link even when a default saved view exists', async () => { + savedViewsState.data = [defaultSavedView]; + window.history.replaceState(null, '', '/alerts?view=alerts'); + await renderCurrentUrl(); + + expect(requestedFilters()).toEqual({ page: 1, pageSize: 25, sort: 'priority' }); + expect(window.location.search).toBe('?view=alerts'); + }); + + it('still applies the saved default when opening alerts without an explicit drilldown', async () => { + savedViewsState.data = [defaultSavedView]; + await renderCurrentUrl(); + await userEvent.click(screen.getByRole('tab', { name: 'Alerts' })); + + expect(requestedFilters()).toMatchObject({ severity: 'low', status: 'resolved' }); + expect(screen.getByRole('button', { name: /Low resolved alerts/, pressed: true })).toBeInTheDocument(); + }); + + it('reads the current URL when history remounts cached server props', async () => { + const cachedPage = await AlertsPage({ + searchParams: Promise.resolve({ severity: 'critical', unresolved_only: 'true' }), + }); + window.history.replaceState(null, '', '/alerts?view=alerts'); + render(cachedPage, { wrapper: NavigationTestProvider }); + + expect(requestedFilters()?.severity).toBeUndefined(); + expect(requestedFilters()?.unresolvedOnly).toBeUndefined(); + expect(screen.queryByRole('button', { name: 'Remove unresolved-only filter' })).toBeNull(); + expect(screen.getByRole('tab', { name: 'Alerts' })).toHaveAttribute('aria-selected', 'true'); + }); + + it('follows Back and Forward query changes without requiring fresh server props', async () => { + window.history.replaceState(null, '', '/alerts?view=alerts&severity=critical&unresolved_only=true'); + await renderCurrentUrl(); + + act(() => window.history.pushState(null, '', '/alerts?view=alerts&severity=high&created_within_hours=24')); + expect(requestedFilters()).toMatchObject({ severity: 'high', createdWithinHours: 24 }); + expect(requestedFilters()?.unresolvedOnly).toBeUndefined(); + + act(() => window.history.back()); + await waitFor(() => expect(requestedFilters()).toMatchObject({ severity: 'critical', unresolvedOnly: true })); + expect(requestedFilters()?.createdWithinHours).toBeUndefined(); + + act(() => window.history.forward()); + await waitFor(() => expect(requestedFilters()).toMatchObject({ severity: 'high', createdWithinHours: 24 })); + expect(requestedFilters()?.unresolvedOnly).toBeUndefined(); + }); + it('opens the status breakdown in the alert grid, not the entity queue', async () => { const page = await AlertsPage({ searchParams: Promise.resolve({ view: 'alerts', status: 'false_positive' }), diff --git a/apps/web/src/components/alerts/AlertsView.tsx b/apps/web/src/components/alerts/AlertsView.tsx index d23b502bd..27093c655 100644 --- a/apps/web/src/components/alerts/AlertsView.tsx +++ b/apps/web/src/components/alerts/AlertsView.tsx @@ -3,6 +3,7 @@ import { useState, useCallback } from 'react'; import useSWR, { useSWRConfig } from 'swr'; import Link from 'next/link'; +import { useSearchParams } from 'next/navigation'; import { BulkTriageBar } from './BulkTriageBar'; import { alertsApi, type Alert, type AlertFacets, type AlertFilters, type ConfidenceLabel } from '@/lib/api'; import { clsx } from 'clsx'; @@ -14,6 +15,7 @@ import { ErrorState } from '@/components/ui/ErrorState'; import { SavedViewsBar } from '@/components/saved-views/SavedViewsBar'; import { useLocale } from '@/components/i18n/LocaleProvider'; import { demoFallback } from '@/lib/demoFallback'; +import { readAlertDrilldown } from '@/lib/alertDrilldown'; // Wave 1 of the AiSOC v6 capability roadmap. The "entities" tab renders the // rolled-up Risk-Based Alerting queue — alerts contribute time-decayed risk @@ -390,16 +392,29 @@ export function AlertsView({ // its SDK clients, and in a console that is the wrong default: a noisy // low-severity source emitting faster than an analyst pages pushes a // critical off page one and keeps it there. - const [filters, setFilters] = useState({ + const searchParams = useSearchParams(); + const drilldown = searchParams ? readAlertDrilldown(searchParams) : undefined; + const [localFilters, setFilters] = useState({ page: 1, pageSize: 25, sort: 'priority', ...initialFilters, }); + // History can restore cached server props after a chip was removed. Read + // URL-controlled fields from the live router, keeping local sort, page size, + // and other saved-view fields when replacing the URL. + const filters: AlertFilters = drilldown ? { + ...localFilters, + severity: drilldown.filters.severity, + status: drilldown.filters.status, + unresolvedOnly: drilldown.filters.unresolvedOnly, + createdWithinHours: drilldown.filters.createdWithinHours, + } : localFilters; // Default to the entity-centric queue — that's the whole point of Wave 1's // RBA work. Analysts can flip back to the raw alert grid for legacy // workflows or when triaging a specific alert ID. - const [viewMode, setViewMode] = useState(initialViewMode); + const [viewMode, setViewMode] = useState(drilldown?.viewMode ?? initialViewMode); + const [autoApplyDefault] = useState((drilldown?.viewMode ?? initialViewMode) !== 'alerts'); const { t } = useLocale(); const { data, error, isLoading } = useSWR( @@ -423,6 +438,24 @@ export function AlertsView({ const handleFilterChange = useCallback((newFilters: AlertFilters) => { setFilters(newFilters); + + const url = new URL(window.location.href); + const params = { + view: 'alerts', + severity: newFilters.severity || undefined, + status: newFilters.status || undefined, + unresolved_only: newFilters.unresolvedOnly ? 'true' : undefined, + created_within_hours: newFilters.createdWithinHours?.toString(), + }; + for (const [name, value] of Object.entries(params)) { + if (value === undefined) url.searchParams.delete(name); + else url.searchParams.set(name, value); + } + + // Keep a reload on the same queue, including when its final chip is + // removed. Native history preserves local sort/pagination and unrelated + // query parameters without a server navigation remounting this view. + window.history.replaceState(null, '', `${url.pathname}${url.search}${url.hash}`); }, []); const alerts = data?.alerts || []; @@ -504,6 +537,7 @@ export function AlertsView({ total={total} facets={facets} filters={filters} + autoApplyDefault={autoApplyDefault} isLoading={isLoading} error={error} onFilterChange={handleFilterChange} @@ -520,6 +554,7 @@ function AlertsTable({ total, facets, filters, + autoApplyDefault, isLoading, error, onFilterChange, @@ -528,6 +563,7 @@ function AlertsTable({ total: number; facets?: AlertFacets; filters: AlertFilters; + autoApplyDefault: boolean; isLoading: boolean; error: unknown; onFilterChange: (f: AlertFilters) => void; @@ -582,6 +618,7 @@ function AlertsTable({ viewType="alerts" filters={filters} + autoApplyDefault={autoApplyDefault} onApply={(applied) => onFilterChange({ ...applied, @@ -734,7 +771,7 @@ function AlertsTableGrid({ onFilterChange({ page: 1, pageSize: filters.pageSize ?? 25, sort: filters.sort })} diff --git a/apps/web/src/components/dashboard/operations/AlertPosturePanel.tsx b/apps/web/src/components/dashboard/operations/AlertPosturePanel.tsx index 9a3bd4890..7e892faea 100644 --- a/apps/web/src/components/dashboard/operations/AlertPosturePanel.tsx +++ b/apps/web/src/components/dashboard/operations/AlertPosturePanel.tsx @@ -193,13 +193,13 @@ function StackedBar({ return (

{label}

-
+
{entries.map(([key, n]) => ( diff --git a/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx b/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx index 00e1195d4..37d1654ea 100644 --- a/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx +++ b/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx @@ -40,8 +40,8 @@ vi.mock('@/lib/api', () => ({ vi.mock('next/link', () => ({ __esModule: true, - default: ({ children, href }: { children: React.ReactNode; href: string }) => ( - {children} + default: ({ children, ...props }: React.ComponentProps<'a'>) => ( + {children} ), })); diff --git a/apps/web/src/components/saved-views/SavedViewsBar.test.tsx b/apps/web/src/components/saved-views/SavedViewsBar.test.tsx index cfadc8d8f..5240d3a18 100644 --- a/apps/web/src/components/saved-views/SavedViewsBar.test.tsx +++ b/apps/web/src/components/saved-views/SavedViewsBar.test.tsx @@ -231,6 +231,58 @@ describe('SavedViewsBar', () => { expect(onApply).not.toHaveBeenCalled(); }); + it('does not apply or highlight a default that arrives after an explicit deep link', () => { + const onApply = vi.fn(); + const onDefaultLoaded = vi.fn(); + const toolbar = () => ( + + viewType="alerts" + filters={{ status: 'escalated' }} + onApply={onApply} + onDefaultLoaded={onDefaultLoaded} + autoApplyDefault={false} + /> + ); + const { rerender } = render(toolbar()); + + seedViews('alerts', [ + makeView({ id: 'v-default', is_default: true, filters: { status: 'resolved' } }), + ]); + rerender(toolbar()); + + expect(onApply).not.toHaveBeenCalled(); + expect(onDefaultLoaded).not.toHaveBeenCalled(); + expect(screen.getByTestId('saved-view-chip-v-default')).toHaveAttribute('aria-pressed', 'false'); + }); + + it('allows manually selecting a default preset when automatic application is disabled', async () => { + const defaultFilters = { status: 'resolved' }; + seedViews('alerts', [ + makeView({ id: 'v-default', is_default: true, filters: defaultFilters }), + ]); + const onApply = vi.fn(); + const onDefaultLoaded = vi.fn(); + render( + + viewType="alerts" + filters={{ status: 'escalated' }} + onApply={onApply} + onDefaultLoaded={onDefaultLoaded} + autoApplyDefault={false} + />, + ); + + const preset = screen.getByTestId('saved-view-chip-v-default'); + expect(onApply).not.toHaveBeenCalled(); + expect(preset).toHaveAttribute('aria-pressed', 'false'); + + await userEvent.click(preset); + + expect(onApply).toHaveBeenCalledExactlyOnceWith(defaultFilters); + expect(onDefaultLoaded).not.toHaveBeenCalled(); + expect(preset).toHaveAttribute('aria-pressed', 'true'); + }); + it('saves the current filters with the typed name', async () => { seedViews('alerts', []); createMock.mockResolvedValue(makeView({ id: 'v-new', name: 'My filter' })); diff --git a/apps/web/src/components/saved-views/SavedViewsBar.tsx b/apps/web/src/components/saved-views/SavedViewsBar.tsx index cb07473bb..0ff8e4212 100644 --- a/apps/web/src/components/saved-views/SavedViewsBar.tsx +++ b/apps/web/src/components/saved-views/SavedViewsBar.tsx @@ -58,6 +58,8 @@ interface SavedViewsBarProps { * mount, so it can avoid double-applying or fire analytics. */ onDefaultLoaded?: (view: SavedView) => void; + /** Set false to preserve explicit deep-link filters instead of loading the user's default. */ + autoApplyDefault?: boolean; /** Hide the "Save current view" affordance, e.g. in read-only demos. */ readOnly?: boolean; } @@ -67,6 +69,7 @@ export function SavedViewsBar({ filters, onApply, onDefaultLoaded, + autoApplyDefault = true, readOnly = false, }: SavedViewsBarProps) { // Each page key is unique so multiple bars on the same screen wouldn't @@ -91,7 +94,9 @@ export function SavedViewsBar({ // nothing", which is the state a delete leaves behind — collapsing the two // would re-light the default chip the moment its row was removed. const [picked, setPicked] = useState<{ id: string | null } | null>(null); - const defaultViewId = isLoading ? null : (views.find((v) => v.is_default)?.id ?? null); + const defaultViewId = isLoading || !autoApplyDefault + ? null + : (views.find((v) => v.is_default)?.id ?? null); const activeViewId = picked ? picked.id : defaultViewId; const [openMenuId, setOpenMenuId] = useState(null); @@ -125,7 +130,7 @@ export function SavedViewsBar({ // since changed. const defaultAppliedRef = useRef(false); useEffect(() => { - if (defaultAppliedRef.current || isLoading || views.length === 0) return; + if (!autoApplyDefault || defaultAppliedRef.current || isLoading || views.length === 0) return; defaultAppliedRef.current = true; const def = views.find((v) => v.is_default); @@ -133,7 +138,7 @@ export function SavedViewsBar({ onApplyRef.current(def.filters as TFilters); onDefaultLoadedRef.current?.(def); - }, [views, isLoading]); + }, [views, isLoading, autoApplyDefault]); const apply = useCallback( (view: SavedView) => { @@ -268,6 +273,7 @@ export function SavedViewsBar({