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(war-rooms): sweep worker and a console panel that shows whether a room still mirrors

Beenu Arora54674e609339
diff --git a/apps/web/src/components/cases/CaseWorkspace.tsx b/apps/web/src/components/cases/CaseWorkspace.tsx
index 633bf41e4..7e44f4f1f 100644
--- a/apps/web/src/components/cases/CaseWorkspace.tsx
+++ b/apps/web/src/components/cases/CaseWorkspace.tsx
@@ -29,6 +29,7 @@ import { Skeleton } from '@/components/ui/Skeleton';
import { ErrorState } from '@/components/ui/ErrorState';
import { EmptyState } from '@/components/ui/EmptyState';
import { InvestigationLedger } from './InvestigationLedger';
+import { WarRoomPanel } from './WarRoomPanel';
import { ContextualActions } from '@/components/copilot/ContextualActions';
import { canUseDemoData } from '@/lib/demoFallback';
@@ -986,6 +987,11 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
eyebrow="Ask AiSOC about this case"
/>
+ {/* Depth 9.4 — one action opens a Slack or Teams channel for this case
+ and mirrors its timeline into it. Above the three columns because
+ it is an action on the case, not a facet of it. */}
+ <WarRoomPanel caseId={caseId} />
+
<div className="grid grid-cols-1 gap-4 lg:grid-cols-12">
{/* Left: Linked alerts + IOCs */}
<aside className="lg:col-span-3 space-y-4">
diff --git a/apps/web/src/components/cases/WarRoomPanel.tsx b/apps/web/src/components/cases/WarRoomPanel.tsx
new file mode 100644
index 000000000..4c483e521
--- /dev/null
+++ b/apps/web/src/components/cases/WarRoomPanel.tsx
@@ -0,0 +1,136 @@
+'use client';
+
+/**
+ * Open a chat war room for a case, and show whether it is still mirroring.
+ *
+ * Depth 9.4. The one action the plan asks for, and the honest reporting
+ * around it:
+ *
+ * - **The button performs a real write and fails loudly.** The API returns
+ * 502 with the vendor's own reason when the bot is not deployed or Slack
+ * refuses, and that sentence is what the analyst reads. A toast saying
+ * "opening…" over a request that failed is the control this console is not
+ * allowed to ship.
+ * - **"Never synced" and "synced with nothing to say" render differently.**
+ * `last_synced_at: null` means the sweep has not run for this room yet,
+ * which is a different fact from a quiet case, and collapsing them would
+ * let an analyst read a broken mirror as a calm one.
+ * - **A stalled mirror is shown, not hidden.** `last_error` is rendered in
+ * full. A war room that has silently stopped following the case is worse
+ * than one that was never opened.
+ * - **No `fallbackData` and no mock.** First paint is a loading state.
+ */
+
+import { useCallback, useState } from 'react';
+import useSWR from 'swr';
+
+import { ApiError, warRoomApi, type WarRoom } from '@/lib/api';
+
+function SyncState({ room }: { room: WarRoom }) {
+ if (room.last_error) {
+ return (
+ <span className="text-red-400" role="alert">
+ not mirroring — {room.last_error}
+ </span>
+ );
+ }
+ if (!room.last_synced_at) {
+ // Distinct from "synced and had nothing to say". An analyst must be able
+ // to tell a room nobody has swept from a case nobody has touched.
+ return <span className="text-gray-500">waiting for the first sync</span>;
+ }
+ return (
+ <span className="text-emerald-400">
+ mirroring · last synced {new Date(room.last_synced_at).toLocaleTimeString()}
+ </span>
+ );
+}
+
+export function WarRoomPanel({ caseId }: { caseId: string }) {
+ const { data, error, isLoading, mutate } = useSWR(['war-rooms', caseId], () => warRoomApi.forCase(caseId), {
+ refreshInterval: 30_000,
+ });
+ const [opening, setOpening] = useState(false);
+ const [failure, setFailure] = useState<string | null>(null);
+
+ const open = useCallback(
+ async (provider: 'slack' | 'teams') => {
+ setOpening(true);
+ setFailure(null);
+ try {
+ await warRoomApi.open(caseId, provider);
+ await mutate();
+ } catch (err) {
+ // The vendor's own reason, verbatim. "Something went wrong" sends an
+ // operator to debug the wrong thing; "the slack bot is not
+ // configured" tells them exactly what to do.
+ setFailure(
+ err instanceof ApiError ? err.body || err.message : err instanceof Error ? err.message : 'Open failed.',
+ );
+ } finally {
+ setOpening(false);
+ }
+ },
+ [caseId, mutate],
+ );
+
+ const rooms = data ?? [];
+
+ return (
+ <section className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4 space-y-3" aria-label="War room">
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm font-semibold text-gray-200">War room</h3>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ disabled={opening}
+ onClick={() => void open('slack')}
+ className="text-xs px-3 py-1.5 rounded-md border border-blue-500/40 bg-blue-500/10 text-blue-300 hover:bg-blue-500/20 disabled:opacity-50"
+ >
+ {opening ? 'Opening…' : 'Open in Slack'}
+ </button>
+ <button
+ type="button"
+ disabled={opening}
+ onClick={() => void open('teams')}
+ className="text-xs px-3 py-1.5 rounded-md border border-gray-700 text-gray-300 hover:bg-gray-800 disabled:opacity-50"
+ >
+ Open in Teams
+ </button>
+ </div>
+ </div>
+
+ {failure && (
+ <p className="text-xs text-red-400" role="alert">
+ {failure}
+ </p>
+ )}
+
+ {isLoading ? (
+ <p className="text-xs text-gray-500">Loading…</p>
+ ) : error ? (
+ <p className="text-xs text-red-400" role="alert">
+ Couldn&apos;t load war rooms for this case.
+ </p>
+ ) : rooms.length === 0 ? (
+ <p className="text-xs text-gray-500">
+ No war room yet. Opening one creates a channel, invites the assignees and mirrors the case
+ timeline into it.
+ </p>
+ ) : (
+ <ul className="space-y-2">
+ {rooms.map((room) => (
+ <li key={room.id} className="text-xs flex items-center justify-between gap-3">
+ <span className="text-gray-300 truncate">
+ <span className="uppercase text-[10px] text-gray-500 mr-2">{room.provider}</span>
+ {room.channel_name || room.channel_id}
+ {room.state === 'closed' && <span className="text-gray-600 ml-2">(closed)</span>}
+ </span>
+ <SyncState room={room} />
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ );
+}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index fd03befde..aca6b423f 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -7374,3 +7374,40 @@ export const evaluationsApi = {
`${API_BASE}/api/v1/evaluations/replay/${id}/export` +
`?format=${format}&exclude_latency=${excludeLatency ? 'true' : 'false'}`,
};
+
+// ─── War rooms (depth 9.4) ───────────────────────────────────────────────────
+
+export interface WarRoom {
+ id: string;
+ case_id: string;
+ provider: string;
+ channel_id: string;
+ channel_name: string;
+ channel_url: string;
+ state: string;
+ opened_by: string;
+ /**
+ * `null` means the sweep has never run for this room, which is a different
+ * fact from "ran and had nothing to say". The panel renders them apart.
+ */
+ last_synced_at: string | null;
+ /** Empty on success. A room that has silently stopped mirroring is worse
+ * than one that was never opened, so this is shown in full. */
+ last_error: string;
+}
+
+export const warRoomApi = {
+ forCase: (caseId: string) => request<WarRoom[]>(`/api/v1/war-rooms/cases/${caseId}`),
+
+ open: (caseId: string, provider: 'slack' | 'teams', invite: string[] = []) =>
+ request<WarRoom>(`/api/v1/war-rooms/cases/${caseId}`, {
+ method: 'POST',
+ body: JSON.stringify({ provider, invite }),
+ }),
+
+ sync: (warRoomId: string) =>
+ request<{ posted: number; error: string | null }>(`/api/v1/war-rooms/${warRoomId}/sync`, { method: 'POST' }),
+
+ close: (warRoomId: string) =>
+ request<WarRoom>(`/api/v1/war-rooms/${warRoomId}/close`, { method: 'POST' }),
+};
diff --git a/services/api/app/main.py b/services/api/app/main.py
index e6a2a04d3..077954584 100644
--- a/services/api/app/main.py
+++ b/services/api/app/main.py
@@ -42,6 +42,7 @@ from app.workers.hunt_scheduler import run_forever as run_hunt_scheduler
from app.workers.oauth_refresh import run_forever as run_oauth_refresh
from app.workers.outbound_webhook_delivery import run_forever as run_outbound_webhook_delivery
from app.workers.report_scheduler import run_forever as run_report_scheduler
+from app.workers.war_room_sync import run_forever as run_war_room_sync
from app.workers.retention_purge import run_forever as run_retention_purge
from app.workers.retro_hunt_consumer import run_forever as run_retro_hunt_consumer
from app.workers.shadow_reconcile import run_forever as run_shadow_reconcile
@@ -569,6 +570,24 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
except Exception as exc:
logger.warning("retro_hunt consumer failed to start", error=str(exc))
+ # Depth 9.4. Keeps every open war room current with its case. "Posts the
+ # timeline and verdicts as they change" is a sweep, and without one the
+ # feature is a button that posts a header once and goes quiet — worse
+ # than not opening the channel, because the people in it believe they
+ # are watching the case.
+ #
+ # Deliberately not under the scheduler lock, same reasoning as the
+ # outbound-webhook worker: every post is keyed and the posts table has a
+ # unique constraint, so two replicas racing end with one post and one
+ # `ON CONFLICT DO NOTHING`, while a single lock holder stalling every
+ # tenant's rooms would be the worse failure.
+ war_room_sync_task: asyncio.Task | None = None
+ try:
+ war_room_sync_task = asyncio.create_task(run_war_room_sync(), name="war_room_sync_worker")
+ logger.info("war_room_sync worker started")
+ except Exception as exc:
+ logger.warning("war_room_sync worker failed to start", error=str(exc))
+
# Phase 2.6 — flip /readyz to 200. All lifespan-managed
# dependencies have been touched at this point (DB, Redis,
# Neo4j, schedulers); the load balancer can route traffic
@@ -688,7 +707,11 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
except Exception as exc:
logger.warning("shadow_reconcile worker shutdown error", error=type(exc).__name__)
- for task, label in ((report_scheduler_task, "report_scheduler"), (outbound_webhook_task, "outbound_webhook")):
+ for task, label in (
+ (report_scheduler_task, "report_scheduler"),
+ (outbound_webhook_task, "outbound_webhook"),
+ (war_room_sync_task, "war_room_sync"),
+ ):
if task is not None and not task.done():
task.cancel()
try:
diff --git a/services/api/app/services/war_room.py b/services/api/app/services/war_room.py
index 95011ee2e..8491a88a0 100644
--- a/services/api/app/services/war_room.py
+++ b/services/api/app/services/war_room.py
@@ -291,14 +291,11 @@ async def sync_war_room(
if case is None:
return {"posted": 0, "error": "the case no longer exists"}
- known = {
- row
- for row in (
- await db.execute(text("SELECT event_key FROM aisoc_war_room_posts WHERE war_room_id = :id").bindparams(id=war_room["id"]))
- )
+ known = set(
+ (await db.execute(text("SELECT event_key FROM aisoc_war_room_posts WHERE war_room_id = :id").bindparams(id=war_room["id"])))
.scalars()
.all()
- }
+ )
pending = [(key, body) for key, body in case_events(dict(case)) if key not in known]
if not pending:
await db.execute(
diff --git a/services/api/app/workers/war_room_sync.py b/services/api/app/workers/war_room_sync.py
new file mode 100644
index 000000000..103ee33a8
--- /dev/null
+++ b/services/api/app/workers/war_room_sync.py
@@ -0,0 +1,94 @@
+"""Keep every open war room current with its case.
+
+Depth plan 9.4. "Posts the timeline and verdicts as they change" is a sweep,
+and without one the feature is a button that posts a header once and then
+goes quiet — which is worse than not opening the channel, because people in
+it believe they are watching the case.
+
+Safe on several replicas. Each post is keyed by a fingerprint of the event
+and ``aisoc_war_room_posts`` carries a unique constraint on
+``(war_room_id, event_key)``, so two workers racing on the same room end
+with one post and one ``ON CONFLICT DO NOTHING``. That is why the sweep is
+deliberately *not* under the scheduler lock: a single lock holder stalling
+every tenant's war rooms is a worse failure than an occasional duplicate
+attempt that the constraint already absorbs.
+
+A room whose sync fails keeps its place in the queue and records
+``last_error``. It is not disabled: a chat outage is transient and a room
+that quietly stops mirroring is the thing this worker exists to prevent.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+
+import structlog
+from sqlalchemy import text
+
+from app.db.database import AsyncSessionLocal
+from app.db.rls import set_rls_context
+from app.services.war_room import sync_war_room
+
+logger = structlog.get_logger(__name__)
+
+__all__ = ["run_forever", "run_once"]
+
+#: A minute. Chat is a human-latency surface: posting a status change within
+#: a minute is indistinguishable from instant to somebody reading a channel,
+#: and a tighter loop buys nothing but vendor rate limit.
+POLL_INTERVAL_SECONDS = int(os.environ.get("AISOC_WAR_ROOM_SYNC_INTERVAL", "60"))
+
+#: How many rooms one pass touches. Bounded so a tenant with hundreds cannot
+#: make one tick run for minutes and starve the rest.
+BATCH = int(os.environ.get("AISOC_WAR_ROOM_SYNC_BATCH", "50"))
+
+#: Oldest sync first, never-synced before that. A room that has just been
+#: opened and has never been told anything is the most urgent one.
+_DUE_SQL = """
+SELECT * FROM aisoc_case_war_rooms
+WHERE state = 'open'
+ORDER BY last_synced_at ASC NULLS FIRST
+LIMIT :limit
+"""
+
+
+async def run_once() -> int:
+ """Sync every due room. Returns how many posts were made."""
+ posted = 0
+ async with AsyncSessionLocal() as db:
+ rooms = (await db.execute(text(_DUE_SQL).bindparams(limit=BATCH))).mappings().all()
+ for room in rooms:
+ # Bind the tenant per room. The sweep reads across tenants by
+ # design — it is a platform worker — so it sets the context
+ # explicitly for each one rather than running with none, which
+ # would leave the writes unscoped.
+ await set_rls_context(db, room["tenant_id"])
+ try:
+ result = await sync_war_room(db, tenant_id=room["tenant_id"], war_room=dict(room))
+ posted += result["posted"]
+ if result["error"]:
+ logger.warning(
+ "war_room.sync_failed",
+ war_room_id=str(room["id"]),
+ provider=room["provider"],
+ error=result["error"][:300],
+ )
+ except Exception as exc: # noqa: BLE001 — one bad room must not stop the sweep
+ logger.warning("war_room.sync_raised", war_room_id=str(room["id"]), error=str(exc)[:300])
+ await db.rollback()
+ continue
+ await db.commit()
+ return posted
+
+
+async def run_forever() -> None:
+ """Poll until cancelled. A failed pass must not end the loop."""
+ while True:
+ try:
+ await run_once()
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001
+ logger.warning("war_room.sweep_failed", error=str(exc)[:300])
+ await asyncio.sleep(POLL_INTERVAL_SECONDS)