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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@/api/ai', () => ({
AIAPI: {
getUnifiedFindings: vi.fn(),
getPendingApprovals: vi.fn(),
getIntelligenceSummary: vi.fn(),
},
}));
vi.mock('@/api/patrol', () => ({
getPatrolFindings: vi.fn(),
acknowledgeFinding: vi.fn(),
snoozeFinding: vi.fn(),
dismissFinding: vi.fn(),
reopenFinding: vi.fn(),
resolveFinding: vi.fn(),
setFindingNote: vi.fn(),
}));
vi.mock('@/utils/logger', () => ({
logger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
}));
vi.mock('@/stores/sessionPresentationPolicy', () => ({
presentationPolicyIsDemoMode: vi.fn(() => false),
}));
import { AIAPI } from '@/api/ai';
import { getPatrolFindings, reopenFinding, resolveFinding } from '@/api/patrol';
import { aiIntelligenceStore } from '@/stores/aiIntelligence';
import { presentationPolicyIsDemoMode } from '@/stores/sessionPresentationPolicy';
function approvalExpiryInMinutes(minutesFromNow: number): string {
return new Date(Date.now() + minutesFromNow * 60_000).toISOString();
}
describe('aiIntelligenceStore', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useRealTimers();
vi.mocked(presentationPolicyIsDemoMode).mockReturnValue(false);
vi.mocked(getPatrolFindings).mockResolvedValue([]);
});
it('loads unified findings with canonical alert identity first', async () => {
vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({
findings: [
{
id: 'finding-1',
source: 'threshold',
severity: 'warning',
category: 'performance',
resource_id: 'instance:node:100',
resource_name: 'vm-100',
resource_type: 'vm',
title: 'CPU high',
description: 'CPU usage is high',
impact: 'Workload stalls until CPU pressure clears.',
detected_at: '2026-03-01T00:00:00Z',
last_seen_at: '2026-03-05T00:00:00Z',
times_raised: 5,
alertIdentifier: 'instance:node:100::metric/cpu',
investigation_record: {
id: 'investigation-1',
finding_id: 'finding-1',
subject: {
resource_id: 'instance:node:100',
resource_name: 'vm-100',
resource_type: 'vm',
},
trigger: {
detected_at: '2026-03-01T00:00:00Z',
title: 'CPU high',
},
status: 'completed',
outcome: 'fix_queued',
confidence: 'medium',
evidence: [],
verification: [],
rollback: [],
tools_used: [],
started_at: '2026-03-05T00:00:00Z',
},
},
],
count: 1,
});
await aiIntelligenceStore.loadFindings();
expect(aiIntelligenceStore.findings).toHaveLength(1);
expect(aiIntelligenceStore.findings[0]).toMatchObject({
alertIdentifier: 'instance:node:100::metric/cpu',
lastSeenAt: '2026-03-05T00:00:00Z',
timesRaised: 5,
impact: 'Workload stalls until CPU pressure clears.',
investigationRecord: {
id: 'investigation-1',
finding_id: 'finding-1',
},
});
});
it('keeps the Patrol runtime failure cause on unified findings (#1789)', async () => {
vi.mocked(getPatrolFindings).mockResolvedValueOnce([
{
id: 'patrol-runtime',
key: 'ai-patrol-error',
severity: 'warning',
category: 'reliability',
resource_id: 'pulse-patrol-service',
resource_name: 'Pulse Patrol Service',
resource_type: 'service',
title: 'Pulse Patrol: 30-day cost budget reached',
description: 'Pulse Patrol skipped its analysis because spend reached the budget.',
detected_at: '2026-09-01T00:00:00Z',
last_seen_at: '2026-09-01T00:05:00Z',
auto_resolved: false,
times_raised: 2,
suppressed: false,
investigation_attempts: 0,
failure_cause: 'budget_exhausted',
} as never,
]);
await aiIntelligenceStore.loadPatrolFindings();
expect(aiIntelligenceStore.patrolFindings[0]).toMatchObject({
id: 'patrol-runtime',
failureCause: 'budget_exhausted',
});
});
it('loads direct Patrol findings for Patrol surfaces', async () => {
vi.mocked(getPatrolFindings).mockResolvedValueOnce([
{
id: 'patrol-finding-1',
key: 'apt-host-updates',
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,
alertIdentifier: 'instance:node:100::patrol/provider',
times_raised: 1,
suppressed: false,
investigation_attempts: 0,
},
]);
await aiIntelligenceStore.loadPatrolFindings();
expect(getPatrolFindings).toHaveBeenCalledTimes(1);
expect(aiIntelligenceStore.patrolFindings).toHaveLength(1);
expect(aiIntelligenceStore.patrolFindings[0]).toMatchObject({
id: 'patrol-finding-1',
key: 'apt-host-updates',
source: 'ai-patrol',
isThreshold: false,
status: 'active',
alertIdentifier: 'instance:node:100::patrol/provider',
lastSeenAt: '2026-03-01T00:05:00Z',
});
});
it('keeps unchanged findings, and the list, when a refresh reads them again', async () => {
// Rows render findings with <For>, keyed by object: a refresh that
// replaced unchanged findings rebuilt every row and remounted an open
// review on each 30s/60s poll.
const records = () => [
{
id: 'patrol-disk',
key: 'patrol-disk',
severity: 'warning' as const,
category: 'capacity' as const,
resource_id: 'instance:node:105',
resource_name: 'db-01',
resource_type: 'vm',
title: 'db-01 data disk is 91% full',
description: 'The PostgreSQL volume grew 4% in two days.',
detected_at: '2026-10-22T07:00:00Z',
last_seen_at: '2026-10-23T09:40:00Z',
auto_resolved: false,
times_raised: 1,
suppressed: false,
investigation_attempts: 1,
lifecycle: [{ at: '2026-10-22T07:00:00Z', type: 'detected', message: 'Detected' }],
},
{
id: 'patrol-backup',
key: 'patrol-backup',
severity: 'warning' as const,
category: 'backup' as const,
resource_id: 'instance:node:201',
resource_name: 'pbs-01',
resource_type: 'host',
title: 'Nightly backup on pbs-01 takes three times longer than usual',
description: 'The last three backup jobs each ran for about 3 hours.',
detected_at: '2026-10-22T07:00:00Z',
last_seen_at: '2026-10-23T09:40:00Z',
auto_resolved: false,
times_raised: 1,
suppressed: false,
investigation_attempts: 0,
},
];
vi.mocked(getPatrolFindings).mockImplementation(async () => records());
await aiIntelligenceStore.loadPatrolFindings();
const first = aiIntelligenceStore.patrolFindings;
await aiIntelligenceStore.loadPatrolFindings();
expect(aiIntelligenceStore.patrolFindings).toBe(first);
// The API returns tied findings in no fixed order.
vi.mocked(getPatrolFindings).mockImplementation(async () => records().reverse());
await aiIntelligenceStore.loadPatrolFindings();
const reordered = aiIntelligenceStore.patrolFindings;
expect(reordered.map((finding) => finding.id)).toEqual(['patrol-backup', 'patrol-disk']);
expect(reordered[0]).toBe(first[1]);
expect(reordered[1]).toBe(first[0]);
vi.mocked(getPatrolFindings).mockImplementation(async () =>
records().map((record) =>
record.id === 'patrol-disk' ? { ...record, title: 'db-01 data disk is 93% full' } : record,
),
);
await aiIntelligenceStore.loadPatrolFindings();
const changed = aiIntelligenceStore.patrolFindings;
expect(changed[1]).toBe(first[1]);
expect(changed[0]).not.toBe(first[0]);
expect(changed[0].title).toBe('db-01 data disk is 93% full');
});
it('keeps the unclassified and interrupted outcomes on both finding feeds', async () => {
const outcomes = { 'run-unclassified': 'unclassified', 'run-interrupted': 'interrupted' };
const finding = (id: string, outcome: string) => ({
id,
severity: 'warning',
category: 'reliability',
resource_id: `instance:node:${id}`,
resource_name: id,
resource_type: 'vm',
title: 'Service keeps restarting',
description: 'Patrol investigated the restarts.',
detected_at: '2026-10-22T00:00:00Z',
last_seen_at: '2026-10-22T00:05:00Z',
auto_resolved: false,
times_raised: 1,
suppressed: false,
investigation_attempts: 1,
investigation_status: outcome === 'interrupted' ? 'failed' : 'completed',
investigation_outcome: outcome,
});
const findings = [
...Object.entries(outcomes).map(([id, outcome]) => finding(id, outcome)),
finding('run-unknown', 'not_an_outcome'),
];
vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({
findings: findings.map((item) => ({ ...item, source: 'ai-patrol', status: 'active' })),
count: findings.length,
} as never);
vi.mocked(getPatrolFindings).mockResolvedValueOnce(findings as never);
vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([]);
await aiIntelligenceStore.loadFindings();
await aiIntelligenceStore.loadPatrolFindings();
await aiIntelligenceStore.loadPendingApprovals();
const expected = { ...outcomes, 'run-unknown': undefined };
for (const feed of [aiIntelligenceStore.findings, aiIntelligenceStore.patrolFindings]) {
expect(Object.fromEntries(feed.map((item) => [item.id, item.investigationOutcome]))).toEqual(
expected,
);
}
// An unclassified run left a summary to read; an interrupted run is
// rerun by Patrol, so it never joins the attention queue.
expect(aiIntelligenceStore.findingsNeedingAttention.map((item) => item.id)).toEqual([
'run-unclassified',
]);
expect(aiIntelligenceStore.patrolFindingsNeedingAttention.map((item) => item.id)).toEqual([
'run-unclassified',
]);
});
it('counts open Patrol work from active findings and live Patrol approvals once', async () => {
vi.mocked(getPatrolFindings).mockResolvedValueOnce([
{
id: 'finding-active',
severity: 'warning',
category: 'reliability',
resource_id: 'instance:node:100',
resource_name: 'node-100',
resource_type: 'host',
title: 'Active Patrol issue',
description: 'Patrol found an active issue.',
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,
},
{
id: 'finding-approval',
severity: 'warning',
category: 'reliability',
resource_id: 'instance:node:101',
resource_name: 'node-101',
resource_type: 'host',
title: 'Queued Patrol fix',
description: 'Patrol needs approval.',
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,
},
{
id: 'finding-resolved',
severity: 'info',
category: 'reliability',
resource_id: 'instance:node:102',
resource_name: 'node-102',
resource_type: 'host',
title: 'Resolved Patrol issue',
description: 'Patrol already handled this issue.',
detected_at: '2026-03-01T00:00:00Z',
last_seen_at: '2026-03-01T00:05:00Z',
resolved_at: '2026-03-01T00:10:00Z',
auto_resolved: true,
times_raised: 1,
suppressed: false,
investigation_attempts: 1,
},
]);
vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([
{
id: 'approval-existing-finding',
toolId: 'investigation_fix',
command: 'systemctl restart pulse-agent',
targetType: 'host',
targetId: 'finding-approval',
targetName: 'node-101',
context: 'Restart the agent',
riskLevel: 'medium',
status: 'pending',
requestedAt: '2026-03-01T00:01:00Z',
expiresAt: approvalExpiryInMinutes(6),
},
{
id: 'approval-not-yet-loaded',
toolId: 'investigation_fix',
command: 'systemctl restart another-service',
targetType: 'host',
targetId: 'finding-approval-only',
targetName: 'node-103',
context: 'Restart another service',
riskLevel: 'medium',
status: 'pending',
requestedAt: '2026-03-01T00:01:00Z',
expiresAt: approvalExpiryInMinutes(6),
},
{
id: 'assistant-approval',
toolId: 'run_command',
command: 'apt upgrade',
targetType: 'host',
targetId: 'host-1',
targetName: 'node-1',
context: 'Assistant chat command',
riskLevel: 'high',
status: 'pending',
requestedAt: '2026-03-01T00:01:00Z',
expiresAt: approvalExpiryInMinutes(6),
},
]);
await aiIntelligenceStore.loadPatrolFindings();
await aiIntelligenceStore.loadPendingApprovals();
expect(aiIntelligenceStore.patrolOpenWorkCount).toBe(3);
});
it('promotes auto_resolved to camelCase autoResolved on the unified-finding store record', async () => {
// The store-level UnifiedFinding is what render code reads when it asks
// "who closed this loop?" If the normalizer drops auto_resolved, the
// resolution-reason copy can't differentiate operator-driven Mark
// resolved from Pulse's own auto-detection. Pin the field promotion so
// the attribution doesn't silently regress.
vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({
findings: [
{
id: 'unified-manual-close',
source: 'threshold',
severity: 'warning',
category: 'performance',
resource_id: 'vm-101',
resource_name: 'db-01',
resource_type: 'vm',
title: 'CPU high',
description: 'CPU high',
detected_at: '2026-05-09T10:00:00Z',
last_seen_at: '2026-05-09T10:30:00Z',
resolved_at: '2026-05-09T11:00:00Z',
auto_resolved: false,
},
],
} as never);
await aiIntelligenceStore.loadFindings();
expect(aiIntelligenceStore.findings).toHaveLength(1);
expect(aiIntelligenceStore.findings[0]).toMatchObject({
id: 'unified-manual-close',
autoResolved: false,
});
});
it('routes Mark resolved through the canonical patrol resolve client and refreshes both finding sources', async () => {
// The Patrol surface's manual Mark resolved button must go through
// aiIntelligenceStore.resolveFinding so the refresh and error UX stays
// uniform with the existing acknowledge/snooze/dismiss store actions.
// After a successful resolve the store must reload BOTH the unified
// findings (for the unified workspace) and the patrol-direct findings
// (for the Patrol page) — otherwise the operator sees a stale row on
// whichever surface it didn't refresh.
vi.mocked(resolveFinding).mockResolvedValueOnce({ success: true, message: 'ok' } as never);
vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({ findings: [] } as never);
vi.mocked(getPatrolFindings).mockResolvedValueOnce([]);
const ok = await aiIntelligenceStore.resolveFinding('finding-resolve');
expect(ok).toBe(true);
expect(resolveFinding).toHaveBeenCalledWith('finding-resolve');
expect(AIAPI.getUnifiedFindings).toHaveBeenCalledTimes(1);
expect(getPatrolFindings).toHaveBeenCalledTimes(1);
});
it('reopens a dismissed finding and refreshes full Patrol history', async () => {
vi.mocked(reopenFinding).mockResolvedValueOnce({ success: true, message: 'ok' } as never);
vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({ findings: [] } as never);
vi.mocked(getPatrolFindings).mockResolvedValueOnce([]);
const ok = await aiIntelligenceStore.reopenFinding('finding-reopen');
expect(ok).toBe(true);
expect(reopenFinding).toHaveBeenCalledWith('finding-reopen');
expect(AIAPI.getUnifiedFindings).toHaveBeenCalledTimes(1);
expect(getPatrolFindings).toHaveBeenCalledWith({ includeResolved: true, limit: 200 });
});
it('promotes remind_at on dismissed-as-will_fix_later patrol findings to camelCase remindAt', async () => {
// The store-level UnifiedFinding is what render code consumes; if the
// normalizer drops remind_at, the dismiss confirmation panel and the
// dismissed-row badge cannot show the operator their pending commitment.
// Pin the wiring so the field cannot silently regress in either source.
vi.mocked(getPatrolFindings).mockResolvedValueOnce([
{
id: 'patrol-finding-wfl',
severity: 'warning',
category: 'reliability',
resource_id: 'instance:node:100',
resource_name: 'vm-100',
resource_type: 'vm',
title: 'Disk pressure',
description: 'Will fix during the Q3 storage upgrade.',
detected_at: '2026-05-09T10:00:00Z',
last_seen_at: '2026-05-09T10:05:00Z',
auto_resolved: false,
times_raised: 2,
suppressed: false,
investigation_attempts: 0,
dismissed_reason: 'will_fix_later',
remind_at: '2026-05-16T10:00:00Z',
},
]);
await aiIntelligenceStore.loadPatrolFindings();
expect(aiIntelligenceStore.patrolFindings).toHaveLength(1);
expect(aiIntelligenceStore.patrolFindings[0]).toMatchObject({
id: 'patrol-finding-wfl',
dismissedReason: 'will_fix_later',
remindAt: '2026-05-16T10:00:00Z',
});
vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({
findings: [
{
id: 'unified-finding-wfl',
source: 'ai-patrol',
severity: 'warning',
category: 'reliability',
resource_id: 'instance:node:100',
resource_name: 'vm-100',
resource_type: 'vm',
title: 'Disk pressure',
description: 'Will fix during the Q3 storage upgrade.',
detected_at: '2026-05-09T10:00:00Z',
last_seen_at: '2026-05-09T10:05:00Z',
times_raised: 2,
dismissed_reason: 'will_fix_later',
remind_at: '2026-05-16T10:00:00Z',
},
],
} as never);
await aiIntelligenceStore.loadFindings();
expect(aiIntelligenceStore.findings).toHaveLength(1);
expect(aiIntelligenceStore.findings[0]).toMatchObject({
id: 'unified-finding-wfl',
dismissedReason: 'will_fix_later',
remindAt: '2026-05-16T10:00:00Z',
});
});
it('promotes capacity_forecast on patrol findings to camelCase capacityForecast', async () => {
// capacity_forecast is the deterministic urgency signal (days-to-full,
// current %, daily change). The store-level UnifiedFinding is what the
// findings panel reads; if the normalizer drops capacity_forecast, the
// deterministic urgency line can never render and the operator only sees
// the model's prose. Pin the wiring through both the patrol-direct and
// unified-finding paths.
vi.mocked(getPatrolFindings).mockResolvedValueOnce([
{
id: 'patrol-finding-forecast',
severity: 'warning',
category: 'capacity',
resource_id: 'storage-tower',
resource_name: 'Tower Array',
resource_type: 'storage',
title: 'Storage pool Tower Array at 86% usage',
description: 'Pool is filling.',
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,
capacity_forecast: {
metric: 'storage',
current_pct: 86,
daily_change: 1.4,
days_to_full: 10,
},
},
]);
await aiIntelligenceStore.loadPatrolFindings();
expect(aiIntelligenceStore.patrolFindings).toHaveLength(1);
expect(aiIntelligenceStore.patrolFindings[0]).toMatchObject({
id: 'patrol-finding-forecast',
capacityForecast: {
metric: 'storage',
current_pct: 86,
daily_change: 1.4,
days_to_full: 10,
},
});
});
it('loads the canonical intelligence summary', async () => {
vi.mocked(AIAPI.getIntelligenceSummary).mockResolvedValueOnce({
timestamp: '2026-03-01T00:00:00Z',
overall_health: {
score: 87,
grade: 'B',
trend: 'stable',
factors: [],
prediction: 'Stable',
},
findings_count: {
critical: 1,
warning: 2,
watch: 0,
info: 4,
total: 7,
},
predictions_count: 3,
recent_changes_count: 1,
recent_changes: [
{
id: 'change-1',
observedAt: '2026-03-01T00:00:00Z',
resourceId: 'vm-100',
kind: 'config_update',
sourceType: 'pulse_diff',
confidence: 'high',
},
],
policy_posture: {
total_resources: 4,
sensitivity_counts: {
public: 1,
internal: 1,
sensitive: 1,
restricted: 1,
},
routing_counts: {
'cloud-summary': 2,
'local-first': 1,
'local-only': 1,
},
redaction_counts: {
hostname: 2,
'ip-address': 1,
},
},
learning: {
resources_with_knowledge: 4,
total_notes: 11,
resources_with_baselines: 3,
patterns_detected: 2,
correlations_learned: 1,
incidents_tracked: 5,
},
});
await aiIntelligenceStore.loadIntelligenceSummary();
expect(aiIntelligenceStore.intelligenceSummary).toMatchObject({
findings_count: {
critical: 1,
warning: 2,
total: 7,
},
recent_changes_count: 1,
policy_posture: {
total_resources: 4,
},
});
expect(aiIntelligenceStore.intelligenceSummary?.recent_changes).toHaveLength(1);
expect(aiIntelligenceStore.intelligenceSummary?.learning.correlations_learned).toBe(1);
expect(
aiIntelligenceStore.intelligenceSummary?.policy_posture?.sensitivity_counts?.public,
).toBe(1);
expect(
aiIntelligenceStore.intelligenceSummary?.policy_posture?.routing_counts?.['local-only'],
).toBe(1);
});
it('normalizes the canonical intelligence summary at the store boundary', async () => {
vi.mocked(AIAPI.getIntelligenceSummary).mockResolvedValueOnce({
timestamp: '2026-03-01T00:00:00Z',
overall_health: {
score: 87,
grade: 'B',
trend: 'stable',
factors: [],
prediction: 'Stable',
},
findings_count: {
critical: 0,
warning: 0,
watch: 0,
info: 0,
total: 0,
},
predictions_count: 0,
recent_changes_count: Number.NaN,
recent_changes: [
{
id: 'change-1',
observedAt: '2026-03-01T00:00:00Z',
resourceId: 'vm-100',
kind: 'config_update',
sourceType: 'pulse_diff',
confidence: 'high',
},
],
policy_posture: {
total_resources: Number.NaN,
sensitivity_counts: {
public: Number.NaN,
},
routing_counts: {
'cloud-summary': 1,
'local-only': 1,
},
},
learning: {
resources_with_knowledge: 0,
total_notes: 0,
resources_with_baselines: 0,
patterns_detected: 0,
correlations_learned: 0,
incidents_tracked: 0,
},
});
await aiIntelligenceStore.loadIntelligenceSummary();
expect(aiIntelligenceStore.intelligenceSummary?.recent_changes_count).toBe(1);
expect(aiIntelligenceStore.intelligenceSummary?.policy_posture).toEqual({
total_resources: 2,
sensitivity_counts: {},
routing_counts: {
'cloud-summary': 1,
'local-only': 1,
},
});
});
it('loads the canonical AI dashboard bundle', async () => {
vi.mocked(AIAPI.getIntelligenceSummary).mockResolvedValueOnce({
timestamp: '2026-03-01T00:00:00Z',
overall_health: {
score: 87,
grade: 'B',
trend: 'stable',
factors: [],
prediction: 'Stable',
},
findings_count: {
critical: 0,
warning: 0,
watch: 0,
info: 0,
total: 0,
},
predictions_count: 0,
recent_changes_count: 0,
recent_changes: [],
learning: {
resources_with_knowledge: 0,
total_notes: 0,
resources_with_baselines: 0,
patterns_detected: 0,
correlations_learned: 0,
incidents_tracked: 0,
},
});
await aiIntelligenceStore.loadDashboardData();
expect(AIAPI.getIntelligenceSummary).toHaveBeenCalledTimes(1);
expect(aiIntelligenceStore.intelligenceSummary?.findings_count.total).toBe(0);
// These are every AIAPI read the bundle makes (Patrol findings come from
// the Patrol API module). It does not load the global learned-correlation
// list: no page renders it, and the resource drawer reads per-resource
// correlations from resource intelligence instead. Nor does it load the
// provider circuit-breaker status, which no surface renders.
const aiReads = Object.entries(AIAPI)
.filter(([, read]) => vi.isMockFunction(read) && read.mock.calls.length > 0)
.map(([name]) => name)
.sort();
expect(aiReads).toEqual([
'getIntelligenceSummary',
'getPendingApprovals',
'getUnifiedFindings',
]);
expect(getPatrolFindings).toHaveBeenCalledTimes(1);
});
it('treats queued fixes without a live approval as findings needing attention', async () => {
vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({
findings: [
{
id: 'finding-queued',
source: 'ai-patrol',
severity: 'warning',
category: 'performance',
resource_id: 'instance:node:200',
resource_name: 'node-200',
resource_type: 'host',
title: 'Queued remediation',
description: 'Patrol queued a remediation.',
detected_at: '2026-03-01T00:00:00Z',
status: 'active',
investigation_outcome: 'fix_queued',
},
],
count: 1,
});
vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([]);
await aiIntelligenceStore.loadFindings();
await aiIntelligenceStore.loadPendingApprovals();
expect(aiIntelligenceStore.findingsNeedingAttention.map((finding) => finding.id)).toEqual([
'finding-queued',
]);
expect(aiIntelligenceStore.findingsWithPendingApprovals).toEqual([]);
vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([
{
id: 'approval-1',
toolId: 'investigation_fix',
command: 'systemctl restart pulse-agent',
targetType: 'host',
targetId: 'finding-queued',
targetName: 'node-200',
context: 'Restart the agent',
riskLevel: 'medium',
status: 'pending',
requestedAt: '2026-03-01T00:01:00Z',
expiresAt: approvalExpiryInMinutes(6),
},
]);
await aiIntelligenceStore.loadPendingApprovals();
expect(aiIntelligenceStore.findingsNeedingAttention).toEqual([]);
expect(aiIntelligenceStore.findingsWithPendingApprovals.map((finding) => finding.id)).toEqual([
'finding-queued',
]);
});
it('keeps Assistant approvals resumable while Patrol views stay scoped to investigation_fix approvals', async () => {
vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([
{
id: 'approval-chat',
toolId: 'run_command',
command: 'apt upgrade',
targetType: 'host',
targetId: 'host-1',
targetName: 'node-1',
context: 'Upgrade packages',
riskLevel: 'high',
status: 'pending',
requestedAt: '2026-03-01T00:01:00Z',
expiresAt: approvalExpiryInMinutes(6),
},
{
id: 'approval-fix',
toolId: 'investigation_fix',
command: 'systemctl restart pulse-agent',
targetType: 'host',
targetId: 'finding-queued',
targetName: 'node-200',
context: 'Restart the agent',
riskLevel: 'medium',
status: 'pending',
requestedAt: '2026-03-01T00:01:00Z',
expiresAt: approvalExpiryInMinutes(6),
},
]);
await aiIntelligenceStore.loadPendingApprovals();
expect(aiIntelligenceStore.pendingApprovals.map((approval) => approval.id)).toEqual([
'approval-chat',
'approval-fix',
]);
expect(aiIntelligenceStore.patrolPendingApprovals.map((approval) => approval.id)).toEqual([
'approval-fix',
]);
expect(aiIntelligenceStore.pendingApprovalCount).toBe(2);
expect(aiIntelligenceStore.patrolPendingApprovalCount).toBe(1);
});
it('fails Patrol approval polling closed in public demo mode', async () => {
vi.mocked(presentationPolicyIsDemoMode).mockReturnValue(true);
await aiIntelligenceStore.loadPendingApprovals();
expect(AIAPI.getPendingApprovals).not.toHaveBeenCalled();
expect(aiIntelligenceStore.pendingApprovals).toEqual([]);
expect(aiIntelligenceStore.pendingApprovalCount).toBe(0);
expect(aiIntelligenceStore.approvalsError).toBeNull();
});
it('drops expired approvals from Patrol counts and restores needs-attention immediately', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-03-01T00:05:00Z'));
vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({
findings: [
{
id: 'finding-queued',
source: 'ai-patrol',
severity: 'warning',
category: 'performance',
resource_id: 'instance:node:200',
resource_name: 'node-200',
resource_type: 'host',
title: 'Queued remediation',
description: 'Patrol queued a remediation.',
detected_at: '2026-03-01T00:00:00Z',
status: 'active',
investigation_outcome: 'fix_queued',
},
],
count: 1,
});
vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([
{
id: 'approval-fix',
toolId: 'investigation_fix',
command: 'systemctl restart pulse-agent',
targetType: 'host',
targetId: 'finding-queued',
targetName: 'node-200',
context: 'Restart the agent',
riskLevel: 'medium',
status: 'pending',
requestedAt: '2026-03-01T00:01:00Z',
expiresAt: '2026-03-01T00:06:00Z',
},
]);
await aiIntelligenceStore.loadFindings();
await aiIntelligenceStore.loadPendingApprovals();
expect(aiIntelligenceStore.pendingApprovalCount).toBe(1);
expect(aiIntelligenceStore.findingsWithPendingApprovals.map((finding) => finding.id)).toEqual([
'finding-queued',
]);
expect(aiIntelligenceStore.findingsNeedingAttention).toEqual([]);
await vi.advanceTimersByTimeAsync(61_000);
expect(aiIntelligenceStore.pendingApprovalCount).toBe(0);
expect(aiIntelligenceStore.findingsWithPendingApprovals).toEqual([]);
expect(aiIntelligenceStore.findingsNeedingAttention.map((finding) => finding.id)).toEqual([
'finding-queued',
]);
vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([]);
await aiIntelligenceStore.loadPendingApprovals();
vi.useRealTimers();
});
it('fails malformed approval expiries closed and restores needs-attention state', async () => {
vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({
findings: [
{
id: 'finding-malformed-approval',
source: 'ai-patrol',
severity: 'warning',
category: 'performance',
resource_id: 'instance:node:202',
resource_name: 'node-202',
resource_type: 'host',
title: 'Queued remediation with malformed approval',
description: 'Patrol queued a remediation with malformed approval expiry.',
detected_at: '2026-03-01T00:00:00Z',
status: 'active',
investigation_outcome: 'fix_queued',
},
],
count: 1,
});
vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([
{
id: 'approval-malformed-expiry',
toolId: 'investigation_fix',
command: 'systemctl restart pulse-agent',
targetType: 'host',
targetId: 'finding-malformed-approval',
targetName: 'node-202',
context: 'Restart the agent',
riskLevel: 'medium',
status: 'pending',
requestedAt: '2026-03-01T00:01:00Z',
expiresAt: 'not-a-date',
},
]);
await aiIntelligenceStore.loadFindings();
await aiIntelligenceStore.loadPendingApprovals();
expect(aiIntelligenceStore.pendingApprovalCount).toBe(0);
expect(aiIntelligenceStore.findingsWithPendingApprovals).toEqual([]);
expect(aiIntelligenceStore.findingsNeedingAttention.map((finding) => finding.id)).toEqual([
'finding-malformed-approval',
]);
});
it('sorts Patrol runtime findings to the top of the shared needs-attention queue', async () => {
vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({
findings: [
{
id: 'infra-warning',
source: 'ai-patrol',
severity: 'warning',
category: 'infrastructure',
resource_id: 'instance:node:101',
resource_name: 'db-01',
resource_type: 'host',
title: 'Disk nearly full',
description: 'Storage usage is high.',
detected_at: '2026-03-01T00:00:00Z',
status: 'active',
investigation_outcome: 'fix_verification_unknown',
},
{
id: 'runtime-warning',
source: 'ai-patrol',
severity: 'warning',
category: 'service',
resource_id: 'ai-service',
resource_name: 'Pulse Patrol Service',
resource_type: 'service',
title: 'Pulse Patrol: Provider billing or quota issue',
description: 'Provider billing or quota needs attention.',
detected_at: '2026-03-01T00:01:00Z',
last_seen_at: '2026-03-01T00:05:00Z',
status: 'active',
investigation_outcome: 'fix_failed',
},
],
count: 2,
});
vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([]);
await aiIntelligenceStore.loadFindings();
await aiIntelligenceStore.loadPendingApprovals();
expect(aiIntelligenceStore.findingsNeedingAttention.map((finding) => finding.id)).toEqual([
'runtime-warning',
'infra-warning',
]);
});
it('sorts pending approvals and approval-linked findings by urgency', async () => {
vi.mocked(AIAPI.getUnifiedFindings).mockResolvedValueOnce({
findings: [
{
id: 'finding-later',
source: 'ai-patrol',
severity: 'warning',
category: 'performance',
resource_id: 'instance:node:200',
resource_name: 'node-200',
resource_type: 'host',
title: 'Queued remediation later',
description: 'Later approval.',
detected_at: '2026-03-01T00:00:00Z',
status: 'active',
investigation_outcome: 'fix_queued',
},
{
id: 'finding-sooner',
source: 'ai-patrol',
severity: 'warning',
category: 'performance',
resource_id: 'instance:node:201',
resource_name: 'node-201',
resource_type: 'host',
title: 'Queued remediation sooner',
description: 'Sooner approval.',
detected_at: '2026-03-01T00:00:00Z',
status: 'active',
investigation_outcome: 'fix_queued',
},
],
count: 2,
});
vi.mocked(AIAPI.getPendingApprovals).mockResolvedValueOnce([
{
id: 'approval-later',
toolId: 'investigation_fix',
command: 'restart later',
targetType: 'host',
targetId: 'finding-later',
targetName: 'node-200',
context: 'Later approval',
riskLevel: 'low',
status: 'pending',
requestedAt: '2026-03-01T00:01:00Z',
expiresAt: approvalExpiryInMinutes(10),
},
{
id: 'approval-sooner',
toolId: 'investigation_fix',
command: 'restart sooner',
targetType: 'host',
targetId: 'finding-sooner',
targetName: 'node-201',
context: 'Sooner approval',
riskLevel: 'high',
status: 'pending',
requestedAt: '2026-03-01T00:02:00Z',
expiresAt: approvalExpiryInMinutes(6),
},
]);
await aiIntelligenceStore.loadFindings();
await aiIntelligenceStore.loadPendingApprovals();
expect(aiIntelligenceStore.pendingApprovals.map((approval) => approval.id)).toEqual([
'approval-sooner',
'approval-later',
]);
expect(aiIntelligenceStore.findingsWithPendingApprovals.map((finding) => finding.id)).toEqual([
'finding-sooner',
'finding-later',
]);
});
it('keeps resolved Patrol history bounded when the expanded findings set is sticky', async () => {
vi.mocked(getPatrolFindings).mockResolvedValue([]);
await aiIntelligenceStore.loadPatrolFindings({ includeResolved: true });
await aiIntelligenceStore.loadPatrolFindings();
expect(getPatrolFindings).toHaveBeenNthCalledWith(1, {
includeResolved: true,
limit: 200,
});
expect(getPatrolFindings).toHaveBeenNthCalledWith(2, {
includeResolved: true,
limit: 200,
});
});
});