Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.
Python ai-agentsaiopsdashboarddockerfastapihomelabincident-managementllmmonitoringopenaireactroot-cause-analysisself-hosteduptime-monitoring
feat(agent): diagnosis in notifications, reuse, watching the fix, access settings
karloks200574a50643844c
diff --git a/README.md b/README.mdindex 9cc6dab..5db0ed4 100644--- a/README.md+++ b/README.md@@ -7,9 +7,9 @@ One machine runs the dashboard; every other machine runs a small collector thatreports host and Docker container metrics back to it. It works the same whetherthe machines share a LAN or are spread across sites and VPSes.-It also includes an optional, monitoring-only incident agent (OpenAI API, set `OPENAI_API_KEY`)-that can run a fixed set of read-only health checks and never executes commands.-It's main purpose is to report errors, diagnose errors and propose optimal fixes.+It also includes an optional incident agent (OpenAI API, set `OPENAI_API_KEY`): it diagnoses each+incident from the data Infradeck already has, proposes fixes, watches whether the fix holds and adds its+diagnosis to your notifications. It reads; it never runs commands on your servers.Security comes first: the collectors never get the Docker socket, remote machinesreport over a VPN to a listener the public internet can't reach, and nothing@@ -66,7 +66,10 @@ for what every component can touch and the limits of each protection.- **Account security**: optional two-factor sign-in (authenticator app and single-userecovery codes), **required for admins by default**; change your password, reviewand end your sessions, and reset a locked-out account from the host.-- **Homie chat assistant** (optional) restricted to predefined read-only checks.+- **Incident agent** (optional): diagnoses every warning and critical incident from masked evidence, with each+ claim tied to the data; reuses a diagnosis when the same problem returns within a day; resolves the incident once+ its fix holds; adds the diagnosis to notifications; chat about any incident. Monthly budget, per-model prices and+ who-sees-what in Admin. See [Incident agent](docs/assistant.md).<ui - Three phone screenshots side by side (about 390 px wide): the dashboard top with the bottom tab bar, a server card with the Containers list open, and Admin → Alerts thresholds>@@ -171,7 +174,7 @@ Full documentation is in the [`docs/`](docs/README.md) folder:| [Accounts and two-factor sign-in](docs/accounts.md) | Roles, passwords, authenticator codes, recovery and reset. || [The containers](docs/containers.md) | What each container (backend, PostgreSQL, Redis, collector, Docker proxy, helpers) does and why it is there. || [Deploying](docs/deployment.md), [Adding servers](docs/adding-servers.md), [Configuration](docs/configuration.md), [Troubleshooting](docs/troubleshooting.md) | Installing, running and fixing it. |-| [Development](docs/development.md), [Database schema](docs/database.md), [API overview](docs/api.md), [Homie assistant](docs/assistant.md) | For contributors. |+| [Development](docs/development.md), [Database schema](docs/database.md), [API overview](docs/api.md), [Incident agent](docs/assistant.md) | For contributors. |## Securitydiff --git a/SECURITY.md b/SECURITY.mdindex 61437fd..09dbcd7 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -80,6 +80,13 @@ marked recommended (`src/agent/safety.py`). Nothing the model writes is run. Turautomatically" in Admin › Incident agent to send nothing unless someone asks; without a key nothing is sentand incidents keep the rule-based diagnosis, which is worked out locally.+**Who sees the agent.** With "Show diagnoses to users" off, the backend leaves the agent's report out of every+incident, Overview line and notification for users who aren't admins. Chat access is "Admins only" by default; with+"Per user", only users an admin switched on in Admin › Users may chat, and the backend answers 403 to everyone+else. **The agent resolving incidents**: it only resolves an incident when the condition from its own diagnosis+holds in fresh data (a sample from the last 5 minutes), and the rule stays quiet only for its event window, ending+at once if the problem comes back. A wrong condition can close an incident early, but not hide a new one for long.+## The optional system helperReading the kernel log (`dmesg`) needs a privilege, and crash-vs-clean-shutdown detection needsdiff --git a/TESTS.md b/TESTS.mdindex 61930b6..9c53b69 100644--- a/TESTS.md+++ b/TESTS.md@@ -148,6 +148,8 @@ The chart helper tests for the frontend are separate, in `src/frontend/tests/`.| [`test_admin.py`](#test_adminpy) | 18 | Who may do what: admin-only actions, roles, retention cleanup, the chat on/off switch. || [`test_agent_errors.py`](#test_agent_errorspy) | 5 | Helpful, non-leaking error messages from the AI assistant. || [`test_agent_service.py`](#test_agent_servicepy) | 9 | The assistant can only run the fixed read-only checks; the OpenAI provider and conversation history. |+| [`test_agent_diagnosis.py`](#test_agent_diagnosispy) | 42 | The agent's diagnosis: the evidence pack, secret masking, dangerous commands, checking the model's answer, saving reports. |+| [`test_agent_watch.py`](#test_agent_watchpy) | 10 | Reusing a recent diagnosis, and watching the fix until the agent resolves the incident. || [`test_agent_worker.py`](#test_agent_workerpy) | 12 | The agent's job queue and worker: one job per opened or worsened incident after the commit, retries, time limit, restarts. || [`test_alerts.py`](#test_alertspy) | 10 | The incident engine: one incident per problem, resolve, container rules. || [`test_auth_backend.py`](#test_auth_backendpy) | 50 | Accounts, passwords, the first-account setup token, and the cross-site request check. |@@ -318,6 +320,45 @@ shouldn't, or an admin might be locked out.| `test_only_recent_turns_go_back_to_the_model` | Long conversations send only the most recent turns. || `test_a_failed_turn_is_not_kept_in_the_conversation` | A message that failed (timeout, provider error) is not remembered as part of the conversation. |+### test_agent_diagnosis.py++| Test | What it checks |+|---|---|+| `test_secrets_are_masked` | Passwords, tokens, keys, credentials in URLs, JWTs and private keys are replaced with `[masked]` (8 cases). |+| `test_ordinary_text_is_left_alone` | Ordinary event text, even with words like "token", is not masked. |+| `test_destructive_commands_are_flagged` | `rm -rf`, volume pruning, `DROP DATABASE`, `mkfs`, `chmod 777`, `curl \| sh`, `ufw disable` and more are flagged (9 cases). |+| `test_reading_and_ordinary_commands_are_not` | Reading commands and ordinary fixes are not flagged (7 cases). |+| `test_the_pack_has_an_id_on_every_fact_and_stays_small` | Every fact in the evidence pack has an ID, series stay within 40 points, similar incidents carry their resolution. |+| `test_the_pack_is_masked_and_the_same_every_time` | A secret in an event never reaches the pack, and the same data gives the same pack. |+| `test_signals_keep_only_the_evidence_that_exists` | References to facts that aren't in the pack are removed from a signal. |+| `test_a_signal_with_no_real_evidence_is_dropped_and_confidence_follows` | A signal citing nothing real is dropped and counted, and confidence falls to low. |+| `test_a_dangerous_step_is_flagged_and_never_recommended` | A destructive fix gets a warning and loses "recommended"; the first safe step may keep it. |+| `test_only_one_step_is_recommended` | At most one fix step is recommended. |+| `test_a_verify_condition_on_an_unknown_metric_becomes_manual` | A condition on a metric that isn't in the pack is not watched. |+| `test_an_unusable_answer_is_rejected` | Answers that aren't JSON, aren't an object or have no summary are rejected (3 cases). |+| `test_a_diagnosis_is_saved_as_a_new_version_and_counted` | Each diagnosis is a new version, each model call counts as `diagnosis`, the evidence is sent as untrusted and masked. |+| `test_an_unusable_answer_is_asked_for_once_more` | An unusable answer is asked for once more, saying why. |+| `test_two_unusable_answers_give_a_failed_report` | After two unusable answers the report is saved as failed, with the reason and the evidence. |+| `test_a_provider_error_is_counted_and_raised_so_the_job_is_retried` | A provider error is recorded and raised so the queue retries the job; no report is saved. |+| `test_the_worker_diagnoses_and_reports_back` | The worker's job ends as "diagnosed" with the confidence and version. |+| `test_without_a_key_the_worker_leaves_the_rule_based_diagnosis` | Without an API key the job is skipped and says why. |+| `test_with_automatic_diagnosis_off_only_a_request_is_diagnosed` | With automatic diagnosis off, only a requested diagnosis runs. |++### test_agent_watch.py++| Test | What it checks |+|---|---|+| `test_the_same_problem_within_a_day_reuses_the_diagnosis` | A new incident of the same rule on the same server gets the diagnosis from the last 24 hours, with no tokens spent. |+| `test_an_older_or_different_diagnosis_is_not_reused` | A diagnosis older than a day, or of another container, is not reused. |+| `test_the_worker_reuses_before_asking_the_model` | The worker reuses before it would call the model. |+| `test_getting_worse_or_asking_again_is_never_reused` | Getting worse and "Diagnose again" always ask the model. |+| `test_a_container_that_ran_long_enough_without_restarting_resolves_the_incident` | A container running past the condition without a restart resolves the incident, with the condition as its resolution, and starts the hold. |+| `test_a_recent_restart_keeps_it_open_and_shows_progress` | A recent restart keeps the incident open and reports how long the condition has held. |+| `test_old_data_is_not_proof` | Samples older than 5 minutes never resolve an incident. |+| `test_a_metric_under_its_threshold_long_enough_holds` | A metric under its threshold for long enough holds, described by the metric's name. |+| `test_the_rule_does_not_reopen_what_the_agent_closed_until_the_hold_ends_or_it_breaks` | The rule stays quiet after the agent resolved its incident, until the problem comes back. |+| `test_manual_conditions_are_not_watched` | Conditions that need a person are never acted on. |+### test_agent_worker.py| Test | What it checks |diff --git a/docs/README.md b/docs/README.mdindex 1aca812..93bafc3 100644--- a/docs/README.md+++ b/docs/README.md@@ -11,7 +11,7 @@ The [README](../README.md) is the short version: what the project is, how to sta| [Metrics: what every number means](metrics.md) | CPU %, load, memory, swap, disk, inodes, network, container and system figures: how each is measured and its limits. || [Alerts and incidents](alerts.md) | Every rule, its default thresholds, and how incidents open and resolve. || [Accounts, roles and two-factor sign-in](accounts.md) | Passwords, roles, the Account page, authenticator codes, recovery codes, locked-out accounts. |-| [Homie assistant](assistant.md) | The optional, monitoring-only AI assistant. |+| [Incident agent](assistant.md) | The optional agent: diagnoses, watching the fix, notifications, chat, who sees what, and what it costs. |## Installing and runningdiff --git a/docs/accounts.md b/docs/accounts.mdindex 47d90e2..04a0818 100644--- a/docs/accounts.md+++ b/docs/accounts.md@@ -17,13 +17,14 @@- Everyone signed in can see all servers, containers and incidents.- Only admins can add, approve, dismiss or delete servers, change checkintervals, manage the enrollment key and open the **Admin** page.-- **Admin** page settings that are connected today: alert thresholds (including- per-mount disk thresholds), how long metrics are kept (default 30 days; older- check-in samples and system events are deleted hourly, but only after the check-ins have- been summarised; the summaries behind the Statistics page are not deleted yet, and a- retention setting for each level is planned), and turning- chat with the assistant on or off. The other sections on the page show- placeholder data and aren't saved yet.+- **Admin** page: servers, users and invitations, alert rules and thresholds (including per-mount disk+ thresholds), how long metrics are kept (default 30 days; older check-in samples and system events are deleted+ hourly, but only after the check-ins have been summarised), and the incident agent.+- **The incident agent and roles**: admins always see the agent's diagnoses and may use its chat. Whether other+ users see diagnoses is the **Show diagnoses to users** switch in Admin → Incident agent (on by default). The chat+ is for admins only by default; with **Chat access: Per user**, an **Agent chat** switch next to each user in+ Admin → Users allows it (new users start with it off). Only admins can ask for a new diagnosis. See+ [Incident agent](assistant.md#who-sees-what).## Two-factor sign-indiff --git a/docs/alerts.md b/docs/alerts.mdindex 7bdf5eb..8404e9c 100644--- a/docs/alerts.md+++ b/docs/alerts.md@@ -75,5 +75,13 @@ and are recorded in the audit log.<ui - Active incidents section with a CRITICAL and a WARNING incident, each showing its server and start time>-Incidents are shown on the dashboard only; there are no push notifications yet.-(`ADMIN_ALERT_WEBHOOK_URL` is used by the assistant's `daily_checkup` only.)+**Notifications.** Each person chooses their channels (ntfy, Discord, any webhook, email when SMTP is set up) and+which severities go where in **Account → Notifications**, with quiet hours for warnings. When the incident agent is+set up, a notification about a new warning or critical incident waits up to 3 minutes for its diagnosis and carries+a short summary of it; see [Incident agent](assistant.md#notifications). (`ADMIN_ALERT_WEBHOOK_URL` is used by the+chat's `daily_checkup` only.)++**Resolved by the agent.** Besides resolving when the rule stops firing, an incident the agent diagnosed can be+resolved by the agent once the condition from its diagnosis holds (a container runs N minutes without a restart, a+metric stays under a threshold). The same rule on that server then stays quiet for its window, unless the problem+comes back. See [Incident agent](assistant.md#watching-the-fix).diff --git a/docs/api.md b/docs/api.mdindex 169e579..de07180 100644--- a/docs/api.md+++ b/docs/api.md@@ -27,8 +27,12 @@ All paths are relative to `/api` when going through the frontend/nginx.| `POST /monitoring/join-tokens` | admin | Create the single-use join token for **Connect a server** (shown once). || `GET /monitoring/install-info` | admin | The collector address and images the panel uses. || `GET` / `POST` / `DELETE /monitoring/enrollment-key` | admin | Show status / create or rotate / revoke the enrollment key. |-| `GET` / `PUT /admin/settings` | admin | Metrics retention, chat on/off, require two-factor for admins, alert thresholds and per-mount disk thresholds; the agent's model prices, monthly budget and daily chat limit. |-| `GET /agent/config` | session | Whether chat with the agent can be used: switched on, a key configured, and the monthly budget not used up. |+| `GET` / `PUT /admin/settings` | admin | Metrics retention, chat on/off, require two-factor for admins, alert thresholds and per-mount disk thresholds; the agent's model prices, monthly budget, daily chat limit, automatic diagnosis, whether users see diagnoses, and chat access (`admins_only` or `per_user`). |+| `GET /admin/users`, `PATCH /admin/users/{id}` | admin | Users and invitations; change someone's role, switch them off, or (with per-user chat access) allow them the agent chat (`agent_chat_enabled`). |+| `GET /agent/config` | session | Whether chat with the agent can be used: switched on, allowed for you (`may_chat`), a key configured, and the monthly budget not used up. |+| `GET /incidents`, `GET /incidents/{id}` | session | The incident inbox; one incident with its rule-based diagnosis and, under `agent`, the agent's latest report (with `watch` progress while it is open, `reused_from` when it was reused). The report is left out (`hidden: true`) for users who aren't admins while diagnoses aren't shown to users. |+| `POST /incidents/{id}/acknowledge`, `…/resolve`, `…/mute`, `…/unmute` | admin | Act on an incident. |+| `POST /incidents/{id}/diagnose` | admin | Queue a new diagnosis by the agent (409 without a key, 429 while the budget is used up). || `GET /admin/agent/usage` | admin | This month's model calls, tokens and estimated cost against the budget, per model and per day, with the prices and limits. || `GET /admin/agent/worker` | admin | Whether the agent worker is running, how many jobs wait, are running or wait to be retried, and the latest results. || `POST /admin/agent/test` | admin | Checks the OpenAI key and that the configured model exists, without spending tokens. |@@ -36,7 +40,7 @@ All paths are relative to `/api` when going through the frontend/nginx.| `POST /monitoring/collectors/register/poll` | poll secret | Collector checks approval; returns its token once approved. || `POST /monitoring/collectors/enroll` | enrollment key | Join without approval. || `POST /monitoring/metrics/ingest` | collector token | Collector reports host, container and system metrics. |-| `GET /conversations`, `POST /conversations`, `DELETE /conversations/{id}`, `POST /agent/chat` | session | Homie assistant chats. |+| `GET /conversations`, `POST /conversations`, `DELETE /conversations/{id}`, `POST /agent/chat` | session | Chats with the incident agent (403 for users chat isn't allowed for). || `GET /logs`, `POST /logs`, `GET /dashboard/summary` | session | Audit log and summary counts. `POST /logs` adds an entry to your own log (level from a fixed list, message up to 2000 characters, at most 120 an hour); its source is always `dashboard`. |The four collector endpoints above exist only on the collector gate in the serverdiff --git a/docs/assistant.md b/docs/assistant.mdindex 9c371f1..19a2ed4 100644--- a/docs/assistant.md+++ b/docs/assistant.md@@ -1,12 +1,31 @@[← Documentation](README.md)-# Incident agent (monitoring-only)+# Incident agent++The incident agent diagnoses incidents, watches whether the fix holds, adds its diagnosis to notifications, and+answers questions in a chat. It reads data Infradeck already has; it can't run commands, restart containers or+change files on your servers. Everything about it is in `src/agent/` and in **Admin → Incident agent**.++## Setting it up++1. Create an API key at <https://platform.openai.com/api-keys> and put it in `.env`:+ ```+ OPENAI_API_KEY=sk-…+ AGENT_MODEL=gpt-5-mini # optional; any OpenAI model with Structured Outputs+ ```+2. `docker compose up -d backend agent-worker` (Compose recreates both with the new values).+3. **Admin → Incident agent → Test connection** checks the key and that the model exists, without spending tokens.+4. Enter the model's price per million tokens under **Prices** (from the provider's pricing page), so its calls+ count towards the budget, and set a **Monthly budget** if you want one.++Without a key nothing is sent anywhere: incidents keep the rule-based diagnosis (worked out locally from the same+data), notifications go out as before, and the chat is off. Change the model by changing `AGENT_MODEL` and running+step 2 again.## Diagnoses-When a warning or critical incident opens, or gets worse, the agent worker diagnoses it (Admin → Incident agent →-"Diagnose new incidents automatically"; anyone who may act on incidents can also click **Diagnose now** on the-incident). It works in three steps, in `src/agent/`:+When a warning or critical incident opens, or gets worse, the backend queues a job and the **agent worker**+(its own container, see [The containers](containers.md#infradeck-agent-worker)) diagnoses it in three steps:1. **Evidence pack** (`evidence.py`): the incident, the machine, metrics from an hour before it opened until now,recorded events, image changes of the container, the alert rule's own checks, the containers right now, and@@ -19,40 +38,82 @@ incident). It works in three steps, in `src/agent/`:unsupported claim left out"), fix commands that could destroy data are flagged and never recommended(`safety.py`), and an answer that doesn't parse is asked for once more, then saved as a failed report.-Each diagnosis is a new version in `agent_reports`; the incident page shows the latest, says which model wrote it-and how sure it is, and falls back to the rule-based diagnosis when there is none. The evidence chart, recorded-events and timeline always come from stored data, never from the model. Every model call counts towards the-budget below, and diagnoses stop while the budget is used up.+Each diagnosis is a new version in `agent_reports`. The incident page (Agent) says which model wrote it, when, and+how sure it is, and shows its summary, signals with the facts they rest on, and fix steps; with no diagnosis it+shows the rule-based one and says so. The evidence chart, recorded events and timeline always come from stored+data, never from the model. The Overview shows the first sentence next to the incident.++**Diagnose now / Diagnose again** on an incident asks for a new diagnosis (admins only); the page shows it as soon+as it is ready, without a reload. **Diagnose new incidents automatically** (on by default) can be switched off;+then a diagnosis only happens when someone asks.++**The same problem twice.** When an incident opens for the same rule on the same server (so the same container,+disk or check) as one diagnosed in the last 24 hours, that diagnosis is reused: no model call, no tokens. The+incident says so and links to the earlier one. Getting worse and **Diagnose again** always ask the model.++## Watching the fix++Each diagnosis ends with a condition that shows the incident is over. Two kinds are checked against the data+every minute, without the model (`verify.py`):++- **a container runs N minutes without a restart**;+- **a metric stays under a threshold for N minutes** (memory, swap, load, CPU, a disk).++The incident shows the progress ("Watching: resolves itself once gitlab runs 15 min without a restart. Held for 9+of 15 min."). When the condition holds, the agent resolves the incident with "Resolved by the agent: …", which is+what the resolved list shows. Data older than 5 minutes is never taken as proof.++Most rules resolve their incidents themselves as soon as they stop firing; this matters for the ones that stay+open for a window after the fact (a container exit, an OOM kill, a restart loop counted over 30 minutes). So that+such a rule doesn't open the incident again while its window still covers the old events, the same rule on that+server stays quiet for its window plus 10 minutes (about 70 minutes by default). If the problem comes back in that+time (a new restart, the metric over the threshold), the hold ends at once and the rule opens a new incident.++## Notifications++A notification about a new warning or critical incident waits up to **3 minutes** for the agent's diagnosis and+then carries its first two sentences in a line starting with "Agent:". If the diagnosis isn't ready by then, the+notification goes out without it. It doesn't wait at all when no diagnosis is coming: no key, automatic diagnosis+off, the budget used up, or the worker not running. Resolved notifications never wait.++## Who sees what++- **Show diagnoses to users** (on by default): when off, only owners and admins see the agent's diagnoses, on the+ incident page, on the Overview and in notifications; everyone else sees the rule-based diagnosis. The backend+ leaves the diagnosis out of what it sends them, so it isn't only hidden in the page.+- **Chat access**: **Admins only** (the default), or **Per user**, where an **Agent chat** switch next to each user in+ Admin → Users decides (new users start with it off). Admins always have chat while **Chat** is on.## Chat+The chat answers questions about an incident or any server. Each message goes to the model with the incident's+facts, and the conversation so far (its latest 40 turns). Every reply is held to a JSON schema with OpenAI's+Structured Outputs: a message, and at most one check from a fixed list. The provider sits behind a small interface+(`providers.py`), so other providers can be added later.-The chat runs on the OpenAI API. Set `OPENAI_API_KEY` in `.env` (and optionally `AGENT_MODEL`, default-`gpt-5-mini`), then restart the backend. **Admin → Incident agent → Test connection** confirms the key works and-the model exists without spending tokens. Without a key the chat is off; incidents, notifications and the-rule-based diagnosis work the same.+The chat has no code path for running shell commands. It may request exactly one fixed, read-only check at a time:+`server_health`, `container_health`, or `daily_checkup`, implemented with Python system APIs and Docker's Unix API+socket, never the shell or Docker CLI. The backend container does **not** mount `/var/run/docker.sock`; for the+container checks, point `DOCKER_SOCKET_PATH` at a hardened Docker API proxy that permits only the required GET+endpoints. `daily_checkup` combines host and container checks; on a critical finding it POSTs an alert only to+`ADMIN_ALERT_WEBHOOK_URL`, and without it the result says `not_configured` and no request is made.-**What it costs.** Every call to the model is recorded with its tokens (see `agent_runs` in-[Database schema](database.md)). In **Admin → Incident agent** you enter each model's price per million tokens (copy it-from the provider's pricing page; prices aren't fetched automatically), and the page shows the month's estimated cost,-calls, tokens and cost per model. With a **monthly budget** set, admins get a notification on their channels at 80 %,-and at 100 % the chat pauses until the 1st of next month (incidents and notifications keep working). Each person may-also send at most a set number of chat messages in 24 hours (100 by default), on top of 30 an hour.+## What it costs-Every reply is held to a JSON schema with OpenAI's Structured Outputs: a message, and at most one check from-the fixed list below. The provider sits behind a small interface (`src/agent/providers.py`), so other providers-can be added later.+Every call to the model is recorded with the tokens the provider reports for it (see `agent_runs` in+[Database schema](database.md)). **Admin → Incident agent** shows the month's estimated cost, calls, tokens and cost+per model. The token counts are the provider's own; the cost is an estimate from the prices you enter, and counts+all input at the full price (the provider charges less for cached input), so it errs on the high side. Calls that+fail are recorded with no tokens, since the provider reports none.-The assistant has no code path for running shell commands. It may request-exactly one fixed, read-only check at a time: `server_health`,-`container_health`, or `daily_checkup`, implemented with Python system APIs and-Docker's Unix API socket, never the shell or Docker CLI.+With a **monthly budget**, admins get a notification at 80 %, and at 100 % diagnoses and the chat pause until the+1st of next month (incidents and notifications keep working). Each person may send at most a set number of chat+messages in 24 hours (100 by default), on top of 30 an hour. A diagnosis is usually around 10 000 tokens; a chat+message a few hundred to a few thousand.-The backend container does **not** mount `/var/run/docker.sock`. If you want-the assistant's container checks, point `DOCKER_SOCKET_PATH` at a hardened-Docker API proxy that permits only the required GET endpoints.+## The worker card-`daily_checkup` combines host and container checks. On a critical finding it-POSTs an alert only to `ADMIN_ALERT_WEBHOOK_URL`; without it, the result says-`not_configured` and no request is made. Schedule it from a trusted scheduler-(e.g. a systemd timer) rather than letting the agent create schedules.+**Admin → Incident agent → Worker** is a health check, not a history: whether the worker is running, whether any+jobs are queued, running or waiting to retry, the last job, and how many of the latest jobs failed. The folded+list below it shows the last 10 jobs and why each ended as it did (diagnosed, reused, skipped with the reason, or+failed with the error). Redis keeps only the latest 50; the diagnoses themselves live on each incident.diff --git a/docs/containers.md b/docs/containers.mdindex ac72668..bee8352 100644--- a/docs/containers.md+++ b/docs/containers.md@@ -203,14 +203,14 @@ comes back, sessions saved in its volume work again.## infradeck-agent-worker**What it does.** Runs the incident agent's jobs. When an incident opens, or gets more severe, the backend puts one-job in a queue in Redis; the worker takes jobs one at a time and works on them. Automatic diagnosis (#116) is not-built yet, so for now a job only checks that its incident still needs a diagnosis and notes that; the chat runs in-the backend.+job in a queue in Redis; the worker takes jobs one at a time and diagnoses the incident (see+[Incident agent](assistant.md)). Every minute it also checks the conditions its diagnoses gave and resolves the+incidents whose fix held. The chat runs in the backend.**How it works.** It is the backend image started with `python -m src.agent.worker`. Jobs are published only afterthe database commit that opened the incident, and each event once. A job the worker takes moves to a processinglist and leaves it only when it is done, so a job interrupted by a restart goes back to the queue. A failed job is-tried again after 30 and 60 seconds and then given up; a job running longer than 2 minutes is abandoned. The+tried again after 30 and 60 seconds and then given up; a job running longer than 5 minutes is abandoned. Theworker writes a heartbeat every few seconds, which **Admin → Incident agent → Worker** and the container'shealthcheck read. It runs with no capabilities, a read-only filesystem and no published port.@@ -223,7 +223,8 @@ needed nothing new; a dedicated queue system (Celery, RabbitMQ) would add contaireach the model provider on the internet.**If it stops.** New incidents wait in the queue for their diagnosis and are worked on when it starts again (each-waiting job is kept). Incidents, notifications, the chat and everything else keep working. Admin shows the+waiting job is kept), and nothing is resolved by the agent. Notifications stop waiting for a diagnosis. Incidents,+the chat and everything else keep working. Admin shows theworker as offline.## infradeck-collectordiff --git a/docs/database.md b/docs/database.mdindex 206b907..152c676 100644--- a/docs/database.md+++ b/docs/database.md@@ -24,7 +24,12 @@ limit are rows in `app_settings` (`agent_prices`, `agent_monthly_cap_usd`, `agen**The agent's diagnoses.** `agent_reports` holds the diagnoses, one row per version per incident: the summary,how confident the agent is, the checked answer (signals with the evidence they cite, fix steps, how to verify) andthe masked evidence pack it was given, so every report can be traced to its data. A report the model couldn't-produce has status `failed` and the reason. Rows are deleted with their incident.+produce has status `failed` and the reason. A diagnosis reused from an earlier incident of the same rule has trigger+`reused` and names that incident in its body. Rows are deleted with their incident.++`incident_alerts.reopen_after` is set when the agent resolved an incident because its fix held: until then the same+rule on that server opens no new incident (unless the condition breaks again, which clears it).+`users.agent_chat_enabled` is the per-user chat switch used when chat access is "per user".**Summarised history.** A background job (it checks every minute and does nothing when it is up to date) turns the check-insamples into `host_rollups`, `mount_rollups` and `container_rollups`: one row per server, mount or containerdiff --git a/src/agent/diagnosis.py b/src/agent/diagnosis.pyindex bab0158..93fc20a 100644--- a/src/agent/diagnosis.py+++ b/src/agent/diagnosis.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport jsonimport time+from datetime import datetime, timedelta, timezonefrom sqlalchemy import func@@ -28,6 +29,9 @@ VERIFY_TYPES = ("container_running_for", "metric_below_for", "incident_quiet_forMAX_SIGNALS = 6MAX_STEPS = 5MAX_ATTEMPTS = 2+# A diagnosis of the same rule on the same server (so the same container, mount or check) this recent is reused for a+# new incident instead of asking the model again.+REUSE_WITHIN = timedelta(hours=24)SCHEMA = {"type": "object",@@ -103,7 +107,8 @@ def check_answer(raw: str, labels: dict[str, str]) -> dict:if not signals:confidence = "low" # a cause with nothing in the data behind it can't be more than a guessreturn {"summary": _clip(answer["summary"], 1200), "confidence": confidence, "signals": signals[:MAX_SIGNALS], "fix_steps": steps,- "verify": {"type": verify["type"], "target": _clip(verify.get("target"), 120) or None, "threshold": verify.get("threshold"), "minutes": verify.get("minutes")},+ "verify": {"type": verify["type"], "target": _clip(verify.get("target"), 120) or None, "threshold": verify.get("threshold"), "minutes": verify.get("minutes"),+ "label": labels.get(verify.get("target")) if verify["type"] == "metric_below_for" else None},"dropped_signals": dropped}@@ -155,14 +160,40 @@ def diagnose(db, incident: IncidentAlert, provider: Provider, trigger: str = "inreturn _save(db, incident, trigger, model, pack, "failed", error=f"The model's answer could not be used twice: {reason}")+def reuse_recent(db, incident: IncidentAlert, now: datetime | None = None) -> AgentReport | None:+ """When the same problem came back within REUSE_WITHIN, copy its diagnosis to the new incident instead of paying+ for a new one. Returns the copy, or None when there is nothing recent to reuse. Costs no tokens."""+ now = now or datetime.now(timezone.utc)+ earlier = db.query(AgentReport).join(IncidentAlert, IncidentAlert.id == AgentReport.incident_id) \+ .filter(IncidentAlert.server_id == incident.server_id, IncidentAlert.rule_key == incident.rule_key, IncidentAlert.id != incident.id,+ AgentReport.status == "ok", AgentReport.created_at >= now - REUSE_WITHIN) \+ .order_by(AgentReport.created_at.desc()).first()+ if earlier is None:+ return None+ body = json.loads(earlier.body) if earlier.body else {}+ body["reused_from"] = {"incident_id": earlier.incident_id, "version": earlier.version, "created_at": _iso(earlier.created_at)}+ version = (db.query(func.max(AgentReport.version)).filter(AgentReport.incident_id == incident.id).scalar() or 0) + 1+ report = AgentReport(incident_id=incident.id, version=version, trigger="reused", status="ok", model=earlier.model, confidence=earlier.confidence,+ summary=earlier.summary, body=json.dumps(body), evidence=earlier.evidence)+ db.add(report)+ db.commit()+ return report+++def _iso(moment: datetime) -> str:+ return (moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)).isoformat()++def report_json(report: AgentReport | None) -> dict | None:"""What the incident page gets: the latest report, without the evidence pack."""if report is None:return Nonebody = json.loads(report.body) if report.body else {}- return {"version": report.version, "status": report.status, "model": report.model, "trigger": report.trigger, "created_at": report.created_at.isoformat() if report.created_at.tzinfo else report.created_at.isoformat() + "+00:00",+ reused = body.get("reused_from")+ return {"version": report.version, "status": report.status, "model": report.model, "trigger": report.trigger, "created_at": _iso(report.created_at),"summary": report.summary, "confidence": report.confidence, "signals": body.get("signals", []), "fix_steps": body.get("fix_steps", []), "verify": body.get("verify"),- "dropped_signals": body.get("dropped_signals", 0), "error": report.error}+ "dropped_signals": body.get("dropped_signals", 0), "error": report.error,+ "reused_from": {**reused, "reference": f"INC-{reused['incident_id']:04d}"} if reused else None}def latest(db, incident_id: int) -> AgentReport | None:diff --git a/src/agent/settings.py b/src/agent/settings.pynew file mode 100644index 0000000..4df94c4--- /dev/null+++ b/src/agent/settings.py@@ -0,0 +1,44 @@+"""The agent's switches in Admin › Incident agent, stored in app_settings.++- Automatic diagnosis: new and worsening incidents are diagnosed without anyone asking (on by default).+- Show diagnoses to users: when off, only admins see the agent's diagnoses and their summaries in notifications;+ everyone else sees the rule-based diagnosis (on by default).+- Chat access: "admins_only", or "per_user", where each user's own switch in Admin › Users decides. Admins always+ have chat while it is switched on.+"""+from __future__ import annotations++from src.backend.models import AppSetting++AUTO_DIAGNOSE_KEY = "agent_auto_diagnose"+SHOW_TO_USERS_KEY = "agent_show_diagnoses_to_users"+CHAT_ACCESS_KEY = "agent_chat_access"+CHAT_ACCESS = ("admins_only", "per_user")+++def _setting(db, key: str) -> str | None:+ setting = db.get(AppSetting, key)+ return setting.value if setting else None+++def auto_diagnose(db) -> bool:+ return _setting(db, AUTO_DIAGNOSE_KEY) != "false"+++def show_diagnoses_to_users(db) -> bool:+ return _setting(db, SHOW_TO_USERS_KEY) != "false"+++def sees_diagnoses(db, role: str | None) -> bool:+ """Whether someone with ``role`` sees the agent's diagnoses."""+ return role == "admin" or show_diagnoses_to_users(db)+++def chat_access(db) -> str:+ value = _setting(db, CHAT_ACCESS_KEY)+ return value if value in CHAT_ACCESS else "admins_only"+++def may_chat(db, user) -> bool:+ """Whether ``user`` (a User row) may use the chat, leaving aside the global Chat switch."""+ return user.role == "admin" or (chat_access(db) == "per_user" and bool(user.agent_chat_enabled))diff --git a/src/agent/usage.py b/src/agent/usage.pyindex 628ddc7..1c8cc0f 100644--- a/src/agent/usage.py+++ b/src/agent/usage.py@@ -17,7 +17,6 @@ from ..backend.models import AgentRun, AppSettingPRICES_KEY = "agent_prices"CAP_KEY = "agent_monthly_cap_usd"DAILY_LIMIT_KEY = "agent_daily_chat_limit"-AUTO_DIAGNOSE_KEY = "agent_auto_diagnose"DEFAULT_DAILY_CHAT_LIMIT = 100MAX_DAILY_CHAT_LIMIT = 10000WARN_SHARE = 0.8@@ -82,11 +81,6 @@ def validate_cap(value) -> float | None:return float(value) or None-def auto_diagnose(db) -> bool:- """Whether new and worsening incidents are diagnosed without anyone asking. On unless an admin turned it off."""- return _setting(db, AUTO_DIAGNOSE_KEY) != "false"--def get_daily_limit(db) -> int:try:return max(1, min(MAX_DAILY_CHAT_LIMIT, int(_setting(db, DAILY_LIMIT_KEY) or DEFAULT_DAILY_CHAT_LIMIT)))diff --git a/src/agent/verify.py b/src/agent/verify.pynew file mode 100644index 0000000..67cf8d1--- /dev/null+++ b/src/agent/verify.py@@ -0,0 +1,142 @@+"""Watching an incident after its diagnosis: the condition the agent gave ("gitlab runs 15 minutes without a restart",+"memory stays under 80 % for 10 minutes") is checked against stored data, without the model, and the incident is+resolved once it holds.++Many rules resolve their incidents themselves as soon as they stop firing. This is for the ones that stay open for+a window after the fact (a container exit, an OOM kill, a restart loop counted over 30 minutes): once the fix+holds, the agent closes the incident and writes down how it was confirmed. So that the rule doesn't open it again+at the next check-in while its window still covers the old events, the same rule on that server stays quiet until+``reopen_after``, unless the condition breaks again first, which lifts the hold at once.+"""+from __future__ import annotations++import json+from datetime import datetime, timedelta, timezone++from src.backend import incidents+from src.backend.models import AgentReport, AppSetting, ContainerMetric, HostMetric, IncidentAlert, MountMetric+from src.backend.rules import DEFAULT_THRESHOLDS++WATCHED = ("container_running_for", "metric_below_for")+STALE_AFTER = timedelta(minutes=5) # with no sample this recent, there is nothing to judge+MAX_MINUTES = 24 * 60+MAX_WATCHED = 200+HOLD_MARGIN = timedelta(minutes=10)+++def _utc(moment: datetime) -> datetime:+ return moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)+++def describe(verify: dict | None) -> str | None:+ """The condition in words, or None when nothing is watched."""+ if not verify or verify.get("type") not in WATCHED or not verify.get("minutes"):+ return None+ minutes = int(verify["minutes"])+ if verify["type"] == "container_running_for":+ return f"{verify.get('target') or 'the container'} runs {minutes} min without a restart"+ return f"{verify.get('label') or verify.get('target')} stays under {verify.get('threshold'):g} for {minutes} min"+++def _metric_rows(db, incident: IncidentAlert, metric: str, since: datetime) -> list[tuple[datetime, float | None]]:+ """The samples behind a metric ID from the evidence pack, oldest first."""+ kind, subject = incidents.rule_kind(incident.rule_key), incidents.subject(incident.rule_key)+ host = {"metric:host.cpu": HostMetric.cpu_utilization_pct, "metric:host.memory": HostMetric.ram_pct, "metric:host.swap": HostMetric.swap_pct, "metric:host.load": HostMetric.load_1m}+ if metric == "metric:main":+ metric = {"host:memory": "metric:host.memory", "host:swap": "metric:host.swap", "host:load": "metric:host.load"}.get(kind, metric)+ column = mount_column = container_column = None+ if metric in host:+ column = host[metric]+ elif metric == "metric:mount.used_gb" or (metric == "metric:main" and kind in ("host:disk", "host:inodes")):+ mount_column = MountMetric.used_gb if metric == "metric:mount.used_gb" else MountMetric.used_pct if kind == "host:disk" else MountMetric.inodes_pct+ elif metric in ("metric:container.cpu", "metric:container.restarts") or (metric == "metric:main" and kind.startswith(("container:", "trend:"))):+ container_column = {"metric:container.cpu": ContainerMetric.cpu_pct, "metric:container.restarts": ContainerMetric.restart_count}.get(metric, ContainerMetric.memory_used_mb)+ if column is not None:+ return db.query(HostMetric.time, column).filter(HostMetric.server_id == incident.server_id, HostMetric.time >= since).order_by(HostMetric.time).limit(5000).all()+ if mount_column is not None and subject:+ return db.query(MountMetric.time, mount_column).filter(MountMetric.server_id == incident.server_id, MountMetric.mount == subject, MountMetric.time >= since).order_by(MountMetric.time).limit(5000).all()+ if container_column is not None and subject:+ return db.query(ContainerMetric.time, container_column).filter(ContainerMetric.server_id == incident.server_id, ContainerMetric.name == subject, ContainerMetric.time >= since).order_by(ContainerMetric.time).limit(5000).all()+ return []+++def _held_for(rows: list, ok) -> float | None:+ """Minutes from the earliest sample of the unbroken run of good samples at the end until the newest one; None+ when the newest sample itself isn't good (the condition is broken right now)."""+ if not rows or not ok(rows[-1]):+ return None+ start = None+ for row in reversed(rows):+ if not ok(row):+ break+ start = row+ return (_utc(rows[-1][0]) - _utc(start[0])).total_seconds() / 60+++def evaluate(db, incident: IncidentAlert, verify: dict | None, now: datetime | None = None) -> dict | None:+ """{"text", "minutes", "held_minutes", "holds", "known", "broken"} for a watched condition; None when nothing is+ watched. ``known`` is False when the data is too old to judge (the collector stopped, the container is gone);+ ``broken`` is True when the newest sample fails the condition."""+ text = describe(verify)+ if text is None:+ return None+ now = now or datetime.now(timezone.utc)+ minutes = max(1, min(MAX_MINUTES, int(verify["minutes"])))+ since = now - timedelta(minutes=minutes * 2 + 30)+ if verify["type"] == "container_running_for":+ rows = db.query(ContainerMetric.time, ContainerMetric.status, ContainerMetric.restart_count).filter(+ ContainerMetric.server_id == incident.server_id, ContainerMetric.name == (verify.get("target") or ""), ContainerMetric.time >= since).order_by(ContainerMetric.time).limit(5000).all()+ latest_restarts = rows[-1][2] if rows else None+ held = _held_for(rows, lambda row: row[1] == "running" and row[2] == latest_restarts)+ else:+ threshold = verify.get("threshold")+ rows = _metric_rows(db, incident, verify.get("target") or "", since) if threshold is not None else []+ held = _held_for(rows, lambda row: row[1] is not None and row[1] < threshold)+ known = bool(rows) and now - _utc(rows[-1][0]) <= STALE_AFTER+ return {"text": text, "minutes": minutes, "held_minutes": round(held or 0, 1), "holds": known and held is not None and held >= minutes, "known": known, "broken": known and held is None}+++def _hold(db) -> timedelta:+ """How long a rule stays quiet after the agent resolved its incident: its longest event window, and a margin."""+ setting = db.get(AppSetting, "alert_thresholds")+ try:+ thresholds = {**DEFAULT_THRESHOLDS, **(json.loads(setting.value) if setting else {})}+ except ValueError:+ thresholds = dict(DEFAULT_THRESHOLDS)+ return timedelta(minutes=max(thresholds["event_window_minutes"], thresholds["restart_loop_window_minutes"])) + HOLD_MARGIN+++def _latest_ok(db, incident_id: int) -> AgentReport | None:+ return db.query(AgentReport).filter(AgentReport.incident_id == incident_id, AgentReport.status == "ok").order_by(AgentReport.version.desc()).first()+++def _verify_of(report: AgentReport | None) -> dict | None:+ if report is None or not report.body:+ return None+ verify = json.loads(report.body).get("verify")+ return verify if verify and verify.get("type") in WATCHED else None+++def watch(db, now: datetime | None = None) -> dict:+ """One round: resolve the incidents whose condition holds, and lift the hold on the rules whose condition broke+ again. Returns {"resolved": [ids], "released": [ids]}."""+ now = now or datetime.now(timezone.utc)+ resolved, released = [], []+ active = db.query(IncidentAlert).filter(IncidentAlert.status == "active", IncidentAlert.severity.in_(("WARNING", "CRITICAL"))).order_by(IncidentAlert.id.desc()).limit(MAX_WATCHED).all()+ for incident in active:+ verify = _verify_of(_latest_ok(db, incident.id))+ result = evaluate(db, incident, verify, now)+ if result and result["holds"]:+ incident.status, incident.resolved_at = "resolved", now+ incident.resolution = f"Resolved by the agent: {result['text']}"[:255]+ incident.reopen_after = now + _hold(db)+ resolved.append(incident.id)+ held = db.query(IncidentAlert).filter(IncidentAlert.status == "resolved", IncidentAlert.reopen_after.isnot(None), IncidentAlert.reopen_after > now).limit(MAX_WATCHED).all()+ for incident in held:+ result = evaluate(db, incident, _verify_of(_latest_ok(db, incident.id)), now)+ if result and result["broken"]:+ incident.reopen_after = None # broke again: let the rule open a new incident at once+ released.append(incident.id)+ db.commit()+ return {"resolved": resolved, "released": released}+diff --git a/src/agent/worker.py b/src/agent/worker.pyindex 9220d68..bf891d3 100644--- a/src/agent/worker.py+++ b/src/agent/worker.py@@ -4,6 +4,9 @@ It runs in its own container, so a slow or stuck model never holds up the backenincidents wait for their diagnosis; everything else keeps working. Run with ``python -m src.agent.worker``;``--health`` exits 0 while a worker is alive, for the container's healthcheck.+Every minute it also checks the conditions its diagnoses gave ("gitlab runs 15 min without a restart") and resolves+the incidents whose fix held (verify.py).+A job builds the incident's evidence pack and asks the model for a diagnosis (diagnosis.py), unless the incidentno longer needs one, there is no API key, or this month's budget is used up."""@@ -15,7 +18,7 @@ import sysimport threadingimport time-from src.agent import diagnosis, jobs, usage+from src.agent import diagnosis, jobs, settings, usage, verifyfrom src.agent.providers import configured_key, get_providerfrom src.backend.config import REDIS_URLfrom src.backend.db import SessionLocal@@ -24,6 +27,8 @@ from src.backend.models import IncidentAlert# A diagnosis can take two model calls, each with its own retries; past this the job is given up and retried later.JOB_TIMEOUT_SECONDS = 300POLL_SECONDS = 5+# How often the conditions the agent gave are checked against the data (see verify.py).+WATCH_SECONDS = 60def handle_incident(job: dict) -> tuple[str, str]:@@ -37,10 +42,15 @@ def handle_incident(job: dict) -> tuple[str, str]:return "skipped", "The incident was already resolved."if usage.budget(db)["state"] == "paused":return "skipped", "This month's budget for the agent is used up."- if job.get("type") != jobs.REQUESTED and not usage.auto_diagnose(db):+ if job.get("type") != jobs.REQUESTED and not settings.auto_diagnose(db):return "skipped", "Automatic diagnosis is switched off in Admin; it runs when someone asks."if not configured_key():return "skipped", "No OPENAI_API_KEY is configured; the incident keeps its rule-based diagnosis."+ if job.get("type", jobs.OPENED) == jobs.OPENED:+ # The same problem again within a day: its diagnosis still applies, and asking again would cost tokens.+ reused = diagnosis.reuse_recent(db, incident)+ if reused is not None:+ return "reused", f"Same diagnosis as INC-{json.loads(reused.body)['reused_from']['incident_id']:04d}; no tokens spent"report = diagnosis.diagnose(db, incident, get_provider(), trigger=job.get("type", jobs.OPENED))if report.status != "ok":return "failed", report.error or "The model's answer could not be used."@@ -93,6 +103,14 @@ def process(redis_client, raw: str, handlers=None, timeout: float = JOB_TIMEOUT_return status_text+def watch_once() -> dict:+ db = SessionLocal()+ try:+ return verify.watch(db)+ finally:+ db.close()++def main() -> int:import redis@@ -107,7 +125,16 @@ def main() -> int:started_at = jobs.now_iso()recovered = jobs.recover(client)print(f"Agent worker started{f'; {recovered} unfinished jobs back in the queue' if recovered else ''}.", flush=True)+ last_watch = 0.0while not stopping.is_set():+ if time.monotonic() - last_watch >= WATCH_SECONDS:+ last_watch = time.monotonic()+ try:+ watched = watch_once()+ if watched["resolved"] or watched["released"]:+ print(f"Agent watch: resolved {watched['resolved']}, lifted the hold on {watched['released']}", flush=True)+ except Exception as exc: # a database hiccup must not stop the jobs+ print(f"Agent watch failed: {type(exc).__name__}: {exc}", flush=True)try:jobs.beat(client, started_at)jobs.promote_due(client)diff --git a/src/backend/alerts.py b/src/backend/alerts.pyindex 9070184..d2985f7 100644--- a/src/backend/alerts.py+++ b/src/backend/alerts.py@@ -38,6 +38,11 @@ def raise_alert(db, server_id: int, rule_key: str, severity: str, title: str, deagent_jobs.note(db, agent_jobs.WORSENED, existing, severity)existing.severity, existing.title, existing.description = severity, title[:255], descriptionreturn False+ # The agent closed the last one because its fix held; events still inside the rule's window don't reopen it.+ held = db.query(IncidentAlert.reopen_after).filter(IncidentAlert.server_id == server_id, IncidentAlert.rule_key == rule_key, IncidentAlert.status == "resolved",+ IncidentAlert.reopen_after.isnot(None)).order_by(IncidentAlert.reopen_after.desc()).limit(1).scalar()+ if held is not None and (held if held.tzinfo else held.replace(tzinfo=timezone.utc)) > datetime.now(timezone.utc):+ return Falsealert = IncidentAlert(server_id=server_id, rule_key=rule_key, severity=severity, title=title[:255], description=description)db.add(alert)agent_jobs.note(db, agent_jobs.OPENED, alert, severity)diff --git a/src/backend/main.py b/src/backend/main.pyindex cbe238c..d496563 100644--- a/src/backend/main.py+++ b/src/backend/main.py@@ -64,7 +64,7 @@ from .config import ()from .rules import HELPER_EVENT_KINDS, DEFAULT_THRESHOLDS, HOST_RULE_PREFIX, container_rules, host_rules, validate_thresholds, detect_system_events, system_rules, SYSTEM_RULE_PREFIX, validate_mount_thresholds, validate_helper_events, REBOOT_DETAILS, REBOOT_KEY_PREFIX, detect_container_events, memory_trend_rules, CONTAINER_EVENT_KINDS, MAX_CONTAINER_EVENTS_PER_CHECKIN, MAX_CONTAINER_EVENTS_PER_HOUR, TREND_RULE_PREFIX, NETWORK_EVENT_KINDS, NETWORK_RULE_PREFIX, MAX_NETWORK_EVENTS_PER_CHECKIN, MAX_NETWORK_EVENTS_PER_HOUR, INTERNET_STATUSES, LISTENER_SCOPES, LISTENER_PROTOCOLS, MAX_LISTENERS, FIREWALL_LABELS, detect_listener_changes, detect_firewall_changes, network_rules, validate_listeners, validate_firewallfrom .rate_limit import enforce_ip_limit, enforce_limit, enforce_login_limit, enforce_register_limit, refund_attempt, reset_limits-from ..agent import jobs as agent_jobs, usage as agent_usage+from ..agent import jobs as agent_jobs, settings as agent_settings, usage as agent_usage, verify as agent_verifyfrom ..agent.diagnosis import latest as latest_report, report_jsonfrom ..agent.providers import configured_keyfrom ..agent.chat import check_provider_connection, delete_agent_conversation, send_agent_message@@ -196,6 +196,8 @@ class AdminSettingsRequest(BaseModel):agent_monthly_cap_usd: float | None = Noneagent_daily_chat_limit: int | None = Noneagent_auto_diagnose: bool | None = None+ agent_show_diagnoses_to_users: bool | None = None+ agent_chat_access: Literal["admins_only", "per_user"] | None = Noneclass MetricsIngestRequest(BaseModel):@@ -354,9 +356,9 @@ def startup_event():connection.execute(text("ALTER TABLE incident_alerts ADD COLUMN IF NOT EXISTS rule_key VARCHAR(255)"))connection.execute(text("ALTER TABLE incident_alerts ADD COLUMN IF NOT EXISTS resolved_at TIMESTAMP WITH TIME ZONE"))for column, column_type in (("resolution", "VARCHAR(255)"), ("acknowledged_at", "TIMESTAMP WITH TIME ZONE"), ("acknowledged_by", "INTEGER"), ("muted_until", "TIMESTAMP WITH TIME ZONE"),- ("notified_at", "TIMESTAMP WITH TIME ZONE"), ("resolve_notified_at", "TIMESTAMP WITH TIME ZONE")):+ ("notified_at", "TIMESTAMP WITH TIME ZONE"), ("resolve_notified_at", "TIMESTAMP WITH TIME ZONE"), ("reopen_after", "TIMESTAMP WITH TIME ZONE")):connection.execute(text(f"ALTER TABLE incident_alerts ADD COLUMN IF NOT EXISTS {column} {column_type}"))- for column, column_type in (("username", "VARCHAR(64)"), ("avatar_color", "VARCHAR(16)"), ("preferences", "TEXT"), ("last_seen_at", "TIMESTAMP WITH TIME ZONE")):+ for column, column_type in (("username", "VARCHAR(64)"), ("avatar_color", "VARCHAR(16)"), ("preferences", "TEXT"), ("last_seen_at", "TIMESTAMP WITH TIME ZONE"), ("agent_chat_enabled", "BOOLEAN NOT NULL DEFAULT FALSE")):connection.execute(text(f"ALTER TABLE users ADD COLUMN IF NOT EXISTS {column} {column_type}"))connection.execute(text("CREATE INDEX IF NOT EXISTS ix_incident_alerts_rule_key ON incident_alerts (rule_key)"))# Alerts from before the alert engine: offline alerts keep going under their rule, the rest were@@ -1005,7 +1007,8 @@ def get_mount_thresholds(db) -> dict:def _admin_settings(db) -> dict:return {"instance_name": get_instance_name(db), "metrics_retention_days": get_metrics_retention_days(db), "agent_chat_enabled": is_agent_chat_enabled(db), "alert_thresholds": get_alert_thresholds(db), "mount_thresholds": get_mount_thresholds(db), "require_2fa_for_admins": require_admin_two_factor(db), "secrets_configured": secrets_box.available(),"require_2fa_for_everyone": require_two_factor_for_everyone(db), "disabled_rules": sorted(get_disabled_rules(db)),- "agent_prices": agent_usage.get_prices(db), "agent_monthly_cap_usd": agent_usage.get_cap(db), "agent_daily_chat_limit": agent_usage.get_daily_limit(db), "agent_auto_diagnose": agent_usage.auto_diagnose(db)}+ "agent_prices": agent_usage.get_prices(db), "agent_monthly_cap_usd": agent_usage.get_cap(db), "agent_daily_chat_limit": agent_usage.get_daily_limit(db), "agent_auto_diagnose": agent_settings.auto_diagnose(db),+ "agent_show_diagnoses_to_users": agent_settings.show_diagnoses_to_users(db), "agent_chat_access": agent_settings.chat_access(db)}def purge_old_metrics(db, now: datetime | None = None) -> int:@@ -1076,9 +1079,15 @@ def update_admin_settings(payload: AdminSettingsRequest, session_id: Annotated[schanges.append(f"Set the agent chat limit to {limit} messages per person per day")except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc- if payload.agent_auto_diagnose is not None and payload.agent_auto_diagnose != agent_usage.auto_diagnose(db):- _set_setting(db, agent_usage.AUTO_DIAGNOSE_KEY, "true" if payload.agent_auto_diagnose else "false")+ if payload.agent_auto_diagnose is not None and payload.agent_auto_diagnose != agent_settings.auto_diagnose(db):+ _set_setting(db, agent_settings.AUTO_DIAGNOSE_KEY, "true" if payload.agent_auto_diagnose else "false")changes.append(f"{'Turned on' if payload.agent_auto_diagnose else 'Turned off'} automatic diagnosis by the agent")+ if payload.agent_show_diagnoses_to_users is not None and payload.agent_show_diagnoses_to_users != agent_settings.show_diagnoses_to_users(db):+ _set_setting(db, agent_settings.SHOW_TO_USERS_KEY, "true" if payload.agent_show_diagnoses_to_users else "false")+ changes.append(f"{'Showed' if payload.agent_show_diagnoses_to_users else 'Hid'} the agent's diagnoses {'to' if payload.agent_show_diagnoses_to_users else 'from'} users who aren't admins")+ if payload.agent_chat_access is not None and payload.agent_chat_access != agent_settings.chat_access(db):+ _set_setting(db, agent_settings.CHAT_ACCESS_KEY, payload.agent_chat_access)+ changes.append("Agent chat is now for admins only" if payload.agent_chat_access == "admins_only" else "Agent chat is now allowed per user")if payload.agent_chat_enabled is not None:_set_setting(db, AGENT_CHAT_ENABLED_KEY, "true" if payload.agent_chat_enabled else "false")changes.append(f"{'Enabled' if payload.agent_chat_enabled else 'Disabled'} chat with the agent")@@ -1109,9 +1118,10 @@ def update_admin_settings(payload: AdminSettingsRequest, session_id: Annotated[s@app.get("/agent/config")def agent_config(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):"""What the Agent page needs to know about the agent; readable by every signed-in user."""- _current_user(session_id, db)+ user = _current_user(session_id, db)spend = agent_usage.budget(db)- return {"chat_enabled": is_agent_chat_enabled(db), "key_configured": bool(configured_key()), "budget_paused": spend["state"] == "paused"}+ account = db.get(User, user["id"])+ return {"chat_enabled": is_agent_chat_enabled(db), "may_chat": bool(account) and agent_settings.may_chat(db, account), "key_configured": bool(configured_key()), "budget_paused": spend["state"] == "paused"}OVERVIEW_ALERT_LIMIT = 50@@ -1250,6 +1260,7 @@ def monitoring_overview(session_id: Annotated[str | None, Cookie(alias=SESSION_C# Most severe first, then newest.severity_rank = case({severity: rank for rank, severity in enumerate(reversed(SEVERITIES))}, value=IncidentAlert.severity, else_=len(SEVERITIES))alerts = _spread_alerts(active_alerts.order_by(severity_rank, IncidentAlert.created_at.desc()).limit(OVERVIEW_ALERT_SCAN).all())+ sees_reports = agent_settings.sees_diagnoses(db, "admin" if _is_admin(db, user["id"]) else "user")hostnames = {server.id: server.hostname for server in servers}servers_by_id = {server.id: server for server in servers}thresholds = get_alert_thresholds(db)@@ -1269,7 +1280,7 @@ def monitoring_overview(session_id: Annotated[str | None, Cookie(alias=SESSION_C"alert_thresholds": {key: thresholds[key] for key in ("memory_warning_pct", "memory_critical_pct", "swap_warning_pct")},"disk_thresholds": {key: thresholds[key] for key in ("disk_warning_pct", "disk_critical_pct", "inodes_warning_pct", "inodes_critical_pct")},"alerts": [{"id": a.id, "server_id": a.server_id, "hostname": hostnames.get(a.server_id), "severity": a.severity, "title": a.title, "description": a.description, "rule_key": a.rule_key, "created_at": a.created_at.isoformat(), "reference": incidents.reference(a.id), "acknowledged": a.acknowledged_at is not None,- "agent_note": _agent_note(db, a, servers_by_id.get(a.server_id))} for a in alerts],+ "agent_note": _agent_note(db, a, servers_by_id.get(a.server_id), sees_reports)} for a in alerts],}@@ -2566,6 +2577,9 @@ def agent_chat(payload: AgentChatRequest, session_id: Annotated[str | None, Cookraise HTTPException(status_code=401, detail="Session is invalid or expired.")if not is_agent_chat_enabled(db):raise HTTPException(status_code=403, detail="Chat with the agent has been turned off by an admin.")+ account = db.get(User, user["id"])+ if account is None or not agent_settings.may_chat(db, account):+ raise HTTPException(status_code=403, detail="Chat with the agent is not switched on for your account. An admin can allow it in Admin › Users.")enforce_limit(redis_client, scope="chat-user", subject=user["id"], limit=CHAT_MESSAGE_LIMIT, window_seconds=3600)spend = agent_usage.budget(db)if spend["state"] == "paused":@@ -2644,19 +2658,19 @@ def agent_chat(payload: AgentChatRequest, session_id: Annotated[str | None, Cook# ---------------------------------------------------------------------------------------------------------# Incidents (the Agent page)-def _agent_note(db, alert: IncidentAlert, server: Server | None) -> str | None:+def _agent_note(db, alert: IncidentAlert, server: Server | None, from_report: bool = True) -> str | None:"""The one line the Overview shows next to an incident, from its diagnosis. Remembered for a minute: theOverview is polled every few seconds and working it out reads samples."""if server is None:return None- key = f"infradeck:incident-note:{alert.id}"+ key = f"infradeck:incident-note:{alert.id}" + ("" if from_report else ":rules")try:cached = redis_client.get(key)if cached is not None:return (cached.decode() if isinstance(cached, bytes) else cached) or Noneexcept Exception:pass- report = latest_report(db, alert.id)+ report = latest_report(db, alert.id) if from_report else Noneif report is not None and report.status == "ok" and report.summary:# The agent's own diagnosis, first sentence; the rule-based note when there is none.note = re.split(r"(?<=[.!?])\s", report.summary.strip(), maxsplit=1)[0][:160]@@ -2702,11 +2716,16 @@ def list_incidents(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE@app.get("/incidents/{incident_id}")def get_incident(incident_id: PathId, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):- _current_user(session_id, db)+ user = _current_user(session_id, db)alert, server = _incident_or_404(db, incident_id)users = dict(db.query(User.id, User.name).all())+ # Admins always see the agent's diagnosis; others only while Admin shows it to them (checked here, not in the page).+ visible = agent_settings.sees_diagnoses(db, "admin" if _is_admin(db, user["id"]) else "user")+ report = report_json(latest_report(db, alert.id)) if visible else None+ if report and report["status"] == "ok" and alert.status == "active":+ report["watch"] = agent_verify.evaluate(db, alert, report["verify"])return {**incidents.summary(alert, server.hostname, datetime.now(timezone.utc), users), "diagnosis": incidents.diagnose(db, alert, server), "cpu_cores": server.cpu_cores,- "agent": {"report": report_json(latest_report(db, alert.id)), "key_configured": bool(configured_key()), "budget_paused": agent_usage.budget(db)["state"] == "paused"}}+ "agent": {"report": report, "hidden": not visible, "key_configured": bool(configured_key()), "budget_paused": agent_usage.budget(db)["state"] == "paused"}}@app.post("/incidents/{incident_id}/diagnose")@@ -2991,6 +3010,30 @@ NOTIFY_WINDOW = timedelta(hours=24)NOTIFY_MARK_SECONDS = 7 * 24 * 3600+# A new warning or critical incident waits this long for the agent's diagnosis, so the notification can carry it.+DIAGNOSIS_WAIT = timedelta(minutes=3)+++def _diagnosis_coming(db) -> bool:+ """Whether a diagnosis can be expected for a new incident: there is a key, automatic diagnosis is on, the budget+ isn't used up and a worker is running. When not, notifications don't wait for one."""+ if not configured_key() or not agent_settings.auto_diagnose(db) or agent_usage.budget(db)["state"] == "paused":+ return False+ try:+ return bool(redis_client.get(agent_jobs.HEARTBEAT))+ except Exception:+ return False+++def _agent_summary(report) -> str | None:+ """The first two sentences of a report, for a notification."""+ if report is None or report.status != "ok" or not report.summary:+ return None+ sentences = re.split(r"(?<=[.!?])\s+", report.summary.strip())+ text = " ".join(sentences[:2])+ return text if len(text) <= 320 else text[:319] + "…"++def dispatch_notifications(db, now: datetime | None = None) -> int:"""Send what hasn't been sent: incidents that opened or resolved in the last day, to every user with channels,following each user's routing and quiet hours. Returns how many messages went out.@@ -3007,6 +3050,7 @@ def dispatch_notifications(db, now: datetime | None = None) -> int:return 0recent = db.query(IncidentAlert).filter((IncidentAlert.created_at >= now - NOTIFY_WINDOW) | (IncidentAlert.resolved_at >= now - NOTIFY_WINDOW), IncidentAlert.severity != "INFO").order_by(IncidentAlert.created_at).limit(200).all()hostnames = dict(db.query(Server.id, Server.hostname).all())+ coming = Nonesent = 0for alert in recent:if incidents.is_muted(alert, now):@@ -3014,6 +3058,13 @@ def dispatch_notifications(db, now: datetime | None = None) -> int:event = "resolved" if alert.status == "resolved" else alert.severity.lower()if event not in notify.EVENTS:continue+ report = latest_report(db, alert.id)+ if event != "resolved" and report is None:+ coming = _diagnosis_coming(db) if coming is None else coming+ created = alert.created_at if alert.created_at.tzinfo else alert.created_at.replace(tzinfo=timezone.utc)+ if coming and now - created < DIAGNOSIS_WAIT:+ continue # checked again in 15 s; after DIAGNOSIS_WAIT it goes out without the diagnosis+ summary = _agent_summary(report) if event != "resolved" else Nonefor user_id, channels in by_user.items():preferences = _preferences(owners[user_id])routing = preferences["routing"].get(event, {})@@ -3028,6 +3079,8 @@ def dispatch_notifications(db, now: datetime | None = None) -> int:return senttitle = f"{'Resolved: ' if event == 'resolved' else ''}{alert.title}"body = f"{hostnames.get(alert.server_id, 'server')} · {alert.severity.lower()} · {incidents.reference(alert.id)}\n{alert.resolution or 'The condition cleared.' if event == 'resolved' else alert.description}"+ if summary and agent_settings.sees_diagnoses(db, owners[user_id].role):+ body += f"\nAgent: {summary}"for channel in wanted:sent += 1 if _deliver(db, channel, owners[user_id], title, body, "INFO" if event == "resolved" else alert.severity) else 0if event == "resolved":@@ -3079,6 +3132,8 @@ INVITE_TTL = timedelta(days=7)class UserUpdateRequest(BaseModel):role: Literal["admin", "user"] | None = Noneis_active: bool | None = None+ # Whether they may use the agent chat when chat access is "per user".+ agent_chat_enabled: bool | None = Noneclass InviteRequest(BaseModel):@@ -3098,10 +3153,11 @@ def _admin_users(db) -> dict:for account in db.query(User).order_by(User.id):users.append({"id": account.id, "name": account.name, "email": account.email, "role": account.role, "role_name": "Owner" if account.id == owner else "Admin" if account.role == "admin" else "Viewer","is_active": account.is_active, "two_factor": account.totp_enabled, "avatar_color": account.avatar_color, "sessions": len(list_user_sessions(redis_client, account.id, None)),- "last_seen_at": account.last_seen_at.isoformat() if account.last_seen_at else None, "created_at": account.created_at.isoformat()})+ "last_seen_at": account.last_seen_at.isoformat() if account.last_seen_at else None, "created_at": account.created_at.isoformat(), "agent_chat_enabled": account.agent_chat_enabled})invites = [{"id": invite.id, "email": invite.email, "role": invite.role, "created_at": invite.created_at.isoformat(), "expires_at": invite.expires_at.isoformat()}for invite in db.query(Invite).filter(Invite.used_at.is_(None), Invite.expires_at > now).order_by(Invite.created_at)]- return {"users": users, "invites": invites, "require_2fa_for_everyone": require_two_factor_for_everyone(db), "require_2fa_for_admins": require_admin_two_factor(db), "secrets_configured": secrets_box.available()}+ return {"users": users, "invites": invites, "require_2fa_for_everyone": require_two_factor_for_everyone(db), "require_2fa_for_admins": require_admin_two_factor(db), "secrets_configured": secrets_box.available(),+ "agent_chat_access": agent_settings.chat_access(db)}@app.get("/admin/users")@@ -3129,6 +3185,9 @@ def admin_update_user(user_id: PathId, payload: UserUpdateRequest, session_id: Aif payload.is_active is not None and payload.is_active != account.is_active:account.is_active = payload.is_activechanges.append("enabled" if payload.is_active else "disabled")+ if payload.agent_chat_enabled is not None and payload.agent_chat_enabled != account.agent_chat_enabled:+ account.agent_chat_enabled = payload.agent_chat_enabled+ record_audit_log(db, user_id=admin["id"], level="INFO", message=f"{'Allowed' if payload.agent_chat_enabled else 'Stopped'} agent chat for {account.email}", source="admin")db.commit()if changes:# A role in a live session would outlast the change, and a disabled account must be out at once.diff --git a/src/backend/models.py b/src/backend/models.pyindex 2bf7ad2..a30da8e 100644--- a/src/backend/models.py+++ b/src/backend/models.py@@ -28,6 +28,8 @@ class User(Base):avatar_color: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)# Display and notification choices, as checked JSON.preferences: Mapped[Optional[str]] = mapped_column(Text, nullable=True)+ # May use the chat with the incident agent when Admin sets chat access to "per user" (admins always may).+ agent_chat_enabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)last_seen_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True),@@ -347,6 +349,9 @@ class IncidentAlert(Base):# When the notifier handled its opening and its resolving, so each is sent once.notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)resolve_notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)+ # Set when the agent resolved it because its fix held: until then the same rule on this server opens no new+ # incident, so events still inside the rule's window don't reopen it (see src/agent/verify.py).+ reopen_after: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)class HostRollup(Base):diff --git a/src/frontend/src/admin/AdminPage.jsx b/src/frontend/src/admin/AdminPage.jsxindex fc3dac2..ff66156 100644--- a/src/frontend/src/admin/AdminPage.jsx+++ b/src/frontend/src/admin/AdminPage.jsx@@ -8,7 +8,7 @@ import { INTERVALS, intervalLabel } from '../dashboard/ServerPanel.jsx'import { serverState } from '../dashboard/logic.js'import { Sparkline } from '../dashboard/charts.jsx'import { usePolled } from '../dashboard/data.js'-import { Icon } from '../icons.jsx'+import { Caret, Icon } from '../icons.jsx'import { refreshOverview, useOverview } from '../overviewStore.js'import { AppShell, serverLink } from '../shell.jsx'import { ADMIN_GROUPS } from '../more/groups.js'@@ -131,7 +131,7 @@ function Users({ me }) {return (<div className="card overflow-hidden"><div className="custom-scroll overflow-x-auto"><table className="w-full min-w-[680px] border-collapse text-left text-[13px]">- <thead><tr className="grid-head h-10"><th className="pl-[18px] font-medium">User</th><th className="font-medium">Role</th><th className="font-medium">Two-factor</th><th className="font-medium">Last seen</th><th className="pr-[18px]" /></tr></thead>+ <thead><tr className="grid-head h-10"><th className="pl-[18px] font-medium">User</th><th className="font-medium">Role</th><th className="font-medium">Two-factor</th>{data.agent_chat_access === 'per_user' && <th className="font-medium">Agent chat</th>}<th className="font-medium">Last seen</th><th className="pr-[18px]" /></tr></thead><tbody>{data.users.map((user) => {const fixed = user.role_name === 'Owner' || user.id === me.id@@ -140,6 +140,7 @@ function Users({ me }) {<td className="pl-[18px]"><span className="flex items-center gap-3"><span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-line bg-raised text-[11px] font-semibold" style={{ color: user.avatar_color || undefined }}>{initials(user.name)}</span><span className="min-w-0"><span className="block truncate font-medium text-paper">{user.name}{user.id === me.id && <span className="ml-2 text-xs font-normal text-muted">you</span>}</span><span className="block truncate text-xs text-muted">{user.email}</span></span></span></td><td>{fixed ? <span className="text-paper">{user.role_name}</span> : <select className="select h-8" aria-label={`Role of ${user.name}`} value={user.role} onChange={(event) => change(user, { role: event.target.value })}><option value="admin">Admin</option><option value="user">Viewer</option></select>}</td><td><span className={`chip ${user.two_factor ? 'chip-ok' : ''}`}>{user.two_factor ? 'On' : 'Off'}</span></td>+ {data.agent_chat_access === 'per_user' && <td>{user.role === 'admin' ? <span className="text-xs text-muted">always</span> : <Switch label={`Agent chat for ${user.name}`} checked={user.agent_chat_enabled} disabled={state.busy} onChange={(on) => change(user, { agent_chat_enabled: on })} />}</td>}<td className="text-soft">{!user.is_active ? 'disabled' : user.sessions > 0 && user.id === me.id ? 'now' : ago(user.last_seen_at)}</td><td className="whitespace-nowrap pr-[18px] text-right">{!fixed && <>{user.sessions > 0 && <button type="button" className="link" onClick={() => run(async () => { await post(`/admin/users/${user.id}/sign-out`); reload() })}>Sign out</button>}@@ -151,7 +152,7 @@ function Users({ me }) {{data.invites.map((invite) => (<tr key={`invite-${invite.id}`} className="h-[54px] border-t border-line"><td className="pl-[18px]"><span className="flex items-center gap-3"><span className="flex h-7 w-7 items-center justify-center rounded-md border border-dashed border-edge text-[11px] text-muted">?</span><span><span className="block font-medium text-paper">Invite pending</span><span className="block text-xs text-muted">{invite.email} · made {ago(invite.created_at)}</span></span></span></td>- <td className="text-soft">{invite.role === 'admin' ? 'Admin' : 'Viewer'}</td><td className="text-muted">n/a</td><td className="text-muted">never</td>+ <td className="text-soft">{invite.role === 'admin' ? 'Admin' : 'Viewer'}</td><td className="text-muted">n/a</td>{data.agent_chat_access === 'per_user' && <td className="text-muted">off</td>}<td className="text-muted">never</td><td className="pr-[18px] text-right"><button type="button" className="link" onClick={() => run(async () => setData(await apiRequest(`/admin/invites/${invite.id}`, { method: 'DELETE' })))}>Cancel</button></td></tr>))}@@ -288,7 +289,13 @@ function Agent({ settings, system, onSaved }) {{(test.error || tested) && <div className="px-[18px] py-2.5">{test.error ? <p role="alert" className="m-0 text-xs text-warn">{test.error}</p> : <p role="status" className="m-0 text-xs text-ok">Connected. {tested.provider} accepts the key and offers {tested.model}.</p>}</div>}<Row title="Diagnose new incidents automatically" detail="When a warning or critical incident opens or gets worse, the agent worker sends its evidence (masked) to the model and writes a diagnosis. Off: incidents keep the rule-based diagnosis, and anyone who may act on incidents can still ask for one."><Switch label="Diagnose automatically" checked={settings.agent_auto_diagnose !== false} disabled={state.busy} onChange={(on) => run(async () => onSaved(await put({ agent_auto_diagnose: on })))} /></Row><Row title="Read container logs" detail="Not available: Infradeck's Docker proxy can't read logs. See SECURITY.md."><Switch label="Read container logs" checked={false} disabled onChange={() => {}} /></Row>- <Row title="Chat" detail="Available to every signed-in user while it is on. Questions and the incident's facts are sent to the provider."><Switch label="Chat with the agent" checked={settings.agent_chat_enabled} disabled={state.busy} onChange={(on) => run(async () => onSaved(await put({ agent_chat_enabled: on })))} /></Row>+ <Row title="Chat" detail="The main switch for the chat; who may use it is set under Chat access. Questions and the incident's facts are sent to the provider."><Switch label="Chat with the agent" checked={settings.agent_chat_enabled} disabled={state.busy} onChange={(on) => run(async () => onSaved(await put({ agent_chat_enabled: on })))} /></Row>+ <Row title="Chat access" detail={settings.agent_chat_access === 'per_user' ? 'Admins always; everyone else only with the Agent chat switch next to their name in Users.' : 'Only owners and admins can use the chat.'}>+ <select className="select" aria-label="Chat access" value={settings.agent_chat_access || 'admins_only'} disabled={state.busy} onChange={(event) => run(async () => onSaved(await put({ agent_chat_access: event.target.value })))}><option value="admins_only">Admins only</option><option value="per_user">Per user</option></select>+ </Row>+ <Row title="Show diagnoses to users" detail="Off: only owners and admins see the agent's diagnoses and their summary in notifications; everyone else sees the rule-based diagnosis.">+ <Switch label="Show diagnoses to users" checked={settings.agent_show_diagnoses_to_users !== false} disabled={state.busy} onChange={(on) => run(async () => onSaved(await put({ agent_show_diagnoses_to_users: on })))} />+ </Row><Row title="Redact IPs and hostnames before sending" detail="Not available yet. Until then, turn Chat off if names must not leave this machine."><Switch label="Redact before sending" checked={false} disabled onChange={() => {}} /></Row></div><Outcome state={state} />@@ -297,30 +304,43 @@ function Agent({ settings, system, onSaved }) {</>}-const JOB_TONE = { failed: 'chip-warn', noted: '', skipped: '', diagnosed: 'chip-ok' }+const JOB_TONE = { failed: 'chip-warn', noted: '', skipped: '', diagnosed: 'chip-ok', reused: 'chip-ok' }-// The worker that runs the agent's jobs: is it alive, what is waiting, and what it did last.+// The worker that runs the agent's jobs, in one line: is it alive, does anything wait, how did the last jobs go.+// The jobs themselves fold away; Redis keeps only the latest 50 and this shows at most 10.function AgentWorker() {const { data, error } = usePolled('/admin/agent/worker', 15)if (!data) return <Notice tone="plain">{error || 'Checking the agent worker…'}</Notice>const waiting = [data.queued ? `${data.queued} queued` : null, data.processing ? `${data.processing} running` : null, data.retrying ? `${data.retrying} waiting to retry` : null].filter(Boolean).join(' · ') || 'nothing waiting'+ const counts = {}+ for (const job of data.recent) counts[job.status] = (counts[job.status] || 0) + 1+ const failed = counts.failed || 0+ const last = data.recent[0]+ const lastLine = last ? `last job ${ago(last.finished_at)}: ${last.status} INC-${String(last.incident_id).padStart(4, '0')}` : 'no jobs yet'+ const detail = !data.online ? `Not running, so new incidents wait for their diagnosis · ${waiting}. Start it with docker compose up -d agent-worker.`+ : `Running since ${ago(data.worker.started_at).replace(' ago', '')} · ${waiting} · ${lastLine}${failed ? ` · ${failed} of the last ${data.recent.length} failed` : ''}`return (<div className="card overflow-hidden">- <Row icon="Q" title="Worker" tone={data.online ? undefined : 'warn'}- detail={data.online ? `Running since ${ago(data.worker.started_at).replace(' ago', '')} · ${waiting}` : `Not running, so new incidents wait for their diagnosis · ${waiting}. Start it with docker compose up -d agent-worker.`}>+ <Row icon="Q" title="Worker" tone={!data.online || failed ? 'warn' : undefined} detail={detail}><span className={`chip ${data.online ? 'chip-ok' : 'chip-warn'}`}>{data.online ? 'Online' : 'Offline'}</span></Row>- {data.recent.length > 0 && <ul className="m-0 list-none divide-y divide-line border-t border-line p-0">- {data.recent.slice(0, 5).map((job) => (- <li key={job.id} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 px-[18px] py-2.5 text-xs">- <span className="w-16 shrink-0 text-muted">{ago(job.finished_at)}</span>- <span className="mono shrink-0 text-soft">INC-{String(job.incident_id).padStart(4, '0')}</span>- <span className="shrink-0 text-muted">{job.type === 'incident.worsened' ? 'got worse' : job.type === 'incident.requested' ? 'asked for' : 'opened'}</span>- <span className={`chip ${JOB_TONE[job.status] ?? ''}`}>{job.status}</span>- <span className="min-w-0 flex-1 basis-60 text-muted">{job.note}</span>- </li>- ))}- </ul>}+ {data.recent.length > 0 && <details className="group border-t border-line">+ <summary className="flex cursor-pointer list-none items-center gap-2.5 px-[18px] py-2.5 text-xs text-muted hover:text-soft">+ <Caret open={false} className="transition-transform group-open:rotate-90" />+ Last {data.recent.length} {data.recent.length === 1 ? 'job' : 'jobs'}: {Object.entries(counts).map(([status, count]) => `${count} ${status}`).join(', ')}+ </summary>+ <ul className="m-0 list-none divide-y divide-line border-t border-line p-0">+ {data.recent.map((job) => (+ <li key={job.id} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 px-[18px] py-2.5 text-xs">+ <span className="w-16 shrink-0 text-muted">{ago(job.finished_at)}</span>+ <Link to={`/agent?incident=${job.incident_id}`} className="mono shrink-0 text-soft hover:text-paper">INC-{String(job.incident_id).padStart(4, '0')}</Link>+ <span className="shrink-0 text-muted">{job.type === 'incident.worsened' ? 'got worse' : job.type === 'incident.requested' ? 'asked for' : 'opened'}</span>+ <span className={`chip ${JOB_TONE[job.status] ?? ''}`}>{job.status}</span>+ <span className="min-w-0 flex-1 basis-60 text-muted">{job.note}</span>+ </li>+ ))}+ </ul>+ </details>}</div>)}diff --git a/src/frontend/src/agent/AgentPage.jsx b/src/frontend/src/agent/AgentPage.jsxindex ba1f4fc..d33c3a5 100644--- a/src/frontend/src/agent/AgentPage.jsx+++ b/src/frontend/src/agent/AgentPage.jsx@@ -85,17 +85,41 @@ function withReport(found, agent) {const CONFIDENCE_TONE = { high: 'chip-ok', medium: '', low: 'chip-warn' }// Who wrote what's below: the agent (which model, how sure, when) or the rules, and a way to ask for a new diagnosis.+const ASK_POLL_MS = 3000+const ASK_PATIENCE_MS = 3 * 60 * 1000+function AgentLine({ incident, canAct, onChanged, compact = false }) {const [state, run] = useAction()- const [asked, setAsked] = useState(false)+ // While a requested diagnosis is on its way: the report version it should replace, and when it was asked for.+ const [waiting, setWaiting] = useState(null)const agent = incident.agent || {}const report = agent.report+ const version = report?.version ?? 0+ const arrived = waiting !== null && version > waiting.version+ const asked = waiting !== null && !arrived+ const slow = asked && waiting.late++ // Look for the new report every few seconds until it is there, so it shows without reloading the page.+ useEffect(() => {+ if (!asked || waiting.late) return undefined // past the patience, the page's own 20 s refresh carries on+ const timer = setInterval(() => {+ onChanged()+ if (Date.now() - waiting.at > ASK_PATIENCE_MS) setWaiting((current) => (current ? { ...current, late: true } : current))+ }, ASK_POLL_MS)+ return () => clearInterval(timer)+ // onChanged is a new function each render; polling only follows the request.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [asked, waiting?.at, waiting?.late])+ useEffect(() => { if (arrived) setWaiting(null) }, [arrived])const resolved = incident.status === 'resolved'const canAsk = canAct && agent.key_configured && !agent.budget_pausedconst why = !agent.key_configured ? 'Set OPENAI_API_KEY in .env for the agent to diagnose incidents.' : agent.budget_paused ? 'This month\'s budget for the agent is used up.' : !canAct ? 'Only owners and admins can ask for a diagnosis.' : undefined- const ask = () => run(async () => { await post(`/incidents/${incident.id}/diagnose`); setAsked(true); setTimeout(onChanged, 15000) })+ const ask = () => run(async () => { await post(`/incidents/${incident.id}/diagnose`); setWaiting({ version, at: Date.now(), late: false }) })let text- if (asked) text = 'Asked the agent. The new diagnosis appears here when the worker gets to it, usually within a minute.'+ if (slow) text = 'Still waiting for the agent. It is taking longer than usual; the worker may be busy or stopped (Admin › Incident agent › Worker).'+ else if (asked) text = <span className="inline-flex items-center gap-2"><span className="spinner" />Asked the agent. The new diagnosis appears here as soon as it is ready, usually within a minute.</span>+ else if (agent.hidden) text = 'Below is the rule-based diagnosis. An admin has kept the agent\'s diagnoses to admins.'+ else if (report?.status === 'ok' && report.reused_from) text = <>Same problem as <Link className="link" to={`/agent?incident=${report.reused_from.incident_id}`}>{report.reused_from.reference}</Link> {formatAge(report.reused_from.created_at)} ago, so its diagnosis is reused and no tokens were spent · <span className="mono">{report.model}</span></>else if (report?.status === 'ok') text = <>Diagnosed by the agent · <span className="mono">{report.model}</span> · {formatAge(report.created_at)} ago{report.version > 1 ? ` · version ${report.version}` : ''}{report.dropped_signals ? ` · ${report.dropped_signals} unsupported ${report.dropped_signals === 1 ? 'claim' : 'claims'} left out` : ''}</>else if (report?.status === 'failed') text = `The agent couldn't diagnose this (${report.error}). Below is the rule-based diagnosis.`else text = incident.severity === 'INFO' ? 'A note, not a problem: the agent only diagnoses warnings and critical incidents.' : 'The agent hasn\'t diagnosed this yet. Below is the rule-based diagnosis, worked out from the same data.'@@ -105,6 +129,9 @@ function AgentLine({ incident, canAct, onChanged, compact = false }) {<span className="min-w-0 flex-1 basis-48">{text}</span>{report?.status === 'ok' && <span className={`chip ${CONFIDENCE_TONE[report.confidence] || ''}`}>{report.confidence} confidence</span>}{!resolved && incident.severity !== 'INFO' && <button type="button" className="btn btn-sm" disabled={!canAsk || state.busy || asked} title={why} onClick={ask}>{report ? 'Diagnose again' : 'Diagnose now'}</button>}+ {report?.watch && !asked && <span className="basis-full text-soft">{report.watch.known+ ? <>Watching: resolves itself once {report.watch.text}. {report.watch.held_minutes >= 1 ? `Held for ${Math.floor(report.watch.held_minutes)} of ${report.watch.minutes} min.` : 'Not holding yet.'}</>+ : <>Watching for {report.watch.text}, but there is no recent data to judge it by.</>}</span>}{state.error && <span role="alert" className="basis-full text-warn">{state.error}</span>}</div>)@@ -456,6 +483,7 @@ export default function AgentPage({ user, onLogout }) {const crumbs = selected ? [{ label: 'Agent', to: '/agent' }, { label: selected.reference }] : [{ label: 'Agent' }]// Why the chat can't be used right now, or null when it can.const chatOff = !config ? null : !config.chat_enabled ? 'Chat with the agent has been turned off by an admin.'+ : config.may_chat === false ? 'Chat with the agent is for admins. An admin can allow it for you in Admin › Users.': config.key_configured === false ? 'The agent has no API key yet. An admin sets OPENAI_API_KEY in .env.': config.budget_paused ? 'This month\'s budget for the agent is used up. An admin can raise it in Admin › Incident agent.' : nulldiff --git a/tests/accounts/test_admin.py b/tests/accounts/test_admin.pyindex e9b98c1..b056006 100644--- a/tests/accounts/test_admin.py+++ b/tests/accounts/test_admin.py@@ -155,7 +155,8 @@ def test_admin_can_turn_agent_chat_off_and_on(fleet, monkeypatch):result = main.update_admin_settings(main.AdminSettingsRequest(agent_chat_enabled=False), session_id="s", db=fleet)assert result == {"instance_name": main.get_instance_name(fleet), "metrics_retention_days": main.DEFAULT_METRICS_RETENTION_DAYS, "agent_chat_enabled": False, "alert_thresholds": rules.DEFAULT_THRESHOLDS, "mount_thresholds": {}, "require_2fa_for_admins": True, "secrets_configured": main.secrets_box.available(), "require_2fa_for_everyone": False, "disabled_rules": [],- "agent_prices": {}, "agent_monthly_cap_usd": None, "agent_daily_chat_limit": main.agent_usage.DEFAULT_DAILY_CHAT_LIMIT, "agent_auto_diagnose": True}+ "agent_prices": {}, "agent_monthly_cap_usd": None, "agent_daily_chat_limit": main.agent_usage.DEFAULT_DAILY_CHAT_LIMIT, "agent_auto_diagnose": True,+ "agent_show_diagnoses_to_users": True, "agent_chat_access": "admins_only"}_login_as(monkeypatch, 2)config = main.agent_config(session_id="s", db=fleet)assert config["chat_enabled"] is False and config["budget_paused"] is Falsediff --git a/tests/accounts/test_new_pages.py b/tests/accounts/test_new_pages.pyindex 6432642..6cc5c4a 100644--- a/tests/accounts/test_new_pages.py+++ b/tests/accounts/test_new_pages.py@@ -503,3 +503,76 @@ def test_asking_for_a_new_diagnosis_queues_a_job(app, monkeypatch):queued = [json.loads(raw) for raw in app.redis.lrange(jobs.QUEUE, 0, -1)]assert [(job["type"], job["incident_id"]) for job in queued] == [("incident.requested", 42)] * 2assert signed_in(app, 3).post("/incidents/42/diagnose").status_code == 403+++# --- the agent in notifications, who sees diagnoses, who may chat (#120, #121, #124) -----------------------------++def _report(app, incident_id=42, summary="gitlab is killed for memory after the update. Its limit is 4 GB. A third sentence."):+ from src.backend.models import AgentReport+ app.db.add(AgentReport(incident_id=incident_id, version=1, trigger="incident.opened", status="ok", model="gpt-test", confidence="high", summary=summary,+ body=json.dumps({"signals": [], "fix_steps": [], "verify": {"type": "manual"}, "dropped_signals": 0}), evidence="{}"))+ app.db.commit()+++def test_a_notification_waits_for_the_diagnosis_and_carries_it(app, outbox, monkeypatch):+ monkeypatch.setattr(main, "_diagnosis_coming", lambda db: True)+ signed_in(app, 1).post("/account/channels", json={"kind": "ntfy", "target": "https://ntfy.example/t"})+ for incident_id in (42, 43):+ app.db.get(IncidentAlert, incident_id).created_at = datetime.now(timezone.utc) - timedelta(seconds=20)+ app.db.commit()++ assert main.dispatch_notifications(app.db) == 0 # both incidents are new: wait for the agent+ _report(app)+ assert main.dispatch_notifications(app.db) == 1 # INC-0042's diagnosis is in; INC-0043 still waits+ assert b"Agent: gitlab is killed for memory after the update. Its limit is 4 GB." in outbox[-1][1] and b"third" not in outbox[-1][1]+++def test_after_three_minutes_it_goes_out_without_the_diagnosis(app, outbox, monkeypatch):+ monkeypatch.setattr(main, "_diagnosis_coming", lambda db: True)+ signed_in(app, 1).post("/account/channels", json={"kind": "ntfy", "target": "https://ntfy.example/t"})+ for incident_id in (42, 43):+ app.db.get(IncidentAlert, incident_id).created_at = NOW - timedelta(seconds=20)+ app.db.commit()++ assert main.dispatch_notifications(app.db, now=NOW + timedelta(seconds=30)) == 0+ assert main.dispatch_notifications(app.db, now=NOW + timedelta(minutes=4)) == 2+ assert all(b"Agent:" not in message[1] for message in outbox)+++def test_without_a_diagnosis_on_the_way_nothing_waits(app, outbox):+ signed_in(app, 1).post("/account/channels", json={"kind": "ntfy", "target": "https://ntfy.example/t"})++ assert main.dispatch_notifications(app.db) == 2 # no key in tests, so no diagnosis is coming+++def test_hidden_diagnoses_stay_hidden_from_users_in_the_page_the_overview_and_notifications(app, outbox):+ _report(app)+ owner, viewer = signed_in(app, 1), signed_in(app, 3)+ viewer.post("/account/channels", json={"kind": "ntfy", "target": "https://ntfy.example/v"})+ assert owner.put("/admin/settings", json={"agent_show_diagnoses_to_users": False}).json()["agent_show_diagnoses_to_users"] is False++ seen = viewer.get("/incidents/42").json()["agent"]+ assert seen["report"] is None and seen["hidden"] is True+ assert owner.get("/incidents/42").json()["agent"]["report"]["summary"].startswith("gitlab") # admins always see it+ note = next(alert for alert in viewer.get("/monitoring/overview").json()["alerts"] if alert["id"] == 42)["agent_note"]+ assert note is None or not note.startswith("gitlab is killed")+ main.dispatch_notifications(app.db)+ assert outbox and all(b"Agent:" not in message[1] for message in outbox)+++def test_chat_is_for_admins_unless_allowed_per_user(app, monkeypatch):+ monkeypatch.setattr(main, "send_agent_message", lambda *args, **kwargs: "ok")+ monkeypatch.setattr(main, "is_agent_chat_enabled", lambda db: True)+ owner, viewer = signed_in(app, 1), signed_in(app, 3)+ viewer.post("/conversations", json={"conversation_id": "v1"})+ ask = lambda: viewer.post("/agent/chat", json={"conversation_id": "v1", "message": "hi"}) # noqa: E731++ assert ask().status_code == 403 and viewer.get("/agent/config").json()["may_chat"] is False # admins only, the default+ owner.put("/admin/settings", json={"agent_chat_access": "per_user"})+ assert ask().status_code == 403 # per user, but not allowed yet+ users = owner.patch("/admin/users/3", json={"agent_chat_enabled": True}).json()+ assert next(user for user in users["users"] if user["id"] == 3)["agent_chat_enabled"] is True and users["agent_chat_access"] == "per_user"+ assert ask().status_code == 200 and viewer.get("/agent/config").json()["may_chat"] is True+ owner.put("/admin/settings", json={"agent_chat_access": "admins_only"})+ assert ask().status_code == 403 # admins only wins over the per-user switch+ assert owner.put("/admin/settings", json={"agent_chat_access": "everyone"}).status_code == 422diff --git a/tests/assistant/test_agent_watch.py b/tests/assistant/test_agent_watch.pynew file mode 100644index 0000000..202b440--- /dev/null+++ b/tests/assistant/test_agent_watch.py@@ -0,0 +1,155 @@+"""Reusing a recent diagnosis (#126) and watching the fix it gave until it holds (#125)."""+import json+from datetime import datetime, timedelta, timezone++import pytest+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker+from sqlalchemy.pool import StaticPool++from src.agent import diagnosis, verify, worker+from src.backend import alerts+from src.backend.models import AgentReport, AgentRun, Base, ContainerMetric, HostMetric, IncidentAlert, Server++NOW = datetime.now(timezone.utc)+++def db():+ engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ session.add(Server(id=1, owner_id=1, hostname="alpha", cpu_cores=4, total_ram_gb=16.0, check_interval_seconds=60, last_seen_at=NOW))+ session.add(IncidentAlert(id=31, server_id=1, severity="CRITICAL", title="gitlab restart loop", description="d", status="resolved", rule_key="container:gitlab:restart_loop",+ created_at=NOW - timedelta(hours=5), resolved_at=NOW - timedelta(hours=4)))+ session.add(IncidentAlert(id=42, server_id=1, severity="CRITICAL", title="gitlab restart loop", description="d", status="active", rule_key="container:gitlab:restart_loop", created_at=NOW - timedelta(minutes=30)))+ session.commit()+ yield session+ session.close()+++def add_report(db, incident_id, verify_condition=None, created_at=None):+ body = {"signals": [{"text": "Memory hits the limit.", "holds": True, "evidence": [{"id": "metric:main", "label": "container memory"}]}], "fix_steps": [],+ "verify": verify_condition or {"type": "manual", "target": None, "threshold": None, "minutes": None}, "dropped_signals": 0}+ version = db.query(AgentReport).filter(AgentReport.incident_id == incident_id).count() + 1+ db.add(AgentReport(incident_id=incident_id, version=version, trigger="incident.opened", status="ok", model="gpt-test", confidence="high", summary="Killed for memory.",+ body=json.dumps(body), evidence="{}", created_at=created_at or NOW))+ db.commit()+++def container_samples(db, minutes, restarts=lambda minute: 6, status=lambda minute: "running"):+ for minute in range(minutes, -1, -1):+ db.add(ContainerMetric(server_id=1, container_id="g" * 64, name="gitlab", status=status(minute), restart_count=restarts(minute), memory_used_mb=1000, time=NOW - timedelta(minutes=minute)))+ db.commit()+++# --- reuse (#126) -----------------------------------------------------------------------------------------------++def test_the_same_problem_within_a_day_reuses_the_diagnosis(db):+ add_report(db, 31, created_at=NOW - timedelta(hours=5))++ copy = diagnosis.reuse_recent(db, db.get(IncidentAlert, 42), NOW)++ shown = diagnosis.report_json(copy)+ assert copy.trigger == "reused" and shown["summary"] == "Killed for memory." and shown["reused_from"]["reference"] == "INC-0031"+ assert db.query(AgentRun).count() == 0 # no tokens spent+++def test_an_older_or_different_diagnosis_is_not_reused(db):+ add_report(db, 31, created_at=NOW - timedelta(hours=25))+ assert diagnosis.reuse_recent(db, db.get(IncidentAlert, 42), NOW) is None++ db.add(IncidentAlert(id=50, server_id=1, severity="CRITICAL", title="redis restart loop", description="d", status="active", rule_key="container:redis:restart_loop"))+ db.commit()+ add_report(db, 31, created_at=NOW - timedelta(hours=1))+ assert diagnosis.reuse_recent(db, db.get(IncidentAlert, 50), NOW) is None # another container+++def test_the_worker_reuses_before_asking_the_model(db, monkeypatch):+ add_report(db, 31, created_at=NOW - timedelta(hours=1))+ monkeypatch.setattr(worker, "SessionLocal", lambda: db)+ monkeypatch.setattr(db, "close", lambda: None)+ monkeypatch.setattr(worker, "configured_key", lambda: "sk-test")+ monkeypatch.setattr(worker, "get_provider", lambda: pytest.fail("the model must not be asked"))++ assert worker.handle_incident({"incident_id": 42, "type": "incident.opened"}) == ("reused", "Same diagnosis as INC-0031; no tokens spent")+++def test_getting_worse_or_asking_again_is_never_reused(db, monkeypatch):+ add_report(db, 31, created_at=NOW - timedelta(hours=1))+ asked = []+ monkeypatch.setattr(worker, "SessionLocal", lambda: db)+ monkeypatch.setattr(db, "close", lambda: None)+ monkeypatch.setattr(worker, "configured_key", lambda: "sk-test")+ monkeypatch.setattr(worker.diagnosis, "diagnose", lambda db, incident, provider, trigger: asked.append(trigger) or AgentReport(status="failed", error="x"))+ monkeypatch.setattr(worker, "get_provider", lambda: object())++ worker.handle_incident({"incident_id": 42, "type": "incident.worsened"})+ worker.handle_incident({"incident_id": 42, "type": "incident.requested"})+ assert asked == ["incident.worsened", "incident.requested"]+++# --- watching (#125) --------------------------------------------------------------------------------------------++RUNNING_15 = {"type": "container_running_for", "target": "gitlab", "threshold": None, "minutes": 15}+++def test_a_container_that_ran_long_enough_without_restarting_resolves_the_incident(db):+ add_report(db, 42, RUNNING_15)+ container_samples(db, 20, restarts=lambda minute: 5 if minute > 18 else 6)++ result = verify.evaluate(db, db.get(IncidentAlert, 42), RUNNING_15, NOW)+ assert result["holds"] and result["held_minutes"] == 18 and result["text"] == "gitlab runs 15 min without a restart"+ assert verify.watch(db, NOW)["resolved"] == [42]+ incident = db.get(IncidentAlert, 42)+ assert incident.status == "resolved" and incident.resolution == "Resolved by the agent: gitlab runs 15 min without a restart" and incident.reopen_after is not None+++def test_a_recent_restart_keeps_it_open_and_shows_progress(db):+ add_report(db, 42, RUNNING_15)+ container_samples(db, 20, restarts=lambda minute: 5 if minute > 6 else 6)++ result = verify.evaluate(db, db.get(IncidentAlert, 42), RUNNING_15, NOW)+ assert not result["holds"] and result["held_minutes"] == 6+ assert verify.watch(db, NOW)["resolved"] == []+++def test_old_data_is_not_proof(db):+ add_report(db, 42, RUNNING_15)+ for minute in range(60, 30, -1):+ db.add(ContainerMetric(server_id=1, container_id="g" * 64, name="gitlab", status="running", restart_count=6, time=NOW - timedelta(minutes=minute)))+ db.commit()++ result = verify.evaluate(db, db.get(IncidentAlert, 42), RUNNING_15, NOW)+ assert result["known"] is False and result["holds"] is False+++def test_a_metric_under_its_threshold_long_enough_holds(db):+ db.add(IncidentAlert(id=60, server_id=1, severity="WARNING", title="memory", description="d", status="active", rule_key="host:memory"))+ for minute in range(30, -1, -1):+ db.add(HostMetric(server_id=1, time=NOW - timedelta(minutes=minute), ram_pct=95 if minute > 12 else 70))+ db.commit()+ condition = {"type": "metric_below_for", "target": "metric:main", "threshold": 80, "minutes": 10, "label": "memory in use"}++ result = verify.evaluate(db, db.get(IncidentAlert, 60), condition, NOW)+ assert result["holds"] and result["text"] == "memory in use stays under 80 for 10 min"+++def test_the_rule_does_not_reopen_what_the_agent_closed_until_the_hold_ends_or_it_breaks(db):+ add_report(db, 42, RUNNING_15)+ container_samples(db, 20)+ verify.watch(db, NOW)++ assert alerts.raise_alert(db, 1, "container:gitlab:restart_loop", "CRITICAL", "gitlab restart loop", "d") is False # old restarts still in the window+ db.add(ContainerMetric(server_id=1, container_id="g" * 64, name="gitlab", status="restarting", restart_count=7, time=NOW + timedelta(seconds=30)))+ db.commit()+ assert verify.watch(db, NOW + timedelta(minutes=1))["released"] == [42]+ assert alerts.raise_alert(db, 1, "container:gitlab:restart_loop", "CRITICAL", "gitlab restart loop", "d") is True # a real new restart opens one+++def test_manual_conditions_are_not_watched(db):+ add_report(db, 42)+ container_samples(db, 20)++ assert verify.evaluate(db, db.get(IncidentAlert, 42), {"type": "manual"}, NOW) is None+ assert verify.watch(db, NOW)["resolved"] == []diff --git a/tests/security/test_second_review.py b/tests/security/test_second_review.pyindex 4043c73..b7f455e 100644--- a/tests/security/test_second_review.py+++ b/tests/security/test_second_review.py@@ -46,6 +46,7 @@ def app(monkeypatch):monkeypatch.setenv("SECRETS_KEY", Fernet.generate_key().decode())monkeypatch.setattr(main, "send_agent_message", lambda *args, **kwargs: "ok")monkeypatch.setattr(main, "is_agent_chat_enabled", lambda db: True)+ monkeypatch.setattr(main.agent_settings, "may_chat", lambda db, user: True) # chat access has its own testsclient = TestClient(main.app, raise_server_exceptions=False)client.Session, client.redis = Session, redisyield client