ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
fix(dashboard): centralize campaign cache invalidation, auto-reset selection on delete, and enhance UX
Mafifrizi3d9f7cb46bb7
diff --git a/README.md b/README.mdindex 2e8c072..e434c87 100644--- a/README.md+++ b/README.md@@ -129,10 +129,13 @@ The ARES Platform features a high-performance, responsive operator dashboard eng- **The Problem Solved**: Aggregates scattered offensive metrics into a single real-time operational pane without requiring manual status queries.- **Key Capabilities**:- - **Unified Scope Context**: Switch seamlessly between `Scope: Global / All` (enterprise-wide telemetry) and specific engagement campaigns (`AD Lab Simulation`).- - **Finding Severity Breakdown**: Live counters for Critical, High, Medium, Low, and Informational findings with CVSS v3 score tracking.- - **Telemetry & Worker Health**: Monitor background task queue depth, execution error rates, and active worker statuses in real time.- - **Audited Activity Stream**: Immutable event log tracking every module dispatch, credential discovery, and lateral progression.+ - **Operational Design System**: Engineered with high-density visual hierarchy (inspired by Grafana, Linear, and Sentry) — featuring subtle left-accented contextual panels (`panel-subtle`), dynamic reactive topbar health indicators, and distinct dashed progress tracks for uninitialized metric baselines.+ - **Actionable Engagement Insights**: Replaces redundant raw counts with contextual security posture insights:+ - *Engagement Posture*: Clear state delineation (`Staged`, `Executing`, or `Standby`) distinguishing scoped targets from executing campaigns.+ - *Execution Health*: Real-time monitor of pipeline anomalies, module execution failures, and enclave stability.+ - *Attack Surface*: Live tracking of discovered hosts, credential pivots, and network penetration depth.+ - **Telemetry & Pipeline Ingestion**: Real-time worker pool throughput, P95 task duration, and live event ingestion indicators.+ - **Tactical Fresh-Install Hero**: Automatic empty-state fallback with a centered initialization CTA and minimal readiness strip when starting with zero campaigns.---@@ -150,8 +153,9 @@ The ARES Platform features a high-performance, responsive operator dashboard eng- **The Problem Solved**: Prevents catastrophic out-of-scope scanning and eliminates unencrypted credential files on operator laptops.- **Key Capabilities**:+ - **Persistent Operator Guidance**: Persistent `<label>` definitions across all campaign pickers and parameter inputs, preventing operator ambiguity during rapid engagements.- **Hard CIDR Whitelists**: Network-level boundary enforcement. The engine intercepts and drops any request targeting unapproved IP addresses or subnets.- - **Noise Profiles & Jitter**: Configure engagement throttle levels (`Stealth`, `Low Noise`, `Aggressive`) with randomized delay distributions.+ - **Noise Profiles & Jitter**: Configure engagement throttle levels (`Stealth`, `Normal`, `Aggressive`) with randomized delay distributions.- **AES-256 Encrypted Enclave Vault**: Harvested NTLM hashes, Kerberos tickets, and service credentials are encrypted at rest with AES-256-GCM.- **Clean Teardown Workflows**: Single-click campaign deletion that securely cleans up all associated database rows, graph vertices, and temporary artifacts.@@ -172,6 +176,7 @@ The ARES Platform features a high-performance, responsive operator dashboard eng- **The Problem Solved**: Replaces unvalidated, unreliable GitHub scripts with typed, reproducible, and auditable adversary modules.- **Key Capabilities**:- **Comprehensive Vector Coverage**: 60+ modular techniques covering Active Directory (`ad.kerberoast`, `ad.adcs`, `ad.enum_users`), Windows (`windows.uac_bypass`), Linux, Cloud (AWS, Azure, GCP), and Network infrastructure.+ - **Streamlined Execution Panel**: Clean execution view with persistent field labels, demoted low-weight dependency hints, and focused on-submit validation replacing intrusive default warning cards.- **Dynamic Typed Schemas**: UI forms are generated dynamically from Python Pydantic models with strict validation.- **Dry-Run Safety Engine**: Validate target responsiveness, parameters, and expected outcome before transmitting offensive traffic.- **Role-Gated Execution**: Operator and Team Lead permissions required for execution; sensitive high-noise modules require explicit confirmation.@@ -213,6 +218,7 @@ The ARES Platform features a high-performance, responsive operator dashboard eng- **The Problem Solved**: Eliminates the 40+ hours typically spent manually writing, formatting, and redacting pentest reports.- **Key Capabilities**:+ - **Structured Generation Grid**: Aligned multi-column layout with persistent `<label>` elements (`Target Campaign`, `Export Format`) and clean inline validation error feedback.- **Multi-Format Export**: One-click generation of **PDF**, **HTML**, **Markdown**, and **JSON** deliverables.- **Automated Headless PDF Engine**: Integrated fallback using Microsoft Edge / Chromium headless mode for clean PDF export without complex GTK dependencies on Windows.- **Automated Evidence Redaction**: Automatically redacts sensitive raw passwords and private keys in customer deliverables while retaining audit proofs.@@ -234,8 +240,9 @@ The ARES Platform features a high-performance, responsive operator dashboard eng- **The Problem Solved**: Coordinates multi-module attack chains autonomously without requiring constant manual operator intervention.- **Key Capabilities**:- - **Goal-Directed Execution Engine**: Define high-level objectives (`domain_admin`, `full_compromise`, `cloud_audit`), and let the engine chain techniques.- - **Plug-and-Play AI Planners**: Integrate with Anthropic Claude, OpenAI, or local Ollama models to analyze engagement context and propose optimal next steps.+ - **Dynamic Engine Verification**: Real-time asynchronous healthchecks against local Ollama daemons (`GET /api/tags`) with sub-second timeouts and TTL caching, paired with dynamic server-side cloud key verification (`Claude`, `OpenAI`).+ - **Clean Operator-Centric Design**: Persistent field labels (`Target Campaign`, `Strategic Objective`, `AI Planning Engine`, `Explicit Authorizations`), human-readable goal descriptions, and complete elimination of server environment variable leakage in UI labels.+ - **Focused On-Submit Validation**: Warning boxes removed from default page render; validation errors display inline beneath target fields only upon execution attempt.- **Adaptive Containment Governor**: Continuously evaluates defensive telemetry and noise thresholds, automatically slowing down or aborting aggressive actions when detection risk peaks.---diff --git a/ares/api/server.py b/ares/api/server.pyindex 3b5efb5..d2dc611 100644--- a/ares/api/server.py+++ b/ares/api/server.py@@ -1901,12 +1901,15 @@ async def list_campaigns("X-Total-Count": str(total),"X-Page": str(page),"X-Per-Page": str(per_page),+ "Cache-Control": "no-cache, no-store, must-revalidate",+ "Pragma": "no-cache",},)@app.get("/campaigns/{campaign_id}", tags=["campaigns"])async def get_campaign(+ response: Response,campaign_id: str,actor: AuthenticatedUser = _api_key_read_dep,db: AresDatabase = Depends(get_db),@@ -1915,6 +1918,8 @@ async def get_campaign(if not c:raise HTTPException(404, "Campaign not found")await _require_campaign_access(c, actor)+ response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"+ response.headers["Pragma"] = "no-cache"return c@@ -1994,6 +1999,7 @@ async def issue_campaign_websocket_ticket(@app.delete("/campaigns/{campaign_id}", tags=["campaigns"])async def delete_campaign(+ response: Response,campaign_id: str,actor: AuthenticatedUser = Depends(require_team_lead()),db: AresDatabase = Depends(get_db),@@ -2013,6 +2019,8 @@ async def delete_campaign(f"id={campaign_id} name={c.get('name', '')} reports_deleted={deleted_reports}",None,)+ response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"+ response.headers["Pragma"] = "no-cache"return {"status": "deleted", "campaign_id": campaign_id}@@ -2688,6 +2696,41 @@ async def start_autonomous_engagement(}+_ollama_status_cache: tuple[float, bool] = (0.0, False)+++async def _check_ollama_reachable() -> bool:+ """Check if local Ollama daemon is reachable. Fail-safe: catches all exceptions, never raises."""+ global _ollama_status_cache+ import time+ now = time.monotonic()+ if now - _ollama_status_cache[0] < 10.0:+ return _ollama_status_cache[1]++ raw_url = (+ os.environ.get("OLLAMA_HOST")+ or os.environ.get("OLLAMA_BASE_URL")+ or "http://127.0.0.1:11434"+ ).strip().rstrip("/")+ if not raw_url.startswith("http://") and not raw_url.startswith("https://"):+ raw_url = f"http://{raw_url}"+ if "://localhost:" in raw_url:+ raw_url = raw_url.replace("://localhost:", "://127.0.0.1:")++ is_ok = False+ try:+ import httpx+ async with httpx.AsyncClient(timeout=0.8, follow_redirects=False) as client:+ resp = await client.get(f"{raw_url}/api/tags")+ is_ok = resp.status_code == 200+ except Exception:+ # Failsafe: catch all timeout, connection refused, DNS failure, or non-200 protocol errors+ is_ok = False++ _ollama_status_cache = (now, is_ok)+ return is_ok++@app.get("/strategy/active", tags=["strategy"])async def list_active_engagements(actor: AuthenticatedUser = Depends(require_operator()),@@ -2698,11 +2741,17 @@ async def list_active_engagements("ARES_MAX_ENGAGEMENTS", _MAX_CONCURRENT_ENGAGEMENTS))+ ollama_ready = await _check_ollama_reachable()return {"active_engagements": dict(_active_engagements),"count": len(_active_engagements),"max_allowed": _max,"slots_available": max(0, _max - len(_active_engagements)),+ "llm_backends": {+ "claude": bool(os.environ.get("ANTHROPIC_API_KEY")),+ "openai": bool(os.environ.get("OPENAI_API_KEY")),+ "local": ollama_ready,+ },}diff --git a/docs/assets/screenshots/dashboard-overview.png b/docs/assets/screenshots/dashboard-overview.pngindex 2a8252e..3c69ea7 100644Binary files a/docs/assets/screenshots/dashboard-overview.png and b/docs/assets/screenshots/dashboard-overview.png differdiff --git a/docs/assets/screenshots/dashboard-reports.png b/docs/assets/screenshots/dashboard-reports.pngindex d25c494..c0b1e4a 100644Binary files a/docs/assets/screenshots/dashboard-reports.png and b/docs/assets/screenshots/dashboard-reports.png differdiff --git a/docs/assets/screenshots/dashboard-strategy.png b/docs/assets/screenshots/dashboard-strategy.pngindex 7e7933b..ee99803 100644Binary files a/docs/assets/screenshots/dashboard-strategy.png and b/docs/assets/screenshots/dashboard-strategy.png differdiff --git a/docs/assets/screenshots/login-enclave.png b/docs/assets/screenshots/login-enclave.pngindex 3e0bb2f..48e8153 100644Binary files a/docs/assets/screenshots/login-enclave.png and b/docs/assets/screenshots/login-enclave.png differdiff --git a/frontend/src/features/dashboard/CampaignSync.test.tsx b/frontend/src/features/dashboard/CampaignSync.test.tsxnew file mode 100644index 0000000..83fec7a--- /dev/null+++ b/frontend/src/features/dashboard/CampaignSync.test.tsx@@ -0,0 +1,269 @@+// @vitest-environment jsdom+import "@testing-library/jest-dom/vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { MemoryRouter, Route, Routes } from "react-router-dom";+import type { Campaign } from "../../api/types";++let mockCampaigns: Campaign[] = [];++vi.mock("../auth/authContext", () => ({+ useAuth: () => ({+ user: { username: "admin", role: "team_lead" },+ loading: false,+ logout: vi.fn(),+ logoutAll: vi.fn()+ })+}));++vi.mock("../../api/client", async () => {+ const actual = await vi.importActual("../../api/client");+ return {+ ...actual,+ api: {+ health: vi.fn(async () => ({ status: "ok" })),+ telemetry: vi.fn(async () => ({})),+ campaigns: vi.fn(async () => [...mockCampaigns]),+ campaign: vi.fn(async (id: string) => mockCampaigns.find((c) => c.id === id) ?? null),+ deleteCampaign: vi.fn(async (id: string) => {+ const found = mockCampaigns.find((c) => c.id === id);+ if (!found) {+ throw new Error("Campaign not found");+ }+ mockCampaigns = mockCampaigns.filter((c) => c.id !== id);+ return { status: "deleted", campaign_id: id };+ }),+ modules: vi.fn(async () => []),+ templates: vi.fn(async () => []),+ reports: vi.fn(async () => ({ campaign_id: "", reports: [] })),+ monthlyStats: vi.fn(async () => ({ total: 0, confirmed_findings: 0, series: [] })),+ activeStrategy: vi.fn(async () => ({ active: false, llm_backends: { claude: true, openai: true, local: false } })),+ findings: vi.fn(async () => []),+ cvss: vi.fn(async () => ({})),+ diffCampaign: vi.fn(async () => ({})),+ executionChains: vi.fn(async () => []),+ runCampaign: vi.fn(async () => ({}))+ }+ };+});++import { api } from "../../api/client";+import { clearDashboardSession } from "./dashboardUiState";+import {+ CampaignsPage,+ DashboardShell,+ ModulesPage,+ OverviewPage,+ ReportsPage,+ StrategyPage+} from "./DashboardPages";++function renderWithShell(initialRoute = "/campaigns") {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ staleTime: 0+ }+ }+ });++ return render(+ <QueryClientProvider client={queryClient}>+ <MemoryRouter initialEntries={[initialRoute]}>+ <DashboardShell>+ <Routes>+ <Route path="/" element={<OverviewPage />} />+ <Route path="/campaigns" element={<CampaignsPage />} />+ <Route path="/modules" element={<ModulesPage />} />+ <Route path="/reports" element={<ReportsPage />} />+ <Route path="/strategy" element={<StrategyPage />} />+ </Routes>+ </DashboardShell>+ </MemoryRouter>+ </QueryClientProvider>+ );+}++describe("Campaign deletion state synchronization across consumers", () => {+ beforeEach(() => {+ sessionStorage.clear();+ localStorage.clear();+ clearDashboardSession();+ vi.spyOn(window, "confirm").mockReturnValue(true);+ mockCampaigns = [+ {+ id: "camp-001",+ name: "Enterprise Simulation",+ client: "Acme Corp",+ status: "created",+ noise_profile: "stealth",+ operator: "admin"+ },+ {+ id: "camp-002",+ name: "AD Lab Pivot",+ client: "Internal",+ status: "created",+ noise_profile: "normal",+ operator: "admin"+ }+ ];+ });++ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ });++ it("synchronously removes deleted campaign from badge, scope dropdown, table, and selection without page refresh", async () => {+ renderWithShell("/campaigns");++ // Wait for initial load+ await waitFor(() => {+ expect(screen.getAllByText("Enterprise Simulation").length).toBeGreaterThanOrEqual(1);+ expect(screen.getAllByText("AD Lab Pivot").length).toBeGreaterThanOrEqual(1);+ });++ // 1. Assert initial badge count in sidebar is "2"+ const navCountBadges = document.querySelectorAll(".nav-count-badge");+ const campaignsBadge = Array.from(navCountBadges).find(+ (el) => el.closest("a")?.getAttribute("href") === "/campaigns"+ );+ expect(campaignsBadge?.textContent).toBe("2");++ // 2. Switch to Scope tab to select camp-001 and trigger deletion+ const scopeTabBtn = screen.getByRole("tab", { name: "Scope" });+ fireEvent.click(scopeTabBtn);++ const targetPicker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;+ expect(targetPicker).toBeInTheDocument();+ expect(targetPicker.querySelectorAll("option").length).toBe(3); // "Select campaign" + 2 campaigns++ // Select camp-001+ fireEvent.change(targetPicker, { target: { value: "camp-001" } });++ // The Delete button should be enabled for the selected campaign+ const deleteBtn = screen.getByRole("button", { name: "Delete" });+ expect(deleteBtn).not.toBeDisabled();++ // 3. Click Delete+ await act(async () => {+ fireEvent.click(deleteBtn);+ });++ // 4. Assert backend delete was called with camp-001+ await waitFor(() => {+ expect(api.deleteCampaign).toHaveBeenCalledWith("camp-001");+ });++ // 5. Assert camp-001 is immediately removed from the UI:+ // User was automatically switched to "List" tab+ await waitFor(() => {+ expect(screen.queryByText("Enterprise Simulation")).not.toBeInTheDocument();+ expect(screen.getAllByText("AD Lab Pivot").length).toBeGreaterThanOrEqual(1);+ });++ // 6. Assert sidebar badge count automatically updated to "1"+ const updatedBadge = Array.from(document.querySelectorAll(".nav-count-badge")).find(+ (el) => el.closest("a")?.getAttribute("href") === "/campaigns"+ );+ expect(updatedBadge?.textContent).toBe("1");++ // 7. Assert topbar scope select no longer includes camp-001 and defaulted to Global+ const topbarSelect = screen.getByLabelText("Active campaign scope") as HTMLSelectElement;+ const topbarOptions = Array.from(topbarSelect.options).map((opt) => opt.value);+ expect(topbarOptions).not.toContain("camp-001");+ expect(topbarOptions).toContain("camp-002");+ expect(topbarSelect.value).toBe(""); // Reset to empty / Global++ // 8. Navigate to Scope tab again and verify Target Campaign dropdown has only camp-002+ fireEvent.click(screen.getByRole("tab", { name: "Scope" }));+ const refreshedPicker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;+ const refreshedOptions = Array.from(refreshedPicker.options).map((opt) => opt.value);+ expect(refreshedOptions).not.toContain("camp-001");+ expect(refreshedOptions).toContain("camp-002");+ expect(refreshedPicker.value).toBe(""); // Value reset, not stuck on deleted campaign++ // 9. Navigate to Overview and assert Campaign Activity table only contains camp-002+ fireEvent.click(screen.getByRole("link", { name: /Overview/i }));+ await waitFor(() => {+ expect(screen.queryByText("Enterprise Simulation")).not.toBeInTheDocument();+ expect(screen.getAllByText("AD Lab Pivot").length).toBeGreaterThanOrEqual(1);+ });++ // 10. Navigate to Strategy and assert Target Campaign dropdown only contains camp-002+ fireEvent.click(screen.getByRole("link", { name: /Strategy/i }));+ await waitFor(() => {+ const stratPicker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;+ const stratOptions = Array.from(stratPicker.options).map((opt) => opt.value);+ expect(stratOptions).not.toContain("camp-001");+ expect(stratOptions).toContain("camp-002");+ });++ // 11. Navigate to Modules, switch to Run Panel, and assert Target Campaign dropdown has only camp-002+ fireEvent.click(screen.getByRole("link", { name: /Modules/i }));+ fireEvent.click(screen.getByRole("tab", { name: "Run Panel" }));+ await waitFor(() => {+ const modPicker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;+ const modOptions = Array.from(modPicker.options).map((opt) => opt.value);+ expect(modOptions).not.toContain("camp-001");+ expect(modOptions).toContain("camp-002");+ });++ // 12. Navigate to Reports and assert Target Campaign dropdown has only camp-002+ fireEvent.click(screen.getByRole("link", { name: /Reports/i }));+ await waitFor(() => {+ const repPicker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;+ const repOptions = Array.from(repPicker.options).map((opt) => opt.value);+ expect(repOptions).not.toContain("camp-001");+ expect(repOptions).toContain("camp-002");+ });+ });++ it("deleting all campaigns immediately renders the Fresh Install Hero in Overview", async () => {+ // Start with 1 campaign+ mockCampaigns = [+ {+ id: "camp-002",+ name: "AD Lab Pivot",+ client: "Internal",+ status: "created",+ noise_profile: "normal",+ operator: "admin"+ }+ ];++ renderWithShell("/campaigns");++ await waitFor(() => {+ expect(screen.getAllByText("AD Lab Pivot").length).toBeGreaterThanOrEqual(1);+ });++ // Go to Scope tab and delete the last campaign+ fireEvent.click(screen.getByRole("tab", { name: "Scope" }));+ const picker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;+ fireEvent.change(picker, { target: { value: "camp-002" } });++ const deleteBtn = screen.getByRole("button", { name: "Delete" });+ await act(async () => {+ fireEvent.click(deleteBtn);+ });++ await waitFor(() => {+ expect(api.deleteCampaign).toHaveBeenCalledWith("camp-002");+ });++ // In List tab, the empty state message should now appear+ await waitFor(() => {+ expect(screen.getByText(/No campaigns yet/i)).toBeInTheDocument();+ });++ // Sidebar badge should be gone+ const badge = Array.from(document.querySelectorAll(".nav-count-badge")).find(+ (el) => el.closest("a")?.getAttribute("href") === "/campaigns"+ );+ expect(badge).toBeUndefined();+ });+});diff --git a/frontend/src/features/dashboard/DashboardPages.tsx b/frontend/src/features/dashboard/DashboardPages.tsxindex 0c69901..dd72d77 100644--- a/frontend/src/features/dashboard/DashboardPages.tsx+++ b/frontend/src/features/dashboard/DashboardPages.tsx@@ -4,8 +4,11 @@ import {CheckCircle2,ChevronDown,Copy,+ Info,+ Layers,Loader2,Menu,+ Plus,Search,ShieldAlert,ShieldCheck,@@ -17,6 +20,7 @@ import {FormEvent,KeyboardEvent,ReactNode,+ useCallback,useEffect,useMemo,useRef,@@ -331,6 +335,63 @@ export function DashboardShell({ children }: { children: ReactNode }) {});const telemetrySnapshot = telemetry.data as TelemetrySnapshot | undefined;+ const queryClient = useQueryClient();+ const deleteCampaignMutation = useMutation({+ mutationFn: (id: string) => api.deleteCampaign(id),+ onSuccess: async (_, id) => {+ queryClient.setQueryData<Campaign[]>(["campaigns"], (old) =>+ old ? old.filter((c) => c.id !== id) : []+ );+ queryClient.removeQueries({ queryKey: ["campaign", id] });+ queryClient.removeQueries({ queryKey: ["findings", id] });+ queryClient.removeQueries({ queryKey: ["cvss", id] });+ queryClient.removeQueries({ queryKey: ["reports", id] });++ if (selectedCampaignId === id) {+ setSelectedCampaignId("");+ }+ if (liveCampaignId === id) {+ setLiveCampaignId("");+ setLiveConnected(false);+ }++ await queryClient.invalidateQueries({ queryKey: ["telemetry"], refetchType: "all" });+ await queryClient.invalidateQueries({ queryKey: ["monthlyStats"], refetchType: "all" });+ await queryClient.invalidateQueries({ queryKey: ["campaigns"], refetchType: "all" });+ }+ });++ const deleteCampaign = useCallback(+ async (id: string): Promise<boolean> => {+ try {+ await deleteCampaignMutation.mutateAsync(id);+ return true;+ } catch {+ return false;+ }+ },+ [deleteCampaignMutation]+ );++ useEffect(() => {+ if (selectedCampaignId && campaigns.isSuccess) {+ const exists = (campaigns.data ?? []).some((c) => c.id === selectedCampaignId);+ if (!exists) {+ setSelectedCampaignId("");+ }+ }+ }, [selectedCampaignId, campaigns.data, campaigns.isSuccess, setSelectedCampaignId]);++ useEffect(() => {+ if (liveCampaignId && campaigns.isSuccess) {+ const exists = (campaigns.data ?? []).some((c) => c.id === liveCampaignId);+ if (!exists) {+ setLiveCampaignId("");+ setLiveConnected(false);+ }+ }+ }, [liveCampaignId, campaigns.data, campaigns.isSuccess, setLiveCampaignId, setLiveConnected]);+useCampaignEventSocket({campaignId: liveCampaignId,enabled: liveConnected,@@ -338,6 +399,8 @@ export function DashboardShell({ children }: { children: ReactNode }) {onEvent: (event) => setLiveEvents((items) => [event, ...items].slice(0, 100))});+ const campaignList = campaigns.data ?? [];+const dashboardUi = useMemo<DashboardUiState>(() => ({selectedCampaignId,@@ -347,12 +410,22 @@ export function DashboardShell({ children }: { children: ReactNode }) {liveConnected,setLiveConnected,liveEvents,- clearLiveEvents: () => setLiveEvents([])+ clearLiveEvents: () => setLiveEvents([]),+ campaigns: campaignList,+ campaignsLoading: campaigns.isLoading,+ campaignsError: campaigns.error,+ deleteCampaign,+ refetchCampaigns: () => queryClient.invalidateQueries({ queryKey: ["campaigns"], refetchType: "all" })}),[+ campaignList,+ campaigns.error,+ campaigns.isLoading,+ deleteCampaign,liveCampaignId,liveConnected,liveEvents,+ queryClient,selectedCampaignId,setLiveCampaignId,setLiveConnected,@@ -603,7 +676,7 @@ export function DashboardShell({ children }: { children: ReactNode }) {<selectclassName="topbar-scope-select"aria-label="Active campaign scope"- value={selectedCampaignId}+ value={selectedCampaignId && campaignList.some((c) => c.id === selectedCampaignId) ? selectedCampaignId : ""}onChange={(e) => {setSelectedCampaignId(e.target.value);if (e.target.value) {@@ -612,7 +685,7 @@ export function DashboardShell({ children }: { children: ReactNode }) {}}><option value="">Scope: Global / All</option>- {(campaigns.data ?? []).map((c) => (+ {campaignList.map((c) => (<option key={c.id} value={c.id}>{c.name || c.id.slice(0, 12)}</option>@@ -668,26 +741,54 @@ export function DashboardShell({ children }: { children: ReactNode }) {<div className="topbar-right">{/* Telemetry Operational Status */}<div className="relative">- <button- className="topbar-status-btn"- type="button"- aria-label="System operational status"- aria-expanded={telemetryOpen}- onClick={() => setTelemetryOpen((v) => !v)}- title="System operational health and telemetry status"- >- <span className={`status-dot ${health.isSuccess && !telemetry.isError ? "online" : "warning"}`} />- <span className="status-title">{health.isSuccess ? "Operational" : "Connecting"}</span>- <span className="status-pill-count font-mono">- {telemetrySnapshot ? `${metricNumber(telemetrySnapshot.modules, "total")} runs` : "v6.0"}- </span>- </button>+ {(() => {+ const healthSnapshot = health.data as Record<string, unknown> | undefined;+ const healthStatus = String(healthSnapshot?.status ?? "").toLowerCase();+ const isHealthOk = health.isSuccess && healthStatus === "ok";+ const isHealthDegraded = health.isSuccess && healthStatus === "degraded";+ const isHealthOffline = health.isError;+ const isHealthConnecting = health.isLoading;++ let topbarDotClass = "online";+ let topbarText = "Operational";++ if (isHealthOffline) {+ topbarDotClass = "danger";+ topbarText = "Offline";+ } else if (isHealthConnecting) {+ topbarDotClass = "warning";+ topbarText = "Connecting";+ } else if (isHealthDegraded || telemetry.isError) {+ topbarDotClass = "warning";+ topbarText = isHealthDegraded ? "Degraded" : "Telemetry Lag";+ } else if (isHealthOk) {+ topbarDotClass = "online";+ topbarText = "Operational";+ }++ return (+ <button+ className="topbar-status-btn"+ type="button"+ aria-label="System operational status"+ aria-expanded={telemetryOpen}+ onClick={() => setTelemetryOpen((v) => !v)}+ title={`System operational health: ${topbarText} (API: ${healthStatus || "pending"})`}+ >+ <span className={`status-dot ${topbarDotClass}`} />+ <span className="status-title">{topbarText}</span>+ <span className="status-pill-count font-mono">+ {telemetrySnapshot ? `${metricNumber(telemetrySnapshot.modules, "total")} runs` : healthSnapshot?.version ? `v${healthSnapshot.version}` : "v6.0"}+ </span>+ </button>+ );+ })()}{telemetryOpen && (<aside className="telemetry-popover" aria-label="Enclave telemetry quick view"><div className="telemetry-popover-header"><div className="flex items-center gap-2">- <span className="status-dot online" />+ <span className={`status-dot ${health.isSuccess && !telemetry.isError ? "online" : "warning"}`} /><strong>Enclave Subsystem Health</strong></div><button className="icon-button icon-button-small" onClick={() => setTelemetryOpen(false)} aria-label="Close telemetry view" type="button">@@ -695,6 +796,10 @@ export function DashboardShell({ children }: { children: ReactNode }) {</button></div><div className="telemetry-popover-grid">+ <div className="popover-stat">+ <span>API Backend</span>+ <strong>{health.isSuccess ? String((health.data as Record<string, unknown> | undefined)?.status ?? "ok").toUpperCase() : health.isError ? "OFFLINE" : "CHECKING"}</strong>+ </div><div className="popover-stat"><span>Worker Pool</span><strong>{metricNumber(telemetrySnapshot?.workers, "active")} active</strong>@@ -703,15 +808,11 @@ export function DashboardShell({ children }: { children: ReactNode }) {<span>Task Queue</span><strong>{metricNumber(telemetrySnapshot?.queue, "depth")} queued</strong></div>- <div className="popover-stat">- <span>Module Error Rate</span>- <strong>{telemetrySnapshot ? `${formatRate(metricNumber(telemetrySnapshot.modules, "error_rate"))}` : "0%"}</strong>- </div><div className="popover-stat"><span>Live Ingest</span><div className="mt-0.5 flex items-center gap-1.5">- <span className={`h-1.5 w-1.5 rounded-full ${liveConnected ? "bg-emerald-400" : "bg-zinc-500"}`} />- <strong className="!mt-0 text-zinc-100">{liveConnected ? "Connected" : "Standby"}</strong>+ <span className={`h-1.5 w-1.5 rounded-full ${telemetry.isSuccess ? "bg-emerald-400" : "bg-zinc-500"}`} />+ <strong className="!mt-0 text-zinc-100">{telemetry.isSuccess ? "Active" : "Standby"}</strong></div></div></div>@@ -821,32 +922,169 @@ export function DashboardShell({ children }: { children: ReactNode }) {}export function OverviewPage() {+ const navigate = useNavigate();+ const writeDashboardSession = useDashboardSessionWriter();+ const { campaigns: campaignList, campaignsLoading } = useDashboardUi();const telemetry = useQuery({ queryKey: ["telemetry"], queryFn: api.telemetry });const monthlyStats = useQuery({ queryKey: ["monthlyStats"], queryFn: api.monthlyStats });- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });const snapshot = telemetry.data as TelemetrySnapshot | undefined;const monthlyData = monthlyStats.data as MonthlyFindingStats | undefined;- const campaignList = campaigns.data ?? [];- const activeCampaigns = campaignList.filter((campaign) => String(campaign.status ?? "").toLowerCase() !== "deleted").length;+ const nonDeletedCampaigns = campaignList.filter(+ (campaign) => String(campaign.status ?? "").toLowerCase() !== "deleted"+ );+ const runningCampaigns = nonDeletedCampaigns.filter((campaign) =>+ ["running", "active", "executing"].includes(String(campaign.status ?? "").toLowerCase())+ );+ const trackedCount = nonDeletedCampaigns.length;+ const runningCount = runningCampaigns.length;+const findings = typeof monthlyData?.confirmed_findings === "number" ? monthlyData.confirmed_findings : 0;const monthlyTotal = typeof monthlyData?.total === "number" ? monthlyData.total : 0;const monthlySeries = normalizeMonthlySeries(monthlyData?.period, monthlyData?.series);++ // Dynamic header status subtitle (strictly distinguish running execution vs in-scope campaigns)+ let overviewSubtitle: string;+ if (trackedCount === 0) {+ overviewSubtitle = "Enclave standby · No campaigns in scope · Ready for campaign deployment";+ } else if (runningCount > 0) {+ overviewSubtitle = `${runningCount} active execution${runningCount === 1 ? "" : "s"} · ${trackedCount} in scope · Enclave telemetry streaming`;+ } else {+ overviewSubtitle = `${trackedCount} campaign${trackedCount === 1 ? "" : "s"} in scope · Telemetry pipeline standby · Fail-closed policy enforced`;+ }++ // Fresh install empty-state (Task 5)+ if (!campaignsLoading && trackedCount === 0) {+ return (+ <Page title="Overview" subtitle={overviewSubtitle}>+ <div className="dashboard-empty-hero">+ <div className="fresh-hero-icon-wrap">+ <ShieldAlert size={32} className="text-rose-500" />+ </div>+ <h2>No Campaigns Initialized</h2>+ <p>+ Initialize an authorized red-team engagement to define target boundaries,+ configure CIDR scopes, and execute automated validation modules.+ </p>+ <div className="fresh-hero-actions">+ <button+ className="btn btn-primary flex items-center gap-2 px-4 py-2 text-sm font-semibold"+ onClick={() => {+ writeDashboardSession("ares.dashboard.campaigns.tab", "List");+ navigate("/campaigns");+ }}+ type="button"+ >+ <Plus size={16} />+ <span>Create First Campaign</span>+ </button>+ <button+ className="btn flex items-center gap-2 px-4 py-2 text-sm"+ onClick={() => navigate("/modules")}+ type="button"+ >+ <Layers size={15} />+ <span>Browse Module Catalog</span>+ </button>+ </div>+ </div>++ <div className="fresh-readiness-panel">+ <div className="telemetry-strip flex items-center justify-between text-xs text-zinc-400">+ <div className="flex items-center gap-5">+ <span><strong className="text-zinc-200">Runtime:</strong> Ready</span>+ <span><strong className="text-zinc-200">Worker Pool:</strong> {metricNumber(snapshot?.workers, "active")} active</span>+ <span><strong className="text-zinc-200">Task Queue:</strong> {metricNumber(snapshot?.queue, "depth")} queued</span>+ </div>+ <span className="text-zinc-500 font-mono text-[11px]">Awaiting first engagement initialization</span>+ </div>+ </div>+ </Page>+ );+ }++ // Tactical operational highlights (Task 2 & 3)+ const failedRuns = metricNumber(snapshot?.modules, "failed");+ const errorRate = metricNumber(snapshot?.modules, "error_rate");+ const hostsDiscovered = metricNumber(snapshot?.hosts, "discovered");+ const hostsOwned = metricNumberOrNull(snapshot?.hosts, "owned");+return (- <Page- title="Overview"- >+ <Page title="Overview" subtitle={overviewSubtitle}><div className="dashboard-grid"><TelemetryPanel snapshot={snapshot} loading={telemetry.isLoading} confirmedFindings={findings} /><div className="side-stack">- <section className="panel p-4">+ <section className="panel-subtle"><SectionHeader title="Highlights" /><div className="highlight-list">- <HighlightRow label="Active campaigns" value={String(activeCampaigns)} tone="low" detail="available engagements" />- <HighlightRow label="Findings" value={String(findings)} tone={findings > 0 ? "medium" : "low"} detail="confirmed observations" />- <HighlightRow label="Runtime" value={telemetry.isSuccess ? "Operational" : "Pending"} tone={telemetry.isSuccess ? "low" : "medium"} detail="telemetry stream" />+ {runningCount > 0 ? (+ <HighlightRow+ label="Engagement Posture"+ value={`${runningCount} Running`}+ tone="low"+ detail={`${runningCount} engagement${runningCount === 1 ? "" : "s"} actively executing validation modules`}+ />+ ) : trackedCount > 0 ? (+ <HighlightRow+ label="Engagement Posture"+ value="Staged"+ tone="neutral"+ detail={+ trackedCount === 1+ ? "1 campaign in scope — awaiting execution run"+ : `${trackedCount} campaigns in scope — awaiting execution run`+ }+ />+ ) : (+ <HighlightRow+ label="Engagement Posture"+ value="Standby"+ tone="neutral"+ detail="No active engagements"+ />+ )}++ {failedRuns > 0 ? (+ <HighlightRow+ label="Execution Health"+ value={`${failedRuns} Failed`}+ tone="high"+ detail={`${formatRate(errorRate)} module failure rate detected`}+ />+ ) : snapshot ? (+ <HighlightRow+ label="Execution Health"+ value="Nominal"+ tone="low"+ detail="Zero module execution errors recorded"+ />+ ) : (+ <HighlightRow+ label="Execution Health"+ value="Standby"+ tone="neutral"+ detail="Awaiting telemetry sample ingestion"+ />+ )}++ {hostsDiscovered > 0 ? (+ <HighlightRow+ label="Attack Surface"+ value={`${hostsDiscovered} Mapped`}+ tone={hostsOwned && hostsOwned > 0 ? "high" : "low"}+ detail={hostsOwned && hostsOwned > 0 ? `${hostsOwned} targets owned` : "Perimeter discovered, 0 targets owned"}+ />+ ) : (+ <HighlightRow+ label="Attack Surface"+ value="Unmapped"+ tone="neutral"+ detail="Run recon modules to map attack surface"+ />+ )}</div></section>- <section className="panel p-4">++ <section className="panel-subtle"><SectionHeader title="Monthly Statistics" /><div className="monthly-stat"><span>{formatMetric(monthlyTotal)}</span>@@ -893,8 +1131,13 @@ function normalizeMonthlySeries(export function CampaignsPage() {const queryClient = useQueryClient();- const { selectedCampaignId: selected, setSelectedCampaignId: setSelected } = useDashboardUi();- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });+ const {+ selectedCampaignId: selected,+ setSelectedCampaignId: setSelected,+ campaigns: campaignList,+ deleteCampaign,+ refetchCampaigns+ } = useDashboardUi();const [name, setName] = useSessionState("ares.dashboard.campaigns.create.name", "");const [client, setClient] = useSessionState("ares.dashboard.campaigns.create.client", "Internal");const [targets, setTargets] = useSessionState("ares.dashboard.campaigns.create.targets", "");@@ -903,6 +1146,8 @@ export function CampaignsPage() {const [createWarning, setCreateWarning] = useState("");const [otherId, setOtherId] = useSessionState("ares.dashboard.campaigns.compareId", "");const [activeTab, setActiveTab] = useSessionState("ares.dashboard.campaigns.tab", "List");+ const [deleteError, setDeleteError] = useState<unknown>(null);+ const [isDeleting, setIsDeleting] = useState(false);const detail = useQuery({queryKey: ["campaign", selected],queryFn: () => api.campaign(selected),@@ -940,28 +1185,37 @@ export function CampaignsPage() {setNoiseProfile("stealth");setCreateWarning("");setActiveTab("Scope");- void queryClient.invalidateQueries({ queryKey: ["campaigns"] });+ queryClient.setQueryData<Campaign[]>(["campaigns"], (old) => [campaign, ...(old ?? [])]);+ void queryClient.invalidateQueries({ queryKey: ["campaigns"], refetchType: "all" });}});const restore = useMutation({ mutationFn: () => api.restoreVault(selected) });const run = useMutation({mutationFn: () => api.runCampaign(selected, { plan: { stages: [] }, global_params: {}, dry_run: true })});- const remove = useMutation({- mutationFn: () => api.deleteCampaign(selected),- onSuccess: () => {- const deleted = selected;- setSelected("");- setOtherId("");- void queryClient.invalidateQueries({ queryKey: ["campaigns"] });- void queryClient.removeQueries({ queryKey: ["campaign", deleted] });- void queryClient.removeQueries({ queryKey: ["findings", deleted] });- void queryClient.removeQueries({ queryKey: ["cvss", deleted] });- void queryClient.removeQueries({ queryKey: ["reports", deleted] });- }- });- const campaignList = campaigns.data ?? [];+ const handleDelete = async (targetId: string) => {+ if (!targetId) return;+ if (!window.confirm("Delete this campaign and its stored findings, hosts, credentials, and loot?")) {+ return;+ }+ setIsDeleting(true);+ setDeleteError(null);+ try {+ const ok = await deleteCampaign(targetId);+ if (ok) {+ setSelected("");+ setOtherId("");+ setActiveTab("List");+ } else {+ setDeleteError("Failed to delete campaign");+ }+ } catch (err) {+ setDeleteError(err);+ } finally {+ setIsDeleting(false);+ }+ };return (<Page@@ -1005,15 +1259,19 @@ export function CampaignsPage() {<DataPanel title="Create Error" data={create.error} /></section><CampaignTable campaigns={campaignList} />- <DataPanel title="Campaign Error" data={campaigns.error} /></>)}{activeTab === "Scope" && (<><section className="panel p-4"><SectionHeader title="Campaign Detail" />- <CampaignPicker campaigns={campaignList} value={selected} onChange={setSelected} />- <CampaignScopeSummary campaign={detail.data ?? campaigns.data?.find((item) => item.id === selected)} loading={detail.isFetching} />+ <div>+ <label htmlFor="scope-campaign-select" className="block text-xs font-medium text-zinc-300 mb-1.5">+ Target Campaign+ </label>+ <CampaignPicker id="scope-campaign-select" campaigns={campaignList} value={selected} onChange={setSelected} />+ </div>+ <CampaignScopeSummary campaign={detail.data ?? campaignList.find((item) => item.id === selected)} loading={detail.isFetching} /><div className="mt-3 flex flex-wrap gap-2"><button className="btn" disabled={!selected} onClick={() => restore.mutate()}>Restore Vault@@ -1023,19 +1281,15 @@ export function CampaignsPage() {</button><buttonclassName="btn btn-danger"- disabled={!selected || remove.isPending}- onClick={() => {- if (window.confirm("Delete this campaign and its stored findings, hosts, credentials, and loot?")) {- remove.mutate();- }- }}+ disabled={!selected || isDeleting}+ onClick={() => handleDelete(selected)}>- Delete+ {isDeleting ? "Deleting…" : "Delete"}</button><input className="field max-w-xs" placeholder="Compare campaign ID" value={otherId} onChange={(e) => setOtherId(e.target.value)} /></div></section>- <DataPanel title="Delete Error" data={remove.error} />+ <DataPanel title="Delete Error" data={deleteError} /><DataPanel title="Campaign Detail Error" data={detail.error} /><DataPanel title="CVSS Error" data={cvss.error} /><DataPanel title="Campaign Diff Error" data={diff.error} />@@ -1047,7 +1301,12 @@ export function CampaignsPage() {<section className="grid gap-4"><section className="panel p-4"><SectionHeader title="Campaign Findings" />- <CampaignPicker campaigns={campaignList} value={selected} onChange={setSelected} />+ <div>+ <label htmlFor="findings-campaign-select" className="block text-xs font-medium text-zinc-300 mb-1.5">+ Target Campaign+ </label>+ <CampaignPicker id="findings-campaign-select" campaigns={campaignList} value={selected} onChange={setSelected} />+ </div>{!selected ? <EmptyState text="Select a campaign to review findings." /> : null}</section>{selected ? <DataPanel title="Findings Error" data={findings.error} /> : null}@@ -1126,9 +1385,8 @@ function ExecutionChainsPanel({}export function ModulesPage() {- const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId } = useDashboardUi();+ const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId, campaigns: campaignList } = useDashboardUi();const queryClient = useQueryClient();- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });const modules = useQuery({ queryKey: ["modules"], queryFn: api.modules });const executionChains = useQuery({ queryKey: ["executionChains"], queryFn: api.executionChains });const [selectedId, setSelectedId] = useSessionState("ares.dashboard.modules.selectedId", "");@@ -1183,7 +1441,7 @@ export function ModulesPage() {return related;}, [executionChains.data]);const selected = list.find((item) => item.id === selectedId);- const selectedCampaign = campaignDetail.data ?? (campaigns.data ?? []).find((item) => item.id === campaignId);+ const selectedCampaign = campaignDetail.data ?? campaignList.find((item) => item.id === campaignId);const scopeWarning = moduleScopeWarning(selected, selectedCampaign, params, dryRun);const categories = unique(list.map((item) => item.category || ""));const visible = list.filter((item) => {@@ -1211,8 +1469,10 @@ export function ModulesPage() {const requiresConfirmation = sensitive || isFeasibilityBlocked;const dryRunSupported = selected?.dry_run_supported !== false;const kerberoastTargetMissing = selected?.id === "ad.kerberoast" && !String(params.target_user ?? "").trim();- const canRun = Boolean(campaignId && selectedId) && (!requiresConfirmation || confirmed) && !run.isPending && (!dryRun || dryRunSupported);- const runBlocked = !canRun || Boolean(scopeWarning) || kerberoastTargetMissing;+ const [attemptedRun, setAttemptedRun] = useState(false);+ const executionConditionBlocked = (!requiresConfirmation || confirmed) && !run.isPending && (!dryRun || dryRunSupported) && !Boolean(scopeWarning) && !kerberoastTargetMissing;+ const canRun = Boolean(campaignId && selectedId) && executionConditionBlocked;+ const runBlocked = !canRun;const runHint = moduleRunHint(campaignId, selected, selectedCampaign, sensitive, confirmed, dryRun);const persistedRun = lastRunRecord?.campaignId === campaignId && lastRunRecord.moduleId === selectedId ? lastRunRecord : null;const runResult = (run.data ?? (!persistedRun?.isError ? persistedRun?.payload : undefined)) as Record<string, unknown> | undefined;@@ -1316,12 +1576,40 @@ export function ModulesPage() {</div>) : null}{selected?.dependency_notes?.length ? (- <p className="notice mt-3">Dependencies: {selected.dependency_notes.join("; ")}</p>+ <p className="mt-2 text-xs text-zinc-400 flex items-center gap-1.5">+ <Info size={13} className="text-zinc-500 shrink-0" />+ <span className="text-zinc-400 font-medium">Dependencies:</span> {selected.dependency_notes.join("; ")}+ </p>) : null}{selected && !dryRunSupported && (- <p className="notice notice-danger mt-3">Dry-run is unavailable for this module. No preview will be generated.</p>+ <p className="mt-1 text-xs text-amber-400/80 flex items-center gap-1.5">+ <Info size={13} className="text-amber-400 shrink-0" />+ <span>Dry-run preview is unavailable for this module.</span>+ </p>)}- <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={setCampaignId} />+ <div className="mt-3">+ <label htmlFor="module-campaign-select" className="block text-xs font-medium text-zinc-300 mb-1.5">+ Target Campaign+ </label>+ <CampaignPicker+ id="module-campaign-select"+ campaigns={campaignList}+ value={campaignId}+ hasError={attemptedRun && !campaignId}+ onChange={(id) => {+ setCampaignId(id);+ if (id) {+ setAttemptedRun(false);+ }+ }}+ />+ {attemptedRun && !campaignId && (+ <p className="mt-1.5 flex items-center gap-1.5 text-xs text-rose-400" role="alert">+ <AlertTriangle size={13} className="shrink-0 text-rose-400" />+ Select a scoped campaign before executing this module.+ </p>+ )}+ </div>{campaignId && campaignDetail.isFetching && (<div className="notice mt-3"><Loader2 className="spin" size={16} /> Loading campaign scope...@@ -1334,9 +1622,14 @@ export function ModulesPage() {className="mt-4 grid gap-3"onSubmit={(e) => {e.preventDefault();- if (runBlocked) {+ if (!campaignId) {+ setAttemptedRun(true);return;}+ if (!executionConditionBlocked) {+ return;+ }+ setAttemptedRun(false);run.mutate();}}>@@ -1450,7 +1743,7 @@ export function ModulesPage() {)}</div>)}- {runHint && (+ {runHint && runHint !== "Select a campaign before running a module." && (<p className="notice">{runHint}</p>@@ -1472,7 +1765,11 @@ export function ModulesPage() {: "Confirm authorized high-noise or sensitive execution"}</label>)}- <button className="btn btn-primary" type="submit" disabled={runBlocked}>+ <button+ className="btn btn-primary"+ type="submit"+ disabled={!selectedId || run.isPending || (campaignId ? !executionConditionBlocked : false)}+ >{run.isPending ? (<><Loader2 className="spin" size={16} /> Running...@@ -1515,8 +1812,7 @@ export function ModulesPage() {}export function ReportsPage() {- const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId } = useDashboardUi();- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });+ const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId, campaigns: campaignList } = useDashboardUi();const [format, setFormat] = useSessionState("ares.dashboard.reports.format", "html");const [warning, setWarning] = useState("");const [libraryError, setLibraryError] = useState("");@@ -1624,33 +1920,68 @@ export function ReportsPage() {title="Generate Report"description="Export findings, scope, and remediation."/>- <div className="compact-form-row">- <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={(id) => { setCampaignId(id); setWarning(""); }} />- <select className="field" value={format} onChange={(e) => setFormat(e.target.value)}>- {["html", "pdf", "markdown", "json"].map((item) => <option key={item} value={item}>{item}</option>)}- </select>- <button- className="btn btn-primary"- disabled={generate.isPending}- onClick={() => {- if (!campaignId) {- setWarning("Campaign is required.");- return;- }- setWarning("");- generate.mutate();- }}- >- {generate.isPending ? (- <>- <Loader2 className="spin" size={16} /> Generating...- </>- ) : (- "Generate Report"+ <div className="grid gap-3 sm:grid-cols-3 items-end">+ <div>+ <label htmlFor="report-campaign-select" className="block text-xs font-medium text-zinc-300 mb-1.5">+ Target Campaign+ </label>+ <CampaignPicker+ id="report-campaign-select"+ campaigns={campaignList}+ value={campaignId}+ hasError={Boolean(warning && !campaignId)}+ onChange={(id) => {+ setCampaignId(id);+ setWarning("");+ }}+ />+ {warning && !campaignId && (+ <p className="mt-1.5 flex items-center gap-1.5 text-xs text-rose-400" role="alert">+ <AlertTriangle size={13} className="shrink-0 text-rose-400" />+ {warning}+ </p>)}- </button>+ </div>+ <div>+ <label htmlFor="report-format-select" className="block text-xs font-medium text-zinc-300 mb-1.5">+ Export Format+ </label>+ <select+ id="report-format-select"+ className="field"+ value={format}+ onChange={(e) => setFormat(e.target.value)}+ >+ <option value="html">HTML Document</option>+ <option value="pdf">PDF Document</option>+ <option value="markdown">Markdown</option>+ <option value="json">JSON Export</option>+ </select>+ </div>+ <div>+ <button+ className="btn btn-primary w-full"+ disabled={generate.isPending}+ onClick={() => {+ if (!campaignId) {+ setWarning("Select a scoped campaign before generating a report.");+ return;+ }+ setWarning("");+ generate.mutate();+ }}+ >+ {generate.isPending ? (+ <>+ <Loader2 className="spin" size={16} /> Generating...+ </>+ ) : (+ "Generate Report"+ )}+ </button>+ </div></div>- {warning && <p className="notice notice-danger mt-3">{warning}</p>}+ {warning && campaignId && <p className="notice notice-danger mt-3">{warning}</p>}{pdfIssueHint && (<p className="notice notice-danger mt-3"><AlertTriangle size={16} />@@ -1875,14 +2206,14 @@ export function TemplatesPage() {export function StrategyPage() {const { user } = useAuth();- const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId } = useDashboardUi();- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });+ const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId, campaigns: campaignList } = useDashboardUi();const active = useQuery({ queryKey: ["strategy-active"], queryFn: api.activeStrategy });const [goal, setGoal] = useSessionState("ares.dashboard.strategy.goal", "domain_admin");const [llmBackend, setLlmBackend] = useSessionState("ares.dashboard.strategy.llmBackend", "claude");const [authorizations, setAuthorizations] = useSessionState("ares.dashboard.strategy.authorizations", "");const [lastEngageResult, setLastEngageResult] = useSessionState<PersistedResult | null>("ares.dashboard.strategy.lastEngage", null);const [activeTab, setActiveTab] = useSessionState("ares.dashboard.strategy.tab", "Objective");+ const [attemptedSubmit, setAttemptedSubmit] = useState(false);const strategyResultKey = `${campaignId}:${goal}:${llmBackend}:${authorizations}`;const engage = useMutation({mutationFn: () =>@@ -1904,6 +2235,19 @@ export function StrategyPage() {});const persistedEngageResult = lastEngageResult?.key === strategyResultKey ? lastEngageResult : null;const allowed = user?.role === "team_lead" || user?.role === "operator";++ const llmBackends = (active.data?.llm_backends as Record<string, boolean> | undefined);+ const isEngineUnconfigured = llmBackends ? llmBackends[llmBackend] === false : false;++ const handleEngage = () => {+ if (!campaignId) {+ setAttemptedSubmit(true);+ return;+ }+ setAttemptedSubmit(false);+ engage.mutate();+ };+return (<Pagetitle="Strategy"@@ -1915,35 +2259,101 @@ export function StrategyPage() {{activeTab === "Objective" && (<section className="panel p-4"><SectionHeader title="Objective Builder" />- <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={setCampaignId} />- <select className="field mt-3" value={goal} onChange={(e) => setGoal(e.target.value)}>- {["domain_admin", "enterprise_admin", "cloud_admin", "data_exfil", "persistence", "full_compromise"].map((item) => <option key={item} value={item}>{item}</option>)}- </select>- <select className="field mt-3" value={llmBackend} onChange={(e) => setLlmBackend(e.target.value)}>- <option value="claude">Claude / ANTHROPIC_API_KEY</option>- <option value="openai">OpenAI / OPENAI_API_KEY</option>- <option value="local">Local Ollama</option>- </select>- <p className="notice mt-2">- {strategyBackendHint(llmBackend)}- </p>- <textarea- className="field mt-3 min-h-28"- placeholder="Authorization notes, one per line"- value={authorizations}- onChange={(e) => setAuthorizations(e.target.value)}- />+ <div className="space-y-4">+ <div>+ <label htmlFor="strategy-campaign-select" className="block text-xs font-medium text-zinc-300 mb-1.5">+ Target Campaign+ </label>+ <CampaignPicker+ id="strategy-campaign-select"+ campaigns={campaignList}+ value={campaignId}+ hasError={attemptedSubmit && !campaignId}+ onChange={(id) => {+ setCampaignId(id);+ if (id) {+ setAttemptedSubmit(false);+ }+ }}+ />+ {attemptedSubmit && !campaignId && (+ <p className="mt-1.5 flex items-center gap-1.5 text-xs text-rose-400" role="alert">+ <AlertTriangle size={13} className="shrink-0 text-rose-400" />+ Select a scoped campaign before starting Strategy.+ </p>+ )}+ </div>++ <div>+ <label htmlFor="strategy-goal-select" className="block text-xs font-medium text-zinc-300 mb-1.5">+ Strategic Objective+ </label>+ <select+ id="strategy-goal-select"+ className="field"+ value={goal}+ onChange={(e) => setGoal(e.target.value)}+ >+ <option value="domain_admin">Domain Admin (Active Directory)</option>+ <option value="enterprise_admin">Enterprise Admin (Forest Root)</option>+ <option value="cloud_admin">Cloud Admin (Identity Provider)</option>+ <option value="data_exfil">Data Exfiltration</option>+ <option value="persistence">Persistence & Foothold</option>+ <option value="full_compromise">Full Infrastructure Compromise</option>+ </select>+ </div>++ <div>+ <label htmlFor="strategy-engine-select" className="block text-xs font-medium text-zinc-300 mb-1.5">+ AI Planning Engine+ </label>+ <select+ id="strategy-engine-select"+ className="field"+ value={llmBackend}+ onChange={(e) => setLlmBackend(e.target.value)}+ >+ <option value="claude">Claude (Anthropic)</option>+ <option value="openai">OpenAI (GPT-4o)</option>+ <option value="local">Local (Ollama)</option>+ </select>+ {isEngineUnconfigured && (+ <p className="mt-1.5 flex items-center gap-1.5 text-xs text-amber-400/90">+ <Info size={13} className="shrink-0 text-amber-400" />+ {llmBackend === "claude"+ ? "Anthropic API key is not configured in the server environment. Configure it on the server or select another engine."+ : llmBackend === "openai"+ ? "OpenAI API key is not configured in the server environment. Configure it on the server or select another engine."+ : "Local Ollama service is not reachable at http://127.0.0.1:11434. Start Ollama or verify server connection."}+ </p>+ )}+ </div>++ <div>+ <label htmlFor="strategy-authorizations" className="block text-xs font-medium text-zinc-300 mb-1.5">+ Explicit Authorizations+ </label>+ <textarea+ id="strategy-authorizations"+ className="field min-h-24"+ placeholder="Authorization notes or specific module constraints, one per line"+ value={authorizations}+ onChange={(e) => setAuthorizations(e.target.value)}+ />+ </div>+ </div>+{!allowed && (- <p className="notice notice-danger mt-2">+ <p className="notice notice-danger mt-3">Strategy engagement requires operator or team lead role.</p>)}- {!campaignId && (- <p className="notice mt-2">- Select a scoped campaign before starting Strategy.- </p>- )}- <button className="btn btn-primary mt-3" disabled={!allowed || !campaignId || engage.isPending} onClick={() => engage.mutate()}>++ <button+ className="btn btn-primary mt-4"+ disabled={!allowed || engage.isPending}+ onClick={handleEngage}+ >{engage.isPending ? (<><Loader2 className="spin" size={16} /> Engaging...@@ -2355,9 +2765,9 @@ export function LivePage() {liveConnected,setLiveConnected,liveEvents,- clearLiveEvents+ clearLiveEvents,+ campaigns: campaignList} = useDashboardUi();- const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });const campaignId = liveCampaignId || selectedCampaignId;const [activeTab, setActiveTab] = useSessionState("ares.dashboard.live.tab", "Stream");const streamEvents = liveEvents.slice(0, 10);@@ -2379,7 +2789,7 @@ export function LivePage() {description="Watch selected campaign events."/><CampaignPicker- campaigns={campaigns.data ?? []}+ campaigns={campaignList}value={campaignId}onChange={(id) => {setLiveCampaignId(id);@@ -2440,6 +2850,7 @@ export function LivePage() {function Page({title,+ subtitle,actions,tabs,activeTab,@@ -2447,6 +2858,7 @@ function Page({children}: {title: string;+ subtitle?: ReactNode;actions?: ReactNode;tabs?: string[];activeTab?: string;@@ -2487,7 +2899,7 @@ function Page({<div><p className="page-eyebrow">{meta.eyebrow}</p><h1>{title}</h1>- <p>{meta.description}</p>+ <p className="page-subtitle">{subtitle ?? meta.description}</p></div></div>{actions ? <div className="page-actions">{actions}</div> : null}@@ -2684,6 +3096,10 @@ function TelemetryPanel({ snapshot, loading, confirmedFindings }: { snapshot?: Tconst throughputValue = tasksPerMin === null ? "n/a" : `${formatMetric(tasksPerMin)}/min`;const latencyDetail = p95 === null ? "no run timing data" : `${formatMetric(p95, " ms")} p95`;+ const isIngestionActive = Boolean(snapshot && snapshot.timestamp);+ const ingestionDotClass = loading ? "pending" : isIngestionActive ? "active" : "pending";+ const ingestionText = loading ? "Connecting..." : isIngestionActive ? "Ingestion Active" : "Awaiting Data";+return (<section className="panel telemetry-panel"><SectionHeader@@ -2691,8 +3107,8 @@ function TelemetryPanel({ snapshot, loading, confirmedFindings }: { snapshot?: Tdescription={loading ? "Waiting for metrics." : `Last sample: ${formatTimestamp(snapshot?.timestamp)}`}action={<div className="telemetry-live-status" title="Real-time telemetry ingestion pipeline">- <span className={`status-indicator-dot ${snapshot ? "active" : "pending"}`} />- <span className="status-indicator-text">{snapshot ? "Ingestion Active" : "Awaiting Data"}</span>+ <span className={`status-indicator-dot ${ingestionDotClass}`} />+ <span className="status-indicator-text">{ingestionText}</span>{snapshot?.timestamp ? (<span className="status-indicator-time font-mono">{formatReportTime(snapshot.timestamp)}</span>) : null}@@ -2729,14 +3145,20 @@ function TelemetryPanel({ snapshot, loading, confirmedFindings }: { snapshot?: T}function TelemetryBar({ label, value, tone = "ok" }: { label: string; value: number | null; tone?: "ok" | "danger" }) {- const clamped = value === null ? 0 : Math.max(0, Math.min(100, value));+ const isNa = value === null;+ const isZero = value === 0;+ const clamped = isNa ? 0 : Math.max(0, Math.min(100, value));+ const trackClass = `telemetry-bar-track ${isNa ? "is-na" : isZero ? "is-zero" : ""}`;+ const valueLabel = isNa ? "n/a" : `${clamped}%`;+ const valueClass = isNa ? "is-na font-mono" : isZero ? "is-zero font-mono" : "font-mono";+return (- <div className="telemetry-bar" title={value === null ? "Not enough telemetry data" : undefined}>+ <div className="telemetry-bar" title={isNa ? "No data yet" : isZero ? "0% (measured baseline)" : `${label}: ${clamped}%`}><span>{label}</span>- <div className="telemetry-bar-track">+ <div className={trackClass}><div className={tone === "danger" ? "telemetry-bar-fill danger" : "telemetry-bar-fill"} style={{ width: `${clamped}%` }} /></div>- <strong>{value === null ? "n/a" : `${clamped}%`}</strong>+ <strong className={valueClass}>{valueLabel}</strong></div>);}@@ -3079,14 +3501,26 @@ function CampaignScopeSummary({ campaign, loading }: { campaign?: Campaign; loadfunction CampaignPicker({campaigns,value,- onChange+ onChange,+ id,+ hasError,+ className}: {campaigns: Campaign[];value: string;onChange: (id: string) => void;+ id?: string;+ hasError?: boolean;+ className?: string;}) {+ const safeValue = value && campaigns.some((c) => c.id === value) ? value : "";return (- <select className="field" value={value} onChange={(event) => onChange(event.target.value)}>+ <select+ id={id}+ className={`field ${hasError ? "border-rose-500/70 focus:border-rose-500" : ""} ${className ?? ""}`.trim()}+ value={safeValue}+ onChange={(event) => onChange(event.target.value)}+ ><option value="">Select campaign</option>{campaigns.map((campaign) => (<option key={campaign.id} value={campaign.id}>diff --git a/frontend/src/features/dashboard/dashboardUiState.ts b/frontend/src/features/dashboard/dashboardUiState.tsindex 1bfd691..f74d4fe 100644--- a/frontend/src/features/dashboard/dashboardUiState.ts+++ b/frontend/src/features/dashboard/dashboardUiState.ts@@ -1,5 +1,5 @@import { createContext, Dispatch, SetStateAction, useCallback, useContext, useEffect, useRef, useState } from "react";-import type { UserProfile } from "../../api/types";+import type { Campaign, UserProfile } from "../../api/types";const DASHBOARD_SESSION_PREFIX = "ares.dashboard.";const DASHBOARD_PRINCIPAL_KEY = `${DASHBOARD_SESSION_PREFIX}principal`;@@ -39,6 +39,11 @@ export interface DashboardUiState {setLiveConnected: Dispatch<SetStateAction<boolean>>;liveEvents: unknown[];clearLiveEvents: () => void;+ campaigns: Campaign[];+ campaignsLoading: boolean;+ campaignsError: unknown;+ deleteCampaign: (id: string) => Promise<boolean>;+ refetchCampaigns: () => Promise<unknown>;}export const DashboardUiContext = createContext<DashboardUiState | null>(null);diff --git a/frontend/src/styles.css b/frontend/src/styles.cssindex c9805bf..b3ad6c7 100644--- a/frontend/src/styles.css+++ b/frontend/src/styles.css@@ -968,6 +968,84 @@ button:disabled {padding: 0.85rem;}+.panel-subtle {+ border-left: 2px solid #3f3f46;+ background: rgba(18, 18, 21, 0.45);+ border-radius: 0 8px 8px 0;+ padding: 0.95rem 1.15rem;+ transition: border-color 0.2s ease, background 0.2s ease;+}++.panel-subtle:hover {+ border-left-color: #71717a;+ background: rgba(24, 24, 27, 0.65);+}++.panel-subtle .section-header {+ margin-bottom: 0.65rem;+}++.panel-subtle .section-header h2 {+ font-size: 0.88rem;+ font-weight: 600;+ color: #e4e4e7;+ letter-spacing: -0.01em;+}++.dashboard-empty-hero {+ border: 1px solid #27272a;+ border-radius: 12px;+ background: radial-gradient(ellipse at 50% 0%, rgba(225, 29, 72, 0.08) 0%, rgba(18, 18, 21, 0.9) 70%, #0c0c0e 100%);+ padding: 3.5rem 2rem 2.75rem;+ text-align: center;+ display: flex;+ flex-direction: column;+ align-items: center;+ box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05);+}++.fresh-hero-icon-wrap {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 64px;+ height: 64px;+ border-radius: 50%;+ background: rgba(225, 29, 72, 0.1);+ border: 1px solid rgba(225, 29, 72, 0.3);+ box-shadow: 0 0 24px rgba(225, 29, 72, 0.15);+ margin-bottom: 1.25rem;+}++.dashboard-empty-hero h2 {+ font-size: 1.35rem;+ font-weight: 700;+ color: #fafafa;+ letter-spacing: -0.02em;+ margin: 0 0 0.5rem;+}++.dashboard-empty-hero p {+ max-width: 540px;+ font-size: 0.88rem;+ line-height: 1.55;+ color: #a1a1aa;+ margin: 0 0 1.75rem;+}++.fresh-hero-actions {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 0.85rem;+ flex-wrap: wrap;+ margin-bottom: 0;+}++.fresh-readiness-panel {+ margin-top: 1rem;+}+.dashboard-grid {display: grid;grid-template-columns: minmax(0, 1.45fr) minmax(300px, 0.82fr);@@ -1312,16 +1390,30 @@ textarea.field {}.telemetry-bar-track {+ position: relative;height: 8px;overflow: hidden;border-radius: 999px;- background: #27272a;+ background: #18181b;+ border: 1px solid rgba(255, 255, 255, 0.08);+ box-sizing: border-box;+}++.telemetry-bar-track.is-na {+ background: rgba(24, 24, 27, 0.3);+ border: 1px dashed rgba(113, 113, 122, 0.4);+}++.telemetry-bar-track.is-zero {+ background: rgba(24, 24, 27, 0.55);+ border: 1px solid rgba(63, 63, 70, 0.6);}.telemetry-bar-fill {height: 100%;border-radius: inherit;background: #e4e4e7;+ transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);}.telemetry-bar-fill.danger {@@ -1334,6 +1426,16 @@ textarea.field {font-weight: 600;font-family: ui-monospace, SFMono-Regular, monospace;text-align: right;+ letter-spacing: -0.02em;+}++.telemetry-bar strong.is-na {+ color: #71717a;+ font-weight: 500;+}++.telemetry-bar strong.is-zero {+ color: #a1a1aa;}.telemetry-strip {diff --git a/tests/unit/test_api_endpoints.py b/tests/unit/test_api_endpoints.pyindex 93626bb..3092c97 100644--- a/tests/unit/test_api_endpoints.py+++ b/tests/unit/test_api_endpoints.py@@ -6671,3 +6671,26 @@ class TestMainWebSocketAuthoritativeLifetime:"expected pending broadcast cleanup",)await _settle_main_websocket(socket, route_task)+++async def test_strategy_active_returns_llm_backends_resiliently():+ """Verify /strategy/active provides fail-safe llm_backends availability without 500s."""+ from ares.api.server import app+ from ares.api.rbac import get_current_user, AuthenticatedUser+ from starlette.testclient import TestClient++ app.dependency_overrides[get_current_user] = lambda: AuthenticatedUser(username="test_op", role="operator")+ try:+ client = TestClient(app, base_url="http://localhost")+ resp = client.get("/strategy/active")+ assert resp.status_code == 200+ data = resp.json()+ assert "llm_backends" in data+ assert isinstance(data["llm_backends"], dict)+ assert "claude" in data["llm_backends"]+ assert "openai" in data["llm_backends"]+ assert "local" in data["llm_backends"]+ assert isinstance(data["llm_backends"]["local"], bool)+ finally:+ app.dependency_overrides.pop(get_current_user, None)