Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

feat(dashboard): implement systemic UX fixes and modal confirmations (Items 1-7)

Mafifrizi2a5d2e550e31
diff --git a/UX_AUDIT_REPORT.md b/UX_AUDIT_REPORT.md
new file mode 100644
index 0000000..fb47e40
--- /dev/null
+++ b/UX_AUDIT_REPORT.md
@@ -0,0 +1,215 @@
+# ARES Dashboard UX Audit Report
+**Tanggal Audit:** 27 September 2026
+**Auditor:** Antigravity Pair-Programming Agent
+**Cakupan:** Semua halaman dashboard setelah login (Login page dikecualikan)
+**Standard Audit:** AGENTS.md, Zero Fictitious Claims, Anti-Slop Design System, WCAG 2.1 AA
+
+---
+
+## 1. RINGKASAN EKSEKUTIF
+
+Audit dilakukan secara menyeluruh terhadap 11 entitas permukaan (10 halaman utama + 1 Global Layout Shell) dengan membaca source code aktual pada `frontend/src/features/dashboard/DashboardPages.tsx`, `frontend/src/features/graph/GraphPage.tsx`, dan `frontend/src/styles.css`.
+
+| Metrik | Nilai |
+|:---|:---|
+| **Total Halaman / Permukaan Diaudit** | **11** (1 Shell + 10 Halaman Dashboard) |
+| **Total Masalah Ditemukan** | **25 Masalah** |
+| **CRITICAL** (Fungsi terganggu / Dead-end) | **2** |
+| **HIGH** (Membingungkan / Error-prone / Hierarchy cacat) | **9** |
+| **MEDIUM** (Inkonsistensi / Raw JSON Dump / Responsive polish) | **10** |
+| **LOW** (Minor polish / Contrast detail / Micro-interaction) | **4** |
+
+### 4 Masalah Paling Kritis:
+1. **[CRITICAL] Dead-End di Halaman Reports Tab Library (`REP-01`)**:
+ Saat operator membuka `/reports` tab `Library` tanpa campaign yang terpilih di session, sistem menampilkan pesan *"Select a campaign to list reports"*, tetapi **tidak ada komponen `CampaignPicker` sama sekali di tab Library**. Operator terkunci dan harus kembali ke tab Generate atau mengutak-atik header.
+2. **[CRITICAL] Penghapusan API Key Tanpa Dialog Konfirmasi (`SEC-01`)**:
+ Di halaman `/security` tab `API Keys`, tombol `Delete` langsung memicu mutasi penghapusan API key instan tanpa konfirmasi (`window.confirm` atau modal). Satu klik tidak sengaja langsung mencabut kredensial otomasi secara permanen.
+3. **[HIGH] Form Ganti Password Tanpa Field Konfirmasi (`SEC-02`)**:
+ Di halaman `/security` tab `Account`, hanya ada input `Current password` dan `New password`. Tidak ada field `Confirm New Password`. Jika operator salah ketik satu karakter, password berubah dan user terkunci dari sistem.
+4. **[HIGH] Dead Shortcut `/` di Topbar Search (`SHL-01`)**:
+ Topbar menampilkan badge shortcut keyboard visual `<span className="search-kbd-badge">/</span>`, namun tidak ada event listener keyboard global untuk tombol `/`. Ini menciptakan *false affordance*.
+
+---
+
+## 2. DETAIL PER HALAMAN
+
+### 2.1 Global Layout & Shell — `DashboardShell` (`/*`)
+*Komponen: `DashboardShell` di `frontend/src/features/dashboard/DashboardPages.tsx` (Baris 352–1094)*
+
+| ID | Masalah | Severity | File/Komponen | Baris | Tipe Solusi |
+|---|---|---|---|---|---|
+| **SHL-01** | **Dead Shortcut Hotkey `/` pada Search Bar**<br>UI menampilkan badge `/` seolah-olah tombol slash bisa ditekan untuk langsung fokus ke search bar, namun tidak ada listener `keydown` global. | **HIGH** | `DashboardPages.tsx`<br>`DashboardShell` | 892 | **Fix Langsung**:<br>Pasang `window.addEventListener("keydown")` global untuk tombol `/`. |
+| **SHL-02** | **Dismissal Dropdown Search Menggunakan Timeout 140ms yang Rawan Race Condition**<br>`onBlur` search input memakai `setTimeout(..., 140)`. Pada perangkat lambat, klik pada hasil search bisa gagal terpanggil sebelum dropdown hilang. | **MEDIUM** | `DashboardPages.tsx`<br>`DashboardShell` | 874 | **Fix Langsung**:<br>Gunakan `onMouseDown={(e) => e.preventDefault()}` pada container hasil search. |
+| **SHL-03** | **Sidebar Collapse Pada Layar Mobile/Tablet (<=920px) Menyembunyikan Navigasi Tanpa Pengganti**<br>Pada layar <=920px, navigasi berubah horizontal. Jika tombol menu ditekan, sidebar disembunyikan dengan `display: none` tanpa drawer/overlay menu pengganti. | **MEDIUM** | `styles.css`<br>Media Query | 2516–2539 | **Keputusan Desain**:<br>Tentukan apakah mobile nav menggunakan slide-over drawer atau bottom bar. |
+| **SHL-04** | **Risiko Notifikasi Sistem Tertekan Permanen**<br>Jika user menghapus notifikasi sistem seperti `health:error`, ID tersebut disimpan permanen di localStorage dengan prefix matching, sehingga jika backend mati lagi di masa depan, alert tidak akan muncul lagi. | **MEDIUM** | `DashboardPages.tsx`<br>`DashboardShell` | 716–719 | **Fix Langsung**:<br>Batasi scope dismissal notifikasi kesehatan hanya pada session aktif atau per timestamp. |
+| **SHL-05** | **Ketiadaan Accessible Focus Ring pada Tombol dan Icon Header**<br>Elemen `.btn` dan `.icon-button` tidak memiliki definisi `:focus-visible`, menyulitkan navigasi murni keyboard (WCAG 2.4.7). | **LOW** | `styles.css`<br>`.btn` | 1094–1150 | **Fix Langsung**:<br>Tambahkan standard `:focus-visible { outline: 2px solid #38bdf8; outline-offset: 2px; }`. |
+
+---
+
+### 2.2 Overview — `/`
+*Komponen: `OverviewPage` di `frontend/src/features/dashboard/DashboardPages.tsx` (Baris 1094–1460)*
+
+| ID | Masalah | Severity | File/Komponen | Baris | Tipe Solusi |
+|---|---|---|---|---|---|
+| **OVR-01** | **Ikon Alarmist Menyesatkan pada Onboarding Empty State**<br>Saat instalasi baru (`trackedCount === 0`), ditampilkan ikon `ShieldAlert` merah mawar menyala (`text-rose-500`) dengan border merah, memberi kesan terjadi insiden keamanan genting padahal hanya status siap operasi. | **MEDIUM** | `DashboardPages.tsx`<br>`OverviewPage` | 1149 | **Fix Langsung**:<br>Ganti ikon dengan `Target` atau `Layers` berwarna netral/cyan. |
+| **OVR-02** | **Label Footer "Perimeter mapped" Saat 0 Host Terpetakan**<br>Jika `hostsDiscovered === 0`, footer kartu Attack Surface tetap menampilkan teks `"Perimeter mapped"`, yang secara teknis keliru. Seharusnya menampilkan *"Awaiting recon"* atau *"0 hosts"*. | **MEDIUM** | `DashboardPages.tsx`<br>`OverviewPage` | 1297–1300 | **Fix Langsung**:<br>Evaluasi kondisi `hostsDiscovered > 0 ? "Perimeter mapped" : "Awaiting recon"`. |
+| **OVR-03** | **Inkonsistensi Interaktivitas Baris Tabel Campaign**<br>Pada Overview, baris tabel campaign bisa diklik untuk memfilter dashboard (`onSelectCampaign`), namun pada `/campaigns` baris tabel yang sama tidak interaktif. | **LOW** | `DashboardPages.tsx`<br>`CampaignTable` | 1426, 5205 | **Fix Langsung**:<br>Seragamkan feedback kursor dan interaksi baris di semua tabel campaign. |
+
+---
+
+### 2.3 Campaigns — `/campaigns`
+*Komponen: `CampaignsPage` di `frontend/src/features/dashboard/DashboardPages.tsx` (Baris 1460–1810)*
+
+| ID | Masalah | Severity | File/Komponen | Baris | Tipe Solusi |
+|---|---|---|---|---|---|
+| **CMP-01** | **Hierarki Visual Terbalik pada Tab "List"**<br>Tab diberi nama "List", namun 60% viewport atas dihabiskan oleh form pembuatan campaign yang masif (Name, Client, Noise, 2 textarea Targets & Scope CIDRs), memaksa operator scroll ke bawah setiap kali ingin melihat daftar campaign. | **HIGH** | `DashboardPages.tsx`<br>`CampaignsPage` | 1636–1670 | **Keputusan Desain**:<br>Jadikan form Create sebagai Collapsible/Drawer atau pisahkan tab "Campaigns" vs "New Campaign". |
+| **CMP-02** | **Input Perbandingan Campaign Menggunakan UUID Mentah Tanpa Picker**<br>Pada tab "Scope", fitur perbandingan diff (`api.diffCampaign`) hanya menyediakan raw text field `placeholder="Compare campaign ID"`. Operator harus menghafal/copy-paste string UUID campaign lain secara manual. | **HIGH** | `DashboardPages.tsx`<br>`CampaignsPage` | 1709 | **Fix Langsung**:<br>Ganti text input dengan `CampaignPicker` dropdown (exclude campaign aktif). |
+| **CMP-03** | **Tabel Findings Statis Tanpa Kemampuan Inspeksi Detail / Remediasi**<br>Pada tab "Findings", tabel hanya menampilkan 5 kolom teks statis (Severity, Title, Module, MITRE, Host). Baris tidak bisa diklik/di-expand untuk membaca deskripsi kerentanan, evidence, CVSS, atau langkah remediasi. | **HIGH** | `DashboardPages.tsx`<br>`FindingsTable` | 5243–5256 | **Fix Langsung**:<br>Tambahkan drawer inspeksi detail temuan atau expandable row seperti pada Module Run Summary. |
+| **CMP-04** | **Penumpukan 6 Panel Error Sekaligus di Tab Scope**<br>Terdapat 6 `DataPanel` error yang ditumpuk beruntun (`Vault Restore Error`, `Dry Run Error`, `Delete Error`, `Campaign Detail Error`, `CVSS Error`, `Campaign Diff Error`), menimbulkan visual noise jika terjadi anomali minor. | **LOW** | `DashboardPages.tsx`<br>`CampaignsPage` | 1713–1718 | **Fix Langsung**:<br>Satukan notifikasi error ke dalam consolidated alert strip. |
+
+---
+
+### 2.4 Modules — `/modules`
+*Komponen: `ModulesPage` di `frontend/src/features/dashboard/DashboardPages.tsx` (Baris 1810–2326)*
+
+| ID | Masalah | Severity | File/Komponen | Baris | Tipe Solusi |
+|---|---|---|---|---|---|
+| **MOD-01** | **Styling Error Bahaya Merah (`notice-danger`) pada Status Loading Normal**<br>Saat modul sedang dieksekusi (`run.isPending`), UI menampilkan kotak banner berkedip dengan class `notice notice-danger` (border merah pekat dan background merah menyala), membuat operator mengira modul langsung gagal padahal sedang bekerja. | **HIGH** | `DashboardPages.tsx`<br>`ModulesPage` | 2257–2262 | **Fix Langsung**:<br>Ubah class dari `notice-danger` menjadi `notice-info` atau `notice-active` dengan aksen cyan/emerald. |
+| **MOD-02** | **Double Vertical Scrollbar pada Layar Laptop Standar (1366x768 / 1080p dengan zoom)**<br>Daftar kartu katalog modul dipatok dengan `max-h-[640px] overflow-auto`. Pada viewport sedang, ini memicu scroll ganda (scroll halaman dan scroll kotak modul). | **MEDIUM** | `DashboardPages.tsx`<br>`ModulesPage` | 2035 | **Fix Langsung**:<br>Gunakan tinggi adaptif `max-h-[calc(100vh-290px)]` atau virtual list. |
+| **MOD-03** | **Ketiadaan Tombol Reset Parameter pada Run Panel**<br>Setelah parameter terisi (baik dari riwayat session atau transfer dari execution chain), tidak ada tombol "Clear / Reset to Defaults". Operator harus menghapus isi field satu per satu secara manual. | **LOW** | `DashboardPages.tsx`<br>`ModulesPage` | 2159–2212 | **Fix Langsung**:<br>Tambahkan tombol kecil "Reset Form" di samping header Module Parameters. |
+
+---
+
+### 2.5 Reports — `/reports`
+*Komponen: `ReportsPage` di `frontend/src/features/dashboard/DashboardPages.tsx` (Baris 2326–2586)*
+
+| ID | Masalah | Severity | File/Komponen | Baris | Tipe Solusi |
+|---|---|---|---|---|---|
+| **REP-01** | **[CRITICAL] Dead-End di Tab Library: Tidak Ada Pemilih Campaign**<br>Jika user membuka tab `Library` tanpa campaign yang aktif di session, muncul tulisan *"Select a campaign to list reports."*, tetapi tidak ada dropdown `CampaignPicker` di tab tersebut. Dropdown hanya ada di tab `Generate`. | **CRITICAL** | `DashboardPages.tsx`<br>`ReportsPage` | 2579 | **Fix Langsung**:<br>Pindahkan `CampaignPicker` ke atas level Page Header atau render di kedua tab. |
+| **REP-02** | **Ketiadaan Preview Laporan di Dalam Browser**<br>Laporan yang digenerate (HTML / Markdown / JSON) hanya memiliki opsi "Download" dan "Delete". Operator tidak bisa membaca isi laporan langsung di dashboard tanpa harus men-download file ke disk lokal. | **MEDIUM** | `DashboardPages.tsx`<br>`ReportsPage` | 2547–2563 | **Keputusan Desain**:<br>Sediakan modal preview/iframe untuk format HTML dan Markdown. |
+
+---
+
+### 2.6 Graph — `/graph`
+*Komponen: `GraphPage` di `frontend/src/features/graph/GraphPage.tsx` (Baris 1–1762)*
+
+| ID | Masalah | Severity | File/Komponen | Baris | Tipe Solusi |
+|---|---|---|---|---|---|
+| **GRP-01** | **Canvas Kosong Tanpa Panduan Saat Campaign Belum Memiliki Host**<br>Fungsi `isGraphEmpty` diimpor di baris 43 namun tidak pernah dipakai. Ketika campaign baru dibuka (0 node), canvas hanya menampilkan background grid kosong tanpa ada pesan onboarding atau tombol saran tindakan (cth: *"Jalankan modul discovery untuk memetakan target"*). | **HIGH** | `GraphPage.tsx` | 43, 959 | **Fix Langsung**:<br>Pasang overlay EmptyState di atas canvas ReactFlow jika `filteredGraph.nodes.length === 0`. |
+| **GRP-02** | **Divergensi Visual & Skema Desain Ekstrem (Cobalt Strike Retro 90s)**<br>Halaman Graph menggunakan styling Windows 95/Cobalt Strike retro (`graphCobalt.css`), dengan tombol ber-ASCII (`[P]`, `[R]`, `[S]`, `[Z]`, `[L]`), yang sangat bertolak belakang dengan estetika modern dark-tech ARES di 9 halaman lainnya. | **MEDIUM** | `GraphPage.tsx`<br>`graphCobalt.css` | 16, 980–1100 | **Keputusan Desain**:<br>Konfirmasi dengan owner apakah skin Cobalt Strike ini dipertahankan sebagai tactical gimmick atau diselaraskan dengan design system ARES. |
+
+---
+
+### 2.7 Templates — `/templates`
+*Komponen: `TemplatesPage` di `frontend/src/features/dashboard/DashboardPages.tsx` (Baris 2587–2723)*
+
+| ID | Masalah | Severity | File/Komponen | Baris | Tipe Solusi |
+|---|---|---|---|---|---|
+| **TPL-01** | **Input Parameter Global Berupa Raw JSON Textarea yang Kaku dan Mudah Rusak**<br>Field parameter global mewajibkan operator menulis format JSON mentah tanpa syntax highlighting atau formatting helper. Satu kesalahan tanda kutip langsung memblokir tombol generate. | **HIGH** | `DashboardPages.tsx`<br>`TemplatesPage` | 2670–2703 | **Fix Langsung**:<br>Tambahkan tombol "Format JSON" / "Beautify" dan validasi error inline yang presisi. |
+| **TPL-02** | **Dead-End Simulasi Plan: Tidak Bisa Langsung Diterapkan ke Campaign**<br>Setelah plan berhasil digenerate dan diverifikasi, tidak ada tombol untuk *"Terapkan Plan ke Campaign"* atau *"Jalankan Plan Ini"*. Operator hanya disajikan preview JSON. | **HIGH** | `DashboardPages.tsx`<br>`TemplatesPage` | 2712–2718 | **Keputusan Desain**:<br>Tambahkan CTA "Execute Plan on Campaign" yang mengoper parameter ke Campaigns Run. |
+
+---
+
+### 2.8 Strategy — `/strategy`
+*Komponen: `StrategyPage` di `frontend/src/features/dashboard/DashboardPages.tsx` (Baris 2724–2912)*
+
+| ID | Masalah | Severity | File/Komponen | Baris | Tipe Solusi |
+|---|---|---|---|---|---|
+| **STR-01** | **Hasil Perencanaan AI Hanya Berupa Raw JSON Dump Tanpa Timeline Visual**<br>Fitur Strategy AI yang canggih (mengeksekusi perancangan serangan multi-round) hanya menampilkan output akhir berupa `DataPanel` JSON mentah di tab "Active" dan "Result", tanpa ada visualisasi tahapan round atau approval checklist. | **HIGH** | `DashboardPages.tsx`<br>`StrategyPage` | 2894, 2901 | **Keputusan Desain**:<br>Rancang komponen timeline visual untuk menampilkan tahapan reasoning dan langkah aksi AI. |
+
+---
+
+### 2.9 Security — `/security`
+*Komponen: `SecurityPage` di `frontend/src/features/dashboard/DashboardPages.tsx` (Baris 2933–3165)*
+
+| ID | Masalah | Severity | File/Komponen | Baris | Tipe Solusi |
+|---|---|---|---|---|---|
+| **SEC-01** | **[CRITICAL] Penghapusan API Key Tanpa Dialog Konfirmasi**<br>Tombol `Delete` pada daftar API key langsung mengeksekusi `remove.mutate(key.id)` saat diklik tanpa peringatan. Terpencet tidak sengaja akan mematikan integrasi produksi secara instan. | **CRITICAL** | `DashboardPages.tsx`<br>`SecurityPage` | 3093 | **Fix Langsung**:<br>Pasang dialog konfirmasi sebelum menghapus API key. |
+| **SEC-02** | **Ganti Password Tanpa Input Konfirmasi Password Baru**<br>Form hanya meminta `Current password` dan `New password`. Ketiadaan field konfirmasi menimbulkan risiko tinggi salah ketik password yang berujung account lockout. | **HIGH** | `DashboardPages.tsx`<br>`SecurityPage` | 3050–3056 | **Fix Langsung**:<br>Tambahkan input `Confirm new password` dan validasi kesamaan sebelum submit. |
+| **SEC-03** | **Tab Audit & User Management Hanya Menampilkan Raw JSON Dump**<br>Bagi role `team_lead`, audit log keamanan dan daftar pengguna internal hanya dirender via `DataPanel` JSON mentah. Tidak ada tabel log dengan timestamp, action, IP, dan actor. | **MEDIUM** | `DashboardPages.tsx`<br>`SecurityPage` | 3104–3105 | **Keputusan Desain**:<br>Implementasikan tabel audit log dan tabel manajemen pengguna yang rapi. |
+
+---
+
+### 2.10 EDR/OPSEC — `/edr`
+*Komponen: `EdrPage` di `frontend/src/features/dashboard/DashboardPages.tsx` (Baris 3166–3287)*
+
+| ID | Masalah | Severity | File/Komponen | Baris | Tipe Solusi |
+|---|---|---|---|---|---|
+| **EDR-01** | **Tab Knowledge Base Sebagian Besar Berupa Raw JSON Dump**<br>Setelah menampilkan 3 kartu metrik ringkas, seluruh data knowledge base diserahkan ke `DataPanel` JSON mentah tanpa tabel pemetaan teknik vs produk EDR (CrowdStrike, Defender, dll). | **MEDIUM** | `DashboardPages.tsx`<br>`EdrPage` | 3220 | **Keputusan Desain**:<br>Ubah menjadi tabel matriks teknik bypass per vendor EDR. |
+| **EDR-02** | **Kontras Rendah Tanda Bintang Wajib Isi (`text-red-700`)**<br>Tanda bintang mandatory menggunakan warna Tailwind gelap `text-red-700`, yang di atas latar belakang `#09090b` memiliki contrast ratio buruk (tidak lolos WCAG AA). | **LOW** | `DashboardPages.tsx`<br>`EdrPage` | 3236, 3242 | **Fix Langsung**:<br>Ganti ke `text-rose-400` atau `text-red-400`. |
+
+---
+
+### 2.11 Live Events — `/live`
+*Komponen: `LivePage` di `frontend/src/features/dashboard/DashboardPages.tsx` (Baris 3289–3491)*
+
+| ID | Masalah | Severity | File/Komponen | Baris | Tipe Solusi |
+|---|---|---|---|---|---|
+| **LIV-01** | **Ketiadaan Kontrol Pause / Freeze pada Aliran Event Live**<br>Saat ribuan event masuk dengan cepat, operator tidak memiliki tombol untuk membekukan tampilan stream sementara guna membaca detail payload tanpa harus memutuskan sambungan WebSocket. | **MEDIUM** | `DashboardPages.tsx`<br>`LivePage` | 3360–3375 | **Fix Langsung**:<br>Tambahkan state `isStreamPaused` untuk menghentikan pembaruan visual buffer sementara. |
+
+---
+
+## 3. TEMUAN SISTEMIK (CROSS-PAGE PATTERNS)
+
+Ada 6 pola masalah arsitektur UX yang berulang di banyak halaman sekaligus:
+
+### Pola 1: Ketergantungan Berlebihan pada Raw JSON Dump (`DataPanel`)
+- **Lokasi Tersebar:** `Campaigns` (Scope tab), `Templates` (Plan Builder), `Strategy` (Active & Result tab), `Security` (Audit & Users tab), `EDR` (Stats tab).
+- **Dampak UX:** Memberi kesan aplikasi masih "setengah jadi" (prototype perkakas developer internal) dan tidak ramah bagi operator non-developer atau executive stakeholders.
+- **Rekomendasi:** Ubah data terstruktur (tabel user, audit log, perincian bypass) menjadi tabel dan badge interaktif. Simpan raw JSON hanya di dalam drawer "Inspect Raw Payload" opsional.
+
+### Pola 2: Fragmentasi State & Pemilih Campaign (`CampaignPicker`)
+- **Lokasi Tersebar:** Ada di Topbar, ada di dalam tab tertentu, namun hilang di tab Library (`Reports`), tab Buffer (`Live`), dan tidak ada di `Templates`.
+- **Dampak UX:** Operator bingung apakah aksi yang mereka lakukan sedang memodifikasi Scope global atau Campaign tertentu.
+- **Rekomendasi:** Jadikan Campaign Picker sebagai konteks universal yang melekat di level `DashboardShell` (Header) atau pastikan setiap sub-halaman yang membutuhkan campaign selalu menyertakan picker di posisi yang konsisten (kiri atas konten).
+
+### Pola 3: Inkonsistensi Dialog Aksi Destruktif
+- **Lokasi Tersebar:**
+ - Hapus Campaign: memakai `window.confirm` browser.
+ - Hapus Report: memakai `window.confirm` browser.
+ - Hapus API Key: **TIDAK ADA KONFIRMASI APAPUN**.
+- **Dampak UX:** Inkonsistensi berat antara dialog native browser yang menghentikan thread JS vs aksi tanpa konfirmasi yang berbahaya.
+- **Rekomendasi:** Buat komponen modal konfirmasi destruktif standar ARES (`ConfirmationModal`) dengan judul, deskripsi dampak, dan tombol konfirmasi merah.
+
+### Pola 4: URL Tidak Sinkron dengan State Tab (`useSessionState`)
+- **Lokasi Tersebar:** Semua halaman (`Campaigns`, `Modules`, `Reports`, `Templates`, `Strategy`, `Security`, `EDR`, `Live`).
+- **Dampak UX:** Tombol Back/Forward pada browser tidak bisa digunakan untuk berpindah tab. Jika link di-copy ke tim lain, link tidak membuka tab yang dimaksud karena tab disimpan di `sessionStorage` lokal, bukan URL Search Params/Hash.
+- **Rekomendasi:** Gunakan URL Search Params (misal `?tab=scope` atau `?tab=chains`) sebagai sumber kebenaran tab, dengan fallback ke session.
+
+### Pola 5: Indikator Loading Berwarna Bahaya (`notice-danger`)
+- **Lokasi Tersebar:** `ModulesPage` (baris 2257), `OverviewPage` empty state (baris 1149).
+- **Dampak UX:** Elemen dengan kondisi berjalan normal atau belum ada data diberi border dan background merah terang, memicu kepanikan operator secara keliru.
+
+### Pola 6: Ketiadaan Accessible Keyboard Focus Visible
+- **Lokasi Tersebar:** Seluruh form, tombol, catalog card, dan filter di `styles.css`.
+- **Dampak UX:** Navigasi via tombol Tab tidak memperlihatkan highlight kotak fokus yang jelas pada elemen aktif, melanggar WCAG 2.1 Success Criterion 2.4.7.
+
+---
+
+## 4. REKOMENDASI PRIORITAS IMPLEMENTASI
+
+Urutan pengerjaan berdasarkan rasio **Impact vs Effort**:
+
+### Phase 1: Quick Wins & Critical Fixes (High Impact, Low Effort) — Est: 1–2 Sesi
+1. **[REP-01]** Tambahkan `CampaignPicker` ke tab Library di `/reports` agar tidak terjadi dead-end.
+2. **[SEC-01]** Pasang modal konfirmasi pada tombol Delete API Key di `/security`.
+3. **[SEC-02]** Tambahkan field "Confirm New Password" pada form ganti password di `/security`.
+4. **[SHL-01]** Tambahkan keyboard listener global untuk tombol `/` agar langsung fokus ke search bar.
+5. **[MOD-01]** Ganti styling status eksekusi modul dari `notice-danger` (merah) ke `notice-info` (cyan/pulsing).
+6. **[EDR-02]** Ubah class asteris wajib dari `text-red-700` ke `text-rose-400`.
+7. **[CMP-02]** Ganti input text perbandingan campaign dengan dropdown `CampaignPicker`.
+
+### Phase 2: Structural & Component Polish (High Impact, Medium Effort) — Est: 2–3 Sesi
+1. **[CMP-01]** Reorganisasi tab "List" di Campaigns agar tabel campaign terlihat langsung di atas (form create dibuat collapsible atau drawer).
+2. **[CMP-03]** Buat detail drawer untuk tabel Findings di `/campaigns`.
+3. **[GRP-01]** Pasang overlay EmptyState ramah pada canvas `/graph` saat campaign baru dibuat.
+4. **[LIV-01]** Tambahkan kontrol Pause/Resume pada stream di `/live`.
+5. **[TPL-01]** Pasang validasi interaktif dan tombol "Beautify JSON" pada parameter template.
+6. **[SHL-05]** Pasang focus-visible styling standar di `styles.css` untuk semua tombol dan input.
+
+### Phase 3: Major UX Elevation (Strategic Value, Needs Owner Direction) — Est: 3–4 Sesi
+1. **[STR-01]** Desain ulang tab Active & Result di Strategy menjadi visual timeline AI execution.
+2. **[SEC-03]** Implementasi tabel audit log dan tabel user management terstruktur di Security.
+3. **[EDR-01]** Transformasi Knowledge Base EDR dari JSON mentah menjadi tabular bypass matrix.
+4. **[GRP-02]** Putuskan arah desain GraphPage: selaraskan dengan modern dark-tech ARES atau pertahankan retro Cobalt Strike.
+5. **[Pola 4]** Migrasi manajemen tab dari `useSessionState` murni menjadi URL Query Params (`?tab=...`) untuk mendukung deep linking dan browser history.
diff --git a/frontend/src/components/ui/ConfirmModal.test.tsx b/frontend/src/components/ui/ConfirmModal.test.tsx
new file mode 100644
index 0000000..38fdac2
--- /dev/null
+++ b/frontend/src/components/ui/ConfirmModal.test.tsx
@@ -0,0 +1,95 @@
+// @vitest-environment jsdom
+import "../../test/setup";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ConfirmModal } from "./ConfirmModal";
+
+describe("ConfirmModal", () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("does not render when open is false", () => {
+ const onConfirm = vi.fn();
+ const onCancel = vi.fn();
+
+ render(
+ <ConfirmModal
+ open={false}
+ title="Delete Key"
+ description="Are you sure?"
+ onConfirm={onConfirm}
+ onCancel={onCancel}
+ />
+ );
+
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+
+ it("renders title, description and calls onConfirm on confirm click", () => {
+ const onConfirm = vi.fn();
+ const onCancel = vi.fn();
+
+ render(
+ <ConfirmModal
+ open={true}
+ title="Delete API Key"
+ description="This action cannot be undone."
+ confirmLabel="Yes, Delete"
+ cancelLabel="No, Keep"
+ onConfirm={onConfirm}
+ onCancel={onCancel}
+ />
+ );
+
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ expect(screen.getByText("Delete API Key")).toBeInTheDocument();
+ expect(screen.getByText("This action cannot be undone.")).toBeInTheDocument();
+
+ const confirmBtn = screen.getByRole("button", { name: "Yes, Delete" });
+ fireEvent.click(confirmBtn);
+ expect(onConfirm).toHaveBeenCalledTimes(1);
+ expect(onCancel).not.toHaveBeenCalled();
+ });
+
+ it("calls onCancel when cancel button or close button is clicked", () => {
+ const onConfirm = vi.fn();
+ const onCancel = vi.fn();
+
+ render(
+ <ConfirmModal
+ open={true}
+ title="Delete Item"
+ description="Confirm deletion"
+ onConfirm={onConfirm}
+ onCancel={onCancel}
+ />
+ );
+
+ const cancelBtn = screen.getByRole("button", { name: "Cancel" });
+ fireEvent.click(cancelBtn);
+ expect(onCancel).toHaveBeenCalledTimes(1);
+
+ const closeBtn = screen.getByRole("button", { name: "Close dialog" });
+ fireEvent.click(closeBtn);
+ expect(onCancel).toHaveBeenCalledTimes(2);
+ });
+
+ it("closes on Escape key press", () => {
+ const onConfirm = vi.fn();
+ const onCancel = vi.fn();
+
+ render(
+ <ConfirmModal
+ open={true}
+ title="Escape Test"
+ description="Test escape key"
+ onConfirm={onConfirm}
+ onCancel={onCancel}
+ />
+ );
+
+ fireEvent.keyDown(window, { key: "Escape" });
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend/src/components/ui/ConfirmModal.tsx b/frontend/src/components/ui/ConfirmModal.tsx
new file mode 100644
index 0000000..4ee8056
--- /dev/null
+++ b/frontend/src/components/ui/ConfirmModal.tsx
@@ -0,0 +1,124 @@
+import { AlertTriangle, X } from "lucide-react";
+import { useEffect, useRef } from "react";
+
+export interface ConfirmModalProps {
+ open: boolean;
+ title: string;
+ description: string;
+ confirmLabel?: string; // default: "Delete"
+ cancelLabel?: string; // default: "Cancel"
+ variant?: "danger" | "warning"; // default: "danger"
+ onConfirm: () => void;
+ onCancel: () => void;
+}
+
+export function ConfirmModal({
+ open,
+ title,
+ description,
+ confirmLabel = "Delete",
+ cancelLabel = "Cancel",
+ variant = "danger",
+ onConfirm,
+ onCancel
+}: ConfirmModalProps) {
+ const confirmButtonRef = useRef<HTMLButtonElement | null>(null);
+
+ useEffect(() => {
+ if (!open) return;
+
+ function handleKeyDown(event: KeyboardEvent) {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ onCancel();
+ }
+ }
+
+ window.addEventListener("keydown", handleKeyDown);
+ // Focus the action button for keyboard accessibility
+ const timer = window.setTimeout(() => {
+ confirmButtonRef.current?.focus();
+ }, 50);
+
+ return () => {
+ window.removeEventListener("keydown", handleKeyDown);
+ window.clearTimeout(timer);
+ };
+ }, [open, onCancel]);
+
+ if (!open) return null;
+
+ const isWarning = variant === "warning";
+
+ return (
+ <div
+ className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/70 backdrop-blur-xs p-4"
+ onClick={(e) => {
+ if (e.target === e.currentTarget) {
+ onCancel();
+ }
+ }}
+ role="presentation"
+ >
+ <section
+ aria-describedby="confirm-modal-description"
+ aria-labelledby="confirm-modal-title"
+ aria-modal="true"
+ className="panel w-full max-w-md p-5 shadow-2xl border border-zinc-800 bg-[#111114] rounded-lg"
+ role="dialog"
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex items-start gap-3">
+ <div
+ className={`p-2 rounded-md shrink-0 ${
+ isWarning
+ ? "bg-amber-500/10 text-amber-400 border border-amber-500/20"
+ : "bg-rose-500/10 text-rose-400 border border-rose-500/20"
+ }`}
+ >
+ <AlertTriangle size={18} />
+ </div>
+ <div>
+ <h2 className="text-base font-semibold text-zinc-100" id="confirm-modal-title">
+ {title}
+ </h2>
+ <p className="mt-1.5 text-sm text-zinc-400 leading-normal" id="confirm-modal-description">
+ {description}
+ </p>
+ </div>
+ </div>
+ <button
+ aria-label="Close dialog"
+ className="icon-button icon-button-small text-zinc-400 hover:text-zinc-100"
+ onClick={onCancel}
+ type="button"
+ >
+ <X size={14} />
+ </button>
+ </div>
+
+ <div className="mt-6 flex items-center justify-end gap-2.5">
+ <button
+ className="btn"
+ onClick={onCancel}
+ type="button"
+ >
+ {cancelLabel}
+ </button>
+ <button
+ className={`btn ${
+ isWarning
+ ? "border-amber-500/40 bg-amber-500/10 text-amber-300 hover:bg-amber-500/20"
+ : "btn-danger"
+ }`}
+ onClick={onConfirm}
+ ref={confirmButtonRef}
+ type="button"
+ >
+ {confirmLabel}
+ </button>
+ </div>
+ </section>
+ </div>
+ );
+}
diff --git a/frontend/src/features/dashboard/CampaignSync.test.tsx b/frontend/src/features/dashboard/CampaignSync.test.tsx
index 83fec7a..b414f80 100644
--- a/frontend/src/features/dashboard/CampaignSync.test.tsx
+++ b/frontend/src/features/dashboard/CampaignSync.test.tsx
@@ -91,7 +91,6 @@ describe("Campaign deletion state synchronization across consumers", () => {
sessionStorage.clear();
localStorage.clear();
clearDashboardSession();
- vi.spyOn(window, "confirm").mockReturnValue(true);
mockCampaigns = [
{
id: "camp-001",
@@ -148,11 +147,18 @@ describe("Campaign deletion state synchronization across consumers", () => {
const deleteBtn = screen.getByRole("button", { name: "Delete" });
expect(deleteBtn).not.toBeDisabled();
- // 3. Click Delete
+ // 3. Click Delete (opens confirmation modal)
await act(async () => {
fireEvent.click(deleteBtn);
});
+ // Confirm deletion in ConfirmModal
+ const confirmModalBtn = screen.getByRole("button", { name: "Delete Campaign" });
+ expect(confirmModalBtn).toBeInTheDocument();
+ await act(async () => {
+ fireEvent.click(confirmModalBtn);
+ });
+
// 4. Assert backend delete was called with camp-001
await waitFor(() => {
expect(api.deleteCampaign).toHaveBeenCalledWith("camp-001");
@@ -251,6 +257,11 @@ describe("Campaign deletion state synchronization across consumers", () => {
fireEvent.click(deleteBtn);
});
+ const confirmModalBtn = screen.getByRole("button", { name: "Delete Campaign" });
+ await act(async () => {
+ fireEvent.click(confirmModalBtn);
+ });
+
await waitFor(() => {
expect(api.deleteCampaign).toHaveBeenCalledWith("camp-002");
});
diff --git a/frontend/src/features/dashboard/DashboardPages.test.tsx b/frontend/src/features/dashboard/DashboardPages.test.tsx
index 2d3d33e..6950a84 100644
--- a/frontend/src/features/dashboard/DashboardPages.test.tsx
+++ b/frontend/src/features/dashboard/DashboardPages.test.tsx
@@ -382,10 +382,14 @@ describe("Live Events session partitioning & reactive switching", () => {
refetchCampaigns: vi.fn().mockResolvedValue(true)
};
+ const { MemoryRouter } = await import("react-router-dom");
+
const view = render(
- <DashboardUiContext.Provider value={mockUiState}>
- <LivePage />
- </DashboardUiContext.Provider>
+ <MemoryRouter>
+ <DashboardUiContext.Provider value={mockUiState}>
+ <LivePage />
+ </DashboardUiContext.Provider>
+ </MemoryRouter>
);
// Should display Operation Alpha's session events
@@ -409,9 +413,11 @@ describe("Live Events session partitioning & reactive switching", () => {
};
view.rerender(
- <DashboardUiContext.Provider value={updatedUiState}>
- <LivePage />
- </DashboardUiContext.Provider>
+ <MemoryRouter>
+ <DashboardUiContext.Provider value={updatedUiState}>
+ <LivePage />
+ </DashboardUiContext.Provider>
+ </MemoryRouter>
);
// Now should display Operation Bravo's session event
diff --git a/frontend/src/features/dashboard/DashboardPages.tsx b/frontend/src/features/dashboard/DashboardPages.tsx
index 0fc9ab2..a113b7e 100644
--- a/frontend/src/features/dashboard/DashboardPages.tsx
+++ b/frontend/src/features/dashboard/DashboardPages.tsx
@@ -57,9 +57,11 @@ import {
type DashboardUiState,
useDashboardSessionWriter,
useDashboardUi,
- useSessionState
+ useSessionState,
+ useTabParam
} from "./dashboardUiState";
import { StructuredJsonViewer } from "../../components/common/StructuredJsonViewer";
+import { ConfirmModal } from "../../components/ui/ConfirmModal";
interface ModuleRunRecord {
campaignId: string;
@@ -361,6 +363,7 @@ export function DashboardShell({ children }: { children: ReactNode }) {
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
const [searchTerm, setSearchTerm] = useState("");
const [searchOpen, setSearchOpen] = useState(false);
+ const searchInputRef = useRef<HTMLInputElement>(null);
const [notificationsOpen, setNotificationsOpen] = useState(false);
const [operatorMenuOpen, setOperatorMenuOpen] = useState(false);
const [telemetryOpen, setTelemetryOpen] = useState(false);
@@ -371,6 +374,29 @@ export function DashboardShell({ children }: { children: ReactNode }) {
getStoredNotificationIds(NOTIFICATIONS_DELETED_KEY, username)
);
+ useEffect(() => {
+ function handleKeyDown(e: globalThis.KeyboardEvent) {
+ const target = e.target as HTMLElement | null;
+ const tag = target?.tagName?.toLowerCase() || "";
+ const isEditable =
+ tag === "input" ||
+ tag === "textarea" ||
+ tag === "select" ||
+ Boolean(target?.isContentEditable) ||
+ target?.getAttribute?.("contenteditable") === "true" ||
+ Boolean(target?.closest?.("[contenteditable='true']"));
+
+ if (e.key === "/" && !isEditable && !e.ctrlKey && !e.metaKey && !e.altKey) {
+ e.preventDefault();
+ searchInputRef.current?.focus();
+ searchInputRef.current?.select();
+ }
+ }
+
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, []);
+
useEffect(() => {
if (username) {
const storedDeleted = getStoredNotificationIds(NOTIFICATIONS_DELETED_KEY, username);
@@ -575,10 +601,9 @@ export function DashboardShell({ children }: { children: ReactNode }) {
id: `campaign:${campaign.id}`,
label: campaign.name || campaign.id,
detail: `Campaign ${campaign.id.slice(0, 12)}`,
- route: "/campaigns",
+ route: "/campaigns?tab=Scope",
onSelect: () => {
setSelectedCampaignId(campaign.id);
- writeDashboardSession("ares.dashboard.campaigns.tab", "Scope");
}
},
`${campaign.name ?? ""} ${campaign.id} ${campaign.client ?? ""} ${campaign.status ?? ""}`
@@ -591,10 +616,9 @@ export function DashboardShell({ children }: { children: ReactNode }) {
id: `module:${module.id}`,
label: module.id,
detail: module.description || "Module",
- route: "/modules",
+ route: `/modules?tab=Run+Panel&module=${encodeURIComponent(module.id)}`,
onSelect: () => {
writeDashboardSession("ares.dashboard.modules.selectedId", module.id);
- writeDashboardSession("ares.dashboard.modules.tab", "Run Panel");
}
},
`${module.id} ${module.name ?? ""} ${module.description ?? ""} ${module.category ?? ""} ${module.mitre ?? ""}`
@@ -608,10 +632,8 @@ export function DashboardShell({ children }: { children: ReactNode }) {
id: `report:${report.filename}`,
label: report.filename,
detail: `${report.format || "report"} artifact`,
- route: "/reports",
- onSelect: () => {
- writeDashboardSession("ares.dashboard.reports.tab", "Library");
- }
+ route: "/reports?tab=Library",
+ onSelect: () => {}
},
`${report.filename} ${report.format ?? ""}`
);
@@ -625,10 +647,9 @@ export function DashboardShell({ children }: { children: ReactNode }) {
id: `template:${templateName}`,
label: templateName,
detail: String(template.description ?? "Campaign template"),
- route: "/templates",
+ route: "/templates?tab=Plan+Builder",
onSelect: () => {
writeDashboardSession("ares.dashboard.templates.name", templateName);
- writeDashboardSession("ares.dashboard.templates.tab", "Plan Builder");
}
},
`${templateName} ${String(template.description ?? "")}`
@@ -852,9 +873,6 @@ export function DashboardShell({ children }: { children: ReactNode }) {
value={selectedCampaignId && campaignList.some((c) => c.id === selectedCampaignId) ? selectedCampaignId : ""}
onChange={(e) => {
setSelectedCampaignId(e.target.value);
- if (e.target.value) {
- writeDashboardSession("ares.dashboard.campaigns.tab", "Scope");
- }
}}
>
<option value="">Scope: Global / All</option>
@@ -870,6 +888,7 @@ export function DashboardShell({ children }: { children: ReactNode }) {
<label className="topbar-search" aria-label="Dashboard search">
<Search size={15} />
<input
+ ref={searchInputRef}
aria-label="Search dashboard"
onBlur={() => window.setTimeout(() => setSearchOpen(false), 140)}
onChange={(event) => {
@@ -880,6 +899,7 @@ export function DashboardShell({ children }: { children: ReactNode }) {
onKeyDown={(event) => {
if (event.key === "Escape") {
setSearchOpen(false);
+ (event.target as HTMLInputElement).blur();
}
if (event.key === "Enter" && searchResults.length > 0) {
event.preventDefault();
@@ -1146,7 +1166,7 @@ export function OverviewPage() {
<Page title="Overview" subtitle={overviewSubtitle}>
<div className="dashboard-empty-hero">
<div className="fresh-hero-icon-wrap">
- <ShieldAlert size={32} className="text-rose-500" />
+ <Target size={32} className="text-cyan-400" />
</div>
<h2>No Campaigns Initialized</h2>
<p>
@@ -1157,8 +1177,7 @@ export function OverviewPage() {
<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");
+ navigate("/campaigns?tab=List");
}}
type="button"
>
@@ -1211,8 +1230,7 @@ export function OverviewPage() {
type="button"
className="btn btn-primary text-xs flex items-center gap-1.5"
onClick={() => {
- writeDashboardSession("ares.dashboard.campaigns.tab", "List");
- navigate("/campaigns");
+ navigate("/campaigns?tab=List");
}}
title="Initialize an authorized engagement"
>
@@ -1457,6 +1475,9 @@ function normalizeMonthlySeries(
});
}
+const VALID_TABS_CAMPAIGNS = ["List", "Scope", "Findings"] as const;
+type CampaignsTab = typeof VALID_TABS_CAMPAIGNS[number];
+
export function CampaignsPage() {
const queryClient = useQueryClient();
const {
@@ -1475,8 +1496,12 @@ export function CampaignsPage() {
const [noiseProfile, setNoiseProfile] = useSessionState("ares.dashboard.campaigns.create.noiseProfile", "stealth");
const [createWarning, setCreateWarning] = useState("");
const [otherId, setOtherId] = useSessionState("ares.dashboard.campaigns.compareId", "");
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.campaigns.tab", "List");
+ const [rawTab, setActiveTab] = useTabParam("List");
+ const activeTab = (VALID_TABS_CAMPAIGNS as readonly string[]).includes(rawTab)
+ ? (rawTab as CampaignsTab)
+ : "List";
const [deleteError, setDeleteError] = useState<unknown>(null);
+ const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
const [localDeleting, setLocalDeleting] = useState(false);
const isDeleting = localDeleting || Boolean(isDeletingCampaign);
const detail = useQuery({
@@ -1604,9 +1629,6 @@ export function CampaignsPage() {
const handleDelete = async (targetId: string) => {
if (!targetId || isDeleting) return;
- if (!window.confirm("Delete this campaign and its stored findings, hosts, credentials, and loot?")) {
- return;
- }
setLocalDeleting(true);
setDeleteError(null);
try {
@@ -1702,7 +1724,7 @@ export function CampaignsPage() {
<button
className="btn btn-danger"
disabled={!selected || isDeleting}
- onClick={() => handleDelete(selected)}
+ onClick={() => setDeleteTarget(selected)}
>
{isDeleting ? "Deleting…" : "Delete"}
</button>
@@ -1736,6 +1758,22 @@ export function CampaignsPage() {
{selected ? <FindingsTable findings={findings.data ?? []} /> : null}
</section>
)}
+ <ConfirmModal
+ open={deleteTarget !== null}
+ title="Delete Campaign"
+ description="Permanently delete this campaign and all its stored findings, hosts, credentials, and loot artifacts. This action cannot be undone."
+ confirmLabel="Delete Campaign"
+ cancelLabel="Cancel"
+ variant="danger"
+ onConfirm={() => {
+ if (deleteTarget) {
+ const target = deleteTarget;
+ setDeleteTarget(null);
+ void handleDelete(target);
+ }
+ }}
+ onCancel={() => setDeleteTarget(null)}
+ />
</Page>
);
}
@@ -1807,6 +1845,9 @@ function ExecutionChainsPanel({
);
}
+const VALID_TABS_MODULES = ["Catalog", "Execution Chains", "Run Panel", "Results"] as const;
+type ModulesTab = typeof VALID_TABS_MODULES[number];
+
export function ModulesPage() {
const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId, campaigns: campaignList } = useDashboardUi();
const [searchParams] = useSearchParams();
@@ -1822,22 +1863,19 @@ export function ModulesPage() {
const [confirmed, setConfirmed] = useSessionState("ares.dashboard.modules.confirmed", false);
const [params, setParams] = useSessionState<Record<string, unknown>>("ares.dashboard.modules.params", {});
const [lastRunRecord, setLastRunRecord] = useSessionState<ModuleRunRecord | null>("ares.dashboard.modules.lastRun", null);
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.modules.tab", "Catalog");
+ const [rawTab, setActiveTab] = useTabParam("Catalog");
+ const activeTab = (VALID_TABS_MODULES as readonly string[]).includes(rawTab)
+ ? (rawTab as ModulesTab)
+ : "Catalog";
const previousSelectedId = useRef(selectedId);
useEffect(() => {
const queryModule = searchParams.get("module") || (location.state as { moduleId?: string } | null)?.moduleId;
- const queryTab = searchParams.get("tab") || (location.state as { tab?: string } | null)?.tab;
if (queryModule) {
setSelectedId(queryModule);
- if (queryTab) {
- setActiveTab(queryTab);
- } else {
- setActiveTab("Run Panel");
- }
}
- }, [searchParams, location.state, setSelectedId, setActiveTab]);
+ }, [searchParams, location.state, setSelectedId]);
const campaignDetail = useQuery({
queryKey: ["campaign", campaignId],
queryFn: () => api.campaign(campaignId),
@@ -2255,7 +2293,7 @@ export function ModulesPage() {
</div>
{run.isPending && (
- <div className="notice notice-danger text-xs" role="status" aria-live="polite">
+ <div className="notice notice-info text-xs" role="status" aria-live="polite">
<Loader2 className="spin shrink-0" size={15} />
Module execution in progress. Keep this page open while ARES validates the target and collects results.
</div>
@@ -2323,13 +2361,21 @@ export function ModulesPage() {
);
}
+const VALID_TABS_REPORTS = ["Generate", "Library"] as const;
+type ReportsTab = typeof VALID_TABS_REPORTS[number];
+
export function ReportsPage() {
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("");
+ const [deleteReportTarget, setDeleteReportTarget] = useState<ReportItem | null>(null);
+ const [confirmClearAllReports, setConfirmClearAllReports] = useState(false);
const [lastGenerateResult, setLastGenerateResult] = useSessionState<PersistedResult | null>("ares.dashboard.reports.lastGenerate", null);
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.reports.tab", "Generate");
+ const [rawTab, setActiveTab] = useTabParam("Generate");
+ const activeTab = (VALID_TABS_REPORTS as readonly string[]).includes(rawTab)
+ ? (rawTab as ReportsTab)
+ : "Generate";
const queryClient = useQueryClient();
const reports = useQuery({
queryKey: ["reports", campaignId],
@@ -2518,13 +2564,7 @@ export function ReportsPage() {
<button
className="btn btn-danger"
disabled={deleteDisabled}
- onClick={() => {
- if (!window.confirm(`Delete all ${reportItems.length} report artifacts for this campaign? This cannot be undone.`)) {
- return;
- }
- setLibraryError("");
- clearReports.mutate();
- }}
+ onClick={() => setConfirmClearAllReports(true)}
>
{clearReports.isPending ? (
<Loader2 className="spin" size={15} />
@@ -2533,39 +2573,49 @@ export function ReportsPage() {
</button>
) : null}
/>
- <div className="table-scroll">
- <table className="table">
- <thead><tr><th>Filename</th><th>Format</th><th>Size</th><th>Modified</th><th>Actions</th></tr></thead>
- <tbody>
- {reportItems.map((item) => (
- <tr key={item.filename}>
- <td className="font-medium text-zinc-100 font-mono text-sm">{item.filename}</td>
- <td><span className="badge">{item.format}</span></td>
- <td>{formatBytes(item.size_bytes)}</td>
- <td>{formatReportDate(item.modified_at)}</td>
- <td>
- <button className="btn" disabled={download.isPending || deleteDisabled} onClick={() => download.mutate(item)}>
- Download
- </button>
- <button
- className="btn btn-danger"
- disabled={deleteDisabled}
- onClick={() => {
- if (!window.confirm(`Delete report artifact "${item.filename}"? This cannot be undone.`)) {
- return;
- }
- setLibraryError("");
- deleteReport.mutate(item);
- }}
- >
- Delete
- </button>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
+ <div className="p-4 border-b border-zinc-800/80">
+ <label htmlFor="library-campaign-select" className="block text-xs font-medium text-zinc-300 mb-1.5">
+ Target Campaign
+ </label>
+ <CampaignPicker
+ id="library-campaign-select"
+ campaigns={campaignList}
+ value={campaignId}
+ onChange={(id) => {
+ setCampaignId(id);
+ setWarning("");
+ }}
+ />
</div>
+ {campaignId && reportItems.length > 0 && (
+ <div className="table-scroll">
+ <table className="table">
+ <thead><tr><th>Filename</th><th>Format</th><th>Size</th><th>Modified</th><th>Actions</th></tr></thead>
+ <tbody>
+ {reportItems.map((item) => (
+ <tr key={item.filename}>
+ <td className="font-medium text-zinc-100 font-mono text-sm">{item.filename}</td>
+ <td><span className="badge">{item.format}</span></td>
+ <td>{formatBytes(item.size_bytes)}</td>
+ <td>{formatReportDate(item.modified_at)}</td>
+ <td>
+ <button className="btn" disabled={download.isPending || deleteDisabled} onClick={() => download.mutate(item)}>
+ Download
+ </button>
+ <button
+ className="btn btn-danger"
+ disabled={deleteDisabled}
+ onClick={() => setDeleteReportTarget(item)}
+ >
+ Delete
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
{libraryError && (
<p className="notice notice-danger mt-3">
<AlertTriangle size={16} />
@@ -2580,17 +2630,53 @@ export function ReportsPage() {
<DataPanel title="Download Result" data={download.error} />
</section>
)}
+ <ConfirmModal
+ open={deleteReportTarget !== null}
+ title="Delete Report"
+ description={`Permanently delete report artifact "${deleteReportTarget?.filename ?? ""}". This action cannot be undone.`}
+ confirmLabel="Delete Report"
+ cancelLabel="Cancel"
+ variant="danger"
+ onConfirm={() => {
+ if (deleteReportTarget) {
+ setLibraryError("");
+ deleteReport.mutate(deleteReportTarget);
+ setDeleteReportTarget(null);
+ }
+ }}
+ onCancel={() => setDeleteReportTarget(null)}
+ />
+ <ConfirmModal
+ open={confirmClearAllReports}
+ title="Delete All Reports"
+ description={`Permanently delete all ${reportItems.length} report artifacts for this campaign. This action cannot be undone.`}
+ confirmLabel="Delete All Reports"
+ cancelLabel="Cancel"
+ variant="danger"
+ onConfirm={() => {
+ setLibraryError("");
+ clearReports.mutate();
+ setConfirmClearAllReports(false);
+ }}
+ onCancel={() => setConfirmClearAllReports(false)}
+ />
</Page>
);
}
+const VALID_TABS_TEMPLATES = ["Templates", "Plan Builder"] as const;
+type TemplatesTab = typeof VALID_TABS_TEMPLATES[number];
+
export function TemplatesPage() {
const templates = useQuery({ queryKey: ["templates"], queryFn: api.templates });
const [name, setName] = useSessionState("ares.dashboard.templates.name", "");
const [params, setParams] = useSessionState("ares.dashboard.templates.params", "{}");
const [warning, setWarning] = useState("");
const [lastPlanResult, setLastPlanResult] = useSessionState<PersistedResult | null>("ares.dashboard.templates.lastPlan", null);
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.templates.tab", "Templates");
+ const [rawTab, setActiveTab] = useTabParam("Templates");
+ const activeTab = (VALID_TABS_TEMPLATES as readonly string[]).includes(rawTab)
+ ? (rawTab as TemplatesTab)
+ : "Templates";
const templatePlanKey = `${name.trim()}:${params}`;
const plan = useMutation({
mutationFn: () => api.templatePlan(name, safeJson(params)),
@@ -2721,6 +2807,9 @@ export function TemplatesPage() {
);
}
+const VALID_TABS_STRATEGY = ["Objective", "Active", "Result"] as const;
+type StrategyTab = typeof VALID_TABS_STRATEGY[number];
+
export function StrategyPage() {
const { user } = useAuth();
const { selectedCampaignId: campaignId, setSelectedCampaignId: setCampaignId, campaigns: campaignList } = useDashboardUi();
@@ -2729,7 +2818,10 @@ export function StrategyPage() {
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 [rawTab, setActiveTab] = useTabParam("Objective");
+ const activeTab = (VALID_TABS_STRATEGY as readonly string[]).includes(rawTab)
+ ? (rawTab as StrategyTab)
+ : "Objective";
const [attemptedSubmit, setAttemptedSubmit] = useState(false);
const strategyResultKey = `${campaignId}:${goal}:${llmBackend}:${authorizations}`;
const engage = useMutation({
@@ -2930,6 +3022,9 @@ function formatDateTime(value: string): string {
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
}
+const VALID_TABS_SECURITY = ["Account", "API Keys", "Audit"] as const;
+type SecurityTab = typeof VALID_TABS_SECURITY[number];
+
export function SecurityPage() {
const { user } = useAuth();
const keys = useQuery({ queryKey: ["api-keys"], queryFn: api.apiKeys });
@@ -2939,18 +3034,26 @@ export function SecurityPage() {
const secretKeyInputRef = useRef<HTMLInputElement | null>(null);
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
+ const [confirmPassword, setConfirmPassword] = useState("");
+ const [confirmTouched, setConfirmTouched] = useState(false);
const [keyName, setKeyName] = useState("");
const [scopes, setScopes] = useState("read");
const [creatingApiKey, setCreatingApiKey] = useState(false);
const [generatedApiKey, setGeneratedApiKey] = useState<GeneratedApiKey | null>(null);
const [apiKeyError, setApiKeyError] = useState<unknown>(null);
const [copyStatus, setCopyStatus] = useState<ApiKeyCopyStatus>("idle");
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.security.tab", "Account");
+ const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
+ const [rawTab, setActiveTab] = useTabParam("Account");
+ const activeTab = (VALID_TABS_SECURITY as readonly string[]).includes(rawTab)
+ ? (rawTab as SecurityTab)
+ : "Account";
const change = useMutation({
mutationFn: () => api.changePassword({ current_password: currentPassword, new_password: newPassword }),
onSuccess: () => {
setCurrentPassword("");
setNewPassword("");
+ setConfirmPassword("");
+ setConfirmTouched(false);
}
});
const remove = useMutation({
@@ -3045,11 +3148,45 @@ export function SecurityPage() {
<form className="grid gap-2" onSubmit={(event) => {
event.preventDefault();
if (!event.currentTarget.reportValidity()) return;
+ if (newPassword !== confirmPassword) return;
change.mutate();
}}>
<input className="field" required type="password" placeholder="Current password" value={currentPassword} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCurrentPassword(e.target.value); }} />
<input className="field" required minLength={12} type="password" placeholder="New password" value={newPassword} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setNewPassword(e.target.value); }} />
- <button className="btn" disabled={change.isPending} type="submit">
+ <div>
+ <input
+ className={`field ${confirmTouched && confirmPassword !== "" && newPassword !== confirmPassword ? "border-rose-500/70 focus:border-rose-500" : ""}`}
+ required
+ minLength={12}
+ type="password"
+ placeholder="Confirm new password"
+ value={confirmPassword}
+ onInvalid={setRequiredMessage}
+ onBlur={() => setConfirmTouched(true)}
+ onChange={(e) => {
+ clearValidationMessage(e);
+ setConfirmTouched(true);
+ setConfirmPassword(e.target.value);
+ }}
+ />
+ {confirmTouched && confirmPassword !== "" && newPassword !== confirmPassword && (
+ <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" />
+ Passwords do not match
+ </p>
+ )}
+ </div>
+ <button
+ className="btn"
+ disabled={
+ change.isPending ||
+ !currentPassword.trim() ||
+ !newPassword ||
+ !confirmPassword ||
+ newPassword !== confirmPassword
+ }
+ type="submit"
+ >
{change.isPending && <Loader2 className="spin" size={16} />}
Change Password
</button>
@@ -3090,7 +3227,7 @@ export function SecurityPage() {
{key.expires_at ? <span>Expires: {formatDateTime(key.expires_at)}</span> : <span>No expiry</span>}
</div>
</div>
- <button className="btn btn-danger" disabled={remove.isPending} onClick={() => remove.mutate(key.id)}>Delete</button>
+ <button className="btn btn-danger" disabled={remove.isPending} onClick={() => setDeleteTarget(key.id)} type="button">Delete</button>
</div>
))}
{(keys.data ?? []).length === 0 && <EmptyState text="No API keys yet." />}
@@ -3159,10 +3296,28 @@ export function SecurityPage() {
</section>
</div>
)}
+ <ConfirmModal
+ open={deleteTarget !== null}
+ title="Delete API Key"
+ description="This action cannot be undone. All integrations using this key will immediately lose access."
+ confirmLabel="Delete API Key"
+ cancelLabel="Cancel"
+ variant="danger"
+ onConfirm={() => {
+ if (deleteTarget) {
+ remove.mutate(deleteTarget);
+ setDeleteTarget(null);
+ }
+ }}
+ onCancel={() => setDeleteTarget(null)}
+ />
</Page>
);
}
+const VALID_TABS_EDR = ["Knowledge Base", "Report Outcome"] as const;
+type EdrTab = typeof VALID_TABS_EDR[number];
+
export function EdrPage() {
const stats = useQuery({ queryKey: ["edr-stats"], queryFn: api.edrStats });
const [techniqueId, setTechniqueId] = useSessionState("ares.dashboard.edr.techniqueId", "");
@@ -3171,7 +3326,10 @@ export function EdrPage() {
const [success, setSuccess] = useSessionState("ares.dashboard.edr.success", false);
const [notes, setNotes] = useSessionState("ares.dashboard.edr.notes", "");
const [lastReportResult, setLastReportResult] = useSessionState<PersistedResult | null>("ares.dashboard.edr.lastReport", null);
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.edr.tab", "Knowledge Base");
+ const [rawTab, setActiveTab] = useTabParam("Knowledge Base");
+ const activeTab = (VALID_TABS_EDR as readonly string[]).includes(rawTab)
+ ? (rawTab as EdrTab)
+ : "Knowledge Base";
const edrReportKey = `${techniqueId.trim()}:${vendor.trim()}:${version.trim()}:${success}:${notes.trim()}`;
const report = useMutation({
mutationFn: () =>
@@ -3286,6 +3444,9 @@ export function EdrPage() {
);
}
+const VALID_TABS_LIVE = ["Stream", "Buffer"] as const;
+type LiveTab = typeof VALID_TABS_LIVE[number];
+
export function LivePage() {
const {
selectedCampaignId,
@@ -3299,7 +3460,10 @@ export function LivePage() {
campaigns: campaignList
} = useDashboardUi();
const campaignId = liveCampaignId || selectedCampaignId;
- const [activeTab, setActiveTab] = useSessionState("ares.dashboard.live.tab", "Stream");
+ const [rawTab, setActiveTab] = useTabParam("Stream");
+ const activeTab = (VALID_TABS_LIVE as readonly string[]).includes(rawTab)
+ ? (rawTab as LiveTab)
+ : "Stream";
const [bufferViewScope, setBufferViewScope] = useState<"session" | "all">("session");
const currentCampaign = useMemo(() => {
diff --git a/frontend/src/features/dashboard/DashboardShellSearchShortcut.test.tsx b/frontend/src/features/dashboard/DashboardShellSearchShortcut.test.tsx
new file mode 100644
index 0000000..3e9250f
--- /dev/null
+++ b/frontend/src/features/dashboard/DashboardShellSearchShortcut.test.tsx
@@ -0,0 +1,175 @@
+// @vitest-environment jsdom
+import "../../test/setup";
+import "@testing-library/jest-dom/vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { MemoryRouter, Route, Routes } from "react-router-dom";
+
+vi.mock("../auth/authContext", () => ({
+ useAuth: () => ({
+ user: { username: "operator", role: "operator" },
+ 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 () => []),
+ modules: vi.fn(async () => []),
+ templates: vi.fn(async () => []),
+ reports: vi.fn(async () => ({ campaign_id: "", reports: [] }))
+ }
+ };
+});
+
+import { clearDashboardSession } from "./dashboardUiState";
+import { DashboardShell } from "./DashboardPages";
+
+function DummyContent() {
+ return (
+ <div>
+ <h1>Test Page</h1>
+ <input data-testid="form-input" placeholder="Type here" />
+ <textarea data-testid="form-textarea" placeholder="Multi-line here" />
+ <div data-testid="editable-div" contentEditable="true" suppressContentEditableWarning>Editable content</div>
+ </div>
+ );
+}
+
+function renderShell() {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ staleTime: 0
+ }
+ }
+ });
+
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={["/"]}>
+ <DashboardShell>
+ <Routes>
+ <Route path="/" element={<DummyContent />} />
+ </Routes>
+ </DashboardShell>
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+}
+
+describe("DashboardShell Global '/' Search Shortcut (SHL-01)", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ clearDashboardSession();
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("focuses search input and selects its text when '/' is pressed from page body", () => {
+ renderShell();
+
+ const searchInput = screen.getByLabelText("Search dashboard") as HTMLInputElement;
+ searchInput.value = "existing-query";
+ expect(document.activeElement).not.toBe(searchInput);
+
+ const selectSpy = vi.spyOn(searchInput, "select");
+
+ // Press '/' on window/body
+ fireEvent.keyDown(window, { key: "/" });
+
+ expect(document.activeElement).toBe(searchInput);
+ expect(selectSpy).toHaveBeenCalled();
+ });
+
+ it("does not focus search bar when '/' is typed inside an input element", () => {
+ renderShell();
+
+ const searchInput = screen.getByLabelText("Search dashboard") as HTMLInputElement;
+ const formInput = screen.getByTestId("form-input") as HTMLInputElement;
+
+ formInput.focus();
+ expect(document.activeElement).toBe(formInput);
+
+ const defaultPrevented = !fireEvent.keyDown(formInput, { key: "/" });
+
+ expect(document.activeElement).toBe(formInput);
+ expect(document.activeElement).not.toBe(searchInput);
+ expect(defaultPrevented).toBe(false);
+ });
+
+ it("does not focus search bar when '/' is typed inside a textarea", () => {
+ renderShell();
+
+ const searchInput = screen.getByLabelText("Search dashboard") as HTMLInputElement;
+ const textarea = screen.getByTestId("form-textarea") as HTMLTextAreaElement;
+
+ textarea.focus();
+ expect(document.activeElement).toBe(textarea);
+
+ const defaultPrevented = !fireEvent.keyDown(textarea, { key: "/" });
+
+ expect(document.activeElement).toBe(textarea);
+ expect(document.activeElement).not.toBe(searchInput);
+ expect(defaultPrevented).toBe(false);
+ });
+
+ it("does not focus search bar when '/' is typed inside a contentEditable element", () => {
+ renderShell();
+
+ const searchInput = screen.getByLabelText("Search dashboard") as HTMLInputElement;
+ const editableDiv = screen.getByTestId("editable-div");
+
+ editableDiv.focus();
+
+ const defaultPrevented = !fireEvent.keyDown(editableDiv, { key: "/" });
+
+ expect(document.activeElement).not.toBe(searchInput);
+ expect(defaultPrevented).toBe(false);
+ });
+
+ it("ignores modifier keys like Ctrl+'/', Alt+'/', or Meta+'/'", () => {
+ renderShell();
+
+ const searchInput = screen.getByLabelText("Search dashboard") as HTMLInputElement;
+
+ // Ctrl + /
+ fireEvent.keyDown(window, { key: "/", ctrlKey: true });
+ expect(document.activeElement).not.toBe(searchInput);
+
+ // Alt + /
+ fireEvent.keyDown(window, { key: "/", altKey: true });
+ expect(document.activeElement).not.toBe(searchInput);
+
+ // Meta + /
+ fireEvent.keyDown(window, { key: "/", metaKey: true });
+ expect(document.activeElement).not.toBe(searchInput);
+ });
+
+ it("loses focus when Escape is pressed while focused on search input", () => {
+ renderShell();
+
+ const searchInput = screen.getByLabelText("Search dashboard") as HTMLInputElement;
+
+ // Focus via shortcut
+ fireEvent.keyDown(window, { key: "/" });
+ expect(document.activeElement).toBe(searchInput);
+
+ // Press Escape
+ fireEvent.keyDown(searchInput, { key: "Escape" });
+ expect(document.activeElement).not.toBe(searchInput);
+ });
+});
diff --git a/frontend/src/features/dashboard/DestructiveActionModals.test.tsx b/frontend/src/features/dashboard/DestructiveActionModals.test.tsx
new file mode 100644
index 0000000..4ea4721
--- /dev/null
+++ b/frontend/src/features/dashboard/DestructiveActionModals.test.tsx
@@ -0,0 +1,335 @@
+// @vitest-environment jsdom
+import "../../test/setup";
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { MemoryRouter, Route, Routes } from "react-router-dom";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("../auth/authContext", () => ({
+ useAuth: () => ({
+ user: { username: "admin", role: "team_lead" },
+ loading: false,
+ logout: vi.fn(),
+ logoutAll: vi.fn()
+ })
+}));
+
+let mockCampaigns = [
+ {
+ id: "camp-alpha",
+ name: "Alpha Operation",
+ client: "CyberDyne",
+ status: "created",
+ noise_profile: "stealth",
+ operator: "admin",
+ targets: ["10.0.0.1"]
+ }
+];
+
+let mockReports = [
+ {
+ filename: "ares-report-alpha-2026.pdf",
+ format: "pdf",
+ size_bytes: 1048576,
+ modified_at: 1774000000
+ },
+ {
+ filename: "ares-report-alpha-2026.html",
+ format: "html",
+ size_bytes: 524288,
+ modified_at: 1774000100
+ }
+];
+
+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) => {
+ 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 (id: string) => ({
+ campaign_id: id,
+ reports: id === "camp-alpha" ? [...mockReports] : []
+ })),
+ generateReport: vi.fn(async () => ({ status: "generated", filename: "test.html" })),
+ deleteReport: vi.fn(async (campId: string, filename: string) => {
+ mockReports = mockReports.filter((r) => r.filename !== filename);
+ return { status: "deleted" };
+ }),
+ clearReports: vi.fn(async () => {
+ mockReports = [];
+ return { status: "cleared" };
+ }),
+ downloadReport: vi.fn(async () => new Blob(["test"])),
+ 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 () => []),
+ restoreVault: vi.fn(async () => ({ restored: 0 })),
+ executeWorkflow: vi.fn(async () => ({ status: "executed" })),
+ createCampaign: vi.fn(async (data: any) => ({ ...data, id: "new-camp" }))
+ }
+ };
+});
+
+import { api } from "../../api/client";
+import { clearDashboardSession } from "./dashboardUiState";
+import { CampaignsPage, DashboardShell, ReportsPage } from "./DashboardPages";
+
+function renderWithProviders(element: React.ReactNode, initialPath = "/") {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ staleTime: 0
+ }
+ }
+ });
+
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={[initialPath]}>
+ <DashboardShell>
+ <Routes>
+ <Route path="/campaigns" element={element} />
+ <Route path="/reports" element={element} />
+ </Routes>
+ </DashboardShell>
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+}
+
+describe("Item 7: Destructive Action ConfirmModal Consistency", () => {
+ let confirmSpy: any;
+
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ clearDashboardSession();
+ vi.clearAllMocks();
+ confirmSpy = vi.spyOn(window, "confirm");
+
+ mockCampaigns = [
+ {
+ id: "camp-alpha",
+ name: "Alpha Operation",
+ client: "CyberDyne",
+ status: "created",
+ noise_profile: "stealth",
+ operator: "admin",
+ targets: ["10.0.0.1"]
+ }
+ ];
+
+ mockReports = [
+ {
+ filename: "ares-report-alpha-2026.pdf",
+ format: "pdf",
+ size_bytes: 1048576,
+ modified_at: 1774000000
+ },
+ {
+ filename: "ares-report-alpha-2026.html",
+ format: "html",
+ size_bytes: 524288,
+ modified_at: 1774000100
+ }
+ ];
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ });
+
+ describe("CampaignsPage Delete Confirmation", () => {
+ it("opens ConfirmModal with specific title and description when Delete is clicked, cancel does nothing", async () => {
+ renderWithProviders(<CampaignsPage />, "/campaigns");
+
+ // Wait for initial load
+ await waitFor(() => {
+ expect(screen.getAllByText("Alpha Operation").length).toBeGreaterThanOrEqual(1);
+ });
+
+ // Switch to Scope tab
+ fireEvent.click(screen.getByRole("tab", { name: "Scope" }));
+
+ // Select target campaign
+ const picker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;
+ expect(picker).toBeInTheDocument();
+ fireEvent.change(picker, { target: { value: "camp-alpha" } });
+
+ const deleteBtn = screen.getByRole("button", { name: "Delete" });
+ expect(deleteBtn).not.toBeDisabled();
+
+ // Click Delete
+ await act(async () => {
+ fireEvent.click(deleteBtn);
+ });
+
+ // ConfirmModal should be visible
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "Delete Campaign" })).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ "Permanently delete this campaign and all its stored findings, hosts, credentials, and loot artifacts. This action cannot be undone."
+ )
+ ).toBeInTheDocument();
+
+ // Click Cancel
+ const cancelBtn = screen.getByRole("button", { name: "Cancel" });
+ await act(async () => {
+ fireEvent.click(cancelBtn);
+ });
+
+ // Modal closed, backend NOT called, window.confirm NEVER called
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(api.deleteCampaign).not.toHaveBeenCalled();
+ expect(confirmSpy).not.toHaveBeenCalled();
+ });
+
+ it("confirms campaign deletion in ConfirmModal and executes deleteCampaign", async () => {
+ renderWithProviders(<CampaignsPage />, "/campaigns");
+
+ // Wait for initial load
+ await waitFor(() => {
+ expect(screen.getAllByText("Alpha Operation").length).toBeGreaterThanOrEqual(1);
+ });
+
+ // Switch to Scope tab
+ fireEvent.click(screen.getByRole("tab", { name: "Scope" }));
+
+ const picker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;
+ fireEvent.change(picker, { target: { value: "camp-alpha" } });
+
+ const deleteBtn = screen.getByRole("button", { name: "Delete" });
+ expect(deleteBtn).not.toBeDisabled();
+
+ await act(async () => {
+ fireEvent.click(deleteBtn);
+ });
+
+ // Click the Confirm button in the modal
+ const modalConfirmBtn = screen.getByRole("button", { name: "Delete Campaign" });
+ await act(async () => {
+ fireEvent.click(modalConfirmBtn);
+ });
+
+ // Backend called with camp-alpha, window.confirm NEVER called
+ await waitFor(() => {
+ expect(api.deleteCampaign).toHaveBeenCalledWith("camp-alpha");
+ });
+ expect(confirmSpy).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("ReportsPage Delete Confirmation", () => {
+ it("opens ConfirmModal for single report deletion, cancel aborts, confirm executes deleteReport", async () => {
+ // Set active campaign in storage
+ sessionStorage.setItem("ares.dashboard.selectedCampaignId", JSON.stringify("camp-alpha"));
+ renderWithProviders(<ReportsPage />, "/reports?tab=Library");
+
+ // Wait for reports table to load
+ await waitFor(() => {
+ expect(screen.getByText("ares-report-alpha-2026.pdf")).toBeInTheDocument();
+ });
+
+ // Get delete buttons in the table
+ const deleteButtons = screen.getAllByRole("button", { name: "Delete" });
+ expect(deleteButtons.length).toBe(2);
+
+ // Click Delete on first report
+ await act(async () => {
+ fireEvent.click(deleteButtons[0]);
+ });
+
+ // ConfirmModal should be visible with specific description
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "Delete Report" })).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ 'Permanently delete report artifact "ares-report-alpha-2026.pdf". This action cannot be undone.'
+ )
+ ).toBeInTheDocument();
+
+ // Click Cancel first
+ const cancelBtn = screen.getByRole("button", { name: "Cancel" });
+ await act(async () => {
+ fireEvent.click(cancelBtn);
+ });
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(api.deleteReport).not.toHaveBeenCalled();
+
+ // Open modal again and confirm
+ await act(async () => {
+ fireEvent.click(deleteButtons[0]);
+ });
+ const confirmModalBtn = screen.getByRole("button", { name: "Delete Report" });
+ await act(async () => {
+ fireEvent.click(confirmModalBtn);
+ });
+
+ await waitFor(() => {
+ expect(api.deleteReport).toHaveBeenCalledWith("camp-alpha", "ares-report-alpha-2026.pdf");
+ });
+ expect(confirmSpy).not.toHaveBeenCalled();
+ });
+
+ it("opens ConfirmModal for 'Delete all' reports, cancel aborts, confirm executes clearReports", async () => {
+ sessionStorage.setItem("ares.dashboard.selectedCampaignId", JSON.stringify("camp-alpha"));
+ renderWithProviders(<ReportsPage />, "/reports?tab=Library");
+
+ await waitFor(() => {
+ expect(screen.getByRole("button", { name: "Delete all" })).toBeInTheDocument();
+ });
+
+ const deleteAllBtn = screen.getByRole("button", { name: "Delete all" });
+ await act(async () => {
+ fireEvent.click(deleteAllBtn);
+ });
+
+ // ConfirmModal should be open with count
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "Delete All Reports" })).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ "Permanently delete all 2 report artifacts for this campaign. This action cannot be undone."
+ )
+ ).toBeInTheDocument();
+
+ // Cancel test
+ const cancelBtn = screen.getByRole("button", { name: "Cancel" });
+ await act(async () => {
+ fireEvent.click(cancelBtn);
+ });
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(api.clearReports).not.toHaveBeenCalled();
+
+ // Open and confirm
+ await act(async () => {
+ fireEvent.click(deleteAllBtn);
+ });
+ const confirmAllBtn = screen.getByRole("button", { name: "Delete All Reports" });
+ await act(async () => {
+ fireEvent.click(confirmAllBtn);
+ });
+
+ await waitFor(() => {
+ expect(api.clearReports).toHaveBeenCalledWith("camp-alpha");
+ });
+ expect(confirmSpy).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/frontend/src/features/dashboard/LoadingColorIndicator.test.tsx b/frontend/src/features/dashboard/LoadingColorIndicator.test.tsx
new file mode 100644
index 0000000..16f576b
--- /dev/null
+++ b/frontend/src/features/dashboard/LoadingColorIndicator.test.tsx
@@ -0,0 +1,152 @@
+// @vitest-environment jsdom
+import "../../test/setup";
+import "@testing-library/jest-dom/vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { 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";
+
+vi.mock("../auth/authContext", () => ({
+ useAuth: () => ({
+ user: { username: "operator", role: "operator" },
+ loading: false,
+ logout: vi.fn(),
+ logoutAll: vi.fn()
+ })
+}));
+
+let pendingModuleRun = false;
+
+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 () => [
+ { id: "cmp-1", name: "Campaign 1", status: "active" }
+ ]),
+ modules: vi.fn(async () => [
+ { id: "recon.portscan", name: "Port Scanner", description: "Scans ports", category: "recon" }
+ ]),
+ templates: vi.fn(async () => []),
+ executionChains: vi.fn(async () => []),
+ reports: vi.fn(async () => ({ campaign_id: "", reports: [] })),
+ monthlyStats: vi.fn(async () => ({ total: 0, confirmed_findings: 0, series: [] })),
+ runModule: vi.fn(() => new Promise((resolve) => {
+ if (!pendingModuleRun) {
+ resolve({ status: "success" });
+ }
+ }))
+ }
+ };
+});
+
+import { clearDashboardSession } from "./dashboardUiState";
+import { DashboardShell, ModulesPage, OverviewPage } from "./DashboardPages";
+
+describe("Loading & Empty State Non-Alarmist Color Consistency (ITEM 5)", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ clearDashboardSession();
+ pendingModuleRun = false;
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("OverviewPage empty state uses cyan styling instead of red alert", async () => {
+ const { api } = await import("../../api/client");
+ vi.mocked(api.campaigns).mockResolvedValueOnce([]);
+
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: 0 } }
+ });
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={["/"]}>
+ <DashboardShell>
+ <Routes>
+ <Route path="/" element={<OverviewPage />} />
+ </Routes>
+ </DashboardShell>
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+
+ await waitFor(() => {
+ expect(screen.getByText("No Campaigns Initialized")).toBeInTheDocument();
+ });
+
+ const heroWrap = document.querySelector(".fresh-hero-icon-wrap");
+ expect(heroWrap).toBeInTheDocument();
+
+ // Verify alarmist ShieldAlert with text-rose-500 is gone
+ const roseAlert = heroWrap?.querySelector(".text-rose-500");
+ expect(roseAlert).toBeNull();
+
+ // Verify cyan Target icon is present
+ const cyanIcon = heroWrap?.querySelector(".text-cyan-400");
+ expect(cyanIcon).toBeInTheDocument();
+ });
+
+ it("ModulesPage in-progress execution notice uses notice-info instead of notice-danger", async () => {
+ pendingModuleRun = true;
+
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: 0 } }
+ });
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={["/modules"]}>
+ <DashboardShell>
+ <Routes>
+ <Route path="/modules" element={<ModulesPage />} />
+ </Routes>
+ </DashboardShell>
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+
+ // Wait for modules to load
+ await waitFor(() => {
+ expect(screen.getByText("recon.portscan")).toBeInTheDocument();
+ });
+
+ // Select module
+ fireEvent.click(screen.getByText("recon.portscan"));
+
+ // Switch to Run Panel tab
+ fireEvent.click(screen.getByRole("tab", { name: "Run Panel" }));
+
+ // Select campaign
+ const campaignPicker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;
+ fireEvent.change(campaignPicker, { target: { value: "cmp-1" } });
+
+ await waitFor(() => {
+ expect(screen.getByRole("button", { name: /Execute recon.portscan/i })).toBeInTheDocument();
+ });
+
+ // Execute module to trigger run.isPending
+ fireEvent.click(screen.getByRole("button", { name: /Execute recon.portscan/i }));
+
+ await waitFor(() => {
+ expect(screen.getByText(/Module execution in progress/i)).toBeInTheDocument();
+ });
+
+ const runningNotice = screen.getByText(/Module execution in progress/i).closest(".notice");
+ expect(runningNotice).toBeInTheDocument();
+
+ // Must NOT have danger/red class
+ expect(runningNotice).not.toHaveClass("notice-danger");
+
+ // Must have info/active class
+ expect(runningNotice).toHaveClass("notice-info");
+ });
+});
diff --git a/frontend/src/features/dashboard/ReportsLibraryCampaignPicker.test.tsx b/frontend/src/features/dashboard/ReportsLibraryCampaignPicker.test.tsx
new file mode 100644
index 0000000..a6a9a94
--- /dev/null
+++ b/frontend/src/features/dashboard/ReportsLibraryCampaignPicker.test.tsx
@@ -0,0 +1,201 @@
+// @vitest-environment jsdom
+import "../../test/setup";
+import "@testing-library/jest-dom/vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { 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";
+
+const mockCampaigns: Campaign[] = [
+ {
+ id: "cmp-alpha",
+ name: "Operation Alpha",
+ target: "10.0.0.1",
+ status: "active",
+ created_at: "2026-03-01T00:00:00Z"
+ } as unknown as Campaign,
+ {
+ id: "cmp-beta",
+ name: "Operation Beta",
+ target: "10.0.0.2",
+ status: "completed",
+ created_at: "2026-03-02T00:00:00Z"
+ } as unknown as Campaign
+];
+
+vi.mock("../auth/authContext", () => ({
+ useAuth: () => ({
+ user: { username: "operator", role: "operator" },
+ 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),
+ modules: vi.fn(async () => []),
+ templates: vi.fn(async () => []),
+ reports: vi.fn(async (id: string) => {
+ if (id === "cmp-alpha") {
+ return {
+ campaign_id: "cmp-alpha",
+ reports: [
+ {
+ filename: "ares-report-alpha.html",
+ format: "html",
+ size_bytes: 1048576,
+ modified_at: "2026-03-01T12:00:00Z"
+ }
+ ]
+ };
+ }
+ if (id === "cmp-beta") {
+ return {
+ campaign_id: "cmp-beta",
+ reports: [
+ {
+ filename: "ares-report-beta.pdf",
+ format: "pdf",
+ size_bytes: 2097152,
+ modified_at: "2026-03-02T12:00:00Z"
+ }
+ ]
+ };
+ }
+ return { campaign_id: id, reports: [] };
+ }),
+ deleteReport: vi.fn(async () => ({})),
+ clearReports: vi.fn(async () => ({})),
+ generateReport: vi.fn(async () => ({ status: "generated", filename: "test.html" })),
+ downloadReport: vi.fn(async () => new Blob(["test"]))
+ }
+ };
+});
+
+import { clearDashboardSession } from "./dashboardUiState";
+import { DashboardShell, ReportsPage } from "./DashboardPages";
+
+function renderReportsPage() {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ staleTime: 0
+ }
+ }
+ });
+
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={["/reports"]}>
+ <DashboardShell>
+ <Routes>
+ <Route path="/reports" element={<ReportsPage />} />
+ </Routes>
+ </DashboardShell>
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+}
+
+describe("ReportsPage Library Tab CampaignPicker (REP-01)", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ clearDashboardSession();
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("renders CampaignPicker above 'Select a campaign to list reports.' when no campaign is selected", async () => {
+ renderReportsPage();
+
+ // Switch to Library tab
+ const libraryTabBtn = screen.getByRole("tab", { name: "Library" });
+ fireEvent.click(libraryTabBtn);
+
+ // Verify CampaignPicker is visible in the Library tab
+ await waitFor(() => {
+ const picker = screen.getByLabelText("Target Campaign");
+ expect(picker).toBeInTheDocument();
+ expect(picker).toHaveAttribute("id", "library-campaign-select");
+ });
+
+ // Verify empty state message is shown
+ expect(screen.getByText("Select a campaign to list reports.")).toBeInTheDocument();
+ });
+
+ it("selecting a campaign in Library tab lists reports and hides the empty message", async () => {
+ renderReportsPage();
+
+ const libraryTabBtn = screen.getByRole("tab", { name: "Library" });
+ fireEvent.click(libraryTabBtn);
+
+ await waitFor(() => {
+ expect(screen.getAllByText("Operation Alpha").length).toBeGreaterThanOrEqual(1);
+ });
+
+ const picker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;
+ fireEvent.change(picker, { target: { value: "cmp-alpha" } });
+
+ // Reports for cmp-alpha should appear and empty state should disappear
+ await waitFor(() => {
+ expect(screen.getByText("ares-report-alpha.html")).toBeInTheDocument();
+ });
+
+ expect(screen.queryByText("Select a campaign to list reports.")).not.toBeInTheDocument();
+ });
+
+ it("synchronizes campaign selection between Library and Generate tabs bidirectionally", async () => {
+ renderReportsPage();
+
+ // 1. In Library tab, select cmp-alpha
+ fireEvent.click(screen.getByRole("tab", { name: "Library" }));
+ await waitFor(() => {
+ expect(screen.getAllByText("Operation Alpha").length).toBeGreaterThanOrEqual(1);
+ });
+
+ const libraryPicker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;
+ fireEvent.change(libraryPicker, { target: { value: "cmp-alpha" } });
+
+ await waitFor(() => {
+ expect(screen.getByText("ares-report-alpha.html")).toBeInTheDocument();
+ });
+
+ // 2. Switch to Generate tab -> cmp-alpha should already be selected
+ fireEvent.click(screen.getByRole("tab", { name: "Generate" }));
+
+ await waitFor(() => {
+ const generatePicker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;
+ expect(generatePicker.id).toBe("report-campaign-select");
+ expect(generatePicker.value).toBe("cmp-alpha");
+ });
+
+ // 3. In Generate tab, change selection to cmp-beta
+ const generatePicker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;
+ fireEvent.change(generatePicker, { target: { value: "cmp-beta" } });
+ expect(generatePicker.value).toBe("cmp-beta");
+
+ // 4. Switch back to Library tab -> cmp-beta should be selected and its report listed
+ fireEvent.click(screen.getByRole("tab", { name: "Library" }));
+
+ await waitFor(() => {
+ const updatedLibraryPicker = screen.getByLabelText("Target Campaign") as HTMLSelectElement;
+ expect(updatedLibraryPicker.id).toBe("library-campaign-select");
+ expect(updatedLibraryPicker.value).toBe("cmp-beta");
+ expect(screen.getByText("ares-report-beta.pdf")).toBeInTheDocument();
+ });
+ });
+});
diff --git a/frontend/src/features/dashboard/SecurityPasswordConfirm.test.tsx b/frontend/src/features/dashboard/SecurityPasswordConfirm.test.tsx
new file mode 100644
index 0000000..d32052e
--- /dev/null
+++ b/frontend/src/features/dashboard/SecurityPasswordConfirm.test.tsx
@@ -0,0 +1,129 @@
+// @vitest-environment jsdom
+import "../../test/setup";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { api } from "../../api/client";
+import { SecurityPage } from "./DashboardPages";
+
+vi.mock("../auth/authContext", () => ({
+ useAuth: () => ({
+ user: { username: "admin", role: "team_lead" },
+ loading: false,
+ logout: vi.fn(),
+ logoutAll: vi.fn()
+ })
+}));
+
+describe("SecurityPage Password Confirmation (SEC-02)", () => {
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false }
+ }
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ sessionStorage.clear();
+ vi.restoreAllMocks();
+ });
+
+ function renderPage() {
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={["/security?tab=Account"]}>
+ <SecurityPage />
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+ }
+
+ it("renders 3 password fields: current, new, and confirm new password", () => {
+ renderPage();
+
+ expect(screen.getByPlaceholderText("Current password")).toBeInTheDocument();
+ expect(screen.getByPlaceholderText("New password")).toBeInTheDocument();
+ expect(screen.getByPlaceholderText("Confirm new password")).toBeInTheDocument();
+ });
+
+ it("disables submit button and shows no error on initial load when fields are empty", () => {
+ renderPage();
+
+ const submitBtn = screen.getByRole("button", { name: "Change Password" });
+ expect(submitBtn).toBeDisabled();
+ expect(screen.queryByText("Passwords do not match")).toBeNull();
+ });
+
+ it("shows inline error and disables submit when passwords do not match", () => {
+ renderPage();
+
+ const currentInput = screen.getByPlaceholderText("Current password");
+ const newInput = screen.getByPlaceholderText("New password");
+ const confirmInput = screen.getByPlaceholderText("Confirm new password");
+ const submitBtn = screen.getByRole("button", { name: "Change Password" });
+
+ fireEvent.change(currentInput, { target: { value: "oldsecret12345" } });
+ fireEvent.change(newInput, { target: { value: "newsecret12345" } });
+ fireEvent.change(confirmInput, { target: { value: "mismatch12345" } });
+
+ expect(screen.getByRole("alert")).toHaveTextContent("Passwords do not match");
+ expect(confirmInput.className).toContain("border-rose-500");
+ expect(submitBtn).toBeDisabled();
+ });
+
+ it("clears inline error and enables submit when passwords match", () => {
+ renderPage();
+
+ const currentInput = screen.getByPlaceholderText("Current password");
+ const newInput = screen.getByPlaceholderText("New password");
+ const confirmInput = screen.getByPlaceholderText("Confirm new password");
+ const submitBtn = screen.getByRole("button", { name: "Change Password" });
+
+ fireEvent.change(currentInput, { target: { value: "oldsecret12345" } });
+ fireEvent.change(newInput, { target: { value: "newsecret12345" } });
+ fireEvent.change(confirmInput, { target: { value: "newsecret12345" } });
+
+ expect(screen.queryByText("Passwords do not match")).toBeNull();
+ expect(confirmInput.className).not.toContain("border-rose-500");
+ expect(submitBtn).not.toBeDisabled();
+ });
+
+ it("submits changePassword with current_password and new_password without payload alteration", async () => {
+ const changeSpy = vi.spyOn(api, "changePassword").mockResolvedValue({
+ status: "ok",
+ message: "Password changed successfully"
+ });
+
+ renderPage();
+
+ const currentInput = screen.getByPlaceholderText("Current password");
+ const newInput = screen.getByPlaceholderText("New password");
+ const confirmInput = screen.getByPlaceholderText("Confirm new password");
+ const submitBtn = screen.getByRole("button", { name: "Change Password" });
+
+ fireEvent.change(currentInput, { target: { value: "currentPass123!" } });
+ fireEvent.change(newInput, { target: { value: "newSecurePass123!" } });
+ fireEvent.change(confirmInput, { target: { value: "newSecurePass123!" } });
+
+ fireEvent.click(submitBtn);
+
+ await waitFor(() => {
+ expect(changeSpy).toHaveBeenCalledWith({
+ current_password: "currentPass123!",
+ new_password: "newSecurePass123!"
+ });
+ });
+
+ // On success, fields should be reset
+ await waitFor(() => {
+ expect(currentInput).toHaveValue("");
+ expect(newInput).toHaveValue("");
+ expect(confirmInput).toHaveValue("");
+ });
+ });
+});
diff --git a/frontend/src/features/dashboard/TabParamSync.test.tsx b/frontend/src/features/dashboard/TabParamSync.test.tsx
new file mode 100644
index 0000000..abe1db1
--- /dev/null
+++ b/frontend/src/features/dashboard/TabParamSync.test.tsx
@@ -0,0 +1,345 @@
+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";
+import { MemoryRouter, Routes, Route, useLocation, useNavigate } from "react-router-dom";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ CampaignsPage,
+ ModulesPage,
+ ReportsPage,
+ TemplatesPage,
+ StrategyPage,
+ SecurityPage,
+ EdrPage,
+ LivePage
+} from "./DashboardPages";
+import { DashboardUiProvider } from "./dashboardUi";
+import type { DashboardUiState } from "./dashboardUiState";
+
+vi.mock("../../api/client", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../api/client")>();
+ return {
+ ...actual,
+ api: {
+ ...actual.api,
+ campaigns: vi.fn().mockResolvedValue([
+ { id: "camp-123", name: "Alpha", client: "SecOps", targets: ["10.0.0.1"], scope_cidrs: ["10.0.0.0/24"], noise_profile: "stealth" }
+ ]),
+ campaign: vi.fn().mockResolvedValue({ id: "camp-123", name: "Alpha", client: "SecOps", targets: ["10.0.0.1"], scope_cidrs: ["10.0.0.0/24"], noise_profile: "stealth" }),
+ findings: vi.fn().mockResolvedValue([]),
+ cvss: vi.fn().mockResolvedValue([]),
+ diffCampaign: vi.fn().mockResolvedValue({}),
+ modules: vi.fn().mockResolvedValue([
+ { id: "recon.fingerprint", name: "Recon", description: "Fingerprint target", category: "recon", opsec_level: "LOW" },
+ { id: "ad.kerberoast", name: "Kerberoast", description: "Request TGS", category: "ad", opsec_level: "MEDIUM" }
+ ]),
+ executionChains: vi.fn().mockResolvedValue([]),
+ reports: vi.fn().mockResolvedValue({ reports: [{ filename: "audit.html", format: "html" }] }),
+ templates: vi.fn().mockResolvedValue([{ id: "tpl-1", name: "Standard Recon", description: "Default recon plan", stages: 2, modules: 4 }]),
+ activeStrategy: vi.fn().mockResolvedValue({ llm_backends: { claude: true, local: true } }),
+ apiKeys: vi.fn().mockResolvedValue({ keys: [{ id: "key-1", name: "CI Key", prefix: "ares_ci", created_at: "2026-01-01" }] }),
+ securityAudit: vi.fn().mockResolvedValue({ events: [] }),
+ users: vi.fn().mockResolvedValue([]),
+ edrStats: vi.fn().mockResolvedValue({ message: "Ready", success_rate: 0.9 }),
+ liveEvents: vi.fn().mockResolvedValue([])
+ }
+ };
+});
+
+vi.mock("../auth/authContext", () => ({
+ useAuth: () => ({
+ user: { username: "operator", role: "team_lead" },
+ logout: vi.fn(),
+ logoutAll: vi.fn()
+ })
+}));
+
+const mockDashboardUi: DashboardUiState = {
+ selectedCampaignId: "camp-123",
+ setSelectedCampaignId: vi.fn(),
+ liveCampaignId: "camp-123",
+ setLiveCampaignId: vi.fn(),
+ liveConnected: true,
+ setLiveConnected: vi.fn(),
+ liveEvents: [],
+ pushLiveEvent: vi.fn(),
+ clearLiveEvents: vi.fn(),
+ campaigns: [
+ { id: "camp-123", name: "Alpha", client: "SecOps", targets: ["10.0.0.1"], scope_cidrs: ["10.0.0.0/24"], noise_profile: "stealth" }
+ ],
+ campaignsLoading: false,
+ campaignsError: null,
+ deleteCampaign: vi.fn().mockResolvedValue(true),
+ isDeletingCampaign: false,
+ refetchCampaigns: vi.fn().mockResolvedValue(undefined)
+};
+
+// Helper component that displays the current URL search query for assertions
+function UrlTracker() {
+ const location = useLocation();
+ return <div data-testid="url-tracker">{`${location.pathname}${location.search}`}</div>;
+}
+
+describe("Tab Navigation URL Synchronization (Item 6)", () => {
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, gcTime: 0 }
+ }
+ });
+ queryClient.setQueryData(["modules"], [
+ { id: "recon.fingerprint", name: "Recon", description: "Fingerprint target", category: "recon", opsec_level: "LOW" },
+ { id: "ad.kerberoast", name: "Kerberoast", description: "Request TGS", category: "ad", opsec_level: "MEDIUM" }
+ ]);
+ queryClient.setQueryData(["campaign", "camp-123"], {
+ id: "camp-123", name: "Alpha", client: "SecOps", targets: ["10.0.0.1"], scope_cidrs: ["10.0.0.0/24"], noise_profile: "stealth"
+ });
+ sessionStorage.clear();
+ localStorage.clear();
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ });
+
+ it("syncs /campaigns to URL /campaigns?tab=List on mount", async () => {
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DashboardUiProvider value={mockDashboardUi}>
+ <MemoryRouter initialEntries={["/campaigns"]}>
+ <UrlTracker />
+ <Routes>
+ <Route path="/campaigns" element={<CampaignsPage />} />
+ </Routes>
+ </MemoryRouter>
+ </DashboardUiProvider>
+ </QueryClientProvider>
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId("url-tracker").textContent).toBe("/campaigns?tab=List");
+ });
+ });
+
+ it("updates URL to /campaigns?tab=Scope when clicking Scope tab", async () => {
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DashboardUiProvider value={mockDashboardUi}>
+ <MemoryRouter initialEntries={["/campaigns?tab=List"]}>
+ <UrlTracker />
+ <Routes>
+ <Route path="/campaigns" element={<CampaignsPage />} />
+ </Routes>
+ </MemoryRouter>
+ </DashboardUiProvider>
+ </QueryClientProvider>
+ );
+
+ const scopeTabBtn = screen.getByRole("tab", { name: "Scope" });
+ fireEvent.click(scopeTabBtn);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("url-tracker").textContent).toBe("/campaigns?tab=Scope");
+ });
+ });
+
+ it("activates API Keys tab directly when opening /security?tab=API+Keys", async () => {
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DashboardUiProvider value={mockDashboardUi}>
+ <MemoryRouter initialEntries={["/security?tab=API+Keys"]}>
+ <UrlTracker />
+ <Routes>
+ <Route path="/security" element={<SecurityPage />} />
+ </Routes>
+ </MemoryRouter>
+ </DashboardUiProvider>
+ </QueryClientProvider>
+ );
+
+ const apiKeyTab = screen.getByRole("tab", { name: "API Keys" });
+ expect(apiKeyTab.classList.contains("active")).toBe(true);
+ expect(screen.getByRole("heading", { name: "API Keys" })).toBeDefined();
+ });
+
+ it("falls back to default List tab when opening /campaigns?tab=xyz without crashing", async () => {
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DashboardUiProvider value={mockDashboardUi}>
+ <MemoryRouter initialEntries={["/campaigns?tab=xyz"]}>
+ <UrlTracker />
+ <Routes>
+ <Route path="/campaigns" element={<CampaignsPage />} />
+ </Routes>
+ </MemoryRouter>
+ </DashboardUiProvider>
+ </QueryClientProvider>
+ );
+
+ const listTab = screen.getByRole("tab", { name: "List" });
+ expect(listTab.classList.contains("active")).toBe(true);
+ expect(screen.getByRole("heading", { name: "Create Campaign" })).toBeDefined();
+ });
+
+ it("activates Run Panel and selects module when opening /modules?tab=Run+Panel&module=recon.fingerprint", async () => {
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DashboardUiProvider value={mockDashboardUi}>
+ <MemoryRouter initialEntries={["/modules?tab=Run+Panel&module=recon.fingerprint"]}>
+ <UrlTracker />
+ <Routes>
+ <Route path="/modules" element={<ModulesPage />} />
+ </Routes>
+ </MemoryRouter>
+ </DashboardUiProvider>
+ </QueryClientProvider>
+ );
+
+ // Run Panel tab should be active
+ const runPanelTab = screen.getByRole("tab", { name: "Run Panel" });
+ expect(runPanelTab.classList.contains("active")).toBe(true);
+
+ // Module should be selected
+ await waitFor(() => {
+ expect(screen.getByText("recon.fingerprint")).toBeDefined();
+ });
+ });
+
+ it("synchronizes ReportsPage default tab to /reports?tab=Generate", async () => {
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DashboardUiProvider value={mockDashboardUi}>
+ <MemoryRouter initialEntries={["/reports"]}>
+ <UrlTracker />
+ <Routes>
+ <Route path="/reports" element={<ReportsPage />} />
+ </Routes>
+ </MemoryRouter>
+ </DashboardUiProvider>
+ </QueryClientProvider>
+ );
+ await waitFor(() => {
+ expect(screen.getByTestId("url-tracker").textContent).toBe("/reports?tab=Generate");
+ });
+ });
+
+ it("synchronizes TemplatesPage default tab to /templates?tab=Templates", async () => {
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DashboardUiProvider value={mockDashboardUi}>
+ <MemoryRouter initialEntries={["/templates"]}>
+ <UrlTracker />
+ <Routes>
+ <Route path="/templates" element={<TemplatesPage />} />
+ </Routes>
+ </MemoryRouter>
+ </DashboardUiProvider>
+ </QueryClientProvider>
+ );
+ await waitFor(() => {
+ expect(screen.getByTestId("url-tracker").textContent).toBe("/templates?tab=Templates");
+ });
+ });
+
+ it("synchronizes StrategyPage default tab to /strategy?tab=Objective", async () => {
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DashboardUiProvider value={mockDashboardUi}>
+ <MemoryRouter initialEntries={["/strategy"]}>
+ <UrlTracker />
+ <Routes>
+ <Route path="/strategy" element={<StrategyPage />} />
+ </Routes>
+ </MemoryRouter>
+ </DashboardUiProvider>
+ </QueryClientProvider>
+ );
+ await waitFor(() => {
+ expect(screen.getByTestId("url-tracker").textContent).toBe("/strategy?tab=Objective");
+ });
+ });
+
+ it("synchronizes EdrPage default tab to /edr?tab=Knowledge+Base", async () => {
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DashboardUiProvider value={mockDashboardUi}>
+ <MemoryRouter initialEntries={["/edr"]}>
+ <UrlTracker />
+ <Routes>
+ <Route path="/edr" element={<EdrPage />} />
+ </Routes>
+ </MemoryRouter>
+ </DashboardUiProvider>
+ </QueryClientProvider>
+ );
+ await waitFor(() => {
+ expect(screen.getByTestId("url-tracker").textContent).toBe("/edr?tab=Knowledge+Base");
+ });
+ });
+
+ it("synchronizes LivePage default tab to /live?tab=Stream", async () => {
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DashboardUiProvider value={mockDashboardUi}>
+ <MemoryRouter initialEntries={["/live"]}>
+ <UrlTracker />
+ <Routes>
+ <Route path="/live" element={<LivePage />} />
+ </Routes>
+ </MemoryRouter>
+ </DashboardUiProvider>
+ </QueryClientProvider>
+ );
+ await waitFor(() => {
+ expect(screen.getByTestId("url-tracker").textContent).toBe("/live?tab=Stream");
+ });
+ });
+
+ it("does not accumulate browser history entries when switching tabs due to replace: true", async () => {
+ function BackButton() {
+ const nav = useNavigate();
+ return (
+ <button data-testid="back-btn" onClick={() => nav(-1)}>
+ Back
+ </button>
+ );
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <DashboardUiProvider value={mockDashboardUi}>
+ <MemoryRouter initialEntries={["/modules?tab=Catalog", "/campaigns?tab=List"]} initialIndex={1}>
+ <BackButton />
+ <UrlTracker />
+ <Routes>
+ <Route path="/campaigns" element={<CampaignsPage />} />
+ <Route path="/modules" element={<ModulesPage />} />
+ </Routes>
+ </MemoryRouter>
+ </DashboardUiProvider>
+ </QueryClientProvider>
+ );
+
+ // Switch to Scope tab (replace: true)
+ const scopeTab = screen.getByRole("tab", { name: "Scope" });
+ fireEvent.click(scopeTab);
+ await waitFor(() => {
+ expect(screen.getByTestId("url-tracker").textContent).toBe("/campaigns?tab=Scope");
+ });
+
+ // Switch to Findings tab (replace: true)
+ const findingsTab = screen.getByRole("tab", { name: "Findings" });
+ fireEvent.click(findingsTab);
+ await waitFor(() => {
+ expect(screen.getByTestId("url-tracker").textContent).toBe("/campaigns?tab=Findings");
+ });
+
+ // Now click Back — because replace: true was used on both tab changes, Back goes to the previous route (/modules?tab=Catalog)
+ fireEvent.click(screen.getByTestId("back-btn"));
+ await waitFor(() => {
+ expect(screen.getByTestId("url-tracker").textContent).toBe("/modules?tab=Catalog");
+ });
+ });
+});
diff --git a/frontend/src/features/dashboard/dashboardUi.test.tsx b/frontend/src/features/dashboard/dashboardUi.test.tsx
index 2747a36..6f7f928 100644
--- a/frontend/src/features/dashboard/dashboardUi.test.tsx
+++ b/frontend/src/features/dashboard/dashboardUi.test.tsx
@@ -27,14 +27,6 @@ const PERSISTENT_CASES: StateCase[] = [
{ label: "live campaign", key: "ares.dashboard.live.campaignId", fallback: "", stored: "campaign-a", updated: "campaign-b" },
{ label: "campaign comparison", key: "ares.dashboard.campaigns.compareId", fallback: "", stored: "campaign-a", updated: "campaign-b" },
{ label: "selected module", key: "ares.dashboard.modules.selectedId", fallback: "", stored: "module-a", updated: "module-b" },
- { label: "campaign tab", key: "ares.dashboard.campaigns.tab", fallback: "List", stored: "Scope", updated: "Findings" },
- { label: "module tab", key: "ares.dashboard.modules.tab", fallback: "Catalog", stored: "Run Panel", updated: "Results" },
- { label: "report tab", key: "ares.dashboard.reports.tab", fallback: "Generate", stored: "Library", updated: "Generate" },
- { label: "template tab", key: "ares.dashboard.templates.tab", fallback: "Templates", stored: "Plan Builder", updated: "Templates" },
- { label: "strategy tab", key: "ares.dashboard.strategy.tab", fallback: "Objective", stored: "Active", updated: "Result" },
- { label: "security tab", key: "ares.dashboard.security.tab", fallback: "Account", stored: "API Keys", updated: "Audit" },
- { label: "EDR tab", key: "ares.dashboard.edr.tab", fallback: "Knowledge Base", stored: "Report Outcome", updated: "Knowledge Base" },
- { label: "live tab", key: "ares.dashboard.live.tab", fallback: "Stream", stored: "Buffer", updated: "Stream" },
{ label: "module category", key: "ares.dashboard.modules.category", fallback: "", stored: "network", updated: "recon" },
{ label: "module OPSEC", key: "ares.dashboard.modules.opsec", fallback: "", stored: "LOW", updated: "MEDIUM" },
{ label: "report format", key: "ares.dashboard.reports.format", fallback: "html", stored: "pdf", updated: "markdown" },
@@ -69,12 +61,11 @@ const VOLATILE_CASES: StateCase[] = [
];
const DIRECT_WRITER_CASES = [
- ["campaign tab", "ares.dashboard.campaigns.tab", "Scope"],
+ ["selected campaign", "ares.dashboard.selectedCampaignId", "campaign-b"],
["selected module", "ares.dashboard.modules.selectedId", "module-a"],
- ["module tab", "ares.dashboard.modules.tab", "Run Panel"],
- ["report tab", "ares.dashboard.reports.tab", "Library"],
- ["template name", "ares.dashboard.templates.name", "template-a"],
- ["template tab", "ares.dashboard.templates.tab", "Plan Builder"]
+ ["module category", "ares.dashboard.modules.category", "recon"],
+ ["report format", "ares.dashboard.reports.format", "markdown"],
+ ["template name", "ares.dashboard.templates.name", "template-a"]
] as const;
function requireFixed(condition: boolean, message: string): void {
@@ -323,20 +314,20 @@ describe("dashboard session persistence policy", () => {
});
it("blocks an old epoch writer after full cleanup and permits a new mount", () => {
- const key = "ares.dashboard.modules.tab";
+ const key = "ares.dashboard.modules.selectedId";
const stale = renderHook(() => useDashboardSessionWriter());
- const initialAccepted = stale.result.current(key, "Run Panel");
+ const initialAccepted = stale.result.current(key, "module-a");
requireFixed(initialAccepted, "Initial mounted writer should be accepted.");
clearDashboardSession();
- const staleRejected = stale.result.current(key, "Results") === false;
+ const staleRejected = stale.result.current(key, "module-b") === false;
const staleAbsent = sessionStorage.getItem(key) === null;
requireFixed(staleRejected && staleAbsent, "Old epoch writer should remain blocked.");
const current = renderHook(() => useDashboardSessionWriter());
- const currentAccepted = current.result.current(key, "Catalog");
- const currentPersisted = sessionStorage.getItem(key) === JSON.stringify("Catalog");
+ const currentAccepted = current.result.current(key, "module-c");
+ const currentPersisted = sessionStorage.getItem(key) === JSON.stringify("module-c");
requireFixed(currentAccepted && currentPersisted, "New epoch writer should persist normally.");
});
@@ -346,18 +337,18 @@ describe("dashboard session persistence policy", () => {
throw new DOMException("unavailable", "SecurityError");
});
try {
- const rejected = result.current("ares.dashboard.modules.tab", "Run Panel") === false;
+ const rejected = result.current("ares.dashboard.modules.selectedId", "module-a") === false;
requireFixed(rejected, "Failed storage write should be rejected.");
} finally {
setItem.mockRestore();
}
- const storageAbsent = sessionStorage.getItem("ares.dashboard.modules.tab") === null;
+ const storageAbsent = sessionStorage.getItem("ares.dashboard.modules.selectedId") === null;
requireFixed(storageAbsent, "Failed storage write should remain absent.");
});
it("logically blocks an allowed key whose full-cleanup removal fails", () => {
- const key = "ares.dashboard.modules.tab";
- sessionStorage.setItem(key, JSON.stringify("Run Panel"));
+ const key = "ares.dashboard.modules.selectedId";
+ sessionStorage.setItem(key, JSON.stringify("module-a"));
const originalRemoveItem = Storage.prototype.removeItem;
const removeItem = vi.spyOn(Storage.prototype, "removeItem").mockImplementation(function (
this: Storage,
@@ -376,8 +367,8 @@ describe("dashboard session persistence policy", () => {
const neutralized = sessionStorage.getItem(key) === "";
requireFixed(neutralized, "Failed cleanup should neutralize the stored key.");
- const { result } = renderHook(() => useSessionState(key, "Catalog"));
- const fallbackUsed = result.current[0] === "Catalog";
+ const { result } = renderHook(() => useSessionState(key, "module-c"));
+ const fallbackUsed = result.current[0] === "module-c";
requireFixed(fallbackUsed, "Blocked key should not rehydrate old account state.");
});
diff --git a/frontend/src/features/dashboard/dashboardUiState.ts b/frontend/src/features/dashboard/dashboardUiState.ts
index 57d7789..662b7cf 100644
--- a/frontend/src/features/dashboard/dashboardUiState.ts
+++ b/frontend/src/features/dashboard/dashboardUiState.ts
@@ -1,4 +1,5 @@
import { createContext, Dispatch, SetStateAction, useCallback, useContext, useEffect, useRef, useState } from "react";
+import { useSearchParams } from "react-router-dom";
import type { Campaign, UserProfile } from "../../api/types";
const DASHBOARD_SESSION_PREFIX = "ares.dashboard.";
@@ -9,14 +10,6 @@ const PERSISTENT_DASHBOARD_KEYS = new Set<string>([
"ares.dashboard.live.campaignId",
"ares.dashboard.campaigns.compareId",
"ares.dashboard.modules.selectedId",
- "ares.dashboard.campaigns.tab",
- "ares.dashboard.modules.tab",
- "ares.dashboard.reports.tab",
- "ares.dashboard.templates.tab",
- "ares.dashboard.strategy.tab",
- "ares.dashboard.security.tab",
- "ares.dashboard.edr.tab",
- "ares.dashboard.live.tab",
"ares.dashboard.modules.category",
"ares.dashboard.modules.opsec",
"ares.dashboard.reports.format",
@@ -191,3 +184,41 @@ export function useSessionState<T>(key: string, initialValue: T): readonly [T, D
return [value, setValue] as const;
}
+
+export function useTabParam(defaultTab: string) {
+ const [searchParams, setSearchParams] = useSearchParams();
+ const rawTab = searchParams.get("tab");
+
+ useEffect(() => {
+ if (!searchParams.get("tab")) {
+ setSearchParams(
+ (prev) => {
+ if (prev.get("tab")) return prev;
+ const next = new URLSearchParams(prev);
+ next.set("tab", defaultTab);
+ return next;
+ },
+ { replace: true }
+ );
+ }
+ }, [defaultTab, searchParams, setSearchParams]);
+
+ const activeTab = rawTab ?? defaultTab;
+
+ const setActiveTab = useCallback(
+ (tab: string) => {
+ setSearchParams(
+ (prev) => {
+ const next = new URLSearchParams(prev);
+ next.set("tab", tab);
+ return next;
+ },
+ { replace: true }
+ );
+ },
+ [setSearchParams]
+ );
+
+ return [activeTab, setActiveTab] as const;
+}
+
diff --git a/frontend/src/features/graph/TacticalInspectorDrawer.tsx b/frontend/src/features/graph/TacticalInspectorDrawer.tsx
index bd47bfe..1f5bce0 100644
--- a/frontend/src/features/graph/TacticalInspectorDrawer.tsx
+++ b/frontend/src/features/graph/TacticalInspectorDrawer.tsx
@@ -152,7 +152,6 @@ export function TacticalInspectorDrawer({
...(customParams ?? {})
};
sessionStorage.setItem("ares.dashboard.modules.selectedId", JSON.stringify(moduleId));
- sessionStorage.setItem("ares.dashboard.modules.tab", JSON.stringify("Run Panel"));
navigate(`/modules?module=${encodeURIComponent(moduleId)}&target=${encodeURIComponent(targetVal)}&tab=Run+Panel`, {
state: { moduleId, target: targetVal, params: armParams, tab: "Run Panel" }
});
diff --git a/frontend/src/styles.css b/frontend/src/styles.css
index 9f7ecca..78709b9 100644
--- a/frontend/src/styles.css
+++ b/frontend/src/styles.css
@@ -1006,7 +1006,7 @@ button:disabled {
.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%);
+ background: radial-gradient(ellipse at 50% 0%, rgba(6, 182, 212, 0.08) 0%, rgba(18, 18, 21, 0.9) 70%, #0c0c0e 100%);
padding: 3.5rem 2rem 2.75rem;
text-align: center;
display: flex;
@@ -1022,9 +1022,9 @@ button:disabled {
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);
+ background: rgba(6, 182, 212, 0.1);
+ border: 1px solid rgba(6, 182, 212, 0.3);
+ box-shadow: 0 0 24px rgba(6, 182, 212, 0.15);
margin-bottom: 1.25rem;
}
@@ -1259,6 +1259,13 @@ textarea.field {
color: #fda4af;
}
+.notice-info,
+.notice-active {
+ border-color: rgba(6, 182, 212, 0.25);
+ background: rgba(6, 182, 212, 0.08);
+ color: #22d3ee;
+}
+
.notice-optimal,
.notice-success {
border-color: rgba(16, 185, 129, 0.25);