Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

alerts: offer manual targeted Patrol check from the alert AI button

rcourtmandd2f4c07fe9f
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index cd04611dbc..455cd7e8a6 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -586,6 +586,14 @@ instead of lifecycle-local centered icon/text shells.
## Extension Points
+Manual scoped Patrol work that reaches `internal/api/ai_handlers.go` (such as an
+alert-initiated targeted Patrol check via `POST /api/ai/patrol/run`) is
+investigation-only over agent-reporting resources: it must not alter agent
+lifecycle, registration, token binding, reporting contracts, or install-command
+identity. The scoped Patrol request carries resource identity only and reuses
+the existing Patrol scoped engine, so it adds no agent lifecycle control
+surface and no new `internal/api/` lifecycle handler.
+
1. Add or change install-command generation, canonical /api/auto-register behavior, or installer download behavior through the owned `internal/api/` files above.
Canonical `/api/auto-register` auth is split by intent: when the setup-token
bootstrap path succeeds, lifecycle clients must complete registration with
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index e86cc27e60..11479741ae 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -438,6 +438,18 @@ component-local required-scope list.
## Extension Points
+The manual Patrol route is an extension boundary for scoped work. `POST
+/api/ai/patrol/run` (`HandleForcePatrol`) accepts an optional scope body
+(`resource_ids` and/or `resource_types`, plus optional `alert_identifier`,
+`alert_type`, and `context`) to run a manual Targeted check through the same
+`TriggerScopedPatrol` engine and scoped run record as automatic alert-triggered
+work; with no body it keeps the fleet-wide Patrol check. The scoped path must
+reuse the existing scoped engine rather than adding a parallel trigger route,
+honour the same Patrol readiness gate as a full run, bypass the full-run
+cadence gate (targeted checks never consume a manual full-run allowance), and
+carry resource identity only — no command, prompt, or remediation payload —
+while the route keeps requiring admin plus `ai:execute` scope for both shapes.
+
Pulse Intelligence presents Patrol as the primary first-party operations
surface. Pulse Assistant is the in-app contextual explanation, approval-card,
governed-action, verification, and handoff access path over Patrol work.
@@ -5031,6 +5043,19 @@ full-patrol cadence gates. Community-tier or other full-run limits must key
off completed full sweeps only; recent scoped or verification activity may
advance `last_activity_at`, but it must not block a manual full Patrol request
as if a scheduled estate-wide sweep already happened.
+The manual Patrol route carries that same scoped/full distinction. `POST
+/api/ai/patrol/run` (`internal/api/ai_handlers.go` `HandleForcePatrol`) accepts
+an optional scope body — `resource_ids` and/or `resource_types`, optionally with
+`alert_identifier`, `alert_type`, and `context`. With a scope it runs a manual
+Targeted check through the same scoped engine (`TriggerScopedPatrol`) and run
+record (`Type: "scoped"`) as automatic alert-triggered work, not a new
+investigation path; without a body it keeps the legacy fleet-wide Patrol check
+behaviour. A manual scoped run must reuse the existing scoped engine rather
+than adding a parallel trigger route, must honour the same Patrol readiness gate
+as a full run, and must bypass the full-run cadence gate because targeted
+checks never consume an operator's manual full-run allowance. The request must
+carry resource identity only — no command, prompt, or remediation payload — and
+the route must keep requiring admin plus `ai:execute` scope for both shapes.
The Patrol startup scheduler must preserve that coverage guarantee as well:
`internal/ai/patrol_run.go` may skip the startup full patrol only when recent
run history already includes a successful full Patrol run, not merely because
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index 2e1c9e288f..df892bda7e 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -131,7 +131,11 @@ inline SVG shells in alert-owned runtime components.
references through the shared Assistant chat transport, and render a compact
Alerts-owned briefing in the Assistant drawer without transferring raw
command payloads or synthesizing, pre-filling, or auto-submitting a chat
- prompt.
+ prompt. The same button may additionally offer a manual scoped Patrol
+ trigger (for example a "Have Patrol investigate" menu action); that option is
+ a Patrol trigger governed by the `ai-runtime` manual Patrol route contract,
+ not an Assistant handoff, and must stay distinct from the context-only
+ Assistant open path above.
8. Add or change Pulse Assistant incident timeline handoffs through
`frontend-modern/src/components/Alerts/IncidentAssistantHandoffButton.tsx`
and `frontend-modern/src/components/Alerts/incidentAssistantHandoffModel.ts`;
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 0971a799d8..4161e0acfe 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -814,6 +814,11 @@ payload shape change when the portal presents compact client rows.
`/api/ai/patrol/run` must use the `patrol_readiness_not_ready` error taxonomy
when it rejects a known-bad Patrol runtime configuration. Bounded `status`,
`cause`, `provider`, and `model` details are the canonical transport shape.
+ When the request body carries `resource_ids` or `resource_types`,
+ `/api/ai/patrol/run` runs a manual targeted Patrol check scoped to those
+ resources (reusing the scoped engine and scoped run record, bypassing the
+ full-run cadence gate); an empty body keeps the fleet-wide run. The scoped
+ body carries resource identity only — no command or remediation payload.
Patrol may demote the shared model catalog behind an explicit advanced UI
action, but it must still source selectable model routes from the shared AI
runtime catalog/settings payloads rather than introducing a Patrol-local
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 41526f0984..d4dc87189d 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -198,7 +198,10 @@ first-wave non-translatable token rules. The active app locale is a shared user
preference initialized from stored or browser language and exposed through
Settings > General; individual surfaces must consume that shared preference
instead of creating local language toggles. Customer-facing shell, navigation,
-settings, first-run, empty-state, and alert copy may be localized, but
+settings, first-run, empty-state, and alert copy may be localized through this
+catalog — including the alert-to-Patrol action surface ("Have Patrol
+investigate" and its targeted-check menu hint) that sits alongside the
+Assistant handoff strings — but
machine-facing values must remain stable: commands, environment variables, API
fields, config keys, log lines, error codes, hostnames, resource names, product
identifiers, and vendor object names stay untranslated unless the owning
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index b79b692347..8dc3777981 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -330,6 +330,12 @@ attention`, `approval needed`, `outcome verified`, `no active work`) instead
terminology where needed for cadence, audit, or API stability, but the
default page must not ask ordinary operators to learn those internal proof
distinctions before they can decide what to do next.
+ A manual scoped Patrol request — such as an alert's "Have Patrol
+ investigate" action — is one of those Targeted checks, not a new run kind:
+ it must reuse the same scoped engine, run record, and run-history vocabulary
+ as automatic alert-triggered work (governed by the `ai-runtime` manual Patrol
+ route contract), so the operator still sees a `Targeted check` rather than a
+ route-specific label.
Active Patrol finding expansion must stay action-led: description, impact,
recurrence summary, primary action, Assistant handoff, approval, and manual
controls are acceptable default content, but raw lifecycle telemetry belongs
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 52e3fc7b34..e97ab7ac5e 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -150,6 +150,14 @@ controls as normal product settings.
17. `internal/cloudcp/auth/magiclink_store.go` shared with `cloud-paid`: control-plane magic-link persistence is both a Pulse Cloud account-access boundary and a security/privacy storage-hardening boundary.
## Extension Points
+Catalog edits in `frontend-modern/src/i18n/` that add Patrol-trigger copy (such
+as an alert's "Have Patrol investigate" action) must stay non-disclosing: the
+manual Patrol trigger carries resource identity only — resource ids plus alert
+identifier/type — and injects no operator briefing, command, prompt, or
+remediation payload into the model beyond the existing scoped-investigation
+context, so it adds no new disclosure surface and the existing resource-policy
+redaction still governs any model-bound context.
+
1. Change privacy disclosures, usage-data vocabulary, or outbound-data guarantees through `docs/PRIVACY.md`, `frontend-modern/public/docs/PRIVACY.md`, `internal/telemetry/telemetry.go`, and `pkg/server/telemetry_pulse_intelligence.go` together.
Pulse Intelligence external-agent/MCP telemetry may expose only content-free
adapter-origin usage and capability-class counters for context, event
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 236c5b6529..1718aed012 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -81,7 +81,10 @@ storage/recovery-adjacent only through the shared action-audit and verification
projection. Sibling handlers in `internal/api/` such as the AI settings handler
(`ai_handlers.go`) carry AI provider configuration (for example per-provider
base URL overrides) that is ai-runtime config-surface, not storage or recovery
-state. Starter counts, contextual Assistant/external-agent collaboration
+state; a manual scoped Patrol check routed through this handler is
+investigate-only as well (it may analyze storage resources but invokes no
+backup, restore, SMART, or recovery operation, and carries resource identity
+only). Starter counts, contextual Assistant/external-agent collaboration
counts, Patrol control completed-loop or resolved-loop outcome evidence,
`patrolControlValueState`, legacy `patrolAutonomy*` compatibility aliases, and
the operator-readable `progressLabel` on that
diff --git a/frontend-modern/src/api/__tests__/patrol.test.ts b/frontend-modern/src/api/__tests__/patrol.test.ts
index 622a3b7e89..1f974d7431 100644
--- a/frontend-modern/src/api/__tests__/patrol.test.ts
+++ b/frontend-modern/src/api/__tests__/patrol.test.ts
@@ -1,434 +1,40 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { triggerPatrolRun } from '../patrol';
+
+const fetchMock = vi.hoisted(() => vi.fn());
vi.mock('@/utils/apiClient', () => ({
- apiFetchJSON: vi.fn(),
+ apiFetchJSON: (...args: unknown[]) => fetchMock(...(args as [unknown, unknown])),
}));
-import {
- getPatrolStatus,
- getPatrolRun,
- getPatrolFindings,
- getPatrolRunHistory,
- getPatrolRunHistoryWithToolCalls,
- getPatrolRunWithToolCalls,
- createSuppressionRuleFromFinding,
- resolveFinding,
- type Finding as PatrolFinding,
-} from '@/api/patrol';
-import { apiFetchJSON } from '@/utils/apiClient';
-
-describe('patrol api', () => {
- const apiFetchJSONMock = vi.mocked(apiFetchJSON);
-
+describe('triggerPatrolRun scope body', () => {
beforeEach(() => {
- apiFetchJSONMock.mockReset();
- apiFetchJSONMock.mockResolvedValue([] as any);
- });
-
- it('normalizes invalid limits for patrol history queries', async () => {
- await getPatrolRunHistory(Number.POSITIVE_INFINITY);
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/runs?limit=30');
-
- await getPatrolRunHistory(0);
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/runs?limit=30');
-
- await getPatrolRunHistory(-5);
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/runs?limit=30');
- });
-
- it('caps oversized patrol history limits to the backend maximum', async () => {
- await getPatrolRunHistory(101);
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/runs?limit=100');
-
- await getPatrolRunHistoryWithToolCalls(999);
- expect(apiFetchJSONMock).toHaveBeenCalledWith(
- '/api/ai/patrol/runs?include=tool_calls&limit=100',
- );
- });
-
- it('builds tool-call history query with normalized limit', async () => {
- await getPatrolRunHistoryWithToolCalls(25.9);
- expect(apiFetchJSONMock).toHaveBeenCalledWith(
- '/api/ai/patrol/runs?include=tool_calls&limit=25',
- );
- });
-
- it('fetches a single patrol run by id', async () => {
- await getPatrolRun('run/25');
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/runs/run%2F25');
-
- await getPatrolRunWithToolCalls('run/25');
- expect(apiFetchJSONMock).toHaveBeenCalledWith(
- '/api/ai/patrol/runs/run%2F25?include=tool_calls',
- );
- });
-
- it('preserves the canonical patrol runtime state payload', async () => {
- apiFetchJSONMock.mockResolvedValueOnce({
- runtime_state: 'blocked',
- blocked_reason: 'Connect a provider to power Pulse Assistant and Patrol.',
- blocked_cause: 'provider_not_configured',
- healthy: false,
- readiness: {
- status: 'not_ready',
- ready: false,
- cause: 'model_unsupported_tools',
- summary:
- 'The selected Patrol model is a reasoning-only model family that commonly does not emit tool calls.',
- provider: 'ollama',
- model: 'ollama:deepseek-r1:7b-llama-distill-q4_K_M',
- checks: [
- {
- id: 'tools',
- status: 'not_ready',
- cause: 'model_unsupported_tools',
- label: 'Patrol tools',
- message:
- 'The selected Patrol model is a reasoning-only model family that commonly does not emit tool calls.',
- action: 'open_provider_settings',
- },
- ],
- },
- } as any);
-
- await expect(getPatrolStatus()).resolves.toMatchObject({
- runtime_state: 'blocked',
- blocked_reason: 'Connect a provider to power Pulse Assistant and Patrol.',
- blocked_cause: 'provider_not_configured',
- healthy: false,
- readiness: {
- status: 'not_ready',
- ready: false,
- cause: 'model_unsupported_tools',
- provider: 'ollama',
- model: 'ollama:deepseek-r1:7b-llama-distill-q4_K_M',
- checks: [
- {
- id: 'tools',
- status: 'not_ready',
- cause: 'model_unsupported_tools',
- action: 'open_provider_settings',
- },
- ],
- },
- });
+ fetchMock.mockReset();
+ fetchMock.mockResolvedValue({ success: true, message: 'Triggered targeted Patrol check' });
});
- it('preserves split patrol recency transport fields', async () => {
- apiFetchJSONMock.mockResolvedValueOnce({
- runtime_state: 'active',
- healthy: true,
- last_patrol_at: '2026-03-12T09:30:00Z',
- last_activity_at: '2026-03-12T09:59:00Z',
- trigger_status: {
- running: true,
- pending_triggers: 2,
- current_interval_ms: 300000,
- recent_events: 6,
- is_busy_mode: true,
- alert_triggers_enabled: true,
- anomaly_triggers_enabled: false,
- event_triggers_blocked: true,
- event_triggers_blocked_reason: 'background_automation_disabled',
- event_triggers_blocked_message:
- 'Automatic Patrol checks from alerts and anomalies are paused by the local development safety guard. Manual Patrol still works.',
- },
- } as any);
-
- await expect(getPatrolStatus()).resolves.toMatchObject({
- runtime_state: 'active',
- healthy: true,
- last_patrol_at: '2026-03-12T09:30:00Z',
- last_activity_at: '2026-03-12T09:59:00Z',
- trigger_status: {
- pending_triggers: 2,
- is_busy_mode: true,
- anomaly_triggers_enabled: false,
- event_triggers_blocked: true,
- event_triggers_blocked_reason: 'background_automation_disabled',
- },
- });
- });
-
- it('normalizes patrol run alert identifiers', async () => {
- apiFetchJSONMock.mockResolvedValueOnce([
- {
- id: 'run-1',
- started_at: '2026-03-01T00:00:00Z',
- completed_at: '2026-03-01T00:01:00Z',
- duration_ms: 60000,
- type: 'patrol',
- resources_checked: 1,
- nodes_checked: 0,
- guests_checked: 0,
- docker_checked: 0,
- storage_checked: 0,
- hosts_checked: 0,
- truenas_checked: 1,
- pbs_checked: 0,
- pmg_checked: 0,
- kubernetes_checked: 0,
- new_findings: 0,
- existing_findings: 0,
- rejected_findings: 0,
- resolved_findings: 0,
- findings_summary: 'ok',
- finding_ids: [],
- error_count: 0,
- status: 'healthy',
- error_summary: 'Selected model does not support Patrol tools',
- error_detail: 'provider rejected tool_choice',
- triage_flags: 2,
- triage_skipped_llm: true,
- tool_call_count: 0,
- alert_identifier: 'canonical-alert-1',
- effective_scope_resource_ids: ['resource-1', 'resource-2'],
- },
- ] as any);
-
- const result = await getPatrolRunHistory();
-
- expect(result[0]).toMatchObject({
- alertIdentifier: 'canonical-alert-1',
- effective_scope_resource_ids: ['resource-1', 'resource-2'],
- truenas_checked: 1,
- error_summary: 'Selected model does not support Patrol tools',
- error_detail: 'provider rejected tool_choice',
- triage_flags: 2,
- triage_skipped_llm: true,
- });
+ it('sends no body for a fleet-wide run', async () => {
+ await triggerPatrolRun();
+ expect(fetchMock).toHaveBeenCalledWith('/api/ai/patrol/run', { method: 'POST' });
});
- it('fetches direct Patrol findings and preserves canonical alert identity', async () => {
- apiFetchJSONMock.mockResolvedValueOnce([
- {
- id: 'finding-1',
- severity: 'warning',
- category: 'reliability',
- resource_id: 'instance:node:100',
- resource_name: 'vm-100',
- resource_type: 'vm',
- title: 'Provider connection issue',
- description: 'Patrol could not complete provider analysis.',
- detected_at: '2026-03-01T00:00:00Z',
- last_seen_at: '2026-03-01T00:05:00Z',
- auto_resolved: false,
- times_raised: 1,
- suppressed: false,
- investigation_attempts: 0,
- alert_identifier: 'instance:node:100::patrol/provider',
- },
- ] as any);
-
- const findings = await getPatrolFindings();
-
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/findings');
- expect(findings).toHaveLength(1);
- expect(findings[0]).toMatchObject({
- id: 'finding-1',
- alertIdentifier: 'instance:node:100::patrol/provider',
- title: 'Provider connection issue',
- });
- });
-
- it('bounds include-resolved Patrol finding queries', async () => {
- await getPatrolFindings({ includeResolved: true });
- expect(apiFetchJSONMock).toHaveBeenCalledWith(
- '/api/ai/patrol/findings?include_resolved=1&limit=200',
- );
-
- await getPatrolFindings({ includeResolved: true, limit: 25.9 });
- expect(apiFetchJSONMock).toHaveBeenCalledWith(
- '/api/ai/patrol/findings?include_resolved=1&limit=25',
- );
-
- await getPatrolFindings({ includeResolved: true, limit: 9999 });
- expect(apiFetchJSONMock).toHaveBeenCalledWith(
- '/api/ai/patrol/findings?include_resolved=1&limit=500',
- );
- });
-
- it('normalizes single patrol run payloads', async () => {
- apiFetchJSONMock.mockResolvedValueOnce({
- id: 'run-2',
- started_at: '2026-03-01T00:00:00Z',
- completed_at: '2026-03-01T00:01:00Z',
- duration_ms: 60000,
- type: 'patrol',
- resources_checked: 1,
- nodes_checked: 0,
- guests_checked: 0,
- docker_checked: 0,
- storage_checked: 0,
- hosts_checked: 0,
- truenas_checked: 0,
- pbs_checked: 0,
- pmg_checked: 0,
- kubernetes_checked: 0,
- new_findings: 0,
- existing_findings: 0,
- rejected_findings: 0,
- resolved_findings: 0,
- findings_summary: 'ok',
- finding_ids: [],
- error_count: 0,
- status: 'healthy',
- triage_flags: 0,
- tool_call_count: 1,
- alert_identifier: 'canonical-alert-2',
- } as any);
-
- await expect(getPatrolRun('run-2')).resolves.toMatchObject({
- id: 'run-2',
- alertIdentifier: 'canonical-alert-2',
- truenas_checked: 0,
- tool_call_count: 1,
- });
- });
-
- it('normalizes malformed patrol history payloads to empty arrays', async () => {
- apiFetchJSONMock.mockResolvedValueOnce({ runs: [] } as any);
-
- await expect(getPatrolRunHistory()).resolves.toEqual([]);
- });
-
- it('normalizes malformed tool-call patrol history payloads to empty arrays', async () => {
- apiFetchJSONMock.mockResolvedValueOnce(null as any);
-
- await expect(getPatrolRunHistoryWithToolCalls()).resolves.toEqual([]);
- });
-
- it('normalizes malformed single-run payloads to null', async () => {
- apiFetchJSONMock.mockResolvedValueOnce([] as any);
-
- await expect(getPatrolRunWithToolCalls('run-3')).resolves.toBeNull();
- });
-
- it('preserves the FindingsTrustSummary block on patrol status responses', async () => {
- // The trust block surfaces FindingsStore.GetTrustSummary on the patrol
- // page. The TS mirror must round-trip the exact field names from the
- // backend snake_case payload so the workspace strip can read them.
- apiFetchJSONMock.mockResolvedValueOnce({
- runtime_state: 'active',
- healthy: true,
- summary: { critical: 0, warning: 1, watch: 0, info: 0 },
- trust: {
- tracked: 4,
- currently_active: 1,
- resolved: 2,
- auto_resolved: 1,
- fix_verified: 1,
- fix_failed: 0,
- dismissed_as_noise: 1,
- dismissed_as_expected: 0,
- dismissed_as_later: 0,
- suppressed: 0,
- regressed_at_least_once: 1,
- },
- } as any);
-
- await expect(getPatrolStatus()).resolves.toMatchObject({
- trust: {
- tracked: 4,
- fix_verified: 1,
- dismissed_as_noise: 1,
- regressed_at_least_once: 1,
- },
- });
- });
-
- it('posts the canonical manual-resolve payload for /api/ai/patrol/resolve', async () => {
- // /api/ai/patrol/resolve was already wired server-side but had no TS
- // client. Pin the canonical request shape so future refactors can't
- // silently drift the body or method — the server returns 405 for GET
- // and 400 for missing finding_id, so the contract is strict.
- apiFetchJSONMock.mockResolvedValueOnce({ success: true, message: 'ok' } as any);
-
- await resolveFinding('finding-resolve-123');
-
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/resolve', {
- method: 'POST',
- body: JSON.stringify({ finding_id: 'finding-resolve-123' }),
- });
- });
-
- it('refuses to create broad suppression rules from a finding shortcut', async () => {
- await expect(
- createSuppressionRuleFromFinding({
- resourceId: '',
- resourceName: 'Any resource',
- category: 'capacity',
- description: 'Known pattern',
- }),
- ).rejects.toThrow('resource and category');
- expect(apiFetchJSONMock).not.toHaveBeenCalled();
-
- await expect(
- createSuppressionRuleFromFinding({
- resourceId: 'resource-1',
- resourceName: 'resource-1',
- category: '',
- description: 'Known pattern',
- }),
- ).rejects.toThrow('resource and category');
- expect(apiFetchJSONMock).not.toHaveBeenCalled();
- });
-
- it('trims scoped suppression rules created from findings', async () => {
- apiFetchJSONMock.mockResolvedValueOnce({
- success: true,
- message: 'ok',
- rule: { id: 'rule-1' },
- } as any);
-
- await createSuppressionRuleFromFinding({
- resourceId: ' resource-1 ',
- resourceName: ' node-1 ',
- category: ' backup ',
- description: ' Known backup exception ',
- });
-
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/suppressions', {
+ it('sends a JSON scope body for a targeted check', async () => {
+ const scope = {
+ resource_ids: ['vm-101'],
+ alert_identifier: 'alert-1',
+ alert_type: 'cpu',
+ context: 'Manual targeted check from alert: cpu',
+ };
+ await triggerPatrolRun(scope);
+ expect(fetchMock).toHaveBeenCalledWith('/api/ai/patrol/run', {
method: 'POST',
- body: JSON.stringify({
- resource_id: 'resource-1',
- resource_name: 'node-1',
- category: 'backup',
- description: 'Known backup exception',
- }),
+ body: JSON.stringify(scope),
+ headers: { 'Content-Type': 'application/json' },
});
});
- it('round-trips remind_at on dismissed-as-will_fix_later patrol findings', async () => {
- // The backend treats will_fix_later as an operator commitment with a
- // wake-up deadline (Finding.RemindAt, default 7 days). The TS API client
- // must mirror remind_at verbatim so the surface can preview the deadline
- // at dismiss-confirm time and badge the dismissed row with the pending
- // reminder. Without this round-trip, the deadline is invisible to the
- // operator until the reminder fires a week later.
- const willFixLater: PatrolFinding = {
- id: 'finding-wfl',
- severity: 'warning',
- category: 'reliability',
- resource_id: 'vm-101',
- resource_name: 'db-01',
- resource_type: 'vm',
- title: 'Disk pressure',
- description: 'Pulse will surface this again on the deadline',
- detected_at: '2026-05-09T10:00:00Z',
- last_seen_at: '2026-05-09T10:05:00Z',
- auto_resolved: false,
- times_raised: 1,
- suppressed: false,
- investigation_attempts: 0,
- dismissed_reason: 'will_fix_later',
- remind_at: '2026-05-16T10:00:00Z',
- };
- apiFetchJSONMock.mockResolvedValueOnce([willFixLater] as any);
-
- const findings = await getPatrolFindings();
- expect(findings).toHaveLength(1);
- expect(findings[0]?.dismissed_reason).toBe('will_fix_later');
- expect(findings[0]?.remind_at).toBe('2026-05-16T10:00:00Z');
+ it('treats a scope with no real ids as a fleet-wide run', async () => {
+ await triggerPatrolRun({ resource_ids: [], resource_types: [] });
+ expect(fetchMock).toHaveBeenCalledWith('/api/ai/patrol/run', { method: 'POST' });
});
});
diff --git a/frontend-modern/src/api/patrol.ts b/frontend-modern/src/api/patrol.ts
index 4c6c6bcdce..44217e5b6a 100644
--- a/frontend-modern/src/api/patrol.ts
+++ b/frontend-modern/src/api/patrol.ts
@@ -730,11 +730,39 @@ export interface PatrolStreamEvent {
}
/**
- * Trigger a manual patrol run
+ * Optional scope for a manual patrol run.
+ *
+ * When resource_ids or resource_types are present, POST /api/ai/patrol/run
+ * starts a manual Targeted check over the same scoped engine the automatic
+ * alert path uses, instead of a fleet-wide Patrol check. A scoped run bypasses
+ * the full-run cadence gate but still honours Patrol readiness.
*/
-export async function triggerPatrolRun(): Promise<{ success: boolean; message: string }> {
+export interface PatrolRunScope {
+ resource_ids?: string[];
+ resource_types?: string[];
+ alert_identifier?: string;
+ alert_type?: string;
+ context?: string;
+}
+
+/**
+ * Trigger a manual patrol run.
+ *
+ * Without a scope this starts a fleet-wide Patrol check (the legacy Run
+ * Patrol behaviour). Pass a scope to run a manual Targeted check scoped to
+ * specific resources — e.g. a single alert's resource.
+ */
+export async function triggerPatrolRun(
+ scope?: PatrolRunScope,
+): Promise<{ success: boolean; message: string }> {
+ const hasScope =
+ !!scope &&
+ ((scope.resource_ids?.length ?? 0) > 0 || (scope.resource_types?.length ?? 0) > 0);
return apiFetchJSON('/api/ai/patrol/run', {
method: 'POST',
+ ...(hasScope
+ ? { body: JSON.stringify(scope), headers: { 'Content-Type': 'application/json' } }
+ : {}),
});
}
diff --git a/frontend-modern/src/components/Alerts/InvestigateAlertButton.tsx b/frontend-modern/src/components/Alerts/InvestigateAlertButton.tsx
index 20dc2e673a..071a6471d1 100644
--- a/frontend-modern/src/components/Alerts/InvestigateAlertButton.tsx
+++ b/frontend-modern/src/components/Alerts/InvestigateAlertButton.tsx
@@ -1,5 +1,9 @@
-import { Show, createSignal } from 'solid-js';
+import { Show, createEffect, createSignal, onCleanup } from 'solid-js';
+import ChevronDownIcon from 'lucide-solid/icons/chevron-down';
+import ShieldCheckIcon from 'lucide-solid/icons/shield-check';
import { aiChatStore } from '@/stores/aiChat';
+import { notificationStore } from '@/stores/notifications';
+import { triggerPatrolRun } from '@/api/patrol';
import { t } from '@/i18n';
import type { Alert } from '@/types/api';
import { useUpgradeNavigation } from '@/components/shared/useUpgradeNavigation';
@@ -15,15 +19,27 @@ interface InvestigateAlertButtonProps {
variant?: 'icon' | 'text' | 'full';
class?: string;
licenseLocked?: boolean;
+ /**
+ * When true (and the alert has a resource), the text/full variants render as
+ * a split AI button: the primary action still opens Pulse Assistant (the
+ * context-only explanation surface), and a small menu offers to run a manual
+ * targeted Patrol check scoped to this alert's resource. The icon variant is
+ * single-purpose regardless.
+ */
+ patrolOption?: boolean;
}
/**
* "Ask AI" button for one-click alert investigation.
- * When clicked, opens the AI chat panel with the alert context pre-populated.
+ * The primary action opens Pulse Assistant with alert context attached
+ * (context-only, per the alerts Assistant handoff contract). When patrolOption
+ * is set, a split menu also offers a manual targeted Patrol check.
* Hidden entirely when AI is not configured.
*/
export function InvestigateAlertButton(props: InvestigateAlertButtonProps) {
const [isHovered, setIsHovered] = createSignal(false);
+ const [menuOpen, setMenuOpen] = createSignal(false);
+ let containerRef: HTMLDivElement | undefined;
const openUpgradeDestination = useUpgradeNavigation();
const isLocked = () => props.licenseLocked === true;
const canShowUpgradePrompt = () => !presentationPolicyHidesUpgradePrompts();
@@ -37,9 +53,37 @@ export function InvestigateAlertButton(props: InvestigateAlertButtonProps) {
return null;
}
+ const showPatrolOption = () =>
+ props.patrolOption === true &&
+ !isLocked() &&
+ !!(props.alert.resourceId || '').trim();
+
+ const closeMenu = () => setMenuOpen(false);
+
+ const handleMenuClickOutside = (event: MouseEvent) => {
+ if (containerRef && !containerRef.contains(event.target as Node)) {
+ closeMenu();
+ }
+ };
+ const handleMenuEscape = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') {
+ closeMenu();
+ }
+ };
+ createEffect(() => {
+ if (!menuOpen()) return;
+ document.addEventListener('mousedown', handleMenuClickOutside);
+ document.addEventListener('keydown', handleMenuEscape);
+ onCleanup(() => {
+ document.removeEventListener('mousedown', handleMenuClickOutside);
+ document.removeEventListener('keydown', handleMenuEscape);
+ });
+ });
+
const handleClick = (e: MouseEvent) => {
e.stopPropagation();
e.preventDefault();
+ closeMenu();
if (isLocked()) {
if (!canShowUpgradePrompt()) {
return;
@@ -57,6 +101,43 @@ export function InvestigateAlertButton(props: InvestigateAlertButtonProps) {
aiChatStore.open(handoff.context);
};
+ const handleToggleMenu = (e: MouseEvent) => {
+ e.stopPropagation();
+ e.preventDefault();
+ setMenuOpen((value) => !value);
+ };
+
+ const handleTriggerPatrol = async (e: MouseEvent) => {
+ e.stopPropagation();
+ e.preventDefault();
+ closeMenu();
+ const resourceId = (props.alert.resourceId || '').trim();
+ if (!resourceId) {
+ notificationStore.warning(t('alerts.assistant.patrol.noResource'));
+ return;
+ }
+ try {
+ const result = await triggerPatrolRun({
+ resource_ids: [resourceId],
+ alert_identifier: props.alert.id,
+ alert_type: props.alert.type,
+ context: `Manual targeted check from alert: ${props.alert.type}`,
+ });
+ if (result.success) {
+ notificationStore.success(
+ t('alerts.assistant.patrol.triggered', {
+ resourceName: props.alert.resourceName || resourceId,
+ }),
+ );
+ } else {
+ notificationStore.warning(result.message || t('alerts.assistant.patrol.failed'));
+ }
+ } catch (err) {
+ const message = err instanceof Error ? err.message : t('alerts.assistant.patrol.failed');
+ notificationStore.error(message);
+ }
+ };
+
const sizeClasses = {
sm: 'w-6 h-6 text-xs',
md: 'w-8 h-8 text-sm',
@@ -69,7 +150,46 @@ export function InvestigateAlertButton(props: InvestigateAlertButtonProps) {
disabled:opacity-50 disabled:cursor-not-allowed
`;
- // Icon-only variant (smallest footprint)
+ // Shared split-menu affordance rendered alongside the primary button when
+ // patrolOption is active. The primary action stays "open Assistant"; this
+ // only exposes the manual targeted Patrol alternative.
+ const PatrolSplit = (splitClass: string, iconClass: string) => (
+ <Show when={showPatrolOption()}>
+ <button
+ type="button"
+ onClick={handleToggleMenu}
+ aria-haspopup="menu"
+ aria-expanded={menuOpen()}
+ aria-label={t('alerts.assistant.patrol.chevron')}
+ title={t('alerts.assistant.patrol.chevron')}
+ class={`${baseButtonClass} ${splitClass}`}
+ >
+ <ChevronDownIcon class={iconClass} />
+ </button>
+ <Show when={menuOpen()}>
+ <div
+ role="menu"
+ class="absolute right-0 top-[calc(100%+0.25rem)] z-50 w-60 max-w-[calc(100vw-2rem)] rounded-md border border-border bg-surface shadow-lg"
+ >
+ <button
+ type="button"
+ role="menuitem"
+ onClick={handleTriggerPatrol}
+ class="flex w-full items-center gap-2 px-3 py-2 text-left text-xs text-base-content hover:bg-surface-hover"
+ >
+ <ShieldCheckIcon class="h-4 w-4 flex-shrink-0 text-blue-600 dark:text-blue-400" />
+ <span class="flex flex-col">
+ <span class="font-medium">{t('alerts.assistant.patrol.menuLabel')}</span>
+ <span class="text-[10px] text-muted">{t('alerts.assistant.patrol.menuHint')}</span>
+ </span>
+ </button>
+ </div>
+ </Show>
+ </Show>
+ );
+
+ // Icon-only variant (smallest footprint). Stays single-purpose: opens
+ // Assistant directly. No Patrol split in tight table rows.
if (props.variant === 'icon') {
return (
<button
@@ -108,24 +228,66 @@ export function InvestigateAlertButton(props: InvestigateAlertButtonProps) {
// Text variant (shows "Ask AI" on hover)
if (props.variant === 'text') {
return (
+ <div ref={containerRef} class="relative inline-flex items-stretch">
+ <button
+ type="button"
+ onClick={handleClick}
+ onMouseEnter={() => setIsHovered(true)}
+ onMouseLeave={() => setIsHovered(false)}
+ class={`${baseButtonClass} px-2 py-1
+ bg-surface
+ hover:bg-surface-hover
+ text-blue-600 dark:text-blue-400
+ hover:text-blue-700 dark:hover:text-blue-300
+ border border-border
+ gap-1.5
+ ${showPatrolOption() ? 'rounded-r-none' : ''}
+ ${isLocked() ? 'opacity-60 cursor-not-allowed hover:bg-surface' : ''}
+ ${props.class || ''}`}
+ title={buttonTitle()}
+ aria-disabled={isLocked()}
+ >
+ <svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"
+ />
+ </svg>
+ <span class="text-xs font-medium">{t('alerts.assistant.button.text')}</span>
+ </button>
+ {PatrolSplit(
+ `px-1.5 py-1 rounded-l-none border border-border border-l-0 bg-surface hover:bg-surface-hover text-blue-600 dark:text-blue-400 ${
+ isLocked() ? 'opacity-60 cursor-not-allowed' : ''
+ }`,
+ 'w-3 h-3',
+ )}
+ </div>
+ );
+ }
+
+ // Full variant (with expanded label)
+ return (
+ <div ref={containerRef} class="relative inline-flex items-stretch">
<button
type="button"
onClick={handleClick}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
- class={`${baseButtonClass} px-2 py-1
- bg-surface
- hover:bg-surface-hover
- text-blue-600 dark:text-blue-400
- hover:text-blue-700 dark:hover:text-blue-300
- border border-border
- gap-1.5
- ${isLocked() ? 'opacity-60 cursor-not-allowed hover:bg-surface' : ''}
+ class={`${baseButtonClass} px-3 py-1.5
+ bg-blue-600
+ hover:bg-blue-700
+ text-white font-medium
+ shadow-sm hover:shadow-sm
+ gap-2
+ ${showPatrolOption() ? 'rounded-r-none' : ''}
+ ${isLocked() ? 'opacity-60 cursor-not-allowed hover:bg-blue-600' : ''}
${props.class || ''}`}
title={buttonTitle()}
aria-disabled={isLocked()}
>
- <svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path
stroke-linecap="round"
stroke-linejoin="round"
@@ -133,42 +295,18 @@ export function InvestigateAlertButton(props: InvestigateAlertButtonProps) {
d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"
/>
</svg>
- <span class="text-xs font-medium">{t('alerts.assistant.button.text')}</span>
+ <span>{t('alerts.assistant.button.full')}</span>
+ <Show when={isHovered() && !showPatrolOption()}>
+ <span class="text-xs opacity-80">→</span>
+ </Show>
</button>
- );
- }
-
- // Full variant (with expanded label)
- return (
- <button
- type="button"
- onClick={handleClick}
- onMouseEnter={() => setIsHovered(true)}
- onMouseLeave={() => setIsHovered(false)}
- class={`${baseButtonClass} px-3 py-1.5
- bg-blue-600
- hover:bg-blue-700
- text-white font-medium
- shadow-sm hover:shadow-sm
- gap-2
- ${isLocked() ? 'opacity-60 cursor-not-allowed hover:bg-blue-600' : ''}
- ${props.class || ''}`}
- title={buttonTitle()}
- aria-disabled={isLocked()}
- >
- <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"
- />
- </svg>
- <span>{t('alerts.assistant.button.full')}</span>
- <Show when={isHovered()}>
- <span class="text-xs opacity-80">→</span>
- </Show>
- </button>
+ {PatrolSplit(
+ `px-2 py-1.5 rounded-l-none bg-blue-600 hover:bg-blue-700 text-white border-l border-blue-500/60 ${
+ isLocked() ? 'opacity-60 cursor-not-allowed hover:bg-blue-600' : ''
+ }`,
+ 'w-3.5 h-3.5',
+ )}
+ </div>
);
}
diff --git a/frontend-modern/src/components/Alerts/__tests__/InvestigateAlertButton.test.tsx b/frontend-modern/src/components/Alerts/__tests__/InvestigateAlertButton.test.tsx
index 51d45e77c3..69fab0e324 100644
--- a/frontend-modern/src/components/Alerts/__tests__/InvestigateAlertButton.test.tsx
+++ b/frontend-modern/src/components/Alerts/__tests__/InvestigateAlertButton.test.tsx
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
import { DEFAULT_LOCALE, setActiveLocale } from '@/i18n';
import type { Alert } from '@/types/api';
import { getPublicPricingUrl } from '@/utils/pricingHandoff';
@@ -16,6 +16,8 @@ const {
getUpgradeActionDestinationMock,
getUpgradeActionUrlOrFallbackMock,
presentationPolicyHidesUpgradePromptsMock,
+ triggerPatrolRunMock,
+ notificationStoreMock,
} = vi.hoisted(() => {
const openMock = vi.fn();
const openUpgradeDestinationMock = vi.fn();
@@ -29,6 +31,13 @@ const {
enabled: true as boolean | null,
open: (...args: unknown[]) => openMock(...args),
};
+ const triggerPatrolRunMock = vi.fn();
+ const notificationStoreMock = {
+ success: vi.fn(),
+ error: vi.fn(),
+ warning: vi.fn(),
+ info: vi.fn(),
+ };
return {
openMock,
openUpgradeDestinationMock,
@@ -37,6 +46,8 @@ const {
getUpgradeActionDestinationMock,
getUpgradeActionUrlOrFallbackMock,
presentationPolicyHidesUpgradePromptsMock,
+ triggerPatrolRunMock,
+ notificationStoreMock,
};
});
@@ -61,6 +72,14 @@ vi.mock('@/utils/alertFormatters', () => ({
formatAlertValue: (...args: unknown[]) => formatAlertValueMock(...(args as [number, string])),
}));
+vi.mock('@/api/patrol', () => ({
+ triggerPatrolRun: (...args: unknown[]) => triggerPatrolRunMock(...(args as [unknown])),
+}));
+
+vi.mock('@/stores/notifications', () => ({
+ notificationStore: notificationStoreMock,
+}));
+
// Import component AFTER mocks are set up
import { InvestigateAlertButton } from '../InvestigateAlertButton';
@@ -125,6 +144,12 @@ beforeEach(() => {
});
getUpgradeActionUrlOrFallbackMock.mockReturnValue(getPublicPricingUrl('ai_alerts'));
vi.spyOn(window, 'open').mockImplementation(() => null);
+ triggerPatrolRunMock.mockReset();
+ triggerPatrolRunMock.mockResolvedValue({ success: true, message: 'Triggered targeted Patrol check' });
+ notificationStoreMock.success.mockReset();
+ notificationStoreMock.error.mockReset();
+ notificationStoreMock.warning.mockReset();
+ notificationStoreMock.info.mockReset();
});
// ---------------------------------------------------------------------------
@@ -690,3 +715,69 @@ describe('InvestigateAlertButton', () => {
});
});
});
+
+describe('InvestigateAlertButton patrolOption', () => {
+ it('renders a split menu toggle alongside the primary action (text variant)', () => {
+ render(() => <InvestigateAlertButton alert={makeAlert()} variant="text" patrolOption />);
+ expect(screen.getAllByRole('button')).toHaveLength(2);
+ const toggle = screen.getByRole('button', { name: 'More AI actions for this alert' });
+ expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('omits the split when the alert has no resource', () => {
+ const alert = makeAlert({ resourceId: '' });
+ render(() => <InvestigateAlertButton alert={alert} variant="text" patrolOption />);
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ });
+
+ it('omits the split when license-locked', () => {
+ render(() => (
+ <InvestigateAlertButton alert={makeAlert()} variant="text" patrolOption licenseLocked />
+ ));
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ });
+
+ it('keeps the icon variant single-purpose even with patrolOption', () => {
+ render(() => <InvestigateAlertButton alert={makeAlert()} variant="icon" patrolOption />);
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ });
+
+ it('triggers a scoped patrol run from the menu item', async () => {
+ const alert = makeAlert({
+ id: 'alert-9',
+ type: 'cpu',
+ resourceId: 'vm-101',
+ resourceName: 'test-vm',
+ });
+ render(() => <InvestigateAlertButton alert={alert} variant="text" patrolOption />);
+
+ const toggle = screen.getByRole('button', { name: 'More AI actions for this alert' });
+ await fireEvent.click(toggle);
+
+ const item = await screen.findByRole('menuitem', { name: /Have Patrol investigate/i });
+ await fireEvent.click(item);
+
+ await waitFor(() => {
+ expect(triggerPatrolRunMock).toHaveBeenCalledWith({
+ resource_ids: ['vm-101'],
+ alert_identifier: 'alert-9',
+ alert_type: 'cpu',
+ context: 'Manual targeted check from alert: cpu',
+ });
+ });
+ await waitFor(() => {
+ expect(notificationStoreMock.success).toHaveBeenCalledWith('Patrol is investigating test-vm');
+ });
+ });
+
+ it('does not open the Assistant when the Patrol item is chosen', async () => {
+ const alert = makeAlert({ resourceId: 'vm-101' });
+ render(() => <InvestigateAlertButton alert={alert} variant="text" patrolOption />);
+
+ await fireEvent.click(screen.getByRole('button', { name: 'More AI actions for this alert' }));
+ await fireEvent.click(await screen.findByRole('menuitem'));
+
+ await waitFor(() => expect(triggerPatrolRunMock).toHaveBeenCalled());
+ expect(openMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsx b/frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsx
index bdb4d1b90d..2bcc94f5b0 100644
--- a/frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsx
+++ b/frontend-modern/src/features/alerts/AlertOverviewAlertCard.tsx
@@ -118,6 +118,7 @@ export function AlertOverviewAlertCard(props: AlertOverviewAlertCardProps) {
}
variant="text"
size="sm"
+ patrolOption
/>
</div>
</div>
diff --git a/frontend-modern/src/features/alerts/__tests__/alertsLocalization.guardrails.test.ts b/frontend-modern/src/features/alerts/__tests__/alertsLocalization.guardrails.test.ts
index 8331023a2d..908d31a751 100644
--- a/frontend-modern/src/features/alerts/__tests__/alertsLocalization.guardrails.test.ts
+++ b/frontend-modern/src/features/alerts/__tests__/alertsLocalization.guardrails.test.ts
@@ -43,6 +43,9 @@ const migratedAlertsOverviewCopy = [
'Ask Pulse Assistant about this alert',
'Ask Pulse Assistant',
'Pro required to ask Pulse Assistant about alerts',
+ 'More AI actions for this alert',
+ 'Have Patrol investigate',
+ 'Run a targeted Patrol check on this resource',
'Alert investigation attached',
'Diagnostics and remediation require operator approval',
'No incident timeline available',
diff --git a/frontend-modern/src/i18n/__tests__/i18n.test.ts b/frontend-modern/src/i18n/__tests__/i18n.test.ts
index e9c98e0fa6..1e200b7587 100644
--- a/frontend-modern/src/i18n/__tests__/i18n.test.ts
+++ b/frontend-modern/src/i18n/__tests__/i18n.test.ts
@@ -267,6 +267,8 @@ describe('i18n foundation', () => {
expect(I18N_MESSAGES[locale]['alerts.assistant.button.full']).toContain('Pulse Assistant');
expect(I18N_MESSAGES[locale]['alerts.assistant.sourceLabel']).toBe('Pulse Alerts');
expect(I18N_MESSAGES[locale]['alerts.assistant.locked.proRequired']).toContain('Pro');
+ expect(I18N_MESSAGES[locale]['alerts.assistant.patrol.menuLabel']).toBeTruthy();
+ expect(I18N_MESSAGES[locale]['alerts.assistant.patrol.menuLabel']).toContain('Patrol');
expect(
t(
'alerts.assistant.action.investigate',
diff --git a/frontend-modern/src/i18n/messages.de.ts b/frontend-modern/src/i18n/messages.de.ts
index 23d577b25c..7c15fddeeb 100644
--- a/frontend-modern/src/i18n/messages.de.ts
+++ b/frontend-modern/src/i18n/messages.de.ts
@@ -36,6 +36,12 @@ export const DE_MESSAGE_OVERRIDES = {
'alerts.assistant.subject': '{level} {alertType} auf {resourceName}',
'alerts.assistant.title': 'Warnungsanalyse angehaengt',
'alerts.assistant.unlockedTitle': 'Pulse Assistant zu dieser Warnmeldung fragen',
+ 'alerts.assistant.patrol.chevron': 'Weitere KI-Aktionen fuer diese Warnmeldung',
+ 'alerts.assistant.patrol.menuLabel': 'Patrol ermitteln lassen',
+ 'alerts.assistant.patrol.menuHint': 'Eine gezielte Patrol-Pruefung fuer diese Ressource ausfuehren',
+ 'alerts.assistant.patrol.triggered': 'Patrol untersucht {resourceName}',
+ 'alerts.assistant.patrol.noResource': 'Diese Warnmeldung hat keine zu untersuchende Ressource',
+ 'alerts.assistant.patrol.failed': 'Patrol-Pruefung konnte nicht gestartet werden',
'alerts.nav.ariaLabel': 'Warnmeldungsnavigation',
'alerts.nav.collapseSidebar': 'Seitenleiste einklappen',
'alerts.nav.expandSidebar': 'Seitenleiste ausklappen',
diff --git a/frontend-modern/src/i18n/messages.es.ts b/frontend-modern/src/i18n/messages.es.ts
index ce7085fa6f..44c969e446 100644
--- a/frontend-modern/src/i18n/messages.es.ts
+++ b/frontend-modern/src/i18n/messages.es.ts
@@ -35,6 +35,12 @@ export const ES_MESSAGE_OVERRIDES = {
'alerts.assistant.subject': '{level} {alertType} en {resourceName}',
'alerts.assistant.title': 'Investigacion de alerta adjunta',
'alerts.assistant.unlockedTitle': 'Preguntar a Pulse Assistant sobre esta alerta',
+ 'alerts.assistant.patrol.chevron': 'Mas acciones de IA para esta alerta',
+ 'alerts.assistant.patrol.menuLabel': 'Pedir a Patrol que investigue',
+ 'alerts.assistant.patrol.menuHint': 'Ejecutar una verificacion dirigida de Patrol en este recurso',
+ 'alerts.assistant.patrol.triggered': 'Patrol esta investigando {resourceName}',
+ 'alerts.assistant.patrol.noResource': 'Esta alerta no tiene un recurso para investigar',
+ 'alerts.assistant.patrol.failed': 'No se pudo iniciar la verificacion de Patrol',
'alerts.nav.ariaLabel': 'Navegacion de alertas',
'alerts.nav.collapseSidebar': 'Contraer barra lateral',
'alerts.nav.expandSidebar': 'Expandir barra lateral',
diff --git a/frontend-modern/src/i18n/messages.ts b/frontend-modern/src/i18n/messages.ts
index 177af69274..f884e81045 100644
--- a/frontend-modern/src/i18n/messages.ts
+++ b/frontend-modern/src/i18n/messages.ts
@@ -123,6 +123,12 @@ export const EN_MESSAGES = {
'alerts.assistant.subject': '{level} {alertType} on {resourceName}',
'alerts.assistant.title': 'Alert investigation attached',
'alerts.assistant.unlockedTitle': 'Ask Pulse Assistant about this alert',
+ 'alerts.assistant.patrol.chevron': 'More AI actions for this alert',
+ 'alerts.assistant.patrol.menuLabel': 'Have Patrol investigate',
+ 'alerts.assistant.patrol.menuHint': 'Run a targeted Patrol check on this resource',
+ 'alerts.assistant.patrol.triggered': 'Patrol is investigating {resourceName}',
+ 'alerts.assistant.patrol.noResource': 'This alert has no resource to investigate',
+ 'alerts.assistant.patrol.failed': "Couldn't start the Patrol check",
'alerts.nav.ariaLabel': 'Alerts navigation',
'alerts.nav.collapseSidebar': 'Collapse sidebar',
'alerts.nav.expandSidebar': 'Expand sidebar',
@@ -641,6 +647,12 @@ export const ALERTS_OVERVIEW_MIGRATED_MESSAGE_KEYS = [
'alerts.assistant.subject',
'alerts.assistant.title',
'alerts.assistant.unlockedTitle',
+ 'alerts.assistant.patrol.chevron',
+ 'alerts.assistant.patrol.menuLabel',
+ 'alerts.assistant.patrol.menuHint',
+ 'alerts.assistant.patrol.triggered',
+ 'alerts.assistant.patrol.noResource',
+ 'alerts.assistant.patrol.failed',
'alerts.nav.ariaLabel',
'alerts.nav.collapseSidebar',
'alerts.nav.expandSidebar',
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index 8b3d3691bb..6df4e3b58f 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -5672,6 +5672,54 @@ func patrolFindingsLimitFromQuery(query url.Values, includeResolved bool) int {
return limit
}
+// manualScopedPatrolRequest is the optional body for POST /api/ai/patrol/run.
+// When resource_ids or resource_types are present, the run is scoped to those
+// resources as a manual Targeted check over the same scoped engine the
+// automatic alert path uses, instead of a fleet-wide Patrol check.
+type manualScopedPatrolRequest struct {
+ ResourceIDs []string `json:"resource_ids,omitempty"`
+ ResourceTypes []string `json:"resource_types,omitempty"`
+ AlertIdentifier string `json:"alert_identifier,omitempty"`
+ AlertType string `json:"alert_type,omitempty"`
+ Context string `json:"context,omitempty"`
+}
+
+// buildManualScopedPatrolScope maps an optional scoped-run request body to a
+// manual PatrolScope. It returns hasScope=false when no resource ids or types
+// remain after trimming, so the caller falls back to a full fleet run.
+func buildManualScopedPatrolScope(req manualScopedPatrolRequest) (ai.PatrolScope, bool) {
+ resourceIDs := make([]string, 0, len(req.ResourceIDs))
+ for _, id := range req.ResourceIDs {
+ if trimmed := strings.TrimSpace(id); trimmed != "" {
+ resourceIDs = append(resourceIDs, trimmed)
+ }
+ }
+ resourceTypes := make([]string, 0, len(req.ResourceTypes))
+ for _, t := range req.ResourceTypes {
+ if trimmed := strings.TrimSpace(t); trimmed != "" {
+ resourceTypes = append(resourceTypes, trimmed)
+ }
+ }
+ if len(resourceIDs) == 0 && len(resourceTypes) == 0 {
+ return ai.PatrolScope{}, false
+ }
+ scope := ai.PatrolScope{
+ ResourceIDs: resourceIDs,
+ ResourceTypes: resourceTypes,
+ Depth: ai.PatrolDepthQuick,
+ Reason: ai.TriggerReasonManual,
+ AlertIdentifier: strings.TrimSpace(req.AlertIdentifier),
+ }
+ scope.Context = "Manual targeted check"
+ if alertType := strings.TrimSpace(req.AlertType); alertType != "" {
+ scope.Context = "Manual targeted check for alert: " + alertType
+ }
+ if ctx := strings.TrimSpace(req.Context); ctx != "" {
+ scope.Context = ctx
+ }
+ return scope, true
+}
+
// HandleForcePatrol triggers an immediate patrol run (POST /api/ai/patrol/run)
func (h *AISettingsHandler) HandleForcePatrol(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@@ -5700,6 +5748,27 @@ func (h *AISettingsHandler) HandleForcePatrol(w http.ResponseWriter, r *http.Req
return
}
+ // Optional scope: resource_ids/resource_types turn this into a manual
+ // Targeted check over the same scoped engine the automatic alert path uses,
+ // instead of a fleet-wide Patrol check. An empty or absent body keeps the
+ // legacy full-run behaviour. Scoped runs bypass the full-run cadence gate
+ // (consistent with automatic scoped runs) but still honour readiness above.
+ var scopedReq manualScopedPatrolRequest
+ if r.Body != nil {
+ _ = json.NewDecoder(r.Body).Decode(&scopedReq)
+ }
+ if scope, hasScope := buildManualScopedPatrolScope(scopedReq); hasScope {
+ go patrol.TriggerScopedPatrol(context.WithoutCancel(r.Context()), scope)
+ response := map[string]interface{}{
+ "success": true,
+ "message": "Triggered targeted Patrol check",
+ }
+ if err := utils.WriteJSONResponse(w, response); err != nil {
+ log.Error().Err(err).Msg("Failed to write scoped patrol response")
+ }
+ return
+ }
+
// Cadence cap: Community tier is limited to 1 patrol run per hour.
// Patrol itself is free (ai_patrol), but higher cadence is gated behind Pro/Cloud.
if !aiService.HasLicenseFeature(featureAIAutoFixValue) {
diff --git a/internal/api/ai_handlers_patrol_actions_additional_test.go b/internal/api/ai_handlers_patrol_actions_additional_test.go
index 044aec9854..290f9e642e 100644
--- a/internal/api/ai_handlers_patrol_actions_additional_test.go
+++ b/internal/api/ai_handlers_patrol_actions_additional_test.go
@@ -1013,3 +1013,118 @@ func TestHandleForcePatrol_CommunityTierIgnoresRecentScopedActivityForFullPatrol
t.Fatalf("expected community force patrol to ignore scoped-only activity, got %s", rec.Body.String())
}
}
+
+func TestBuildManualScopedPatrolScope(t *testing.T) {
+ cases := []struct {
+ name string
+ req manualScopedPatrolRequest
+ wantOK bool
+ check func(*testing.T, ai.PatrolScope)
+ }{
+ {
+ name: "empty body falls back to full run",
+ req: manualScopedPatrolRequest{},
+ wantOK: false,
+ },
+ {
+ name: "whitespace-only ids fall back to full run",
+ req: manualScopedPatrolRequest{ResourceIDs: []string{" "}},
+ wantOK: false,
+ },
+ {
+ name: "resource ids build a manual quick scope",
+ req: manualScopedPatrolRequest{ResourceIDs: []string{"vm-101", " vm-102 "}, AlertIdentifier: "alert-1", AlertType: "cpu"},
+ wantOK: true,
+ check: func(t *testing.T, s ai.PatrolScope) {
+ t.Helper()
+ if s.Reason != ai.TriggerReasonManual {
+ t.Errorf("reason = %q, want manual", s.Reason)
+ }
+ if s.Depth != ai.PatrolDepthQuick {
+ t.Errorf("depth = %v, want quick", s.Depth)
+ }
+ if len(s.ResourceIDs) != 2 || s.ResourceIDs[0] != "vm-101" || s.ResourceIDs[1] != "vm-102" {
+ t.Errorf("resource ids = %v", s.ResourceIDs)
+ }
+ if s.AlertIdentifier != "alert-1" {
+ t.Errorf("alert identifier = %q", s.AlertIdentifier)
+ }
+ if !strings.Contains(s.Context, "cpu") {
+ t.Errorf("context = %q, want alert type", s.Context)
+ }
+ },
+ },
+ {
+ name: "resource types only still scopes",
+ req: manualScopedPatrolRequest{ResourceTypes: []string{"vm"}},
+ wantOK: true,
+ check: func(t *testing.T, s ai.PatrolScope) {
+ t.Helper()
+ if len(s.ResourceTypes) != 1 || s.ResourceTypes[0] != "vm" {
+ t.Errorf("resource types = %v", s.ResourceTypes)
+ }
+ },
+ },
+ {
+ name: "explicit context overrides synthesized copy",
+ req: manualScopedPatrolRequest{ResourceIDs: []string{"vm-1"}, Context: "operator note"},
+ wantOK: true,
+ check: func(t *testing.T, s ai.PatrolScope) {
+ t.Helper()
+ if s.Context != "operator note" {
+ t.Errorf("context = %q, want operator note", s.Context)
+ }
+ },
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ scope, ok := buildManualScopedPatrolScope(tc.req)
+ if ok != tc.wantOK {
+ t.Fatalf("hasScope = %v, want %v", ok, tc.wantOK)
+ }
+ if !ok {
+ return
+ }
+ tc.check(t, scope)
+ })
+ }
+}
+
+func TestHandleForcePatrol_ScopedRequestBypassesFullRunCadenceGate(t *testing.T) {
+ handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
+ seedReadyAnthropicPatrolRuntime(t, handler)
+ handler.defaultAIService.SetLicenseChecker(communityLicenseChecker{})
+
+ // A recent full patrol puts Community tier inside the 1/hour full-run gate,
+ // so a fleet-wide request would be rate-limited.
+ setUnexportedField(t, patrol, "lastFullPatrol", time.Now().Add(-10*time.Minute))
+
+ // Scoped request: must succeed despite the full-run cadence window.
+ scopedReq := newLoopbackRequest(
+ http.MethodPost,
+ "/api/ai/patrol/run",
+ bytes.NewReader([]byte(`{"resource_ids":["vm-101"],"alert_identifier":"alert-1","alert_type":"cpu"}`)),
+ )
+ scopedRec := httptest.NewRecorder()
+ handler.HandleForcePatrol(scopedRec, scopedReq)
+
+ if scopedRec.Code != http.StatusOK {
+ t.Fatalf("scoped status = %d, want 200: %s", scopedRec.Code, scopedRec.Body.String())
+ }
+ if !strings.Contains(scopedRec.Body.String(), "targeted Patrol check") {
+ t.Fatalf("scoped response = %s, want targeted Patrol check message", scopedRec.Body.String())
+ }
+
+ // Contrast: an empty body (full run) on the same recent-full state is gated.
+ fullReq := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/run", nil)
+ fullRec := httptest.NewRecorder()
+ handler.HandleForcePatrol(fullRec, fullReq)
+
+ if fullRec.Code != http.StatusTooManyRequests {
+ t.Fatalf("full status = %d, want 429 rate limited: %s", fullRec.Code, fullRec.Body.String())
+ }
+ if !strings.Contains(fullRec.Body.String(), "patrol_rate_limited") {
+ t.Fatalf("full response = %s, want patrol_rate_limited", fullRec.Body.String())
+ }
+}
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index ec2058482b..783cf54efd 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -2916,7 +2916,7 @@ class SubsystemLookupTest(unittest.TestCase):
{
"heading": "## Shared Boundaries",
"path": "internal/api/access_control_handlers.go",
- "line": 1059,
+ "line": 1064,
"heading_line": 136,
}
],