Skip to content

A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.

174 KB
Raw Blame
package opensuite.dashboard;

import opensuite.core.Bytes;
import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.core.Issue;
import opensuite.core.LogEntry;
import opensuite.core.MessageStore;
import opensuite.core.ScanTask;
import opensuite.core.SuiteContext;
import opensuite.core.ToolModule;
import opensuite.ui.MessageEditor;
import opensuite.ui.Theme;
import opensuite.ui.Ui;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

/**
 * The suite dashboard: the front tab and owner of the scanning engine.
 *
 * <p>It replaces the old scanner tab entirely. The left panel lists every scan
 * task as a card (live passive audit plus any active audits); the right panel
 * shows a summary, a sortable issue table with request/response detail, and the
 * selected task's event log. All model changes arrive on background threads and
 * are marshalled onto the EDT before touching Swing.
 */
public class DashboardTool implements ToolModule {

    // Severity palette (shared with the rest of the suite).
    private static final Color HIGH_COL   = Ui.SEV_HIGH;
    private static final Color MEDIUM_COL = Ui.SEV_MEDIUM;
    private static final Color LOW_COL    = Ui.SEV_LOW;
    private static final Color INFO_COL   = Ui.SEV_INFO;

    private static final Color CARD_BG      = Theme.CARD;
    private static final Color CARD_SEL_BG  = Ui.SELECTION;
    private static final Color CARD_BORDER  = Ui.GRID;
    private static final Color GREY_TEXT    = Theme.MUTED;
    private static final Color FINISHED_GREEN = Theme.OK;

    private SuiteContext ctx;
    /** The shared ZAP scan engine (same instance the passive-rules tab uses). */
    private opensuite.engine.ZapEngine zapEngine() {
        return opensuite.engine.ZapEngine.shared();
    }

    private final JPanel root = new JPanel(new BorderLayout());

    // ---- left ----
    private final JPanel taskList = new JPanel();
    private JTextField searchField;
    private final Map<ScanTask, TaskCard> cards = new IdentityHashMap<>();
    /** Re-run action per task, so "Scan again" relaunches the original scan. */
    private final Map<ScanTask, Runnable> rerun = new IdentityHashMap<>();
    // The engine settings each scan ran with, for "View configuration".
    private final Map<ScanTask, opensuite.engine.ScanConfig> taskConfigs = new IdentityHashMap<>();
    // Tasks whose finish has already triggered a project save.
    private final java.util.Set<ScanTask> savedOnFinish =
            java.util.Collections.newSetFromMap(new java.util.concurrent.ConcurrentHashMap<>());
    private ScanTask selected;
    /** Drives the sliding progress-bar animation while a crawl is running. */
    private javax.swing.Timer cardAnimTimer;

    // Background scan threads report progress, issues and log lines far faster
    // than the UI needs to redraw. These coalescers collapse each storm into at
    // most one refresh per interval so the event-dispatch thread never floods.
    private final opensuite.ui.Coalescer tasksRefresh  = new opensuite.ui.Coalescer(200, this::rebuildTasks);
    private final opensuite.ui.Coalescer issuesRefresh = new opensuite.ui.Coalescer(200, this::onIssuesChanged);
    private final opensuite.ui.Coalescer logRefresh     = new opensuite.ui.Coalescer(200, this::flushScanLog);
    private final java.util.Queue<LogEntry> logAddQueue = new java.util.concurrent.ConcurrentLinkedQueue<>();
    private volatile boolean logHasUpdates;

    // ---- right ----
    private final JLabel rightHeader = Ui.heading("");
    private final java.awt.CardLayout rightCards = new java.awt.CardLayout();
    private final JPanel rightBody = new JPanel(rightCards);
    private JTextArea crawlLog;
    private JLabel crawlStats;
    private JTabbedPane taskTabs;                 // the selected task's sub-tabs (Summary ... Live crawl view)
    private final JPanel taskTabsHost = new JPanel(new BorderLayout());   // where the sub-tabs live when attached
    private JFrame detachedFrame;                 // the task detail window when "Open in new window" is used
    private ScanTask detachedTask;
    private final CrawlGraph crawlGraph = new CrawlGraph();
    private final AuditItemsModel auditItemsModel = new AuditItemsModel();
    // A scan of several sites: its sites, each with its own progress, and the one site the tabs are narrowed to.
    private final SitesModel sitesModel = new SitesModel();
    private JPanel sitesCard;
    private JTable sitesTable;
    private JScrollPane sitesScroll;
    private final JComboBox<String> siteBox = Ui.combo(new String[] {ALL_SITES});
    private static final String ALL_SITES = "All sites";
    private String siteFilter;                 // the site shown alone ("http://host:port"), or null for every site
    private ScanTask siteBoxFor;
    private int siteBoxCount = -1;
    private boolean siteBoxFilling;
    private javax.swing.table.TableRowSorter<AuditItemsModel> auditItemsSorter;
    private javax.swing.table.TableRowSorter<ScanLogModel> taskLogSorter;
    private String auditItemsSearch = "";
    private JTable auditItemsTable;
    private MessageEditor auditBaseRequest;
    private final java.util.Map<ScanTask, LiveTaskDialog.Result> liveTaskSettings = new IdentityHashMap<>();
    // The crawl window's live Logger: a table of the scan's HTTP traffic with a
    // request/response viewer, fed from the shared store as the engine runs.
    private final ScanLogModel scanLogModel = new ScanLogModel();
    private JTable scanLogTable;
    private MessageEditor scanReq, scanResp;
    private final IssueTableModel summaryModel =
            new IssueTableModel(new String[]{"Issue type", "Host", "Time"});
    private final IssueTableModel issuesModel =
            new IssueTableModel(new String[]{"Time", "Source", "Issue type", "Host", "Path",
                    "Insertion point", "Severity", "Confidence", "Comment"});
    private JTable summaryTable;
    private JTable issuesTable;
    private final AuditLogModel auditLogModel = new AuditLogModel();
    private JTable auditLogTable;

    private final JLabel cfgType   = Ui.label("");
    private final JLabel cfgScope  = Ui.label("");
    private final JLabel cfgConfig = Ui.label("");

    // Task progress: the metrics we can source honestly from the ZAP engine,
    // shown in two columns matching the reference layout. Pending items and
    // network errors are not reported by the engine we poll, so they are left
    // out rather than shown as a fixed zero.
    private final JLabel progTotalItems   = Ui.label("");
    private JPanel cfgCapturingRow;
    private ToggleSwitch cfgCapturing;
    private JComponent cfgLink;
    private final JLabel progItemsActive  = Ui.label("");
    private final JLabel progItemsDone    = Ui.label("");
    private final JLabel progDiscovered   = Ui.label("");
    private final JLabel progRequests     = Ui.label("");
    private final JLabel progPerSecond    = Ui.label("");
    private final JTextArea summaryTaskLog = new JTextArea();

    private JEditorPane issueDetail;
    private MessageEditor issueRequest;
    private MessageEditor issueResponse;

    // Every request/response viewer the dashboard builds. Some are created in the
    // constructor, before the context exists, so their right-click menu (send to
    // Repeater, Intruder, ...) would have no sinks; init() hands the context to
    // all of them at once, so every viewer behaves the same wherever it appears.
    private final java.util.List<MessageEditor> editors = new java.util.ArrayList<>();

    /** Build a viewer and register it so init() can give it the context. */
    private MessageEditor newEditor(int kind) {
        MessageEditor m = new MessageEditor(ctx, kind, false);
        editors.add(m);
        return m;
    }

    private final JTextArea eventLog = new JTextArea();

    public DashboardTool() {
        buildUi();
    }

    // ----------------------------------------------------------------- module

    @Override public String name() { return "dashboard"; }

    @Override public boolean alwaysTabbed() { return false; }

    @Override public Tab[] tabs() { return new Tab[]{ new Tab("dashboard", root) }; }

    private ScanTask liveAudit;
    /** The default live passive crawl: adds what the Proxy sees, and the links in it, to the site map. */
    private ScanTask liveCrawl;
    private opensuite.engine.LivePassiveScanner passiveScanner;

    @Override public void init(SuiteContext ctx) {
        this.ctx = ctx;
        // The viewers built in the constructor have no context yet, so their
        // right-click menu (send to Repeater, Intruder, ...) has no sinks and
        // does nothing. Hand the context to every registered viewer now, so an
        // audit-item, scan or logger request reads the same as any other.
        for (MessageEditor m : editors) m.setContext(ctx);
        // Let a right-click in the site map or history start a scan through us.
        ctx.setScanLauncher((url, audit) ->
                startSpiderFor(url, audit, opensuite.engine.ScanConfig.preset("Balanced"), 10));
        ctx.setScanWindow(url -> SwingUtilities.invokeLater(() -> newScan(url)));
        // "Scan" on chosen requests: every item sent in one go becomes one audit task.
        ctx.registerSink("scanner", (svc, req, resp, cap) -> SwingUtilities.invokeLater(() -> {
            if (svc == null || req == null) return;
            boolean active = !"passive".equals(cap);
            (active ? pendingActive : pendingPassive).add(new opensuite.engine.ZapScanner.Item(svc, req));
            pendingItems.restart();
        }));
        ctx.setPauseAll(() -> SwingUtilities.invokeLater(this::pauseAllTasks));
        ctx.setResumeAll(() -> SwingUtilities.invokeLater(this::resumeAllTasks));
        opensuite.core.TaskSchedule.start(ctx);
        ctx.addIssueListener(new SuiteContext.IssueListener() {
            @Override public void issueAdded(Issue i) { issuesRefresh.request(); }
            @Override public void issueUpdated(Issue i) { issuesRefresh.request(); }
            @Override public void issuesReloaded()    { issuesRefresh.request(); }
        });
        ctx.addTaskListener(t -> {
            tasksRefresh.request();
            // A scan that has just finished is worth keeping: write the project
            // now rather than waiting for the next autosave or for exit.
            if (t.type() != ScanTask.Type.LIVE_PASSIVE && t.state() == ScanTask.State.FINISHED
                    && savedOnFinish.add(t)) {
                opensuite.ui.StateIO.autosave(ctx);
            }
        });

        // Feed the crawl window's live Logger from the shared store: every crawl
        // or audit request/response the engine records shows up there as it runs.
        ctx.store().addListener(new MessageStore.Listener() {
            @Override public void entryAdded(LogEntry e) {
                if (isScanEntry(e)) { logAddQueue.add(e); logRefresh.request(); }
                else countLiveRequest(e);
            }
            @Override public void entryUpdated(LogEntry e) {
                if (isScanEntry(e)) { logHasUpdates = true; logRefresh.request(); }
            }
            @Override public void reloaded(List<LogEntry> all) {
                for (LogEntry e : all) if (isScanEntry(e)) logAddQueue.add(e);
                logRefresh.request();
            }
        });

        issueRequest  = newEditor(MessageEditor.REQUEST);
        issueResponse = newEditor(MessageEditor.RESPONSE);
        issueSplit.setTopComponent(issueRequest);
        issueSplit.setBottomComponent(issueResponse);

        // The two default tasks, as the reference starts with: a live passive
        // crawl and a live passive audit, both capturing from the Proxy. Scans
        // the user starts add their own tasks on top of these.
        liveCrawl = new ScanTask(ScanTask.Type.LIVE_PASSIVE,
                "Live passive crawl from Proxy (all traffic)",
                "Add links. Add item itself, same domain and URLs in suite scope.");
        ctx.addTask(liveCrawl);
        opensuite.target.PassiveCrawl.reset();
        opensuite.target.PassiveCrawl.setEnabled(true);
        opensuite.target.PassiveCrawl.listen(line -> liveCrawl.log(line), crawlRefresh::request);

        liveAudit = new ScanTask(ScanTask.Type.LIVE_PASSIVE,
                "Live audit from Proxy (all traffic)", "Audit checks - passive");
        liveAudit.log("Capturing in-scope traffic from the Proxy; the passive checks run on every exchange");
        ctx.addTask(liveAudit);

        // Live passive scanning: route in-scope proxy traffic through the engine
        // and poll its alerts into issues. On by default.
        passiveScanner = new opensuite.engine.LivePassiveScanner(ctx);
        ctx.setLiveScanRouter(passiveScanner::routeFor);
        passiveScanner.setEnabled(true);

        rebuildTasks();
        onIssuesChanged();
    }

    @Override public void shutdown() {
        // The ZAP scan engine is shared and shuts itself down via its own hook.
        ensureCardAnimation(false);
    }

    // ----------------------------------------------------------------- layout

    private JSplitPane issueSplit;

    private void buildUi() {
        JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                buildLeft(), buildRight());
        split.setBorder(null);
        split.setDividerSize(1);
        split.setDividerLocation(400);

        root.add(split, BorderLayout.CENTER);
    }

    private JComponent buildLeft() {
        // A white pane 400 wide: one head row (title, the two buttons, three
        // marks), the filter row, then the task cards.
        JPanel left = new JPanel(new BorderLayout());
        left.setBackground(Theme.CONTENT);

        JButton newScan = Ui.primaryButton("New scan", "Crawl and audit a target");
        JButton newLiveTask = Ui.primaryButton("New live task", "Start a live task");
        accentise(newScan);
        accentise(newLiveTask);
        newScan.setBorder(Ui.pad(0, 0, 0, 0));
        newLiveTask.setBorder(Ui.pad(0, 0, 0, 0));
        newScan.setPreferredSize(new Dimension(Ui.column(85, newScan.getFont(), "New scan"), Ui.tall(26)));
        newLiveTask.setPreferredSize(new Dimension(Ui.column(106, newLiveTask.getFont(), "New live task"), Ui.tall(26)));
        newScan.addActionListener(e -> newScan());
        newLiveTask.addActionListener(e -> newLiveTask());

        JPanel header = new JPanel(new BorderLayout());
        header.setOpaque(false);
        header.setBorder(Ui.pad(15, 15, 0, 15));
        JLabel tasksTitle = Ui.heading("Tasks");
        tasksTitle.setBorder(Ui.pad(0, 0, Ui.fontGrowth(), 0));   // the title keeps its place as the buttons beside it grow
        header.add(tasksTitle, BorderLayout.WEST);
        JPanel btns = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        btns.setOpaque(false);
        btns.add(newScan);
        btns.add(Box.createHorizontalStrut(10));
        btns.add(newLiveTask);
        int mark = 21 + Ui.fontGrowth() / 2;
        JPanel marks = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        marks.setOpaque(false);
        marks.add(new HeaderIconButton("pause", mark, "Pause all tasks", () -> {
            if (ctx == null) return;
            pauseAllTasks();
        }));
        marks.add(Box.createHorizontalStrut(10 + Ui.fontGrowth()));
        marks.add(new HeaderIconButton("gear", mark, "Task settings", () -> {
            if (ctx != null) opensuite.ui.SettingsDialog.open(ownerFrame(), ctx, "Project > Tasks");
        }));
        marks.add(Box.createHorizontalStrut(10 + Ui.fontGrowth()));
        marks.add(new HeaderIconButton("help", mark, "Getting started",
                () -> { if (ctx != null && ctx.frame() instanceof opensuite.ui.SuiteFrame sf) sf.selectTool("discover"); }));
        // The pane is 400 wide. When the title, the two buttons and the three
        // marks do not fit on one line (they do not at the usual desktop font
        // size), the marks drop to a line of their own, as in the reference.
        int oneLine = Ui.heading("Tasks").getPreferredSize().width + 20 + btns.getPreferredSize().width + 20 + marks.getPreferredSize().width;
        if (oneLine <= 400 - 30) {
            btns.add(Box.createHorizontalStrut(20));
            btns.add(marks);
            header.add(btns, BorderLayout.EAST);
        } else {
            header.add(btns, BorderLayout.EAST);
            marks.setBorder(Ui.pad(13, 1, 0, 0));
            header.add(marks, BorderLayout.SOUTH);
        }

        // Filter popup (state and kind chips) and the search box.
        searchField = Ui.searchField(14);
        searchField.setColumns(0);
        searchField.setPreferredSize(new Dimension(133 + 11 * Ui.fontGrowth(), Ui.tall(22)));
        searchField.getDocument().addDocumentListener(new DocumentListener() {
            @Override public void insertUpdate(DocumentEvent e)  { rebuildTasks(); }
            @Override public void removeUpdate(DocumentEvent e)  { rebuildTasks(); }
            @Override public void changedUpdate(DocumentEvent e) { rebuildTasks(); }
        });
        JButton filterBtn = opensuite.ui.Glyphs.button(opensuite.ui.Glyphs.funnel(Ui.em(17), Theme.TEXT), "Filter tasks", null);
        filterBtn.setText("Filter");
        filterBtn.setFont(Ui.PLAIN);
        filterBtn.setBorder(null);
        filterBtn.setHorizontalTextPosition(SwingConstants.RIGHT);
        filterBtn.setIconTextGap(5);
        JLabel chevron = new JLabel(new javax.swing.Icon() {
            @Override public int getIconWidth() { return 11; }
            @Override public int getIconHeight() { return 7; }
            @Override public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
                g2.setColor(Theme.TEXT);
                g2.setStroke(new BasicStroke(1.3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
                java.awt.geom.Path2D p = new java.awt.geom.Path2D.Double();
                p.moveTo(x + 0.9, y + 0.9); p.lineTo(x + 5.5, y + 6.0); p.lineTo(x + 10.1, y + 0.9);
                g2.draw(p);
                g2.dispose();
            }
        });
        filterBtn.addActionListener(e -> {
            JPopupMenu m = new JPopupMenu();
            JPanel body = new JPanel();
            body.setLayout(new BoxLayout(body, BoxLayout.Y_AXIS));
            body.setBorder(Ui.pad(8, 10, 8, 10));
            body.add(chipRow("Running", "Paused", "Finished"));
            body.add(Box.createVerticalStrut(6));
            body.add(chipRow("Live task", "Scan", "Intruder attack"));
            m.add(body);
            m.show(filterBtn, 0, filterBtn.getHeight());
        });
        JPanel filterRow = new JPanel(new BorderLayout());
        filterRow.setOpaque(false);
        filterRow.setBorder(Ui.pad(Ui.roomy(15), 15, 0, 16));
        JPanel fl = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        fl.setOpaque(false);
        fl.add(filterBtn);
        fl.add(Box.createHorizontalStrut(9));
        fl.add(chevron);
        fl.add(Box.createRigidArea(new Dimension(0, Ui.tall(22))));
        filterRow.add(fl, BorderLayout.WEST);
        filterRow.add(searchField, BorderLayout.EAST);

        JPanel top = new JPanel(new BorderLayout());
        top.setOpaque(false);
        top.add(header, BorderLayout.NORTH);
        top.add(filterRow, BorderLayout.SOUTH);

        // Scrollable list of cards; each card brings its own 8px of shadow.
        taskList.setLayout(new BoxLayout(taskList, BoxLayout.Y_AXIS));
        taskList.setOpaque(false);
        JPanel holder = new JPanel(new BorderLayout());
        holder.setBackground(Theme.CONTENT);
        holder.setBorder(Ui.pad(22, 7, 8, 7));
        holder.add(taskList, BorderLayout.NORTH);

        left.add(top, BorderLayout.NORTH);
        JScrollPane listScroll = new JScrollPane(holder);
        listScroll.setBorder(null);
        listScroll.getViewport().setBackground(Theme.CONTENT);
        listScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        listScroll.getVerticalScrollBar().setUnitIncrement(16);
        left.add(listScroll, BorderLayout.CENTER);
        left.setMinimumSize(new Dimension(300, 100));
        return left;
    }

    private JComponent buildRight() {
        JPanel right = new JPanel(new BorderLayout());
        right.setBackground(Theme.BG);

        // Task head: the back mark and the task title on the left, three
        // controls (play or pause, settings, help) on the right; 74px in all.
        rightHeader.setText("Dashboard");
        rightHeader.setIcon(backIcon());
        rightHeader.setIconTextGap(21 + Ui.fontGrowth() / 2);
        rightHeader.setBorder(Ui.pad(2, 0, 0, 0));

        // One row, centred on one line: the box that narrows a scan to one site is taller than the marks beside it.
        JPanel headerControls = new JPanel();
        headerControls.setLayout(new BoxLayout(headerControls, BoxLayout.X_AXIS));
        headerControls.setOpaque(false);
        playPauseBtn = new HeaderIconButton("pause", 17, "Pause or resume the selected task", () -> {
            if (selected != null && selected.state() != ScanTask.State.FINISHED) {
                boolean on = selected.state() != ScanTask.State.RUNNING;
                selected.setState(on ? ScanTask.State.RUNNING : ScanTask.State.PAUSED);
                if (selected == liveAudit && passiveScanner != null) passiveScanner.setEnabled(on);
                if (selected == liveCrawl) opensuite.target.PassiveCrawl.setEnabled(on);
                if (ctx != null) ctx.taskChanged(selected);
            }
        });
        siteBox.setToolTipText(Ui.tip("Show one site of this scan alone in every tab"));
        siteBox.setVisible(false);
        siteBox.setMaximumSize(new Dimension(Ui.em(190), siteBox.getPreferredSize().height));
        siteBox.addActionListener(e -> {
            if (siteBoxFilling) return;
            Object pick = siteBox.getSelectedItem();
            String site = null;
            if (pick != null && !ALL_SITES.equals(pick) && selected != null)
                for (opensuite.core.SiteProgress.Site st : selected.sites().all()) if (st.host().equals(pick)) site = st.site();
            showSite(site);
        });
        headerControls.add(siteBox);
        headerControls.add(Box.createHorizontalStrut(14 + Ui.fontGrowth()));
        headerControls.add(playPauseBtn);
        headerControls.add(Box.createHorizontalStrut(10 + Ui.fontGrowth()));
        headerControls.add(new HeaderIconButton("gear", 17, "View the selected task's configuration",
                () -> openTaskSettings(selected, rightHeader)));
        headerControls.add(Box.createHorizontalStrut(10 + Ui.fontGrowth()));
        headerControls.add(new HeaderIconButton("help", 17, "Getting started",
                () -> { if (ctx != null && ctx.frame() instanceof opensuite.ui.SuiteFrame sf) sf.selectTool("discover"); }));

        JPanel header = new JPanel(new BorderLayout());
        header.setOpaque(false);
        header.setBorder(Ui.pad(18, 21, 29 + Ui.fontGrowth() / 2, 20 + Ui.fontGrowth() / 2));
        header.add(rightHeader, BorderLayout.WEST);
        header.add(headerControls, BorderLayout.EAST);
        header.setPreferredSize(new Dimension(10, Ui.roomy(74)));
        right.add(header, BorderLayout.NORTH);

        taskTabs = new JTabbedPane();
        taskTabs.setBorder(Ui.pad(0, 0, 0, 0));
        taskTabs.putClientProperty(opensuite.ui.theme.FlatTabbedPaneUI.LEFT_INSET, 20);
        allTabs.add(new Object[] { "Summary", buildSummaryTab() });
        allTabs.add(new Object[] { "Audit items", buildAuditItemsTab() });
        allTabs.add(new Object[] { "Issues", buildIssuesTab() });
        allTabs.add(new Object[] { "Event log", buildEventLogTab() });
        allTabs.add(new Object[] { "Logger", buildTaskLoggerTab() });
        allTabs.add(new Object[] { "Audit log", buildAuditLogTab() });
        allTabs.add(new Object[] { "Live crawl view", crawlGraph });
        // The page the scan's own browser has open: shown live while the tab is open on that scan.
        new opensuite.engine.CrawlWatch(this::zapEngine).start(
                () -> watchedScan() != null,
                () -> { ScanTask w = watchedScan(); return w != null && w == selected && crawlGraph.isShowing(); },
                f -> {
                    if (f == null) {
                        SwingUtilities.invokeLater(() -> crawlGraph.notLive(selected));
                        return;
                    }
                    ScanTask w = watchedScan();
                    if (w == null) return;
                    if (w != selected || !crawlGraph.isShowing()) return;
                    // A page the scan refused to request (another site, a page left out by a rule) is the engine's
                    // refusal and no part of the target: it is not shown. The Event log lists what was left out.
                    if (w.refuses(f.url())) { SwingUtilities.invokeLater(() -> crawlGraph.stillLive(w)); return; }
                    java.awt.image.BufferedImage fitted = crawlGraph.prepare(f.image(), f.cssWidth());
                    SwingUtilities.invokeLater(() -> {
                        if (selected == w) crawlGraph.setPage(w, f.image(), fitted, f.cssWidth(), f.url(), f.title(), f.pages());
                    });
                });
        applyTabs(0);
        taskTabsHost.setOpaque(false);
        taskTabsHost.add(taskTabs, BorderLayout.CENTER);

        rightBody.setOpaque(false);
        rightBody.add(taskTabsHost, "scan");
        rightBody.add(buildDetachedCard(), "detached");
        rightBody.add(buildCrawlCard(), "crawl");
        right.add(rightBody, BorderLayout.CENTER);
        return right;
    }

    /** The scans that crawl, whatever they are doing now: a scan keeps its Live crawl view once the crawl is over. */
    private final java.util.Set<ScanTask> crawlScans =
            java.util.Collections.synchronizedSet(java.util.Collections.newSetFromMap(new IdentityHashMap<>()));

    /** The running scan whose browser is to be looked at: the selected one if it is such a scan, else the first that is. */
    private ScanTask watchedScan() {
        ScanTask t = selected;
        if (t != null && t.state() == ScanTask.State.RUNNING && crawlScans.contains(t)) return t;
        if (ctx == null) return null;
        for (ScanTask x : ctx.tasks()) if (x.state() == ScanTask.State.RUNNING && crawlScans.contains(x)) return x;
        return null;
    }

    /** Every tab a task can have, in order: title, component. */
    private final java.util.List<Object[]> allTabs = new java.util.ArrayList<>();
    private int tabsMode = -1;

    /**
     * Show the tabs that suit the task: 0 the passive crawl (its summary is the
     * whole of it), 1 an audit, 2 a task that crawls and so has the live crawl view too.
     */
    private void applyTabs(int mode) {
        if (mode == tabsMode) return;
        tabsMode = mode;
        Component keep = taskTabs.getSelectedComponent();
        taskTabs.removeAll();
        for (Object[] t : allTabs) {
            String title = (String) t[0];
            if (mode == 0 && !"Summary".equals(title)) continue;
            if (mode == 1 && "Live crawl view".equals(title)) continue;
            taskTabs.addTab(title, (Component) t[1]);
        }
        if (keep != null && taskTabs.indexOfComponent(keep) >= 0) taskTabs.setSelectedComponent(keep);
    }

    /** The mark before the task title: the scan mark, the same one the wizard's Scan details step carries. */
    private static javax.swing.Icon backIcon() {
        return new javax.swing.Icon() {
            private final double f = (17 + Ui.fontGrowth() / 2.0) / 17.0;
            @Override public int getIconWidth() { return (int) Math.round(16 * f); }
            @Override public int getIconHeight() { return (int) Math.round(17 * f); }
            @Override public void paintIcon(Component c, Graphics g, int px, int py) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.translate(px, py);
                g2.scale(f, f);
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
                g2.setColor(Theme.TEXT);
                g2.setStroke(new BasicStroke(1.3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
                g2.translate(0, 0.5);
                NewScanWizard.drawScanMark(g2);
                g2.dispose();
            }
        };
    }

    /**
     * Crawl view: a live Logger of the scan's HTTP traffic (table + request and
     * response viewer), plus an Event log tab, like the reference crawl window.
     */
    private JComponent buildCrawlCard() {
        JPanel p = new JPanel(new BorderLayout(0, 6));

        crawlStats = Ui.bold("Crawling");
        crawlStats.setBorder(Ui.pad(2, 2, 4, 2));
        p.add(crawlStats, BorderLayout.NORTH);

        // ---- Logger: live request table over a request/response viewer ----
        scanLogTable = new JTable(scanLogModel);
        Ui.styleTable(scanLogTable);
        Ui.distributeWidths(scanLogTable, 48, 95, 60, 70, 170, 200, 150, 60, 70);
        lightHeader(scanLogTable);
        scanLogTable.setRowSorter(new opensuite.ui.NumberSorter<>(scanLogModel));
        Ui.newestFirst(scanLogTable, 0);
        // The same right-click menu the proxy history has: send to Repeater,
        // Intruder, add to scope, copy URL. No delete: the scan owns this log.
        new opensuite.proxy.HistoryContextMenu(ctx, scanLogTable, scanLogModel::at, null).install();
        scanReq  = newEditor(MessageEditor.REQUEST);
        scanResp = newEditor(MessageEditor.RESPONSE);
        opensuite.ui.RowSelection.watch(scanLogTable, scanLogModel::at, this::showScanSelected);
        JScrollPane logScroll = new JScrollPane(scanLogTable);
        logScroll.setBorder(BorderFactory.createLineBorder(Ui.GRID));
        JSplitPane detail = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scanReq, scanResp);
        detail.setDividerSize(1);
        Ui.balance(detail, 0.5);
        JSplitPane logger = new JSplitPane(JSplitPane.VERTICAL_SPLIT, logScroll, detail);
        logger.setDividerSize(1);
        Ui.balance(logger, 0.5);

        // ---- Event log: the crawl's own progress lines ----
        crawlLog = new JTextArea();
        crawlLog.setEditable(false);
        crawlLog.setFont(Ui.MONO);
        crawlLog.setLineWrap(true);
        crawlLog.setWrapStyleWord(false);

        JTabbedPane tabs = new JTabbedPane();
        tabs.addTab("Logger", logger);
        tabs.addTab("Event log", Ui.scroll(crawlLog));
        p.add(tabs, BorderLayout.CENTER);
        return p;
    }

    private void showScanSelected() {
        int row = scanLogTable.getSelectedRow();
        if (row < 0) return;
        LogEntry e = scanLogModel.at(scanLogTable.convertRowIndexToModel(row));
        if (e == null) return;
        scanReq.setMessage(e.service(), e.request() == null ? new HttpMessage(new byte[0]) : e.request().copy());
        scanResp.setMessage(e.service(), e.response() == null ? new HttpMessage(new byte[0]) : e.response().copy(), e.request());
    }

    /** True for traffic the engine's crawl or audit produced. */
    private static boolean isScanEntry(LogEntry e) {
        String t = e.tool();
        return "crawl".equals(t) || "audit".equals(t);
    }

    /** Coalesces the passive crawl's updates: one task refresh per burst of traffic, on the event thread. */
    private final opensuite.ui.Coalescer crawlRefresh = new opensuite.ui.Coalescer(250, () -> {
        if (liveCrawl == null || ctx == null) return;
        liveCrawl.setDiscoveredLocations(opensuite.target.PassiveCrawl.itemsAdded());
        liveCrawl.setItemsDone(opensuite.target.PassiveCrawl.responsesProcessed());
        ctx.taskChanged(liveCrawl);
    });

    // Distinct method + URL pairs the live passive audit has seen: its "locations".
    private final java.util.Set<String> liveLocations = java.util.concurrent.ConcurrentHashMap.newKeySet();

    /**
     * The live passive audit's figures: every in-scope exchange that reaches the
     * engine while capture is on counts as a request, and each distinct method
     * and URL as a discovered location.
     */
    private void countLiveRequest(LogEntry e) {
        if (liveAudit == null || liveAudit.state() != ScanTask.State.RUNNING) return;
        if (e.service() == null || e.request() == null || !ctx.scope().isInScope(e)) return;
        liveAudit.addRequests(1);
        liveLocations.add(e.request().method() + " " + e.url());
        liveAudit.setDiscoveredLocations(liveLocations.size());
        ctx.taskChanged(liveAudit);
    }

    private JComponent buildSummaryTab() {
        // ---- left card: what a crawl added to the site map, or an audit's worst findings ----
        summaryTable = new JTable(summaryModel);
        Ui.styleTable(summaryTable);
        summaryTable.setRowSorter(new opensuite.ui.NumberSorter<>(summaryTable.getModel()));
        Ui.distributeWidths(summaryTable, 260, 230, 170);
        summaryIssueIconColumn(summaryTable, 0);   // glyph icon before the issue type

        JTable added = new JTable(addedModel);
        Ui.styleTable(added);
        Ui.proportionalWidths(added, 129, 57, 189, 70, 82);

        leftCards.setOpaque(false);
        leftCards.add(framed(added, "No items to show", "Items found in the crawl will display here."), "added");
        leftCards.add(framed(summaryTable), "issues");

        leftHead = sectionHeader("Items added to site map", sectionIcon("folder"), "View site map", () -> {
            if (selected == liveCrawl || selected == null) {
                if (ctx != null && ctx.frame() instanceof opensuite.ui.SuiteFrame sf) sf.selectTool("target");
            } else selectIssuesTab();
        });
        JPanel vulnsCard = card();
        vulnsCard.setLayout(new BorderLayout());
        vulnsCard.setBorder(Ui.pad(20, 20, 30, 20));
        vulnsCard.add(leftHead, BorderLayout.NORTH);
        vulnsCard.add(leftCards, BorderLayout.CENTER);

        // ---- right column: configuration and progress in one card, the log in another ----
        summaryTaskLog.setEditable(false);
        summaryTaskLog.setFont(Ui.PLAIN);
        summaryTaskLog.setForeground(Theme.TEXT);
        summaryTaskLog.setLineWrap(false);
        summaryTaskLog.setOpaque(false);
        summaryTaskLog.setBorder(null);
        JScrollPane logScroll = new JScrollPane(summaryTaskLog);
        logScroll.setBorder(Ui.pad(2, 0, 0, 0));
        logScroll.setOpaque(false);
        logScroll.getViewport().setOpaque(false);

        JPanel cfgHead = sectionHeader("Task configuration", NewScanWizard.scanMarkIcon(Theme.TEXT, 1.2f),
                "View configuration", () -> openTaskSettings(selected, cfgType));
        cfgLink = (JComponent) ((BorderLayout) ((JPanel) cfgHead.getComponent(0)).getLayout()).getLayoutComponent(BorderLayout.EAST);
        JPanel stateCard = card();
        stateCard.setLayout(new BorderLayout());
        stateCard.add(opensuite.ui.Sections.column(0,
                opensuite.ui.Sections.fill(cfgHead), opensuite.ui.Sections.fill(configGrid()),
                opensuite.ui.Sections.gap(35),
                opensuite.ui.Sections.fill(sectionHeader("Task progress", sectionIcon("pie"), null, null)),
                opensuite.ui.Sections.fill(progressGrid()),
                opensuite.ui.Sections.gap(10)), BorderLayout.CENTER);

        JPanel logCard = card();
        logCard.setLayout(new BorderLayout());
        logCard.add(sectionHeader("Task log", sectionIcon("clock"), null, null), BorderLayout.NORTH);
        logCard.add(logScroll, BorderLayout.CENTER);

        JPanel rightCol = new JPanel(new BorderLayout(0, 20));
        rightCol.setOpaque(false);
        rightCol.add(stateCard, BorderLayout.NORTH);
        rightCol.add(logCard, BorderLayout.CENTER);

        // Two equal columns on white, 20px apart and 20px in from every side.
        // A scan of several sites lists them above its findings, each with its own progress.
        sitesTable = new JTable(sitesModel) {
            // What a site is waiting for, or why it failed, on hover; and what a right-click offers.
            @Override public String getToolTipText(java.awt.event.MouseEvent e) {
                opensuite.core.SiteProgress.Site st = sitesModel.at(rowAtPoint(e.getPoint()));
                if (st == null) return null;
                String more = st.note().isEmpty() ? "" : st.note() + ". ";
                return Ui.tip(st.host() + ": " + st.status().label() + ". " + more + "Right-click to show this site alone or to skip it");
            }
        };
        Ui.styleTable(sitesTable);
        Ui.proportionalWidths(sitesTable, 170, 90, 85, 85, 60);
        sitesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        ToolTipManager.sharedInstance().registerComponent(sitesTable);
        sitesTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mousePressed(java.awt.event.MouseEvent e) { menu(e); }
            @Override public void mouseReleased(java.awt.event.MouseEvent e) { menu(e); }
            private void menu(java.awt.event.MouseEvent e) {
                if (!e.isPopupTrigger()) return;
                int row = sitesTable.rowAtPoint(e.getPoint());
                opensuite.core.SiteProgress.Site st = sitesModel.at(row);
                ScanTask t = selected;
                if (st == null || t == null) return;
                sitesTable.setRowSelectionInterval(row, row);
                JPopupMenu m = new JPopupMenu();
                JMenuItem only = new JMenuItem("Show only " + st.host());
                only.addActionListener(a -> showSite(st.site()));
                JMenuItem every = new JMenuItem("Show all sites");
                every.setEnabled(siteFilter != null);
                every.addActionListener(a -> showSite(null));
                JMenuItem skip = new JMenuItem("Skip " + st.host());
                skip.setEnabled(t.state() != ScanTask.State.FINISHED && !st.status().over() && !st.skipAsked());
                skip.addActionListener(a -> {
                    if (t.sites().skip(st.site())) {
                        t.log("Skipping " + st.host() + ": asked for by the user");
                        if (ctx != null) ctx.taskChanged(t);
                    }
                });
                m.add(only); m.add(every); m.addSeparator(); m.add(skip);
                m.show(sitesTable, e.getX(), e.getY());
            }
        });
        sitesScroll = framed(sitesTable);
        sitesCard = card();
        sitesCard.setLayout(new BorderLayout());
        sitesCard.setBorder(Ui.pad(20, 20, 20, 20));
        sitesCard.add(sectionHeader("Sites in this scan", sectionIcon("folder"), null, null), BorderLayout.NORTH);
        sitesCard.add(sitesScroll, BorderLayout.CENTER);
        sitesCard.setVisible(false);
        JPanel leftCol = new JPanel(new BorderLayout(0, 20));
        leftCol.setOpaque(false);
        leftCol.add(sitesCard, BorderLayout.NORTH);
        leftCol.add(vulnsCard, BorderLayout.CENTER);

        JPanel holder = new JPanel(new GridLayout(1, 2, 20, 0));
        holder.setBackground(Theme.CONTENT);
        holder.setBorder(Ui.pad(20, 20, 20, 20));
        holder.add(leftCol);
        holder.add(rightCol);
        return holder;
    }

    /** The left summary card's two faces and its heading, which changes with the task. */
    private final CardLayout leftCardsLayout = new CardLayout();
    private final JPanel leftCards = new JPanel(leftCardsLayout);
    private JPanel leftHead;
    private final AddedModel addedModel = new AddedModel();

    /** A table in a hairline frame, filling its card. */
    private static JScrollPane framed(JTable t) { return framed(t, null, null); }

    /**
     * The same, with a message in the middle of the table while it is empty:
     * a small drawing of our own (three linked tiles), a heading and a line of text.
     */
    private static JScrollPane framed(JTable t, String emptyTitle, String emptyText) {
        JScrollPane sp = new JScrollPane(t) {
            @Override public void paint(Graphics g) {
                super.paint(g);
                if (emptyTitle == null || t.getRowCount() > 0) return;
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                Theme.textSmoothing(g2);
                Rectangle v = getViewport().getBounds();
                float k = Theme.FONT_SIZE / 13f;
                int art = Math.round(69 * k), gap1 = Math.round(49 * k), gap2 = Math.round(41 * k);
                Font big = Ui.BOLD.deriveFont((float) Math.round(19 * k));
                FontMetrics fb = g2.getFontMetrics(big), fp = g2.getFontMetrics(Ui.PLAIN);
                int capBig = Math.round(15 * k), capSmall = Theme.FONT_SIZE;
                int block = art + gap1 + capBig + gap2 + capSmall;
                int cx = v.x + v.width / 2, top = v.y + Math.max(8, (v.height - block) / 2 + Math.round(7 * k));
                if (v.height < block + 16) { g2.dispose(); return; }

                // Three tiles joined by two lines: a little site map.
                g2.translate(cx - Math.round(61 * k), top);
                g2.scale(k, k);
                g2.setColor(Theme.dark ? Theme.BORDER : new Color(0x93, 0xB2, 0xCF));
                g2.setStroke(new BasicStroke(3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
                g2.drawLine(22, 16, 61, 16); g2.drawLine(61, 16, 61, 52); g2.drawLine(61, 34, 100, 34); g2.drawLine(61, 52, 78, 52);
                g2.setColor(Theme.CONTROL);
                int[][] tiles = { { 0, 0 }, { 78, 18 }, { 56, 37 } };
                for (int[] at : tiles) {
                    g2.setColor(Theme.CONTROL);
                    g2.fillRoundRect(at[0], at[1], 44, 32, 10, 10);
                    g2.setColor(Theme.dark ? Theme.BG : Color.WHITE);
                    g2.setStroke(new BasicStroke(2.4f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
                    g2.drawLine(at[0] + 12, at[1] + 12, at[0] + 32, at[1] + 12);
                    g2.drawLine(at[0] + 12, at[1] + 20, at[0] + 26, at[1] + 20);
                }
                g2.dispose();

                g2 = (Graphics2D) g.create();
                Theme.textSmoothing(g2);
                g2.setColor(Theme.dark ? Theme.TEXT : Color.BLACK);
                g2.setFont(big);
                int y = top + art + gap1 + capBig;
                g2.drawString(emptyTitle, cx - fb.stringWidth(emptyTitle) / 2, y);
                g2.setColor(Theme.TEXT);
                g2.setFont(Ui.PLAIN);
                g2.drawString(emptyText, cx - fp.stringWidth(emptyText) / 2, y + gap2 + capSmall - 5);
                g2.dispose();
            }
        };
        t.getModel().addTableModelListener(e -> sp.repaint());
        sp.setBorder(BorderFactory.createLineBorder(Ui.GRID));
        sp.getVerticalScrollBar().setUnitIncrement(16);
        t.setFillsViewportHeight(true);
        // On the dark theme the page's own grey is the stripe colour, so the table stands on the darker ground and its rows alternate.
        Color ground = Theme.dark ? Theme.CONTENT : Theme.BG;
        t.setBackground(ground);
        sp.getViewport().setBackground(ground);
        return sp;
    }

    /** What the passive crawl has added to the site map. */
    private static final class AddedModel extends AbstractTableModel {
        private final String[] cols = { "Host", "Method", "URL", "Status code", "MIME type" };
        private java.util.List<String[]> rows = java.util.List.of();
        void refresh() {
            java.util.List<String[]> now = new ArrayList<>(opensuite.target.PassiveCrawl.items());
            if (now.size() != rows.size()) { rows = now; fireTableDataChanged(); }
        }
        @Override public int getRowCount() { return rows.size(); }
        @Override public int getColumnCount() { return cols.length; }
        @Override public String getColumnName(int c) { return cols[c]; }
        @Override public Object getValueAt(int r, int c) { return rows.get(r)[c]; }
    }

    /** A human-readable label for a scan task type, as the reference shows. */
    private static String typeLabel(ScanTask.Type type) {
        return switch (type) {
            case LIVE_PASSIVE -> "Live audit";
            case LIVE_ACTIVE  -> "Crawl";
            case AUDIT        -> "Audit";
        };
    }

    private void selectIssuesTab() {
        // "View all" jumps to the full Issues tab.
        if (summaryTable == null) return;
        java.awt.Container c = summaryTable;
        while (c != null && !(c instanceof JTabbedPane)) c = c.getParent();
        if (c instanceof JTabbedPane tp) {
            int idx = tp.indexOfTab("Issues");
            if (idx >= 0) tp.setSelectedIndex(idx);
        }
    }

    /** Add a component to a vertical box, left-aligned and capped to its height. */
    private static void addLeft(JPanel box, JComponent c) {
        c.setAlignmentX(Component.LEFT_ALIGNMENT);
        c.setMaximumSize(new Dimension(Integer.MAX_VALUE, c.getPreferredSize().height));
        box.add(c);
    }

    /** A thin horizontal rule between card sections. */
    private static JComponent divider() {
        JSeparator s = new JSeparator(SwingConstants.HORIZONTAL);
        s.setForeground(Ui.GRID);
        s.setMaximumSize(new Dimension(Integer.MAX_VALUE, 1));
        return s;
    }

    /** A flat, softly rounded card in the page colour, set on the white of the summary. */
    private static JPanel card() {
        JPanel p = new JPanel() {
            @Override protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(getBackground());
                g2.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8);
                g2.dispose();
            }
        };
        p.setBackground(Theme.BG);
        p.setOpaque(false);
        p.setBorder(Ui.pad(20, 20, 20, 20));
        return p;
    }

    /**
     * A card heading: a mark and a bold title, an optional link at the right,
     * then a hairline 10px under the row and 10px of air beneath that.
     */
    private JPanel sectionHeader(String title, javax.swing.Icon icon, String linkText, Runnable onLink) {
        JPanel row = new JPanel(new BorderLayout());
        row.setOpaque(false);
        JLabel h = Ui.bold(title);
        h.setForeground(Theme.TEXT);
        if (icon != null) { h.setIcon(boxed14(icon)); h.setIconTextGap(10); }
        row.add(h, BorderLayout.WEST);
        if (linkText != null) row.add(accentLink(linkText, onLink), BorderLayout.EAST);
        row.setPreferredSize(new Dimension(10, Ui.tall(17)));
        JPanel p = new JPanel(new BorderLayout());
        p.setOpaque(false);
        p.add(row, BorderLayout.NORTH);
        JComponent rule = new JComponent() {
            @Override public Dimension getPreferredSize() { return new Dimension(10, 20); }
            @Override protected void paintComponent(Graphics g) { g.setColor(Theme.BORDER); g.fillRect(0, 9, getWidth(), 1); }
        };
        p.add(rule, BorderLayout.CENTER);
        p.putClientProperty("heading", h);
        return p;
    }

    /** A heading mark cut to its ink and centred in a 14px box, so every title starts at the same place. */
    private static javax.swing.Icon boxed14(javax.swing.Icon icon) {
        javax.swing.Icon t = opensuite.ui.Glyphs.trimmed(icon);
        return new javax.swing.Icon() {
            private final int box = 14 + Ui.fontGrowth();
            @Override public int getIconWidth() { return box; }
            @Override public int getIconHeight() { return box; }
            @Override public void paintIcon(Component c, Graphics g, int x, int y) {
                t.paintIcon(c, g, x + (box - t.getIconWidth()) / 2, y + (box - t.getIconHeight()) / 2);
            }
        };
    }

    /** The colour of a link in a card heading: a deep orange, underlined. */
    private static Color linkColour() { return Theme.dark ? new Color(0xFF, 0x9E, 0x7A) : new Color(0xAD, 0x5B, 0x28); }

    /** An underlined link, as the reference uses for a card's action. */
    private static JLabel accentLink(String text, Runnable onClick) {
        JLabel l = new JLabel(text) {
            @Override protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                FontMetrics fm = g.getFontMetrics(getFont());
                Insets in = getInsets();
                int y = in.top + (getHeight() - in.top - in.bottom - fm.getHeight()) / 2 + fm.getAscent() + 2;
                g.setColor(getForeground());
                g.fillRect(in.left, y, fm.stringWidth(getText()), 1);
            }
        };
        l.setFont(Ui.PLAIN);
        l.setForeground(linkColour());
        l.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        l.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mousePressed(java.awt.event.MouseEvent e) {
                if (onClick != null) onClick.run();
            }
        });
        return l;
    }

    private void showTaskConfig(ScanTask task, Component near) {
        if (task == null) {
            JOptionPane.showMessageDialog(near, "Select a task first.", "Task configuration",
                    JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        opensuite.engine.ScanConfig c = taskConfigs.get(task);
        JPanel g = new JPanel(new GridBagLayout());
        g.setOpaque(false);
        int row = 0;
        addKv(g, row++, "Task:", Ui.label(task.title()));
        addKv(g, row++, "Type:", Ui.label(task.configuration()));
        addKv(g, row++, "Scope:", Ui.label(task.scope()));
        if (c == null) {
            addKv(g, row, "Configuration:", Ui.label("not recorded for this task"));
        } else {
            addKv(g, row++, "Configuration:", Ui.label(c.name()));
            addKv(g, row++, "Crawl depth:", Ui.label(c.crawlDepth() == 0 ? "unlimited" : String.valueOf(c.crawlDepth())));
            addKv(g, row++, "Crawl time limit:", Ui.label(minutes(c.crawlDurationMin())));
            addKv(g, row++, "Submit forms:", Ui.label(c.submitForms() ? "yes" : "no"));
            addKv(g, row++, "AJAX crawl:", Ui.label(c.ajaxSpider() ? "on" : "off"));
            if (c.ajaxSpider()) {
                addKv(g, row++, "AJAX time limit:", Ui.label(minutes(c.ajaxMaxDurationMin())));
                addKv(g, row++, "AJAX depth:", Ui.label(c.ajaxMaxDepth() == 0 ? "unlimited" : String.valueOf(c.ajaxMaxDepth())));
                addKv(g, row++, "AJAX states:", Ui.label(c.ajaxMaxStates() == 0 ? "unlimited" : String.valueOf(c.ajaxMaxStates())));
            }
            addKv(g, row++, "Attack strength:", Ui.label(c.attackStrength()));
            addKv(g, row++, "Alert threshold:", Ui.label(c.alertThreshold()));
            addKv(g, row++, "Injection points:", Ui.label(mask(c.injectableMask(),
                    new int[]{opensuite.engine.ScanConfig.INJECT_QUERY, opensuite.engine.ScanConfig.INJECT_BODY,
                            opensuite.engine.ScanConfig.INJECT_PATH, opensuite.engine.ScanConfig.INJECT_HEADERS,
                            opensuite.engine.ScanConfig.INJECT_COOKIE},
                    new String[]{"query string", "body", "path", "headers", "cookies"})));
            addKv(g, row++, "Body types:", Ui.label(mask(c.rpcMask(),
                    new int[]{opensuite.engine.ScanConfig.RPC_MULTIPART, opensuite.engine.ScanConfig.RPC_XML,
                            opensuite.engine.ScanConfig.RPC_JSON, opensuite.engine.ScanConfig.RPC_GWT,
                            opensuite.engine.ScanConfig.RPC_ODATA},
                    new String[]{"multipart", "XML", "JSON", "GWT", "OData"})));
            addKv(g, row++, "Request delay:", Ui.label(c.delayMs() == 0 ? "none" : c.delayMs() + " ms"));
            addKv(g, row, "Audit time limit:", Ui.label(minutes(c.scanDurationMin())));
        }
        JPanel body = new JPanel(new BorderLayout());
        body.setBorder(Ui.pad(16, 20, 12, 20));
        body.add(g, BorderLayout.NORTH);
        Window owner = near == null ? null : SwingUtilities.getWindowAncestor(near);
        JDialog d = new JDialog(owner, "Task configuration", Dialog.ModalityType.APPLICATION_MODAL);
        JButton close = Ui.button("Close");
        close.addActionListener(e -> d.dispose());
        JPanel bar = new JPanel(new FlowLayout(FlowLayout.RIGHT, 8, 6));
        bar.add(close);
        body.add(bar, BorderLayout.SOUTH);
        d.setContentPane(body);
        d.pack();
        d.setSize(Math.max(460, d.getWidth()), d.getHeight());
        d.setLocationRelativeTo(near);
        d.setVisible(true);
    }

    private static String minutes(int m) { return m == 0 ? "none" : m + " min"; }

    private static String mask(int value, int[] bits, String[] names) {
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < bits.length; i++) {
            if ((value & bits[i]) == 0) continue;
            if (b.length() > 0) b.append(", ");
            b.append(names[i]);
        }
        return b.length() == 0 ? "none" : b.toString();
    }

    private static final int CONFIG_COLUMN = Ui.column(99, Ui.BOLD, "Configuration:");
    private static final int PROGRESS_COLUMN = Ui.column(144, Ui.BOLD, "Site map items added:");

    /** One caption and value: an 18px row with the value {@code column} px in, rows 26px apart. */
    private static JPanel kv(JLabel caption, int column, JComponent value) {
        JPanel p = new JPanel(null) {
            @Override public Dimension getPreferredSize() {
                return new Dimension(column + value.getPreferredSize().width, Ui.tall(26));
            }
            @Override public void doLayout() {
                // Text sits a pixel high in its row; a switch, being taller, 2px down.
                int vh = value.getPreferredSize().height;
                caption.setBounds(0, -1, column, Ui.tall(18));
                if (value instanceof JLabel) value.setBounds(column, -1, Math.max(0, getWidth() - column), Ui.tall(18));
                else value.setBounds(column + 2, 2, Math.max(0, getWidth() - column - 2), vh);
            }
        };
        p.setOpaque(false);
        caption.setForeground(Theme.TEXT);
        value.setForeground(Theme.TEXT);
        p.add(caption);
        p.add(value);
        return p;
    }

    private JPanel configGrid() {
        cfgCapturing = new ToggleSwitch(true);
        cfgCapturing.setOnToggle(() -> {
            if (selected == null) return;
            boolean on = cfgCapturing.isOn();
            selected.setState(on ? ScanTask.State.RUNNING : ScanTask.State.PAUSED);
            if (selected == liveAudit && passiveScanner != null) passiveScanner.setEnabled(on);
            if (selected == liveCrawl) opensuite.target.PassiveCrawl.setEnabled(on);
            if (ctx != null) ctx.taskChanged(selected);
        });
        JPanel sw = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        sw.setOpaque(false);
        sw.add(cfgCapturing);
        cfgCapturingRow = kv(Ui.bold("Capturing"), CONFIG_COLUMN, sw);
        return opensuite.ui.Sections.column(0,
                opensuite.ui.Sections.fill(kv(Ui.bold("Task type:"), CONFIG_COLUMN, cfgType)),
                opensuite.ui.Sections.fill(kv(Ui.bold("Scope:"), CONFIG_COLUMN, cfgScope)),
                opensuite.ui.Sections.fill(kv(Ui.bold("Configuration:"), CONFIG_COLUMN, cfgConfig)),
                opensuite.ui.Sections.fill(cfgCapturingRow));
    }

    /** Task progress: the figures in one aligned column, 144px in. */
    private JPanel progressGrid() {
        requestsRow = kv(capRequests, PROGRESS_COLUMN, progRequests);
        return opensuite.ui.Sections.column(0,
                opensuite.ui.Sections.fill(kv(capTotalItems, PROGRESS_COLUMN, progTotalItems)),
                opensuite.ui.Sections.fill(kv(capItemsActive, PROGRESS_COLUMN, progItemsActive)),
                opensuite.ui.Sections.fill(kv(capItemsDone, PROGRESS_COLUMN, progItemsDone)),
                opensuite.ui.Sections.fill(requestsRow));
    }

    private JPanel requestsRow;

    private static void addKv(JPanel g, int row, String caption, JLabel value) {
        GridBagConstraints c = new GridBagConstraints();
        c.gridy = row; c.anchor = GridBagConstraints.WEST; c.insets = new Insets(2, 0, 2, 0);
        c.gridx = 0; c.insets = new Insets(2, 0, 2, 14); g.add(Ui.bold(caption), c);
        c.gridx = 1; c.insets = new Insets(2, 0, 2, 0); c.weightx = 1; g.add(value, c);
    }

    // The progress captions are fields because a passive crawl counts different things from an audit.
    private final JLabel capTotalItems  = Ui.bold("Total audit items:");
    private final JLabel capItemsActive = Ui.bold("Audit items in progress:");
    private final JLabel capItemsDone   = Ui.bold("Audit items completed:");
    private final JLabel capRequests    = Ui.bold("Requests:");

    /** Give the summary table a light header with a bottom rule, like the reference. */
    private static void lightHeader(JTable t) {
        javax.swing.table.JTableHeader h = t.getTableHeader();
        h.setBackground(Theme.HEADER);
        h.setForeground(Theme.TEXT);
        h.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Ui.GRID));
        h.setReorderingAllowed(false);
    }

    /**
     * Put a severity glyph (a coloured disc with "!" for serious
     * findings, "i" for informational ones) in front of the issue-type text.
     */
    private void summaryIssueIconColumn(JTable table, int textCol) {
        table.getColumnModel().getColumn(textCol).setCellRenderer(
            new javax.swing.table.DefaultTableCellRenderer() {
                @Override public Component getTableCellRendererComponent(JTable t, Object v,
                        boolean sel, boolean focus, int row, int column) {
                    super.getTableCellRendererComponent(t, v, sel, focus, row, column);
                    int mr = t.convertRowIndexToModel(row);
                    setIcon(issueGlyphIcon(summaryModel.severityAt(mr), summaryModel.confidenceAt(mr)));
                    setIconTextGap(7);
                    return this;
                }
            });
    }

    /** The shared issue badge; every issue list in the suite uses the same mark. */
    private static javax.swing.Icon issueGlyphIcon(Issue.Severity sev, Issue.Confidence conf) {
        return Ui.issueBadge(sev, conf);
    }

    /** A small pennant/flag glyph shown to the left of the task title. */
    private static javax.swing.Icon pennantIcon() {
        int s = 18;
        java.awt.image.BufferedImage img =
                new java.awt.image.BufferedImage(s, s, java.awt.image.BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(Theme.MUTED);
        g.setStroke(new BasicStroke(1.4f));
        g.drawLine(5, 2, 5, 16);
        g.drawPolygon(new int[]{5, 15, 5}, new int[]{3, 7, 11}, 3);
        g.dispose();
        return new javax.swing.ImageIcon(img);
    }

    /** A round header control button (play/pause, settings or help glyph). */
    private HeaderIconButton playPauseBtn;

    private static final class HeaderIconButton extends JComponent {
        private String kind;
        private final int size;
        void setKind(String k) { if (!k.equals(kind)) { kind = k; repaint(); } }
        HeaderIconButton(String kind, int size, String tip, Runnable onClick) {
            this.kind = kind;
            this.size = size;
            Dimension d = new Dimension(size, size);
            setPreferredSize(d); setMinimumSize(d); setMaximumSize(d);
            setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            setToolTipText(tip);
            addMouseListener(new java.awt.event.MouseAdapter() {
                @Override public void mousePressed(java.awt.event.MouseEvent e) {
                    if (onClick != null) onClick.run();
                }
            });
        }
        @Override protected void paintComponent(Graphics g) {
            paintMark((Graphics2D) g, kind, size, 0, 0);
        }
    }

    /** A thin-lined mark in a ring (pause, play) or the suite's gear and help marks, {@code s} px across. */
    private static void paintMark(Graphics2D g, String kind, int s, int x, int y) {
        if ("gear".equals(kind)) { opensuite.ui.Glyphs.gear(s, Theme.TEXT).paintIcon(null, g, x, y); return; }
        if ("help".equals(kind)) { opensuite.ui.Glyphs.help(s, Theme.TEXT).paintIcon(null, g, x, y); return; }
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g2.setColor(Theme.TEXT);
        g2.setStroke(new BasicStroke(Math.max(1.2f, s / 15f)));
        g2.draw(new java.awt.geom.Ellipse2D.Double(x + 0.9, y + 0.9, s - 1.8, s - 1.8));
        double cx = x + s / 2.0, cy = y + s / 2.0, u = s / 21.0;
        if ("play".equals(kind)) {
            java.awt.geom.Path2D p = new java.awt.geom.Path2D.Double();
            p.moveTo(cx - 2.6 * u, cy - 4.4 * u); p.lineTo(cx + 4.4 * u, cy); p.lineTo(cx - 2.6 * u, cy + 4.4 * u); p.closePath();
            g2.fill(p);
        } else {
            g2.fill(new java.awt.geom.Rectangle2D.Double(cx - 3.6 * u, cy - 4 * u, 2 * u, 8 * u));
            g2.fill(new java.awt.geom.Rectangle2D.Double(cx + 1.6 * u, cy - 4 * u, 2 * u, 8 * u));
        }
        g2.dispose();
    }

    private JComponent buildIssuesTab() {
        issuesTable = new JTable(issuesModel);
        Ui.styleTable(issuesTable);
        Ui.distributeWidths(issuesTable, 95, 70, 190, 140, 130, 110, 80, 80, 110);
        Ui.severityColumn(issuesTable, 6);           // Severity column
        Ui.severityIconColumn(issuesTable, 2, 6, 7);  // the issue badge before the issue type
        issuesTable.getSelectionModel().addListSelectionListener(this::onIssueRowSelected);
        opensuite.ui.IssueMenu.install(issuesTable, ctx, r -> issuesModel.issueAt(r));

        issueDetail = new JEditorPane();
        issueDetail.setEditorKit(Theme.htmlKit());
        opensuite.ui.Advisory.clickable(issueDetail);
        issueDetail.setEditable(false);
        issueDetail.setFont(Ui.PLAIN);

        // Request/response editors are created in init() once ctx exists.
        issueSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        issueSplit.setBorder(null);
        Ui.balance(issueSplit, 0.5);

        JTabbedPane detailTabs = new JTabbedPane();
        detailTabs.addTab("Advisory", Ui.scroll(issueDetail));
        detailTabs.addTab("Request / response", issueSplit);

        JButton exportReport = Ui.button("export report", "Save all findings as an HTML or XML report");
        exportReport.addActionListener(e -> exportIssuesReport());
        JPanel issuesBar = new JPanel(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 6, 3));
        issuesBar.add(exportReport);
        JPanel issuesPanel = new JPanel(new BorderLayout());
        issuesPanel.add(issuesBar, BorderLayout.NORTH);
        issuesPanel.add(Ui.scroll(issuesTable), BorderLayout.CENTER);

        JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, issuesPanel, detailTabs);
        split.setBorder(null);
        Ui.balance(split, 0.4);
        return split;
    }

    private void exportIssuesReport() {
        // The report is of what the tab lists: this task's findings, at the one site shown if it is narrowed to one.
        List<Issue> listed = new ArrayList<>();
        for (int i = 0; i < issuesModel.getRowCount(); i++) { Issue is = issuesModel.issueAt(i); if (is != null) listed.add(is); }
        String name = "opensuite-report";
        if (siteFilter != null && selected != null) {
            opensuite.core.SiteProgress.Site st = selected.sites().get(siteFilter);
            if (st != null) name += "-" + st.host().replaceAll("[^A-Za-z0-9.-]", "_");
        }
        opensuite.report.Export.reportDialog(ctx == null ? null : ctx.frame(), listed, name);
    }

    private final javax.swing.table.DefaultTableModel eventModel = new javax.swing.table.DefaultTableModel(
            new Object[]{"Time", "Type", "Source", "Message"}, 0) {
        @Override public boolean isCellEditable(int r, int c) { return false; }
    };
    private JTable eventTable;
    private final CardLayout eventCards = new CardLayout();
    private final JPanel eventArea = new JPanel(eventCards);

    private JComponent buildEventLogTab() {
        eventLog.setEditable(false);   // kept as the text source the detached window and tests read
        JPanel chips = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 0));
        chips.setOpaque(false);
        chips.add(new JLabel(opensuite.ui.Glyphs.funnel(16, Theme.ICON)));
        chips.add(Ui.label("Filter"));
        java.util.Map<String, JToggleButton> kinds = new java.util.LinkedHashMap<>();
        for (String t : new String[]{"Critical", "Error", "Info", "Debug"}) {
            JToggleButton b = new JToggleButton(t, !t.equals("Debug"));
            b.setFont(Ui.BOLD);
            b.setFocusable(false);
            b.setMargin(new Insets(2, 10, 2, 10));
            chips.add(b);
            kinds.put(t, b);
        }
        JTextField search = Ui.searchField(14);
        eventTable = new JTable(eventModel);
        Ui.styleTable(eventTable);
        Ui.distributeWidths(eventTable, 150, 70, 90, 600);
        lightHeader(eventTable);
        javax.swing.table.TableRowSorter<javax.swing.table.DefaultTableModel> sorter = new opensuite.ui.NumberSorter<>(eventModel);
        eventTable.setRowSorter(sorter);
        // A row shows when its type's button is pressed in and it holds the searched text.
        Runnable go = () -> {
            String q = search.getText().strip().toLowerCase(java.util.Locale.ROOT);
            sorter.setRowFilter(new RowFilter<javax.swing.table.DefaultTableModel, Integer>() {
                @Override public boolean include(Entry<? extends javax.swing.table.DefaultTableModel, ? extends Integer> row) {
                    JToggleButton kind = kinds.get(String.valueOf(row.getValue(1)));
                    if (kind != null && !kind.isSelected()) return false;
                    if (q.isEmpty()) return true;
                    for (int c = 0; c < row.getValueCount(); c++)
                        if (String.valueOf(row.getValue(c)).toLowerCase(java.util.Locale.ROOT).contains(q)) return true;
                    return false;
                }
            });
        };
        for (JToggleButton kind : kinds.values()) kind.addActionListener(e -> go.run());
        search.getDocument().addDocumentListener(new DocumentListener() {
            @Override public void insertUpdate(DocumentEvent e) { go.run(); }
            @Override public void removeUpdate(DocumentEvent e) { go.run(); }
            @Override public void changedUpdate(DocumentEvent e) { go.run(); }
        });
        JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT, 4, 0));
        right.setOpaque(false);
        right.add(search);
        right.add(opensuite.ui.Glyphs.menuButton("Table layout", () -> opensuite.ui.TableLayoutMenu.build(eventTable)));
        JPanel bar = new JPanel(new BorderLayout());
        bar.setOpaque(false);
        bar.setBorder(Ui.pad(6, 4, 6, 4));
        bar.add(chips, BorderLayout.WEST);
        bar.add(right, BorderLayout.EAST);

        JPanel empty = opensuite.ui.EmptyState.of("No event log items to show",
                "The event log shows key task events, such as start times, alerts, and progress updates.", null);
        eventArea.setOpaque(false);
        eventArea.add(empty, "empty");
        JScrollPane sp = new JScrollPane(eventTable);
        sp.setBorder(BorderFactory.createLineBorder(Ui.GRID));
        eventArea.add(sp, "table");
        eventCards.show(eventArea, "empty");
        JPanel p = new JPanel(new BorderLayout());
        p.setOpaque(false);
        p.add(bar, BorderLayout.NORTH);
        p.add(eventArea, BorderLayout.CENTER);
        return p;
    }

    /** Refill the event table from the task's log lines. */
    private void refreshEventTable(ScanTask t) {
        if (eventTable == null) return;
        java.util.List<ScanTask.Event> lines = t == null ? java.util.List.of() : t.events();
        // The same task with the same last line has nothing new to show.
        // Narrowed to one site, the lines are those that name it.
        String named = null;
        if (siteFilter != null && t != null) {
            opensuite.core.SiteProgress.Site st = t.sites().get(siteFilter);
            if (st != null) named = st.host();
        }
        if (named != null) {
            java.util.List<ScanTask.Event> own = new ArrayList<>();
            for (ScanTask.Event e : lines) if (e.line().contains(named)) own.add(e);
            lines = own;
        }
        String shown = (t == null ? 0 : t.number) + "/" + named + "/" + lines.size() + "/" + (lines.isEmpty() ? 0 : lines.get(lines.size() - 1).at());
        if (shown.equals(eventsShown)) return;
        eventsShown = shown;
        eventModel.setRowCount(0);
        java.text.SimpleDateFormat when = new java.text.SimpleDateFormat("HH:mm:ss d MMM yyyy");
        // Newest first, as the reference lists its events.
        for (int i = lines.size() - 1; i >= 0; i--) {
            ScanTask.Event e = lines.get(i);
            eventModel.addRow(new Object[]{when.format(new java.util.Date(e.at())), eventType(e.line()), "Task " + t.number, e.line()});
        }
        eventCards.show(eventArea, lines.isEmpty() ? "empty" : "table");
    }
    private String eventsShown = "";

    /** A line that reports something going wrong is an error; every other line is information. */
    static String eventType(String line) {
        return java.util.regex.Pattern.compile("(?i)\\b(error|failed|could not|was not accepted)\\b").matcher(line).find() ? "Error" : "Info";
    }

    /** A chronological log of findings as they were detected. */
    private JComponent buildAuditLogTab() {
        auditLogTable = new JTable(auditLogModel);
        Ui.styleTable(auditLogTable);
        Ui.distributeWidths(auditLogTable, 48, 150, 80, 90, 200, 150, 130, 130, 85, 85);
        lightHeader(auditLogTable);
        auditLogGlyphColumn(auditLogTable, 4);   // severity/confidence glyph before the issue type
        // Severity column stays plain dark text: the glyph carries the colour.

        javax.swing.table.TableRowSorter<AuditLogModel> sorter =
                new opensuite.ui.NumberSorter<>(auditLogModel);
        auditLogTable.setRowSorter(sorter);
        Ui.newestFirst(auditLogTable, 0);

        // Filter state shared by the Filter popup and the Search box.
        final java.util.Set<Issue.Severity> enabled = java.util.EnumSet.allOf(Issue.Severity.class);
        final String[] query = { "" };
        final Runnable apply = () -> sorter.setRowFilter(new RowFilter<AuditLogModel, Integer>() {
            @Override public boolean include(Entry<? extends AuditLogModel, ? extends Integer> e) {
                Issue is = auditLogModel.issueAt(e.getIdentifier());
                if (is != null && !enabled.contains(is.severity())) return false;
                String q = query[0].toLowerCase();
                if (q.isEmpty()) return true;
                for (int c = 0; c < e.getValueCount(); c++) {
                    Object v = e.getValue(c);
                    if (v != null && v.toString().toLowerCase().contains(q)) return true;
                }
                return false;
            }
        });

        // ---- Filter button (left): a real per-severity filter ----
        JButton filter = new JButton("Filter", funnelIcon());
        filter.setFont(Ui.PLAIN);
        filter.setFocusPainted(false);
        filter.addActionListener(e -> {
            JPopupMenu m = new JPopupMenu();
            for (Issue.Severity s : Issue.Severity.values()) {
                JCheckBoxMenuItem it = new JCheckBoxMenuItem(s.label(), enabled.contains(s));
                it.addActionListener(a -> {
                    if (it.isSelected()) enabled.add(s); else enabled.remove(s);
                    apply.run();
                });
                m.add(it);
            }
            m.show(filter, 0, filter.getHeight());
        });

        // ---- Search box (right): a real text filter over all columns ----
        JTextField search = new JTextField(16);
        search.setBorder(null);
        search.setOpaque(false);
        search.getDocument().addDocumentListener(new DocumentListener() {
            private void upd() { query[0] = search.getText().trim(); apply.run(); }
            @Override public void insertUpdate(DocumentEvent e) { upd(); }
            @Override public void removeUpdate(DocumentEvent e) { upd(); }
            @Override public void changedUpdate(DocumentEvent e) { upd(); }
        });
        JPanel searchWrap = new JPanel(new BorderLayout(6, 0));
        searchWrap.setBackground(Theme.BG);
        searchWrap.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Ui.GRID), Ui.pad(3, 8, 3, 8)));
        searchWrap.add(search, BorderLayout.CENTER);
        searchWrap.add(new JLabel(magnifierIcon()), BorderLayout.EAST);

        JPanel bar = new JPanel(new BorderLayout());
        bar.setOpaque(false);
        bar.setBorder(Ui.pad(0, 0, 6, 0));
        bar.add(filter, BorderLayout.WEST);
        bar.add(searchWrap, BorderLayout.EAST);

        JPanel p = new JPanel(new BorderLayout(0, 4));
        p.setOpaque(false);
        p.setBorder(Ui.pad(4, 4, 4, 4));
        p.add(bar, BorderLayout.NORTH);
        p.add(Ui.scroll(auditLogTable), BorderLayout.CENTER);
        return p;
    }

    /** The severity/confidence glyph disc in front of an audit-log issue type. */
    private void auditLogGlyphColumn(JTable table, int textCol) {
        table.getColumnModel().getColumn(textCol).setCellRenderer(
            new javax.swing.table.DefaultTableCellRenderer() {
                @Override public Component getTableCellRendererComponent(JTable t, Object v,
                        boolean sel, boolean focus, int row, int column) {
                    super.getTableCellRendererComponent(t, v, sel, focus, row, column);
                    Issue is = auditLogModel.issueAt(t.convertRowIndexToModel(row));
                    if (is != null) setIcon(issueGlyphIcon(is.severity(), is.confidence()));
                    setIconTextGap(7);
                    return this;
                }
            });
    }

    /** A small funnel glyph for the Filter button. */
    private static javax.swing.Icon funnelIcon() {
        int s = 14;
        java.awt.image.BufferedImage img =
                new java.awt.image.BufferedImage(s, s, java.awt.image.BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(Theme.MUTED);
        g.setStroke(new BasicStroke(1.3f));
        g.drawPolygon(new int[]{1, 13, 8, 6}, new int[]{2, 2, 8, 13}, 4);
        g.dispose();
        return new javax.swing.ImageIcon(img);
    }

    /** A small magnifier glyph for the Search box. */
    private static javax.swing.Icon magnifierIcon() {
        int s = 14;
        java.awt.image.BufferedImage img =
                new java.awt.image.BufferedImage(s, s, java.awt.image.BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(Theme.MUTED);
        g.setStroke(new BasicStroke(1.4f));
        g.drawOval(2, 2, 7, 7);
        g.drawLine(9, 9, 13, 13);
        g.dispose();
        return new javax.swing.ImageIcon(img);
    }

    // ---------------------------------------------------------------- helpers

    private static void accentise(JButton b) {
        // Plain, like every other button in the app (no orange).
        b.setFocusPainted(false);
    }

    /** Small grey line icons for the summary section headings. */
    private static javax.swing.Icon sectionIcon(String kind) {
        int s = 16 + Ui.fontGrowth();
        java.awt.image.BufferedImage img =
                new java.awt.image.BufferedImage(s, s, java.awt.image.BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g.scale(s / 16.0, s / 16.0);
        g.setColor(Theme.TEXT);
        g.setStroke(new BasicStroke(1.2f));
        switch (kind) {
            case "folder" -> {
                g.drawLine(2, 5, 6, 5); g.drawLine(6, 5, 7, 4);
                g.drawRoundRect(2, 5, 12, 8, 2, 2);
            }
            case "gear" -> {
                g.drawOval(5, 5, 6, 6);
                for (int a = 0; a < 360; a += 45) {
                    double r = Math.toRadians(a);
                    g.drawLine((int) (8 + 4 * Math.cos(r)), (int) (8 + 4 * Math.sin(r)),
                               (int) (8 + 6.5 * Math.cos(r)), (int) (8 + 6.5 * Math.sin(r)));
                }
            }
            case "clock" -> {
                g.drawOval(2, 2, 12, 12);
                g.drawLine(8, 8, 8, 4); g.drawLine(8, 8, 11, 9);
            }
            case "warning" -> {
                // A rounded triangle with an exclamation mark.
                g.drawPolygon(new int[]{8, 2, 14}, new int[]{2, 13, 13}, 3);
                g.drawLine(8, 6, 8, 9);
                g.fillOval(7, 10, 2, 2);
            }
            case "pencil" -> {
                g.drawLine(3, 13, 11, 5);
                g.drawLine(11, 5, 13, 7);
                g.drawLine(13, 7, 5, 15);
                g.drawLine(3, 13, 5, 15);
            }
            case "pie" -> {
                g.drawOval(2, 2, 12, 12);
                g.drawLine(8, 8, 8, 2);
                g.drawLine(8, 8, 13, 10);
            }
        }
        g.dispose();
        return new javax.swing.ImageIcon(img);
    }

    // ----------------------------------------------------------- task cards

    /**
     * Collapses a burst of refresh requests into at most one refresh per
     * interval on the event-dispatch thread. {@link #request()} may be called
     * from any thread; the action always runs on the EDT.
     */

    /** Apply queued scan-log entries to the table in one batch (runs on the EDT). */
    private void flushScanLog() {
        List<LogEntry> batch = new ArrayList<>();
        for (LogEntry e; (e = logAddQueue.poll()) != null; ) batch.add(e);
        if (!batch.isEmpty()) { scanLogModel.addAll(batch); for (LogEntry e : batch) auditItemsModel.add(e); }
        if (logHasUpdates) { logHasUpdates = false; scanLogModel.refreshRows(); }
    }

    /** The numbers of the tasks the list has shown, to tell a new one when it arrives. */
    private final java.util.Set<Integer> listed = new java.util.HashSet<>();

    private void rebuildTasks() {
        List<ScanTask> tasks = ctx == null ? List.of() : ctx.tasks();
        String q = searchField == null ? "" : searchField.getText().trim().toLowerCase();

        taskList.removeAll();
        cards.clear();

        // Keep the previous selection alive if it still exists.
        boolean selectionStillPresent = false;

        // A task started since the list was last built is shown at once: it is selected, and it is at the top.
        ScanTask fresh = null;
        for (ScanTask t : tasks) if (!listed.contains(t.number) && !listed.isEmpty()) fresh = t;
        for (ScanTask t : tasks) listed.add(t.number);
        if (fresh != null) selected = fresh;

        // Newest first, so a task just started is on top without scrolling.
        List<ScanTask> newestFirst = new ArrayList<>(tasks);
        java.util.Collections.reverse(newestFirst);
        for (ScanTask t : newestFirst) {
            if (!passesFilter(t)) continue;
            if (!q.isEmpty()) {
                String hay = (t.number + " " + t.title() + " " + t.configuration()
                        + " " + t.stateLabel()).toLowerCase();
                if (!hay.contains(q)) continue;
            }
            TaskCard card = new TaskCard(t);
            cards.put(t, card);
            card.setAlignmentX(Component.LEFT_ALIGNMENT);
            taskList.add(card);
            taskList.add(Box.createVerticalStrut(Math.max(0, 4 - 2 * Ui.fontGrowth())));
            if (t == selected) selectionStillPresent = true;
        }

        if (!selectionStillPresent) {
            selected = newestFirst.isEmpty() ? null : newestFirst.get(0);
        }
        for (Map.Entry<ScanTask, TaskCard> e : cards.entrySet()) {
            e.getValue().setSelectedLook(e.getKey() == selected);
        }

        taskList.revalidate();
        taskList.repaint();

        // Run the shared animation timer only while a crawl is actively running,
        // so an idle dashboard does no repaint work.
        boolean animating = tasks.stream().anyMatch(t ->
                t.type() == ScanTask.Type.LIVE_ACTIVE && t.state() == ScanTask.State.RUNNING);
        ensureCardAnimation(animating);

        refreshRight();
    }

    /** Start or stop the single timer that animates running crawl progress bars. */
    private void ensureCardAnimation(boolean animating) {
        if (animating) {
            if (cardAnimTimer == null) {
                cardAnimTimer = new javax.swing.Timer(30, e -> taskList.repaint());
                cardAnimTimer.start();
            }
        } else if (cardAnimTimer != null) {
            cardAnimTimer.stop();
            cardAnimTimer = null;
        }
    }

    private void selectTask(ScanTask t) {
        selected = t;
        for (Map.Entry<ScanTask, TaskCard> e : cards.entrySet()) {
            e.getValue().setSelectedLook(e.getKey() == selected);
        }
        refreshRight();
    }

    private Window ownerFrame() { return ctx == null ? null : ctx.frame(); }

    /** Which task states and kinds the list shows; everything by default. */
    private final java.util.Set<String> taskFilter = new java.util.HashSet<>(java.util.List.of(
            "Running", "Paused", "Finished", "Live task", "Scan", "Intruder attack"));

    private JComponent chipRow(String... names) {
        JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
        row.setOpaque(false);
        for (String n : names) {
            JToggleButton b = new JToggleButton(n, taskFilter.contains(n));
            b.setFont(Ui.PLAIN);
            b.setFocusable(false);
            b.setMargin(new Insets(2, 10, 2, 10));
            b.addActionListener(e -> { if (b.isSelected()) taskFilter.add(n); else taskFilter.remove(n); rebuildTasks(); });
            row.add(b);
        }
        return row;
    }

    private boolean passesFilter(ScanTask t) {
        String state = t.stateLabel();
        if (!taskFilter.contains(state)) return false;
        boolean live = t.type() == ScanTask.Type.LIVE_PASSIVE || liveTaskSettings.containsKey(t);
        return taskFilter.contains(live ? "Live task" : "Scan");
    }

    /** Rename a task to any label the user types. */
    private void renameTask(ScanTask t) {
        Object input = JOptionPane.showInputDialog(ownerFrame(), "Rename task:",
                "Rename task", JOptionPane.PLAIN_MESSAGE, null, null, t.title());
        if (input == null) return;
        String name = input.toString().trim();
        if (name.isEmpty()) return;
        t.setTitle(name);
        if (ctx != null) ctx.taskChanged(t);
    }

    /** Remove a task from the dashboard after confirmation. */
    private void deleteTask(ScanTask t) {
        int ok = JOptionPane.showConfirmDialog(ownerFrame(),
                "Remove task \"" + t.number + ". " + t.title() + "\" from the dashboard?\n"
                + "Any findings it has already reported are kept.",
                "Delete task", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
        if (ok != JOptionPane.OK_OPTION) return;
        // Really stop the task: cancel() signals its scan loop to stop the engine
        // (spider/active scan/AJAX spider) and exit, so nothing keeps running or
        // accumulating memory in the background after the card is gone.
        t.cancel();
        if (t == liveAudit && passiveScanner != null) passiveScanner.setEnabled(false);
        if (t == liveCrawl) opensuite.target.PassiveCrawl.setEnabled(false);
        rerun.remove(t);
        crawlScans.remove(t);
        // The task's config and its already-saved marker go with it; leaving
        // them held every task (deleted included) for the whole session.
        taskConfigs.remove(t);
        savedOnFinish.remove(t);
        if (selected == t) selected = null;
        if (ctx != null) ctx.removeTask(t);
    }


    // ------------------------------------------------------------ live tasks

    /** "New live task": a live audit or live passive crawl over traffic from the chosen tools. */
    private void newLiveTask() {
        LiveTaskDialog d = new LiveTaskDialog(ctx, ctx == null ? null : ctx.frame(), null);
        d.setVisible(true);
        if (!d.saved()) return;
        LiveTaskDialog.Result r = d.result();
        ScanTask t = new ScanTask(r.passiveCrawl() ? ScanTask.Type.LIVE_ACTIVE : ScanTask.Type.LIVE_PASSIVE,
                r.title(), r.configuration());
        t.setScope(switch (r.scopeMode()) {
            case "suite" -> "Suite scope";
            case "custom" -> r.customScope() == null ? "Custom scope" : describeScope(r.customScope());
            default -> "Everything";
        });
        t.log((r.passiveCrawl() ? "Live passive crawl" : "Live audit") + " started. " + r.title());
        if (r.passiveCrawl()) t.log(r.passiveSummary());
        if (r.dedupe()) t.log("Ignoring duplicate items based on URL and parameter names");
        t.log("Resource pool: " + r.pool().name());
        liveTaskSettings.put(t, r);
        ctx.addTask(t);
        selectTask(t);
    }

    private static String describeScope(opensuite.core.Scope sc) {
        List<String> parts = new ArrayList<>();
        for (opensuite.core.Scope.Rule rule : sc.include()) if (rule.enabled) parts.add(rule.describe());
        return parts.isEmpty() ? "Custom scope" : String.join(", ", parts);
    }

    /** The gear / Settings: live tasks open their editor, scans show their configuration. */
    private void openTaskSettings(ScanTask task, Component near) {
        if (task == null) {
            JOptionPane.showMessageDialog(near, "Select a task first.", "Task settings", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        boolean live = task.type() == ScanTask.Type.LIVE_PASSIVE || (task.type() == ScanTask.Type.LIVE_ACTIVE && !rerun.containsKey(task));
        if (!live) { showTaskConfig(task, near); return; }
        LiveTaskDialog d = new LiveTaskDialog(ctx, ownerFrame() instanceof Frame f ? f : null, task);
        d.setVisible(true);
        if (!d.saved()) return;
        LiveTaskDialog.Result r = d.result();
        liveTaskSettings.put(task, r);
        task.setTitle(r.title());
        task.setScope(switch (r.scopeMode()) {
            case "suite" -> "Suite scope";
            case "custom" -> r.customScope() == null ? "Custom scope" : describeScope(r.customScope());
            default -> "Everything";
        });
        task.log("Settings changed: " + r.title() + " (" + r.configuration() + ")");
        ctx.taskChanged(task);
    }

    // ---------------------------------------------------- audit items / logger

    /** Audit items: one row for each address the audit has worked on, with how far the audit of it has got. */
    private JComponent buildAuditItemsTab() {
        auditItemsTable = new JTable(auditItemsModel);
        Ui.styleTable(auditItemsTable);
        Ui.distributeWidths(auditItemsTable, 40, 110, 280, 125, 100, 60, 80, 60, 95, 160, 160, 80);
        lightHeader(auditItemsTable);
        auditItemsTable.getColumnModel().getColumn(AuditItemsModel.RULES).setCellRenderer(new RulesRunRenderer());
        auditBaseRequest = newEditor(MessageEditor.REQUEST);
        JTextField search = Ui.field("");
        search.putClientProperty("JTextField.placeholderText", "Search");
        javax.swing.table.TableRowSorter<AuditItemsModel> sorter = new opensuite.ui.NumberSorter<>(auditItemsModel);
        auditItemsSorter = sorter;
        auditItemsTable.setRowSorter(sorter);
        search.getDocument().addDocumentListener(new DocumentListener() {
            private void go() {
                auditItemsSearch = search.getText().strip();
                filterTaskTables();
            }
            @Override public void insertUpdate(DocumentEvent e) { go(); }
            @Override public void removeUpdate(DocumentEvent e) { go(); }
            @Override public void changedUpdate(DocumentEvent e) { go(); }
        });
        JButton kebab = opensuite.ui.Glyphs.menuButton("Table layout", () -> opensuite.ui.TableLayoutMenu.build(auditItemsTable));
        JPanel bar = new JPanel(new BorderLayout());
        bar.setOpaque(false);
        JPanel right = new JPanel(new FlowLayout(FlowLayout.RIGHT, 4, 0));
        right.setOpaque(false);
        right.add(search); right.add(kebab);
        bar.add(right, BorderLayout.EAST);
        JScrollPane sp = new JScrollPane(auditItemsTable);
        sp.setBorder(BorderFactory.createLineBorder(Ui.GRID));

        // Lower pane: the base request, the insertion points list, and the inspector the editor carries.
        JPanel points = new JPanel(new BorderLayout(0, 4));
        points.setOpaque(false);
        points.setBorder(Ui.pad(0, 6, 0, 0));
        JPanel chip = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 0));
        chip.setOpaque(false);
        chip.add(Ui.bold("Parameters"));
        points.add(chip, BorderLayout.NORTH);
        javax.swing.table.DefaultTableModel pm = new javax.swing.table.DefaultTableModel(new Object[]{"Parameter", "Type"}, 0) {
            @Override public boolean isCellEditable(int r, int c) { return false; }
        };
        JTable pt = new JTable(pm);
        Ui.styleTable(pt);
        points.add(Ui.scroll(pt), BorderLayout.CENTER);
        JPanel info = new JPanel(new BorderLayout());
        info.setOpaque(false);
        JLabel infoHead = Ui.bold("Information");
        infoHead.setBorder(Ui.pad(4, 0, 2, 0));
        info.add(infoHead, BorderLayout.NORTH);
        info.add(Ui.note("Select an audit item to see the first request the audit sent to it and the parameters of that request."), BorderLayout.CENTER);
        points.add(info, BorderLayout.SOUTH);
        // Drawn again only when another item is selected, or when the selected item gets its first request:
        // a table that is filling moves its selection about without the choice changing.
        Object[] showing = {null, null};
        Runnable showItem = () -> {
            int r = auditItemsTable.getSelectedRow();
            AuditItem it = r < 0 ? null : auditItemsModel.at(auditItemsTable.convertRowIndexToModel(r));
            if (it == null) return;
            if (it == showing[0] && it.first == showing[1]) return;
            showing[0] = it;
            showing[1] = it.first;
            pm.setRowCount(0);
            if (it.first == null) { auditBaseRequest.setMessage(null, new HttpMessage(new byte[0])); return; }
            auditBaseRequest.setMessage(it.first.service(), it.first.request());
            for (var prm : it.first.request().parameters()) pm.addRow(new Object[]{prm.name(), prm.type()});
        };
        auditItemsTable.getSelectionModel().addListSelectionListener(e -> { if (!e.getValueIsAdjusting()) showItem.run(); });
        auditItemsModel.addTableModelListener(e -> { if (e.getType() == javax.swing.event.TableModelEvent.UPDATE) showItem.run(); });
        JSplitPane lower = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, auditBaseRequest, points);
        lower.setDividerSize(1);
        Ui.balance(lower, 0.6);
        JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, sp, lower);
        split.setDividerSize(1);
        Ui.balance(split, 0.45);
        JPanel p = new JPanel(new BorderLayout(0, 4));
        p.setOpaque(false);
        p.add(bar, BorderLayout.NORTH);
        p.add(split, BorderLayout.CENTER);
        return p;
    }

    /** One audit item: an address and what the audit did with it. */
    private static final class AuditItem {
        final String host, url;
        LogEntry first;
        int requests, errors;
        int row = -1;              // where it is in the table now, or -1
        java.util.Date start, end;
        AuditItem(String host, String url) { this.host = host; this.url = url; }
    }

    /**
     * The audit items of the selected task. For an audit that reported its
     * rule starts ({@link opensuite.core.RuleProgress}) the rows are the
     * addresses the engine started a rule on, in the order it first did, and
     * each row says how many of the rules that apply to it have been run and
     * how many of the task's findings are at it. A task that has audited
     * nothing yet, one still crawling for instance, has no rows: what other
     * tasks audited is never shown under it.
     *
     * <p>Requests, errors and times come from the audit requests sent to the
     * address itself.
     */
    private final class AuditItemsModel extends AbstractTableModel {
        private static final int STATUS = 3, RULES = 4, ISSUES = 5;
        private final String[] cols = {"#", "Host", "URL", "Status", "Progress",
                "Issues", "Requests", "Errors", "Parameters", "Start time", "End time", "Comment"};
        private final List<AuditItem> all = new ArrayList<>();       // every address audit traffic was seen for, in order
        private final java.util.Map<String, AuditItem> byKey = new java.util.HashMap<>();
        private List<AuditItem> rows = new ArrayList<>();            // the selected task's own addresses
        private final java.text.DateFormat fmt = new java.text.SimpleDateFormat("HH:mm:ss dd MMM yyyy");
        private ScanTask shown;
        private boolean byRules;
        private int listed, drawn = -1, issuesDrawn = -1;
        private ScanTask.State stateDrawn;
        private java.util.Map<String, Integer> issues = java.util.Map.of();

        AuditItem at(int r) { return r >= 0 && r < rows.size() ? rows.get(r) : null; }
        opensuite.core.RuleProgress progress() { return byRules && shown != null ? shown.rules() : null; }

        private AuditItem item(String key) {
            AuditItem it = byKey.get(key);
            if (it == null) {
                String site = opensuite.core.RuleProgress.site(key);
                String host = site.substring(site.indexOf("://") + 3);
                if (host.lastIndexOf(':') > host.lastIndexOf(']')) host = host.substring(0, host.lastIndexOf(':'));
                it = new AuditItem(host, key);
                byKey.put(key, it);
                all.add(it);
            }
            return it;
        }

        void add(LogEntry e) {
            if (!"audit".equals(e.tool())) return;
            AuditItem it = item(opensuite.core.RuleProgress.key(e.service().url() + e.request().path()));
            if (it.first == null) { it.first = e; it.start = e.time(); }
            it.requests++;
            if (!e.error().isEmpty()) it.errors++;
            it.end = e.time();
            if (it.row >= 0 && it.row < rows.size() && rows.get(it.row) == it) {
                fireTableRowsUpdated(it.row, it.row);
            }
        }

        /** Bring the table in line with the selected task: its rows, and whatever has changed in them. */
        void sync(ScanTask t, List<Issue> allIssues, int issuesStamp) {
            opensuite.core.RuleProgress p = t == null ? null : t.rules();
            boolean now = p != null && p.known();
            if (t != shown || now != byRules) {
                for (AuditItem it : rows) it.row = -1;
                shown = t;
                byRules = now;
                listed = 0;
                drawn = issuesDrawn = -1;
                // A task that has audited nothing yet (still crawling, say) has no rows:
                // the addresses other tasks audited are theirs, not this one's.
                rows = new ArrayList<>();
                fireTableDataChanged();
            }
            if (byRules) {
                List<String> more = p.addresses(listed);
                if (!more.isEmpty()) {
                    int from = rows.size();
                    for (String a : more) { AuditItem it = item(a); it.row = rows.size(); rows.add(it); }
                    listed += more.size();
                    fireTableRowsInserted(from, rows.size() - 1);
                }
            }
            boolean changed = false;
            if (issuesDrawn != issuesStamp) {
                issuesDrawn = issuesStamp;
                java.util.Map<String, Integer> counts = new java.util.HashMap<>();
                if (byRules) {
                    String source = "Scan " + t.number;
                    for (Issue is : allIssues) {
                        if (is.service() == null || !is.foundBy(source)) continue;
                        counts.merge(opensuite.core.RuleProgress.key(is.service().url() + (is.path() == null ? "/" : is.path())), 1, Integer::sum);
                    }
                }
                if (!counts.equals(issues)) { issues = counts; changed = true; }
            }
            int version = p == null ? 0 : p.version();
            ScanTask.State state = t == null ? null : t.state();
            if (version != drawn || state != stateDrawn) { drawn = version; stateDrawn = state; changed = true; }
            if (changed && !rows.isEmpty()) fireTableRowsUpdated(0, rows.size() - 1);
        }

        /** Where an address stands: every rule run on it, or what the scan is doing while some are not. */
        private String status(AuditItem it) {
            opensuite.core.RuleProgress p = progress();
            if (p == null) return "";
            opensuite.core.RuleProgress.Count c = p.count(it.url);
            if (c != null && c.done()) return "Finished";
            return shown.state() == ScanTask.State.RUNNING ? "Scanning" : shown.state() == ScanTask.State.PAUSED ? "Paused" : "Stopped";
        }

        @Override public int getRowCount() { return rows.size(); }
        @Override public int getColumnCount() { return cols.length; }
        @Override public String getColumnName(int c) { return cols[c]; }
        @Override public Class<?> getColumnClass(int c) { return c == RULES ? opensuite.core.RuleProgress.Count.class : Object.class; }
        @Override public Object getValueAt(int r, int c) {
            AuditItem it = rows.get(r);
            return switch (c) {
                case 0 -> r + 1;
                case 1 -> it.host;
                case 2 -> it.url;
                case STATUS -> status(it);
                case RULES -> progress() == null ? null : progress().count(it.url);
                case ISSUES -> progress() == null ? "" : issues.getOrDefault(it.url, 0);
                case 6 -> it.requests;
                case 7 -> it.errors;
                case 8 -> it.first == null ? "" : it.first.request().parameters().size();
                case 9 -> it.start == null ? "" : fmt.format(it.start);
                case 10 -> it.end == null ? "" : fmt.format(it.end);
                default -> "";
            };
        }
    }

    /**
     * How far the audit of an address has got: a percentage and a small bar.
     * It is a rough guide: the checks differ a great deal in size, so it does
     * not move evenly.
     */
    private final class RulesRunRenderer extends javax.swing.table.DefaultTableCellRenderer {
        private int percent = -1;

        @Override public Component getTableCellRendererComponent(JTable t, Object v, boolean sel, boolean f, int r, int c) {
            super.getTableCellRendererComponent(t, "", sel, f, r, c);
            setToolTipText(null);
            percent = -1;
            AuditItem it = auditItemsModel.at(t.convertRowIndexToModel(r));
            opensuite.core.RuleProgress p = auditItemsModel.progress();
            if (it == null || p == null || !(v instanceof opensuite.core.RuleProgress.Count n)) return this;
            percent = n.total() == 0 ? 100 : n.percent();
            return this;
        }

        @Override protected void paintComponent(Graphics g0) {
            super.paintComponent(g0);
            if (percent < 0) return;
            Graphics2D g = (Graphics2D) g0.create();
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            g.setFont(getFont());
            FontMetrics fm = g.getFontMetrics();
            int pad = Ui.em(6), textW = fm.stringWidth("100%"), gap = Ui.em(6);
            int barH = Math.max(4, Ui.em(5)), barW = Math.max(0, getWidth() - pad * 2 - textW - gap);
            int y = (getHeight() - barH) / 2;
            if (barW >= Ui.em(16)) {
                g.setColor(Theme.BORDER);
                g.fillRoundRect(pad, y, barW, barH, barH, barH);
                int fill = (int) Math.round(barW * percent / 100.0);
                if (fill > 0) {
                    g.setColor(percent >= 100 ? FINISHED_GREEN : Theme.ACCENT);
                    g.fillRoundRect(pad, y, Math.max(barH, fill), barH, barH, barH);
                }
            }
            String text = percent + "%";
            g.setColor(getForeground());
            g.drawString(text, getWidth() - pad - fm.stringWidth(text), (getHeight() - fm.getHeight()) / 2 + fm.getAscent());
            g.dispose();
        }
    }

    private static String escapeHtml(String s) {
        return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
    }

    /** Logger: the task's own traffic, the same table and viewer as the crawl window. */
    private JComponent buildTaskLoggerTab() {
        JTable table = new JTable(scanLogModel);
        Ui.styleTable(table);
        Ui.distributeWidths(table, 48, 95, 60, 70, 170, 200, 150, 60, 70);
        lightHeader(table);
        taskLogSorter = new opensuite.ui.NumberSorter<>(scanLogModel);
        table.setRowSorter(taskLogSorter);
        Ui.newestFirst(table, 0);
        MessageEditor req = newEditor(MessageEditor.REQUEST);
        MessageEditor resp = newEditor(MessageEditor.RESPONSE);
        table.getSelectionModel().addListSelectionListener(e -> {
            int row = table.getSelectedRow();
            if (row < 0) return;
            LogEntry en = scanLogModel.at(table.convertRowIndexToModel(row));
            if (en == null) return;
            req.setMessage(en.service(), en.request());
            if (en.response() != null) resp.setMessage(en.service(), en.response(), en.request());
        });
        JButton capture = Ui.filterButton();
        capture.setText("Capture filter: this task's traffic | Capturing requests up to 1MB; capturing responses up to 1MB");
        JCheckBox logging = Ui.check("Logging on", true);
        JPanel captureBar = Ui.filterBar(capture, logging, opensuite.ui.Glyphs.button(opensuite.ui.Glyphs.help(), "Live traffic generated by this task", null));
        JButton view = Ui.filterButton();
        view.setText("View filter: Showing all items");
        JTextField search = Ui.field("");
        search.putClientProperty("JTextField.placeholderText", "Search");
        JButton kebab = opensuite.ui.Glyphs.menuButton("Table layout", () -> opensuite.ui.TableLayoutMenu.build(table));
        JPanel viewBar = Ui.filterBar(view, search, kebab);
        JScrollPane logScroll = new JScrollPane(table);
        logScroll.setBorder(BorderFactory.createLineBorder(Ui.GRID));
        JSplitPane detail = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, req, resp);
        detail.setDividerSize(1);
        Ui.balance(detail, 0.5);
        JSplitPane logger = new JSplitPane(JSplitPane.VERTICAL_SPLIT, logScroll, detail);
        logger.setDividerSize(1);
        Ui.balance(logger, 0.5);
        JPanel p = new JPanel(new BorderLayout(0, 4));
        p.setOpaque(false);
        p.add(Ui.vbox(captureBar, viewBar), BorderLayout.NORTH);
        p.add(logger, BorderLayout.CENTER);
        return p;
    }

    // ------------------------------------------------------------ detached view

    /** What the main pane shows while the task detail is open in its own window. */
    private JComponent buildDetachedCard() {
        JPanel col = new JPanel();
        col.setLayout(new BoxLayout(col, BoxLayout.Y_AXIS));
        col.setOpaque(false);
        JLabel icon = new JLabel(opensuite.ui.Glyphs.export(56, Theme.BORDER));
        JLabel h = Ui.heading("Task is in detached view");
        JLabel t = Ui.label("Task detail is open in another window.");
        t.setForeground(Theme.MUTED);
        JButton front = Ui.button("Bring to front", "Raise the task window");
        JButton attach = Ui.primaryButton("Re-attach tab", "Return the task detail to the dashboard");
        front.addActionListener(e -> { if (detachedFrame != null) { detachedFrame.toFront(); detachedFrame.requestFocus(); } });
        attach.addActionListener(e -> reattachTask());
        JPanel btns = Ui.row(front, attach);
        for (JComponent c : new JComponent[]{icon, h, t, btns}) { c.setAlignmentX(Component.CENTER_ALIGNMENT); col.add(c); col.add(Box.createVerticalStrut(10)); }
        JPanel wrap = new JPanel(new GridBagLayout());
        wrap.setOpaque(false);
        wrap.add(col, new GridBagConstraints());
        return wrap;
    }

    private void reattachTask() {
        if (detachedFrame == null) return;
        JFrame f = detachedFrame;
        detachedFrame = null;
        detachedTask = null;
        f.getContentPane().removeAll();
        f.dispose();
        taskTabsHost.add(taskTabs, BorderLayout.CENTER);
        taskTabsHost.revalidate();
        taskTabsHost.repaint();
        refreshRight();
    }

    /** Open the selected task's detail in its own window; the dashboard shows a placeholder until it is re-attached. */
    private void openTaskWindow(ScanTask t) {
        selectTask(t);
        if (detachedFrame != null) { detachedFrame.toFront(); return; }
        JFrame f = new JFrame(t.number + ". " + t.title());
        f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        detachedFrame = f;
        detachedTask = t;

        // Header: an editable title (rename inline), and the same three controls as the pane.
        JTextField title = Ui.field(t.title());
        title.setFont(Ui.HEADING);
        title.addActionListener(e -> { String n = title.getText().strip(); if (!n.isEmpty()) { t.setTitle(n); f.setTitle(t.number + ". " + n); ctx.taskChanged(t); } });
        JPanel head = new JPanel(new BorderLayout(8, 0));
        head.setOpaque(false);
        head.setBorder(Ui.pad(8, 10, 4, 10));
        JButton back = opensuite.ui.Glyphs.button(opensuite.ui.Glyphs.arrow(16, Theme.ICON, 3), "Re-attach to the dashboard", this::reattachTask);
        JPanel left = new JPanel(new FlowLayout(FlowLayout.LEFT, 6, 0));
        left.setOpaque(false);
        left.add(back);
        left.add(Ui.label(t.number + "."));
        left.add(title);
        head.add(left, BorderLayout.WEST);
        JPanel controls = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 0));
        controls.setOpaque(false);
        controls.add(new HeaderIconButton("play", 17, "Pause or resume the task", () -> {
            if (t.state() != ScanTask.State.FINISHED) {
                t.setState(t.state() == ScanTask.State.RUNNING ? ScanTask.State.PAUSED : ScanTask.State.RUNNING);
                ctx.taskChanged(t);
            }
        }));
        controls.add(new HeaderIconButton("gear", 17, "Task settings", () -> openTaskSettings(t, f.getContentPane())));
        controls.add(new HeaderIconButton("help", 17, "Getting started", () -> { if (ctx.frame() instanceof opensuite.ui.SuiteFrame sf) sf.selectTool("discover"); }));
        head.add(controls, BorderLayout.EAST);

        // Move the live sub-tabs into this window; the dashboard shows the placeholder meanwhile.
        taskTabsHost.remove(taskTabs);
        taskTabsHost.revalidate();
        taskTabsHost.repaint();
        rightCards.show(rightBody, "detached");
        JPanel body = new JPanel(new BorderLayout());
        body.add(head, BorderLayout.NORTH);
        body.add(taskTabs, BorderLayout.CENTER);
        f.setContentPane(body);
        f.setSize(1100, 720);
        f.setLocationRelativeTo(ownerFrame());
        f.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override public void windowClosing(java.awt.event.WindowEvent e) { reattachTask(); }
        });
        f.setVisible(true);
    }

    /** A single task card in the left-hand list. */
    private final class TaskCard extends JPanel {
        private final ScanTask task;

        private boolean selectedLook;

        TaskCard(ScanTask task) {
            super(new BorderLayout());
            this.task = task;
            setOpaque(false);
            // 8px of shadow all round, then 20px of padding inside the card.
            int g = Ui.fontGrowth();
            setBorder(Ui.pad(28 + g / 2, 28, 28 - g / 2, 31 + g / 2));

            boolean passive  = task.type() == ScanTask.Type.LIVE_PASSIVE;
            boolean finished = task.state() == ScanTask.State.FINISHED;
            boolean running  = task.state() == ScanTask.State.RUNNING;

            // ---- header: title (truncates), a play/pause circle, an overflow menu.
            JLabel title = Ui.bold(task.number + ". " + task.title());
            title.setToolTipText(task.number + ". " + task.title());

            title.setForeground(Theme.TEXT);
            JPanel controls = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
            controls.setOpaque(false);
            if (!finished) {
                controls.add(new HeaderIconButton(running ? "pause" : "play", 17, running ? "Pause" : "Resume", this::toggleState));
                controls.add(Box.createHorizontalStrut(13 + g));
            }
            controls.add(new MenuButton());

            JPanel titleRow = new JPanel(new BorderLayout(6 + 2 * g, 0));
            titleRow.setOpaque(false);
            titleRow.add(title, BorderLayout.CENTER);
            titleRow.add(controls, BorderLayout.EAST);
            titleRow.setPreferredSize(new Dimension(10, 17));
            titleRow.setMaximumSize(new Dimension(Integer.MAX_VALUE, 17));
            int wrap = 300 + 10 * g;

            // The description wraps inside the card, 300px at most.
            JTextArea config = opensuite.ui.Sections.text(task.configuration());
            config.setSize(new Dimension(wrap, 10));
            config.setPreferredSize(new Dimension(wrap, config.getPreferredSize().height));
            config.setMaximumSize(new Dimension(wrap, config.getPreferredSize().height));
            config.addMouseListener(new java.awt.event.MouseAdapter() {
                @Override public void mousePressed(java.awt.event.MouseEvent e) { selectTask(task); }
            });

            JPanel head = new JPanel();
            head.setOpaque(false);
            head.setLayout(new BoxLayout(head, BoxLayout.Y_AXIS));
            titleRow.setAlignmentX(LEFT_ALIGNMENT);
            config.setAlignmentX(LEFT_ALIGNMENT);
            head.add(titleRow);
            head.add(Box.createVerticalStrut(15 + g / 2));
            head.add(config);

            // The passive audit is a simple on/off capture stage, so it shows a
            // "Capturing" toggle and no bar. Active work (a crawl, or an audit)
            // keeps a progress bar while it runs, but a finished task shows no bar.
            boolean crawl = task.type() == ScanTask.Type.LIVE_ACTIVE;
            JComponent progress = (passive || finished) ? null : new ProgressStrip(task);

            int stateGap = 8 + 3 * g;
            JPanel stateRow = new JPanel(new FlowLayout(FlowLayout.LEFT, stateGap, 0));
            stateRow.setBorder(Ui.pad(0, -stateGap, 0, 0));
            stateRow.setOpaque(false);
            if (passive && !finished) {
                // On/off toggle for the continuous passive capture stage.
                JLabel capturing = Ui.label("Capturing");
                capturing.setBorder(Ui.pad(0, 0, g, 0));   // the switch grows downwards; the word keeps its line
                stateRow.add(capturing);
                ToggleSwitch sw = new ToggleSwitch(running);
                sw.setOnToggle(this::toggleState);
                stateRow.add(sw);
            } else {
                // Active task, or a finished one: show the status word next to a
                // small state icon. A finished task reads in green.
                JLabel st = Ui.label(statusText(finished, crawl));
                // A scan at work carries the scan mark; any other state its own.
                boolean working = !finished && task.state() == ScanTask.State.RUNNING && task != liveCrawl;
                st.setIcon(working ? NewScanWizard.scanMarkIcon(null, 1.2f) : statusIcon(task.state()));
                st.setIconTextGap(5);
                if (finished && task.note().isEmpty()) st.setForeground(FINISHED_GREEN);
                // Sites that failed are said in red beside the rest, while the scan runs and when it is over.
                String[] among = task.sites().summaryParts();
                boolean plain = task.note().isEmpty() && task.waiting().isEmpty() && (finished || task.state() == ScanTask.State.RUNNING);
                if (plain && !among[1].isEmpty()) {
                    String lead = finished ? statusText(true, crawl) : among[0];
                    st.setText("<html>" + escapeHtml(lead) + (lead.isEmpty() ? "" : lead.endsWith(":") ? " " : ", ")
                            + "<font color='#C0392B'>" + escapeHtml(among[1]) + "</font></html>");
                }
                st.setToolTipText(task.note().isEmpty() ? null : task.note());
                // A part of the scan that did not run is said in red, whatever else the card says.
                if (!task.caution().isEmpty()) {
                    String lead = st.getText().startsWith("<html>") ? st.getText().replace("<html>", "").replace("</html>", "")
                            : escapeHtml(st.getText());
                    st.setText("<html>" + lead + (lead.isEmpty() ? "" : ", ") + "<font color='#C0392B'>" + escapeHtml(task.caution()) + "</font></html>");
                    st.setForeground(Theme.TEXT);
                    st.setToolTipText(task.cautionDetail());
                }
                stateRow.add(st);
            }

            // A crawl discovers, it does not detect: its card carries its real
            // figures (locations and requests) rather than issue pills that could
            // only ever read zero. Audits show their issue pills; the live passive
            // card counts every issue found so far, and says so.
            // The passive crawl only fills the site map, so it has neither.
            JComponent tail = task == liveCrawl ? null : crawl ? crawlFigures() : issuesRow();

            JPanel body = new JPanel();
            body.setOpaque(false);
            body.setLayout(new BoxLayout(body, BoxLayout.Y_AXIS));
            head.setAlignmentX(LEFT_ALIGNMENT);
            stateRow.setAlignmentX(LEFT_ALIGNMENT);
            body.add(head);
            if (progress != null) {
                progress.setAlignmentX(LEFT_ALIGNMENT);
                body.add(Box.createVerticalStrut(6));
                body.add(progress);
            }
            body.add(Box.createVerticalStrut(12));
            body.add(stateRow);
            if (tail != null) {
                tail.setAlignmentX(LEFT_ALIGNMENT);
                tail.setMaximumSize(new Dimension(Integer.MAX_VALUE, tail.getPreferredSize().height));
                body.add(Box.createVerticalStrut(Ui.roomy(8)));
                body.add(tail);
            } else if (g > 0) {
                body.add(Box.createVerticalStrut(g));   // a card that ends on its switch has that much more beneath it
            }

            add(body, BorderLayout.CENTER);

            addMouseListener(new java.awt.event.MouseAdapter() {
                @Override public void mousePressed(java.awt.event.MouseEvent e) { selectTask(task); }
            });

            setSelectedLook(task == selected);
        }

        /** The status word shown beside the state icon. */
        private String statusText(boolean finished, boolean crawl) {
            boolean audit = task.type() == ScanTask.Type.AUDIT;
            // A running scan says which half of its work it is on.
            if (!finished) {
                if (task.state() == ScanTask.State.PAUSED && !task.note().isEmpty()) return task.note();
                if (task.state() != ScanTask.State.RUNNING || task == liveCrawl) return task.stateLabel();
                if (!task.waiting().isEmpty()) return task.waiting();
                // A scan of several sites says where it is among them.
                String among = task.sites().summary();
                if (!among.isEmpty()) return among;
                return crawl ? "Crawling" : audit ? "Auditing" : task.stateLabel();
            }
            // A scan that never ran says so, and why, where it would have said it finished.
            if (!task.note().isEmpty()) return task.note();
            if (crawl) return "Crawl finished";
            if (!audit) return "Finished";
            if (task.title().startsWith("Passive scan")) return "Passive scan finished";
            return task.title().startsWith("Crawl and audit") ? "Crawl and audit finished" : "Audit finished";
        }

        /** Flip the task between running and paused, driving live scanning too. */
        private void toggleState() {
            task.setState(task.state() == ScanTask.State.RUNNING
                    ? ScanTask.State.PAUSED : ScanTask.State.RUNNING);
            if (task == liveAudit) {
                boolean on = task.state() == ScanTask.State.RUNNING;
                if (passiveScanner != null) passiveScanner.setEnabled(on);
                task.log(on ? "Capture resumed" : "Capture paused");
            }
            if (task == liveCrawl) {
                opensuite.target.PassiveCrawl.setEnabled(task.state() == ScanTask.State.RUNNING);
            }
            ctx.taskChanged(task);
        }

        /** The right-aligned "Issues:" label followed by one pill per severity. */
        private JComponent issuesRow() {
            JPanel row = new JPanel();
            row.setOpaque(false);
            row.setLayout(new BoxLayout(row, BoxLayout.X_AXIS));
            row.add(Box.createHorizontalGlue());
            JLabel lbl = Ui.label("Issues:");
            lbl.setForeground(GREY_TEXT);
            row.add(lbl);
            int gap = 5 + 2 * Ui.fontGrowth() + Ui.fontGrowth() / 2;   // 10 at the usual 13px
            row.add(Box.createHorizontalStrut(6 + 3 * Ui.fontGrowth()));
            row.add(pill(task.high(),   HIGH_COL));   row.add(Box.createHorizontalStrut(gap));
            row.add(pill(task.medium(), MEDIUM_COL)); row.add(Box.createHorizontalStrut(gap));
            row.add(pill(task.low(),    LOW_COL));    row.add(Box.createHorizontalStrut(gap));
            row.add(pill(task.info(),   INFO_COL));
            return row;
        }

        /** What a crawl found, right-aligned where an audit shows its pills. */
        private JComponent crawlFigures() {
            JPanel row = new JPanel();
            row.setOpaque(false);
            row.setLayout(new BoxLayout(row, BoxLayout.X_AXIS));
            row.add(Box.createHorizontalGlue());
            int loc = Math.max(0, task.discoveredLocations());
            JLabel lbl = Ui.label("Discovered " + loc + (loc == 1 ? " location, " : " locations, ")
                    + task.requests() + (task.requests() == 1 ? " request" : " requests"));
            lbl.setForeground(GREY_TEXT);
            row.add(lbl);
            return row;
        }

        @Override public Dimension getMaximumSize() {
            return new Dimension(Integer.MAX_VALUE, getPreferredSize().height);
        }

        /** The greys of the shadow, from its outer edge inwards. */
        private static final int[] SHADOW = { 0xFE, 0xFC, 0xF9, 0xF7, 0xF7, 0xF4, 0xF0, 0xEB };

        @Override protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth(), h = getHeight();
            // A soft shadow 8px deep, a shade heavier under the card than over it.
            if (!Theme.dark) for (int k = 0; k < 8; k++) {
                int v = SHADOW[k];
                g2.setColor(new Color(v, v, v));
                g2.fillRoundRect(k, k, w - 2 * k, h - 2 * k, 2 * (12 - k), 2 * (12 - k));
            }
            java.awt.geom.RoundRectangle2D card = new java.awt.geom.RoundRectangle2D.Float(8, 8, w - 16, h - 16, 8, 8);
            // The selected card is tinted and carries a bar down its right edge.
            g2.setColor(selectedLook ? (Theme.dark ? Theme.CONTROL_TINT : new Color(0xEB, 0xF1, 0xF6)) : Theme.dark ? Theme.CARD : new Color(0xFB, 0xFB, 0xFB));
            g2.fill(card);
            if (Theme.dark) { g2.setColor(Ui.GRID); g2.draw(card); }
            if (selectedLook) {
                g2.clip(card);
                g2.setColor(Theme.CONTROL);
                g2.fillRect(w - 8 - 6, 8, 6, h - 16);
            }
            g2.dispose();
        }

        /** The task's three-dot overflow menu. */
        private final class MenuButton extends JComponent {
            /** When the menu last closed, so a click that dismissed it toggles shut
             *  instead of immediately reopening a fresh menu. */
            private long menuHiddenAt;

            MenuButton() {
                Dimension d = new Dimension(11, 17);
                setPreferredSize(d); setMinimumSize(d); setMaximumSize(d);
                setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                setToolTipText("Task actions");
                addMouseListener(new java.awt.event.MouseAdapter() {
                    @Override public void mousePressed(java.awt.event.MouseEvent e) {
                        // The click that closes an open popup arrives here right
                        // after the popup hides; ignore it so a second click acts
                        // as "close" rather than reopening the menu.
                        if (System.currentTimeMillis() - menuHiddenAt < 250) return;
                        showMenu();
                    }
                });
            }

            private void showMenu() {
                JPopupMenu m = new JPopupMenu();
                boolean finished = task.state() == ScanTask.State.FINISHED;
                boolean running  = task.state() == ScanTask.State.RUNNING;
                if (!finished) m.add(mi(running ? "Pause task" : "Resume task", this::toggle));
                m.add(mi("View task details", () -> selectTask(task)));
                m.add(mi("Open in new window", () -> openTaskWindow(task)));
                m.addSeparator();
                m.add(mi("Rename task", () -> renameTask(task)));
                if (rerun.containsKey(task)) m.add(mi("Scan again", () -> {
                    Runnable r = rerun.get(task);
                    if (r != null) r.run();
                }));
                m.add(mi("Settings", () -> openTaskSettings(task, TaskCard.this)));
                m.addSeparator();
                m.add(mi("Delete", () -> deleteTask(task)));
                m.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
                    @Override public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent e) {}
                    @Override public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent e) {
                        menuHiddenAt = System.currentTimeMillis();
                    }
                    @Override public void popupMenuCanceled(javax.swing.event.PopupMenuEvent e) {
                        menuHiddenAt = System.currentTimeMillis();
                    }
                });
                m.show(MenuButton.this, 0, getHeight());
            }

            private void toggle() { toggleState(); }

            private JMenuItem mi(String text, Runnable action) {
                JMenuItem it = new JMenuItem(text);
                it.addActionListener(a -> action.run());
                return it;
            }
            @Override protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(Theme.TEXT);
                double cx = getWidth() / 2.0, cy = getHeight() / 2.0;
                for (int i = -1; i <= 1; i++) g2.fill(new java.awt.geom.Ellipse2D.Double(cx - 1.5, cy - 1.5 + i * 5, 3, 3));
                g2.dispose();
            }
        }

        void setSelectedLook(boolean on) {
            this.selectedLook = on;
            repaint();
        }
    }

    /** A round play/pause button, like the control on each scan-task tile. */
    private static final class CircleButton extends JComponent {
        private final boolean running;
        CircleButton(boolean running, Runnable onClick) {
            this.running = running;
            Dimension d = new Dimension(22, 22);
            setPreferredSize(d); setMinimumSize(d); setMaximumSize(d);
            setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            setToolTipText(running ? "Pause" : "Resume");
            addMouseListener(new java.awt.event.MouseAdapter() {
                @Override public void mousePressed(java.awt.event.MouseEvent e) {
                    if (onClick != null) onClick.run();
                }
            });
        }
        @Override protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth(), h = getHeight();
            g2.setColor(Theme.ICON);
            g2.setStroke(new BasicStroke(1.4f));
            g2.drawOval(1, 1, w - 3, h - 3);
            int cx = w / 2, cy = h / 2;
            if (running) {
                // Two pause bars.
                g2.fillRect(cx - 4, cy - 4, 2, 8);
                g2.fillRect(cx + 2, cy - 4, 2, 8);
            } else {
                // A play triangle, nudged right so it reads as centred.
                int[] xs = {cx - 3, cx - 3, cx + 5};
                int[] ys = {cy - 5, cy + 5, cy};
                g2.fillPolygon(xs, ys, 3);
            }
            g2.dispose();
        }
    }

    /** A slim, rounded progress bar for active tasks (no inline text). */
    private static final class ProgressStrip extends JComponent {
        // A shared clock so the slide stays continuous even when the card list is
        // rebuilt (which recreates the strip) during a scan - otherwise the
        // segment would snap back to the start on every rebuild.
        private static final long ANIM_EPOCH = System.nanoTime();
        private static final double ANIM_SPEED = 2.2;   // radians per second

        private final ScanTask task;
        // A continuous task (a running crawl) has no percentage, so its bar shows
        // a segment sliding back and forth instead of a proportional fill. The
        // repaint ticks come from a single dashboard-level timer (see
        // ensureCardAnimation), not a per-strip one, so the slide never stalls
        // when the card list is rebuilt during a scan.
        private final boolean indeterminate;

        ProgressStrip(ScanTask task) {
            this.task = task;
            this.indeterminate = task.progress() < 0 && task.state() == ScanTask.State.RUNNING;
            setPreferredSize(new Dimension(220, 9));
            setMinimumSize(new Dimension(40, 9));
            setMaximumSize(new Dimension(Integer.MAX_VALUE, 9));
        }

        @Override protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth(), h = getHeight();
            g2.setColor(Theme.SURFACE_3);
            g2.fillRoundRect(0, 0, w - 1, h - 1, h, h);
            g2.setColor(Ui.ACCENT);
            if (indeterminate) {
                // A short segment eased smoothly to and fro across the track. The
                // phase comes from the wall clock, so it never resets on rebuild.
                double phase = (System.nanoTime() - ANIM_EPOCH) / 1_000_000_000.0 * ANIM_SPEED;
                int segW = Math.max(h * 3, (int) (w * 0.28));
                double frac = (1 - Math.cos(phase)) / 2;   // 0..1..0, slowing at each end
                int x = (int) Math.round((w - 1 - segW) * frac);
                g2.fillRoundRect(x, 0, segW, h - 1, h, h);
            } else {
                double p = task.progress();
                int fill = p >= 0 ? (int) Math.round(p * (w - 1))
                        : (task.state() == ScanTask.State.RUNNING ? w - 1 : 0);
                if (fill > 0) g2.fillRoundRect(0, 0, Math.max(h, fill), h - 1, h, h);
            }
            g2.dispose();
        }
    }

    /** A small icon marking a task's run state, shown beside the status word. */
    private static Icon statusIcon(ScanTask.State state) {
        return new Icon() {
            @Override public int getIconWidth()  { return 12; }
            @Override public int getIconHeight() { return 12; }
            @Override public void paintIcon(Component c, Graphics g, int x, int y) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.translate(x, y);
                switch (state) {
                    case RUNNING -> {
                        g2.setColor(Ui.ACCENT);
                        g2.fillPolygon(new int[]{2, 2, 11}, new int[]{1, 11, 6}, 3);
                    }
                    case PAUSED -> {
                        g2.setColor(Theme.ICON);
                        g2.fillRect(2, 1, 3, 10);
                        g2.fillRect(7, 1, 3, 10);
                    }
                    case FINISHED -> {
                        g2.setColor(Theme.OK);
                        g2.setStroke(new BasicStroke(2f));
                        g2.drawPolyline(new int[]{1, 5, 11}, new int[]{6, 11, 1}, 3);
                    }
                }
                g2.dispose();
            }
        };
    }

    /** A small on/off pill toggle (blue when on, grey when off). */
    private static final class ToggleSwitch extends JComponent {
        private boolean on;
        private Runnable onToggle;

        ToggleSwitch(boolean on) {
            this.on = on;
            Dimension d = new Dimension(29 + 2 * Ui.fontGrowth(), 17 + Ui.fontGrowth());
            setPreferredSize(d);
            setMinimumSize(d);
            setMaximumSize(d);
            setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            addMouseListener(new java.awt.event.MouseAdapter() {
                @Override public void mousePressed(java.awt.event.MouseEvent e) {
                    ToggleSwitch.this.on = !ToggleSwitch.this.on;
                    repaint();
                    if (onToggle != null) onToggle.run();
                }
            });
        }

        void setOnToggle(Runnable r) { this.onToggle = r; }
        boolean isOn() { return on; }
        void setOn(boolean v) { if (on != v) { on = v; repaint(); } }

        @Override protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth(), h = getHeight();
            g2.setColor(on ? Theme.CONTROL : Theme.TOGGLE_OFF);
            g2.fillRoundRect(0, 0, w, h, h, h);
            int knob = h - 6;
            int x = on ? w - knob - 3 : 3;
            g2.setColor(Color.WHITE);
            g2.fillOval(x, 3, knob, knob);
            g2.dispose();
        }
    }

    /** A capsule-shaped, coloured issue-count pill with white text. */
    private static JComponent pill(int count, Color bg) {
        final String text = Integer.toString(count);
        JComponent c = new JComponent() {
            @Override protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                int w = getWidth(), h = getHeight();
                g2.setColor(bg);
                g2.fillRoundRect(0, 0, w - 1, h - 1, h, h);   // radius = height: a capsule
                g2.setColor(Color.WHITE);
                g2.setFont(Ui.BOLD);
                FontMetrics fm = g2.getFontMetrics();
                int tw = fm.stringWidth(text);
                int tx = (w - tw) / 2;
                int ty = (h + fm.getAscent() - fm.getDescent()) / 2;
                g2.drawString(text, tx, ty);
                g2.dispose();
            }
            @Override public Dimension getPreferredSize() {
                // 32 by 18 painted at the usual 13px, as measured.
                FontMetrics fm = getFontMetrics(Ui.BOLD);
                int w = Math.max(Ui.em(27) + 1, fm.stringWidth(text) + Ui.em(16));
                return new Dimension(w, Ui.fontGrowth() > 0 ? Ui.em(15) + 1 : 20);
            }
            @Override public Dimension getMinimumSize() { return getPreferredSize(); }
            @Override public Dimension getMaximumSize() { return getPreferredSize(); }
        };
        return c;
    }

    // --------------------------------------------------------------- right

    private void refreshRight() {
        ScanTask t = selected;
        if (t == null) {
            rightCards.show(rightBody, "scan");
            applyIssueTables();
            rightHeader.setText("Dashboard");
            cfgType.setText("-");
            cfgScope.setText("-");
            cfgConfig.setText("-");
            for (JLabel l : new JLabel[]{progTotalItems, progItemsActive, progItemsDone,
                    progDiscovered, progRequests, progPerSecond}) {
                l.setText("0");
            }
            eventLog.setText("");
            summaryTaskLog.setText("");
            return;
        }

        rightHeader.setText(t.number + ". " + t.title());
        if (playPauseBtn != null) playPauseBtn.setKind(t.state() == ScanTask.State.RUNNING ? "pause" : "play");
        boolean crawlKind = t.type() == ScanTask.Type.LIVE_ACTIVE;
        // A scan that crawls keeps the Live crawl view when it goes on to audit and when it is done.
        applyTabs(t == liveCrawl ? 0 : crawlKind || crawlScans.contains(t) ? 2 : 1);
        // The left summary card: what the passive crawl added, or the audit's findings.
        boolean addedFace = t == liveCrawl;
        leftCardsLayout.show(leftCards, addedFace ? "added" : "issues");
        if (leftHead != null && leftHead.getClientProperty("heading") instanceof JLabel hl) {
            hl.setText(addedFace ? "Items added to site map" : "Most serious vulnerabilities found (live)");
            hl.setIcon(boxed14(sectionIcon(addedFace ? "folder" : "warning")));
            Component link = ((BorderLayout) ((JPanel) leftHead.getComponent(0)).getLayout()).getLayoutComponent(BorderLayout.EAST);
            if (link instanceof JLabel ll) ll.setText(addedFace ? "View site map" : "View all");
        }
        if (addedFace) addedModel.refresh();

        if (detachedFrame != null && t == detachedTask) {
            rightCards.show(rightBody, "detached");
        }
        // Live crawl view, the activity: what this scan is doing, in plain words, and the requests it sent last.
        if (t.type() != ScanTask.Type.LIVE_PASSIVE || liveTaskSettings.containsKey(t)) {
            List<LogEntry> latest = new ArrayList<>();
            for (int i = scanLogModel.getRowCount() - 1; i >= 0 && latest.size() < CrawlGraph.HISTORY; i--) {
                LogEntry en = scanLogModel.at(i);
                if (en == null || en.request() == null || en.service() == null || !atShownSite(en.service())
                        || (en.time() != null && en.time().getTime() < t.startedAt())) continue;
                latest.add(en);
            }
            String stage = t.state() == ScanTask.State.FINISHED ? (t.note().isEmpty() ? "Finished" : t.note())
                    : t.state() == ScanTask.State.PAUSED ? (t.note().isEmpty() ? "Paused" : t.note())
                    : !t.waiting().isEmpty() ? t.waiting()
                    : !t.sites().summary().isEmpty() ? t.sites().summary()
                    : t.type() == ScanTask.Type.LIVE_ACTIVE ? "Crawling" : t.type() == ScanTask.Type.AUDIT ? "Auditing" : "Running";
            String session = t.session().isEmpty() ? "No login configured" : t.session();
            // Every site's figures, or those of the one site shown.
            opensuite.core.SiteProgress.Site one = siteFilter == null ? null : t.sites().get(siteFilter);
            String found = one == null
                    ? t.discoveredLocations() + (t.discoveredLocations() == 1 ? " location, " : " locations, ")
                            + t.requests() + (t.requests() == 1 ? " request" : " requests")
                    : one.host() + ": " + one.status().label() + ", " + one.locations() + (one.locations() == 1 ? " location" : " locations");
            crawlGraph.setActivity(stage, session, found, latest, t.sessionHeaders());
            crawlGraph.setSites(siteTreeOf(t));
        } else {
            crawlGraph.clear();
        }
        crawlGraph.notLive(t);

        // A scan shows the same row of tabs while it crawls as while it audits,
        // the Live crawl view among them.
        rightCards.show(rightBody, "scan");
        syncSites(t);
        applyIssueTables();
        auditItemsModel.sync(t, allIssues, issuesStamp);

        // A scan started from New scan names its own kind before the configuration,
        // e.g. "Crawl and audit - Balanced", and keeps that kind through both halves.
        int dash = t.configuration() == null ? -1 : t.configuration().indexOf(" - ");
        boolean named = rerun.containsKey(t) && dash > 0;
        cfgType.setText(t == liveCrawl ? "Live passive crawl" : named ? t.configuration().substring(0, dash) : typeLabel(t.type()));
        boolean liveKind = t.type() == ScanTask.Type.LIVE_PASSIVE;
        cfgScope.setText(t.scope().isEmpty() ? (liveKind ? "Proxy (all traffic)" : "-") : t.scope());
        cfgConfig.setText(t.configuration());
        cfgCapturingRow.setVisible(liveKind);
        cfgCapturing.setOn(t.state() == ScanTask.State.RUNNING);
        cfgLink.setVisible(true);

        // Audit items: the active-scan rule count (real), split into completed
        // and in-progress by ZAP's live scan percentage.
        boolean running = t.state() == ScanTask.State.RUNNING;
        int ruleTotal = t.auditItemsTotal();
        double frac = t.progress() < 0 ? 0 : t.progress();   // -1 for continuous tasks
        int completed = (int) Math.round(ruleTotal * frac);
        int active = running ? Math.max(0, ruleTotal - completed) : 0;
        // The live passive audit has no fixed work list, so its audit-item
        // figures do not apply; its requests and locations are what it has seen.
        boolean passive = t.type() == ScanTask.Type.LIVE_PASSIVE;
        // A live audit's items are the distinct locations it has audited so far.
        int liveItems = liveLocations.size();
        progTotalItems.setText(Integer.toString(passive ? liveItems : ruleTotal));
        progItemsActive.setText(Integer.toString(passive ? 0 : active));
        progItemsDone.setText(Integer.toString(passive ? liveItems : completed));
        // An audit that reported its rule starts has real figures: the addresses it is auditing, and how many
        // of them have had every rule run. Those not done are in progress only while the scan is running.
        if (!passive && t.rules().known()) {
            int[] items = t.rules().totals();
            progTotalItems.setText(Integer.toString(items[0]));
            progItemsDone.setText(Integer.toString(items[1]));
            progItemsActive.setText(Integer.toString(running ? items[0] - items[1] : 0));
        }
        progRequests.setText(Integer.toString(t.requests()));
        boolean crawlTask = t == liveCrawl;
        capTotalItems.setText(crawlTask ? "Site map items added:" : "Total audit items:");
        capItemsActive.setText(crawlTask ? "Responses processed:" : "Audit items in progress:");
        capItemsDone.setText(crawlTask ? "Responses queued:" : "Audit items completed:");
        if (requestsRow != null) requestsRow.setVisible(!crawlTask);
        // A scan says how far its audit has got as one rough percentage: a count of checks read as if
        // they were a list of static rules, when each is a set of live requests. The live tasks, which
        // have no end, keep their counts.
        boolean scan = !passive && !crawlTask;
        if (scan) {
            capTotalItems.setText("Audit progress:");
            int pct = (int) Math.max(0, Math.min(100, Math.round(frac * 100)));
            progTotalItems.setText(t.type() == ScanTask.Type.AUDIT ? pct + "%"
                    : t.state() == ScanTask.State.FINISHED ? "No audit" : "Not started");
        }
        for (JComponent c : new JComponent[] {capItemsActive, progItemsActive, capItemsDone, progItemsDone}) c.setVisible(!scan);
        if (crawlTask) {
            progTotalItems.setText(Integer.toString(opensuite.target.PassiveCrawl.itemsAdded()));
            progItemsActive.setText(Integer.toString(opensuite.target.PassiveCrawl.responsesProcessed()));
            progItemsDone.setText("0");
        }

        // Newest first, each line led by a prompt mark, as the reference lists them.
        java.util.List<String> lines = new ArrayList<>(t.logLines());
        java.util.Collections.reverse(lines);
        StringBuilder logText = new StringBuilder();
        for (String line : lines) logText.append("> ").append(line).append('\n');
        summaryTaskLog.setText(logText.toString());
        summaryTaskLog.setCaretPosition(0);

        eventLog.setText(String.join("\n", t.logLines()));
        eventLog.setCaretPosition(eventLog.getDocument().getLength());
        refreshEventTable(t);
    }

    // The shared issue list as last seen, and which task's slice the tables show.
    private List<Issue> allIssues = new ArrayList<>();
    private int issuesStamp;
    private ScanTask tablesFor;
    private int tablesStamp = -1;

    /**
     * Fill the Summary, Issues and Audit log tables for the selected task: a
     * scan task shows only what it found, the live audit shows the shared set.
     * Rebuilt only when the task or the issue list has changed, so the
     * once-a-second progress refresh does not reset the tables' selection.
     */
    private void applyIssueTables() {
        ScanTask t = selected;
        if (t == tablesFor && issuesStamp == tablesStamp) return;
        tablesFor = t;
        tablesStamp = issuesStamp;
        List<Issue> rows = allIssues;
        if (t != null && t.type() != ScanTask.Type.LIVE_PASSIVE) {
            String source = "Scan " + t.number;
            rows = new ArrayList<>();
            for (Issue i : allIssues) if (i.foundBy(source) && atShownSite(i.service())) rows.add(i);
        }
        summaryModel.setIssues(rows);
        issuesModel.setIssues(rows);
        auditLogModel.setIssues(rows);
    }

    private void onIssuesChanged() {
        List<Issue> all = ctx == null ? new ArrayList<>() : ctx.issues();
        all.sort(java.util.Comparator.comparingInt(Issue::rank));
        allIssues = all;
        issuesStamp++;
        // The live audit task reflects the shared issue set.
        if (liveAudit != null) {
            int h = 0, m = 0, l = 0, i = 0;
            for (Issue is : all) switch (is.severity()) {
                case HIGH -> h++; case MEDIUM -> m++; case LOW -> l++; default -> i++;
            }
            liveAudit.setCounts(h, m, l, i);
            if (ctx != null) ctx.taskChanged(liveAudit);
        }
        refreshRight();
    }

    private void onIssueRowSelected(ListSelectionEvent e) {
        if (e.getValueIsAdjusting()) return;
        int viewRow = issuesTable.getSelectedRow();
        if (viewRow < 0 || viewRow >= issuesModel.getRowCount()) return;
        Issue is = issuesModel.issueAt(viewRow);
        if (is == null) return;

        issueDetail.setText(opensuite.ui.Advisory.renderCompact(is));
        issueDetail.setCaretPosition(0);

        // Findings on the same engine message now share one request/response
        // pair, so hand the viewer its own copy: the editors are read-only here,
        // but an action that ever mutated the shown message in place must not
        // reach back into the sibling findings' evidence.
        HttpMessage req = is.request() == null ? null : is.request().copy();
        HttpMessage resp = is.response() == null ? null : is.response().copy();
        if (issueRequest != null) {
            issueRequest.setMessage(is.service(), req);
        }
        if (issueResponse != null) {
            issueResponse.setMessage(is.service(), resp, req == null ? null : req.copy());
        }
        opensuite.ui.IssueMenu.markEvidence(is, issueRequest, issueResponse);
    }


    // ------------------------------------------------------------- actions

    private void newScan() { newScan(null); }

    private void newScan(String url) {
        // The scan wizard: scan type, URLs, configuration, login, resource pool.
        NewScanWizard w = new NewScanWizard(ctx, ctx == null ? null : ctx.frame());
        if (url != null) w.startOn(url);
        w.setVisible(true);
        if (!w.started()) return;
        // A scope drawn up in the wizard is this scan's alone: the project's scope is the user's to set.
        opensuite.core.Scope custom = w.customScope();
        if (w.perSite()) {
            // Asked for: every URL is a scan of its own, with its own tasks and its own scope.
            for (String one : w.targetUrls()) {
                startSpiderFor(java.util.List.of(one), w.crawlAndAudit(), w.config(), w.threads(), w.isolated(), w.apiOnly() ? "API scan" : null,
                        w.login().auth(), custom);
            }
            return;
        }
        // One job for every URL listed: a single crawl task and audit task.
        startSpiderFor(w.targetUrls(), w.crawlAndAudit(), w.config(), w.threads(), w.isolated(), w.apiOnly() ? "API scan" : null,
                w.login().auth(), custom);
    }

    private final java.util.List<opensuite.engine.ZapScanner.Item> pendingActive = new ArrayList<>(), pendingPassive = new ArrayList<>();
    private final javax.swing.Timer pendingItems = new javax.swing.Timer(250, e -> {
        if (!pendingActive.isEmpty()) { auditItems(new ArrayList<>(pendingActive), true); pendingActive.clear(); }
        if (!pendingPassive.isEmpty()) { auditItems(new ArrayList<>(pendingPassive), false); pendingPassive.clear(); }
    });
    { pendingItems.setRepeats(false); }

    /**
     * Audit the chosen requests and nothing else, as one task. Each request is
     * scanned as it stands, with the cookies and headers it was sent with.
     */
    private void auditItems(java.util.List<opensuite.engine.ZapScanner.Item> items, boolean active) {
        opensuite.engine.ZapEngine ze = zapEngine();
        if (ze == null || !ze.available()) {
            JOptionPane.showMessageDialog(ctx.frame(),
                    "The scan engine (OWASP ZAP) is not installed.\n"
                    + "Run ./fetch-zap.sh to add it, then try again.",
                    "Scan engine required", JOptionPane.WARNING_MESSAGE);
            return;
        }
        opensuite.engine.ScanConfig cfg = opensuite.engine.ScanConfig.preset("Balanced");
        String what = active ? "Audit" : "Passive scan";
        String first = items.get(0).service().host();
        String title = what + " of " + (items.size() == 1 ? first + items.get(0).request().path()
                : items.size() + " requests to " + first);
        opensuite.core.ScanTask task = new opensuite.core.ScanTask(
                opensuite.core.ScanTask.Type.AUDIT, title, what + " - " + (active ? cfg.name() : "selected items"));
        task.setScope(items.size() == 1 ? items.get(0).service().url() + items.get(0).request().requestTarget()
                : items.size() + " requests");
        ctx.addTask(task);
        taskConfigs.put(task, cfg);
        task.log("Starting scan engine (first run can take ~30s)...");
        ctx.taskChanged(task);
        Thread t = new Thread(() -> {
            try {
                ze.start();
                new opensuite.engine.ZapScanner(ctx, ze).auditRequests(items, active, cfg, task);
            } catch (Exception ex) {
                task.log("Scan engine error: " + ex.getMessage());
                task.setState(opensuite.core.ScanTask.State.FINISHED);
                ctx.taskChanged(task);
            }
        }, "zap-audit-items");
        t.setDaemon(true);
        t.start();
    }

    private void startSpiderFor(String url, boolean thenAudit) {
        startSpiderFor(url, thenAudit, opensuite.engine.ScanConfig.crawlDefault(), 10);
    }

    private void startSpiderFor(String url, boolean thenAudit, opensuite.engine.ScanConfig cfg, int threads) {
        startSpiderFor(java.util.List.of(url), thenAudit, cfg, threads);
    }

    /**
     * Crawl every URL with the ZAP engine as one job, and when {@code thenAudit}
     * is set, audit what the crawl discovered. All the URLs share one crawl task
     * and one audit task, scanned one after another, so the thread setting is
     * applied once to the engine rather than multiplied per target. The engine is
     * required: detection is ZAP's job, so there is no home-grown fall-back
     * scanner. If the engine is not installed, scanning is unavailable until it
     * is fetched.
     */
    private void startSpiderFor(java.util.List<String> urls, boolean thenAudit,
                                opensuite.engine.ScanConfig cfg, int threads) {
        startSpiderFor(urls, thenAudit, cfg, threads, false, null, null, null);
    }

    private void startSpiderFor(java.util.List<String> urls, boolean thenAudit,
                                opensuite.engine.ScanConfig cfg, int threads, boolean isolated, String kind,
                                opensuite.engine.ScanAuth auth, opensuite.core.Scope custom) {
        // A scan that crawls with the browser does not start without it.
        if (cfg != null && cfg.ajaxSpider() && !opensuite.proxy.BrowserSetup.readyOrFetch(ctx.frame(), ctx,
                () -> startSpiderFor(urls, thenAudit, cfg, threads, isolated, kind, auth, custom))) return;
        opensuite.engine.ZapEngine ze = zapEngine();
        if (ze == null || !ze.available()) {
            JOptionPane.showMessageDialog(ctx.frame(),
                    "The scan engine (OWASP ZAP) is not installed.\n"
                    + "Run ./fetch-zap.sh to add it, then try again.",
                    "Scan engine required", JOptionPane.WARNING_MESSAGE);
            return;
        }
        // Parse every URL and collect the seeds. Each site (not the whole host: its other ports stay out) goes
        // into the scan's own scope. The project's scope is not touched: that is the user's to set.
        final opensuite.core.Scope own = new opensuite.core.Scope();
        java.util.List<opensuite.engine.ZapScanner.Seed> seeds = new ArrayList<>();
        // An address given twice is scanned once.
        java.util.List<String> once = opensuite.core.SiteProgress.withoutRepeats(urls);
        int listed = 0;
        for (String u : urls) if (u != null && !u.isBlank()) listed++;
        final int repeats = listed - once.size();
        for (String raw : once) {
            String url = raw.trim();
            if (url.isEmpty()) continue;
            HttpService svc = HttpService.parse(url);
            if (svc == null) {
                JOptionPane.showMessageDialog(ctx.frame(),
                        "Could not parse this URL, skipping it:\n" + url
                        + "\n\nUse the form https://host/path.",
                        "Scan", JOptionPane.WARNING_MESSAGE);
                continue;
            }
            String pathq = "/";
            try {
                java.net.URI u = java.net.URI.create(url);
                if (u.getRawPath() != null && !u.getRawPath().isEmpty()) pathq = u.getRawPath();
            } catch (Exception ignored) {}
            String seedUrl = svc.url() + (pathq.startsWith("/") ? pathq : "/" + pathq);
            own.includeSite(svc);
            seeds.add(new opensuite.engine.ZapScanner.Seed(svc, seedUrl));
        }
        if (seeds.isEmpty()) return;
        // What the wizard's detailed scope adds to the sites or takes away from them.
        if (custom != null) {
            for (opensuite.core.Scope.Rule r : custom.include()) own.include().add(r);
            for (opensuite.core.Scope.Rule r : custom.exclude()) own.exclude().add(r);
        }

        // The card reads like the reference: what the job is, of what, and the
        // configuration it runs with, e.g. "Crawl and audit of host" over
        // "Crawl and audit - Lightweight".
        // The port is part of the name when it is not the usual one: two sites on one host are two things.
        opensuite.core.HttpService firstSvc = seeds.get(0).service();
        String first = firstSvc.host() + (firstSvc.defaultPort() ? "" : ":" + firstSvc.port());
        String what = kind != null ? kind : (thenAudit ? "Crawl and audit" : "Crawl");
        java.util.Set<String> distinct = new java.util.LinkedHashSet<>();
        for (opensuite.engine.ZapScanner.Seed sd : seeds) distinct.add(sd.service().url());
        String title = distinct.size() == 1 ? what + " of " + first : what + " of " + distinct.size() + " sites";
        opensuite.core.ScanTask task = new opensuite.core.ScanTask(
                opensuite.core.ScanTask.Type.LIVE_ACTIVE, title, what + " - " + cfg.name());
        task.setScope(distinct.size() == 1 ? seeds.get(0).service().url() : distinct.size() + " sites");
        ctx.addTask(task);
        taskConfigs.put(task, cfg);
        for (opensuite.engine.ZapScanner.Seed sd : seeds) task.sites().add(sd.service().url(), sd.url());
        if (repeats > 0) task.log("Removed " + repeats + " duplicate URL" + (repeats == 1 ? "" : "s") + ": each address is scanned once");
        if (isolated) task.log("Isolated scan: results are kept with this task and not merged into the site map or issue log.");
        // Remember how to run this exact scan again, for the task's "Scan again".
        final java.util.List<String> againUrls = new ArrayList<>(urls);
        final boolean againAudit = thenAudit;
        final opensuite.engine.ScanConfig againCfg = cfg;
        final int againThreads = threads;
        final boolean againIsolated = isolated; final String againKind = kind;
        // Scanning again starts from the login as it was set up, not as the first run left it.
        final opensuite.engine.ScanAuth againAuth = auth == null ? null : auth.copy();
        // The login a single-page application keeps in browser storage goes to the crawl's browser.
        if (auth != null) for (java.util.Map.Entry<String, java.util.Map<String, String>> held : auth.storage.entrySet())
            opensuite.engine.CrawlWatch.seedStorage(held.getKey(), held.getValue());
        crawlScans.add(task);
        rerun.put(task, () -> startSpiderFor(againUrls, againAudit, againCfg, againThreads, againIsolated, againKind,
                againAuth == null ? null : againAuth.copy(), custom));
        task.log("Starting scan engine (first run can take ~30s)...");
        ctx.taskChanged(task);
        final java.util.List<opensuite.engine.ZapScanner.Seed> fseeds = seeds;
        Thread zth = new Thread(() -> {
            opensuite.engine.SessionGuard guard = null;
            try {
                ze.start();
                // Threads are set once here, not per target.
                try { ze.api().setSpiderThreads(threads); ze.api().setActiveThreadPerHost(threads); }
                catch (Exception ignored) {}
                task.log("Engine ready. Crawling " + fseeds.size() + (fseeds.size() == 1 ? " site" : " sites"));
                ctx.taskChanged(task);
                // The scan's login: its headers go on the scanner's requests for as long as it runs.
                guard = new opensuite.engine.SessionGuard(ctx, ze.api(), auth, fseeds, task);
                try {
                    guard.begin();
                } catch (Exception ex) {
                    task.log("The scan was not started: " + ex.getMessage());
                    task.setNote("Not started: " + ex.getMessage());
                    task.setState(opensuite.core.ScanTask.State.FINISHED);
                    ctx.taskChanged(task);
                    ctx.alert("scanner", "Scan " + task.number + " was not started: " + ex.getMessage());
                    return;
                }
                opensuite.engine.ZapScanner zs = new opensuite.engine.ZapScanner(ctx, ze);
                guard.logLeftAlone();
                guard.applyFormTokens();
                guard.applyLogoutAvoidance();
                zs.setSkipRules(guard.skipRules());
                zs.setLoopCheck(guard.loopCheck());
                zs.setCrawlThreads(threads);
                zs.setScanScope(own);
                zs.crawlAndAudit(fseeds, thenAudit, cfg, task);
            } catch (Exception ex) {
                task.log("Scan engine error: " + ex.getMessage());
                opensuite.core.Debug.error("scan " + task.number + " stopped on an engine error", ex);
                task.setState(opensuite.core.ScanTask.State.FINISHED);
                ctx.taskChanged(task);
            } finally {
                if (guard != null) guard.end();
            }
        }, "zap-scan");
        zth.setDaemon(true);
        zth.start();
    }

    // --------------------------------------------------------- the sites of a scan

    /** Whether something at this service belongs to what the tabs show: every site, or the one chosen. */
    static final int TREE_PATHS = 200, TREE_ROWS = 20000;

    /** Each site of a scan, with how it stands, over the paths the crawl has found at it. */
    private java.util.Map<String, List<String>> siteTreeOf(ScanTask t) {
        java.util.Map<String, java.util.Set<String>> paths = new java.util.LinkedHashMap<>();
        for (opensuite.core.SiteProgress.Site st : t.sites().all()) paths.put(st.site().toLowerCase(java.util.Locale.ROOT), new java.util.TreeSet<>());
        int looked = 0;
        for (int i = scanLogModel.getRowCount() - 1; i >= 0 && looked < TREE_ROWS; i--, looked++) {
            LogEntry en = scanLogModel.at(i);
            if (en == null || en.service() == null || !"crawl".equals(en.tool())
                    || (en.time() != null && en.time().getTime() < t.startedAt())) continue;
            java.util.Set<String> at = paths.get(en.service().url().toLowerCase(java.util.Locale.ROOT));
            if (at == null || at.size() >= TREE_PATHS) continue;
            String p = en.pathAndQuery();
            int q = p == null ? -1 : p.indexOf('?');
            if (p != null) at.add(q < 0 ? p : p.substring(0, q));
        }
        java.util.Map<String, List<String>> out = new java.util.LinkedHashMap<>();
        for (opensuite.core.SiteProgress.Site st : t.sites().all()) {
            java.util.Set<String> at = paths.get(st.site().toLowerCase(java.util.Locale.ROOT));
            out.put(st.host() + "  (" + st.status().label() + ", " + at.size() + (at.size() == 1 ? " path)" : " paths)"), new ArrayList<>(at));
        }
        return out;
    }

    private boolean atShownSite(HttpService svc) {
        return siteFilter == null || (svc != null && svc.url().equalsIgnoreCase(siteFilter));
    }

    /** Narrow every tab of the selected task to one of its sites, or back to all of them with null. */
    private void showSite(String site) {
        if (java.util.Objects.equals(site, siteFilter)) return;
        siteFilter = site;
        siteBoxFilling = true;
        try {
            String host = null;
            if (site != null && selected != null) {
                opensuite.core.SiteProgress.Site st = selected.sites().get(site);
                if (st != null) host = st.host();
            }
            siteBox.setSelectedItem(host == null ? ALL_SITES : host);
        } finally { siteBoxFilling = false; }
        tablesStamp = -1;          // the issue tables are filled again
        filterTaskTables();
        refreshRight();
    }

    /** The Audit items and Logger tables: what was searched for, at the site shown. */
    private void filterTaskTables() {
        final String site = siteFilter;
        if (auditItemsSorter != null) {
            java.util.List<RowFilter<Object, Object>> both = new ArrayList<>();
            if (!auditItemsSearch.isEmpty()) both.add(RowFilter.regexFilter("(?i)" + java.util.regex.Pattern.quote(auditItemsSearch)));
            if (site != null) both.add(new RowFilter<Object, Object>() {
                @Override public boolean include(Entry<?, ?> en) {
                    AuditItem it = auditItemsModel.at((Integer) en.getIdentifier());
                    return it != null && opensuite.core.RuleProgress.site(it.url).equalsIgnoreCase(opensuite.core.RuleProgress.site(site));
                }
            });
            auditItemsSorter.setRowFilter(both.isEmpty() ? null : RowFilter.andFilter(both));
        }
        if (taskLogSorter != null) {
            taskLogSorter.setRowFilter(site == null ? null : new RowFilter<ScanLogModel, Integer>() {
                @Override public boolean include(Entry<? extends ScanLogModel, ? extends Integer> en) {
                    LogEntry le = scanLogModel.at(en.getIdentifier());
                    return le != null && le.service() != null && le.service().url().equalsIgnoreCase(site);
                }
            });
        }
    }

    /** Bring the list of sites, and the box that narrows the tabs to one, in line with the selected task. */
    private void syncSites(ScanTask t) {
        opensuite.core.SiteProgress sp = t == null ? null : t.sites();
        boolean several = sp != null && sp.several();
        if (t != siteBoxFor || (sp != null && sp.size() != siteBoxCount)) {
            boolean other = t != siteBoxFor;
            siteBoxFor = t;
            siteBoxCount = sp == null ? -1 : sp.size();
            siteBoxFilling = true;
            try {
                siteBox.removeAllItems();
                siteBox.addItem(ALL_SITES);
                if (several) for (opensuite.core.SiteProgress.Site st : sp.all()) siteBox.addItem(st.host());
            } finally { siteBoxFilling = false; }
            // Another task starts with every site showing.
            if (other && siteFilter != null) { siteFilter = null; tablesStamp = -1; filterTaskTables(); }
        }
        siteBox.setVisible(several);
        if (sitesCard == null) return;
        sitesModel.sync(several ? t : null);
        if (sitesCard.isVisible() != several) { sitesCard.setVisible(several); sitesCard.revalidate(); }
        if (several) {
            // As tall as its rows up to eight, then it scrolls.
            int rowsShown = Math.min(8, sitesModel.getRowCount());
            int h = sitesTable.getTableHeader().getPreferredSize().height + rowsShown * sitesTable.getRowHeight() + 4;
            if (sitesScroll.getPreferredSize().height != h) {
                sitesScroll.setPreferredSize(new Dimension(10, h));
                sitesCard.revalidate();
            }
        }
    }

    /** The sites of a scan of several, one to a row: where each has got to and what it has produced. */
    private final class SitesModel extends AbstractTableModel {
        private final String[] cols = {"Site", "Status", "Locations", "Requests", "Issues"};
        private List<opensuite.core.SiteProgress.Site> rows = List.of();
        private java.util.Map<String, Integer> requests = java.util.Map.of(), issues = java.util.Map.of();

        opensuite.core.SiteProgress.Site at(int r) { return r >= 0 && r < rows.size() ? rows.get(r) : null; }

        void sync(ScanTask t) {
            List<opensuite.core.SiteProgress.Site> now = t == null ? List.of() : t.sites().all();
            java.util.Map<String, Integer> req = new java.util.HashMap<>(), iss = new java.util.HashMap<>();
            if (t != null) {
                // Requests are the scan's own to that site since it started; issues are those this scan found there.
                for (int i = 0; i < scanLogModel.getRowCount(); i++) {
                    LogEntry e = scanLogModel.at(i);
                    if (e == null || e.service() == null || !isScanEntry(e)
                            || (e.time() != null && e.time().getTime() < t.startedAt())) continue;
                    req.merge(e.service().url().toLowerCase(java.util.Locale.ROOT), 1, Integer::sum);
                }
                String source = "Scan " + t.number;
                for (Issue is : allIssues) {
                    if (is.service() == null || !is.foundBy(source)) continue;
                    iss.merge(is.service().url().toLowerCase(java.util.Locale.ROOT), 1, Integer::sum);
                }
            }
            boolean sameRows = now.size() == rows.size();
            if (sameRows) for (int i = 0; i < now.size(); i++) if (now.get(i) != rows.get(i)) { sameRows = false; break; }
            rows = now;
            requests = req;
            issues = iss;
            if (!sameRows) fireTableDataChanged();
            else if (!rows.isEmpty()) fireTableRowsUpdated(0, rows.size() - 1);
        }

        @Override public int getRowCount() { return rows.size(); }
        @Override public int getColumnCount() { return cols.length; }
        @Override public String getColumnName(int c) { return cols[c]; }
        @Override public Class<?> getColumnClass(int c) { return c >= 2 ? Integer.class : String.class; }
        @Override public Object getValueAt(int r, int c) {
            opensuite.core.SiteProgress.Site st = rows.get(r);
            String key = st.site().toLowerCase(java.util.Locale.ROOT);
            return switch (c) {
                case 0 -> st.host();
                case 1 -> st.skipAsked() && !st.status().over() ? "Skipping" : st.status().label();
                case 2 -> st.locations();
                case 3 -> requests.getOrDefault(key, 0);
                default -> issues.getOrDefault(key, 0);
            };
        }
    }

    // --------------------------------------------------------- table model

    /** Backs both the summary and issues tables from a shared issue list. */
    private static final class IssueTableModel extends AbstractTableModel {
        private final String[] columns;
        private final boolean full;   // the Issues tab: the full column set
        private List<Issue> rows = new ArrayList<>();
        private final java.text.DateFormat fmt = java.text.DateFormat.getTimeInstance(java.text.DateFormat.MEDIUM);
        private final java.text.DateFormat dateFmt = new java.text.SimpleDateFormat("HH:mm:ss dd MMM yyyy");

        IssueTableModel(String[] columns) {
            this.columns = columns;
            this.full = columns.length >= 9;
        }

        void setIssues(List<Issue> issues) {
            this.rows = issues;
            fireTableDataChanged();
        }

        Issue issueAt(int row) {
            return row >= 0 && row < rows.size() ? rows.get(row) : null;
        }

        @Override public int getRowCount() { return rows.size(); }
        @Override public int getColumnCount() { return columns.length; }
        @Override public String getColumnName(int c) { return columns[c]; }

        // Only the Comment column of the full Issues table is editable.
        @Override public boolean isCellEditable(int r, int c) { return full && c == 8; }
        @Override public void setValueAt(Object v, int r, int c) {
            if (full && c == 8) rows.get(r).setComment(v == null ? "" : v.toString());
        }

        @Override public Object getValueAt(int r, int c) {
            Issue i = rows.get(r);
            if (full) {
                return switch (c) {
                    case 0 -> fmt.format(new java.util.Date(i.time()));
                    case 1 -> i.source();
                    case 2 -> i.title();
                    case 3 -> i.host();
                    case 4 -> i.path();
                    case 5 -> i.param() == null ? "" : i.param();
                    case 6 -> i.severityLabel();
                    case 7 -> i.confidence().label();
                    default -> i.comment();
                };
            }
            return switch (c) {
                case 0 -> i.title();
                case 1 -> i.host();
                case 2 -> dateFmt.format(new java.util.Date(i.time()));
                default -> "";
            };
        }

        Issue.Severity severityAt(int row) {
            return row >= 0 && row < rows.size() ? rows.get(row).severity() : null;
        }

        Issue.Confidence confidenceAt(int row) {
            return row >= 0 && row < rows.size() ? rows.get(row).confidence() : null;
        }
    }

    /** The Audit log: every finding in the order it was detected. */
    private static final class AuditLogModel extends AbstractTableModel {
        private final String[] cols = {"#", "Time", "Source", "Action", "Issue type",
                "Host", "Path", "Insertion point", "Severity", "Confidence"};
        private List<Issue> rows = new ArrayList<>();
        private final java.text.DateFormat fmt = new java.text.SimpleDateFormat("HH:mm:ss dd MMM yyyy");
        @Override public Class<?> getColumnClass(int c) { return c == 0 ? Integer.class : String.class; }

        void setIssues(List<Issue> issues) {
            List<Issue> copy = new ArrayList<>(issues);
            copy.sort(java.util.Comparator.comparingLong(Issue::time));
            rows = copy;
            fireTableDataChanged();
        }

        Issue issueAt(int row) {
            return row >= 0 && row < rows.size() ? rows.get(row) : null;
        }

        @Override public int getRowCount() { return rows.size(); }
        @Override public int getColumnCount() { return cols.length; }
        @Override public String getColumnName(int c) { return cols[c]; }
        @Override public Object getValueAt(int r, int c) {
            Issue i = rows.get(r);
            return switch (c) {
                case 0 -> r + 1;
                case 1 -> fmt.format(new java.util.Date(i.time()));
                case 2 -> i.source();
                case 3 -> "Issue present";
                case 4 -> i.title();
                case 5 -> i.host();
                case 6 -> i.path();
                case 7 -> i.param() == null ? "" : i.param();
                case 8 -> i.severityLabel();
                default -> i.confidence().label();
            };
        }
    }

    /** Live model for the crawl window's Logger: the engine's HTTP traffic. */
    private static final class ScanLogModel extends AbstractTableModel {
        /** Upper bound on live-log rows held in memory. A long scan can stream a
         *  huge amount of traffic; keeping only the most recent rows bounds the
         *  table's memory while still showing the live tail. */
        private static final int MAX_ROWS = 50_000;

        private final String[] cols = {"#", "Time", "Tool", "Method", "Host",
                "Path", "Query", "Status", "Length"};
        private final List<LogEntry> rows = new ArrayList<>();
        private final java.text.DateFormat fmt =
                java.text.DateFormat.getTimeInstance(java.text.DateFormat.MEDIUM);

        void add(LogEntry e) {
            rows.add(e);
            fireTableRowsInserted(rows.size() - 1, rows.size() - 1);
            trim();
        }
        void addAll(List<LogEntry> es) {
            if (es.isEmpty()) return;
            int from = rows.size();
            rows.addAll(es);
            fireTableRowsInserted(from, rows.size() - 1);
            trim();
        }
        /** Drop the oldest rows once the cap is exceeded, so the log cannot grow
         *  without bound during a very long scan. */
        private void trim() {
            if (rows.size() <= MAX_ROWS) return;
            rows.subList(0, rows.size() - MAX_ROWS).clear();
            fireTableDataChanged();
        }
        /** Repaint existing rows in one event, for a batch of in-place updates. */
        void refreshRows() {
            if (!rows.isEmpty()) fireTableRowsUpdated(0, rows.size() - 1);
        }
        void updated(LogEntry e) {
            int i = rows.indexOf(e);
            if (i >= 0) fireTableRowsUpdated(i, i);
        }
        LogEntry at(int r) { return (r >= 0 && r < rows.size()) ? rows.get(r) : null; }

        @Override public int getRowCount() { return rows.size(); }
        @Override public int getColumnCount() { return cols.length; }
        @Override public String getColumnName(int c) { return cols[c]; }
        @Override public Class<?> getColumnClass(int c) { return c == 0 ? Integer.class : String.class; }
        @Override public Object getValueAt(int r, int c) {
            LogEntry e = rows.get(r);
            return switch (c) {
                case 0 -> e.number();
                case 1 -> fmt.format(e.time());
                case 2 -> e.tool();
                case 3 -> e.request() == null ? "" : e.request().method();
                case 4 -> e.service() == null ? "" : e.service().host();
                case 5 -> e.request() == null ? "" : e.request().path();
                case 6 -> e.request() == null ? "" : e.request().query();
                case 7 -> e.status() == 0 ? "" : String.valueOf(e.status());
                default -> e.responseLen() == 0 ? "" : String.valueOf(e.responseLen());
            };
        }
    }

    /** Set every paused task running again, with the passive work behind the live tasks. */
    private void resumeAllTasks() {
        if (ctx == null) return;
        for (ScanTask t : ctx.tasks()) if (t.state() == ScanTask.State.PAUSED) {
            t.setState(ScanTask.State.RUNNING);
            if (t == liveAudit && passiveScanner != null) passiveScanner.setEnabled(true);
            if (t == liveCrawl) opensuite.target.PassiveCrawl.setEnabled(true);
            ctx.taskChanged(t);
        }
    }

    /** Pause every running task: scans, and the live tasks with the passive work behind them. */
    private void pauseAllTasks() {
        if (ctx == null) return;
        for (ScanTask t : ctx.tasks()) if (t.state() == ScanTask.State.RUNNING) {
            t.setState(ScanTask.State.PAUSED);
            if (t == liveAudit && passiveScanner != null) passiveScanner.setEnabled(false);
            if (t == liveCrawl) opensuite.target.PassiveCrawl.setEnabled(false);
            ctx.taskChanged(t);
        }
    }
}