Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(queue): investigation queue workbench + endpoints (PR-5 / W7)

Beenu Arora96a5d276e9b2
diff --git a/apps/docs/docs/console/queue.md b/apps/docs/docs/console/queue.md
new file mode 100644
index 000000000..09f43b5fa
--- /dev/null
+++ b/apps/docs/docs/console/queue.md
@@ -0,0 +1,223 @@
+---
+sidebar_position: 1
+title: Investigation Queue workbench
+description: The /queue workbench — an opinionated, single-page feed answering "what should I work on next?" with atomic claim semantics, server-anchored SLA countdowns, and one-click triage actions.
+---
+
+# Investigation Queue workbench
+
+`/queue` is the page a Tier-1 analyst lives on. It exists to answer one question — *"what should I work on next?"* — and it answers it the same way an experienced shift-lead would: alerts already assigned to you first, then critical and high alerts no one has claimed, all of it ordered by SLA due time so the closest-to-breach work surfaces first. Low-priority unassigned alerts are deliberately excluded; those are triaged in bulk on `/alerts`.
+
+This page documents the bucket model, the SLA timer, the action set, and the API surface that powers the workbench.
+
+## Where the workbench sits
+
+```
+┌──────────────────────────────────────────────────────────────────────────┐
+│ Investigation Queue [Mine 3] [Unassigned 12] [All 15] │
+│ ────────────────────────────────────────────────────────────────────── │
+│ ● CRIT Impossible travel · [email protected] SLA -2m 04s [Open] │
+│ ● HIGH Defender — credential dump · web-01 SLA 3m 41s [Open] │
+│ ● HIGH GitHub PAT exfil · svc-deploy SLA 9m 12s [Open] │
+│ ● MED New OAuth grant · helpdesk@… SLA 1h 22m [Open] │
+│ ────────────────────────────────────────────────────────────────────── │
+│ ● HIGH AWS S3 mass-download · prod-data-lake SLA 12m 03s [Claim] │
+│ ● HIGH Suspicious lateral SMB · fin-pc-19 SLA 14m 47s [Claim] │
+│ │
+│ Mine first ─────► Unassigned (critical / high) ─────► oldest SLA │
+└──────────────────────────────────────────────────────────────────────────┘
+```
+
+The queue is intentionally narrow — one row per alert, one anchor entity per row, one suggested next action. The Investigation Rail (W6) and `/alerts` are where the deep dive happens; the queue is where you decide *which* deep dive to take next.
+
+## The three buckets
+
+The owner toggle drives both the filter and the count badges. Counts are returned for every bucket on every fetch so the workbench can switch tabs without re-fetching.
+
+| Bucket | What it shows | Why |
+|---|---|---|
+| **Mine** | Every open alert assigned to the current user, any severity. | Once you own a row you finish it — severity is no longer the gating factor. |
+| **Unassigned** | Open `critical` and `high` alerts with no `assigned_to_id`. | The "up for grabs" queue. Low-priority unassigned alerts are deliberately omitted: paging through them one at a time is a documented anti-pattern of legacy SOC consoles. |
+| **All** | Mine first, then Unassigned, ordered as above. | The default landing view. Tier-1 sees their own work without losing sight of the unowned high-severity queue. |
+
+Each bucket is filtered against the same `closed` exit set (`resolved`, `closed`, `false_positive`, `fp`) and the same snooze mask (`snoozed_until <= now`), so claiming, resolving, or snoozing a row makes it disappear deterministically across all three views.
+
+## The SLA timer
+
+Every queue row carries a server-computed `sla_due_at` and `sla_remaining_seconds`. The frontend then ticks the timer down once per second against the server's authoritative `generated_at` timestamp, so:
+
+- The number two analysts on two laptops see for the *same row at the same wall-clock moment* is identical.
+- A 30-second polling gap does not produce a 30-second jump in the countdown — the next page payload arrives with a fresh `generated_at` and the local clock simply re-anchors.
+- Once `sla_remaining_seconds` goes negative, the pill flips to **breached** and the row sorts to the top of its bucket (because `sla_due_at ASC` is the primary sort).
+
+### SLA target resolution
+
+`sla_due_at` is a *virtual* column computed at query time as `first_seen + mttd_target`, where `mttd_target` is severity-keyed and tenant-configurable:
+
+```
+critical → configurable, defaults to DEFAULT_SLA_TARGETS["critical"]["mttd_target"] minutes
+high → ...
+medium → ...
+low → ...
+info → ...
+```
+
+The query merges `DEFAULT_SLA_TARGETS` with any rows in `tenant_sla_config`, so per-tenant overrides win without rewriting the alerts schema when the targets are re-tuned. The SQL is a plain `CASE` on severity, so PostgreSQL can index-walk on `alerts.first_seen` and apply the offset cheaply — there is no per-row Python pass.
+
+### The 10-minute amber threshold
+
+The SLA pill has three colour states:
+
+| State | Trigger | Meaning |
+|---|---|---|
+| `ok` | `sla_remaining_seconds >= 600` | Plenty of runway. |
+| `warn` | `0 <= sla_remaining_seconds < 600` | Inside the last 10 minutes — act now. |
+| `breached` | `sla_remaining_seconds < 0` | Past the deadline — bump the case, escalate, or document why it slipped. |
+
+10 minutes is the operations-spec threshold and is independent of severity — anything in the last ten minutes of an SLA is treated as "act now" territory.
+
+## The actions
+
+Each queue row exposes four single-click actions. They are intentionally flat — no modals, no confirmation dialogs — so an SOC can sweep through a backlog without breaking flow:
+
+| Action | What it does | Backend |
+|---|---|---|
+| **Open** | Navigates to `/alerts/{id}` to load the Investigation Rail. | Read-only. |
+| **Claim** | Atomically assigns the unassigned alert to the current user. | `POST /api/v1/alerts/{id}/claim` |
+| **Release** | (Only on rows you own.) Sets `assigned_to_id = NULL`, returning the row to the Unassigned bucket. | `PATCH /api/v1/alerts/{id}` |
+| **Snooze** | Defers the row from the queue for a fixed window. The four presets are **15m / 1h / 4h / 24h**. Anything longer should go through a suppression rule, not a per-alert snooze. | `POST /api/v1/alerts/{id}/snooze` |
+
+### Atomic claim semantics
+
+Claim is the only action with race semantics, because two analysts looking at the same Unassigned bucket can both reach for the same row. The backend handles this with a compare-and-set:
+
+```sql
+UPDATE alerts
+ SET assigned_to_id = :user, assigned_at = now(), updated_at = now()
+ WHERE id = :alert_id
+ AND assigned_to_id IS NULL
+RETURNING assigned_to_id;
+```
+
+- If the `RETURNING` row matches the caller → claim succeeded, response is `200 AlertResponse`.
+- If it does not return a row → someone else got there first; the endpoint re-reads `assigned_to_id` and responds with `409 Conflict` carrying the actual owner's UUID.
+- If the alert is already assigned to *the caller* → no-op `200`. Re-clicking Claim after a stale page refresh must never produce a 409, and it does not.
+
+The frontend surfaces a `toast` on `409` so the analyst sees who beat them to the row and can move on without reloading.
+
+## The API envelope
+
+The workbench is served by a single endpoint:
+
+```
+GET /api/v1/alerts/queue
+ ?owner=me|unassigned|all (default: all)
+ &period=24h|7d|30d|all (default: all)
+ &page=1 (default: 1)
+ &page_size=50 (default: 50, max: 200)
+```
+
+### Route ordering
+
+`/alerts/queue` is registered **before** `/alerts/{alert_id}` in the FastAPI router. This is intentional and load-bearing: FastAPI matches top-down, and a parametric path that lands first would happily route `GET /alerts/queue` into `get_alert(alert_id="queue")` and 422. The endpoint definition is explicit about the ordering so future contributors do not accidentally swap them.
+
+### Response shape
+
+The `QueueResponse` envelope:
+
+```jsonc
+{
+ "items": [
+ {
+ "id": "8b2e…",
+ "tenant_id": "…",
+ "title": "Impossible travel — Okta",
+ "severity": "high",
+ "status": "new",
+ "priority": 3,
+ "category": "identity",
+ "connector_type": "okta",
+
+ "assigned_to_id": "11a3…", // null if unclaimed
+ "case_id": null,
+
+ "first_seen": "2026-05-13T08:31:00Z",
+ "sla_due_at": "2026-05-13T09:01:00Z",
+ "sla_remaining_seconds": -124, // negative → breached
+ "sla_breached": true,
+ "age_seconds": 1864,
+
+ "asset": { "kind": "host", "value": "web-01" },
+ "suggested_action": {
+ "priority": 1,
+ "action": "Isolate the host via EDR",
+ "risk": "high"
+ },
+ "bucket": "mine"
+ }
+ ],
+ "total": 15,
+ "counts": { "mine": 3, "unassigned": 12, "all": 15 },
+ "period": "all",
+ "owner": "all",
+ "page": 1,
+ "page_size": 50,
+ "pages": 1,
+ "generated_at": "2026-05-13T09:03:04Z"
+}
+```
+
+Notes on the contract:
+
+- `counts` is **always** populated for all three buckets regardless of the `owner` filter — that is what lets the tab badges and the sidebar live badge render without an extra round-trip.
+- `generated_at` is the server-side `now()` used to compute `sla_remaining_seconds`. The frontend drifts all per-row countdowns from this value, so two analysts on different boxes see the same numbers.
+- `asset` surfaces one representative pivot per alert (host → user → asset → ip, in that order). The full pivotable list lives on the Investigation Rail; this is the *anchor*, not the inventory.
+- `suggested_action` is the lowest-priority entry from `Alert.ai_recommendations`, normalised across modern (`{priority, action, risk}`) and legacy (bare string) payloads. Older rows that wrote strings get `risk="low"` and a priority derived from their array index.
+
+## Polling and freshness
+
+The workbench polls `GET /alerts/queue` on a **15-second cadence** (`refreshInterval: 15000`, `keepPreviousData: true`). Between polls, every row's SLA countdown ticks down once per second on the client, anchored to `generated_at`. The combination means:
+
+- The page is never more than 15 seconds stale.
+- The numbers never visibly stutter — the client never re-renders the countdown from a stale anchor, it always re-anchors from the latest server response.
+- Action responses (claim / release / snooze) re-validate the SWR cache immediately, so a successful action is reflected in the queue without waiting for the next 15-second tick.
+
+## Sidebar live badge
+
+The sidebar `Investigation Queue` nav item carries a live pill showing the **count of items in your personal Mine bucket**. The badge is rendered by a small `LiveQueueBadge` component that polls `GET /alerts/queue?owner=me&page_size=1` on a **30-second cadence** (the metadata-only request is much cheaper than the full workbench fetch).
+
+- The badge is hidden entirely when `counts.mine === 0` — we don't draw attention to an empty queue.
+- Counts > 99 render as `99+` while the exact number is preserved in the `aria-label` and `title` attributes for screen readers and tooltip hover.
+- The badge revalidates on focus and on reconnect, so coming back from a sleeping laptop refreshes the number immediately rather than waiting for the next 30-second tick.
+
+## Permissions and tenancy
+
+All queue endpoints run under the existing `alerts:read` and `alerts:write` permissions and a tenant-scoped DB session. The build query has `Alert.tenant_id == current_user.tenant_id` baked in at the SQLAlchemy layer, and `claim_alert` re-asserts the tenant filter on every row read. Analysts only ever see queue rows for alerts they are authorised to see on `/alerts` in the first place.
+
+## What this replaces
+
+| Before (v1.4) | After (v1.5) |
+|---|---|
+| Analysts paged through `/alerts` filtered by `assigned_to_me=true` and severity. | One opinionated `/queue` page with three buckets and a single ordering rule. |
+| SLA countdowns were derived client-side from `first_seen` and a hard-coded default. | SLA target resolved server-side from `tenant_sla_config`, anchored to `generated_at` for cross-analyst consistency. |
+| Claim was a PATCH that any client could send — no race protection. | Atomic compare-and-set on `assigned_to_id IS NULL`. Two analysts racing for the same alert is now a deterministic single-winner. |
+| Snooze did not exist as a queue affordance; alerts had to be acknowledged or assigned away. | Four preset snooze windows (15m / 1h / 4h / 24h) on every row, server-validated against a 30-day ceiling. |
+| Sidebar showed a static "Alerts" label. | Sidebar `Investigation Queue` link carries a live pill anchored to the same backend the workbench uses. |
+
+## Source layout
+
+| Concern | File |
+|---|---|
+| Workbench page route | [`apps/web/src/app/(app)/queue/page.tsx`](https://github.com/beenuar/AiSOC/blob/main/apps/web/src/app/(app)/queue/page.tsx) |
+| Workbench component | [`apps/web/src/components/queue/QueueView.tsx`](https://github.com/beenuar/AiSOC/blob/main/apps/web/src/components/queue/QueueView.tsx) |
+| Sidebar live badge | [`apps/web/src/components/layout/LiveQueueBadge.tsx`](https://github.com/beenuar/AiSOC/blob/main/apps/web/src/components/layout/LiveQueueBadge.tsx) |
+| API client | [`apps/web/src/lib/api.ts`](https://github.com/beenuar/AiSOC/blob/main/apps/web/src/lib/api.ts) (search for `queueApi`) |
+| Queue endpoint + claim/snooze | [`services/api/app/api/v1/endpoints/alerts.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/api/v1/endpoints/alerts.py) |
+| Queue builder, claim logic, SLA expression | [`services/api/app/services/alert_queue.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/alert_queue.py) |
+| SLA targets (default + per-tenant resolution) | [`services/api/app/services/sla.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/sla.py) |
+| Backend tests | [`services/api/tests/test_alert_queue.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/tests/test_alert_queue.py) |
+| Frontend tests | [`apps/web/src/components/queue/QueueView.test.tsx`](https://github.com/beenuar/AiSOC/blob/main/apps/web/src/components/queue/QueueView.test.tsx) · [`apps/web/src/components/layout/LiveQueueBadge.test.tsx`](https://github.com/beenuar/AiSOC/blob/main/apps/web/src/components/layout/LiveQueueBadge.test.tsx) |
+
+## Author
+
+Beenu Arora · `[email protected]`
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index dbadad174..5dc658978 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -27,6 +27,11 @@ const sidebars: SidebarsConfig = {
"features/attack-path-agent",
],
},
+ {
+ type: "category",
+ label: "Console",
+ items: ["console/queue"],
+ },
{
type: "category",
label: "Architecture",
diff --git a/apps/web/src/app/(app)/queue/page.tsx b/apps/web/src/app/(app)/queue/page.tsx
new file mode 100644
index 000000000..4d3840231
--- /dev/null
+++ b/apps/web/src/app/(app)/queue/page.tsx
@@ -0,0 +1,9 @@
+import { QueueView } from '@/components/queue/QueueView';
+
+export const metadata = {
+ title: 'Investigation Queue | AiSOC',
+};
+
+export default function QueuePage() {
+ return <QueueView />;
+}
diff --git a/apps/web/src/components/layout/LiveQueueBadge.test.tsx b/apps/web/src/components/layout/LiveQueueBadge.test.tsx
new file mode 100644
index 000000000..66411d7a2
--- /dev/null
+++ b/apps/web/src/components/layout/LiveQueueBadge.test.tsx
@@ -0,0 +1,142 @@
+/**
+ * Tests for the sidebar `LiveQueueBadge`.
+ *
+ * The badge fetches `GET /api/v1/alerts/queue?owner=me` on a low-rate poll
+ * and surfaces the `counts.mine` value as a pill on the Investigation
+ * Queue nav item. We assert the three states that matter for sidebar UX:
+ *
+ * 1. Zero count → component renders nothing (don't draw attention to
+ * an empty queue).
+ * 2. Small count → numeric label and aria-label match the count.
+ * 3. >99 count → clamped to "99+" so the pill never overflows the
+ * sidebar slot.
+ *
+ * @author Beenu Arora <[email protected]>
+ */
+
+import { render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { LiveQueueBadge } from './LiveQueueBadge';
+import type { QueueResponse } from '@/lib/api';
+
+// ---------------------------------------------------------------------------
+// Mock infrastructure
+// ---------------------------------------------------------------------------
+//
+// We treat SWR as a thin pass-through: the test owns the data shape and the
+// component just reads `data?.counts?.mine`. We also mock the API client so
+// SWR never tries to hit a real fetch.
+
+const swrState: { data: QueueResponse | undefined } = { data: undefined };
+
+vi.mock('swr', () => ({
+ __esModule: true,
+ default: () => ({
+ data: swrState.data,
+ error: undefined,
+ isLoading: false,
+ isValidating: false,
+ mutate: vi.fn(),
+ }),
+}));
+
+vi.mock('@/lib/api', async () => {
+ const actual = await vi.importActual<typeof import('@/lib/api')>('@/lib/api');
+ return {
+ ...actual,
+ queueApi: {
+ list: vi.fn(),
+ claim: vi.fn(),
+ assign: vi.fn(),
+ snooze: vi.fn(),
+ },
+ };
+});
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Build a minimal QueueResponse shaped just enough for the badge.
+ *
+ * The badge only reads `counts.mine`; the rest is here to satisfy the
+ * type contract so we catch upstream shape regressions at typecheck time.
+ */
+function makeResponse(mineCount: number): QueueResponse {
+ return {
+ items: [],
+ total: mineCount,
+ counts: { mine: mineCount, unassigned: 0, all: mineCount },
+ period: 'all',
+ owner: 'me',
+ page: 1,
+ page_size: 1,
+ pages: 1,
+ generated_at: new Date().toISOString(),
+ };
+}
+
+afterEach(() => {
+ swrState.data = undefined;
+});
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+describe('LiveQueueBadge', () => {
+ it('renders nothing when SWR has no data yet', () => {
+ swrState.data = undefined;
+
+ const { container } = render(<LiveQueueBadge />);
+
+ // An undefined SWR result resolves to `count = 0`, which we hide.
+ expect(container.firstChild).toBeNull();
+ });
+
+ it('renders nothing when the mine count is zero', () => {
+ swrState.data = makeResponse(0);
+
+ const { container } = render(<LiveQueueBadge />);
+
+ expect(container.firstChild).toBeNull();
+ expect(screen.queryByTestId('sidebar-queue-badge')).not.toBeInTheDocument();
+ });
+
+ it('renders the numeric count when the user has open alerts', () => {
+ swrState.data = makeResponse(5);
+
+ render(<LiveQueueBadge />);
+
+ const pill = screen.getByTestId('sidebar-queue-badge');
+ expect(pill).toHaveTextContent('5');
+ expect(pill).toHaveAttribute('aria-label', '5 items in your queue');
+ // Title mirrors the aria-label for sighted users on hover.
+ expect(pill).toHaveAttribute('title', '5 items in your queue');
+ });
+
+ it('uses the singular noun when the count is exactly one', () => {
+ swrState.data = makeResponse(1);
+
+ render(<LiveQueueBadge />);
+
+ const pill = screen.getByTestId('sidebar-queue-badge');
+ expect(pill).toHaveTextContent('1');
+ expect(pill).toHaveAttribute('aria-label', '1 item in your queue');
+ });
+
+ it('clamps the display label to "99+" past one hundred', () => {
+ swrState.data = makeResponse(247);
+
+ render(<LiveQueueBadge />);
+
+ const pill = screen.getByTestId('sidebar-queue-badge');
+ // Display is clamped so the pill stays inside the sidebar gutter…
+ expect(pill).toHaveTextContent('99+');
+ // …but the accessible label keeps the real number so screen readers get
+ // the truth.
+ expect(pill).toHaveAttribute('aria-label', '247 items in your queue');
+ });
+});
diff --git a/apps/web/src/components/layout/LiveQueueBadge.tsx b/apps/web/src/components/layout/LiveQueueBadge.tsx
new file mode 100644
index 000000000..7c14a949c
--- /dev/null
+++ b/apps/web/src/components/layout/LiveQueueBadge.tsx
@@ -0,0 +1,50 @@
+'use client';
+
+import useSWR from 'swr';
+import { queueApi, type QueueResponse } from '@/lib/api';
+
+const POLL_INTERVAL_MS = 30_000;
+
+/**
+ * Sidebar pill that surfaces the current user's open Investigation Queue
+ * count. It polls `GET /api/v1/alerts/queue?owner=me` on a low-rate timer so
+ * the sidebar stays current without paying for a full page render.
+ *
+ * Rendered as the right-slot of the Investigation Queue nav item. Hidden when
+ * the count is zero so we don't draw attention to an empty queue.
+ *
+ * @author Beenu Arora <[email protected]>
+ */
+export function LiveQueueBadge() {
+ const { data } = useSWR<QueueResponse>(
+ ['sidebar:queue:mine'],
+ () => queueApi.list({ owner: 'me', period: 'all', page: 1, page_size: 1 }),
+ {
+ refreshInterval: POLL_INTERVAL_MS,
+ revalidateOnFocus: true,
+ revalidateOnReconnect: true,
+ shouldRetryOnError: false,
+ dedupingInterval: 10_000,
+ },
+ );
+
+ const count = data?.counts?.mine ?? 0;
+
+ if (count <= 0) {
+ return null;
+ }
+
+ const display = count > 99 ? '99+' : String(count);
+ const label = `${count} item${count === 1 ? '' : 's'} in your queue`;
+
+ return (
+ <span
+ className="ml-auto inline-flex items-center justify-center min-w-[1.25rem] h-5 px-1.5 rounded-full text-xs font-bold text-white tabular-nums bg-brand-600"
+ aria-label={label}
+ title={label}
+ data-testid="sidebar-queue-badge"
+ >
+ {display}
+ </span>
+ );
+}
diff --git a/apps/web/src/components/layout/Sidebar.tsx b/apps/web/src/components/layout/Sidebar.tsx
index 9c9c87acf..c2d6ea5a6 100644
--- a/apps/web/src/components/layout/Sidebar.tsx
+++ b/apps/web/src/components/layout/Sidebar.tsx
@@ -5,6 +5,7 @@ import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { clsx } from 'clsx';
import packageJson from '../../../package.json';
+import { LiveQueueBadge } from './LiveQueueBadge';
const APP_VERSION = packageJson.version;
@@ -14,6 +15,13 @@ interface NavItem {
icon: React.ReactNode;
badge?: number;
badgeColor?: string;
+ /**
+ * Optional live-data right slot. Renders in place of the static ``badge``
+ * pill when present, so nav items that need real-time counts (e.g. the
+ * Investigation Queue) can own their own polling without bloating this
+ * component.
+ */
+ liveBadge?: React.ReactNode;
}
interface NavSection {
@@ -104,6 +112,12 @@ const ClockIcon = () => (
</svg>
);
+const InboxIcon = () => (
+ <svg className="w-5 h-5" aria-hidden="true" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M2.25 13.5h3.86a2.25 2.25 0 012.012 1.244l.256.512a2.25 2.25 0 002.013 1.244h3.218a2.25 2.25 0 002.013-1.244l.256-.512a2.25 2.25 0 012.013-1.244h3.859m-19.5.338V18a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18v-4.162c0-.224-.034-.447-.1-.661L19.24 5.338a2.25 2.25 0 00-2.15-1.588H6.911a2.25 2.25 0 00-2.15 1.588L2.35 13.177a2.25 2.25 0 00-.1.661z" />
+ </svg>
+);
+
const ScanIcon = () => (
<svg className="w-5 h-5" aria-hidden="true" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7.5 3.75H6A2.25 2.25 0 003.75 6v1.5M16.5 3.75H18A2.25 2.25 0 0120.25 6v1.5m0 9V18A2.25 2.25 0 0118 20.25h-1.5m-9 0H6A2.25 2.25 0 013.75 18v-1.5M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
@@ -148,6 +162,12 @@ const navSections: NavSection[] = [
badge: 0,
badgeColor: 'bg-red-500',
},
+ {
+ label: 'Investigation Queue',
+ href: '/queue',
+ icon: <InboxIcon />,
+ liveBadge: <LiveQueueBadge />,
+ },
{
label: 'Cases',
href: '/cases',
@@ -395,13 +415,15 @@ export function Sidebar() {
>
<span className={active ? 'text-brand-400' : 'text-fg-subtle'}>{item.icon}</span>
<span>{item.label}</span>
- {typeof item.badge === 'number' && item.badge > 0 && (
- <span
- className={`ml-auto text-xs font-bold px-1.5 py-0.5 rounded-full text-white ${item.badgeColor ?? 'bg-gray-600'}`}
- >
- {item.badge > 99 ? '99+' : item.badge}
- </span>
- )}
+ {item.liveBadge
+ ? item.liveBadge
+ : typeof item.badge === 'number' && item.badge > 0 && (
+ <span
+ className={`ml-auto text-xs font-bold px-1.5 py-0.5 rounded-full text-white ${item.badgeColor ?? 'bg-gray-600'}`}
+ >
+ {item.badge > 99 ? '99+' : item.badge}
+ </span>
+ )}
</Link>
</li>
);
diff --git a/apps/web/src/components/queue/QueueView.test.tsx b/apps/web/src/components/queue/QueueView.test.tsx
new file mode 100644
index 000000000..b9c73a534
--- /dev/null
+++ b/apps/web/src/components/queue/QueueView.test.tsx
@@ -0,0 +1,463 @@
+/**
+ * Smoke tests for the Investigation Queue workbench (PR-5 / v1.5 §W7).
+ *
+ * The QueueView is the analyst's "what should I work on next?" screen, so the
+ * behaviours we pin here are the ones an SOC would actually file a P1 against
+ * if they regressed:
+ *
+ * 1. Loading skeleton renders before the first server response.
+ * 2. Empty-state copy adapts to the active owner tab.
+ * 3. Queue rows render the data the backend hands us (severity, SLA pill,
+ * bucket, asset, suggested action, "In case" pill).
+ * 4. Claim button issues `POST /alerts/{id}/claim`, fires a success toast,
+ * and revalidates the SWR cache.
+ * 5. A 409 from a teammate-beat-us-to-it race is surfaced as a friendly toast.
+ * 6. Owner toggle is mirrored to the URL via SWR key change (we assert on the
+ * observed query payload, since SWR re-fetches when keys change).
+ * 7. Backend errors render the ErrorState with a working retry.
+ *
+ * We mock SWR + `@/lib/api` + react-hot-toast so the test focuses on the view
+ * layer without booting a fetch stack. The mocked SWR shim mirrors the subset
+ * of the real hook the component touches.
+ *
+ * @author Beenu Arora <[email protected]>
+ */
+
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import { act, render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { QueueItem, QueueResponse } from '@/lib/api';
+
+// ─── Mock SWR ─────────────────────────────────────────────────────────────────
+//
+// The component calls `useSWR(['queue', owner, period, page], fetcher, opts)`.
+// We render the latest payload returned by the fetcher and expose a hand-rolled
+// mutate() so tests can assert revalidations after mutations.
+
+const swrState = vi.hoisted(() => ({
+ data: undefined as QueueResponse | undefined,
+ error: undefined as Error | undefined,
+ isLoading: false,
+ mutateCount: 0,
+}));
+
+const mutateMock = vi.hoisted(() => vi.fn());
+
+vi.mock('swr', () => ({
+ __esModule: true,
+ default: () => ({
+ data: swrState.data,
+ error: swrState.error,
+ isLoading: swrState.isLoading,
+ mutate: mutateMock,
+ }),
+}));
+
+// ─── Mock the API layer ───────────────────────────────────────────────────────
+
+const queueListMock = vi.hoisted(() => vi.fn());
+const queueClaimMock = vi.hoisted(() => vi.fn());
+const queueAssignMock = vi.hoisted(() => vi.fn());
+const queueSnoozeMock = vi.hoisted(() => vi.fn());
+const currentUserMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@/lib/api', () => ({
+ __esModule: true,
+ queueApi: {
+ list: queueListMock,
+ claim: queueClaimMock,
+ assign: queueAssignMock,
+ snooze: queueSnoozeMock,
+ },
+ authApi: {
+ currentUser: currentUserMock,
+ },
+}));
+
+// ─── Mock next/link ───────────────────────────────────────────────────────────
+//
+// We render <Link> as a plain anchor so the click handlers + child markup are
+// reachable; the full Next router is irrelevant here.
+
+vi.mock('next/link', () => ({
+ __esModule: true,
+ default: ({
+ children,
+ href,
+ ...rest
+ }: {
+ children: React.ReactNode;
+ href: string;
+ [k: string]: unknown;
+ }) => (
+ <a href={typeof href === 'string' ? href : ''} {...rest}>
+ {children}
+ </a>
+ ),
+}));
+
+// ─── Mock toast ───────────────────────────────────────────────────────────────
+
+const toastSuccess = vi.hoisted(() => vi.fn());
+const toastError = vi.hoisted(() => vi.fn());
+vi.mock('react-hot-toast', () => ({
+ __esModule: true,
+ default: { success: toastSuccess, error: toastError },
+}));
+
+// Import AFTER mocks so the module picks them up.
+import { QueueView } from './QueueView';
+
+// ─── Fixtures ─────────────────────────────────────────────────────────────────
+
+const NOW_ISO = '2026-05-13T12:00:00Z';
+const CURRENT_USER_ID = 'user-self';
+
+function makeItem(overrides: Partial<QueueItem> = {}): QueueItem {
+ return {
+ id: 'a-1',
+ tenant_id: 't-1',
+ title: 'Suspicious PowerShell encoded command',
+ severity: 'high',
+ status: 'new',
+ priority: 1,
+ category: 'endpoint',
+ connector_type: 'edr',
+ assigned_to_id: null,
+ case_id: null,
+ first_seen: '2026-05-13T11:00:00Z',
+ sla_due_at: '2026-05-13T13:00:00Z',
+ sla_remaining_seconds: 3600,
+ sla_breached: false,
+ age_seconds: 3600,
+ asset: { kind: 'host', value: 'win-laptop-42', label: 'win-laptop-42' },
+ suggested_action: {
+ priority: 1,
+ action: 'Isolate host',
+ risk: 'high',
+ },
+ bucket: 'unassigned',
+ ...overrides,
+ };
+}
+
+function makeResponse(items: QueueItem[], overrides: Partial<QueueResponse> = {}): QueueResponse {
+ return {
+ items,
+ total: items.length,
+ counts: {
+ mine: items.filter((i) => i.bucket === 'mine').length,
+ unassigned: items.filter((i) => i.bucket === 'unassigned').length,
+ all: items.length,
+ },
+ period: 'all',
+ owner: 'me',
+ page: 1,
+ page_size: 50,
+ pages: 1,
+ generated_at: NOW_ISO,
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ swrState.data = undefined;
+ swrState.error = undefined;
+ swrState.isLoading = false;
+ swrState.mutateCount = 0;
+ mutateMock.mockReset();
+ mutateMock.mockResolvedValue(undefined);
+ queueListMock.mockReset();
+ queueClaimMock.mockReset();
+ queueAssignMock.mockReset();
+ queueSnoozeMock.mockReset();
+ toastSuccess.mockReset();
+ toastError.mockReset();
+ currentUserMock.mockReset();
+ currentUserMock.mockReturnValue({
+ id: CURRENT_USER_ID,
+ email: '[email protected]',
+ role: 'responder',
+ tenant_id: 't-1',
+ });
+});
+
+/**
+ * Click an action button and drain the resulting async handler inside a
+ * single `act()` boundary.
+ *
+ * The action handlers in `QueueView` (claim/release/snooze) are async
+ * fire-and-forget — the JSX wires `onClick={() => onClaim(id)}` and the
+ * handler `await`s `queueApi.*` and `mutate()`, then resets the busy flag
+ * via `setBusy(id, null)` in a `finally` block. user-event's implicit
+ * `act()` wrapper only covers the click dispatch itself, so the trailing
+ * `setBusy(null)` state update lands outside `act` and triggers the
+ * "An update to QueueView inside a test was not wrapped in act(...)" warning.
+ *
+ * Wrapping both the click and microtask drainage in a manual `act()` keeps
+ * the entire async chain — including the `finally` cleanup — inside the
+ * boundary, which is what the React testing contract requires.
+ */
+async function clickAndSettle(user: ReturnType<typeof userEvent.setup>, el: HTMLElement) {
+ await act(async () => {
+ await user.click(el);
+ // Drain at least three microtask hops:
+ // 1. queueApi.* promise resolves
+ // 2. await mutate() yields one tick
+ // 3. finally { setBusy(null) } commits
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+describe('QueueView', () => {
+ it('renders the loading skeleton before the first server response', () => {
+ swrState.isLoading = true;
+ swrState.data = undefined;
+
+ render(<QueueView />);
+
+ // Header still renders during loading so the analyst sees context.
+ expect(screen.getByText(/Investigation Queue/i)).toBeInTheDocument();
+ // No queue rows yet — the data is undefined.
+ expect(screen.queryByText('Suspicious PowerShell encoded command')).not.toBeInTheDocument();
+ });
+
+ it('renders the empty state for an empty Mine bucket', () => {
+ swrState.data = makeResponse([], { owner: 'me' });
+
+ render(<QueueView />);
+
+ expect(screen.getByText(/Nothing in your queue/i)).toBeInTheDocument();
+ expect(
+ screen.getByText(/Switch to Unassigned to pick something up/i),
+ ).toBeInTheDocument();
+ });
+
+ it('renders queue items with severity, asset, bucket, and SLA info', () => {
+ const item = makeItem();
+ swrState.data = makeResponse([item]);
+
+ render(<QueueView />);
+
+ // Title is rendered.
+ expect(screen.getByText(item.title)).toBeInTheDocument();
+
+ // Scope all per-row assertions inside the alert row's anchor so we don't
+ // collide with same-text nodes in the owner toggle / counts header.
+ const row = screen.getByRole('link', { name: /Investigate Suspicious PowerShell/i });
+ const withinRow = within(row);
+
+ // Severity pill ("HIGH").
+ expect(withinRow.getByText('HIGH')).toBeInTheDocument();
+ // Bucket pill — "Unassigned" also appears as an OwnerToggle tab label,
+ // so we must scope to the row.
+ expect(withinRow.getByText('Unassigned')).toBeInTheDocument();
+ // Asset label rendered in the metadata strip.
+ expect(withinRow.getByText('win-laptop-42')).toBeInTheDocument();
+ // Suggested action text comes through with the "→" prefix.
+ expect(withinRow.getByText(/Isolate host/i)).toBeInTheDocument();
+ // SLA pill renders with "SLA" prefix and a formatted countdown.
+ expect(withinRow.getByText(/^SLA /)).toBeInTheDocument();
+ });
+
+ it('shows "In case" pill when the alert is already linked to a case', () => {
+ const item = makeItem({ case_id: 'case-42' });
+ swrState.data = makeResponse([item]);
+
+ render(<QueueView />);
+
+ expect(screen.getByText(/In case/i)).toBeInTheDocument();
+ });
+
+ it("marks rows assigned to the current user as 'Mine' and shows the Release action", () => {
+ const item = makeItem({
+ bucket: 'mine',
+ assigned_to_id: CURRENT_USER_ID,
+ });
+ swrState.data = makeResponse([item]);
+
+ render(<QueueView />);
+
+ // "Mine" appears both as an OwnerToggle tab label and as the BucketBadge
+ // inside the row; scope to the row so we're asserting on the badge.
+ const row = screen.getByRole('link', { name: /Investigate Suspicious PowerShell/i });
+ expect(within(row).getByText('Mine')).toBeInTheDocument();
+
+ // No Claim button — already mine.
+ expect(screen.queryByRole('button', { name: /^Claim$/ })).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /^Release$/ })).toBeInTheDocument();
+ });
+
+ it('issues POST /claim and revalidates SWR on successful claim', async () => {
+ const item = makeItem();
+ swrState.data = makeResponse([item]);
+ queueClaimMock.mockResolvedValue({ id: item.id });
+
+ const user = userEvent.setup();
+ render(<QueueView />);
+
+ const claimBtn = screen.getByRole('button', { name: /^Claim$/ });
+ await clickAndSettle(user, claimBtn);
+
+ expect(queueClaimMock).toHaveBeenCalledTimes(1);
+ expect(queueClaimMock).toHaveBeenCalledWith(item.id);
+ expect(toastSuccess).toHaveBeenCalledWith(
+ expect.stringMatching(/Claimed — this alert is yours/),
+ );
+ expect(mutateMock).toHaveBeenCalled();
+ });
+
+ it('surfaces a 409 conflict as a "teammate beat you to it" toast', async () => {
+ const item = makeItem();
+ swrState.data = makeResponse([item]);
+ queueClaimMock.mockRejectedValue(
+ new Error('409 Conflict: alert already claimed'),
+ );
+
+ const user = userEvent.setup();
+ render(<QueueView />);
+
+ const claimBtn = screen.getByRole('button', { name: /^Claim$/ });
+ await clickAndSettle(user, claimBtn);
+
+ expect(toastError).toHaveBeenCalledWith(
+ expect.stringMatching(/Another responder claimed this alert first/),
+ );
+ expect(toastSuccess).not.toHaveBeenCalled();
+ // We still revalidate so the UI catches up to the new ownership state.
+ expect(mutateMock).toHaveBeenCalled();
+ });
+
+ it('falls back to a generic error toast when claim fails for unknown reasons', async () => {
+ const item = makeItem();
+ swrState.data = makeResponse([item]);
+ queueClaimMock.mockRejectedValue(new Error('boom'));
+
+ const user = userEvent.setup();
+ render(<QueueView />);
+
+ await clickAndSettle(user, screen.getByRole('button', { name: /^Claim$/ }));
+
+ expect(toastError).toHaveBeenCalledWith('boom');
+ });
+
+ it('releases an assigned alert with a null assignee', async () => {
+ const item = makeItem({
+ bucket: 'mine',
+ assigned_to_id: CURRENT_USER_ID,
+ });
+ swrState.data = makeResponse([item]);
+ queueAssignMock.mockResolvedValue({ id: item.id });
+
+ const user = userEvent.setup();
+ render(<QueueView />);
+
+ await clickAndSettle(user, screen.getByRole('button', { name: /^Release$/ }));
+
+ expect(queueAssignMock).toHaveBeenCalledWith(item.id, null);
+ expect(toastSuccess).toHaveBeenCalledWith(
+ expect.stringMatching(/Released back to the unassigned pool/),
+ );
+ });
+
+ it('snoozes an alert for the selected duration', async () => {
+ const item = makeItem({
+ bucket: 'mine',
+ assigned_to_id: CURRENT_USER_ID,
+ });
+ swrState.data = makeResponse([item]);
+ queueSnoozeMock.mockResolvedValue({ id: item.id });
+
+ const user = userEvent.setup();
+ const { container } = render(<QueueView />);
+
+ // Force the <details> open directly. JSDOM's native summary-toggle
+ // behaviour is inconsistent across versions, so we don't rely on it for
+ // this assertion — we care about the action handler being wired up, not
+ // about the disclosure mechanics.
+ const detailsEl = container.querySelector('details') as HTMLDetailsElement | null;
+ expect(detailsEl).not.toBeNull();
+ if (detailsEl) detailsEl.open = true;
+
+ // Pick the 1h preset. The menuitem buttons live inside the disclosure and
+ // are addressable by their preset label.
+ const oneHour = screen.getByRole('menuitem', { name: '1h' });
+ await clickAndSettle(user, oneHour);
+
+ expect(queueSnoozeMock).toHaveBeenCalledWith(item.id, { duration_minutes: 60 });
+ expect(toastSuccess).toHaveBeenCalledWith(expect.stringMatching(/Snoozed for 1h/));
+ });
+
+ it('renders owner toggle counts from the response', () => {
+ swrState.data = makeResponse(
+ [
+ makeItem({ id: 'a-mine', bucket: 'mine', assigned_to_id: CURRENT_USER_ID }),
+ makeItem({ id: 'a-other', bucket: 'unassigned' }),
+ ],
+ {
+ counts: { mine: 3, unassigned: 7, all: 12 },
+ },
+ );
+
+ render(<QueueView />);
+
+ // Each tab renders its label + a numeric badge.
+ const mineTab = screen.getByRole('tab', { name: /Mine/i });
+ const unassignedTab = screen.getByRole('tab', { name: /Unassigned/i });
+ const allTab = screen.getByRole('tab', { name: /^All/i });
+
+ expect(mineTab).toBeInTheDocument();
+ expect(unassignedTab).toBeInTheDocument();
+ expect(allTab).toBeInTheDocument();
+
+ // Badges show the counts (3, 7, 12).
+ expect(mineTab.textContent).toContain('3');
+ expect(unassignedTab.textContent).toContain('7');
+ expect(allTab.textContent).toContain('12');
+ });
+
+ it('switches owner tab on click', async () => {
+ swrState.data = makeResponse([makeItem({ bucket: 'unassigned' })]);
+
+ const user = userEvent.setup();
+ render(<QueueView />);
+
+ const unassignedTab = screen.getByRole('tab', { name: /Unassigned/i });
+ expect(unassignedTab).toHaveAttribute('aria-selected', 'false');
+
+ await act(async () => {
+ await user.click(unassignedTab);
+ });
+
+ // After click, that tab is selected — we re-read because React swaps the
+ // aria-selected attribute after the state update flushes.
+ expect(
+ screen.getByRole('tab', { name: /Unassigned/i }),
+ ).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('renders the error state when SWR returns an error', () => {
+ swrState.error = new Error('Network failure');
+ swrState.data = undefined;
+
+ render(<QueueView />);
+
+ expect(screen.getByText(/Couldn't load the queue/i)).toBeInTheDocument();
+ });
+
+ it('caps the SEV badge to INFO when severity is unknown', () => {
+ // Defence-in-depth: if the backend ever ships a severity we don't model,
+ // we still want a fallback pill so the UI doesn't crash.
+ const item = makeItem({
+ // @ts-expect-error — intentionally invalid for the guard test.
+ severity: 'bogus',
+ });
+ swrState.data = makeResponse([item]);
+
+ render(<QueueView />);
+
+ expect(screen.getByText('INFO')).toBeInTheDocument();
+ });
+});
diff --git a/apps/web/src/components/queue/QueueView.tsx b/apps/web/src/components/queue/QueueView.tsx
new file mode 100644
index 000000000..f3be99188
--- /dev/null
+++ b/apps/web/src/components/queue/QueueView.tsx
@@ -0,0 +1,794 @@
+'use client';
+
+/**
+ * Investigation Queue workbench (PR-5 / v1.5 §W7).
+ *
+ * Answers the analyst's one true question — "what should I work on next?" —
+ * with a ranked, server-prioritised feed of alerts split across three buckets:
+ *
+ * ┌───────────┬──────────────────────────────────────────────────────────┐
+ * │ Mine │ Alerts already assigned to the current responder. │
+ * │ Unassigned│ Up-for-grabs alerts the responder can claim atomically. │
+ * │ All │ Mine first, then unassigned, ordered by SLA + severity. │
+ * └───────────┴──────────────────────────────────────────────────────────┘
+ *
+ * The page polls the backend every 15 seconds, but per-row SLA countdowns tick
+ * down once per second on the client to avoid a stale-looking workbench.
+ * Countdowns are anchored to the server's `generated_at` timestamp so the
+ * clock the analyst sees matches the clock the SLA rules ran against.
+ *
+ * Actions are deliberately single-click — Claim, Release, Snooze, Open — so an
+ * SOC can move through the queue without diving into modals. Backend ownership
+ * semantics are atomic (single-writer 409 on simultaneous claims), so the UI
+ * surfaces conflicts via toast instead of optimistic-lock surprises.
+ */
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import useSWR from 'swr';
+import Link from 'next/link';
+import { clsx } from 'clsx';
+import toast from 'react-hot-toast';
+import {
+ queueApi,
+ authApi,
+ type AlertSeverity,
+ type QueueItem,
+ type QueueOwner,
+ type QueuePeriod,
+ type QueueResponse,
+} from '@/lib/api';
+import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';
+import { ErrorState } from '@/components/ui/ErrorState';
+import { Skeleton } from '@/components/ui/Skeleton';
+
+// ─── Config ───────────────────────────────────────────────────────────────────
+
+const SEVERITY_CONFIG: Record<
+ AlertSeverity,
+ { label: string; dot: string; text: string; bg: string }
+> = {
+ critical: { label: 'CRIT', dot: 'bg-red-500', text: 'text-red-400', bg: 'bg-red-500/10 border-red-500/20' },
+ high: { label: 'HIGH', dot: 'bg-orange-500', text: 'text-orange-400', bg: 'bg-orange-500/10 border-orange-500/20' },
+ medium: { label: 'MED', dot: 'bg-yellow-500', text: 'text-yellow-400', bg: 'bg-yellow-500/10 border-yellow-500/20' },
+ low: { label: 'LOW', dot: 'bg-blue-500', text: 'text-blue-400', bg: 'bg-blue-500/10 border-blue-500/20' },
+ info: { label: 'INFO', dot: 'bg-gray-500', text: 'text-gray-400', bg: 'bg-gray-500/10 border-gray-500/20' },
+};
+
+const RISK_CONFIG = {
+ high: { dot: 'bg-red-500', text: 'text-red-400' },
+ medium: { dot: 'bg-yellow-500', text: 'text-yellow-400' },
+ low: { dot: 'bg-blue-500', text: 'text-blue-400' },
+} as const;
+
+const OWNER_OPTIONS: { value: QueueOwner; label: string }[] = [
+ { value: 'me', label: 'Mine' },
+ { value: 'unassigned', label: 'Unassigned' },
+ { value: 'all', label: 'All' },
+];
+
+const PERIOD_OPTIONS: { value: QueuePeriod; label: string }[] = [
+ { value: '24h', label: '24h' },
+ { value: '7d', label: '7d' },
+ { value: '30d', label: '30d' },
+ { value: 'all', label: 'All' },
+];
+
+// Snooze presets cover the realistic "I'll get back to this" windows an analyst
+// uses during triage. Longer windows (days/weeks) should go through a proper
+// suppression rule, not a single-alert snooze.
+const SNOOZE_PRESETS: { label: string; minutes: number }[] = [
+ { label: '15m', minutes: 15 },
+ { label: '1h', minutes: 60 },
+ { label: '4h', minutes: 240 },
+ { label: '24h', minutes: 1440 },
+];
+
+const PAGE_SIZE = 50;
+
+// ─── Helpers ──────────────────────────────────────────────────────────────────
+
+/**
+ * Re-render every second so per-row SLA countdowns stay accurate without
+ * round-tripping to the server on every tick.
+ *
+ * The hook returns a numeric "tick" so callers can use it as a dependency, but
+ * most callers only need the side-effect of forcing a re-render.
+ */
+function useSecondTick(enabled: boolean): number {
+ const [tick, setTick] = useState(0);
+ useEffect(() => {
+ if (!enabled) return;
+ const id = setInterval(() => setTick((t) => t + 1), 1000);
+ return () => clearInterval(id);
+ }, [enabled]);
+ return tick;
+}
+
+/**
+ * Render a remaining-seconds value as a compact "1h 12m" or "23m 04s" string.
+ * Negative values mean "breached" and are formatted as "-1h 12m".
+ */
+function formatRemaining(seconds: number): string {
+ const negative = seconds < 0;
+ const abs = Math.abs(Math.round(seconds));
+ const h = Math.floor(abs / 3600);
+ const m = Math.floor((abs % 3600) / 60);
+ const s = abs % 60;
+ const sign = negative ? '-' : '';
+ if (h > 0) return `${sign}${h}h ${String(m).padStart(2, '0')}m`;
+ if (m > 0) return `${sign}${m}m ${String(s).padStart(2, '0')}s`;
+ return `${sign}${s}s`;
+}
+
+/**
+ * Compute remaining-seconds against the server's authoritative clock so the
+ * countdown the analyst sees matches the deadline the SLA engine enforces.
+ *
+ * The math: `generated_at` is the server's wall-clock at the moment the queue
+ * response was assembled. The client treats that moment as "T=0 for this
+ * payload" and ticks down based on real elapsed time since then. This nudges
+ * out client/server clock skew bigger than the page refresh interval.
+ */
+function computeRemainingSeconds(item: QueueItem, generatedAt: string): number {
+ const generatedMs = new Date(generatedAt).getTime();
+ const elapsedSec = (Date.now() - generatedMs) / 1000;
+ return item.sla_remaining_seconds - elapsedSec;
+}
+
+/**
+ * Map a remaining-seconds value to a colour state used by the SLA pill.
+ *
+ * The 10-minute amber threshold matches the operations spec — anything inside
+ * the last 10 minutes of an SLA is "act now" territory, regardless of severity.
+ */
+function slaState(remainingSec: number): 'ok' | 'warn' | 'breached' {
+ if (remainingSec < 0) return 'breached';
+ if (remainingSec < 600) return 'warn';
+ return 'ok';
+}
+
+// ─── Sub-components ───────────────────────────────────────────────────────────
+
+function SeverityBadge({ severity }: { severity: AlertSeverity }) {
+ const cfg = SEVERITY_CONFIG[severity] ?? SEVERITY_CONFIG.info;
+ return (
+ <span className={clsx('inline-flex items-center gap-1 text-[10px] font-mono font-semibold px-1.5 py-0.5 rounded border', cfg.text, cfg.bg)}>
+ <span className={clsx('w-1.5 h-1.5 rounded-full', cfg.dot)} />
+ {cfg.label}
+ </span>
+ );
+}
+
+function OwnerToggle({
+ value,
+ counts,
+ onChange,
+}: {
+ value: QueueOwner;
+ counts: QueueResponse['counts'] | null;
+ onChange: (next: QueueOwner) => void;
+}) {
+ return (
+ <div
+ role="tablist"
+ aria-label="Queue owner filter"
+ className="inline-flex items-center bg-gray-900/60 border border-gray-800/60 rounded-lg p-0.5"
+ >
+ {OWNER_OPTIONS.map((opt) => {
+ const active = value === opt.value;
+ const count =
+ counts == null
+ ? null
+ : opt.value === 'me'
+ ? counts.mine
+ : opt.value === 'unassigned'
+ ? counts.unassigned
+ : counts.all;
+ return (
+ <button
+ key={opt.value}
+ type="button"
+ role="tab"
+ aria-selected={active}
+ onClick={() => onChange(opt.value)}
+ className={clsx(
+ 'text-xs px-3 py-1.5 rounded-md transition-colors flex items-center gap-1.5',
+ active ? 'bg-blue-600 text-white' : 'text-gray-400 hover:text-gray-200',
+ )}
+ >
+ {opt.label}
+ {count != null && (
+ <span
+ aria-live="polite"
+ className={clsx(
+ 'text-[10px] font-mono px-1.5 py-px rounded-full',
+ active ? 'bg-white/15 text-white' : 'bg-gray-800 text-gray-400',
+ )}
+ >
+ {count > 99 ? '99+' : count}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+function PeriodFilter({
+ value,
+ onChange,
+}: {
+ value: QueuePeriod;
+ onChange: (next: QueuePeriod) => void;
+}) {
+ return (
+ <div className="inline-flex items-center bg-gray-900/40 border border-gray-800/60 rounded-lg p-0.5">
+ {PERIOD_OPTIONS.map((opt) => (
+ <button
+ key={opt.value}
+ type="button"
+ onClick={() => onChange(opt.value)}
+ aria-pressed={value === opt.value}
+ className={clsx(
+ 'text-xs px-2.5 py-1 rounded-md transition-colors',
+ value === opt.value
+ ? 'bg-gray-700 text-gray-100'
+ : 'text-gray-500 hover:text-gray-300',
+ )}
+ >
+ {opt.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function SlaCountdown({
+ item,
+ generatedAt,
+}: {
+ item: QueueItem;
+ generatedAt: string;
+}) {
+ // Re-evaluate on every render — the parent ticks once per second via
+ // `useSecondTick`, so this picks up wall-clock drift automatically.
+ const remaining = computeRemainingSeconds(item, generatedAt);
+ const state = slaState(remaining);
+ const cls =
+ state === 'breached'
+ ? 'text-red-400 bg-red-500/10 border-red-500/30'
+ : state === 'warn'
+ ? 'text-amber-400 bg-amber-500/10 border-amber-500/30'
+ : 'text-emerald-400 bg-emerald-500/10 border-emerald-500/30';
+ return (
+ <span
+ className={clsx(
+ 'inline-flex items-center gap-1 text-[10px] font-mono px-2 py-0.5 rounded border',
+ cls,
+ )}
+ title={`SLA due ${new Date(item.sla_due_at).toLocaleString()}`}
+ // Help screen readers read this as a live timer.
+ aria-live="off"
+ >
+ {state === 'breached' && (
+ <span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" aria-hidden />
+ )}
+ SLA {formatRemaining(remaining)}
+ </span>
+ );
+}
+
+function SuggestedActionBadge({ item }: { item: QueueItem }) {
+ if (!item.suggested_action) return null;
+ const cfg = RISK_CONFIG[item.suggested_action.risk];
+ return (
+ <span
+ className="inline-flex items-center gap-1 text-[10px] text-gray-400 bg-gray-800/60 border border-gray-700/60 px-1.5 py-0.5 rounded"
+ title={`Suggested next action (risk: ${item.suggested_action.risk})`}
+ >
+ <span className={clsx('w-1.5 h-1.5 rounded-full', cfg.dot)} aria-hidden />
+ <span className="truncate max-w-[14rem]">→ {item.suggested_action.action}</span>
+ </span>
+ );
+}
+
+function BucketBadge({ bucket }: { bucket: 'mine' | 'unassigned' }) {
+ if (bucket === 'mine') {
+ return (
+ <span className="text-[10px] font-medium text-blue-300 bg-blue-500/10 border border-blue-500/20 px-1.5 py-0.5 rounded">
+ Mine
+ </span>
+ );
+ }
+ return (
+ <span className="text-[10px] font-medium text-gray-400 bg-gray-700/40 border border-gray-700/60 px-1.5 py-0.5 rounded">
+ Unassigned
+ </span>
+ );
+}
+
+function QueueRowActions({
+ item,
+ isMine,
+ busyAction,
+ onClaim,
+ onRelease,
+ onSnooze,
+}: {
+ item: QueueItem;
+ isMine: boolean;
+ busyAction: 'claim' | 'release' | 'snooze' | null;
+ onClaim: (id: string) => void;
+ onRelease: (id: string) => void;
+ onSnooze: (id: string, minutes: number) => void;
+}) {
+ // <details>-based dropdown gives us zero-dep, keyboard-accessible disclosure
+ // without pulling a popover library. Clicking outside closes via the native
+ // toggle; we additionally close after picking a duration.
+ const detailsRef = useRef<HTMLDetailsElement>(null);
+ const closeSnoozeMenu = () => {
+ if (detailsRef.current) detailsRef.current.open = false;
+ };
+
+ const claimable = !isMine && !item.assigned_to_id;
+ const releasable = isMine;
+
+ return (
+ <div className="flex items-center gap-1.5 shrink-0">
+ {claimable && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onClaim(item.id);
+ }}
+ disabled={busyAction === 'claim'}
+ className="text-[11px] font-medium px-2 py-1 rounded border border-blue-500/40 bg-blue-500/10 text-blue-300 hover:bg-blue-500/20 hover:border-blue-500/60 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {busyAction === 'claim' ? 'Claiming…' : 'Claim'}
+ </button>
+ )}
+
+ {releasable && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onRelease(item.id);
+ }}
+ disabled={busyAction === 'release'}
+ className="text-[11px] font-medium px-2 py-1 rounded border border-gray-700/60 text-gray-300 hover:bg-gray-800/60 hover:border-gray-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {busyAction === 'release' ? 'Releasing…' : 'Release'}
+ </button>
+ )}
+
+ <details ref={detailsRef} className="relative">
+ <summary
+ onClick={(e) => {
+ // Suppress the parent <Link> navigation. We can't use
+ // preventDefault on summary directly (it cancels the toggle), so
+ // we stop propagation only and let the native disclosure run.
+ e.stopPropagation();
+ }}
+ className="list-none cursor-pointer text-[11px] font-medium px-2 py-1 rounded border border-gray-700/60 text-gray-300 hover:bg-gray-800/60 hover:border-gray-600 transition-colors select-none"
+ aria-label="Snooze options"
+ >
+ {busyAction === 'snooze' ? 'Snoozing…' : 'Snooze'}
+ </summary>
+ <div
+ role="menu"
+ className="absolute right-0 top-full mt-1 z-20 flex flex-col bg-gray-900 border border-gray-800 rounded-lg shadow-xl p-1 min-w-[8rem]"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ >
+ <span className="text-[10px] uppercase tracking-wider text-gray-500 px-2 py-1">
+ Snooze for
+ </span>
+ {SNOOZE_PRESETS.map((preset) => (
+ <button
+ key={preset.minutes}
+ type="button"
+ role="menuitem"
+ onClick={() => {
+ onSnooze(item.id, preset.minutes);
+ closeSnoozeMenu();
+ }}
+ className="text-left text-xs px-2 py-1 rounded text-gray-300 hover:bg-gray-800 hover:text-white transition-colors"
+ >
+ {preset.label}
+ </button>
+ ))}
+ </div>
+ </details>
+ </div>
+ );
+}
+
+interface QueueRowProps {
+ item: QueueItem;
+ generatedAt: string;
+ isMine: boolean;
+ busyAction: 'claim' | 'release' | 'snooze' | null;
+ onClaim: (id: string) => void;
+ onRelease: (id: string) => void;
+ onSnooze: (id: string, minutes: number) => void;
+}
+
+function QueueRow({ item, generatedAt, isMine, busyAction, onClaim, onRelease, onSnooze }: QueueRowProps) {
+ const remaining = computeRemainingSeconds(item, generatedAt);
+ const breached = remaining < 0;
+
+ return (
+ <Link
+ href={`/alerts/${item.id}`}
+ className={clsx(
+ 'group flex items-start gap-3 px-4 py-3 border-b border-gray-800/40 last:border-0 transition-colors',
+ breached
+ ? 'bg-red-950/20 hover:bg-red-950/30 border-l-2 border-l-red-500/60'
+ : 'hover:bg-gray-800/30',
+ )}
+ aria-label={`Investigate ${item.title}`}
+ >
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <SeverityBadge severity={item.severity} />
+ <BucketBadge bucket={item.bucket} />
+ <SlaCountdown item={item} generatedAt={generatedAt} />
+ {item.case_id && (
+ <span
+ className="text-[10px] text-violet-300 bg-violet-500/10 border border-violet-500/20 px-1.5 py-0.5 rounded"
+ title="Already linked to a case"
+ >
+ In case
+ </span>
+ )}
+ </div>
+
+ <p className="text-sm text-gray-200 mt-1 truncate group-hover:text-white">
+ {item.title}
+ </p>
+
+ <div className="flex items-center gap-2 mt-1 text-[11px] text-gray-500 flex-wrap">
+ {item.asset && (
+ <span className="font-mono text-gray-400" title={item.asset.kind}>
+ {item.asset.label ?? item.asset.value}
+ </span>
+ )}
+ {item.connector_type && (
+ <>
+ <span className="text-gray-700">·</span>
+ <span>{item.connector_type}</span>
+ </>
+ )}
+ {item.category && (
+ <>
+ <span className="text-gray-700">·</span>
+ <span>{item.category}</span>
+ </>
+ )}
+ <span className="text-gray-700">·</span>
+ <span>{formatRemaining(item.age_seconds)} old</span>
+ {item.suggested_action && (
+ <>
+ <span className="text-gray-700">·</span>
+ <SuggestedActionBadge item={item} />
+ </>
+ )}
+ </div>
+ </div>
+
+ <QueueRowActions
+ item={item}
+ isMine={isMine}
+ busyAction={busyAction}
+ onClaim={onClaim}
+ onRelease={onRelease}
+ onSnooze={onSnooze}
+ />
+ </Link>
+ );
+}
+
+function QueueSkeleton() {
+ return (
+ <div className="border border-gray-800/60 rounded-xl divide-y divide-gray-800/40 overflow-hidden">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <div key={i} className="flex items-start gap-3 px-4 py-3">
+ <div className="flex-1 min-w-0 space-y-2">
+ <div className="flex items-center gap-2">
+ <Skeleton className="w-12 h-4" />
+ <Skeleton className="w-16 h-4" />
+ <Skeleton className="w-20 h-4" />
+ </div>
+ <Skeleton className="w-3/4 h-4" />
+ <Skeleton className="w-1/2 h-3" />
+ </div>
+ <div className="flex items-center gap-2">
+ <Skeleton className="w-14 h-7" />
+ <Skeleton className="w-16 h-7" />
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// ─── Main View ────────────────────────────────────────────────────────────────
+
+export function QueueView() {
+ const [owner, setOwner] = useState<QueueOwner>('me');
+ const [period, setPeriod] = useState<QueuePeriod>('all');
+ const [page, setPage] = useState(1);
+ // Map of alert ids to "we have an in-flight mutation against this row" so we
+ // can disable per-row buttons without blocking the whole table.
+ const [busyMap, setBusyMap] = useState<Record<string, 'claim' | 'release' | 'snooze'>>({});
+
+ // The current user's id powers the "is this row mine?" check and the
+ // sidebar's live counts.
+ const currentUserId = useMemo(() => authApi.currentUser()?.id ?? null, []);
+
+ const { data, error, isLoading, mutate } = useSWR<QueueResponse>(
+ ['queue', owner, period, page],
+ () => queueApi.list({ owner, period, page, page_size: PAGE_SIZE }),
+ {
+ // 15-second polling keeps the queue fresh without hammering the API.
+ // Inter-fetch drift is absorbed by the per-row countdown ticker.
+ refreshInterval: 15000,
+ keepPreviousData: true,
+ },
+ );
+
+ // Tick once a second so SLA pills decrement live between fetches. We only
+ // tick when there are rows on screen — saves a wasted setInterval on empty
+ // states and during the initial loading skeleton.
+ const items = data?.items ?? [];
+ useSecondTick(items.length > 0);
+
+ const setBusy = useCallback((id: string, action: 'claim' | 'release' | 'snooze' | null) => {
+ setBusyMap((prev) => {
+ const next = { ...prev };
+ if (action === null) delete next[id];
+ else next[id] = action;
+ return next;
+ });
+ }, []);
+
+ const handleClaim = useCallback(
+ async (alertId: string) => {
+ setBusy(alertId, 'claim');
+ try {
+ await queueApi.claim(alertId);
+ toast.success('Claimed — this alert is yours');
+ await mutate();
+ } catch (err) {
+ // Backend returns 409 if a teammate beat us to it. We surface that
+ // clearly rather than blanket-erroring, because it's the most common
+ // failure mode and an analyst needs to know the row is no longer free.
+ const message =
+ err instanceof Error && err.message.toLowerCase().includes('409')
+ ? 'Another responder claimed this alert first'
+ : err instanceof Error
+ ? err.message
+ : 'Failed to claim alert';
+ toast.error(message);
+ await mutate();
+ } finally {
+ setBusy(alertId, null);
+ }
+ },
+ [mutate, setBusy],
+ );
+
+ const handleRelease = useCallback(
+ async (alertId: string) => {
+ setBusy(alertId, 'release');
+ try {
+ await queueApi.assign(alertId, null);
+ toast.success('Released back to the unassigned pool');
+ await mutate();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : 'Failed to release alert';
+ toast.error(message);
+ } finally {
+ setBusy(alertId, null);
+ }
+ },
+ [mutate, setBusy],
+ );
+
+ const handleSnooze = useCallback(
+ async (alertId: string, minutes: number) => {
+ setBusy(alertId, 'snooze');
+ try {
+ await queueApi.snooze(alertId, { duration_minutes: minutes });
+ toast.success(`Snoozed for ${minutes < 60 ? `${minutes}m` : `${minutes / 60}h`}`);
+ await mutate();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : 'Failed to snooze alert';
+ toast.error(message);
+ } finally {
+ setBusy(alertId, null);
+ }
+ },
+ [mutate, setBusy],
+ );
+
+ const counts = data?.counts ?? null;
+ const generatedAt = data?.generated_at ?? new Date().toISOString();
+ const total = data?.total ?? 0;
+ const totalPages = data?.pages ?? 1;
+
+ // Loading state — only shows the skeleton on first paint. Subsequent
+ // re-fetches keep the previous data on screen (`keepPreviousData`) so the
+ // queue doesn't flicker every 15 seconds.
+ if (isLoading && !data) {
+ return (
+ <div className="space-y-4">
+ <Header
+ owner={owner}
+ period={period}
+ counts={null}
+ onOwnerChange={setOwner}
+ onPeriodChange={setPeriod}
+ />
+ <QueueSkeleton />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ <Header
+ owner={owner}
+ period={period}
+ counts={counts}
+ onOwnerChange={(next) => {
+ setOwner(next);
+ setPage(1);
+ }}
+ onPeriodChange={(next) => {
+ setPeriod(next);
+ setPage(1);
+ }}
+ />
+
+ {error && (
+ <ErrorState
+ title="Couldn't load the queue"
+ description="The backend didn't return queue data. Try again, or check the API logs if this keeps happening."
+ error={error}
+ onRetry={() => mutate()}
+ />
+ )}
+
+ {!error && items.length === 0 && (
+ <EmptyState
+ icon={EmptyStateIcons.alert}
+ title={
+ owner === 'me'
+ ? 'Nothing in your queue'
+ : owner === 'unassigned'
+ ? 'Nothing waiting to be claimed'
+ : 'Queue is clear'
+ }
+ description={
+ owner === 'me'
+ ? "Your team is on top of it. Switch to Unassigned to pick something up, or All to see the broader queue."
+ : owner === 'unassigned'
+ ? 'Every alert is assigned. Switch to Mine to keep working through your queue.'
+ : 'No alerts inside the current period. Widen the period filter to see older work.'
+ }
+ />
+ )}
+
+ {!error && items.length > 0 && (
+ <div className="border border-gray-800/60 rounded-xl divide-y divide-gray-800/40 overflow-hidden bg-gray-950/40">
+ {items.map((item) => (
+ <QueueRow
+ key={item.id}
+ item={item}
+ generatedAt={generatedAt}
+ isMine={Boolean(currentUserId) && item.assigned_to_id === currentUserId}
+ busyAction={busyMap[item.id] ?? null}
+ onClaim={handleClaim}
+ onRelease={handleRelease}
+ onSnooze={handleSnooze}
+ />
+ ))}
+ </div>
+ )}
+
+ {!error && totalPages > 1 && (
+ <Pagination
+ page={page}
+ totalPages={totalPages}
+ total={total}
+ pageSize={PAGE_SIZE}
+ onChange={setPage}
+ />
+ )}
+ </div>
+ );
+}
+
+// ─── Header + Pagination ──────────────────────────────────────────────────────
+
+function Header({
+ owner,
+ period,
+ counts,
+ onOwnerChange,
+ onPeriodChange,
+}: {
+ owner: QueueOwner;
+ period: QueuePeriod;
+ counts: QueueResponse['counts'] | null;
+ onOwnerChange: (next: QueueOwner) => void;
+ onPeriodChange: (next: QueuePeriod) => void;
+}) {
+ return (
+ <div className="flex items-end justify-between flex-wrap gap-3">
+ <div>
+ <h1 className="text-xl font-semibold text-gray-100">Investigation Queue</h1>
+ <p className="text-sm text-gray-500 mt-0.5">
+ Ranked by SLA pressure and severity — your next move, top of the list.
+ </p>
+ </div>
+ <div className="flex items-center gap-2 flex-wrap">
+ <OwnerToggle value={owner} counts={counts} onChange={onOwnerChange} />
+ <PeriodFilter value={period} onChange={onPeriodChange} />
+ </div>
+ </div>
+ );
+}
+
+function Pagination({
+ page,
+ totalPages,
+ total,
+ pageSize,
+ onChange,
+}: {
+ page: number;
+ totalPages: number;
+ total: number;
+ pageSize: number;
+ onChange: (page: number) => void;
+}) {
+ const start = (page - 1) * pageSize + 1;
+ const end = Math.min(page * pageSize, total);
+ return (
+ <div className="flex items-center justify-between text-xs text-gray-500 px-1">
+ <span>
+ Showing {start}–{end} of {total}
+ </span>
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ onClick={() => onChange(Math.max(1, page - 1))}
+ disabled={page <= 1}
+ className="px-2 py-1 rounded border border-gray-800 text-gray-400 hover:bg-gray-800/60 hover:text-gray-200 disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ ← Prev
+ </button>
+ <span className="px-2 text-gray-500">
+ Page {page} / {totalPages}
+ </span>
+ <button
+ type="button"
+ onClick={() => onChange(Math.min(totalPages, page + 1))}
+ disabled={page >= totalPages}
+ className="px-2 py-1 rounded border border-gray-800 text-gray-400 hover:bg-gray-800/60 hover:text-gray-200 disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ Next →
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index ae853b737..9d273dcd6 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -437,6 +437,147 @@ export const alertsApi = {
}),
};
+// ─── Investigation Queue (W7) ───────────────────────────────────────────────
+//
+// The Investigation Queue is the analyst's working surface: one ranked list
+// of "what should I work on next?" sourced from the canonical alerts table.
+// The backend computes a virtual ``sla_due_at`` per row (``first_seen +
+// mttd_target`` for the alert's severity) and orders the queue by
+//
+// 1. assignment bucket (mine before unassigned), and
+// 2. ``sla_due_at`` ascending within each bucket.
+//
+// Snoozed and closed alerts are excluded server-side. Unassigned ``medium``
+// and below are also excluded — those are triaged in bulk on /alerts, not
+// one-by-one on the queue. See ``services/api/app/services/alert_queue.py``
+// for the full contract.
+
+export type QueueOwner = 'me' | 'unassigned' | 'all';
+export type QueuePeriod = '24h' | '7d' | '30d' | 'all';
+export type QueueBucket = 'mine' | 'unassigned';
+export type QueueRisk = 'low' | 'medium' | 'high';
+
+export interface QueueAsset {
+ /** ``host`` | ``user`` | ``ip`` | ``asset`` — chosen by the backend. */
+ kind: string;
+ value: string;
+ label?: string | null;
+}
+
+export interface QueueAction {
+ /** 1-indexed priority; lower is more urgent. */
+ priority: number;
+ action: string;
+ risk: QueueRisk;
+}
+
+export interface QueueItem {
+ id: string;
+ tenant_id: string;
+ title: string;
+ severity: AlertSeverity;
+ status: AlertStatus;
+ priority: number;
+ category?: string | null;
+ connector_type?: string | null;
+
+ assigned_to_id?: string | null;
+ case_id?: string | null;
+
+ first_seen: string;
+ sla_due_at: string;
+ /** Seconds until ``sla_due_at`` — negative once breached. */
+ sla_remaining_seconds: number;
+ sla_breached: boolean;
+ age_seconds: number;
+
+ asset?: QueueAsset | null;
+ suggested_action?: QueueAction | null;
+
+ bucket: QueueBucket;
+}
+
+export interface QueueCounts {
+ mine: number;
+ unassigned: number;
+ all: number;
+}
+
+export interface QueueResponse {
+ items: QueueItem[];
+ total: number;
+ counts: QueueCounts;
+ period: QueuePeriod;
+ owner: QueueOwner;
+ page: number;
+ page_size: number;
+ pages: number;
+ /** Server's authoritative ``now`` — the UI drifts its countdowns from this. */
+ generated_at: string;
+}
+
+export interface QueueFilters {
+ owner?: QueueOwner;
+ period?: QueuePeriod;
+ page?: number;
+ page_size?: number;
+}
+
+export const queueApi = {
+ /**
+ * Fetch the Investigation Queue.
+ *
+ * Returns up to ``page_size`` items (capped server-side at 200) plus
+ * the live ``counts`` for all buckets — that's what the sidebar badge
+ * polls. The endpoint is cheap because the server only projects the
+ * columns the queue actually renders; do *not* fan out to ``alertsApi.get``
+ * for every row.
+ */
+ list: (filters: QueueFilters = {}) =>
+ request<QueueResponse>('/api/v1/alerts/queue', {
+ params: filters as Record<string, string | number>,
+ }),
+
+ /**
+ * Atomically claim an unassigned alert for the current user.
+ *
+ * Returns ``409`` if another analyst grabbed the row first — the UI
+ * should surface that as "claimed by Sam · refresh" rather than a
+ * generic error. Idempotent if the caller already owns the alert.
+ */
+ claim: (alertId: string) =>
+ request<Alert>(`/api/v1/alerts/${alertId}/claim`, {
+ method: 'POST',
+ }),
+
+ /**
+ * Reassign or unassign an alert. Pass ``assignee = null`` to release.
+ *
+ * Reuses the existing ``PATCH /alerts/{id}`` endpoint — the server
+ * already accepts ``assignee`` updates. We add a thin wrapper here so
+ * the queue view doesn't have to re-derive the URL.
+ */
+ assign: (alertId: string, assignee: string | null) =>
+ request<Alert>(`/api/v1/alerts/${alertId}`, {
+ method: 'PATCH',
+ body: JSON.stringify({ assignee }),
+ }),
+
+ /**
+ * Snooze an alert for ``duration_minutes`` (1 → 43200 / 30d) or until
+ * a specific timestamp. The alert re-enters the queue automatically
+ * once ``snoozed_until`` passes.
+ */
+ snooze: (
+ alertId: string,
+ body: { duration_minutes?: number; until?: string; reason?: string },
+ ) =>
+ request<Alert>(`/api/v1/alerts/${alertId}/snooze`, {
+ method: 'POST',
+ body: JSON.stringify(body),
+ }),
+};
+
// ─── Risk-Based Alerting (entity rollup) ─────────────────────────────────────
//
// Wave 1 of the AiSOC v6 capability roadmap: alerts contribute time-decayed
diff --git a/services/api/app/api/v1/endpoints/alerts.py b/services/api/app/api/v1/endpoints/alerts.py
index 4021de004..f7f777e6b 100644
--- a/services/api/app/api/v1/endpoints/alerts.py
+++ b/services/api/app/api/v1/endpoints/alerts.py
@@ -2,7 +2,7 @@
import uuid
from datetime import UTC, datetime
-from typing import Annotated
+from typing import Annotated, Literal
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel
@@ -11,6 +11,13 @@ from sqlalchemy import and_, func, select, update
from app.api.v1.deps import AuthUser, DBSession, require_permission
from app.db.rls import TenantDBSession
from app.models.alert import Alert
+from app.services.alert_queue import (
+ AlertAlreadyClaimedError,
+ AlertNotFoundError,
+ QueueResponse,
+ build_queue,
+ claim_alert,
+)
router = APIRouter(prefix="/alerts", tags=["alerts"])
@@ -165,6 +172,40 @@ async def get_alert_stats(
)
+# NOTE: `/queue` is defined here — *before* `/{alert_id}` — on purpose.
+# FastAPI matches routes top-down, so a static path must precede the
+# parametric path of the same depth or the framework will route
+# `GET /alerts/queue` into `get_alert(alert_id="queue")` and 422.
[email protected]("/queue", response_model=QueueResponse)
+async def get_alert_queue(
+ current_user: Annotated[AuthUser, Depends(require_permission("alerts:read"))],
+ db: TenantDBSession,
+ owner: Literal["me", "unassigned", "all"] = Query(default="all"),
+ period: Literal["24h", "7d", "30d", "all"] = Query(default="all"),
+ page: int = Query(default=1, ge=1),
+ page_size: int = Query(default=50, ge=1, le=200),
+) -> QueueResponse:
+ """Investigation Queue workbench feed.
+
+ Returns the prioritised list of alerts the analyst should work on
+ next: alerts assigned to them, followed by unassigned
+ critical/high alerts, ordered by SLA due time.
+
+ The endpoint also returns ``counts`` for both buckets unconditionally
+ so the topbar badge and the workbench tabs can render without an
+ extra round-trip.
+ """
+ return await build_queue(
+ db,
+ tenant_id=current_user.tenant_id,
+ user_id=current_user.user_id,
+ owner=owner,
+ period=period,
+ page=page,
+ page_size=page_size,
+ )
+
+
@router.get("/{alert_id}", response_model=AlertResponse)
async def get_alert(
alert_id: uuid.UUID,
@@ -240,6 +281,33 @@ async def escalate_alert(
return AlertResponse.model_validate(alert)
[email protected]("/{alert_id}/claim", response_model=AlertResponse)
+async def claim_alert_endpoint(
+ alert_id: uuid.UUID,
+ current_user: Annotated[AuthUser, Depends(require_permission("alerts:write"))],
+ db: TenantDBSession,
+) -> AlertResponse:
+ """Atomically claim an unassigned alert for the current user.
+
+ Returns ``409 Conflict`` if the alert is already assigned to someone
+ else — the claim is a compare-and-set on ``assigned_to_id``, so two
+ analysts racing for the same alert never both win.
+ """
+ try:
+ alert = await claim_alert(
+ db,
+ alert_id=alert_id,
+ tenant_id=current_user.tenant_id,
+ user_id=current_user.user_id,
+ )
+ except AlertNotFoundError as exc:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
+ except AlertAlreadyClaimedError as exc:
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
+
+ return AlertResponse.model_validate(alert)
+
+
@router.post("/{alert_id}/snooze", response_model=AlertResponse)
async def snooze_alert(
alert_id: uuid.UUID,
diff --git a/services/api/app/services/alert_queue.py b/services/api/app/services/alert_queue.py
new file mode 100644
index 000000000..1f4ec98d1
--- /dev/null
+++ b/services/api/app/services/alert_queue.py
@@ -0,0 +1,520 @@
+"""Investigation queue workbench backend.
+
+This module powers the ``/queue`` workbench in the AiSOC console — a
+fixed-priority list of alerts an analyst should be working *right
+now*. The ordering rule is deliberately opinionated and mirrors what
+shift-leads on a live SOC floor would draw on the whiteboard:
+
+1. Alerts assigned to the current user first, oldest SLA first.
+2. Unassigned alerts at severity ``critical`` or ``high``, oldest SLA
+ first.
+
+Unassigned ``low`` / ``medium`` / ``info`` alerts are deliberately
+omitted from the queue. Those are triaged in bulk on ``/alerts``;
+paging through them one-by-one on the queue is a documented
+anti-pattern of legacy SOC tools we are deliberately *not* reproducing.
+
+The queue is computed against a *virtual* ``sla_due_at`` column —
+``Alert.first_seen + mttd_target`` for the alert's severity. We avoid
+materialising the column on every row because the SLA target is a
+tenant-configurable knob (see ``tenant_sla_config``); computing it
+at query time keeps the alerts schema invariant when targets are
+re-tuned. The expression we generate is plain SQL ``CASE`` on
+severity, so PostgreSQL can index-walk over ``alerts.first_seen``
+and apply the offset cheaply.
+
+AiSOC — open-source AI Security Operations Center (MIT License)
+Author: Beenu Arora <[email protected]>
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime, timedelta
+from typing import Literal
+
+from pydantic import BaseModel, Field
+from sqlalchemy import and_, case, func, literal, or_, select, update
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.alert import Alert
+from app.models.sla import TenantSLAConfig
+from app.services.sla import DEFAULT_SLA_TARGETS
+
+# Severities that show up in the *unassigned* bucket of the queue.
+# Low-priority alerts should be triaged in bulk on ``/alerts``; we
+# don't want analysts paging through low-noise findings one-by-one.
+QUEUE_UNASSIGNED_SEVERITIES: tuple[str, ...] = ("critical", "high")
+
+# Alert statuses that *exit* the queue. Anything in this set is
+# considered done — claim/snooze/assign must not return it to the
+# queue, and the queue endpoint hides it.
+QUEUE_CLOSED_STATUSES: tuple[str, ...] = (
+ "resolved",
+ "closed",
+ "false_positive",
+ "fp",
+)
+
+# Maximum page size for the queue endpoint. The workbench paginates
+# locally; this cap exists to keep one bad client from yanking
+# tens of thousands of rows at once.
+QUEUE_MAX_PAGE_SIZE: int = 200
+
+
+# ─── Type aliases for query params ──────────────────────────────────────
+
+
+Owner = Literal["me", "unassigned", "all"]
+Period = Literal["24h", "7d", "30d", "all"]
+
+PERIOD_TO_TIMEDELTA: dict[str, timedelta | None] = {
+ "24h": timedelta(hours=24),
+ "7d": timedelta(days=7),
+ "30d": timedelta(days=30),
+ "all": None,
+}
+
+
+# ─── Pydantic response shapes ───────────────────────────────────────────
+
+
+class QueueAsset(BaseModel):
+ """Lightweight asset descriptor for a queue row.
+
+ The queue surfaces *one* representative entity per alert so the
+ row is informative at a glance ("VPN brute force on `web-01`")
+ without enumerating every entity. The full pivotable list lives
+ on the Investigation Rail when the analyst opens the alert.
+ """
+
+ kind: str = Field(description="host | user | ip | asset")
+ value: str
+ label: str | None = None
+
+
+class QueueAction(BaseModel):
+ """Top suggested next action for a queue row.
+
+ Sourced from ``Alert.ai_recommendations``. The lowest-priority
+ integer wins (1 = most urgent). String-only legacy values are
+ accepted and mapped to ``risk="low"`` with the array index as a
+ fallback priority.
+ """
+
+ priority: int
+ action: str
+ risk: str = "low"
+
+
+class QueueItem(BaseModel):
+ """One row in the Investigation Queue workbench.
+
+ Intentionally slimmer than ``AlertResponse``. The queue exists to
+ answer "what should I work on next?" — clicking a row navigates
+ to ``/alerts/{id}`` which loads full detail via the existing
+ detail endpoint (``GET /alerts/{id}``). Keeping this payload
+ small means a busy SOC with thousands of open alerts can refresh
+ the queue cheaply (the badge on the topbar polls it).
+ """
+
+ id: uuid.UUID
+ tenant_id: uuid.UUID
+ title: str
+ severity: str
+ status: str
+ priority: int
+ category: str | None = None
+ connector_type: str | None = None
+
+ assigned_to_id: uuid.UUID | None = None
+ case_id: uuid.UUID | None = None
+
+ first_seen: datetime
+ sla_due_at: datetime
+ # Seconds until ``sla_due_at``. Negative once the SLA is breached;
+ # the frontend uses the sign to flip the timer to red.
+ sla_remaining_seconds: int
+ sla_breached: bool
+
+ # Seconds since ``first_seen``. Cheaper for the UI to render
+ # than a relative-time library re-parsing dates on every tick.
+ age_seconds: int
+
+ asset: QueueAsset | None = None
+ suggested_action: QueueAction | None = None
+
+ bucket: Literal["mine", "unassigned"]
+
+
+class QueueResponse(BaseModel):
+ """Paginated queue response.
+
+ ``counts`` always reports both buckets so the workbench can
+ render the "mine / unassigned / all" tabs without re-fetching.
+ ``generated_at`` is the server-side ``now`` we used to compute
+ SLA remaining — the frontend can drift its own clock from this
+ so multiple analysts on different boxes see the same countdowns.
+ """
+
+ items: list[QueueItem]
+ total: int
+ counts: dict[str, int]
+ period: str
+ owner: str
+ page: int
+ page_size: int
+ pages: int
+ generated_at: datetime
+
+
+# ─── Errors ─────────────────────────────────────────────────────────────
+
+
+class AlertNotFoundError(LookupError):
+ """The requested alert does not exist for this tenant."""
+
+
+class AlertAlreadyClaimedError(RuntimeError):
+ """Another analyst already owns this alert."""
+
+ def __init__(self, alert_id: uuid.UUID, owner_id: uuid.UUID) -> None:
+ super().__init__(f"alert {alert_id} already claimed by {owner_id}")
+ self.alert_id = alert_id
+ self.owner_id = owner_id
+
+
+# ─── SLA target resolution ──────────────────────────────────────────────
+
+
+async def load_sla_targets(
+ db: AsyncSession,
+ tenant_id: uuid.UUID,
+) -> dict[str, int]:
+ """Return a ``{severity → mttd_target_minutes}`` mapping for the tenant.
+
+ Per-tenant overrides in ``tenant_sla_config`` win; severities not
+ overridden fall back to ``DEFAULT_SLA_TARGETS``. We only need
+ ``mttd_target`` here because the queue's SLA timer is MTTD
+ (time-to-acknowledge). MTTR and MTTC live on cases / SLA reports.
+ """
+ result: dict[str, int] = {
+ sev: cfg["mttd_target"] for sev, cfg in DEFAULT_SLA_TARGETS.items()
+ }
+ rows = await db.execute(
+ select(TenantSLAConfig).where(TenantSLAConfig.tenant_id == tenant_id)
+ )
+ for cfg in rows.scalars().all():
+ if cfg.severity in result:
+ result[cfg.severity] = cfg.mttd_target
+ return result
+
+
+def sla_due_at_expression(targets: dict[str, int]):
+ """SQL expression for the virtual ``sla_due_at`` column.
+
+ Materialises ``Alert.first_seen + mttd_target`` as a ``CASE`` on
+ severity. Returns a SQLAlchemy ``ColumnElement`` suitable for
+ use in both ``select`` and ``order_by``. The fallback uses the
+ ``info`` target so brand-new or unknown severities still produce
+ a sortable value rather than ``NULL``.
+ """
+ branches = [
+ (Alert.severity == sev, Alert.first_seen + literal(timedelta(minutes=mins)))
+ for sev, mins in targets.items()
+ ]
+ fallback = Alert.first_seen + literal(
+ timedelta(minutes=DEFAULT_SLA_TARGETS["info"]["mttd_target"])
+ )
+ return case(*branches, else_=fallback)
+
+
+# ─── Asset / action projection ──────────────────────────────────────────
+
+
+def first_asset(alert: Alert) -> QueueAsset | None:
+ """Pick the single most useful pivot for a queue row.
+
+ Priority order: ``host → user → asset → ip``. This isn't the
+ place to enumerate every entity — that's what the Investigation
+ Rail (W6) is for. We surface one anchor so the row is meaningful
+ at a glance.
+ """
+ hosts = [
+ h for h in (alert.affected_hosts or []) if isinstance(h, str) and h.strip()
+ ]
+ if hosts:
+ return QueueAsset(kind="host", value=hosts[0].strip())
+ users = [
+ u for u in (alert.affected_users or []) if isinstance(u, str) and u.strip()
+ ]
+ if users:
+ return QueueAsset(kind="user", value=users[0].strip())
+ assets = [
+ a for a in (alert.affected_assets or []) if isinstance(a, str) and a.strip()
+ ]
+ if assets:
+ return QueueAsset(kind="asset", value=assets[0].strip())
+ ips = [
+ i for i in (alert.affected_ips or []) if isinstance(i, str) and i.strip()
+ ]
+ if ips:
+ return QueueAsset(kind="ip", value=ips[0].strip())
+ return None
+
+
+def first_action(alert: Alert) -> QueueAction | None:
+ """Pick the top suggested next action.
+
+ ``Alert.ai_recommendations`` is written by the ResponderAgent at
+ investigation close. Older rows wrote bare strings; modern rows
+ write structured dicts. We accept both shapes. The action with
+ the lowest ``priority`` wins (1 = most urgent); ties break by
+ array order.
+ """
+ raw = alert.ai_recommendations
+ if not isinstance(raw, list) or not raw:
+ return None
+
+ candidates: list[QueueAction] = []
+ for idx, item in enumerate(raw):
+ if isinstance(item, str):
+ text = item.strip()
+ if not text:
+ continue
+ candidates.append(QueueAction(priority=idx + 1, action=text))
+ elif isinstance(item, dict):
+ action = str(item.get("action") or "").strip()
+ if not action:
+ continue
+ try:
+ priority = max(1, int(item.get("priority", idx + 1)))
+ except (TypeError, ValueError):
+ priority = idx + 1
+ risk = str(item.get("risk") or "low").lower()
+ if risk not in {"low", "medium", "high"}:
+ risk = "low"
+ candidates.append(
+ QueueAction(priority=priority, action=action, risk=risk)
+ )
+
+ if not candidates:
+ return None
+ candidates.sort(key=lambda c: c.priority)
+ return candidates[0]
+
+
+# ─── Queue assembly ─────────────────────────────────────────────────────
+
+
+async def build_queue(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ user_id: uuid.UUID,
+ owner: Owner = "all",
+ period: Period = "all",
+ page: int = 1,
+ page_size: int = 50,
+) -> QueueResponse:
+ """Assemble queue rows for the given owner / period.
+
+ The returned ``items`` are always pre-sorted:
+ * bucket 0 (assigned to me) before bucket 1 (unassigned),
+ * within each bucket: ``sla_due_at`` ascending,
+ * tiebreaker: severity descending (critical > high > …).
+
+ ``counts`` is always populated for *all* buckets regardless of
+ the ``owner`` filter, so the workbench tabs render correctly.
+ """
+ page_size = max(1, min(page_size, QUEUE_MAX_PAGE_SIZE))
+ page = max(1, page)
+
+ now = datetime.now(UTC)
+ period_delta = PERIOD_TO_TIMEDELTA.get(period)
+
+ targets = await load_sla_targets(db, tenant_id)
+ sla_expr = sla_due_at_expression(targets)
+
+ base_filters = [
+ Alert.tenant_id == tenant_id,
+ Alert.status.notin_(QUEUE_CLOSED_STATUSES),
+ or_(Alert.snoozed_until.is_(None), Alert.snoozed_until <= now),
+ ]
+ if period_delta is not None:
+ base_filters.append(Alert.first_seen >= (now - period_delta))
+
+ mine_filter = and_(*base_filters, Alert.assigned_to_id == user_id)
+ unassigned_filter = and_(
+ *base_filters,
+ Alert.assigned_to_id.is_(None),
+ Alert.severity.in_(QUEUE_UNASSIGNED_SEVERITIES),
+ )
+
+ # Counts: always report both buckets so the topbar badge + tabs
+ # work without re-fetching.
+ mine_count = (
+ await db.execute(select(func.count()).select_from(Alert).where(mine_filter))
+ ).scalar_one()
+ unassigned_count = (
+ await db.execute(
+ select(func.count()).select_from(Alert).where(unassigned_filter)
+ )
+ ).scalar_one()
+
+ # Bucket label: mine (0) sorts before unassigned (1).
+ bucket_expr = case(
+ (Alert.assigned_to_id == user_id, literal(0)),
+ else_=literal(1),
+ )
+
+ # Severity rank for the tiebreaker: critical > high > medium > …
+ severity_rank = case(
+ (Alert.severity == "critical", literal(0)),
+ (Alert.severity == "high", literal(1)),
+ (Alert.severity == "medium", literal(2)),
+ (Alert.severity == "low", literal(3)),
+ else_=literal(4),
+ )
+
+ if owner == "me":
+ where_clause = mine_filter
+ total = mine_count
+ elif owner == "unassigned":
+ where_clause = unassigned_filter
+ total = unassigned_count
+ else: # all
+ where_clause = or_(mine_filter, unassigned_filter)
+ total = mine_count + unassigned_count
+
+ offset = (page - 1) * page_size
+ rows = (
+ await db.execute(
+ select(Alert, bucket_expr.label("_bucket"), sla_expr.label("_sla_due"))
+ .where(where_clause)
+ .order_by(bucket_expr.asc(), sla_expr.asc(), severity_rank.asc())
+ .offset(offset)
+ .limit(page_size)
+ )
+ ).all()
+
+ items: list[QueueItem] = []
+ for row in rows:
+ alert: Alert = row[0]
+ bucket_idx: int = int(row[1])
+ sla_due_at: datetime = row[2]
+ if sla_due_at.tzinfo is None:
+ sla_due_at = sla_due_at.replace(tzinfo=UTC)
+ remaining = int((sla_due_at - now).total_seconds())
+
+ first_seen = alert.first_seen
+ if first_seen.tzinfo is None:
+ first_seen = first_seen.replace(tzinfo=UTC)
+ age = int((now - first_seen).total_seconds())
+
+ items.append(
+ QueueItem(
+ id=alert.id,
+ tenant_id=alert.tenant_id,
+ title=alert.title,
+ severity=alert.severity,
+ status=alert.status,
+ priority=alert.priority,
+ category=alert.category,
+ connector_type=alert.connector_type,
+ assigned_to_id=alert.assigned_to_id,
+ case_id=alert.case_id,
+ first_seen=first_seen,
+ sla_due_at=sla_due_at,
+ sla_remaining_seconds=remaining,
+ sla_breached=remaining < 0,
+ age_seconds=max(0, age),
+ asset=first_asset(alert),
+ suggested_action=first_action(alert),
+ bucket="mine" if bucket_idx == 0 else "unassigned",
+ )
+ )
+
+ pages = (total + page_size - 1) // page_size if total else 0
+ return QueueResponse(
+ items=items,
+ total=total,
+ counts={
+ "mine": mine_count,
+ "unassigned": unassigned_count,
+ "all": mine_count + unassigned_count,
+ },
+ period=period,
+ owner=owner,
+ page=page,
+ page_size=page_size,
+ pages=pages,
+ generated_at=now,
+ )
+
+
+# ─── Claim ──────────────────────────────────────────────────────────────
+
+
+async def claim_alert(
+ db: AsyncSession,
+ *,
+ alert_id: uuid.UUID,
+ tenant_id: uuid.UUID,
+ user_id: uuid.UUID,
+) -> Alert:
+ """Atomically claim an unassigned alert for the current user.
+
+ Behaviour:
+ * Unassigned → assign to me.
+ * Already assigned to me → no-op (idempotent — refreshing
+ the queue and re-clicking claim
+ must not 409).
+ * Assigned to someone else → ``AlertAlreadyClaimedError``.
+
+ The update is guarded with a ``WHERE assigned_to_id IS NULL``
+ clause so two analysts racing for the same row can't both win —
+ the second update is a no-op and we surface 409 to the loser.
+ """
+ result = await db.execute(
+ select(Alert).where(Alert.id == alert_id, Alert.tenant_id == tenant_id)
+ )
+ alert = result.scalar_one_or_none()
+ if alert is None:
+ raise AlertNotFoundError(str(alert_id))
+
+ if alert.assigned_to_id == user_id:
+ return alert # idempotent
+
+ if alert.assigned_to_id is not None:
+ raise AlertAlreadyClaimedError(
+ alert_id=alert_id,
+ owner_id=alert.assigned_to_id,
+ )
+
+ now = datetime.now(UTC)
+ update_result = await db.execute(
+ update(Alert)
+ .where(Alert.id == alert_id, Alert.assigned_to_id.is_(None))
+ .values(assigned_to_id=user_id, assigned_at=now, updated_at=now)
+ .returning(Alert.assigned_to_id)
+ )
+ winner = update_result.scalar_one_or_none()
+ if winner is None or winner != user_id:
+ # Someone else grabbed it between our SELECT and UPDATE.
+ # Re-read so the error carries the actual owner.
+ refresh = await db.execute(
+ select(Alert.assigned_to_id).where(Alert.id == alert_id)
+ )
+ actual_owner = refresh.scalar_one_or_none()
+ if actual_owner is None:
+ raise AlertNotFoundError(str(alert_id))
+ if actual_owner == user_id:
+ await db.commit()
+ await db.refresh(alert)
+ return alert
+ raise AlertAlreadyClaimedError(alert_id=alert_id, owner_id=actual_owner)
+
+ await db.commit()
+ await db.refresh(alert)
+ return alert
diff --git a/services/api/app/services/sla.py b/services/api/app/services/sla.py
index cbd0ccd20..1d923576f 100644
--- a/services/api/app/services/sla.py
+++ b/services/api/app/services/sla.py
@@ -28,6 +28,18 @@ DEFAULT_KPI_BAR_TARGETS: dict[str, float] = {
"mitre_subtechnique_tagging_min_pct": 60.0,
}
+# Default per-severity SLA targets (minutes) used as the fallback when a tenant
+# has not provided overrides via ``tenant_sla_config``. The queue's `sla_due_at`
+# expression also reads ``DEFAULT_SLA_TARGETS["info"]["mttd_target"]`` as a
+# catch-all for severities that fall outside the standard four-tier ladder.
+DEFAULT_SLA_TARGETS: dict[str, dict[str, int]] = {
+ "critical": {"mttd_target": 15, "mttr_target": 60, "mttc_target": 120},
+ "high": {"mttd_target": 30, "mttr_target": 120, "mttc_target": 240},
+ "medium": {"mttd_target": 60, "mttr_target": 240, "mttc_target": 480},
+ "low": {"mttd_target": 120, "mttr_target": 480, "mttc_target": 1440},
+ "info": {"mttd_target": 240, "mttr_target": 960, "mttc_target": 2880},
+}
+
def merge_kpi_bar_dict(existing: dict | None, patch: dict[str, float]) -> dict[str, float]:
"""Merge ``patch`` into stored ``kpi_bar`` and coerce to the four known keys + defaults."""
@@ -243,16 +255,10 @@ async def compute_sla_metrics(
buckets.setdefault(sev, []).append(d)
per_severity: dict[str, dict[str, Any]] = {}
- default_targets = {
- "critical": {"mttd_target": 15, "mttr_target": 60, "mttc_target": 120},
- "high": {"mttd_target": 30, "mttr_target": 120, "mttc_target": 240},
- "medium": {"mttd_target": 60, "mttr_target": 240, "mttc_target": 480},
- "low": {"mttd_target": 120, "mttr_target": 480, "mttc_target": 1440},
- }
for sev in ["critical", "high", "medium", "low"]:
items = buckets.get(sev, [])
- targets = configs.get(sev) or default_targets.get(sev, {})
+ targets = configs.get(sev) or DEFAULT_SLA_TARGETS.get(sev, {})
mttd_vals = [i["mttd"] for i in items if i["mttd"] is not None]
mttr_vals = [i["mttr"] for i in items if i["mttr"] is not None]
diff --git a/services/api/tests/test_alert_queue.py b/services/api/tests/test_alert_queue.py
new file mode 100644
index 000000000..f3ba3fb37
--- /dev/null
+++ b/services/api/tests/test_alert_queue.py
@@ -0,0 +1,1064 @@
+"""Unit tests for the investigation-queue workbench backend (W7 / PR-5).
+
+The queue service in ``app.services.alert_queue`` is split into pure
+helpers + an async orchestrator, mirroring the alert-explain pattern
+we already test in ``test_alert_explain.py``. We test it the same way:
+
+* **Pure helpers** (``first_asset``, ``first_action``) get
+ straightforward in-process tests with hand-built ``Alert``
+ stand-ins. These lock in the "one anchor entity per row" and
+ "top suggested action" projections the workbench renders.
+
+* **SLA target resolution** (``load_sla_targets``) is exercised
+ against an in-memory ``MagicMock(AsyncSession)``. The defaults
+ matter: a tenant with zero overrides must still get a full
+ ``severity → mttd_target_minutes`` map, otherwise the SQL
+ ``CASE`` for ``sla_due_at`` would produce ``NULL`` rows and the
+ workbench would drop them silently.
+
+* **`sla_due_at_expression`** is a SQL expression. We only verify it
+ compiles into a ``CASE`` block — full equivalence is covered by the
+ integration tests in CI which exercise real Postgres.
+
+* **`build_queue`** is unit-tested by mocking every
+ ``AsyncSession.execute`` call. We exercise the owner filter,
+ pagination math, the counts contract, and the row-projection
+ pipeline (alert → ``QueueItem``). The opinionated SQL ordering
+ itself is exercised end-to-end by the integration tests; here we
+ prove that whatever rows the DB returns in order are projected in
+ that same order, with the correct ``bucket`` / ``sla_*`` fields.
+
+* **`claim_alert`** gets dedicated coverage for all four documented
+ branches: unassigned-grab-succeeds, already-mine-idempotent,
+ already-someone-else-409, lost-the-race-409. The latter walks the
+ fallback re-read path so the error carries the *actual* owner.
+
+The tests deliberately do NOT spin up FastAPI's TestClient or a real
+Postgres. The endpoint module is a thin orchestration layer; the
+service layer here is what carries the business rules. Mocking the
+session keeps the suite fast (<1s) and deterministic.
+
+AiSOC — open-source AI Security Operations Center (MIT License)
+Author: Beenu Arora <[email protected]>
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from app.services.alert_queue import (
+ QUEUE_CLOSED_STATUSES,
+ QUEUE_UNASSIGNED_SEVERITIES,
+ AlertAlreadyClaimedError,
+ AlertNotFoundError,
+ QueueAction,
+ QueueAsset,
+ build_queue,
+ claim_alert,
+ first_action,
+ first_asset,
+ load_sla_targets,
+ sla_due_at_expression,
+)
+from app.services.sla import DEFAULT_SLA_TARGETS
+
+# ---------------------------------------------------------------------------
+# Fixtures / helpers
+# ---------------------------------------------------------------------------
+
+
+def _alert(
+ *,
+ alert_id: uuid.UUID | None = None,
+ tenant_id: uuid.UUID | None = None,
+ title: str = "Suspicious login from new geo",
+ severity: str = "high",
+ status: str = "new",
+ priority: int = 50,
+ category: str | None = "identity",
+ connector_type: str | None = "okta",
+ assigned_to_id: uuid.UUID | None = None,
+ case_id: uuid.UUID | None = None,
+ affected_hosts: list[Any] | None = None,
+ affected_users: list[Any] | None = None,
+ affected_assets: list[Any] | None = None,
+ affected_ips: list[Any] | None = None,
+ ai_recommendations: list[Any] | None = None,
+ first_seen: datetime | None = None,
+ assigned_at: datetime | None = None,
+ snoozed_until: datetime | None = None,
+) -> SimpleNamespace:
+ """Build a stand-in for the ``Alert`` ORM object.
+
+ ``SimpleNamespace`` is the same pattern we use in
+ ``test_alert_explain.py``: the service code only ever
+ attribute-accesses fields it needs, never calls ORM-only methods.
+ Using a namespace keeps the test free of SQLAlchemy setup / Postgres
+ type wiring (``JSONB``/``UUID``) that would otherwise pin the
+ suite to an integration harness.
+ """
+ return SimpleNamespace(
+ id=alert_id or uuid.uuid4(),
+ tenant_id=tenant_id or uuid.uuid4(),
+ title=title,
+ severity=severity,
+ status=status,
+ priority=priority,
+ category=category,
+ connector_type=connector_type,
+ assigned_to_id=assigned_to_id,
+ case_id=case_id,
+ affected_hosts=affected_hosts or [],
+ affected_users=affected_users or [],
+ affected_assets=affected_assets or [],
+ affected_ips=affected_ips or [],
+ ai_recommendations=ai_recommendations or [],
+ first_seen=first_seen or datetime.now(UTC) - timedelta(minutes=10),
+ assigned_at=assigned_at,
+ snoozed_until=snoozed_until,
+ )
+
+
+def _scalar_one_or_none_result(value: Any) -> MagicMock:
+ """Mock ``await session.execute(...).scalar_one_or_none() == value``."""
+ result = MagicMock()
+ result.scalar_one_or_none = MagicMock(return_value=value)
+ return result
+
+
+def _scalar_one_result(value: Any) -> MagicMock:
+ """Mock ``await session.execute(...).scalar_one() == value``."""
+ result = MagicMock()
+ result.scalar_one = MagicMock(return_value=value)
+ return result
+
+
+def _scalars_all_result(values: list[Any]) -> MagicMock:
+ """Mock ``await session.execute(...).scalars().all() == values``."""
+ result = MagicMock()
+ scalars = MagicMock()
+ scalars.all = MagicMock(return_value=values)
+ result.scalars = MagicMock(return_value=scalars)
+ return result
+
+
+def _rows_all_result(rows: list[tuple[Any, ...]]) -> MagicMock:
+ """Mock ``await session.execute(...).all() == rows``.
+
+ ``build_queue`` projects ``select(Alert, bucket_expr, sla_expr)``
+ and iterates ``rows`` indexing as ``row[0]``, ``row[1]``,
+ ``row[2]``. We use tuples to mirror that exactly.
+ """
+ result = MagicMock()
+ result.all = MagicMock(return_value=rows)
+ return result
+
+
+def _tenant_sla_cfg(severity: str, mttd_target: int) -> SimpleNamespace:
+ """Stand-in for a ``TenantSLAConfig`` row."""
+ return SimpleNamespace(severity=severity, mttd_target=mttd_target)
+
+
+# ---------------------------------------------------------------------------
+# load_sla_targets — defaults + tenant overrides
+# ---------------------------------------------------------------------------
+
+
+class TestLoadSlaTargets:
+ """Tenant overrides win, defaults fill the rest.
+
+ A regression here would either (a) drop a severity that the
+ tenant didn't override — silently dropping rows from the queue —
+ or (b) ignore tenant overrides — pinning every tenant to the
+ out-of-the-box MTTD targets.
+ """
+
+ @pytest.mark.asyncio
+ async def test_returns_defaults_when_no_tenant_overrides(self) -> None:
+ # Empty config → fall back to ``DEFAULT_SLA_TARGETS`` for
+ # every severity. The dict must contain every key the
+ # ``CASE`` expression branches on, including ``info``.
+ db = MagicMock()
+ db.execute = AsyncMock(return_value=_scalars_all_result([]))
+
+ targets = await load_sla_targets(db, uuid.uuid4())
+
+ assert set(targets.keys()) == set(DEFAULT_SLA_TARGETS.keys())
+ for sev, default in DEFAULT_SLA_TARGETS.items():
+ assert targets[sev] == default["mttd_target"]
+
+ @pytest.mark.asyncio
+ async def test_tenant_override_wins(self) -> None:
+ # Only the overridden severity should change; the rest must
+ # keep their defaults.
+ db = MagicMock()
+ db.execute = AsyncMock(
+ return_value=_scalars_all_result(
+ [_tenant_sla_cfg("critical", 5)]
+ )
+ )
+
+ targets = await load_sla_targets(db, uuid.uuid4())
+
+ assert targets["critical"] == 5
+ # All other severities keep defaults.
+ assert targets["high"] == DEFAULT_SLA_TARGETS["high"]["mttd_target"]
+ assert targets["medium"] == DEFAULT_SLA_TARGETS["medium"]["mttd_target"]
+ assert targets["low"] == DEFAULT_SLA_TARGETS["low"]["mttd_target"]
+ assert targets["info"] == DEFAULT_SLA_TARGETS["info"]["mttd_target"]
+
+ @pytest.mark.asyncio
+ async def test_unknown_severity_override_is_ignored(self) -> None:
+ # A row with a severity outside the canonical ladder
+ # (mis-configured tenant table) must NOT inject a new key
+ # into the result — that would break the SQL ``CASE`` (which
+ # only branches on the canonical severities).
+ db = MagicMock()
+ db.execute = AsyncMock(
+ return_value=_scalars_all_result(
+ [_tenant_sla_cfg("unknown_severity", 99)]
+ )
+ )
+
+ targets = await load_sla_targets(db, uuid.uuid4())
+
+ assert "unknown_severity" not in targets
+ # Defaults still present and unmodified.
+ assert targets["critical"] == DEFAULT_SLA_TARGETS["critical"]["mttd_target"]
+
+ @pytest.mark.asyncio
+ async def test_multiple_overrides_apply_independently(self) -> None:
+ # Each row overrides exactly one severity. We expect the
+ # final dict to reflect every override, not just the last one.
+ db = MagicMock()
+ db.execute = AsyncMock(
+ return_value=_scalars_all_result(
+ [
+ _tenant_sla_cfg("critical", 10),
+ _tenant_sla_cfg("high", 20),
+ _tenant_sla_cfg("medium", 90),
+ ]
+ )
+ )
+
+ targets = await load_sla_targets(db, uuid.uuid4())
+
+ assert targets["critical"] == 10
+ assert targets["high"] == 20
+ assert targets["medium"] == 90
+ # Untouched severities still default.
+ assert targets["low"] == DEFAULT_SLA_TARGETS["low"]["mttd_target"]
+
+
+# ---------------------------------------------------------------------------
+# sla_due_at_expression — compiles to a CASE expression
+# ---------------------------------------------------------------------------
+
+
+class TestSlaDueAtExpression:
+ """Verify the SQL expression is well-formed.
+
+ We don't try to execute it here — that requires a real Postgres
+ session because ``Alert.first_seen + timedelta`` lowers to
+ Postgres' interval arithmetic. The integration tests cover that.
+ What we *can* lock in here is that the expression compiles into
+ a ``CASE`` block with one branch per severity in our target map.
+ """
+
+ def test_returns_case_expression(self) -> None:
+ targets = {sev: cfg["mttd_target"] for sev, cfg in DEFAULT_SLA_TARGETS.items()}
+ expr = sla_due_at_expression(targets)
+
+ # ``case`` returns a ``Case`` element; compiling it as a
+ # generic SQL string is enough to prove it's well-formed.
+ compiled = str(expr).upper()
+ assert "CASE" in compiled
+
+ def test_empty_targets_still_compiles(self) -> None:
+ # Defensive: empty dict should not crash construction (the
+ # fallback branch using DEFAULT_SLA_TARGETS["info"] always
+ # exists).
+ expr = sla_due_at_expression({})
+ compiled = str(expr).upper()
+ assert "CASE" in compiled
+
+
+# ---------------------------------------------------------------------------
+# first_asset — host > user > asset > ip
+# ---------------------------------------------------------------------------
+
+
+class TestFirstAsset:
+ """Single-pivot extraction for queue rows.
+
+ A regression here demotes the queue from "VPN brute force on
+ web-01" back to "VPN brute force" — the entity is what makes a
+ row scannable. We exhaustively cover every priority slot.
+ """
+
+ def test_prefers_host_over_others(self) -> None:
+ alert = _alert(
+ affected_hosts=["web-01"],
+ affected_users=["[email protected]"],
+ affected_assets=["asset-1"],
+ affected_ips=["10.0.0.1"],
+ )
+ asset = first_asset(alert)
+ assert isinstance(asset, QueueAsset)
+ assert asset.kind == "host"
+ assert asset.value == "web-01"
+
+ def test_falls_back_to_user_when_no_host(self) -> None:
+ alert = _alert(
+ affected_hosts=[],
+ affected_users=["[email protected]"],
+ affected_ips=["10.0.0.1"],
+ )
+ asset = first_asset(alert)
+ assert asset is not None and asset.kind == "user"
+ assert asset.value == "[email protected]"
+
+ def test_falls_back_to_asset_when_no_host_or_user(self) -> None:
+ alert = _alert(
+ affected_hosts=[],
+ affected_users=[],
+ affected_assets=["crown-jewel-db"],
+ affected_ips=["10.0.0.1"],
+ )
+ asset = first_asset(alert)
+ assert asset is not None and asset.kind == "asset"
+ assert asset.value == "crown-jewel-db"
+
+ def test_falls_back_to_ip_last(self) -> None:
+ alert = _alert(
+ affected_hosts=[],
+ affected_users=[],
+ affected_assets=[],
+ affected_ips=["192.168.1.42"],
+ )
+ asset = first_asset(alert)
+ assert asset is not None and asset.kind == "ip"
+ assert asset.value == "192.168.1.42"
+
+ def test_returns_none_when_no_entities(self) -> None:
+ # No entities → no anchor. The UI will omit the asset chip.
+ alert = _alert(
+ affected_hosts=[],
+ affected_users=[],
+ affected_assets=[],
+ affected_ips=[],
+ )
+ assert first_asset(alert) is None
+
+ def test_skips_blank_strings_and_non_strings(self) -> None:
+ # Lists sometimes contain ``""`` or ``None`` after legacy
+ # ingest pipelines stripped fields. The picker must skip
+ # them rather than emit ``QueueAsset(value="")``.
+ alert = _alert(
+ affected_hosts=["", None, 42, " "],
+ affected_users=["bob"],
+ )
+ asset = first_asset(alert)
+ assert asset is not None
+ assert asset.kind == "user"
+ assert asset.value == "bob"
+
+ def test_strips_surrounding_whitespace(self) -> None:
+ # Trailing spaces from a CSV-style ingest must not bleed
+ # into the rendered chip.
+ alert = _alert(affected_hosts=[" web-01 "])
+ asset = first_asset(alert)
+ assert asset is not None
+ assert asset.value == "web-01"
+
+
+# ---------------------------------------------------------------------------
+# first_action — lowest priority wins, normalises shapes
+# ---------------------------------------------------------------------------
+
+
+class TestFirstAction:
+ """Top suggested-next-action projection."""
+
+ def test_returns_none_when_no_recommendations(self) -> None:
+ alert = _alert(ai_recommendations=[])
+ assert first_action(alert) is None
+
+ def test_returns_none_when_field_is_not_list(self) -> None:
+ # Defensive: older rows wrote dicts; the projection must
+ # bail out instead of crashing.
+ alert = _alert(ai_recommendations=None) # type: ignore[arg-type]
+ assert first_action(alert) is None
+
+ def test_accepts_legacy_string_form(self) -> None:
+ # Legacy: bare strings, no priority. Array index drives the
+ # priority assignment (1-indexed).
+ alert = _alert(ai_recommendations=["Reset password", "Notify user"])
+ action = first_action(alert)
+ assert isinstance(action, QueueAction)
+ assert action.action == "Reset password"
+ assert action.priority == 1
+ # Risk defaults to "low" for legacy entries.
+ assert action.risk == "low"
+
+ def test_lowest_priority_wins(self) -> None:
+ # Modern form: dict with explicit priority. Lower number =
+ # more urgent. Out-of-order recommendations must still pick
+ # the urgent one.
+ alert = _alert(
+ ai_recommendations=[
+ {"action": "Low urgency", "priority": 3, "risk": "low"},
+ {"action": "Highest urgency", "priority": 1, "risk": "high"},
+ {"action": "Medium urgency", "priority": 2, "risk": "medium"},
+ ]
+ )
+ action = first_action(alert)
+ assert action is not None
+ assert action.action == "Highest urgency"
+ assert action.priority == 1
+ assert action.risk == "high"
+
+ def test_invalid_priority_falls_back_to_index(self) -> None:
+ # Non-integer priority → use array-index fallback.
+ alert = _alert(
+ ai_recommendations=[
+ {"action": "First", "priority": "garbage"},
+ {"action": "Second", "priority": "also bad"},
+ ]
+ )
+ action = first_action(alert)
+ # Both fall back to idx+1 → first wins by index.
+ assert action is not None
+ assert action.action == "First"
+ assert action.priority == 1
+
+ def test_normalises_unknown_risk_to_low(self) -> None:
+ # Risk must be one of low/medium/high. Anything else gets
+ # clamped to ``low`` so the UI never paints a chip in an
+ # unknown colour.
+ alert = _alert(
+ ai_recommendations=[
+ {"action": "Quarantine host", "priority": 1, "risk": "EXTREME"},
+ ]
+ )
+ action = first_action(alert)
+ assert action is not None
+ assert action.risk == "low"
+
+ def test_normalises_risk_case_insensitively(self) -> None:
+ # ``HIGH``/``High`` must be recognised, even though our enum
+ # is lowercase. Pipelines sometimes capitalise risk labels.
+ alert = _alert(
+ ai_recommendations=[
+ {"action": "Isolate", "priority": 1, "risk": "HIGH"},
+ ]
+ )
+ action = first_action(alert)
+ assert action is not None
+ assert action.risk == "high"
+
+ def test_skips_empty_action_strings(self) -> None:
+ # An empty ``action`` field is useless to the analyst.
+ # Skip and pick the next candidate.
+ alert = _alert(
+ ai_recommendations=[
+ {"action": " ", "priority": 1},
+ {"action": "Real action", "priority": 2},
+ ]
+ )
+ action = first_action(alert)
+ assert action is not None
+ assert action.action == "Real action"
+
+ def test_priority_is_clamped_to_minimum_one(self) -> None:
+ # ``priority=0`` or negative would distort the sort. We
+ # clamp at 1 so 0-priority entries don't outrank
+ # explicit-1 entries silently.
+ alert = _alert(
+ ai_recommendations=[
+ {"action": "Sneaky", "priority": -10},
+ {"action": "Honest", "priority": 1},
+ ]
+ )
+ action = first_action(alert)
+ # Both end up priority=1; first in array wins the stable sort.
+ assert action is not None
+ assert action.action == "Sneaky"
+ assert action.priority == 1
+
+
+# ---------------------------------------------------------------------------
+# build_queue — owner filter, counts, ordering, pagination, projection
+# ---------------------------------------------------------------------------
+
+
+class TestBuildQueue:
+ """End-to-end queue assembly with a mocked session.
+
+ The opinionated SQL ordering itself is exercised by the
+ integration tests in CI. Here we lock in:
+ * counts are populated for both buckets regardless of filter,
+ * the row projection produces correct ``QueueItem`` fields,
+ * pagination math (``pages`` and ``offset``) is correct,
+ * the ``owner=*`` selector picks the right total + filter.
+ """
+
+ def _setup_db(
+ self,
+ *,
+ mine_count: int,
+ unassigned_count: int,
+ rows: list[tuple[Any, int, datetime]] | None = None,
+ tenant_overrides: list[Any] | None = None,
+ ) -> MagicMock:
+ """Wire a session with the queue's 4-call execute pattern.
+
+ Call order inside ``build_queue``:
+ 1) ``load_sla_targets`` → ``scalars().all()`` on tenant SLA config
+ 2) ``mine_count`` → ``scalar_one()``
+ 3) ``unassigned_count`` → ``scalar_one()``
+ 4) main projection query → ``.all()`` of row tuples
+ """
+ db = MagicMock()
+ db.execute = AsyncMock(
+ side_effect=[
+ _scalars_all_result(tenant_overrides or []),
+ _scalar_one_result(mine_count),
+ _scalar_one_result(unassigned_count),
+ _rows_all_result(rows or []),
+ ]
+ )
+ return db
+
+ @pytest.mark.asyncio
+ async def test_counts_populated_for_both_buckets(self) -> None:
+ # Whatever the owner filter is, the response always carries
+ # ``counts.mine`` and ``counts.unassigned`` so the workbench
+ # tabs render without a second fetch.
+ tenant_id = uuid.uuid4()
+ user_id = uuid.uuid4()
+ db = self._setup_db(mine_count=3, unassigned_count=7)
+
+ resp = await build_queue(
+ db,
+ tenant_id=tenant_id,
+ user_id=user_id,
+ owner="me",
+ )
+
+ assert resp.counts == {"mine": 3, "unassigned": 7, "all": 10}
+ # Even though owner="me" filters to mine only, the counts
+ # *contract* never changes.
+ assert resp.owner == "me"
+
+ @pytest.mark.asyncio
+ async def test_owner_me_uses_mine_count_as_total(self) -> None:
+ db = self._setup_db(mine_count=3, unassigned_count=7)
+
+ resp = await build_queue(
+ db,
+ tenant_id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ owner="me",
+ )
+
+ assert resp.total == 3
+
+ @pytest.mark.asyncio
+ async def test_owner_unassigned_uses_unassigned_count_as_total(self) -> None:
+ db = self._setup_db(mine_count=3, unassigned_count=7)
+
+ resp = await build_queue(
+ db,
+ tenant_id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ owner="unassigned",
+ )
+
+ assert resp.total == 7
+
+ @pytest.mark.asyncio
+ async def test_owner_all_uses_sum_as_total(self) -> None:
+ db = self._setup_db(mine_count=3, unassigned_count=7)
+
+ resp = await build_queue(
+ db,
+ tenant_id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ owner="all",
+ )
+
+ assert resp.total == 10
+
+ @pytest.mark.asyncio
+ async def test_empty_queue_returns_zero_total_and_no_pages(self) -> None:
+ # No alerts at all → total=0, pages=0, items=[]. The
+ # frontend uses ``pages > 0`` to decide whether to render the
+ # paginator.
+ db = self._setup_db(mine_count=0, unassigned_count=0, rows=[])
+
+ resp = await build_queue(
+ db,
+ tenant_id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ owner="all",
+ )
+
+ assert resp.total == 0
+ assert resp.pages == 0
+ assert resp.items == []
+
+ @pytest.mark.asyncio
+ async def test_pages_math_rounds_up(self) -> None:
+ # ceil(7 / 3) = 3 pages. Off-by-one here would either hide
+ # the last page or show an empty trailing page.
+ db = self._setup_db(mine_count=7, unassigned_count=0, rows=[])
+
+ resp = await build_queue(
+ db,
+ tenant_id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ owner="me",
+ page=1,
+ page_size=3,
+ )
+
+ assert resp.pages == 3
+ assert resp.page_size == 3
+
+ @pytest.mark.asyncio
+ async def test_page_size_clamped_to_max(self) -> None:
+ # A misbehaving client passing ``page_size=1_000_000`` must
+ # be clamped to ``QUEUE_MAX_PAGE_SIZE`` (200) so we don't
+ # let them yank the whole tenant in one request.
+ db = self._setup_db(mine_count=0, unassigned_count=0, rows=[])
+
+ resp = await build_queue(
+ db,
+ tenant_id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ page_size=10_000,
+ )
+
+ assert resp.page_size == 200
+
+ @pytest.mark.asyncio
+ async def test_page_clamped_to_minimum_one(self) -> None:
+ # ``page=0`` or negative pages must collapse to page 1.
+ db = self._setup_db(mine_count=0, unassigned_count=0, rows=[])
+
+ resp = await build_queue(
+ db,
+ tenant_id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ page=0,
+ )
+
+ assert resp.page == 1
+
+ @pytest.mark.asyncio
+ async def test_row_projection_fills_queue_item(self) -> None:
+ # Single-row sanity check: the projection must carry every
+ # field the frontend renders (severity, asset chip, action
+ # chip, SLA countdown, age, bucket label).
+ tenant_id = uuid.uuid4()
+ user_id = uuid.uuid4()
+ alert_id = uuid.uuid4()
+
+ first_seen = datetime.now(UTC) - timedelta(minutes=10)
+ sla_due = datetime.now(UTC) + timedelta(minutes=20)
+
+ alert = _alert(
+ alert_id=alert_id,
+ tenant_id=tenant_id,
+ severity="critical",
+ title="Pod crashlooping",
+ status="new",
+ priority=80,
+ assigned_to_id=user_id,
+ affected_hosts=["k8s-node-3"],
+ ai_recommendations=[{"action": "Drain node", "priority": 1, "risk": "high"}],
+ first_seen=first_seen,
+ )
+
+ # bucket=0 (mine), sla_due in the future (not breached).
+ db = self._setup_db(
+ mine_count=1,
+ unassigned_count=0,
+ rows=[(alert, 0, sla_due)],
+ )
+
+ resp = await build_queue(
+ db,
+ tenant_id=tenant_id,
+ user_id=user_id,
+ owner="me",
+ )
+
+ assert len(resp.items) == 1
+ item = resp.items[0]
+ assert item.id == alert_id
+ assert item.tenant_id == tenant_id
+ assert item.title == "Pod crashlooping"
+ assert item.severity == "critical"
+ assert item.priority == 80
+ assert item.bucket == "mine"
+ assert item.sla_breached is False
+ # Countdown is in the future, so > 0.
+ assert item.sla_remaining_seconds > 0
+ # Age is positive (first_seen was 10 minutes ago).
+ assert item.age_seconds >= 0
+ # Asset chip pulls host first.
+ assert item.asset is not None
+ assert item.asset.kind == "host"
+ assert item.asset.value == "k8s-node-3"
+ # Action chip carries the structured recommendation.
+ assert item.suggested_action is not None
+ assert item.suggested_action.action == "Drain node"
+ assert item.suggested_action.risk == "high"
+
+ @pytest.mark.asyncio
+ async def test_breached_sla_flags_negative_remaining(self) -> None:
+ # The frontend flips the timer red when ``sla_breached``
+ # is true. We must report the boolean *and* a negative
+ # countdown for downstream UI to match.
+ tenant_id = uuid.uuid4()
+ user_id = uuid.uuid4()
+ alert = _alert(tenant_id=tenant_id)
+
+ sla_due_past = datetime.now(UTC) - timedelta(minutes=5)
+
+ db = self._setup_db(
+ mine_count=1,
+ unassigned_count=0,
+ rows=[(alert, 0, sla_due_past)],
+ )
+
+ resp = await build_queue(
+ db,
+ tenant_id=tenant_id,
+ user_id=user_id,
+ owner="me",
+ )
+
+ item = resp.items[0]
+ assert item.sla_breached is True
+ assert item.sla_remaining_seconds < 0
+
+ @pytest.mark.asyncio
+ async def test_unassigned_bucket_label_is_unassigned(self) -> None:
+ # bucket=1 maps to ``unassigned`` literal in the QueueItem.
+ # If this regresses, the UI's bucket grouping silently swaps.
+ tenant_id = uuid.uuid4()
+ user_id = uuid.uuid4()
+ alert = _alert(tenant_id=tenant_id, assigned_to_id=None)
+
+ sla_due = datetime.now(UTC) + timedelta(minutes=20)
+ db = self._setup_db(
+ mine_count=0,
+ unassigned_count=1,
+ rows=[(alert, 1, sla_due)],
+ )
+
+ resp = await build_queue(
+ db,
+ tenant_id=tenant_id,
+ user_id=user_id,
+ owner="unassigned",
+ )
+
+ assert resp.items[0].bucket == "unassigned"
+
+ @pytest.mark.asyncio
+ async def test_naive_datetimes_are_treated_as_utc(self) -> None:
+ # Postgres returns ``timestamptz`` rows as tz-aware datetimes
+ # in production, but a SQLite-style stand-in (or some test
+ # fixtures) may hand us naive datetimes. The projection must
+ # coerce them to UTC instead of crashing the arithmetic.
+ tenant_id = uuid.uuid4()
+ user_id = uuid.uuid4()
+
+ # Construct a naive datetime via UTC-now-stripped-tz so we are not
+ # tripped up by the ``utcnow()`` deprecation while still exercising
+ # the naive-coercion path that ``build_queue`` is meant to handle.
+ naive_first_seen = datetime.now(UTC).replace(tzinfo=None)
+ naive_sla_due = naive_first_seen + timedelta(minutes=10)
+ alert = _alert(tenant_id=tenant_id, first_seen=naive_first_seen)
+
+ db = self._setup_db(
+ mine_count=1,
+ unassigned_count=0,
+ rows=[(alert, 0, naive_sla_due)],
+ )
+
+ resp = await build_queue(
+ db,
+ tenant_id=tenant_id,
+ user_id=user_id,
+ owner="me",
+ )
+
+ # No crash + the projection coerced both stamps to UTC so
+ # they compare cleanly.
+ item = resp.items[0]
+ assert item.first_seen.tzinfo is not None
+ assert item.sla_due_at.tzinfo is not None
+
+ @pytest.mark.asyncio
+ async def test_generated_at_is_utc(self) -> None:
+ # The frontend uses ``generated_at`` for client-side clock
+ # drift correction; it MUST be tz-aware UTC.
+ db = self._setup_db(mine_count=0, unassigned_count=0, rows=[])
+
+ resp = await build_queue(
+ db,
+ tenant_id=uuid.uuid4(),
+ user_id=uuid.uuid4(),
+ )
+
+ assert resp.generated_at.tzinfo is not None
+ assert resp.generated_at.utcoffset() == timedelta(0)
+
+ @pytest.mark.asyncio
+ async def test_queue_closed_statuses_constant_matches_contract(self) -> None:
+ # Sanity check: any future status added to the alerts schema
+ # that "exits" the queue must be added here, or the SLA
+ # timer keeps ticking on resolved alerts.
+ assert "resolved" in QUEUE_CLOSED_STATUSES
+ assert "closed" in QUEUE_CLOSED_STATUSES
+ # Both "false_positive" (new canonical) and "fp" (legacy)
+ # must be honoured so a legacy disposition write doesn't
+ # keep the alert visible in the queue.
+ assert "false_positive" in QUEUE_CLOSED_STATUSES
+ assert "fp" in QUEUE_CLOSED_STATUSES
+
+ @pytest.mark.asyncio
+ async def test_unassigned_severities_constant_matches_contract(self) -> None:
+ # ``low``/``medium``/``info`` are deliberately NOT in the
+ # unassigned bucket — they're triaged in bulk on /alerts.
+ assert set(QUEUE_UNASSIGNED_SEVERITIES) == {"critical", "high"}
+
+
+# ---------------------------------------------------------------------------
+# claim_alert — atomic compare-and-set semantics
+# ---------------------------------------------------------------------------
+
+
+class TestClaimAlert:
+ """All four documented branches of the claim path.
+
+ Two analysts can race against the same row; the function does a
+ SELECT, then an UPDATE guarded with ``WHERE assigned_to_id IS NULL``
+ so only one update can win. A regression in any branch produces a
+ bug visible in production (lost claims, false 409s, or silent
+ cross-tenant claim grants).
+ """
+
+ @pytest.mark.asyncio
+ async def test_claim_unassigned_succeeds(self) -> None:
+ # Happy path. The SELECT returns an unassigned row, the
+ # UPDATE returns ``user_id``, commit + refresh fire.
+ tenant_id = uuid.uuid4()
+ user_id = uuid.uuid4()
+ alert_id = uuid.uuid4()
+ alert = _alert(alert_id=alert_id, tenant_id=tenant_id, assigned_to_id=None)
+
+ db = MagicMock()
+ db.execute = AsyncMock(
+ side_effect=[
+ # SELECT lookup
+ _scalar_one_or_none_result(alert),
+ # UPDATE ... RETURNING assigned_to_id
+ _scalar_one_or_none_result(user_id),
+ ]
+ )
+ db.commit = AsyncMock()
+ db.refresh = AsyncMock()
+
+ result = await claim_alert(
+ db,
+ alert_id=alert_id,
+ tenant_id=tenant_id,
+ user_id=user_id,
+ )
+
+ assert result is alert
+ db.commit.assert_awaited_once()
+ db.refresh.assert_awaited_once_with(alert)
+
+ @pytest.mark.asyncio
+ async def test_claim_already_mine_is_idempotent(self) -> None:
+ # If I refresh the queue and re-click claim, we MUST NOT
+ # 409 — that would make the workbench feel broken. We
+ # return the existing alert without issuing an UPDATE.
+ tenant_id = uuid.uuid4()
+ user_id = uuid.uuid4()
+ alert_id = uuid.uuid4()
+ alert = _alert(alert_id=alert_id, tenant_id=tenant_id, assigned_to_id=user_id)
+
+ db = MagicMock()
+ db.execute = AsyncMock(return_value=_scalar_one_or_none_result(alert))
+ db.commit = AsyncMock()
+ db.refresh = AsyncMock()
+
+ result = await claim_alert(
+ db,
+ alert_id=alert_id,
+ tenant_id=tenant_id,
+ user_id=user_id,
+ )
+
+ assert result is alert
+ # Only ONE execute call (the SELECT). No UPDATE issued.
+ assert db.execute.await_count == 1
+ # No commit/refresh either — nothing changed.
+ db.commit.assert_not_awaited()
+ db.refresh.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_claim_assigned_to_other_raises_409(self) -> None:
+ # The classic conflict: another analyst already owns this
+ # alert. We MUST surface the actual owner's ID so the UI
+ # toast can render ``"already claimed by @bob"``.
+ tenant_id = uuid.uuid4()
+ my_id = uuid.uuid4()
+ their_id = uuid.uuid4()
+ alert_id = uuid.uuid4()
+ alert = _alert(alert_id=alert_id, tenant_id=tenant_id, assigned_to_id=their_id)
+
+ db = MagicMock()
+ db.execute = AsyncMock(return_value=_scalar_one_or_none_result(alert))
+
+ with pytest.raises(AlertAlreadyClaimedError) as exc_info:
+ await claim_alert(
+ db,
+ alert_id=alert_id,
+ tenant_id=tenant_id,
+ user_id=my_id,
+ )
+
+ assert exc_info.value.alert_id == alert_id
+ assert exc_info.value.owner_id == their_id
+
+ @pytest.mark.asyncio
+ async def test_claim_missing_alert_raises_not_found(self) -> None:
+ # Wrong tenant, deleted alert, or typo in the URL → 404,
+ # NOT 409. The endpoint maps NotFound → 404 and Conflict →
+ # 409, so a regression here would silently swap the two.
+ tenant_id = uuid.uuid4()
+ user_id = uuid.uuid4()
+ alert_id = uuid.uuid4()
+
+ db = MagicMock()
+ db.execute = AsyncMock(return_value=_scalar_one_or_none_result(None))
+
+ with pytest.raises(AlertNotFoundError):
+ await claim_alert(
+ db,
+ alert_id=alert_id,
+ tenant_id=tenant_id,
+ user_id=user_id,
+ )
+
+ @pytest.mark.asyncio
+ async def test_claim_lost_race_falls_back_to_actual_owner(self) -> None:
+ # Two analysts hit "Claim" at the same time:
+ # * Both SELECTs see ``assigned_to_id=NULL``.
+ # * The first UPDATE wins (returns winner_id).
+ # * The second UPDATE's guarded WHERE no longer matches
+ # so RETURNING is empty.
+ # We must re-read to discover the *actual* owner and 409
+ # with the right ID — telling the loser they collided with
+ # themselves would be confusing.
+ tenant_id = uuid.uuid4()
+ my_id = uuid.uuid4()
+ winner_id = uuid.uuid4()
+ alert_id = uuid.uuid4()
+ # SELECT shows the alert as unassigned (we lost the race
+ # *after* this point).
+ alert = _alert(alert_id=alert_id, tenant_id=tenant_id, assigned_to_id=None)
+
+ db = MagicMock()
+ db.execute = AsyncMock(
+ side_effect=[
+ _scalar_one_or_none_result(alert), # SELECT
+ _scalar_one_or_none_result(None), # UPDATE RETURNING → empty (lost)
+ _scalar_one_or_none_result(winner_id), # re-read owner
+ ]
+ )
+
+ with pytest.raises(AlertAlreadyClaimedError) as exc_info:
+ await claim_alert(
+ db,
+ alert_id=alert_id,
+ tenant_id=tenant_id,
+ user_id=my_id,
+ )
+
+ assert exc_info.value.owner_id == winner_id
+
+ @pytest.mark.asyncio
+ async def test_claim_lost_race_with_no_owner_raises_not_found(self) -> None:
+ # Pathological case: between our SELECT and UPDATE, the
+ # alert was deleted (admin scrubbed it, or tenant teardown).
+ # The re-read returns ``None`` and we surface 404 rather
+ # than a confusing 409 with a missing owner.
+ tenant_id = uuid.uuid4()
+ my_id = uuid.uuid4()
+ alert_id = uuid.uuid4()
+ alert = _alert(alert_id=alert_id, tenant_id=tenant_id, assigned_to_id=None)
+
+ db = MagicMock()
+ db.execute = AsyncMock(
+ side_effect=[
+ _scalar_one_or_none_result(alert),
+ _scalar_one_or_none_result(None),
+ _scalar_one_or_none_result(None), # re-read also returns None
+ ]
+ )
+
+ with pytest.raises(AlertNotFoundError):
+ await claim_alert(
+ db,
+ alert_id=alert_id,
+ tenant_id=tenant_id,
+ user_id=my_id,
+ )
+
+ @pytest.mark.asyncio
+ async def test_claim_lost_race_where_we_actually_won(self) -> None:
+ # Rare but real: the UPDATE returns no row (driver hiccup,
+ # WHERE didn't trigger RETURNING), but the re-read shows
+ # we own the alert anyway. Treat this as a successful claim
+ # rather than 409-ing the legitimate owner.
+ tenant_id = uuid.uuid4()
+ my_id = uuid.uuid4()
+ alert_id = uuid.uuid4()
+ alert = _alert(alert_id=alert_id, tenant_id=tenant_id, assigned_to_id=None)
+
+ db = MagicMock()
+ db.execute = AsyncMock(
+ side_effect=[
+ _scalar_one_or_none_result(alert),
+ _scalar_one_or_none_result(None), # UPDATE returned nothing
+ _scalar_one_or_none_result(my_id), # but re-read shows we own it
+ ]
+ )
+ db.commit = AsyncMock()
+ db.refresh = AsyncMock()
+
+ result = await claim_alert(
+ db,
+ alert_id=alert_id,
+ tenant_id=tenant_id,
+ user_id=my_id,
+ )
+
+ assert result is alert
+ db.commit.assert_awaited_once()
+ db.refresh.assert_awaited_once_with(alert)