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.

frontend: Patrol intelligence surface, shared primitives, and platform parity

rcourtman27ba85ddc61a
diff --git a/frontend-modern/public/docs/PRIVACY.md b/frontend-modern/public/docs/PRIVACY.md
index 50ecd7acab..31c6b7be3f 100644
--- a/frontend-modern/public/docs/PRIVACY.md
+++ b/frontend-modern/public/docs/PRIVACY.md
@@ -14,9 +14,9 @@ third-party analytics, support diagnostics, or ordinary Settings surfaces.
### Anonymous outbound telemetry
-Pulse includes anonymous outbound telemetry that is **enabled by default**. It sends a lightweight ping on startup and once every 24 hours to help me understand how many active installations exist, which releases are actually deployed, and which features are in use.
+Pulse includes anonymous outbound telemetry that is **enabled by default**. It sends a lightweight ping on startup and once every 24 hours to help me understand how many active installations exist, which releases are actually deployed, which features are in use, and whether Patrol control and governed Pulse Intelligence operations are being adopted.
-No hostnames, credentials, infrastructure identifiers, IP addresses, prompts, chat messages, or personally identifiable information is ever sent. See the full field list below.
+No hostnames, credentials, infrastructure identifiers, IP addresses, prompts, chat messages, command text, action output, token values, or personally identifiable information is ever sent. See the full field list below.
#### How to disable
@@ -80,11 +80,69 @@ Every field is listed below with the reason it exists — nothing else leaves yo
| Multi-tenant | `true`/`false` | See whether multi-tenant/runtime-org features are being used |
| Paid license | `true`/`false` | Distinguish free from paid posture without sending the exact commercial tier |
| Has API tokens | `true`/`false` | See whether token-based automation/integration is being used without sending token counts |
+| Pulse Intelligence configured | `true`/`false` | See whether Assistant, Patrol, governed actions, or external-agent access is configured so adoption can be measured without sending configuration details |
+| Pulse Intelligence active 30d | `true`/`false` | See whether Assistant, Patrol, external-agent, or governed-action activity occurred in the current 30-day telemetry window |
+| Pulse Intelligence governed decision 30d | `true`/`false` | See whether Patrol issue activity reached an approved or rejected governed-action decision without sending prompts, findings, resource identifiers, command text, or action output |
+| Pulse Intelligence approved action attempt 30d | `true`/`false` | See whether Patrol issue activity reached an approved governed action attempt without sending action details |
+| Pulse Intelligence resolved issue 30d | `true`/`false` | See whether Patrol issue activity reached resolution with an approved action success without sending prompts, findings, resource identifiers, command text, or action output |
+| Pulse Intelligence Patrol mode decision 30d | `true`/`false` | See whether a Patrol mode starter, Patrol issue activity, contextual Assistant or external-agent collaboration, and either a rejected governed decision or an approved governed decision with a verified outcome occurred without sending prompt text, checkout details, account links, token details, resource identifiers, command text, or action output |
+| Pulse Intelligence Patrol mode resolved issue 30d | `true`/`false` | See whether a Patrol mode starter, Patrol issue activity, contextual Assistant or external-agent collaboration, an approved governed decision, and a verified outcome occurred without sending prompt text, checkout details, account links, token details, resource identifiers, command text, or action output |
+| Pulse Intelligence paid Patrol mode decision 30d | `true`/`false` | See whether the install currently has a paid license and Patrol mode reached a governed decision without sending the exact tier, checkout details, account links, prompts, token details, resource identifiers, command text, or action output |
+| Pulse Intelligence paid Patrol mode resolved issue 30d | `true`/`false` | See whether the install currently has a paid license and Patrol mode reached a resolved issue without sending the exact tier, checkout details, account links, prompts, token details, resource identifiers, command text, or action output |
+| Pulse Intelligence historical Patrol mode decision mirror 30d | `true`/`false` | Compatibility mirror of the Patrol mode decision field for historical aggregate reporting without sending prompt text, checkout details, account links, token details, resource identifiers, command text, or action output |
+| Pulse Intelligence historical Patrol mode resolved mirror 30d | `true`/`false` | Compatibility mirror of the Patrol mode resolved field for historical aggregate reporting without sending prompt text, checkout details, account links, token details, resource identifiers, command text, or action output |
+| Pulse Intelligence paid historical Patrol mode decision mirror 30d | `true`/`false` | Compatibility mirror of the paid Patrol mode decision field for historical aggregate reporting without sending exact tier, checkout details, account links, token details, resource identifiers, command text, or action output |
+| Pulse Intelligence paid historical Patrol mode resolved mirror 30d | `true`/`false` | Compatibility mirror of the paid Patrol mode resolved field for historical aggregate reporting without sending exact tier, checkout details, account links, token details, resource identifiers, command text, or action output |
+| Pulse Intelligence governed action active 30d | `true`/`false` | See whether Patrol or Assistant reached action planning, approval, approve/reject decision, or approved-action depth in the current 30-day telemetry window without sending action details |
+| Pulse Intelligence Assistant governed decision 30d | `true`/`false` | See whether Assistant collaboration specifically reached the Patrol issue plus approved/rejected governed-action path without sending prompts, chat messages, tool details, findings, command text, or action output |
+| Pulse Intelligence Assistant approved action attempt 30d | `true`/`false` | See whether Assistant collaboration specifically reached approved governed-action execution in the 30-day window without sending prompts, chat messages, command text, actors, or action output |
+| Pulse Intelligence Assistant approved action success 30d | `true`/`false` | See whether Assistant collaboration specifically reached approved action success in the 30-day window without sending prompts, chat messages, verification details, command text, or action output |
+| Pulse Intelligence Assistant resolved issue 30d | `true`/`false` | See whether Assistant collaboration specifically reached Patrol resolution plus approved action success in the 30-day window without sending findings, prompts, chat messages, verification details, command text, or action output |
+| Pulse Intelligence external-agent governed decision 30d | `true`/`false` | See whether direct external-agent or MCP collaboration reached the Patrol issue plus approved/rejected governed-action path without sending route parameters, prompts, resource identifiers, command text, or action output |
+| Pulse Intelligence external-agent approved action attempt 30d | `true`/`false` | See whether direct external-agent or MCP collaboration reached approved governed-action execution in the 30-day window without sending route parameters, command text, actors, or action output |
+| Pulse Intelligence external-agent approved action success 30d | `true`/`false` | See whether direct external-agent or MCP collaboration reached approved action success in the 30-day window without sending route parameters, command text, verification details, or action output |
+| Pulse Intelligence external-agent resolved issue 30d | `true`/`false` | See whether direct external-agent or MCP collaboration reached Patrol resolution plus approved action success in the 30-day window without sending findings, route parameters, command text, verification details, or action output |
+| Pulse Intelligence `pulse-mcp` governed decision 30d | `true`/`false` | See whether the `pulse-mcp` adapter specifically reached the Patrol issue plus approved/rejected governed-action path without sending prompts, tool inputs, route parameters, resource identifiers, command text, or action output |
+| Pulse Intelligence `pulse-mcp` approved action attempt 30d | `true`/`false` | See whether the `pulse-mcp` adapter specifically reached approved governed-action execution in the 30-day window without sending prompts, tool inputs, command text, actors, or action output |
+| Pulse Intelligence `pulse-mcp` approved action success 30d | `true`/`false` | See whether the `pulse-mcp` adapter specifically reached approved action success in the 30-day window without sending prompts, tool inputs, verification details, command text, or action output |
+| Pulse Intelligence `pulse-mcp` resolved issue 30d | `true`/`false` | See whether the `pulse-mcp` adapter specifically reached Patrol resolution plus approved action success in the 30-day window without sending findings, prompts, tool inputs, verification details, command text, or action output |
+| Pulse Intelligence starter requests 30d | `3` | Count shared Patrol-work starter requests in the current 30-day telemetry window without sending prompt text, chat messages, tool inputs, resource IDs, or request details |
+| Pulse Intelligence Assistant starter requests 30d | `2` | Count Assistant requests for shared Patrol work in the current 30-day telemetry window without sending prompt text, chat messages, resource IDs, or request details |
+| Pulse Intelligence Patrol starter requests 30d | `1` | Count Patrol work starter requests in the current 30-day telemetry window without sending prompt text, findings, resource IDs, or request details |
+| Pulse Intelligence Patrol mode starter requests 30d | `1` | Count Patrol work, Patrol-mode, and historical entry-point requests for shared Patrol work in the current 30-day telemetry window without sending prompt text, checkout details, account links, resource IDs, or request details |
+| Pulse Intelligence historical Patrol mode starter mirror 30d | `1` | Count historical entry-point requests for Patrol mode in the current 30-day telemetry window without sending prompt text, checkout details, account links, resource IDs, or request details |
+| Pulse Intelligence `pulse-mcp` starter requests 30d | `1` | Count `pulse-mcp` requests for shared Patrol work in the current 30-day telemetry window without sending prompt text, tool inputs, resource IDs, route parameters, or request details |
+| Pulse Intelligence Assistant AI calls 30d | `18` | Count Assistant model calls in the current 30-day telemetry window without sending prompts, responses, session IDs, or chat text |
+| Pulse Intelligence Assistant context AI calls 30d | `7` | Count Assistant model calls tied to a governed resource, finding, handoff, or action context in the current 30-day telemetry window without sending prompts, responses, session IDs, resource IDs, finding IDs, or chat text |
+| Pulse Intelligence Assistant tool calls 30d | `11` | Count Assistant tool calls in the current 30-day telemetry window without sending tool names, tool inputs, tool outputs, prompts, responses, session IDs, resource IDs, finding IDs, command text, or chat text |
+| Pulse Intelligence Patrol AI calls 30d | `6` | Count Patrol model calls in the current 30-day telemetry window without sending provider-bound context or findings text |
+| Pulse Intelligence Patrol runs 30d | `12` | Count Patrol investigations in the current 30-day telemetry window |
+| Pulse Intelligence Patrol new findings 30d | `5` | Count new findings produced by Patrol in the current 30-day telemetry window without sending finding IDs or details |
+| Pulse Intelligence Patrol investigations 30d | `3` | Count findings investigated by Patrol in the current 30-day telemetry window without sending finding IDs, resource IDs, or details |
+| Pulse Intelligence Patrol resolved findings 30d | `2` | Count findings resolved or fix-verified in the current 30-day telemetry window without sending finding IDs, resource IDs, fix details, or verification detail |
+| Pulse Intelligence Patrol autofixes 30d | `1` | Count Patrol autofix records in the current 30-day telemetry window without sending target resources or fix content |
+| Pulse Intelligence external agent enabled | `true`/`false` | See whether at least one token can use the external Pulse Intelligence agent/MCP surface without sending token counts, names, scopes, or values |
+| Pulse Intelligence external agent used 30d | `true`/`false` | See whether an external-agent-capable API token reached a Pulse Intelligence agent/MCP route in the current 30-day telemetry window without sending token identity, route parameters, resource IDs, or request details |
+| Pulse Intelligence MCP adapter used 30d | `true`/`false` | See whether the `pulse-mcp` adapter reached a Pulse Intelligence agent/MCP route in the current 30-day telemetry window without sending token identity, route parameters, resource IDs, prompts, or request details |
+| Pulse Intelligence external agent context requests 30d | `8` | Count external-agent/MCP resource-context and fleet-context requests in the current 30-day telemetry window without sending resource IDs, route parameters, or request details |
+| Pulse Intelligence external agent event stream requests 30d | `3` | Count external-agent/MCP event-stream requests in the current 30-day telemetry window without sending event content, route parameters, or request details |
+| Pulse Intelligence external agent provisioning requests 30d | `2` | Count external-agent/MCP provisioning requests in the current 30-day telemetry window without sending discovered resources, credentials, route parameters, or request details |
+| Pulse Intelligence external agent operator state requests 30d | `5` | Count external-agent/MCP operator-state requests in the current 30-day telemetry window without sending state payloads, route parameters, or request details |
+| Pulse Intelligence external agent finding requests 30d | `4` | Count external-agent/MCP finding-list and finding-decision requests in the current 30-day telemetry window without sending finding IDs, finding text, route parameters, or request details |
+| Pulse Intelligence external agent action requests 30d | `1` | Count external-agent/MCP action-plan, action-decision, and action-execution requests in the current 30-day telemetry window without sending command text, action output, route parameters, or request details |
+| Pulse Intelligence action plans 30d | `4` | Count governed action plans in the current 30-day telemetry window without sending command text, resource IDs, or plan details |
+| Pulse Intelligence approval requests 30d | `2` | Count approval-gated action requests in the current 30-day telemetry window without sending approvers, reasons, command text, or targets |
+| Pulse Intelligence rejected action decisions 30d | `1` | Count rejected governed action decisions in the current 30-day telemetry window without sending approvers, reasons, command text, targets, or action IDs |
+| Pulse Intelligence approved action decisions 30d | `1` | Count approved governed action decisions in the current 30-day telemetry window without sending approvers, reasons, command text, targets, or action IDs |
+| Pulse Intelligence approved action attempts 30d | `1` | Count approved governed action attempts in the current 30-day telemetry window without sending action output, command text, or verification detail |
+| Pulse Intelligence approved action successes 30d | `1` | Count approved governed actions that completed successfully in the current 30-day telemetry window without sending action output, command text, resource IDs, actors, reasons, or verification detail |
#### Server-side handling and retention
- Telemetry pings are stored on the Pulse license server only for aggregate install/use analysis.
-- The license server stores only the same coarse telemetry fields listed above; it does not expand them into exact commercial tiers or exact API-token counts.
+- The license server stores only the same coarse telemetry fields listed above; it does not expand them into exact commercial tiers, exact API-token counts, prompts, chat messages, command text, action output, token values, or resource identifiers.
+- Pulse may derive aggregate Pulse Intelligence adoption reports from those same rows, including whether an install reached Patrol issue activity, Patrol resolution, Assistant, direct external-agent, or MCP collaboration, Patrol mode starter use, paid Patrol mode cohorts, governed-action activity, approved or rejected action decisions, approved action success, recent retention, and observed free-to-paid movement within the source window. Those reports do not add prompts, findings, resource identifiers, tool names, tool inputs, tool outputs, command payloads, action outputs, account links, or exact commercial tiers.
+- External-agent/MCP activity is stored only as a coarse adapter-origin flag plus capability-class counters: context, event stream, provisioning, operator state, findings, and action requests.
- Telemetry rows older than **90 days** are purged automatically.
- The license server uses client IP addresses transiently for abuse/rate limiting, but it does **not** store IP addresses in telemetry rows.
@@ -93,7 +151,7 @@ Every field is listed below with the reason it exists — nothing else leaves yo
- No IP addresses are stored in telemetry rows
- No hostnames, node names, VM names, or any infrastructure identifiers
- No Proxmox credentials, API tokens, or passwords
-- No alert content, AI prompts, or chat messages
+- No alert content, AI prompts, chat messages, tool names, tool inputs, tool outputs, command text, action output, or token values
- No personally identifiable information of any kind
#### Install ID rotation
diff --git a/frontend-modern/scripts/__tests__/settings-diagnostics-boundary-audit.test.mjs b/frontend-modern/scripts/__tests__/settings-diagnostics-boundary-audit.test.mjs
index e31aa55d0b..dd2b86695a 100644
--- a/frontend-modern/scripts/__tests__/settings-diagnostics-boundary-audit.test.mjs
+++ b/frontend-modern/scripts/__tests__/settings-diagnostics-boundary-audit.test.mjs
@@ -96,6 +96,33 @@ export function stripInternalAnalyticsDiagnosticsFields(payload) {
expect(collectUserDiagnosticsInternalAnalyticsFindings({ root, repoRoot })).toEqual([]);
});
+ it('reports legacy MCP vocabulary on native Assistant diagnostics', () => {
+ const { root, repoRoot } = makeFixture(({ root, repoRoot }) => ({
+ [path.join(repoRoot, 'internal', 'api', 'diagnostics.go')]: `
+package api
+
+type AIChatDiagnostic struct {
+ MCPConnected bool
+}
+`,
+ [path.join(root, 'src', 'components', 'Settings', 'DiagnosticsResultsPanel.tsx')]:
+ "export const label = 'MCP Connection';\n",
+ [path.join(root, 'src', 'components', 'Settings', 'diagnosticsModel.ts')]: `
+export interface AIChatDiagnostic {
+ mcpConnected: boolean;
+}
+`,
+ }));
+
+ const findings = collectUserDiagnosticsInternalAnalyticsFindings({ root, repoRoot });
+
+ expect(findings.map((finding) => finding.rule)).toEqual([
+ 'canonical-settings/no-mcp-vocabulary-in-assistant-diagnostics-api',
+ 'canonical-settings/no-mcp-vocabulary-in-assistant-diagnostics-ui',
+ 'canonical-settings/no-mcp-vocabulary-in-assistant-diagnostics-types',
+ ]);
+ });
+
it('reports commercial analytics routes, stores, and settings in product runtime files', () => {
const { root, repoRoot } = makeFixture(({ root, repoRoot }) => ({
[path.join(repoRoot, 'internal', 'api', 'router_routes_licensing.go')]: `
diff --git a/frontend-modern/scripts/settings-diagnostics-boundary-audit.mjs b/frontend-modern/scripts/settings-diagnostics-boundary-audit.mjs
index 59825aab22..a6749c1814 100644
--- a/frontend-modern/scripts/settings-diagnostics-boundary-audit.mjs
+++ b/frontend-modern/scripts/settings-diagnostics-boundary-audit.mjs
@@ -19,6 +19,12 @@ const INTERNAL_ANALYTICS_RULES = [
message:
'Do not expose maintainer/admin analytics from /api/diagnostics or customer product runtime.',
},
+ {
+ rule: 'canonical-settings/no-mcp-vocabulary-in-assistant-diagnostics-api',
+ regex: /\b(?:MCPConnected|MCPToolCount|mcpConnected|mcpToolCount)\b/g,
+ message:
+ 'Do not expose native Pulse Assistant diagnostics through MCP transport fields.',
+ },
],
},
{
@@ -74,6 +80,12 @@ const INTERNAL_ANALYTICS_RULES = [
message:
'Do not render maintainer/admin analytics in the user-facing Settings diagnostics panel.',
},
+ {
+ rule: 'canonical-settings/no-mcp-vocabulary-in-assistant-diagnostics-ui',
+ regex: /\b(?:mcpConnected|mcpToolCount)\b|MCP Connection/g,
+ message:
+ 'Render Pulse Assistant diagnostics as native Assistant runtime availability, not MCP transport state.',
+ },
],
},
{
@@ -87,6 +99,12 @@ const INTERNAL_ANALYTICS_RULES = [
message:
'Do not add commercial funnel or infrastructure onboarding fields to the customer diagnostics payload model.',
},
+ {
+ rule: 'canonical-settings/no-mcp-vocabulary-in-assistant-diagnostics-types',
+ regex: /\b(?:mcpConnected|mcpToolCount)\b/g,
+ message:
+ 'Model Pulse Assistant diagnostics as native Assistant runtime availability, not MCP transport state.',
+ },
],
},
{
diff --git a/frontend-modern/scripts/shared-template-registry.json b/frontend-modern/scripts/shared-template-registry.json
index ee839d3d08..025a85fd2d 100644
--- a/frontend-modern/scripts/shared-template-registry.json
+++ b/frontend-modern/scripts/shared-template-registry.json
@@ -683,8 +683,7 @@
{ "path": "src/components/patrol/ApprovalSection.tsx" },
{ "path": "src/components/patrol/InvestigationMessages.tsx" },
{ "path": "src/components/patrol/InvestigationSection.tsx" },
- { "path": "src/components/patrol/RunToolCallTrace.tsx" },
- { "path": "src/features/patrol/PatrolIntelligenceHeader.tsx" }
+ { "path": "src/components/patrol/RunToolCallTrace.tsx" }
],
"forbiddenPatterns": [
{
@@ -796,12 +795,6 @@
"patterns": [
"h-3 w-3 border-2 border-current border-t-transparent rounded-full animate-spin"
]
- },
- {
- "path": "src/features/patrol/PatrolIntelligenceHeader.tsx",
- "patterns": [
- "animate-spin w-4 h-4 border-2 border-current border-t-transparent rounded-full"
- ]
}
],
"proof": [
@@ -1576,8 +1569,7 @@
{ "path": "src/components/shared/FilterToolbar.tsx" },
{ "path": "src/features/alerts/AlertAppriseDestinationsSection.tsx" },
{ "path": "src/features/alerts/AlertEscalationSection.tsx" },
- { "path": "src/features/alerts/AlertQuietHoursSection.tsx" },
- { "path": "src/features/patrol/PatrolIntelligenceHeader.tsx" }
+ { "path": "src/features/alerts/AlertQuietHoursSection.tsx" }
],
"proof": [
"src/components/shared/SharedPrimitives.guardrails.test.ts",
@@ -1661,28 +1653,12 @@
"requiredConsumers": [
{ "path": "src/components/Settings/AgentProfilesPanel.tsx" },
{ "path": "src/components/Settings/DiagnosticsResultsPanel.tsx" },
- { "path": "src/components/patrol/RunHistoryEntry.tsx" },
- { "path": "src/components/patrol/PatrolStatusBar.tsx" },
- { "path": "src/features/patrol/PatrolIntelligenceSummary.tsx" }
+ { "path": "src/components/patrol/RunHistoryEntry.tsx" }
],
"forbiddenPatterns": [
{
"path": "src/components/patrol/RunHistoryEntry.tsx",
"patterns": ["runStatus.badgeClass"]
- },
- {
- "path": "src/components/patrol/PatrolStatusBar.tsx",
- "patterns": [
- "lastRunStatus.badgeClass",
- "rounded border border-blue-200 bg-blue-50 px-1.5 py-0.5 text-[10px] font-medium text-blue-700"
- ]
- },
- {
- "path": "src/features/patrol/PatrolIntelligenceSummary.tsx",
- "patterns": [
- "runtimeShellPresentation().badgeClass",
- "inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em]"
- ]
}
],
"proof": [
@@ -1896,7 +1872,6 @@
{ "path": "src/components/patrol/InvestigationSection.tsx" },
{ "path": "src/components/patrol/RunHistoryEntry.tsx" },
{ "path": "src/components/patrol/RunToolCallTrace.tsx" },
- { "path": "src/components/patrol/PatrolStatusBar.tsx" },
{ "path": "src/features/proxmox/proxmoxBackupsTableShared.tsx" },
{ "path": "src/features/patrol/PatrolIntelligenceWorkspace.tsx" }
],
@@ -1953,10 +1928,6 @@
"getToolCallResultBadgeClass"
]
},
- {
- "path": "src/components/patrol/PatrolStatusBar.tsx",
- "patterns": ["text-blue-600 dark:text-blue-400\">Findings snapshot unavailable"]
- },
{
"path": "src/features/proxmox/proxmoxBackupsTableShared.tsx",
"patterns": [
diff --git a/frontend-modern/src/api/__tests__/agentCapabilities.test.ts b/frontend-modern/src/api/__tests__/agentCapabilities.test.ts
new file mode 100644
index 0000000000..ac4f4f6ec7
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/agentCapabilities.test.ts
@@ -0,0 +1,849 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ AGENT_CAPABILITIES_PATH,
+ AGENT_OPERATIONS_LOOP_STATUS_PATH,
+ AGENT_SURFACE_ID_PULSE_MCP,
+ fetchAgentCapabilitiesManifest,
+ fetchAgentOperationsLoopStatus,
+ formatAgentMCPServersConfig,
+ formatAgentOpenCodeMCPConfig,
+ getAgentCapabilityErrorCodeSummaries,
+ getAgentMCPOperationsLoopReadiness,
+ getAgentManifestSurfaceToolContract,
+ getAgentManifestSurfaceToolContracts,
+ getAgentMCPClientExamples,
+ getAgentMCPConfigFamilyByShape,
+ getAgentSurfaceToolPosturePresentation,
+ getAgentSurfaceContractEntries,
+ getAgentWorkflowPrompts,
+ groupAgentCapabilitiesByManifestCategories,
+ normalizeAgentMCPAdapter,
+ normalizeAgentSurfaceToolContract,
+ type AgentCapability,
+ type AgentCapabilitiesManifest,
+ type AgentSurfaceToolContract,
+} from '../agentCapabilities';
+import generatedAgentCapabilitiesSource from '@/api/generated/agentCapabilities.ts?raw';
+import { apiFetchJSON } from '@/utils/apiClient';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+}));
+
+const capability = (name: string, category: string): AgentCapability => ({
+ name,
+ category,
+ description: `${name} description`,
+ method: 'GET',
+ path: `/api/${name}`,
+ scope: 'monitoring:read',
+ actionMode: 'read',
+ approvalPolicy: 'scope_only',
+});
+
+const surfaceContract = {
+ core: {
+ id: 'pulse_intelligence_core',
+ label: 'Pulse Intelligence Core',
+ description:
+ 'Canonical context, governed actions, safety gates, approval state, action audit, and verification.',
+ },
+ proactiveEngine: {
+ id: 'pulse_patrol',
+ label: 'Pulse Patrol',
+ description:
+ 'Patrol is the first-party operations surface: it watches, investigates, acts within the chosen Patrol mode, verifies outcomes, and records what happened.',
+ },
+ operatorSurfaces: [
+ {
+ id: 'pulse_assistant',
+ label: 'Pulse Assistant',
+ description:
+ 'The contextual explanation, approval, and handoff surface for Patrol findings, governed actions, verification, and operator questions.',
+ native: true,
+ externalAdapter: false,
+ affordances: {
+ tools: true,
+ interactiveQuestions: true,
+ },
+ },
+ {
+ id: 'pulse_mcp',
+ label: 'Pulse MCP',
+ description: 'The external-agent adapter.',
+ native: false,
+ externalAdapter: true,
+ affordances: {
+ tools: true,
+ resources: true,
+ prompts: true,
+ capabilityMetadata: true,
+ },
+ },
+ ],
+};
+
+const mcpAdapter = {
+ serverName: 'pulse',
+ command: 'pulse-mcp',
+ baseUrlFlag: '--base-url',
+ defaultBaseUrl: 'http://localhost:7655',
+ tokenEnv: 'PULSE_API_TOKEN',
+ configFamilies: [
+ {
+ id: 'opencode',
+ label: 'OpenCode',
+ shape: 'opencode_mcp',
+ description: "Uses OpenCode's top-level mcp object.",
+ fileHints: ['opencode.json', 'opencode.jsonc'],
+ clientLabels: ['OpenCode'],
+ },
+ {
+ id: 'claude-style',
+ label: 'Claude-style clients',
+ shape: 'mcp_servers',
+ description: 'Uses the common mcpServers object.',
+ fileHints: ['claude_desktop_config.json', '.mcp.json'],
+ clientLabels: ['Claude Desktop', 'Claude Code'],
+ },
+ {
+ id: 'custom-mcp',
+ label: 'custom MCP clients',
+ shape: 'custom',
+ clientLabels: ['custom MCP clients'],
+ },
+ ],
+};
+
+describe('agent capabilities API client', () => {
+ it('fetches the public manifest through the shared API client', async () => {
+ const manifest = {
+ version: 'v1',
+ surfaceContract,
+ surfaceToolContracts: [],
+ mcpAdapter,
+ requiredScopes: ['monitoring:read'],
+ categories: [{ id: 'context', label: 'Context (read-only)' }],
+ workflowPrompts: [],
+ capabilities: [capability('get_resource_context', 'context')],
+ } satisfies AgentCapabilitiesManifest;
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce(manifest);
+
+ await expect(fetchAgentCapabilitiesManifest()).resolves.toBe(manifest);
+
+ expect(apiFetchJSON).toHaveBeenCalledWith(AGENT_CAPABILITIES_PATH, {
+ skipAuth: true,
+ headers: { Accept: 'application/json' },
+ });
+ });
+
+ it('fetches the authenticated operations-loop status through the shared API client', async () => {
+ const status = {
+ nextAction: 'open_assistant',
+ progressLabel: 'Open Assistant to explain the Patrol issue and safest next step.',
+ steps: [
+ { id: 'patrol', label: 'Patrol', status: 'complete', count: 1 },
+ { id: 'assistant', label: 'Assistant', status: 'current' },
+ { id: 'governance', label: 'Governance', status: 'pending', count: 0 },
+ { id: 'verification', label: 'Verification', status: 'pending', count: 0 },
+ ],
+ patrolEvidenceCount: 1,
+ patrolIssueEvidenceCount: 1,
+ activeFindingCount: 1,
+ pendingApprovalCount: 0,
+ governedActionCount: 0,
+ approvedDecisionCount: 0,
+ rejectedDecisionCount: 0,
+ verifiedOutcomeCount: 0,
+ operationsLoopStarterCount: 0,
+ assistantOperationsLoopStarterCount: 0,
+ patrolOperationsLoopStarterCount: 0,
+ patrolControlOperationsLoopStarterCount: 0,
+ patrolControlCompletedOperationsLoopCount: 0,
+ patrolControlResolvedOperationsLoopCount: 0,
+ patrolControlValueState: 'not_started',
+ patrolAutonomyOperationsLoopStarterCount: 0,
+ patrolAutonomyCompletedOperationsLoopCount: 0,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ patrolAutonomyValueState: 'not_started',
+ proActivationOperationsLoopStarterCount: 0,
+ proActivationCompletedOperationsLoopCount: 0,
+ proActivationResolvedOperationsLoopCount: 0,
+ proActivationValueProofState: 'not_started',
+ mcpOperationsLoopStarterCount: 0,
+ externalAgentReady: true,
+ windowStart: '2026-06-01T00:00:00Z',
+ generatedAt: '2026-06-20T00:00:00Z',
+ } satisfies Awaited<ReturnType<typeof fetchAgentOperationsLoopStatus>>;
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce(status);
+
+ await expect(fetchAgentOperationsLoopStatus()).resolves.toBe(status);
+
+ expect(apiFetchJSON).toHaveBeenCalledWith(AGENT_OPERATIONS_LOOP_STATUS_PATH, {
+ headers: { Accept: 'application/json' },
+ });
+ });
+
+ it('exports the generated surface tool contract type for Assistant and MCP consumers', () => {
+ const contract: AgentSurfaceToolContract = {
+ surfaceId: 'pulse_assistant',
+ surfaceLabel: 'Pulse Assistant',
+ toolSource: 'assistant_registry',
+ toolNames: ['pulse_query', 'pulse_question'],
+ registryToolNames: ['pulse_query'],
+ nativeToolNames: ['pulse_question'],
+ affordances: {
+ tools: true,
+ interactiveQuestions: true,
+ },
+ };
+
+ expect(contract.surfaceId).toBe('pulse_assistant');
+ expect(contract.registryToolNames).toEqual(['pulse_query']);
+ expect(contract.nativeToolNames).toEqual(['pulse_question']);
+ });
+
+ it('normalizes runtime surface tool contracts without local tool catalog drift', () => {
+ const normalized = normalizeAgentSurfaceToolContract({
+ surfaceId: ' pulse_assistant ',
+ surfaceLabel: ' Pulse Assistant ',
+ toolSource: ' assistant_registry ',
+ toolNames: ['pulse_query', 'pulse_question', 'pulse_query', ' '],
+ registryToolNames: ['pulse_query', 'pulse_query'],
+ nativeToolNames: ['pulse_question'],
+ capabilityNames: [' '],
+ });
+
+ expect(normalized).toEqual({
+ surfaceId: 'pulse_assistant',
+ surfaceLabel: 'Pulse Assistant',
+ toolSource: 'assistant_registry',
+ toolNames: ['pulse_query', 'pulse_question'],
+ registryToolNames: ['pulse_query'],
+ nativeToolNames: ['pulse_question'],
+ capabilityNames: undefined,
+ affordances: {
+ tools: true,
+ interactiveQuestions: true,
+ },
+ });
+ });
+
+ it('presents Assistant capability posture from the surface contract counts', () => {
+ const presentation = getAgentSurfaceToolPosturePresentation({
+ surfaceId: 'pulse_assistant',
+ surfaceLabel: 'Pulse Assistant',
+ toolSource: 'assistant_registry',
+ toolNames: ['pulse_query', 'pulse_question'],
+ registryToolNames: ['pulse_query'],
+ nativeToolNames: ['pulse_question'],
+ });
+
+ expect(presentation).toMatchObject({
+ label: '2 capabilities',
+ tone: 'ready',
+ toolCount: 2,
+ });
+ expect(presentation?.title).toContain('Pulse Assistant capability availability');
+ expect(presentation?.title).toContain('Source: Assistant registry');
+ expect(presentation?.detail).toContain('1 registry capability');
+ expect(presentation?.detail).toContain('1 native capability');
+ expect(presentation?.detail).toContain('Interactive questions');
+ });
+
+ it('uses manifest-owned external-adapter surface tool contracts before local fallback', () => {
+ const surfaceContractWithCLI = {
+ ...surfaceContract,
+ operatorSurfaces: [
+ ...surfaceContract.operatorSurfaces,
+ {
+ id: 'pulse_cli_agent',
+ label: 'Pulse CLI Agent',
+ description: 'Another external-agent adapter.',
+ native: false,
+ externalAdapter: true,
+ affordances: {
+ tools: true,
+ capabilityMetadata: true,
+ },
+ },
+ ],
+ };
+ const manifest = {
+ version: 'v1',
+ surfaceContract: surfaceContractWithCLI,
+ surfaceToolContracts: [
+ {
+ surfaceId: 'pulse_mcp',
+ surfaceLabel: 'Pulse MCP',
+ toolSource: 'capability_manifest',
+ toolNames: ['get_fleet_context'],
+ capabilityNames: ['get_fleet_context'],
+ affordances: {
+ tools: true,
+ resources: true,
+ prompts: true,
+ capabilityMetadata: true,
+ },
+ },
+ {
+ surfaceId: 'pulse_cli_agent',
+ surfaceLabel: 'Pulse CLI Agent',
+ toolSource: 'capability_manifest',
+ toolNames: ['plan_action'],
+ capabilityNames: ['plan_action'],
+ },
+ ],
+ mcpAdapter,
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [],
+ capabilities: [
+ capability('get_fleet_context', 'context'),
+ capability('plan_action', 'actions'),
+ ],
+ } satisfies AgentCapabilitiesManifest;
+
+ const mcp = getAgentManifestSurfaceToolContract(manifest, AGENT_SURFACE_ID_PULSE_MCP);
+ expect(mcp?.toolNames).toEqual(['get_fleet_context']);
+ expect(mcp?.capabilityNames).toEqual(['get_fleet_context']);
+
+ const contracts = getAgentManifestSurfaceToolContracts(manifest);
+ expect(contracts.map((contract) => contract.surfaceId)).toEqual([
+ 'pulse_mcp',
+ 'pulse_cli_agent',
+ ]);
+ expect(contracts[1]?.toolNames).toEqual(['plan_action']);
+ });
+
+ it('does not infer external surface tools when stale payloads omit surface tool contracts', () => {
+ const manifest = {
+ version: 'v1',
+ surfaceContract,
+ surfaceToolContracts: [],
+ mcpAdapter,
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [],
+ capabilities: [
+ capability('get_fleet_context', 'context'),
+ {
+ ...capability('subscribe_events', 'events'),
+ description: 'Subscribe to Pulse Intelligence events.',
+ },
+ capability('plan_action', 'actions'),
+ ],
+ } satisfies AgentCapabilitiesManifest;
+
+ const contract = getAgentManifestSurfaceToolContract(manifest, AGENT_SURFACE_ID_PULSE_MCP);
+
+ expect(contract).toBeUndefined();
+ expect(getAgentSurfaceToolPosturePresentation(contract)).toBeNull();
+ });
+
+ it('gates published external surface tool posture by the manifest surface affordance', () => {
+ const disabledToolSurfaceContract = {
+ ...surfaceContract,
+ operatorSurfaces: surfaceContract.operatorSurfaces.map((surface) =>
+ surface.id === 'pulse_mcp'
+ ? {
+ ...surface,
+ affordances: {
+ resources: true,
+ prompts: true,
+ capabilityMetadata: true,
+ },
+ }
+ : surface,
+ ),
+ };
+ const manifest = {
+ version: 'v1',
+ surfaceContract: disabledToolSurfaceContract,
+ surfaceToolContracts: [
+ {
+ surfaceId: 'pulse_mcp',
+ surfaceLabel: 'Pulse MCP',
+ toolSource: 'capability_manifest',
+ toolNames: ['get_fleet_context'],
+ capabilityNames: ['get_fleet_context'],
+ affordances: {
+ tools: true,
+ resources: true,
+ prompts: true,
+ capabilityMetadata: true,
+ },
+ },
+ ],
+ mcpAdapter,
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [],
+ capabilities: [capability('get_fleet_context', 'context')],
+ } satisfies AgentCapabilitiesManifest;
+
+ const contract = getAgentManifestSurfaceToolContract(manifest, AGENT_SURFACE_ID_PULSE_MCP);
+
+ expect(contract).toMatchObject({
+ surfaceId: 'pulse_mcp',
+ surfaceLabel: 'Pulse MCP',
+ toolSource: 'capability_manifest',
+ toolNames: [],
+ capabilityNames: undefined,
+ affordances: {
+ resources: true,
+ prompts: true,
+ capabilityMetadata: true,
+ },
+ });
+
+ const presentation = getAgentSurfaceToolPosturePresentation(contract);
+ expect(presentation).toMatchObject({
+ label: '0 capabilities',
+ tone: 'empty',
+ toolCount: 0,
+ });
+ expect(presentation?.detail).toContain('Resources');
+ expect(presentation?.detail).not.toContain('published capability');
+ });
+
+ it('does not project native Assistant runtime tools from the static manifest', () => {
+ const manifest = {
+ version: 'v1',
+ surfaceContract,
+ surfaceToolContracts: [],
+ mcpAdapter,
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [],
+ capabilities: [capability('get_fleet_context', 'context')],
+ } satisfies AgentCapabilitiesManifest;
+
+ expect(getAgentManifestSurfaceToolContract(manifest, 'pulse_assistant')).toBeUndefined();
+ expect(getAgentManifestSurfaceToolContract(manifest, 'missing_surface')).toBeUndefined();
+ });
+
+ it('uses manifest-owned category order and presentation copy', () => {
+ const manifest = {
+ version: 'v1',
+ surfaceContract,
+ surfaceToolContracts: [],
+ mcpAdapter,
+ requiredScopes: ['monitoring:read', 'ai:execute'],
+ categories: [
+ {
+ id: 'context',
+ label: 'Context (read-only)',
+ description: 'Discovery and read-only situated reads. Agents start here.',
+ },
+ {
+ id: 'action',
+ label: 'Actions (governed plan/approval/execute)',
+ description: 'Plan, approve, and execute capability invocations against a resource.',
+ },
+ ],
+ capabilities: [
+ capability('plan_action', 'action'),
+ {
+ ...capability('get_patrol_control_status', 'context'),
+ description:
+ 'Return Patrol mode completed/resolved outcome status and compatibility aliases.',
+ },
+ ],
+ workflowPrompts: [],
+ } satisfies AgentCapabilitiesManifest;
+
+ const sections = groupAgentCapabilitiesByManifestCategories(manifest);
+
+ expect(sections.map((section) => section.id)).toEqual(['context', 'action']);
+ expect(sections.map((section) => section.label)).toEqual([
+ 'Context (read-only)',
+ 'Actions (governed plan/approval/execute)',
+ ]);
+ expect(sections[0]?.description).toBe(
+ 'Discovery and read-only situated reads. Agents start here.',
+ );
+ expect(sections[0]?.entries.map((entry) => entry.name)).toEqual(['get_patrol_control_status']);
+ expect(sections[0]?.entries[0]?.description).toBe(
+ 'Return Patrol mode completed/resolved outcome status and compatibility aliases.',
+ );
+ expect(sections[1]?.entries.map((entry) => entry.name)).toEqual(['plan_action']);
+ });
+
+ it('keeps older or extended manifests visible without a local category table', () => {
+ const manifest = {
+ version: 'v1',
+ surfaceContract,
+ surfaceToolContracts: [],
+ mcpAdapter,
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [],
+ capabilities: [
+ capability('future_tool', 'future-category'),
+ capability('uncategorized_tool', ' '),
+ ],
+ } satisfies AgentCapabilitiesManifest;
+
+ const sections = groupAgentCapabilitiesByManifestCategories(manifest);
+
+ expect(sections.map((section) => [section.id, section.label])).toEqual([
+ ['future-category', 'future-category'],
+ ['uncategorized', 'Uncategorized'],
+ ]);
+ expect(sections.flatMap((section) => section.entries.map((entry) => entry.name))).toEqual([
+ 'future_tool',
+ 'uncategorized_tool',
+ ]);
+ });
+
+ it('projects the manifest-owned Pulse Intelligence surface contract for settings UI', () => {
+ const manifest = {
+ version: 'v1',
+ surfaceContract,
+ surfaceToolContracts: [],
+ mcpAdapter,
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [],
+ capabilities: [],
+ } satisfies AgentCapabilitiesManifest;
+
+ const entries = getAgentSurfaceContractEntries(manifest);
+
+ expect(entries.map((entry) => entry.label)).toEqual([
+ 'Pulse Intelligence Core',
+ 'Pulse Patrol',
+ 'Pulse Assistant',
+ 'Pulse MCP',
+ ]);
+ expect(entries.map((entry) => entry.description)).toEqual([
+ 'Canonical context, governed actions, safety gates, approval state, action audit, and verification.',
+ 'Patrol is the first-party operations surface: it watches, investigates, acts within the chosen Patrol mode, verifies outcomes, and records what happened.',
+ 'The contextual explanation, approval, and handoff surface for Patrol findings, governed actions, verification, and operator questions.',
+ 'The external-agent adapter.',
+ ]);
+ expect(entries[2]?.badges).toEqual(['Native surface', 'Actions', 'Interactive questions']);
+ expect(entries[3]?.badges).toEqual([
+ 'External adapter',
+ 'Actions',
+ 'Resources',
+ 'Prompts',
+ 'Capability metadata',
+ ]);
+ });
+
+ it('projects manifest-owned workflow prompts for Assistant and MCP consumers', () => {
+ const manifest = {
+ version: 'v1',
+ surfaceContract,
+ surfaceToolContracts: [],
+ mcpAdapter,
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [
+ {
+ name: ' pulse_triage_fleet ',
+ label: ' Triage fleet ',
+ presentationKind: ' fleet ',
+ description: ' Triage the fleet. ',
+ },
+ {
+ name: 'pulse_investigate_resource',
+ description: ' Investigate a resource. ',
+ arguments: [
+ {
+ name: ' resourceId ',
+ description: ' Canonical resource id. ',
+ required: true,
+ },
+ { name: ' ', description: 'ignored' },
+ ],
+ },
+ {
+ name: ' ',
+ description: 'ignored',
+ },
+ ],
+ capabilities: [],
+ } satisfies AgentCapabilitiesManifest;
+
+ expect(getAgentWorkflowPrompts(manifest)).toEqual([
+ {
+ name: 'pulse_triage_fleet',
+ label: 'Triage fleet',
+ presentationKind: 'fleet',
+ description: 'Triage the fleet.',
+ arguments: [],
+ },
+ {
+ name: 'pulse_investigate_resource',
+ description: 'Investigate a resource.',
+ arguments: [
+ {
+ name: 'resourceId',
+ description: 'Canonical resource id.',
+ required: true,
+ },
+ ],
+ },
+ ]);
+ });
+
+ it('derives Pulse MCP Patrol-control readiness from prompts and surface tools', () => {
+ const patrolControlToolNames = [
+ 'get_patrol_control_status',
+ 'get_fleet_context',
+ 'get_resource_context',
+ 'list_findings',
+ 'plan_action',
+ 'decide_action',
+ 'execute_action',
+ 'resolve_finding',
+ ];
+ const manifest = {
+ version: 'v1',
+ surfaceContract,
+ surfaceToolContracts: [
+ {
+ surfaceId: 'pulse_mcp',
+ surfaceLabel: 'Pulse MCP',
+ toolSource: 'capability_manifest',
+ toolNames: patrolControlToolNames,
+ capabilityNames: patrolControlToolNames,
+ affordances: {
+ tools: true,
+ resources: true,
+ prompts: true,
+ capabilityMetadata: true,
+ },
+ },
+ ],
+ mcpAdapter,
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [{ name: 'pulse_operations_loop', label: 'Ask Patrol to handle an issue' }],
+ capabilities: [],
+ } satisfies AgentCapabilitiesManifest;
+
+ expect(getAgentMCPOperationsLoopReadiness(manifest)).toEqual({
+ available: true,
+ hasAdapter: true,
+ hasPrompt: true,
+ hasSurfaceTools: true,
+ missingCapabilities: [],
+ });
+
+ const baseMCPContract = manifest.surfaceToolContracts[0]!;
+ const incomplete = {
+ ...manifest,
+ surfaceToolContracts: [
+ {
+ ...baseMCPContract,
+ toolNames: patrolControlToolNames.filter((name) => name !== 'execute_action'),
+ capabilityNames: patrolControlToolNames.filter((name) => name !== 'execute_action'),
+ },
+ ],
+ } satisfies AgentCapabilitiesManifest;
+
+ expect(getAgentMCPOperationsLoopReadiness(incomplete)).toMatchObject({
+ available: false,
+ hasAdapter: true,
+ hasPrompt: true,
+ hasSurfaceTools: false,
+ missingCapabilities: ['execute_action'],
+ });
+ });
+
+ it('projects unique stable error codes with their declaring capabilities', () => {
+ const manifest = {
+ version: 'v1',
+ surfaceContract,
+ surfaceToolContracts: [],
+ mcpAdapter,
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [],
+ capabilities: [
+ {
+ ...capability('get_resource_context', 'context'),
+ errorCodes: ['resource_not_found', ''],
+ },
+ {
+ ...capability('plan_action', 'actions'),
+ errorCodes: [' resource_not_found ', 'action_execution_unavailable'],
+ },
+ {
+ ...capability('execute_action', 'actions'),
+ errorCodes: ['action_execution_unavailable'],
+ },
+ ],
+ } satisfies AgentCapabilitiesManifest;
+
+ expect(getAgentCapabilityErrorCodeSummaries(manifest)).toEqual([
+ {
+ code: 'resource_not_found',
+ capabilityNames: ['get_resource_context', 'plan_action'],
+ },
+ {
+ code: 'action_execution_unavailable',
+ capabilityNames: ['plan_action', 'execute_action'],
+ },
+ ]);
+ });
+
+ it('omits empty surface-contract entries from older manifests', () => {
+ const manifest = {
+ version: 'v1',
+ surfaceContract: {
+ core: { id: '', label: '', description: '' },
+ proactiveEngine: { id: '', label: ' ', description: '' },
+ operatorSurfaces: [
+ {
+ id: 'pulse_mcp',
+ label: 'Pulse MCP',
+ description: ' ',
+ native: false,
+ externalAdapter: true,
+ },
+ ],
+ },
+ surfaceToolContracts: [],
+ mcpAdapter,
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [],
+ capabilities: [],
+ } satisfies AgentCapabilitiesManifest;
+
+ expect(getAgentSurfaceContractEntries(manifest)).toEqual([
+ {
+ id: 'pulse_mcp',
+ label: 'Pulse MCP',
+ description: undefined,
+ badges: ['External adapter', 'Actions', 'Resources', 'Prompts', 'Capability metadata'],
+ },
+ ]);
+ });
+
+ it('projects manifest-owned MCP adapter setup for settings UI snippets', () => {
+ const customAdapter = {
+ ...mcpAdapter,
+ serverName: 'pulse-prod',
+ command: 'pulse-mcp-prod',
+ baseUrlFlag: '--pulse-url',
+ defaultBaseUrl: 'https://pulse.example.com',
+ tokenEnv: 'PULSE_PROD_TOKEN',
+ configFamilies: [
+ {
+ id: 'custom-opencode',
+ label: 'Custom OpenCode',
+ shape: 'opencode_mcp',
+ clientLabels: ['OpenCode'],
+ },
+ {
+ id: 'custom-mcp-servers',
+ label: 'Custom MCP servers',
+ shape: 'mcp_servers',
+ clientLabels: ['Claude Desktop', 'Claude Code'],
+ },
+ ],
+ };
+ const manifest = {
+ version: 'v1',
+ surfaceContract,
+ surfaceToolContracts: [],
+ mcpAdapter: customAdapter,
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [],
+ capabilities: [],
+ } satisfies AgentCapabilitiesManifest;
+
+ expect(normalizeAgentMCPAdapter(manifest.mcpAdapter)).toMatchObject({
+ serverName: 'pulse-prod',
+ command: 'pulse-mcp-prod',
+ baseUrlFlag: '--pulse-url',
+ tokenEnv: 'PULSE_PROD_TOKEN',
+ });
+ expect(getAgentMCPClientExamples(manifest)).toEqual([
+ 'OpenCode',
+ 'Claude Desktop',
+ 'Claude Code',
+ ]);
+ expect(getAgentMCPConfigFamilyByShape(manifest.mcpAdapter, 'mcp_servers')?.label).toBe(
+ 'Custom MCP servers',
+ );
+
+ expect(formatAgentOpenCodeMCPConfig(manifest.mcpAdapter, 'https://pulse.example.com')).toBe(
+ JSON.stringify(
+ {
+ $schema: 'https://opencode.ai/config.json',
+ mcp: {
+ 'pulse-prod': {
+ type: 'local',
+ command: ['pulse-mcp-prod', '--pulse-url', 'https://pulse.example.com'],
+ enabled: true,
+ environment: {
+ PULSE_PROD_TOKEN: '<your-api-token>',
+ },
+ },
+ },
+ },
+ null,
+ 2,
+ ),
+ );
+ expect(formatAgentMCPServersConfig(manifest.mcpAdapter, 'https://pulse.example.com')).toBe(
+ JSON.stringify(
+ {
+ mcpServers: {
+ 'pulse-prod': {
+ command: 'pulse-mcp-prod',
+ args: ['--pulse-url', 'https://pulse.example.com'],
+ env: {
+ PULSE_PROD_TOKEN: '<your-api-token>',
+ },
+ },
+ },
+ },
+ null,
+ 2,
+ ),
+ );
+ });
+
+ it('uses generated backend manifest types for the frontend contract', () => {
+ expect(generatedAgentCapabilitiesSource).toContain(
+ '// Source: internal/agentcapabilities manifest structs.',
+ );
+ expect(generatedAgentCapabilitiesSource).toContain('export interface Manifest');
+ expect(generatedAgentCapabilitiesSource).toContain('surfaceContract: SurfaceContract');
+ expect(generatedAgentCapabilitiesSource).toContain('mcpAdapter: MCPAdapterContract');
+ expect(generatedAgentCapabilitiesSource).toContain('workflowPrompts: PulseWorkflowPrompt[]');
+ expect(generatedAgentCapabilitiesSource).toContain('export interface MCPAdapterContract');
+ expect(generatedAgentCapabilitiesSource).toContain('export interface PulseWorkflowPrompt');
+ expect(generatedAgentCapabilitiesSource).toContain('label?: string');
+ expect(generatedAgentCapabilitiesSource).toContain('arguments?: PulseWorkflowPromptArgument[]');
+ expect(generatedAgentCapabilitiesSource).toContain(
+ 'export interface SurfaceAffordanceContract',
+ );
+ expect(generatedAgentCapabilitiesSource).toContain('affordances?: SurfaceAffordanceContract');
+ expect(generatedAgentCapabilitiesSource).toContain('configFamilies: MCPAdapterConfigFamily[]');
+ expect(generatedAgentCapabilitiesSource).toContain(
+ 'operatorSurfaces: OperatorSurfaceContract[]',
+ );
+ expect(generatedAgentCapabilitiesSource).toContain('actionMode: AgentCapabilityActionMode');
+ expect(generatedAgentCapabilitiesSource).toContain(
+ 'approvalPolicy: AgentCapabilityApprovalPolicy',
+ );
+ expect(generatedAgentCapabilitiesSource).toContain('inputSchema?: Record<string, unknown>');
+ expect(generatedAgentCapabilitiesSource).toContain('export interface SurfaceToolContract');
+ expect(generatedAgentCapabilitiesSource).toContain('surfaceId: string');
+ expect(generatedAgentCapabilitiesSource).toContain('toolSource: string');
+ expect(generatedAgentCapabilitiesSource).toContain('toolNames: string[]');
+ expect(generatedAgentCapabilitiesSource).toContain('registryToolNames?: string[]');
+ expect(generatedAgentCapabilitiesSource).toContain('capabilityNames?: string[]');
+ expect(generatedAgentCapabilitiesSource).toContain('nativeToolNames?: string[]');
+ });
+});
diff --git a/frontend-modern/src/api/__tests__/agentProfiles.test.ts b/frontend-modern/src/api/__tests__/agentProfiles.test.ts
index 74bb349afc..88461a308a 100644
--- a/frontend-modern/src/api/__tests__/agentProfiles.test.ts
+++ b/frontend-modern/src/api/__tests__/agentProfiles.test.ts
@@ -406,16 +406,16 @@ describe('AgentProfilesAPI', () => {
const mockResponse = { ok: false, status: 503 } as unknown as Response;
vi.mocked(apiFetch).mockResolvedValueOnce(mockResponse);
vi.mocked(assertAPIResponseOKOrThrowStatus).mockRejectedValueOnce(
- new Error('Pulse Assistant service is not available. Please check Pulse Assistant settings.'),
+ new Error('Pulse Intelligence is not available. Please check Assistant & Patrol settings.'),
);
await expect(AgentProfilesAPI.suggestProfile({ prompt: 'test' })).rejects.toThrow(
- 'Pulse Assistant service is not available',
+ 'Pulse Intelligence is not available',
);
expect(assertAPIResponseOKOrThrowStatus).toHaveBeenCalledWith(
mockResponse,
503,
- 'Pulse Assistant service is not available. Please check Pulse Assistant settings.',
+ 'Pulse Intelligence is not available. Please check Assistant & Patrol settings.',
'Failed to get suggestion: 503',
);
});
@@ -431,7 +431,7 @@ describe('AgentProfilesAPI', () => {
expect(assertAPIResponseOKOrThrowStatus).toHaveBeenCalledWith(
mockResponse,
503,
- 'Pulse Assistant service is not available. Please check Pulse Assistant settings.',
+ 'Pulse Intelligence is not available. Please check Assistant & Patrol settings.',
'Failed to get suggestion: 500',
);
});
diff --git a/frontend-modern/src/api/__tests__/aiChat.test.ts b/frontend-modern/src/api/__tests__/aiChat.test.ts
index c24ac734c8..4d033fc75d 100644
--- a/frontend-modern/src/api/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/api/__tests__/aiChat.test.ts
@@ -15,7 +15,12 @@ vi.mock('@/utils/logger', () => ({
},
}));
-import { AIChatAPI, createAIChatStreamPaintCheckpointPredicate } from '@/api/aiChat';
+import {
+ AIChatAPI,
+ PULSE_OPERATIONS_LOOP_WORKFLOW_PROMPT_NAME,
+ PULSE_PATROL_CONTROL_WORKFLOW_PROMPT_SURFACE,
+ createAIChatStreamPaintCheckpointPredicate,
+} from '@/api/aiChat';
import {
AI_CHAT_DEV_STREAM_FIXTURE_ALIAS_NAMES,
AI_CHAT_DEV_STREAM_FIXTURE_NAMES,
@@ -104,6 +109,86 @@ describe('AIChatAPI', () => {
expect(shouldYield({ type: 'thinking' })).toBe(false);
});
+ it('renders native Assistant workflow prompts through the shared AI route', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ description: 'Pulse fleet triage',
+ text: 'Use get_fleet_context...',
+ });
+
+ await expect(
+ AIChatAPI.renderWorkflowPrompt({
+ name: 'pulse_triage_fleet',
+ arguments: {},
+ }),
+ ).resolves.toEqual({
+ description: 'Pulse fleet triage',
+ text: 'Use get_fleet_context...',
+ });
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/workflow-prompts/render', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'pulse_triage_fleet', arguments: {} }),
+ });
+ });
+
+ it('records first-party workflow prompt activity through the shared AI route', async () => {
+ apiFetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
+
+ await expect(
+ AIChatAPI.recordWorkflowPromptActivity({
+ name: 'pulse_operations_loop',
+ surface: 'pulse_patrol',
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/ai/workflow-prompts/activity', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'pulse_operations_loop', surface: 'pulse_patrol' }),
+ });
+ });
+
+ it('records Patrol control workflow prompt activity through the shared AI route', async () => {
+ apiFetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
+
+ await expect(
+ AIChatAPI.recordWorkflowPromptActivity({
+ name: PULSE_OPERATIONS_LOOP_WORKFLOW_PROMPT_NAME,
+ surface: PULSE_PATROL_CONTROL_WORKFLOW_PROMPT_SURFACE,
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(apiFetchMock).toHaveBeenCalledWith('/api/ai/workflow-prompts/activity', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: 'pulse_operations_loop',
+ surface: 'patrol_control',
+ }),
+ });
+ });
+
+ it('fetches the live native Assistant surface tool contract through the shared AI route', async () => {
+ const contract = {
+ surfaceId: 'pulse_assistant',
+ surfaceLabel: 'Pulse Assistant',
+ toolSource: 'assistant_registry',
+ toolNames: ['pulse_query', 'pulse_question'],
+ registryToolNames: ['pulse_query'],
+ nativeToolNames: ['pulse_question'],
+ affordances: {
+ tools: true,
+ interactiveQuestions: true,
+ },
+ };
+ apiFetchJSONMock.mockResolvedValueOnce(contract);
+
+ await expect(AIChatAPI.getAssistantSurfaceTools()).resolves.toEqual(contract);
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/assistant/surface-tools');
+ });
+
it('runs the local dev stream fixture without opening a provider request', async () => {
const onEvent = vi.fn();
@@ -396,12 +481,7 @@ describe('AIChatAPI', () => {
it('runs the tool-chain dev stream fixture without opening a provider request', async () => {
const onEvent = vi.fn();
- await AIChatAPI.chat(
- '/fixture tool-chain',
- undefined,
- 'openrouter:qwen/qwen3.7-plus',
- onEvent,
- );
+ await AIChatAPI.chat('/fixture tool-chain', undefined, 'openrouter:qwen/qwen3.7-plus', onEvent);
expect(apiFetchMock).not.toHaveBeenCalled();
expect(onEvent.mock.calls.map(([event]) => event.type)).toEqual([
@@ -464,20 +544,10 @@ describe('AIChatAPI', () => {
expect(eventTypes()).toEqual(['session']);
await vi.advanceTimersByTimeAsync(75);
- expect(eventTypes()).toEqual([
- 'session',
- 'workflow_state',
- 'workflow_state',
- 'tool_start',
- ]);
+ expect(eventTypes()).toEqual(['session', 'workflow_state', 'workflow_state', 'tool_start']);
await vi.advanceTimersByTimeAsync(1399);
- expect(eventTypes()).toEqual([
- 'session',
- 'workflow_state',
- 'workflow_state',
- 'tool_start',
- ]);
+ expect(eventTypes()).toEqual(['session', 'workflow_state', 'workflow_state', 'tool_start']);
await vi.advanceTimersByTimeAsync(1);
expect(eventTypes()).toEqual([
@@ -1414,9 +1484,7 @@ describe('AIChatAPI', () => {
it('rejects stalled chat stream reads instead of emitting synthetic completion', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
- const read = vi.fn(
- () => new Promise<ReadableStreamReadResult<Uint8Array>>(() => undefined),
- );
+ const read = vi.fn(() => new Promise<ReadableStreamReadResult<Uint8Array>>(() => undefined));
const releaseLock = vi.fn();
const onEvent = vi.fn();
diff --git a/frontend-modern/src/api/__tests__/aiChatEvents.test.ts b/frontend-modern/src/api/__tests__/aiChatEvents.test.ts
index 7052210d8c..8a64f34f68 100644
--- a/frontend-modern/src/api/__tests__/aiChatEvents.test.ts
+++ b/frontend-modern/src/api/__tests__/aiChatEvents.test.ts
@@ -23,6 +23,7 @@ describe('AI chat stream event contract', () => {
expect(event.data.id).toBe('sess-stream');
expect(aiChatEventsSource).toContain('export interface SessionData');
expect(aiChatEventsSource).toContain("type: 'session'");
+ expect(aiChatEventsSource).toContain('context_limit_tokens?: number');
});
it('does not expose automatic provider fallback metadata on workflow state events', () => {
diff --git a/frontend-modern/src/api/__tests__/patrolUtils.test.ts b/frontend-modern/src/api/__tests__/patrolUtils.test.ts
index 9910e0ed57..20fc2fa77a 100644
--- a/frontend-modern/src/api/__tests__/patrolUtils.test.ts
+++ b/frontend-modern/src/api/__tests__/patrolUtils.test.ts
@@ -87,6 +87,10 @@ describe('patrol utilities', () => {
expect(investigationOutcomeLabels.fix_failed).toBe('Fix Failed');
});
+ it('has correct label for fix_rejected', () => {
+ expect(investigationOutcomeLabels.fix_rejected).toBe('Fix Rejected');
+ });
+
it('has correct label for needs_attention', () => {
expect(investigationOutcomeLabels.needs_attention).toBe('Needs Attention');
});
@@ -125,6 +129,10 @@ describe('patrol utilities', () => {
expect(investigationOutcomeColors.fix_failed).toContain('red');
});
+ it('has amber colors for fix_rejected', () => {
+ expect(investigationOutcomeColors.fix_rejected).toContain('amber');
+ });
+
it('has amber colors for needs_attention', () => {
expect(investigationOutcomeColors.needs_attention).toContain('amber');
});
diff --git a/frontend-modern/src/api/__tests__/settings.test.ts b/frontend-modern/src/api/__tests__/settings.test.ts
index 37ac3b0326..cddc4ee175 100644
--- a/frontend-modern/src/api/__tests__/settings.test.ts
+++ b/frontend-modern/src/api/__tests__/settings.test.ts
@@ -1,11 +1,113 @@
import { describe, expect, it, vi, beforeEach } from 'vitest';
-import { SettingsAPI, type SystemSettingsResponse } from '../settings';
+import { SettingsAPI, type SystemSettingsResponse, type TelemetryPingPreview } from '../settings';
import { apiFetchJSON } from '@/utils/apiClient';
vi.mock('@/utils/apiClient', () => ({
apiFetchJSON: vi.fn(),
}));
+const mockTelemetryPreviewPayload = {
+ install_id: 'preview-install-id',
+ version: '6.0.0',
+ version_channel: 'stable',
+ version_is_development: false,
+ version_is_published_release: true,
+ platform: 'docker',
+ os: 'linux',
+ arch: 'amd64',
+ event: 'heartbeat',
+ pve_nodes: 1,
+ pbs_instances: 0,
+ pmg_instances: 0,
+ vms: 2,
+ containers: 3,
+ agent_hosts: 1,
+ docker_hosts: 0,
+ docker_containers: 0,
+ kubernetes_clusters: 0,
+ kubernetes_nodes: 0,
+ kubernetes_pods: 0,
+ kubernetes_deployments: 0,
+ storage_pools: 1,
+ physical_disks: 2,
+ ceph_clusters: 0,
+ network_shares: 0,
+ truenas_systems: 0,
+ truenas_vms: 0,
+ truenas_apps: 0,
+ vmware_hosts: 0,
+ vmware_vms: 0,
+ vmware_datastores: 0,
+ availability_targets: 1,
+ ai_enabled: false,
+ patrol_enabled: false,
+ discovery_enabled: false,
+ notifications_enabled: false,
+ ai_actions_enabled: false,
+ active_alerts: 0,
+ relay_enabled: false,
+ sso_enabled: false,
+ multi_tenant: false,
+ paid_license: false,
+ has_api_tokens: true,
+ pulse_intelligence_loop_configured: false,
+ pulse_intelligence_loop_active_30d: false,
+ pulse_intelligence_complete_operations_loop_30d: false,
+ pulse_intelligence_approved_execution_loop_30d: false,
+ pulse_intelligence_resolved_operations_loop_30d: false,
+ pulse_intelligence_patrol_control_completed_operations_loop_30d: false,
+ pulse_intelligence_patrol_control_resolved_operations_loop_30d: false,
+ pulse_intelligence_patrol_control_paid_completed_operations_loop_30d: false,
+ pulse_intelligence_patrol_control_paid_resolved_operations_loop_30d: false,
+ pulse_intelligence_pro_activation_completed_operations_loop_30d: false,
+ pulse_intelligence_pro_activation_resolved_operations_loop_30d: false,
+ pulse_intelligence_pro_activation_paid_completed_operations_loop_30d: false,
+ pulse_intelligence_pro_activation_paid_resolved_operations_loop_30d: false,
+ pulse_intelligence_governed_action_active_30d: false,
+ pulse_intelligence_assistant_operations_loop_30d: false,
+ pulse_intelligence_assistant_approved_execution_loop_30d: false,
+ pulse_intelligence_assistant_approved_action_success_loop_30d: false,
+ pulse_intelligence_assistant_resolved_operations_loop_30d: false,
+ pulse_intelligence_external_agent_operations_loop_30d: false,
+ pulse_intelligence_external_agent_approved_execution_loop_30d: false,
+ pulse_intelligence_external_agent_approved_action_success_loop_30d: false,
+ pulse_intelligence_external_agent_resolved_operations_loop_30d: false,
+ pulse_intelligence_mcp_adapter_operations_loop_30d: false,
+ pulse_intelligence_mcp_adapter_approved_execution_loop_30d: false,
+ pulse_intelligence_mcp_adapter_approved_action_success_loop_30d: false,
+ pulse_intelligence_mcp_adapter_resolved_operations_loop_30d: false,
+ pulse_intelligence_operations_loop_starter_requests_30d: 0,
+ pulse_intelligence_assistant_operations_loop_starter_requests_30d: 0,
+ pulse_intelligence_patrol_operations_loop_starter_requests_30d: 0,
+ pulse_intelligence_patrol_control_operations_loop_starter_requests_30d: 0,
+ pulse_intelligence_pro_activation_operations_loop_starter_requests_30d: 0,
+ pulse_intelligence_mcp_operations_loop_starter_requests_30d: 0,
+ pulse_intelligence_assistant_ai_calls_30d: 0,
+ pulse_intelligence_assistant_context_ai_calls_30d: 0,
+ pulse_intelligence_assistant_tool_calls_30d: 0,
+ pulse_intelligence_patrol_ai_calls_30d: 0,
+ pulse_intelligence_patrol_runs_30d: 0,
+ pulse_intelligence_patrol_new_findings_30d: 0,
+ pulse_intelligence_patrol_investigations_30d: 0,
+ pulse_intelligence_patrol_resolved_findings_30d: 0,
+ pulse_intelligence_patrol_autofixes_30d: 0,
+ pulse_intelligence_external_agent_enabled: false,
+ pulse_intelligence_external_agent_used_30d: false,
+ pulse_intelligence_mcp_adapter_used_30d: false,
+ pulse_intelligence_external_agent_context_requests_30d: 0,
+ pulse_intelligence_external_agent_event_stream_requests_30d: 0,
+ pulse_intelligence_external_agent_provisioning_requests_30d: 0,
+ pulse_intelligence_external_agent_operator_state_requests_30d: 0,
+ pulse_intelligence_external_agent_finding_requests_30d: 0,
+ pulse_intelligence_external_agent_action_requests_30d: 0,
+ pulse_intelligence_action_plans_30d: 0,
+ pulse_intelligence_approval_requests_30d: 0,
+ pulse_intelligence_rejected_action_decisions_30d: 0,
+ pulse_intelligence_approved_action_decisions_30d: 0,
+ pulse_intelligence_approved_action_attempts_30d: 0,
+ pulse_intelligence_approved_action_successes_30d: 0,
+} satisfies TelemetryPingPreview;
+
describe('SettingsAPI', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -46,51 +148,7 @@ describe('SettingsAPI', () => {
it('fetches the telemetry preview payload', async () => {
const mockPreview = {
enabled: true,
- payload: {
- install_id: 'preview-install-id',
- version: '6.0.0',
- version_channel: 'stable',
- version_is_development: false,
- version_is_published_release: true,
- platform: 'docker',
- os: 'linux',
- arch: 'amd64',
- event: 'heartbeat',
- pve_nodes: 1,
- pbs_instances: 0,
- pmg_instances: 0,
- vms: 2,
- containers: 3,
- agent_hosts: 1,
- docker_hosts: 0,
- docker_containers: 0,
- kubernetes_clusters: 0,
- kubernetes_nodes: 0,
- kubernetes_pods: 0,
- kubernetes_deployments: 0,
- storage_pools: 1,
- physical_disks: 2,
- ceph_clusters: 0,
- network_shares: 0,
- truenas_systems: 0,
- truenas_vms: 0,
- truenas_apps: 0,
- vmware_hosts: 0,
- vmware_vms: 0,
- vmware_datastores: 0,
- availability_targets: 1,
- ai_enabled: false,
- patrol_enabled: false,
- discovery_enabled: false,
- notifications_enabled: false,
- ai_actions_enabled: false,
- active_alerts: 0,
- relay_enabled: false,
- sso_enabled: false,
- multi_tenant: false,
- paid_license: false,
- has_api_tokens: true,
- },
+ payload: mockTelemetryPreviewPayload,
};
vi.mocked(apiFetchJSON).mockResolvedValueOnce(mockPreview);
diff --git a/frontend-modern/src/api/agentCapabilities.ts b/frontend-modern/src/api/agentCapabilities.ts
new file mode 100644
index 0000000000..415b6b8080
--- /dev/null
+++ b/frontend-modern/src/api/agentCapabilities.ts
@@ -0,0 +1,738 @@
+import { apiFetchJSON } from '@/utils/apiClient';
+import type {
+ AgentCapabilityActionMode,
+ AgentCapabilityApprovalPolicy,
+ Capability,
+ CapabilityCategory,
+ Manifest,
+ MCPAdapterConfigFamily,
+ MCPAdapterContract,
+ OperatorSurfaceContract,
+ PulseWorkflowPrompt,
+ PulseWorkflowPromptArgument,
+ SurfaceAffordanceContract,
+ SurfaceContractComponent,
+ SurfaceToolContract,
+} from './generated/agentCapabilities';
+
+export const AGENT_CAPABILITIES_PATH = '/api/agent/capabilities';
+export const AGENT_PATROL_CONTROL_STATUS_PATH = '/api/agent/patrol-control/status';
+export const AGENT_OPERATIONS_LOOP_STATUS_PATH = AGENT_PATROL_CONTROL_STATUS_PATH;
+
+export type { AgentCapabilityActionMode, AgentCapabilityApprovalPolicy };
+export type AgentCapability = Capability;
+export type AgentCapabilityCategory = CapabilityCategory;
+export type AgentCapabilitiesManifest = Manifest;
+export type AgentMCPAdapterConfigFamily = MCPAdapterConfigFamily;
+export type AgentMCPAdapterContract = MCPAdapterContract;
+export type AgentOperatorSurfaceContract = OperatorSurfaceContract;
+export type AgentWorkflowPrompt = PulseWorkflowPrompt;
+export type AgentWorkflowPromptArgument = PulseWorkflowPromptArgument;
+export type AgentSurfaceAffordanceContract = SurfaceAffordanceContract;
+export type AgentSurfaceContractComponent = SurfaceContractComponent;
+export type AgentSurfaceToolContract = SurfaceToolContract;
+
+export interface AgentCapabilitySection {
+ id: string;
+ label: string;
+ description?: string;
+ entries: AgentCapability[];
+}
+
+export interface AgentSurfaceContractEntry {
+ id: string;
+ label: string;
+ description?: string;
+ badges: string[];
+}
+
+export interface AgentCapabilityErrorCodeSummary {
+ code: string;
+ capabilityNames: string[];
+}
+
+export interface AgentSurfaceToolPosturePresentation {
+ surfaceLabel: string;
+ label: string;
+ title: string;
+ detail?: string;
+ tone: 'ready' | 'empty';
+ toolCount: number;
+}
+
+export type AgentOperationsLoopNextAction =
+ | 'run_patrol'
+ | 'review_findings'
+ | 'open_assistant'
+ | 'review_approvals'
+ | 'open_mcp'
+ | 'complete';
+
+export type AgentOperationsLoopStepStatus = 'complete' | 'current' | 'pending';
+
+export type AgentOperationsLoopProActivationValueProofState =
+ | 'not_started'
+ | 'in_progress'
+ | 'governed_decision_recorded'
+ | 'verified_needs_mcp'
+ | 'verified';
+
+export type AgentOperationsLoopPatrolControlValueState =
+ AgentOperationsLoopProActivationValueProofState;
+
+export type AgentOperationsLoopPatrolAutonomyValueState =
+ AgentOperationsLoopPatrolControlValueState;
+
+export interface AgentOperationsLoopStep {
+ id: 'patrol' | 'assistant' | 'governance' | 'verification';
+ label: string;
+ status: AgentOperationsLoopStepStatus;
+ count?: number;
+}
+
+export interface AgentOperationsLoopStatus {
+ nextAction: AgentOperationsLoopNextAction;
+ progressLabel: string;
+ steps: AgentOperationsLoopStep[];
+ patrolEvidenceCount: number;
+ patrolIssueEvidenceCount: number;
+ activeFindingCount: number;
+ pendingApprovalCount: number;
+ governedActionCount: number;
+ approvedDecisionCount: number;
+ rejectedDecisionCount: number;
+ verifiedOutcomeCount: number;
+ operationsLoopStarterCount: number;
+ assistantOperationsLoopStarterCount: number;
+ patrolOperationsLoopStarterCount: number;
+ patrolControlOperationsLoopStarterCount?: number;
+ patrolControlCompletedOperationsLoopCount?: number;
+ patrolControlResolvedOperationsLoopCount?: number;
+ patrolControlValueState?: AgentOperationsLoopPatrolControlValueState;
+ patrolAutonomyOperationsLoopStarterCount?: number;
+ patrolAutonomyCompletedOperationsLoopCount?: number;
+ patrolAutonomyResolvedOperationsLoopCount?: number;
+ patrolAutonomyValueState?: AgentOperationsLoopPatrolAutonomyValueState;
+ proActivationOperationsLoopStarterCount?: number;
+ proActivationCompletedOperationsLoopCount?: number;
+ proActivationResolvedOperationsLoopCount?: number;
+ proActivationValueProofState?: AgentOperationsLoopProActivationValueProofState;
+ mcpOperationsLoopStarterCount: number;
+ externalAgentReady: boolean;
+ windowStart: string;
+ generatedAt: string;
+}
+
+export const AGENT_MCP_TOKEN_PLACEHOLDER = '<your-api-token>';
+export const AGENT_SURFACE_ID_PULSE_MCP = 'pulse_mcp';
+export const AGENT_WORKFLOW_PROMPT_OPERATIONS_LOOP = 'pulse_operations_loop';
+
+const AGENT_OPERATIONS_LOOP_CAPABILITY_NAMES = [
+ 'get_patrol_control_status',
+ 'get_fleet_context',
+ 'get_resource_context',
+ 'list_findings',
+ 'plan_action',
+ 'decide_action',
+ 'execute_action',
+ 'resolve_finding',
+] as const;
+
+export interface AgentMCPOperationsLoopReadiness {
+ available: boolean;
+ hasAdapter: boolean;
+ hasPrompt: boolean;
+ hasSurfaceTools: boolean;
+ missingCapabilities: string[];
+}
+
+const DEFAULT_AGENT_MCP_CONFIG_FAMILIES: AgentMCPAdapterConfigFamily[] = [
+ {
+ id: 'opencode',
+ label: 'OpenCode',
+ shape: 'opencode_mcp',
+ description: "Uses OpenCode's top-level mcp object.",
+ fileHints: ['opencode.json', 'opencode.jsonc', '~/.config/opencode/opencode.json'],
+ clientLabels: ['OpenCode'],
+ },
+ {
+ id: 'claude-style',
+ label: 'Claude-style clients',
+ shape: 'mcp_servers',
+ description: 'Uses the common mcpServers object supported by Claude Desktop and Claude Code.',
+ fileHints: ['~/Library/Application Support/Claude/claude_desktop_config.json', '.mcp.json'],
+ clientLabels: ['Claude Desktop', 'Claude Code'],
+ },
+ {
+ id: 'custom-mcp',
+ label: 'custom clients',
+ shape: 'custom',
+ description:
+ 'Keeps the connector command, base URL flag, and token environment variable while adapting the outer client config shape.',
+ clientLabels: ['custom clients'],
+ },
+];
+
+const DEFAULT_AGENT_MCP_ADAPTER: AgentMCPAdapterContract = {
+ serverName: 'pulse',
+ command: 'pulse-mcp',
+ baseUrlFlag: '--base-url',
+ defaultBaseUrl: 'http://localhost:7655',
+ tokenEnv: 'PULSE_API_TOKEN',
+ configFamilies: DEFAULT_AGENT_MCP_CONFIG_FAMILIES,
+};
+
+const DEFAULT_AGENT_SURFACE_AFFORDANCES_BY_ID: Record<string, AgentSurfaceAffordanceContract> = {
+ pulse_assistant: {
+ tools: true,
+ interactiveQuestions: true,
+ },
+ pulse_mcp: {
+ tools: true,
+ resources: true,
+ prompts: true,
+ capabilityMetadata: true,
+ },
+};
+
+export async function fetchAgentCapabilitiesManifest(): Promise<AgentCapabilitiesManifest> {
+ return apiFetchJSON<AgentCapabilitiesManifest>(AGENT_CAPABILITIES_PATH, {
+ skipAuth: true,
+ headers: { Accept: 'application/json' },
+ });
+}
+
+export async function fetchAgentOperationsLoopStatus(): Promise<AgentOperationsLoopStatus> {
+ return apiFetchJSON<AgentOperationsLoopStatus>(AGENT_OPERATIONS_LOOP_STATUS_PATH, {
+ headers: { Accept: 'application/json' },
+ });
+}
+
+function trimOrDefault(value: string | undefined, fallback: string): string {
+ return value?.trim() || fallback;
+}
+
+function uniqueTrimmed(values: string[] | undefined): string[] {
+ const seen = new Set<string>();
+ const normalized: string[] = [];
+ for (const raw of values ?? []) {
+ const value = raw.trim();
+ if (!value || seen.has(value)) continue;
+ seen.add(value);
+ normalized.push(value);
+ }
+ return normalized;
+}
+
+function optionalNonEmptyList(values: string[]): string[] | undefined {
+ return values.length > 0 ? values : undefined;
+}
+
+function formatSurfaceToolSource(source: string): string {
+ switch (source) {
+ case 'assistant_registry':
+ return 'Assistant registry';
+ case 'capability_manifest':
+ return 'Capability manifest';
+ default:
+ return source
+ .split(/[_\s-]+/)
+ .filter(Boolean)
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join(' ');
+ }
+}
+
+function findAgentOperatorSurface(
+ manifest: AgentCapabilitiesManifest | undefined,
+ surfaceId: string,
+): AgentOperatorSurfaceContract | undefined {
+ const normalizedSurfaceId = surfaceId.trim();
+ if (!normalizedSurfaceId) return undefined;
+ return manifest?.surfaceContract?.operatorSurfaces?.find(
+ (surface) => surface.id?.trim() === normalizedSurfaceId,
+ );
+}
+
+function findAgentSurfaceToolContract(
+ manifest: AgentCapabilitiesManifest | undefined,
+ surfaceId: string,
+): AgentSurfaceToolContract | undefined {
+ const normalizedSurfaceId = surfaceId.trim();
+ if (!normalizedSurfaceId) return undefined;
+ return manifest?.surfaceToolContracts?.find(
+ (contract) => contract.surfaceId?.trim() === normalizedSurfaceId,
+ );
+}
+
+function cloneConfigFamilies(
+ families: AgentMCPAdapterConfigFamily[],
+): AgentMCPAdapterConfigFamily[] {
+ return families.map((family) => ({
+ ...family,
+ fileHints: family.fileHints ? [...family.fileHints] : undefined,
+ clientLabels: family.clientLabels ? [...family.clientLabels] : undefined,
+ }));
+}
+
+function normalizedConfigFamilies(
+ families: AgentMCPAdapterConfigFamily[] | undefined,
+): AgentMCPAdapterConfigFamily[] {
+ if (!families || families.length === 0) {
+ return cloneConfigFamilies(DEFAULT_AGENT_MCP_CONFIG_FAMILIES);
+ }
+
+ const normalized: AgentMCPAdapterConfigFamily[] = [];
+ for (const family of families) {
+ const id = family.id?.trim() || family.label?.trim() || family.shape?.trim();
+ const label = family.label?.trim() || id;
+ const shape = family.shape?.trim() || id;
+ if (!id || !label || !shape) continue;
+ normalized.push({
+ ...family,
+ id,
+ label,
+ shape,
+ description: family.description?.trim() || undefined,
+ fileHints: family.fileHints?.map((hint) => hint.trim()).filter(Boolean),
+ clientLabels: family.clientLabels?.map((label) => label.trim()).filter(Boolean),
+ });
+ }
+
+ return normalized.length > 0
+ ? normalized
+ : cloneConfigFamilies(DEFAULT_AGENT_MCP_CONFIG_FAMILIES);
+}
+
+export function normalizeAgentMCPAdapter(
+ adapter: AgentMCPAdapterContract | undefined,
+): AgentMCPAdapterContract {
+ return {
+ serverName: trimOrDefault(adapter?.serverName, DEFAULT_AGENT_MCP_ADAPTER.serverName),
+ command: trimOrDefault(adapter?.command, DEFAULT_AGENT_MCP_ADAPTER.command),
+ baseUrlFlag: trimOrDefault(adapter?.baseUrlFlag, DEFAULT_AGENT_MCP_ADAPTER.baseUrlFlag),
+ defaultBaseUrl: trimOrDefault(
+ adapter?.defaultBaseUrl,
+ DEFAULT_AGENT_MCP_ADAPTER.defaultBaseUrl,
+ ),
+ tokenEnv: trimOrDefault(adapter?.tokenEnv, DEFAULT_AGENT_MCP_ADAPTER.tokenEnv),
+ configFamilies: normalizedConfigFamilies(adapter?.configFamilies),
+ };
+}
+
+export function getAgentMCPAdapterConfigFamilies(
+ adapter: AgentMCPAdapterContract | undefined,
+): AgentMCPAdapterConfigFamily[] {
+ return normalizeAgentMCPAdapter(adapter).configFamilies;
+}
+
+export function getAgentMCPConfigFamilyByShape(
+ adapter: AgentMCPAdapterContract | undefined,
+ shape: string,
+): AgentMCPAdapterConfigFamily | undefined {
+ const normalizedShape = shape.trim();
+ if (!normalizedShape) return undefined;
+ return getAgentMCPAdapterConfigFamilies(adapter).find(
+ (family) => family.shape === normalizedShape,
+ );
+}
+
+export function getAgentMCPClientExamples(
+ manifest: AgentCapabilitiesManifest | undefined,
+): string[] {
+ const labels: string[] = [];
+ for (const family of getAgentMCPAdapterConfigFamilies(manifest?.mcpAdapter)) {
+ const clientLabels = family.clientLabels?.filter(Boolean);
+ if (clientLabels && clientLabels.length > 0) {
+ labels.push(...clientLabels);
+ } else {
+ labels.push(family.label);
+ }
+ }
+ return labels;
+}
+
+export function formatAgentOpenCodeMCPConfig(
+ adapter: AgentMCPAdapterContract | undefined,
+ baseUrl: string,
+ tokenPlaceholder = AGENT_MCP_TOKEN_PLACEHOLDER,
+): string {
+ const normalized = normalizeAgentMCPAdapter(adapter);
+ const config = {
+ $schema: 'https://opencode.ai/config.json',
+ mcp: {
+ [normalized.serverName]: {
+ type: 'local',
+ command: [normalized.command, normalized.baseUrlFlag, baseUrl],
+ enabled: true,
+ environment: {
+ [normalized.tokenEnv]: tokenPlaceholder,
+ },
+ },
+ },
+ };
+ return JSON.stringify(config, null, 2);
+}
+
+export function formatAgentMCPServersConfig(
+ adapter: AgentMCPAdapterContract | undefined,
+ baseUrl: string,
+ tokenPlaceholder = AGENT_MCP_TOKEN_PLACEHOLDER,
+): string {
+ const normalized = normalizeAgentMCPAdapter(adapter);
+ const config = {
+ mcpServers: {
+ [normalized.serverName]: {
+ command: normalized.command,
+ args: [normalized.baseUrlFlag, baseUrl],
+ env: {
+ [normalized.tokenEnv]: tokenPlaceholder,
+ },
+ },
+ },
+ };
+ return JSON.stringify(config, null, 2);
+}
+
+function normalizedCapabilityCategoryID(category: string | undefined): string {
+ return category?.trim() || 'uncategorized';
+}
+
+function categoryFallbackLabel(category: string): string {
+ if (category === 'uncategorized') return 'Uncategorized';
+ return category || 'Uncategorized';
+}
+
+function sanitizeAgentCapabilityDescription(description: string | undefined): string {
+ const trimmed = description?.trim();
+ if (!trimmed) return '';
+ return trimmed
+ .replace(/legacy Pro activation aliases/g, 'compatibility aliases')
+ .replace(
+ /Pro activation completed\/resolved proof/g,
+ 'Patrol mode completed/resolved outcome status',
+ )
+ .replace(
+ /Patrol autonomy completed\/resolved outcome status/g,
+ 'Patrol mode completed/resolved outcome status',
+ )
+ .replace(
+ /Patrol autonomy completed\/resolved outcome evidence/g,
+ 'Patrol mode outcome evidence',
+ );
+}
+
+function normalizeAgentCapabilityPresentation(capability: AgentCapability): AgentCapability {
+ return {
+ ...capability,
+ description: sanitizeAgentCapabilityDescription(capability.description),
+ };
+}
+
+export function groupAgentCapabilitiesByManifestCategories(
+ manifest: AgentCapabilitiesManifest | undefined,
+): AgentCapabilitySection[] {
+ if (!manifest) return [];
+
+ const byCategory = new Map<string, AgentCapability[]>();
+ for (const cap of manifest.capabilities) {
+ const category = normalizedCapabilityCategoryID(cap.category);
+ const list = byCategory.get(category) ?? [];
+ list.push(normalizeAgentCapabilityPresentation(cap));
+ byCategory.set(category, list);
+ }
+
+ const sections: AgentCapabilitySection[] = [];
+ for (const category of manifest.categories ?? []) {
+ const id = normalizedCapabilityCategoryID(category.id);
+ const entries = byCategory.get(id);
+ if (!entries || entries.length === 0) continue;
+ const label = category.label?.trim() || categoryFallbackLabel(id);
+ const description = category.description?.trim();
+ sections.push({
+ id,
+ label,
+ description: description || undefined,
+ entries,
+ });
+ byCategory.delete(id);
+ }
+
+ for (const [unknownCategory, entries] of byCategory) {
+ sections.push({
+ id: unknownCategory,
+ label: categoryFallbackLabel(unknownCategory),
+ entries,
+ });
+ }
+
+ return sections;
+}
+
+function trimSurfaceContractComponent(
+ component: AgentSurfaceContractComponent | undefined,
+): AgentSurfaceContractEntry | undefined {
+ const label = component?.label?.trim();
+ if (!label) return undefined;
+ return {
+ id: component?.id?.trim() || label,
+ label,
+ description: component?.description?.trim() || undefined,
+ badges: [],
+ };
+}
+
+function surfaceBadges(surface: AgentOperatorSurfaceContract): string[] {
+ const badges: string[] = [];
+ if (surface.native) badges.push('Native surface');
+ if (surface.externalAdapter) badges.push('External adapter');
+ badges.push(...surfaceAffordanceLabels(normalizeSurfaceAffordances(surface)));
+ return badges;
+}
+
+function surfaceAffordancesDeclared(
+ affordances: AgentSurfaceAffordanceContract | undefined,
+): boolean {
+ return Boolean(
+ affordances?.tools ||
+ affordances?.resources ||
+ affordances?.prompts ||
+ affordances?.capabilityMetadata ||
+ affordances?.interactiveQuestions,
+ );
+}
+
+function normalizeSurfaceAffordances(
+ surface: AgentOperatorSurfaceContract,
+): AgentSurfaceAffordanceContract {
+ if (surfaceAffordancesDeclared(surface.affordances)) {
+ return surface.affordances!;
+ }
+ const id = surface.id?.trim();
+ return id ? (DEFAULT_AGENT_SURFACE_AFFORDANCES_BY_ID[id] ?? {}) : {};
+}
+
+function surfaceAffordanceLabels(affordances: AgentSurfaceAffordanceContract): string[] {
+ const labels: string[] = [];
+ if (affordances.tools) labels.push('Actions');
+ if (affordances.resources) labels.push('Resources');
+ if (affordances.prompts) labels.push('Prompts');
+ if (affordances.capabilityMetadata) labels.push('Capability metadata');
+ if (affordances.interactiveQuestions) labels.push('Interactive questions');
+ return labels;
+}
+
+export function getAgentSurfaceContractEntries(
+ manifest: AgentCapabilitiesManifest | undefined,
+): AgentSurfaceContractEntry[] {
+ if (!manifest) return [];
+
+ const entries: AgentSurfaceContractEntry[] = [];
+ const core = trimSurfaceContractComponent(manifest.surfaceContract?.core);
+ if (core) entries.push(core);
+
+ const proactiveEngine = trimSurfaceContractComponent(manifest.surfaceContract?.proactiveEngine);
+ if (proactiveEngine) entries.push(proactiveEngine);
+
+ for (const surface of manifest.surfaceContract?.operatorSurfaces ?? []) {
+ const label = surface.label?.trim();
+ if (!label) continue;
+ entries.push({
+ id: surface.id?.trim() || label,
+ label,
+ description: surface.description?.trim() || undefined,
+ badges: surfaceBadges(surface),
+ });
+ }
+
+ return entries;
+}
+
+export function getAgentWorkflowPrompts(
+ manifest: AgentCapabilitiesManifest | undefined,
+): AgentWorkflowPrompt[] {
+ const prompts: AgentWorkflowPrompt[] = [];
+ for (const prompt of manifest?.workflowPrompts ?? []) {
+ const name = prompt.name?.trim();
+ if (!name) continue;
+
+ const args: AgentWorkflowPromptArgument[] = [];
+ for (const arg of prompt.arguments ?? []) {
+ const argName = arg.name?.trim();
+ if (!argName) continue;
+ const normalizedArg: AgentWorkflowPromptArgument = {
+ name: argName,
+ required: Boolean(arg.required),
+ };
+ const argDescription = arg.description?.trim();
+ if (argDescription) normalizedArg.description = argDescription;
+ args.push(normalizedArg);
+ }
+
+ const normalizedPrompt: AgentWorkflowPrompt = {
+ name,
+ arguments: args,
+ };
+ const label = prompt.label?.trim();
+ if (label) normalizedPrompt.label = label;
+ const presentationKind = prompt.presentationKind?.trim();
+ if (presentationKind) normalizedPrompt.presentationKind = presentationKind;
+ const description = prompt.description?.trim();
+ if (description) normalizedPrompt.description = description;
+ prompts.push(normalizedPrompt);
+ }
+ return prompts;
+}
+
+export function getAgentMCPOperationsLoopReadiness(
+ manifest: AgentCapabilitiesManifest | undefined,
+): AgentMCPOperationsLoopReadiness {
+ const adapter = normalizeAgentMCPAdapter(manifest?.mcpAdapter);
+ const hasAdapter =
+ Boolean(adapter.command) &&
+ Boolean(adapter.serverName) &&
+ Boolean(adapter.tokenEnv) &&
+ adapter.configFamilies.length > 0;
+ const hasPrompt = getAgentWorkflowPrompts(manifest).some(
+ (prompt) => prompt.name === AGENT_WORKFLOW_PROMPT_OPERATIONS_LOOP,
+ );
+ const contract = getAgentManifestSurfaceToolContract(manifest, AGENT_SURFACE_ID_PULSE_MCP);
+ const toolNames = new Set(contract?.toolNames ?? []);
+ const missingCapabilities = AGENT_OPERATIONS_LOOP_CAPABILITY_NAMES.filter(
+ (name) => !toolNames.has(name),
+ );
+ const hasSurfaceTools = Boolean(contract) && missingCapabilities.length === 0;
+
+ return {
+ available: hasAdapter && hasPrompt && hasSurfaceTools,
+ hasAdapter,
+ hasPrompt,
+ hasSurfaceTools,
+ missingCapabilities,
+ };
+}
+
+export function normalizeAgentSurfaceToolContract(
+ contract: AgentSurfaceToolContract | undefined,
+): AgentSurfaceToolContract | undefined {
+ const surfaceId = contract?.surfaceId?.trim();
+ if (!contract || !surfaceId) return undefined;
+
+ const toolNames = uniqueTrimmed(contract.toolNames);
+ const registryToolNames = uniqueTrimmed(contract.registryToolNames);
+ const capabilityNames = uniqueTrimmed(contract.capabilityNames);
+ const nativeToolNames = uniqueTrimmed(contract.nativeToolNames);
+ const affordances = surfaceAffordancesDeclared(contract.affordances)
+ ? contract.affordances
+ : (DEFAULT_AGENT_SURFACE_AFFORDANCES_BY_ID[surfaceId] ?? undefined);
+ const toolsEnabled = Boolean(affordances?.tools);
+
+ return {
+ surfaceId,
+ surfaceLabel: contract.surfaceLabel?.trim() || undefined,
+ toolSource: contract.toolSource?.trim() || 'unknown',
+ toolNames: toolsEnabled ? toolNames : [],
+ registryToolNames: optionalNonEmptyList(toolsEnabled ? registryToolNames : []),
+ capabilityNames: optionalNonEmptyList(toolsEnabled ? capabilityNames : []),
+ nativeToolNames: optionalNonEmptyList(toolsEnabled ? nativeToolNames : []),
+ affordances,
+ };
+}
+
+export function getAgentManifestSurfaceToolContract(
+ manifest: AgentCapabilitiesManifest | undefined,
+ surfaceId: string,
+): AgentSurfaceToolContract | undefined {
+ if (!manifest) return undefined;
+
+ const normalizedSurfaceId = surfaceId.trim();
+ if (!normalizedSurfaceId) return undefined;
+
+ const surface = findAgentOperatorSurface(manifest, normalizedSurfaceId);
+ if (!surface?.externalAdapter) return undefined;
+
+ const manifestOwnedContract = findAgentSurfaceToolContract(manifest, normalizedSurfaceId);
+ if (!manifestOwnedContract) return undefined;
+
+ return normalizeAgentSurfaceToolContract({
+ ...manifestOwnedContract,
+ surfaceLabel: surface.label?.trim() || normalizedSurfaceId,
+ affordances: normalizeSurfaceAffordances(surface),
+ });
+}
+
+export function getAgentManifestSurfaceToolContracts(
+ manifest: AgentCapabilitiesManifest | undefined,
+): AgentSurfaceToolContract[] {
+ const contracts: AgentSurfaceToolContract[] = [];
+ for (const surface of manifest?.surfaceContract?.operatorSurfaces ?? []) {
+ if (!surface.externalAdapter) continue;
+ const contract = getAgentManifestSurfaceToolContract(manifest, surface.id);
+ if (contract) contracts.push(contract);
+ }
+ return contracts;
+}
+
+export function getAgentSurfaceToolPosturePresentation(
+ contract: AgentSurfaceToolContract | undefined,
+): AgentSurfaceToolPosturePresentation | null {
+ const normalized = normalizeAgentSurfaceToolContract(contract);
+ if (!normalized) return null;
+
+ const toolCount = normalized.toolNames.length;
+ const registryCount = normalized.registryToolNames?.length ?? 0;
+ const capabilityCount = normalized.capabilityNames?.length ?? 0;
+ const nativeCount = normalized.nativeToolNames?.length ?? 0;
+ const source = formatSurfaceToolSource(normalized.toolSource);
+ const surfaceLabel = normalized.surfaceLabel || normalized.surfaceId;
+ const label = toolCount === 1 ? '1 capability' : `${toolCount} capabilities`;
+ const breakdown = [
+ registryCount > 0
+ ? `${registryCount} ${registryCount === 1 ? 'registry capability' : 'registry capabilities'}`
+ : '',
+ capabilityCount > 0
+ ? `${capabilityCount} published ${capabilityCount === 1 ? 'capability' : 'capabilities'}`
+ : '',
+ nativeCount > 0
+ ? `${nativeCount} ${nativeCount === 1 ? 'native capability' : 'native capabilities'}`
+ : '',
+ ].filter(Boolean);
+ const affordanceLabels = surfaceAffordanceLabels(normalized.affordances ?? {});
+ const detail = [...breakdown, ...affordanceLabels].join(', ');
+
+ return {
+ surfaceLabel,
+ label,
+ title: [`${surfaceLabel} capability availability`, `Source: ${source}`, detail || undefined]
+ .filter(Boolean)
+ .join('. '),
+ detail: detail || undefined,
+ tone: toolCount > 0 ? 'ready' : 'empty',
+ toolCount,
+ };
+}
+
+export function getAgentCapabilityErrorCodeSummaries(
+ manifest: AgentCapabilitiesManifest | undefined,
+): AgentCapabilityErrorCodeSummary[] {
+ if (!manifest) return [];
+
+ const summaries = new Map<string, Set<string>>();
+ for (const capability of manifest.capabilities) {
+ const capabilityName = capability.name.trim();
+ if (!capabilityName) continue;
+
+ for (const rawCode of capability.errorCodes ?? []) {
+ const code = rawCode.trim();
+ if (!code) continue;
+ const capabilityNames = summaries.get(code) ?? new Set<string>();
+ capabilityNames.add(capabilityName);
+ summaries.set(code, capabilityNames);
+ }
+ }
+
+ return Array.from(summaries, ([code, capabilityNames]) => ({
+ code,
+ capabilityNames: Array.from(capabilityNames),
+ }));
+}
diff --git a/frontend-modern/src/api/agentProfiles.ts b/frontend-modern/src/api/agentProfiles.ts
index 5d301f79b8..f519363d10 100644
--- a/frontend-modern/src/api/agentProfiles.ts
+++ b/frontend-modern/src/api/agentProfiles.ts
@@ -34,14 +34,14 @@ export interface AgentProfileAssignment {
}
/**
- * Request for AI-assisted profile suggestion.
+ * Request for Pulse Intelligence profile suggestion.
*/
export interface ProfileSuggestionRequest {
prompt: string;
}
/**
- * AI-generated profile suggestion.
+ * Pulse Intelligence profile suggestion.
*/
export interface ProfileSuggestion {
name: string;
@@ -365,7 +365,7 @@ export class AgentProfilesAPI {
}
/**
- * Get AI-assisted profile suggestion.
+ * Get Pulse Intelligence profile suggestion.
* Requires AI to be enabled and running.
*/
static async suggestProfile(request: ProfileSuggestionRequest): Promise<ProfileSuggestion> {
@@ -378,7 +378,7 @@ export class AgentProfilesAPI {
await assertAPIResponseOKOrThrowStatus(
response,
503,
- 'Pulse Assistant service is not available. Please check Pulse Assistant settings.',
+ 'Pulse Intelligence is not available. Please check Assistant & Patrol settings.',
`Failed to get suggestion: ${response.status}`,
);
diff --git a/frontend-modern/src/api/ai.ts b/frontend-modern/src/api/ai.ts
index aac27b6367..f0661b3c81 100644
--- a/frontend-modern/src/api/ai.ts
+++ b/frontend-modern/src/api/ai.ts
@@ -681,6 +681,7 @@ export type InvestigationOutcome =
| 'fix_queued'
| 'fix_executed'
| 'fix_failed'
+ | 'fix_rejected'
| 'needs_attention'
| 'cannot_fix'
| 'timed_out'
diff --git a/frontend-modern/src/api/aiChat.ts b/frontend-modern/src/api/aiChat.ts
index 2ffb6a6af6..0e1787a203 100644
--- a/frontend-modern/src/api/aiChat.ts
+++ b/frontend-modern/src/api/aiChat.ts
@@ -2,6 +2,7 @@ import { apiFetchJSON, apiFetch } from '@/utils/apiClient';
import { assertAPIResponseOK } from './responseUtils';
import { logger } from '@/utils/logger';
import type { AIChatStreamEvent } from './generated/aiChatEvents';
+import type { AgentSurfaceToolContract } from './agentCapabilities';
import { consumeJSONEventStream } from './streaming';
import { maybeRunAIChatDevStreamFixture } from './aiChatDevStreamFixture';
@@ -197,6 +198,34 @@ export interface AIStatus {
engine: string;
}
+export interface AssistantWorkflowPromptRenderRequest {
+ name: string;
+ arguments?: Record<string, string>;
+}
+
+export const PULSE_OPERATIONS_LOOP_WORKFLOW_PROMPT_NAME = 'pulse_operations_loop';
+export const PULSE_PATROL_WORKFLOW_PROMPT_SURFACE = 'pulse_patrol';
+export const PULSE_PATROL_CONTROL_WORKFLOW_PROMPT_SURFACE = 'patrol_control';
+export const PULSE_PATROL_AUTONOMY_WORKFLOW_PROMPT_SURFACE = 'patrol_autonomy';
+export const PULSE_PRO_ACTIVATION_WORKFLOW_PROMPT_SURFACE = 'pulse_pro_activation';
+
+export type AssistantWorkflowPromptActivitySurface =
+ | 'pulse_assistant'
+ | 'pulse_patrol'
+ | 'patrol_control'
+ | 'patrol_autonomy'
+ | 'pulse_pro_activation';
+
+export interface AssistantWorkflowPromptActivityRequest {
+ name: string;
+ surface?: AssistantWorkflowPromptActivitySurface;
+}
+
+export interface AssistantWorkflowPromptRenderResponse {
+ description: string;
+ text: string;
+}
+
// AI Agent (build, code, etc.) with specific permissions and model
export interface Agent {
name: string;
@@ -219,6 +248,35 @@ export class AIChatAPI {
return apiFetchJSON(`${this.baseUrl}/status`) as Promise<AIStatus>;
}
+ // Get the live native Assistant surface tool contract for the current runtime mode.
+ static async getAssistantSurfaceTools(): Promise<AgentSurfaceToolContract> {
+ return apiFetchJSON(
+ `${this.baseUrl}/assistant/surface-tools`,
+ ) as Promise<AgentSurfaceToolContract>;
+ }
+
+ // Render a shared Pulse Intelligence workflow prompt for the native Assistant surface.
+ static async renderWorkflowPrompt(
+ request: AssistantWorkflowPromptRenderRequest,
+ ): Promise<AssistantWorkflowPromptRenderResponse> {
+ return apiFetchJSON(`${this.baseUrl}/workflow-prompts/render`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(request),
+ }) as Promise<AssistantWorkflowPromptRenderResponse>;
+ }
+
+ // Record that a first-party Pulse surface started a shared workflow prompt.
+ static async recordWorkflowPromptActivity(
+ request: AssistantWorkflowPromptActivityRequest,
+ ): Promise<void> {
+ await apiFetch(`${this.baseUrl}/workflow-prompts/activity`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(request),
+ });
+ }
+
// List all chat sessions. Normalizes a null/non-array payload (e.g. a server
// error body) to an empty array so callers can rely on array semantics and do
// not crash on .length/.some()/.map() (#1149).
@@ -310,9 +368,7 @@ export class AIChatAPI {
}
// Summarize a session (compress context when nearing limits)
- static async summarizeSession(
- sessionId: string,
- ): Promise<ChatSessionCompactionResult> {
+ static async summarizeSession(sessionId: string): Promise<ChatSessionCompactionResult> {
return apiFetchJSON(`${this.baseUrl}/sessions/${encodeURIComponent(sessionId)}/summarize`, {
method: 'POST',
}) as Promise<ChatSessionCompactionResult>;
diff --git a/frontend-modern/src/api/generated/agentCapabilities.ts b/frontend-modern/src/api/generated/agentCapabilities.ts
new file mode 100644
index 0000000000..330dcfa550
--- /dev/null
+++ b/frontend-modern/src/api/generated/agentCapabilities.ts
@@ -0,0 +1,113 @@
+// This file is generated from scripts/generate-types.go; DO NOT EDIT.
+// Source: internal/agentcapabilities manifest structs.
+
+/* eslint-disable */
+
+export type AgentCapabilityActionMode = 'read' | 'mixed' | 'write';
+export type AgentCapabilityApprovalPolicy = 'scope_only' | 'action_plan';
+
+export interface Capability {
+ name: string;
+ title?: string;
+ description: string;
+ category: string;
+ method: string;
+ path: string;
+ scope: string;
+ actionMode: AgentCapabilityActionMode;
+ approvalPolicy: AgentCapabilityApprovalPolicy;
+ responseShape?: string;
+ outputSchema?: Record<string, unknown>;
+ errorCodes?: string[];
+ requestBodyShape?: string;
+ inputSchema?: Record<string, unknown>;
+}
+
+export interface CapabilityCategory {
+ id: string;
+ label: string;
+ description?: string;
+}
+
+export interface MCPAdapterConfigFamily {
+ id: string;
+ label: string;
+ shape: string;
+ description?: string;
+ fileHints?: string[];
+ clientLabels?: string[];
+}
+
+export interface MCPAdapterContract {
+ serverName: string;
+ command: string;
+ baseUrlFlag: string;
+ defaultBaseUrl: string;
+ tokenEnv: string;
+ configFamilies: MCPAdapterConfigFamily[];
+}
+
+export interface Manifest {
+ version: string;
+ surfaceContract: SurfaceContract;
+ surfaceToolContracts: SurfaceToolContract[];
+ mcpAdapter: MCPAdapterContract;
+ requiredScopes: string[];
+ categories: CapabilityCategory[];
+ workflowPrompts: PulseWorkflowPrompt[];
+ capabilities: Capability[];
+}
+
+export interface OperatorSurfaceContract {
+ id: string;
+ label: string;
+ description: string;
+ native: boolean;
+ externalAdapter: boolean;
+ affordances?: SurfaceAffordanceContract;
+}
+
+export interface PulseWorkflowPrompt {
+ name: string;
+ label?: string;
+ presentationKind?: string;
+ description?: string;
+ arguments?: PulseWorkflowPromptArgument[];
+}
+
+export interface PulseWorkflowPromptArgument {
+ name: string;
+ description?: string;
+ required?: boolean;
+}
+
+export interface SurfaceAffordanceContract {
+ tools?: boolean;
+ resources?: boolean;
+ prompts?: boolean;
+ capabilityMetadata?: boolean;
+ interactiveQuestions?: boolean;
+}
+
+export interface SurfaceContract {
+ core: SurfaceContractComponent;
+ proactiveEngine: SurfaceContractComponent;
+ operatorSurfaces: OperatorSurfaceContract[];
+}
+
+export interface SurfaceContractComponent {
+ id: string;
+ label: string;
+ description: string;
+}
+
+export interface SurfaceToolContract {
+ surfaceId: string;
+ surfaceLabel?: string;
+ toolSource: string;
+ toolNames: string[];
+ registryToolNames?: string[];
+ capabilityNames?: string[];
+ nativeToolNames?: string[];
+ affordances?: SurfaceAffordanceContract;
+}
diff --git a/frontend-modern/src/api/generated/aiChatEvents.ts b/frontend-modern/src/api/generated/aiChatEvents.ts
index 469c63fd53..c049d63028 100644
--- a/frontend-modern/src/api/generated/aiChatEvents.ts
+++ b/frontend-modern/src/api/generated/aiChatEvents.ts
@@ -1,4 +1,4 @@
-// Code generated by scripts/generate-types.go; DO NOT EDIT.
+// This file is generated from scripts/generate-types.go; DO NOT EDIT.
// Source: internal/ai/chat event payload structs.
/* eslint-disable */
@@ -58,6 +58,7 @@ export interface DoneData {
model?: string;
input_tokens?: number;
output_tokens?: number;
+ context_limit_tokens?: number;
}
export interface ErrorData {
diff --git a/frontend-modern/src/api/patrol.ts b/frontend-modern/src/api/patrol.ts
index ef55f05627..4c6c6bcdce 100644
--- a/frontend-modern/src/api/patrol.ts
+++ b/frontend-modern/src/api/patrol.ts
@@ -47,7 +47,7 @@ export interface Finding {
// quiet on re-detection until this timestamp passes, then the next
// re-detection clears the dismissal and emits a "reminded" lifecycle event.
remind_at?: string;
- // Investigation fields (Patrol Autonomy)
+ // Investigation fields (Patrol mode)
investigation_session_id?: string;
investigation_status?: InvestigationStatus;
investigation_outcome?: InvestigationOutcome;
@@ -78,6 +78,7 @@ export type InvestigationOutcome =
| 'fix_queued'
| 'fix_executed'
| 'fix_failed'
+ | 'fix_rejected'
| 'needs_attention'
| 'cannot_fix'
| 'timed_out'
@@ -403,18 +404,18 @@ export async function setFindingNote(
}
// =============================================================================
-// Patrol Autonomy APIs
+// Patrol Mode APIs
// =============================================================================
/**
- * Get current patrol autonomy settings
+ * Get current Patrol mode settings
*/
export async function getPatrolAutonomySettings(): Promise<PatrolAutonomySettings> {
return apiFetchJSON<PatrolAutonomySettings>('/api/ai/patrol/autonomy');
}
/**
- * Update patrol autonomy settings
+ * Update Patrol mode settings
*/
export async function updatePatrolAutonomySettings(
settings: PatrolAutonomySettings,
@@ -505,6 +506,7 @@ export const investigationOutcomeLabels: Record<InvestigationOutcome, string> =
fix_queued: 'Fix Queued',
fix_executed: 'Fix Executed',
fix_failed: 'Fix Failed',
+ fix_rejected: 'Fix Rejected',
needs_attention: 'Needs Attention',
cannot_fix: 'Cannot Remediate',
timed_out: 'Timed Out — Will Retry',
@@ -525,6 +527,8 @@ export const investigationOutcomeColors: Record<InvestigationOutcome, string> =
'border-green-200 bg-green-50 text-green-700 dark:border-green-800 dark:bg-green-900 dark:text-green-300',
fix_failed:
'border-red-200 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-900 dark:text-red-300',
+ fix_rejected:
+ 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900 dark:text-amber-300',
needs_attention:
'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900 dark:text-amber-300',
cannot_fix: 'border-slate-200 bg-slate-50 text-slate-600',
@@ -544,11 +548,7 @@ export const investigationOutcomeColors: Record<InvestigationOutcome, string> =
export type PatrolRunStatus = 'healthy' | 'issues_found' | 'critical' | 'error';
-export type ToolCallVerificationStatus =
- | 'unknown'
- | 'verified'
- | 'unverified'
- | 'failed';
+export type ToolCallVerificationStatus = 'unknown' | 'verified' | 'unverified' | 'failed';
export interface ToolCallVerification {
status: ToolCallVerificationStatus;
diff --git a/frontend-modern/src/api/settings.ts b/frontend-modern/src/api/settings.ts
index cf4132553c..ec84908435 100644
--- a/frontend-modern/src/api/settings.ts
+++ b/frontend-modern/src/api/settings.ts
@@ -51,6 +51,62 @@ export interface TelemetryPingPreview {
multi_tenant: boolean;
paid_license: boolean;
has_api_tokens: boolean;
+ pulse_intelligence_loop_configured: boolean;
+ pulse_intelligence_loop_active_30d: boolean;
+ pulse_intelligence_complete_operations_loop_30d: boolean;
+ pulse_intelligence_approved_execution_loop_30d: boolean;
+ pulse_intelligence_resolved_operations_loop_30d: boolean;
+ pulse_intelligence_patrol_control_completed_operations_loop_30d: boolean;
+ pulse_intelligence_patrol_control_resolved_operations_loop_30d: boolean;
+ pulse_intelligence_patrol_control_paid_completed_operations_loop_30d: boolean;
+ pulse_intelligence_patrol_control_paid_resolved_operations_loop_30d: boolean;
+ pulse_intelligence_pro_activation_completed_operations_loop_30d: boolean;
+ pulse_intelligence_pro_activation_resolved_operations_loop_30d: boolean;
+ pulse_intelligence_pro_activation_paid_completed_operations_loop_30d: boolean;
+ pulse_intelligence_pro_activation_paid_resolved_operations_loop_30d: boolean;
+ pulse_intelligence_governed_action_active_30d: boolean;
+ pulse_intelligence_assistant_operations_loop_30d: boolean;
+ pulse_intelligence_assistant_approved_execution_loop_30d: boolean;
+ pulse_intelligence_assistant_approved_action_success_loop_30d: boolean;
+ pulse_intelligence_assistant_resolved_operations_loop_30d: boolean;
+ pulse_intelligence_external_agent_operations_loop_30d: boolean;
+ pulse_intelligence_external_agent_approved_execution_loop_30d: boolean;
+ pulse_intelligence_external_agent_approved_action_success_loop_30d: boolean;
+ pulse_intelligence_external_agent_resolved_operations_loop_30d: boolean;
+ pulse_intelligence_mcp_adapter_operations_loop_30d: boolean;
+ pulse_intelligence_mcp_adapter_approved_execution_loop_30d: boolean;
+ pulse_intelligence_mcp_adapter_approved_action_success_loop_30d: boolean;
+ pulse_intelligence_mcp_adapter_resolved_operations_loop_30d: boolean;
+ pulse_intelligence_operations_loop_starter_requests_30d: number;
+ pulse_intelligence_assistant_operations_loop_starter_requests_30d: number;
+ pulse_intelligence_patrol_operations_loop_starter_requests_30d: number;
+ pulse_intelligence_patrol_control_operations_loop_starter_requests_30d: number;
+ pulse_intelligence_pro_activation_operations_loop_starter_requests_30d: number;
+ pulse_intelligence_mcp_operations_loop_starter_requests_30d: number;
+ pulse_intelligence_assistant_ai_calls_30d: number;
+ pulse_intelligence_assistant_context_ai_calls_30d: number;
+ pulse_intelligence_assistant_tool_calls_30d: number;
+ pulse_intelligence_patrol_ai_calls_30d: number;
+ pulse_intelligence_patrol_runs_30d: number;
+ pulse_intelligence_patrol_new_findings_30d: number;
+ pulse_intelligence_patrol_investigations_30d: number;
+ pulse_intelligence_patrol_resolved_findings_30d: number;
+ pulse_intelligence_patrol_autofixes_30d: number;
+ pulse_intelligence_external_agent_enabled: boolean;
+ pulse_intelligence_external_agent_used_30d: boolean;
+ pulse_intelligence_mcp_adapter_used_30d: boolean;
+ pulse_intelligence_external_agent_context_requests_30d: number;
+ pulse_intelligence_external_agent_event_stream_requests_30d: number;
+ pulse_intelligence_external_agent_provisioning_requests_30d: number;
+ pulse_intelligence_external_agent_operator_state_requests_30d: number;
+ pulse_intelligence_external_agent_finding_requests_30d: number;
+ pulse_intelligence_external_agent_action_requests_30d: number;
+ pulse_intelligence_action_plans_30d: number;
+ pulse_intelligence_approval_requests_30d: number;
+ pulse_intelligence_rejected_action_decisions_30d: number;
+ pulse_intelligence_approved_action_decisions_30d: number;
+ pulse_intelligence_approved_action_attempts_30d: number;
+ pulse_intelligence_approved_action_successes_30d: number;
}
export interface TelemetryPreviewResponse {
diff --git a/frontend-modern/src/components/AI/AICostDashboard.tsx b/frontend-modern/src/components/AI/AICostDashboard.tsx
index 03d77e7c09..d67bf4973c 100644
--- a/frontend-modern/src/components/AI/AICostDashboard.tsx
+++ b/frontend-modern/src/components/AI/AICostDashboard.tsx
@@ -26,6 +26,7 @@ import {
AI_COST_PANEL_TITLE,
AI_COST_PATROL_USE_CASE_LABEL,
AI_COST_PROVIDER_MODEL_PAIR_LABEL,
+ AI_COST_TARGET_TABLE_LABEL,
AI_COST_RESET_HISTORY_LABEL,
buildAICostExportFilename,
getAICostBudgetNote,
@@ -36,6 +37,7 @@ import {
getAICostResetHistoryConfirmationMessage,
getAICostResetHistoryErrorMessage,
getAICostResetHistorySuccessMessage,
+ getAICostTargetPresentation,
} from '@/utils/aiCostPresentation';
const usdFormatter = new Intl.NumberFormat(undefined, {
@@ -548,7 +550,9 @@ export const AICostDashboard: Component = () => {
<Table class="min-w-full text-sm">
<TableHeader class="text-xs text-muted uppercase tracking-wide">
<TableRow class="border-b border-border">
- <TableHead class="text-left py-2 pr-4">Top targets</TableHead>
+ <TableHead class="text-left py-2 pr-4">
+ {AI_COST_TARGET_TABLE_LABEL}
+ </TableHead>
<TableHead class="text-right py-2 px-2">Est. USD</TableHead>
<TableHead class="text-right py-2 px-2">Calls</TableHead>
<TableHead class="text-right py-2 px-2">Tokens</TableHead>
@@ -556,27 +560,37 @@ export const AICostDashboard: Component = () => {
</TableHeader>
<TableBody>
<For each={data().targets}>
- {(t) => (
- <TableRow class="border-b border-border-subtle">
- <TableCell class="py-2 pr-4 text-base-content font-mono text-xs">
- {t.target_type}:{t.target_id}
- </TableCell>
- <TableCell class="py-2 px-2 text-right text-base-content">
- <Show
- when={t.pricing_known}
- fallback={<span class="text-muted" aria-hidden="true">—</span>}
- >
- {formatUSD(t.estimated_usd ?? 0)}
- </Show>
- </TableCell>
- <TableCell class="py-2 px-2 text-right text-base-content">
- {formatNumber(t.calls)}
- </TableCell>
- <TableCell class="py-2 px-2 text-right text-base-content">
- {formatNumber(t.total_tokens)}
- </TableCell>
- </TableRow>
- )}
+ {(t) => {
+ const target = getAICostTargetPresentation(t);
+ return (
+ <TableRow class="border-b border-border-subtle">
+ <TableCell class="py-2 pr-4 text-base-content">
+ <span class="font-medium">{target.label}</span>
+ <Show when={target.detail}>
+ <span class="block text-xs text-muted">{target.detail}</span>
+ </Show>
+ </TableCell>
+ <TableCell class="py-2 px-2 text-right text-base-content">
+ <Show
+ when={t.pricing_known}
+ fallback={
+ <span class="text-muted" aria-hidden="true">
+ —
+ </span>
+ }
+ >
+ {formatUSD(t.estimated_usd ?? 0)}
+ </Show>
+ </TableCell>
+ <TableCell class="py-2 px-2 text-right text-base-content">
+ {formatNumber(t.calls)}
+ </TableCell>
+ <TableCell class="py-2 px-2 text-right text-base-content">
+ {formatNumber(t.total_tokens)}
+ </TableCell>
+ </TableRow>
+ );
+ }}
</For>
</TableBody>
</Table>
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
index f497d729c6..ca1343062b 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
@@ -13,6 +13,7 @@ const {
mockChat,
mockAIAPI,
mockAIChatAPI,
+ mockFetchAgentCapabilitiesManifest,
mockNotificationStore,
mockAiChatStore,
mockByType,
@@ -91,6 +92,18 @@ const {
const mockAIChatAPI = {
getStatus: vi.fn().mockResolvedValue({ running: true }),
+ getAssistantSurfaceTools: vi.fn().mockResolvedValue({
+ surfaceId: 'pulse_assistant',
+ surfaceLabel: 'Pulse Assistant',
+ toolSource: 'assistant_registry',
+ toolNames: ['pulse_query', 'pulse_question'],
+ registryToolNames: ['pulse_query'],
+ nativeToolNames: ['pulse_question'],
+ affordances: {
+ tools: true,
+ interactiveQuestions: true,
+ },
+ }),
listSessions: vi.fn().mockResolvedValue([]),
createSession: vi.fn().mockResolvedValue({
id: 'new',
@@ -124,8 +137,25 @@ const {
}),
approveCommand: vi.fn().mockResolvedValue({ approved: true, message: 'ok' }),
denyCommand: vi.fn().mockResolvedValue({ denied: true, message: 'ok' }),
+ renderWorkflowPrompt: vi.fn().mockResolvedValue({
+ description: 'Pulse fleet triage',
+ text: 'Use get_fleet_context to triage the Pulse fleet.',
+ }),
};
+ const mockFetchAgentCapabilitiesManifest = vi.fn().mockResolvedValue({
+ version: 'v1',
+ workflowPrompts: [],
+ capabilities: [],
+ categories: [],
+ requiredScopes: [],
+ surfaceContract: {
+ core: { id: 'pulse_intelligence_core', label: 'Pulse Intelligence Core', description: '' },
+ proactiveEngine: { id: 'pulse_patrol', label: 'Pulse Patrol', description: '' },
+ operatorSurfaces: [],
+ },
+ });
+
const mockNotificationStore = {
info: vi.fn(),
success: vi.fn(),
@@ -144,6 +174,7 @@ const {
handoffResources: undefined,
handoffActions: undefined,
handoffMetadata: undefined,
+ preferredWorkflowPromptName: undefined,
});
const mockAiChatStore = {
@@ -189,6 +220,7 @@ const {
runStatus?: string;
runtimeFailure?: boolean;
};
+ preferredWorkflowPromptName?: string;
briefing?: {
sourceLabel: string;
title: string;
@@ -219,6 +251,7 @@ const {
handoffResources: _handoffResources,
handoffActions: _handoffActions,
handoffMetadata: _handoffMetadata,
+ preferredWorkflowPromptName: _preferredWorkflowPromptName,
...rest
} = mockAiChatStore.context;
mockAiChatStore.context = rest;
@@ -236,6 +269,7 @@ const {
mockChat,
mockAIAPI,
mockAIChatAPI,
+ mockFetchAgentCapabilitiesManifest,
mockNotificationStore,
mockAiChatStore,
mockByType,
@@ -398,6 +432,36 @@ vi.mock('../MentionAutocomplete', () => ({
vi.mock('@/api/ai', () => ({ AIAPI: mockAIAPI }));
vi.mock('@/api/aiChat', () => ({ AIChatAPI: mockAIChatAPI }));
+vi.mock('@/api/agentCapabilities', () => ({
+ fetchAgentCapabilitiesManifest: mockFetchAgentCapabilitiesManifest,
+ getAgentSurfaceToolPosturePresentation: (
+ contract:
+ | {
+ surfaceLabel?: string;
+ toolSource?: string;
+ toolNames?: string[];
+ registryToolNames?: string[];
+ nativeToolNames?: string[];
+ }
+ | undefined,
+ ) => {
+ if (!contract) return null;
+ const toolCount = contract.toolNames?.length ?? 0;
+ const label = toolCount === 1 ? '1 capability' : `${toolCount} capabilities`;
+ return {
+ label,
+ title: `${contract.surfaceLabel || 'Pulse Assistant'} capability availability. Source: ${
+ contract.toolSource === 'assistant_registry' ? 'Assistant registry' : contract.toolSource
+ }. ${(contract.registryToolNames?.length ?? 0).toString()} registry capabilities. ${(
+ contract.nativeToolNames?.length ?? 0
+ ).toString()} native capabilities.`,
+ tone: toolCount > 0 ? 'ready' : 'empty',
+ toolCount,
+ };
+ },
+ getAgentWorkflowPrompts: (manifest: { workflowPrompts?: unknown[] } | undefined) =>
+ manifest?.workflowPrompts ?? [],
+}));
vi.mock('@/stores/notifications', () => ({ notificationStore: mockNotificationStore }));
vi.mock('@/stores/aiChat', () => ({ aiChatStore: mockAiChatStore }));
vi.mock('@/utils/logger', () => ({
@@ -511,7 +575,35 @@ beforeEach(() => {
model: 'openai:gpt-4',
});
mockAIChatAPI.getStatus.mockResolvedValue({ running: true });
+ mockAIChatAPI.getAssistantSurfaceTools.mockResolvedValue({
+ surfaceId: 'pulse_assistant',
+ surfaceLabel: 'Pulse Assistant',
+ toolSource: 'assistant_registry',
+ toolNames: ['pulse_query', 'pulse_question'],
+ registryToolNames: ['pulse_query'],
+ nativeToolNames: ['pulse_question'],
+ affordances: {
+ tools: true,
+ interactiveQuestions: true,
+ },
+ });
mockAIChatAPI.listSessions.mockResolvedValue([]);
+ mockAIChatAPI.renderWorkflowPrompt.mockResolvedValue({
+ description: 'Pulse fleet triage',
+ text: 'Use get_fleet_context to triage the Pulse fleet.',
+ });
+ mockFetchAgentCapabilitiesManifest.mockResolvedValue({
+ version: 'v1',
+ workflowPrompts: [],
+ capabilities: [],
+ categories: [],
+ requiredScopes: [],
+ surfaceContract: {
+ core: { id: 'pulse_intelligence_core', label: 'Pulse Intelligence Core', description: '' },
+ proactiveEngine: { id: 'pulse_patrol', label: 'Pulse Patrol', description: '' },
+ operatorSurfaces: [],
+ },
+ });
mockAIChatAPI.renameSession.mockResolvedValue({
id: 'renamed-session',
title: 'Renamed session',
@@ -813,6 +905,151 @@ describe('AIChat', () => {
expect(screen.getByPlaceholderText('Ask about your infrastructure...')).toBeInTheDocument();
});
+ it('renders shared workflow starters and inserts rendered prompt text into the composer', async () => {
+ mockAiChatStore.context = {
+ targetType: 'vm',
+ targetId: 'vm:101',
+ findingId: undefined,
+ autonomousMode: undefined,
+ briefing: undefined,
+ };
+ mockFetchAgentCapabilitiesManifest.mockResolvedValueOnce({
+ version: 'v1',
+ workflowPrompts: [
+ {
+ name: 'pulse_triage_fleet',
+ label: 'Review fleet posture',
+ presentationKind: 'fleet',
+ description: 'Triage the Pulse fleet.',
+ arguments: [],
+ },
+ {
+ name: 'pulse_operations_loop',
+ label: 'Ask Patrol to handle an issue',
+ presentationKind: 'workflow',
+ description:
+ 'Have Patrol investigate active findings, follow the configured Patrol policy, take approved actions, verify the outcome, and record what happened.',
+ arguments: [],
+ },
+ {
+ name: 'pulse_investigate_resource',
+ label: 'Inspect this resource',
+ presentationKind: 'resource',
+ description: 'Investigate one Pulse resource.',
+ arguments: [{ name: 'resourceId', required: true }],
+ },
+ {
+ name: 'pulse_review_finding',
+ presentationKind: 'finding',
+ description: 'Review one Patrol finding.',
+ arguments: [{ name: 'finding_id', required: true }],
+ },
+ ],
+ capabilities: [],
+ categories: [],
+ requiredScopes: [],
+ surfaceContract: {
+ core: {
+ id: 'pulse_intelligence_core',
+ label: 'Pulse Intelligence Core',
+ description: '',
+ },
+ proactiveEngine: { id: 'pulse_patrol', label: 'Pulse Patrol', description: '' },
+ operatorSurfaces: [],
+ },
+ });
+ mockAIChatAPI.renderWorkflowPrompt.mockResolvedValueOnce({
+ description: 'Pulse resource investigation',
+ text: 'Investigate Pulse resource "vm:101".',
+ });
+
+ renderChat();
+
+ expect(
+ await screen.findByTestId('assistant-workflow-starter-pulse_triage_fleet'),
+ ).toHaveTextContent('Review fleet posture');
+ expect(
+ await screen.findByTestId('assistant-workflow-starter-pulse_operations_loop'),
+ ).toHaveTextContent('Ask Patrol to handle an issue');
+ const resourceStarter = await screen.findByTestId(
+ 'assistant-workflow-starter-pulse_investigate_resource',
+ );
+ expect(screen.queryByTestId('assistant-workflow-starter-pulse_review_finding')).toBeNull();
+
+ fireEvent.click(resourceStarter);
+
+ await waitFor(() => {
+ expect(mockAIChatAPI.renderWorkflowPrompt).toHaveBeenCalledWith({
+ name: 'pulse_investigate_resource',
+ arguments: { resourceId: 'vm:101' },
+ });
+ });
+ expect(screen.getByPlaceholderText('Ask about your infrastructure...')).toHaveValue(
+ 'Investigate Pulse resource "vm:101".',
+ );
+ });
+
+ it('auto-renders a preferred operations-loop starter for scoped Patrol handoffs', async () => {
+ mockAiChatStore.context = {
+ targetType: 'vm',
+ targetId: 'vm:101',
+ findingId: 'finding-1',
+ autonomousMode: false,
+ preferredWorkflowPromptName: 'pulse_operations_loop',
+ };
+ mockFetchAgentCapabilitiesManifest.mockResolvedValueOnce({
+ version: 'v1',
+ workflowPrompts: [
+ {
+ name: 'pulse_operations_loop',
+ label: 'Ask Patrol to handle an issue',
+ presentationKind: 'workflow',
+ description:
+ 'Have Patrol investigate active findings, follow the configured Patrol policy, take approved actions, verify the outcome, and record what happened.',
+ arguments: [],
+ },
+ {
+ name: 'pulse_review_finding',
+ label: 'Review selected finding',
+ presentationKind: 'finding',
+ description: 'Review one Patrol finding.',
+ arguments: [{ name: 'finding_id', required: true }],
+ },
+ ],
+ capabilities: [],
+ categories: [],
+ requiredScopes: [],
+ surfaceContract: {
+ core: {
+ id: 'pulse_intelligence_core',
+ label: 'Pulse Intelligence Core',
+ description: '',
+ },
+ proactiveEngine: { id: 'pulse_patrol', label: 'Pulse Patrol', description: '' },
+ operatorSurfaces: [],
+ },
+ });
+ mockAIChatAPI.renderWorkflowPrompt.mockResolvedValueOnce({
+ description: 'Patrol issue handling',
+ text: 'Handle this Patrol finding through explanation, governed action, verification, and history.',
+ });
+
+ renderChat();
+
+ await waitFor(() => {
+ expect(mockAIChatAPI.renderWorkflowPrompt).toHaveBeenCalledWith({
+ name: 'pulse_operations_loop',
+ arguments: {},
+ });
+ });
+ expect(screen.getByPlaceholderText('Ask about your infrastructure...')).toHaveValue(
+ 'Handle this Patrol finding through explanation, governed action, verification, and history.',
+ );
+ expect(
+ await screen.findByTestId('assistant-workflow-starter-pulse_review_finding'),
+ ).toHaveTextContent('Review selected finding');
+ });
+
it('registers and focuses the composer when opened', async () => {
renderChat();
const textarea = screen.getByPlaceholderText('Ask about your infrastructure...');
@@ -833,6 +1070,30 @@ describe('AIChat', () => {
expect(screen.getByTestId('model-selector')).toBeInTheDocument();
});
+ it('renders native Assistant capability availability from the runtime surface contract', async () => {
+ mockAIChatAPI.getAssistantSurfaceTools.mockResolvedValueOnce({
+ surfaceId: 'pulse_assistant',
+ surfaceLabel: 'Pulse Assistant',
+ toolSource: 'assistant_registry',
+ toolNames: ['pulse_query', 'pulse_question', 'pulse_storage'],
+ registryToolNames: ['pulse_query', 'pulse_storage'],
+ nativeToolNames: ['pulse_question'],
+ affordances: {
+ tools: true,
+ interactiveQuestions: true,
+ },
+ });
+
+ renderChat();
+
+ const toolHealth = await screen.findByTestId('assistant-surface-tools-health');
+ expect(mockAIChatAPI.getAssistantSurfaceTools).toHaveBeenCalled();
+ expect(toolHealth).toHaveTextContent('3 capabilities');
+ const title = toolHealth.getAttribute('title') || '';
+ expect(title).toContain('Pulse Assistant capability availability');
+ expect(title).toContain('Assistant registry');
+ });
+
it('opens the model selector from failed-turn recovery', async () => {
renderChat();
@@ -1094,7 +1355,7 @@ describe('AIChat', () => {
);
expect(screen.getByRole('link', { name: /Open settings/ })).toHaveAttribute(
'href',
- '/settings/system-ai',
+ '/settings/pulse-intelligence/provider',
);
});
@@ -1507,39 +1768,39 @@ describe('AIChat', () => {
sourceLabel: 'Pulse Patrol',
title: 'Patrol finding attached',
subject: 'Provider connection issue on Patrol runtime',
- actionLabel: 'Open Patrol provider settings',
- actionHref: '/settings/system-ai',
+ actionLabel: 'Open Provider & Models',
+ actionHref: '/settings/pulse-intelligence/provider',
},
};
renderChat();
- expect(screen.getByRole('link', { name: 'Open Patrol provider settings' })).toHaveAttribute(
+ expect(screen.getByRole('link', { name: 'Open Provider & Models' })).toHaveAttribute(
'href',
- '/settings/system-ai',
+ '/settings/pulse-intelligence/provider',
);
});
- it('renders Patrol configuration handoff details without replacing the attached headline', () => {
+ it('renders Patrol mode handoff details without replacing the attached headline', () => {
mockAiChatStore.context = {
targetType: 'patrol-configuration',
autonomousMode: false,
briefing: {
sourceLabel: 'Pulse Patrol',
- title: 'Patrol configuration failure attached',
+ title: 'Patrol mode save failure attached',
subject: 'patrol_autonomy_pro_required: Investigation and auto-fix require Pulse Pro.',
statusLabel: 'HTTP 402 · model_unsupported_tools',
detailLines: ['Provider: openrouter'],
evidence: ['Command: sensitive or command detail withheld'],
safetyNote:
- 'Assistant can explain the configuration state; provider changes remain operator-controlled.',
+ 'Assistant can explain the Patrol mode state; provider changes remain operator-controlled.',
},
};
renderChat();
const context = screen.getByLabelText('Assistant context');
- expect(context).toHaveTextContent('Patrol configuration failure attached');
+ expect(context).toHaveTextContent('Patrol mode save failure attached');
expect(context).toHaveTextContent('patrol_autonomy_pro_required');
expect(context).toHaveTextContent('Provider: openrouter');
expect(context).toHaveTextContent('Command: sensitive or command detail withheld');
@@ -1748,7 +2009,7 @@ describe('AIChat', () => {
const routeControls = screen.getByTestId('assistant-composer-route-controls');
const modelSelector = screen.getByTestId('model-selector');
const controlButton = screen.getByRole('button', {
- name: 'Assistant control mode: Read-only',
+ name: 'Assistant chat action mode: Read-only',
});
expect(closeButton).toHaveClass('order-2');
@@ -2004,7 +2265,7 @@ describe('AIChat', () => {
fireEvent.input(textarea, { target: { value: '/connect' } });
fireEvent.keyDown(textarea, { key: 'Enter' });
- expect(mockNavigate).toHaveBeenCalledWith('/settings/system-ai');
+ expect(mockNavigate).toHaveBeenCalledWith('/settings/pulse-intelligence/provider');
expect(onClose).toHaveBeenCalledTimes(1);
expect(mockChat.sendMessage).not.toHaveBeenCalled();
});
@@ -2018,7 +2279,7 @@ describe('AIChat', () => {
selectorProps.onManageProviders?.();
- expect(mockNavigate).toHaveBeenCalledWith('/settings/system-ai');
+ expect(mockNavigate).toHaveBeenCalledWith('/settings/pulse-intelligence/provider');
expect(onClose).toHaveBeenCalledTimes(1);
});
@@ -3141,7 +3402,7 @@ describe('AIChat', () => {
it('opens control menu on click and focuses the current mode', async () => {
renderChat();
const controlButton = screen.getByRole('button', {
- name: 'Assistant control mode: Read-only',
+ name: 'Assistant chat action mode: Read-only',
});
expect(controlButton).toHaveAttribute('aria-expanded', 'false');
@@ -3149,20 +3410,20 @@ describe('AIChat', () => {
expect(controlButton).toHaveAttribute('aria-expanded', 'true');
expect(
- screen.getByRole('menu', { name: 'Assistant control mode options' }),
+ screen.getByRole('menu', { name: 'Assistant chat action options' }),
).toBeInTheDocument();
expect(screen.getByRole('menuitemradio', { name: /Read-only/ })).toHaveAttribute(
'aria-checked',
'true',
);
- expect(screen.getByRole('menuitemradio', { name: /Approval/ })).toHaveAttribute(
+ expect(screen.getByRole('menuitemradio', { name: /Ask first/ })).toHaveAttribute(
'aria-checked',
'false',
);
expect(screen.getByText('Default control mode')).toBeInTheDocument();
- expect(screen.getByText('No commands or control actions')).toBeInTheDocument();
- expect(screen.getByText('Ask before running commands')).toBeInTheDocument();
- expect(screen.getByText('Executes without approval')).toBeInTheDocument();
+ expect(screen.getByText('Observes only')).toBeInTheDocument();
+ expect(screen.getByText('Asks before chat-only actions')).toBeInTheDocument();
+ expect(screen.getByText('Eligible chat-only actions')).toBeInTheDocument();
await waitFor(() => {
expect(document.activeElement).toBe(
screen.getByRole('menuitemradio', { name: /Read-only/ }),
@@ -3173,14 +3434,14 @@ describe('AIChat', () => {
it('opens the control menu from the keyboard', async () => {
renderChat();
const controlButton = screen.getByRole('button', {
- name: 'Assistant control mode: Read-only',
+ name: 'Assistant chat action mode: Read-only',
});
fireEvent.keyDown(controlButton, { key: 'ArrowDown' });
expect(controlButton).toHaveAttribute('aria-expanded', 'true');
expect(
- screen.getByRole('menu', { name: 'Assistant control mode options' }),
+ screen.getByRole('menu', { name: 'Assistant chat action options' }),
).toBeInTheDocument();
await waitFor(() => {
expect(document.activeElement).toBe(
@@ -3198,34 +3459,34 @@ describe('AIChat', () => {
</div>
));
const controlButton = screen.getByRole('button', {
- name: 'Assistant control mode: Read-only',
+ name: 'Assistant chat action mode: Read-only',
});
fireEvent.click(controlButton);
const readOnlyOption = screen.getByRole('menuitemradio', { name: /Read-only/ });
- const approvalOption = screen.getByRole('menuitemradio', { name: /Approval/ });
- const autonomousOption = screen.getByRole('menuitemradio', { name: /Autonomous/ });
+ const askFirstOption = screen.getByRole('menuitemradio', { name: /Ask first/ });
+ const chatActionsOption = screen.getByRole('menuitemradio', { name: /Chat actions/ });
await waitFor(() => {
expect(document.activeElement).toBe(readOnlyOption);
});
fireEvent.keyDown(readOnlyOption, { key: 'ArrowDown' });
- expect(document.activeElement).toBe(approvalOption);
+ expect(document.activeElement).toBe(askFirstOption);
- fireEvent.keyDown(approvalOption, { key: 'End' });
- expect(document.activeElement).toBe(autonomousOption);
+ fireEvent.keyDown(askFirstOption, { key: 'End' });
+ expect(document.activeElement).toBe(chatActionsOption);
- fireEvent.keyDown(autonomousOption, { key: 'Home' });
+ fireEvent.keyDown(chatActionsOption, { key: 'Home' });
expect(document.activeElement).toBe(readOnlyOption);
fireEvent.keyDown(readOnlyOption, { key: 'ArrowUp' });
- expect(document.activeElement).toBe(autonomousOption);
+ expect(document.activeElement).toBe(chatActionsOption);
- fireEvent.keyDown(autonomousOption, { key: 'Escape' });
+ fireEvent.keyDown(chatActionsOption, { key: 'Escape' });
await waitFor(() => {
expect(
- screen.queryByRole('menu', { name: 'Assistant control mode options' }),
+ screen.queryByRole('menu', { name: 'Assistant chat action options' }),
).not.toBeInTheDocument();
expect(document.activeElement).toBe(controlButton);
});
@@ -4249,7 +4510,7 @@ describe('AIChat', () => {
});
});
- it('restores Patrol configuration failure handoff state as a runtime issue', async () => {
+ it('restores Patrol mode save failure handoff state as a runtime issue', async () => {
mockAIChatAPI.listSessions.mockResolvedValue([
{
id: 's-patrol-config',
@@ -4293,9 +4554,9 @@ describe('AIChat', () => {
}),
briefing: expect.objectContaining({
sourceLabel: 'Pulse Patrol',
- title: 'Patrol configuration failure',
- subject: 'Patrol configuration',
- actionLabel: 'Review Patrol configuration issue',
+ title: 'Patrol mode save failure',
+ subject: 'Patrol mode',
+ actionLabel: 'Review Patrol mode issue',
statusLabel: 'runtime issue',
}),
}),
@@ -4405,7 +4666,7 @@ describe('AIChat', () => {
await waitFor(() => {
expect(screen.getByText('Pulse Patrol')).toBeInTheDocument();
expect(screen.getByText('Context attached')).toBeInTheDocument();
- expect(screen.queryByText('Open Patrol provider settings')).not.toBeInTheDocument();
+ expect(screen.queryByText('Open Provider & Models')).not.toBeInTheDocument();
});
fireEvent.click(screen.getByText('Context-only Patrol follow-up'));
@@ -5274,14 +5535,14 @@ describe('AIChat', () => {
renderChat();
await waitFor(() => {
const warning = screen.getByRole('status', {
- name: 'Assistant autonomous control warning',
+ name: 'Assistant chat actions warning',
});
expect(screen.getByTestId('assistant-activity-dock')).toContainElement(warning);
- expect(warning).toHaveTextContent('Autonomous: commands execute without approval.');
+ expect(warning).toHaveTextContent('Chat-only actions are allowed.');
});
});
- it('shows Switch to Approval button in autonomous warning row', async () => {
+ it('shows Switch to Ask first button in autonomous warning row', async () => {
mockAIAPI.getSettings.mockResolvedValue({
model: 'gpt-4',
chat_model: '',
@@ -5292,13 +5553,13 @@ describe('AIChat', () => {
renderChat();
await waitFor(() => {
expect(
- screen.getByRole('status', { name: 'Assistant autonomous control warning' }),
+ screen.getByRole('status', { name: 'Assistant chat actions warning' }),
).toBeInTheDocument();
expect(
- screen.getByRole('button', { name: 'Switch Assistant control mode to Approval' }),
+ screen.getByRole('button', { name: 'Switch Assistant chat actions to Ask first' }),
).toBeInTheDocument();
expect(
- screen.getByRole('button', { name: 'Dismiss autonomous control warning' }),
+ screen.getByRole('button', { name: 'Dismiss chat actions warning' }),
).toBeInTheDocument();
});
});
@@ -5320,13 +5581,13 @@ describe('AIChat', () => {
renderChat();
await waitFor(() => {
- expect(screen.getByText('Approval')).toBeInTheDocument();
+ expect(screen.getByText('Ask first')).toBeInTheDocument();
});
expect(
screen.queryByText(/Approval required for this dashboard brief/),
).not.toBeInTheDocument();
expect(
- screen.queryByRole('status', { name: 'Assistant autonomous control warning' }),
+ screen.queryByRole('status', { name: 'Assistant chat actions warning' }),
).not.toBeInTheDocument();
const textarea = screen.getByPlaceholderText('Ask about your infrastructure...');
@@ -5361,7 +5622,7 @@ describe('AIChat', () => {
renderChat();
await waitFor(() => {
- expect(screen.getByText('Approval')).toBeInTheDocument();
+ expect(screen.getByText('Ask first')).toBeInTheDocument();
});
expect(screen.getByText('Approval required before any action.')).toBeInTheDocument();
expect(
@@ -5394,7 +5655,7 @@ describe('AIChat', () => {
renderChat();
await waitFor(() => {
- expect(screen.getByText('Approval')).toBeInTheDocument();
+ expect(screen.getByText('Ask first')).toBeInTheDocument();
});
expect(screen.getByText('Approval required before any action.')).toBeInTheDocument();
expect(
@@ -5551,7 +5812,7 @@ describe('AIChat', () => {
});
renderChat();
await waitFor(() => {
- expect(screen.getByText('Workload Discovery is off.')).toBeInTheDocument();
+ expect(screen.getByText('Discovery is off.')).toBeInTheDocument();
});
expect(
screen.getByText(
@@ -5565,7 +5826,7 @@ describe('AIChat', () => {
await waitFor(() => {
expect(mockAIAPI.getSettings).toHaveBeenCalled();
});
- expect(screen.queryByText('Workload Discovery is off.')).not.toBeInTheDocument();
+ expect(screen.queryByText('Discovery is off.')).not.toBeInTheDocument();
});
});
@@ -6077,7 +6338,7 @@ describe('AIChat', () => {
screen.getByLabelText('Assistant active turn status'),
);
expect(activityDock).toContainElement(
- screen.getByRole('status', { name: 'Assistant autonomous control warning' }),
+ screen.getByRole('status', { name: 'Assistant chat actions warning' }),
);
});
});
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/activeTurnStatus.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/activeTurnStatus.test.ts
index db6f64e983..bc90eabd05 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/activeTurnStatus.test.ts
+++ b/frontend-modern/src/components/AI/Chat/__tests__/activeTurnStatus.test.ts
@@ -842,7 +842,7 @@ describe('getAssistantActiveTurnStatus', () => {
),
).toEqual({
type: 'tool',
- text: 'Preparing governed tools · command',
+ text: 'Preparing governed actions · command',
});
});
@@ -861,7 +861,7 @@ describe('getAssistantActiveTurnStatus', () => {
message: 'Preparing governed tools',
tool: 'pulse_exec',
}),
- ).toBe('Preparing governed tools · command');
+ ).toBe('Preparing governed actions · command');
});
it('lets a newer provider switch replace stale waiting progress', () => {
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/workflowStarters.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/workflowStarters.test.ts
new file mode 100644
index 0000000000..f8e878cc6f
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/__tests__/workflowStarters.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it } from 'vitest';
+import type { AgentWorkflowPrompt } from '@/api/agentCapabilities';
+import { getAssistantWorkflowStarters } from '../workflowStarters';
+
+const prompts = [
+ {
+ name: 'pulse_triage_fleet',
+ label: 'Review the whole fleet',
+ presentationKind: 'fleet',
+ description: 'Triage the Pulse fleet.',
+ arguments: [],
+ },
+ {
+ name: 'pulse_operations_loop',
+ label: 'Ask Patrol to handle an issue',
+ presentationKind: 'workflow',
+ description:
+ 'Have Patrol investigate active findings, follow the configured Patrol policy, take approved actions, verify the outcome, and record what happened.',
+ arguments: [],
+ },
+ {
+ name: 'pulse_investigate_resource',
+ label: 'Inspect selected resource',
+ presentationKind: 'resource',
+ description: 'Investigate one Pulse resource.',
+ arguments: [{ name: 'resourceId', required: true }],
+ },
+ {
+ name: 'pulse_review_finding',
+ label: 'Review selected finding',
+ presentationKind: 'finding',
+ description: 'Review one Patrol finding.',
+ arguments: [{ name: 'finding_id', required: true }],
+ },
+] satisfies AgentWorkflowPrompt[];
+
+describe('Assistant workflow starters', () => {
+ it('keeps global starters available without scoped context', () => {
+ expect(getAssistantWorkflowStarters(prompts, {})).toEqual([
+ {
+ id: 'pulse_triage_fleet',
+ name: 'pulse_triage_fleet',
+ label: 'Review the whole fleet',
+ description: 'Triage the Pulse fleet.',
+ kind: 'fleet',
+ arguments: {},
+ },
+ {
+ id: 'pulse_operations_loop',
+ name: 'pulse_operations_loop',
+ label: 'Ask Patrol to handle an issue',
+ description:
+ 'Have Patrol investigate active findings, follow the configured Patrol policy, take approved actions, verify the outcome, and record what happened.',
+ kind: 'workflow',
+ arguments: {},
+ },
+ ]);
+ });
+
+ it('resolves resource workflow arguments from attached handoff resources first', () => {
+ const starters = getAssistantWorkflowStarters(prompts, {
+ targetType: 'vm',
+ targetId: 'vm:old',
+ handoffResources: [{ id: 'vm:101', name: 'web-101' }],
+ });
+
+ expect(starters.find((starter) => starter.name === 'pulse_investigate_resource')).toMatchObject(
+ {
+ label: 'Inspect selected resource',
+ kind: 'resource',
+ arguments: { resourceId: 'vm:101' },
+ },
+ );
+ });
+
+ it('does not treat Patrol run ids as resource workflow arguments', () => {
+ const starters = getAssistantWorkflowStarters(prompts, {
+ targetType: 'patrol-run',
+ targetId: 'run-123',
+ findingId: 'finding-1',
+ });
+
+ expect(starters.map((starter) => starter.name)).toEqual([
+ 'pulse_triage_fleet',
+ 'pulse_operations_loop',
+ 'pulse_review_finding',
+ ]);
+ });
+
+ it('resolves finding workflow arguments from direct and action handoff context', () => {
+ const direct = getAssistantWorkflowStarters(prompts, {
+ findingId: 'finding-direct',
+ });
+ expect(direct.find((starter) => starter.name === 'pulse_review_finding')?.arguments).toEqual({
+ finding_id: 'finding-direct',
+ });
+
+ const action = getAssistantWorkflowStarters(prompts, {
+ handoffActions: [{ findingId: 'finding-action' }],
+ });
+ expect(action.find((starter) => starter.name === 'pulse_review_finding')?.arguments).toEqual({
+ finding_id: 'finding-action',
+ });
+ });
+
+ it('falls back to workflow presentation for undeclared kinds instead of inferring names', () => {
+ const [starter] = getAssistantWorkflowStarters(
+ [
+ {
+ name: 'pulse_triage_fleet',
+ label: 'Legacy fleet prompt',
+ presentationKind: 'legacy',
+ arguments: [],
+ },
+ ],
+ {},
+ );
+
+ expect(starter).toMatchObject({
+ name: 'pulse_triage_fleet',
+ kind: 'workflow',
+ });
+ });
+});
diff --git a/frontend-modern/src/components/AI/Chat/activeTurnStatus.ts b/frontend-modern/src/components/AI/Chat/activeTurnStatus.ts
index 5fafb49edd..d2000af04d 100644
--- a/frontend-modern/src/components/AI/Chat/activeTurnStatus.ts
+++ b/frontend-modern/src/components/AI/Chat/activeTurnStatus.ts
@@ -114,6 +114,7 @@ const sanitizeWorkflowStatusMessage = (message: string, tool?: string) => {
}
return sanitized
+ .replace(/\bgoverned tools\b/gi, 'governed actions')
.replace(/\s+\./g, '.')
.replace(/\s{2,}/g, ' ')
.trim();
diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
index 562ffb8080..7061b8dc88 100644
--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts
@@ -2395,7 +2395,7 @@ export function useChat(options: UseChatOptions = {}) {
updateQuestion(messageId, questionId, { isAnswering: true });
try {
- // Send answer to Pulse AI via API
+ // Send answer to Pulse Assistant via API
await AIChatAPI.answerQuestion(questionId, answers);
// Remove the question card - it's been handled
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
index b04606c66e..6dbc6a1405 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -23,6 +23,8 @@ import Redo2Icon from 'lucide-solid/icons/redo-2';
import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';
import RotateCwIcon from 'lucide-solid/icons/rotate-cw';
import SettingsIcon from 'lucide-solid/icons/settings';
+import ShieldAlertIcon from 'lucide-solid/icons/shield-alert';
+import SparklesIcon from 'lucide-solid/icons/sparkles';
import Undo2Icon from 'lucide-solid/icons/undo-2';
import XIcon from 'lucide-solid/icons/x';
import BellIcon from 'lucide-solid/icons/bell';
@@ -34,6 +36,7 @@ import LoaderCircleIcon from 'lucide-solid/icons/loader-circle';
import Minimize2Icon from 'lucide-solid/icons/minimize-2';
import PlusIcon from 'lucide-solid/icons/plus';
import Trash2Icon from 'lucide-solid/icons/trash-2';
+import WrenchIcon from 'lucide-solid/icons/wrench';
import { AIAPI } from '@/api/ai';
import {
AIChatAPI,
@@ -41,6 +44,13 @@ import {
type ChatSession,
type ChatSessionHandoffSummary,
} from '@/api/aiChat';
+import {
+ fetchAgentCapabilitiesManifest,
+ getAgentSurfaceToolPosturePresentation,
+ getAgentWorkflowPrompts,
+ type AgentSurfaceToolContract,
+ type AgentWorkflowPrompt,
+} from '@/api/agentCapabilities';
import { ActionIconButton } from '@/components/shared/Button';
import { SearchField } from '@/components/shared/SearchField';
import { notificationStore } from '@/stores/notifications';
@@ -173,6 +183,7 @@ import {
type AssistantSlashCommand,
type AssistantSlashCommandAction,
} from './assistantSlashCommands';
+import { getAssistantWorkflowStarters, type AssistantWorkflowStarter } from './workflowStarters';
import {
assistantNotificationsEnabled,
assistantNotificationsSupported,
@@ -246,6 +257,22 @@ interface AssistantActiveRoutePresentation {
title: string;
}
+type AssistantSurfaceToolsStatus = 'idle' | 'loading' | 'ready' | 'unavailable';
+
+interface AssistantSurfaceToolsState {
+ status: AssistantSurfaceToolsStatus;
+ contract?: AgentSurfaceToolContract;
+ message?: string;
+}
+
+interface AssistantSurfaceToolHealthPresentation {
+ label: string;
+ title: string;
+ className: string;
+ dotClassName: string;
+ iconClassName: string;
+}
+
interface PromptHistoryEntry {
prompt: string;
mentions: MentionResource[];
@@ -520,7 +547,7 @@ const buildSessionHandoffContext = (session?: ChatSession): AIChatContext | unde
: isPatrolAssessment
? 'Patrol assessment handoff'
: isPatrolConfigurationFailure
- ? 'Patrol configuration failure'
+ ? 'Patrol mode save failure'
: isPatrolFinding
? resourceLabel
? `Patrol finding on ${resourceLabel}`
@@ -574,7 +601,7 @@ const buildSessionHandoffContext = (session?: ChatSession): AIChatContext | unde
: isPatrolAssessment
? 'Current Patrol assessment'
: isPatrolConfigurationFailure
- ? 'Patrol configuration'
+ ? 'Patrol mode'
: findingId
? `Finding ${findingId}`
: undefined,
@@ -596,7 +623,7 @@ const buildSessionHandoffContext = (session?: ChatSession): AIChatContext | unde
actionLabel: summary.requires_approval
? 'Approval required'
: isPatrolConfigurationFailure
- ? 'Review Patrol configuration issue'
+ ? 'Review Patrol mode issue'
: isPatrolAssessment
? 'Review Patrol assessment'
: isPatrolRun && summary.runtime_failure
@@ -679,6 +706,10 @@ export const AIChat: Component<AIChatProps> = (props) => {
});
const [providerReadinessVisible, setProviderReadinessVisible] = createSignal(false);
const [providerReadinessRetryNonce, setProviderReadinessRetryNonce] = createSignal(0);
+ const [assistantSurfaceTools, setAssistantSurfaceTools] =
+ createSignal<AssistantSurfaceToolsState>({
+ status: 'idle',
+ });
const [controlLevel, setControlLevel] = createSignal<AIControlLevel>('read_only');
const [showControlMenu, setShowControlMenu] = createSignal(false);
const [controlSaving, setControlSaving] = createSignal(false);
@@ -687,6 +718,8 @@ export const AIChat: Component<AIChatProps> = (props) => {
const [discoveryEnabled, setDiscoveryEnabled] = createSignal<boolean | null>(null); // null = loading
const [discoveryHintDismissed, setDiscoveryHintDismissed] = createSignal(false);
const [autonomousBannerDismissed, setAutonomousBannerDismissed] = createSignal(false);
+ const [workflowPrompts, setWorkflowPrompts] = createSignal<AgentWorkflowPrompt[]>([]);
+ const [renderingWorkflowStarterId, setRenderingWorkflowStarterId] = createSignal('');
const wsStore = getGlobalWebSocketStore();
const allResources = createMemo<Resource[]>(() => {
const liveResources = wsStore.state.resources ?? [];
@@ -2027,8 +2060,61 @@ export const AIChat: Component<AIChatProps> = (props) => {
};
});
+ const assistantSurfaceToolHealth = createMemo<AssistantSurfaceToolHealthPresentation | null>(
+ () => {
+ const state = assistantSurfaceTools();
+
+ if (state.status === 'loading') {
+ return {
+ label: 'Checking capabilities',
+ title: 'Checking Assistant capability availability',
+ className:
+ 'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-900/60 dark:bg-blue-950/30 dark:text-blue-200',
+ dotClassName: 'bg-blue-500 animate-pulse',
+ iconClassName: 'text-blue-500 dark:text-blue-300',
+ };
+ }
+
+ if (state.status === 'unavailable') {
+ return {
+ label: 'Capabilities unavailable',
+ title:
+ state.message ||
+ 'Pulse could not load the Assistant capability contract for this session.',
+ className:
+ 'border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-100',
+ dotClassName: 'bg-amber-500',
+ iconClassName: 'text-amber-500 dark:text-amber-300',
+ };
+ }
+
+ if (state.status !== 'ready') return null;
+ const posture = getAgentSurfaceToolPosturePresentation(state.contract);
+ if (!posture) return null;
+
+ const readyClassName =
+ posture.tone === 'ready'
+ ? 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-200'
+ : 'border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-100';
+ const readyDotClassName = posture.tone === 'ready' ? 'bg-emerald-500' : 'bg-amber-500';
+ const readyIconClassName =
+ posture.tone === 'ready'
+ ? 'text-emerald-500 dark:text-emerald-300'
+ : 'text-amber-500 dark:text-amber-300';
+
+ return {
+ label: posture.label,
+ title: posture.title,
+ className: readyClassName,
+ dotClassName: readyDotClassName,
+ iconClassName: readyIconClassName,
+ };
+ },
+ );
+
let providerReadinessRequestId = 0;
let lastProviderReadinessKey = '';
+ let assistantSurfaceToolsRequestId = 0;
const refreshSelectedProviderReadiness = async (provider: string, model: string) => {
const requestId = ++providerReadinessRequestId;
@@ -2146,6 +2232,41 @@ export const AIChat: Component<AIChatProps> = (props) => {
}
};
+ const loadWorkflowPrompts = async () => {
+ try {
+ const manifest = await fetchAgentCapabilitiesManifest();
+ setWorkflowPrompts(getAgentWorkflowPrompts(manifest));
+ } catch (error) {
+ logger.debug('[AIChat] Workflow prompt manifest unavailable during initialization:', error);
+ setWorkflowPrompts([]);
+ }
+ };
+
+ const loadAssistantSurfaceTools = async () => {
+ const requestId = ++assistantSurfaceToolsRequestId;
+ setAssistantSurfaceTools({ status: 'loading' });
+
+ try {
+ const contract = await AIChatAPI.getAssistantSurfaceTools();
+ if (requestId !== assistantSurfaceToolsRequestId) return;
+ setAssistantSurfaceTools({ status: 'ready', contract });
+ } catch (error) {
+ if (requestId !== assistantSurfaceToolsRequestId) return;
+ logger.debug(
+ '[AIChat] Assistant surface tool contract unavailable during initialization:',
+ error,
+ );
+ setAssistantSurfaceTools({
+ status: 'unavailable',
+ message: 'Assistant capabilities could not be loaded.',
+ });
+ }
+ };
+
+ const assistantWorkflowStarters = createMemo(() =>
+ getAssistantWorkflowStarters(workflowPrompts(), aiChatStore.context),
+ );
+
createEffect(() => {
const settings = aiRuntimeSettings();
const chatOverride = (settings?.chat_model || '').trim();
@@ -2170,7 +2291,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
setControlLevel(resolved);
if (resolved === 'autonomous') setAutonomousBannerDismissed(false);
notificationStore.success(
- `Control mode set to ${getAIChatControlLevelPresentation(resolved).label}`,
+ `Assistant chat action mode set to ${getAIChatControlLevelPresentation(resolved).label}`,
2000,
);
} catch (error) {
@@ -2351,12 +2472,23 @@ export const AIChat: Component<AIChatProps> = (props) => {
setChatOverrideModel('');
setDiscoveryEnabled(false);
setControlLevel('read_only');
+ setWorkflowPrompts([]);
+ assistantSurfaceToolsRequestId += 1;
+ setAssistantSurfaceTools({ status: 'idle' });
return;
}
- const [sessionsResult, settingsResult, modelsResult] = await Promise.allSettled([
+ const [
+ sessionsResult,
+ settingsResult,
+ modelsResult,
+ workflowPromptsResult,
+ assistantSurfaceToolsResult,
+ ] = await Promise.allSettled([
refreshSessions(),
loadAIRuntimeSettings(),
loadAIRuntimeModels(),
+ loadWorkflowPrompts(),
+ loadAssistantSurfaceTools(),
]);
if (sessionsResult.status === 'rejected') {
logger.error('[AIChat] Failed to load sessions:', sessionsResult.reason);
@@ -2370,6 +2502,18 @@ export const AIChat: Component<AIChatProps> = (props) => {
modelsResult.reason,
);
}
+ if (workflowPromptsResult.status === 'rejected') {
+ logger.debug(
+ '[AIChat] Workflow prompt manifest unavailable during initialization:',
+ workflowPromptsResult.reason,
+ );
+ }
+ if (assistantSurfaceToolsResult.status === 'rejected') {
+ logger.debug(
+ '[AIChat] Assistant surface tool contract unavailable during initialization:',
+ assistantSurfaceToolsResult.reason,
+ );
+ }
} catch (error) {
logger.error('[AIChat] Failed to initialize:', error);
}
@@ -3263,7 +3407,8 @@ export const AIChat: Component<AIChatProps> = (props) => {
Boolean(ctx.handoffContext?.trim()) ||
Boolean(ctx.handoffResources?.length) ||
Boolean(ctx.handoffActions?.length) ||
- Boolean(ctx.handoffMetadata);
+ Boolean(ctx.handoffMetadata) ||
+ Boolean(ctx.preferredWorkflowPromptName?.trim());
sendPromise
.then((ok) => {
if (!ok) {
@@ -3294,6 +3439,78 @@ export const AIChat: Component<AIChatProps> = (props) => {
focusComposer();
};
+ const renderWorkflowStarterIntoComposer = async (
+ starter: AssistantWorkflowStarter,
+ options: { onlyWhenComposerEmpty?: boolean } = {},
+ ) => {
+ if (renderingWorkflowStarterId()) return;
+ if (options.onlyWhenComposerEmpty && input().trim()) return;
+
+ setRenderingWorkflowStarterId(starter.id);
+ try {
+ const rendered = await AIChatAPI.renderWorkflowPrompt({
+ name: starter.name,
+ arguments: starter.arguments,
+ });
+ const starterText = rendered.text.trim();
+ if (!starterText) {
+ notificationStore.warning('Workflow starter returned an empty prompt.', 3000);
+ return;
+ }
+
+ setInput((current) => {
+ const draft = current.trim();
+ if (options.onlyWhenComposerEmpty && draft) return current;
+ return draft ? `${draft}\n\n${starterText}` : starterText;
+ });
+ setSlashCommandActive(false);
+ setSlashCommandQuery('');
+ setMentionActive(false);
+ resetPromptHistoryNavigation();
+ focusComposer();
+ } catch (error) {
+ logger.error('[AIChat] Failed to render workflow starter:', error);
+ const message =
+ error instanceof Error ? error.message : 'Failed to prepare workflow starter.';
+ notificationStore.error(message);
+ } finally {
+ setRenderingWorkflowStarterId('');
+ }
+ };
+
+ const handleWorkflowStarterSelect = async (starter: AssistantWorkflowStarter) => {
+ await renderWorkflowStarterIntoComposer(starter);
+ };
+
+ let autoRenderedWorkflowStarterKey = '';
+ createEffect(() => {
+ const context = aiChatStore.context;
+ const preferredWorkflowPromptName = (context.preferredWorkflowPromptName ?? '').trim();
+ if (!preferredWorkflowPromptName) {
+ autoRenderedWorkflowStarterKey = '';
+ return;
+ }
+
+ const starter = assistantWorkflowStarters().find(
+ (candidate) => candidate.name === preferredWorkflowPromptName,
+ );
+ if (!starter || renderingWorkflowStarterId()) return;
+
+ const starterKey = [
+ starter.name,
+ context.findingId ?? '',
+ context.targetType ?? '',
+ context.targetId ?? '',
+ JSON.stringify(starter.arguments),
+ ].join('|');
+ if (autoRenderedWorkflowStarterKey === starterKey) return;
+
+ autoRenderedWorkflowStarterKey = starterKey;
+ if (input().trim()) return;
+
+ void renderWorkflowStarterIntoComposer(starter, { onlyWhenComposerEmpty: true });
+ });
+
const updateSlashCommandAutocomplete = (value: string, cursorPos: number) => {
const textBeforeCursor = value.slice(0, cursorPos);
const textAfterCursor = value.slice(cursorPos);
@@ -3890,6 +4107,19 @@ export const AIChat: Component<AIChatProps> = (props) => {
chat.updateQuestion(messageId, questionId, { removed: true });
};
+ const workflowStarterIcon = (starter: AssistantWorkflowStarter) => {
+ switch (starter.kind) {
+ case 'resource':
+ return <CpuIcon class="h-3.5 w-3.5" aria-hidden="true" />;
+ case 'finding':
+ return <ShieldAlertIcon class="h-3.5 w-3.5" aria-hidden="true" />;
+ case 'fleet':
+ case 'workflow':
+ default:
+ return <SparklesIcon class="h-3.5 w-3.5" aria-hidden="true" />;
+ }
+ };
+
return (
<>
<Show when={isOpen() && isOverlayLayout()}>
@@ -4709,7 +4939,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
currentStatus() ? 'border-t border-border/70' : ''
}`}
role="status"
- aria-label="Assistant autonomous control warning"
+ aria-label="Assistant chat actions warning"
aria-live="polite"
>
<span
@@ -4717,7 +4947,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
aria-hidden="true"
/>
<span class="min-w-0 flex-1 font-medium leading-4 sm:truncate">
- Autonomous: commands execute without approval.
+ Chat-only actions are allowed.
</span>
<button
type="button"
@@ -4725,7 +4955,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
class="inline-flex shrink-0 items-center rounded-md border border-red-200 bg-surface px-2 py-1 text-[10px] font-medium text-red-700 transition-colors hover:bg-red-50 hover:text-red-900 dark:border-red-800 dark:bg-surface dark:text-red-200 dark:hover:bg-red-950/40"
aria-label={AI_CHAT_SWITCH_TO_APPROVAL_LABEL}
>
- Switch to Approval
+ Switch to Ask first
</button>
<ActionIconButton
onClick={() => setAutonomousBannerDismissed(true)}
@@ -4867,6 +5097,46 @@ export const AIChat: Component<AIChatProps> = (props) => {
</Show>
</div>
</Show>
+ <Show when={assistantWorkflowStarters().length > 0}>
+ <div
+ class="mb-2 flex min-h-7 min-w-0 flex-wrap items-center gap-1.5"
+ aria-label="Assistant workflow starters"
+ data-testid="assistant-workflow-starters"
+ >
+ <For each={assistantWorkflowStarters()}>
+ {(starter) => {
+ const isRendering = () => renderingWorkflowStarterId() === starter.id;
+ const label = () =>
+ starter.description
+ ? `${starter.label}: ${starter.description}`
+ : starter.label;
+ return (
+ <button
+ type="button"
+ onClick={() => {
+ void handleWorkflowStarterSelect(starter);
+ }}
+ disabled={Boolean(renderingWorkflowStarterId())}
+ class="inline-flex h-7 max-w-full items-center gap-1.5 rounded-md border border-border bg-surface-alt px-2 text-[11px] font-medium text-base-content transition-colors hover:border-blue-300 hover:bg-blue-50 disabled:cursor-wait disabled:opacity-60 dark:hover:border-blue-800 dark:hover:bg-blue-950/40"
+ title={label()}
+ aria-label={label()}
+ data-testid={`assistant-workflow-starter-${starter.name}`}
+ >
+ <Show
+ when={isRendering()}
+ fallback={
+ <span class="shrink-0 text-muted">{workflowStarterIcon(starter)}</span>
+ }
+ >
+ <LoaderCircleIcon class="h-3.5 w-3.5 shrink-0 animate-spin text-blue-600 dark:text-blue-300" />
+ </Show>
+ <span class="min-w-0 truncate">{starter.label}</span>
+ </button>
+ );
+ }}
+ </For>
+ </div>
+ </Show>
<form
data-assistant-composer
onSubmit={(e) => {
@@ -4965,6 +5235,28 @@ export const AIChat: Component<AIChatProps> = (props) => {
</div>
)}
</Show>
+ <Show when={assistantSurfaceToolHealth()}>
+ {(health) => (
+ <div
+ role="status"
+ aria-label="Assistant capability availability"
+ aria-live="polite"
+ title={health().title}
+ class={`inline-flex h-7 max-w-[9rem] shrink-0 items-center gap-1.5 rounded-md border px-2 text-[10px] font-medium ${health().className}`}
+ data-testid="assistant-surface-tools-health"
+ >
+ <WrenchIcon
+ class={`h-3 w-3 shrink-0 ${health().iconClassName}`}
+ aria-hidden="true"
+ />
+ <span
+ class={`h-1.5 w-1.5 shrink-0 rounded-full ${health().dotClassName}`}
+ aria-hidden="true"
+ />
+ <span class="min-w-0 truncate">{health().label}</span>
+ </div>
+ )}
+ </Show>
<ActionIconButton
onClick={openAssistantCommandHelp}
tone="outline"
diff --git a/frontend-modern/src/components/AI/Chat/workflowStarters.ts b/frontend-modern/src/components/AI/Chat/workflowStarters.ts
new file mode 100644
index 0000000000..276ad15d17
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/workflowStarters.ts
@@ -0,0 +1,144 @@
+import type { AgentWorkflowPrompt } from '@/api/agentCapabilities';
+import type { AIChatContext } from '@/stores/aiChat';
+
+export type AssistantWorkflowStarterKind = 'fleet' | 'resource' | 'finding' | 'workflow';
+
+export interface AssistantWorkflowStarter {
+ id: string;
+ name: string;
+ label: string;
+ description?: string;
+ kind: AssistantWorkflowStarterKind;
+ arguments: Record<string, string>;
+}
+
+const WORKFLOW_STARTER_KINDS = new Set<AssistantWorkflowStarterKind>([
+ 'fleet',
+ 'resource',
+ 'finding',
+ 'workflow',
+]);
+
+const PATROL_TARGET_TYPES = new Set(['patrol-run', 'patrol-assessment', 'patrol-configuration']);
+
+const normalizeIdentifier = (value: unknown): string => {
+ if (typeof value !== 'string') return '';
+ return value.trim();
+};
+
+const workflowStarterLabel = (prompt: AgentWorkflowPrompt): string => {
+ const label = normalizeIdentifier(prompt.label);
+ if (label) return label;
+
+ const name = normalizeIdentifier(prompt.name);
+ const description = normalizeIdentifier(prompt.description);
+ if (description) return description;
+
+ return name
+ .replace(/^pulse_/, '')
+ .replace(/_/g, ' ')
+ .replace(/\b\w/g, (letter) => letter.toUpperCase());
+};
+
+const workflowStarterKind = (prompt: AgentWorkflowPrompt): AssistantWorkflowStarterKind => {
+ const kind = normalizeIdentifier(prompt.presentationKind);
+ if (WORKFLOW_STARTER_KINDS.has(kind as AssistantWorkflowStarterKind)) {
+ return kind as AssistantWorkflowStarterKind;
+ }
+ return 'workflow';
+};
+
+export const getAssistantWorkflowStarterResourceId = (context: AIChatContext): string => {
+ for (const resource of context.handoffResources ?? []) {
+ const id = normalizeIdentifier(resource.id);
+ if (id) return id;
+ }
+
+ for (const action of context.handoffActions ?? []) {
+ const id = normalizeIdentifier(action.targetResourceId);
+ if (id) return id;
+ }
+
+ const targetId = normalizeIdentifier(context.targetId);
+ const targetType = normalizeIdentifier(context.targetType);
+ if (targetId && !PATROL_TARGET_TYPES.has(targetType)) {
+ return targetId;
+ }
+
+ return '';
+};
+
+export const getAssistantWorkflowStarterFindingId = (context: AIChatContext): string => {
+ const direct = normalizeIdentifier(context.findingId);
+ if (direct) return direct;
+
+ for (const action of context.handoffActions ?? []) {
+ const id = normalizeIdentifier(action.findingId);
+ if (id) return id;
+ }
+
+ return normalizeIdentifier(context.context?.findingId);
+};
+
+const resolveWorkflowStarterArgument = (
+ name: string,
+ context: AIChatContext,
+): string | undefined => {
+ switch (name) {
+ case 'resourceId':
+ return getAssistantWorkflowStarterResourceId(context);
+ case 'finding_id':
+ return getAssistantWorkflowStarterFindingId(context);
+ default:
+ return undefined;
+ }
+};
+
+const buildWorkflowStarterArguments = (
+ prompt: AgentWorkflowPrompt,
+ context: AIChatContext,
+): Record<string, string> | null => {
+ const args: Record<string, string> = {};
+ for (const argument of prompt.arguments ?? []) {
+ const name = normalizeIdentifier(argument.name);
+ if (!name) continue;
+
+ const value = resolveWorkflowStarterArgument(name, context);
+ if (value) {
+ args[name] = value;
+ continue;
+ }
+
+ if (argument.required) return null;
+ }
+ return args;
+};
+
+export const getAssistantWorkflowStarters = (
+ prompts: AgentWorkflowPrompt[],
+ context: AIChatContext,
+): AssistantWorkflowStarter[] => {
+ const starters: AssistantWorkflowStarter[] = [];
+ const seen = new Set<string>();
+
+ for (const prompt of prompts) {
+ const name = normalizeIdentifier(prompt.name);
+ if (!name || seen.has(name)) continue;
+
+ const args = buildWorkflowStarterArguments(prompt, context);
+ if (!args) continue;
+
+ seen.add(name);
+ const description = normalizeIdentifier(prompt.description);
+ starters.push({
+ id: name,
+ name,
+ label: workflowStarterLabel(prompt),
+ description: description || undefined,
+ kind: workflowStarterKind(prompt),
+ arguments: args,
+ });
+ }
+
+ return starters;
+};
diff --git a/frontend-modern/src/components/AI/FindingsPanel.tsx b/frontend-modern/src/components/AI/FindingsPanel.tsx
index 15b36af7ec..e9291ae8fb 100644
--- a/frontend-modern/src/components/AI/FindingsPanel.tsx
+++ b/frontend-modern/src/components/AI/FindingsPanel.tsx
@@ -21,8 +21,9 @@ import { notificationStore } from '@/stores/notifications';
import { aiChatStore } from '@/stores/aiChat';
import {
buildPatrolAssistantApprovalBriefingInput,
- buildPatrolAssistantFindingHandoff,
+ buildPatrolAssistantFindingHandoffFromUnifiedFinding,
buildPatrolAssistantProposedFixBriefingInput,
+ buildPatrolAssistantProposedFixBriefingInputFromApproval,
buildPatrolRemediationPlanAssistantBriefing,
buildPatrolRemediationPlanAssistantModelContext,
patrolAssistantFindingHandoffRequiresApprovalMode,
@@ -30,7 +31,7 @@ import {
type PatrolAssistantProposedFixBriefingInput,
} from '@/features/patrol/patrolInvestigationContextModel';
import { InvestigationSection, ApprovalSection } from '@/components/patrol';
-import { AIAPI, type ApprovalRequest, type RemediationPlan } from '@/api/ai';
+import { AIAPI, type RemediationPlan } from '@/api/ai';
import { createSuppressionRuleFromFinding } from '@/api/patrol';
import type { PatrolRunRecord, PatrolRuntimeState } from '@/api/patrol';
import { formatRelativeTime } from '@/utils/format';
@@ -43,6 +44,8 @@ import { getPatrolFindingsEmptyState } from '@/utils/patrolEmptyStatePresentatio
import CheckCircleIcon from 'lucide-solid/icons/check-circle';
import AlertCircleIcon from 'lucide-solid/icons/alert-circle';
import AlertTriangleIcon from 'lucide-solid/icons/alert-triangle';
+import InfoIcon from 'lucide-solid/icons/info';
+import ChevronDownIcon from 'lucide-solid/icons/chevron-down';
import {
buildFindingFilterOptions,
formatFindingForClipboard,
@@ -52,6 +55,9 @@ import {
formatFindingLoopState,
getFindingActiveRuntimeSortOrder,
getFindingSeverityPresentation,
+ buildPatrolFindingDisplayGroups,
+ getPatrolFindingIssueCountLabel,
+ getFindingPatrolWorkflowPresentation,
getFindingSeveritySortOrder,
getFindingResolutionReason,
getFindingLoopStateBadgeTone,
@@ -95,7 +101,10 @@ interface FindingsPanelProps {
runtimeState?: PatrolRuntimeState;
blockedReason?: string;
overallHealth?: IntelligenceHealthScore;
+ historicalRegressionCount?: number;
+ patrolRuns?: PatrolRunRecord[];
findingsSource?: 'unified' | 'patrol';
+ onAssistantHandoff?: (finding: UnifiedFinding) => void;
runSnapshot?: Pick<
PatrolRunRecord,
| 'resources_checked'
@@ -147,6 +156,33 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
const [dismissedPlanIds, setDismissedPlanIds] = createSignal<string[]>([]);
const isPatrolFindingsSource = createMemo(() => props.findingsSource === 'patrol');
+ const hasUnknownRunSnapshot = createMemo(
+ () => props.runSnapshot !== undefined && props.filterFindingIds === undefined,
+ );
+ const hasEmptyRunSnapshot = createMemo(
+ () =>
+ props.runSnapshot !== undefined &&
+ Array.isArray(props.filterFindingIds) &&
+ props.filterFindingIds.length === 0,
+ );
+ const canRenderRunSnapshotWithoutSourceFindings = createMemo(
+ () => hasUnknownRunSnapshot() || hasEmptyRunSnapshot(),
+ );
+ const shouldShowFindingLifecycle = (finding: UnifiedFinding) =>
+ Boolean(finding.lifecycle && finding.lifecycle.length > 0) &&
+ (!isPatrolFindingsSource() ||
+ finding.status !== 'active' ||
+ props.runSnapshot !== undefined ||
+ filter() === 'all' ||
+ filter() === 'resolved');
+ const shouldShowCollapsedPrimaryAction = (finding: UnifiedFinding) =>
+ isPatrolFindingsSource() &&
+ finding.status === 'active' &&
+ props.runSnapshot === undefined &&
+ expandedId() !== finding.id &&
+ Boolean(getFindingPrimaryActionPresentation(finding));
+ const shouldShowInlineManualControls = (finding: UnifiedFinding) =>
+ finding.status === 'active' && !isPatrolFindingsSource();
const sourceFindings = createMemo(() =>
isPatrolFindingsSource() ? aiIntelligenceStore.patrolFindings : aiIntelligenceStore.findings,
);
@@ -156,7 +192,12 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
? aiIntelligenceStore.patrolFindingsLoading
: aiIntelligenceStore.findingsLoading,
);
- const shouldShowLoadingState = createMemo(() => sourceFindingsLoading() && !sourceHasFindings());
+ const shouldShowLoadingState = createMemo(
+ () =>
+ sourceFindingsLoading() &&
+ !sourceHasFindings() &&
+ !canRenderRunSnapshotWithoutSourceFindings(),
+ );
const sourceFindingsError = createMemo(() =>
isPatrolFindingsSource()
? aiIntelligenceStore.patrolFindingsError
@@ -230,9 +271,6 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
});
// Filter and sort findings
- const hasUnknownRunSnapshot = createMemo(
- () => props.runSnapshot !== undefined && props.filterFindingIds === undefined,
- );
const filteredFindings = createMemo(() => {
if (hasUnknownRunSnapshot()) {
return [];
@@ -381,6 +419,28 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
(f) => f.source !== 'threshold' && !f.isThreshold && !hasTriggeringAlert(f),
);
});
+ const shouldGroupPatrolFindingsByResource = createMemo(
+ () =>
+ isPatrolFindingsSource() &&
+ filter() === 'active' &&
+ props.runSnapshot === undefined &&
+ props.resourceId === undefined,
+ );
+ const patrolFindingDisplayGroups = createMemo(() => {
+ const findings = patrolFindings();
+ if (!shouldGroupPatrolFindingsByResource()) {
+ return findings.map((finding) => ({
+ id: `finding:${finding.id}`,
+ resourceKey: `finding:${finding.id}`,
+ resourceLabel: getFindingSubjectPresentation(finding).label,
+ primaryFinding: finding,
+ relatedFindings: [],
+ findings: [finding],
+ }));
+ }
+
+ return buildPatrolFindingDisplayGroups(findings);
+ });
const filterOptions = createMemo(() => buildFindingFilterOptions(filterCounts()));
const emptyStateCopy = createMemo(() => {
// 'overdue' is a FindingsPanel-local extension to the shared
@@ -395,10 +455,15 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
overallHealth: props.overallHealth,
runtimeState: props.runtimeState,
blockedReason: props.blockedReason,
+ historicalRegressionCount: props.historicalRegressionCount,
+ runs: props.patrolRuns,
runSnapshot: props.runSnapshot,
});
});
const emptyStateTone = createMemo(() => getSemanticTonePresentation(emptyStateCopy().tone));
+ const shouldShowRichEmptyState = createMemo(
+ () => filter() === 'active' || props.runSnapshot !== undefined,
+ );
// Auto-reset filter when the conditional filter buttons disappear
createEffect(() => {
if (filter() === 'attention' && filterCounts().needsAttentionCount === 0) {
@@ -563,20 +628,6 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
setEditingNoteId(null);
};
- const buildLiveApprovalProposedFixBriefing = (
- approval: ApprovalRequest | undefined,
- ): PatrolAssistantProposedFixBriefingInput | undefined =>
- buildPatrolAssistantProposedFixBriefingInput(
- approval
- ? {
- description: approval.context,
- riskLevel: approval.riskLevel,
- targetHost: approval.targetName,
- commandCount: approval.command ? 1 : 0,
- }
- : null,
- );
-
const loadLatestInvestigationProposedFixBriefing = async (
finding: UnifiedFinding,
pendingApprovalBriefing: PatrolAssistantApprovalBriefingInput | undefined,
@@ -610,8 +661,6 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
const openFindingInAssistant = async (finding: UnifiedFinding) => {
await aiIntelligenceStore.loadPendingApprovals();
- const subject = getFindingSubjectPresentation(finding).label;
- const title = getFindingTitlePresentation(finding).label;
const pendingApproval = aiIntelligenceStore.patrolPendingApprovals.find(
(approval) => approval.toolId === 'investigation_fix' && approval.targetId === finding.id,
);
@@ -621,31 +670,14 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
pendingApprovalBriefing,
);
const proposedFix =
- latestInvestigationProposedFix || buildLiveApprovalProposedFixBriefing(pendingApproval);
- const handoff = buildPatrolAssistantFindingHandoff({
- id: finding.id,
- title,
- subject,
- description: finding.description,
- severity: finding.severity,
- findingStatus: finding.status,
- investigationStatus: finding.investigationStatus,
- investigationOutcome: finding.investigationOutcome,
- loopState: finding.loopState,
- timesRaised: finding.timesRaised,
- regressionCount: finding.regressionCount,
- lastRegressionAt: finding.lastRegressionAt,
- remediationId: finding.remediationPlanId,
- resourceId: finding.resourceId,
- resourceName: finding.resourceName,
- resourceType: finding.resourceType,
- detectedAt: finding.detectedAt,
- lastSeenAt: finding.lastSeenAt,
+ latestInvestigationProposedFix ||
+ buildPatrolAssistantProposedFixBriefingInputFromApproval(pendingApproval);
+ const handoff = buildPatrolAssistantFindingHandoffFromUnifiedFinding(finding, {
pendingApproval: pendingApprovalBriefing,
proposedFix,
- investigationRecord: finding.investigationRecord,
});
aiChatStore.open(handoff.context);
+ props.onAssistantHandoff?.(finding);
};
// Create rule from this is the promotion path: take the operator's
@@ -780,12 +812,46 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
};
// Render a single finding item
- const renderFindingItem = (finding: UnifiedFinding, showSourceBadge: boolean = false) => {
+ const renderFindingItem = (
+ finding: UnifiedFinding,
+ showSourceBadge: boolean = false,
+ options: { hideSubject?: boolean; relatedFindings?: readonly UnifiedFinding[] } = {},
+ ) => {
const recency = getFindingRecencyPresentation(finding);
const subject = getFindingSubjectPresentation(finding);
const title = getFindingTitlePresentation(finding);
const manualControls = getFindingManualControlsPresentation(finding);
const severityPresentation = getFindingSeverityPresentation(finding);
+ const rowPrimaryAction = getFindingPrimaryActionPresentation(finding);
+ const patrolWorkflow = () =>
+ getFindingPatrolWorkflowPresentation(finding, aiIntelligenceStore.patrolPendingApprovals);
+ const collapsedApprovalAction = () => {
+ const workflow = patrolWorkflow();
+ return workflow?.stage === 'approval' ? workflow : undefined;
+ };
+ const shouldShowLoopStateBadge = () =>
+ !isPatrolFindingsSource() &&
+ finding.status === 'active' &&
+ finding.source !== 'ai-patrol' &&
+ Boolean(finding.loopState) &&
+ finding.loopState !== 'detected' &&
+ !finding.investigationStatus &&
+ !finding.investigationOutcome;
+ const shouldShowInvestigationStatusBadge = () =>
+ !isPatrolFindingsSource() &&
+ Boolean(finding.investigationStatus) &&
+ !(
+ finding.investigationOutcome &&
+ finding.investigationStatus !== 'running' &&
+ finding.investigationStatus !== 'pending'
+ );
+ const shouldShowInvestigationOutcomeBadge = () =>
+ !isPatrolFindingsSource() &&
+ Boolean(finding.investigationOutcome) &&
+ finding.investigationStatus !== 'running' &&
+ finding.investigationStatus !== 'pending';
+ const shouldShowInvestigationConfidenceBadge = () =>
+ !isPatrolFindingsSource() && Boolean(finding.investigationRecord?.confidence);
const toggleExpanded = () => {
if (expandedId() === finding.id) {
@@ -809,12 +875,20 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
>
{/* Finding header */}
<div class="flex items-start justify-between gap-2">
- <button
- type="button"
+ <div
+ role="button"
+ tabIndex={0}
+ aria-label={`${expandedId() === finding.id ? 'Close issue details' : 'Open issue details'} for ${title.label}`}
aria-expanded={expandedId() === finding.id}
aria-controls={`finding-${finding.id}-details`}
- class="min-w-0 flex-1 cursor-pointer text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/40"
onClick={toggleExpanded}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ toggleExpanded();
+ }
+ }}
+ class="min-w-0 flex-1 cursor-pointer rounded text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/40"
>
<div class="flex items-center gap-2 flex-wrap">
{/* Status badge for non-active findings */}
@@ -862,19 +936,11 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
Acknowledged
</MetadataBadge>
</Show>
- <Show
- when={
- finding.status === 'active' &&
- finding.loopState &&
- !(finding.acknowledgedAt && finding.loopState === 'detected') &&
- !finding.investigationStatus &&
- !finding.investigationOutcome
- }
- >
+ <Show when={shouldShowLoopStateBadge()}>
<MetadataBadge
{...FINDING_ROW_BADGE_PROPS}
tone={getFindingLoopStateBadgeTone(finding.loopState!)}
- title={`Patrol loop: ${formatFindingLoopState(finding.loopState!)}`}
+ title={`Patrol status: ${formatFindingLoopState(finding.loopState!)}`}
>
{formatFindingLoopState(finding.loopState!)}
</MetadataBadge>
@@ -888,17 +954,8 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
Out of scope
</MetadataBadge>
</Show>
- {/* Investigation status badge — only when no outcome badge will show */}
- <Show
- when={
- finding.investigationStatus &&
- !(
- finding.investigationOutcome &&
- finding.investigationStatus !== 'running' &&
- finding.investigationStatus !== 'pending'
- )
- }
- >
+ {/* Non-Patrol investigation status badge — only when no outcome badge will show. */}
+ <Show when={shouldShowInvestigationStatusBadge()}>
<MetadataBadge
{...FINDING_ROW_BADGE_PROPS}
tone={getInvestigationStatusBadgeTone(finding.investigationStatus!)}
@@ -920,14 +977,8 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
{getInvestigationStatusLabel(finding.investigationStatus!)}
</MetadataBadge>
</Show>
- {/* Investigation outcome badge — replaces status badge when outcome is known */}
- <Show
- when={
- finding.investigationOutcome &&
- finding.investigationStatus !== 'running' &&
- finding.investigationStatus !== 'pending'
- }
- >
+ {/* Non-Patrol investigation outcome badge — replaces status badge when known. */}
+ <Show when={shouldShowInvestigationOutcomeBadge()}>
<MetadataBadge
{...FINDING_ROW_BADGE_PROPS}
tone={getInvestigationOutcomeBadgeTone(finding.investigationOutcome!)}
@@ -935,13 +986,14 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
{getInvestigationOutcomeLabel(finding.investigationOutcome!)}
</MetadataBadge>
</Show>
- {/* Investigation confidence badge — surfaces the seven-question
- schema's confidence answer in the collapsed row so operators
- can scan trust without expanding the card. */}
- <Show when={finding.investigationRecord?.confidence}>
+ {/* Non-Patrol confidence badge. Patrol keeps investigation detail
+ in the expanded issue so the default row stays simple. */}
+ <Show when={shouldShowInvestigationConfidenceBadge()}>
<MetadataBadge
{...FINDING_ROW_BADGE_PROPS}
- tone={getInvestigationConfidenceBadgeTone(finding.investigationRecord!.confidence!)}
+ tone={getInvestigationConfidenceBadgeTone(
+ finding.investigationRecord!.confidence!,
+ )}
title={`Investigation confidence: ${finding.investigationRecord!.confidence!}`}
>
{finding.investigationRecord!.confidence!} confidence
@@ -972,7 +1024,16 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</div>
{/* Resource info */}
<div class="text-xs text-muted mt-1">
- {subject.label} - {recency.label} {formatTime(recency.timestamp)}
+ <Show
+ when={options.hideSubject}
+ fallback={
+ <>
+ {subject.label} - {recency.label} {formatTime(recency.timestamp)}
+ </>
+ }
+ >
+ {recency.label} {formatTime(recency.timestamp)}
+ </Show>
<Show when={finding.status === 'resolved' && finding.resolvedAt}>
<span class="ml-2 text-green-600 dark:text-green-400">
{' · '}
@@ -1029,10 +1090,33 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</span>
</Show>
</div>
- </button>
+ </div>
{/* Actions */}
<div class="flex items-center gap-1 shrink-0">
- <Show when={finding.status === 'active'}>
+ <Show when={expandedId() !== finding.id ? collapsedApprovalAction() : undefined}>
+ {(action) => (
+ <button
+ type="button"
+ onClick={toggleExpanded}
+ class="rounded bg-amber-600 px-2 py-1 text-xs font-semibold text-white transition-colors hover:bg-amber-700"
+ title={action().detail}
+ >
+ {action().label}
+ </button>
+ )}
+ </Show>
+ <Show when={shouldShowCollapsedPrimaryAction(finding) && rowPrimaryAction}>
+ {(action) => (
+ <a
+ href={action().href}
+ onClick={(e) => e.stopPropagation()}
+ class="inline-flex items-center rounded bg-blue-600 px-2 py-1 text-xs font-semibold text-white transition-colors hover:bg-blue-700"
+ >
+ {action().label}
+ </a>
+ )}
+ </Show>
+ <Show when={shouldShowInlineManualControls(finding)}>
<Show when={manualControls.acknowledge && !finding.acknowledgedAt}>
<button
type="button"
@@ -1088,51 +1172,47 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</button>
</Show>
</Show>
- {/* Expand indicator */}
- <svg
- class={`w-4 h-4 text-slate-400 transition-transform ${expandedId() === finding.id ? 'rotate-180' : ''}`}
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
+ <button
+ type="button"
+ aria-label={`${expandedId() === finding.id ? 'Hide' : 'View'} details for ${title.label}`}
+ aria-expanded={expandedId() === finding.id}
+ aria-controls={`finding-${finding.id}-details`}
+ onClick={toggleExpanded}
+ class="inline-flex items-center gap-1 rounded border border-border bg-surface px-2 py-1 text-xs font-medium text-muted transition-colors hover:bg-surface-hover hover:text-base-content focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/40"
+ title={expandedId() === finding.id ? 'Hide details' : 'View details'}
>
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M19 9l-7 7-7-7"
+ <span>{expandedId() === finding.id ? 'Hide' : 'Details'}</span>
+ <ChevronDownIcon
+ class={`h-3.5 w-3.5 transition-transform ${expandedId() === finding.id ? 'rotate-180' : ''}`}
/>
- </svg>
+ </button>
</div>
</div>
{/* Expanded content */}
- <Show when={expandedId() === finding.id}>
- {renderExpandedContent(finding)}
- </Show>
+ <Show when={expandedId() === finding.id}>{renderExpandedContent(finding, options)}</Show>
</div>
);
};
// Render expanded content for a finding
- const renderExpandedContent = (finding: UnifiedFinding) => {
+ const renderExpandedContent = (
+ finding: UnifiedFinding,
+ options: { relatedFindings?: readonly UnifiedFinding[] } = {},
+ ) => {
const primaryAction = getFindingPrimaryActionPresentation(finding);
const manualControls = getFindingManualControlsPresentation(finding);
+ const relatedFindings = options.relatedFindings ?? [];
+ const shouldShowAssistantPrimaryAction = !isPatrolFindingsSource();
+ const shouldShowAssistantManageAction = isPatrolFindingsSource() && !primaryAction;
+ const shouldShowExpandedManageMenu =
+ !primaryAction ||
+ manualControls.acknowledge ||
+ manualControls.snooze ||
+ manualControls.dismiss;
return (
<div id={`finding-${finding.id}-details`} class="mt-3 pt-3 border-t border-border-subtle">
- <Show when={primaryAction}>
- {(action) => (
- <div class="mb-3">
- <a
- href={action().href}
- onClick={(e) => e.stopPropagation()}
- class="inline-flex items-center rounded border border-border bg-surface px-2.5 py-1.5 text-xs font-semibold text-base-content transition-colors hover:bg-surface-hover"
- >
- {action().label}
- </a>
- </div>
- )}
- </Show>
<Show when={hasTriggeringAlert(finding)}>
<div class="text-xs text-amber-700 dark:text-amber-300 mb-2">
Triggered by alert{finding.alertType ? ` (${finding.alertType})` : ''} • Identifier{' '}
@@ -1163,7 +1243,37 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</p>
</Show>
- <Show when={finding.lifecycle && finding.lifecycle.length > 0}>
+ <Show when={relatedFindings.length > 0}>
+ <div class="mt-3 rounded border border-border bg-surface-alt p-2">
+ <div class="text-xs font-medium text-base-content">Related issues</div>
+ <div class="mt-2 space-y-1">
+ <For each={relatedFindings}>
+ {(relatedFinding) => {
+ const relatedSeverity = getFindingSeverityPresentation(relatedFinding);
+ const relatedTitle = getFindingTitlePresentation(relatedFinding);
+ const relatedRecency = getFindingRecencyPresentation(relatedFinding);
+ return (
+ <div class="flex flex-wrap items-center gap-2 text-xs text-muted">
+ <MetadataBadge
+ {...FINDING_ROW_BADGE_PROPS}
+ tone={relatedSeverity.badgeTone}
+ uppercase={relatedSeverity.uppercase}
+ >
+ {relatedSeverity.label}
+ </MetadataBadge>
+ <span class="font-medium text-base-content">{relatedTitle.label}</span>
+ <span>
+ {relatedRecency.label} {formatTime(relatedRecency.timestamp)}
+ </span>
+ </div>
+ );
+ }}
+ </For>
+ </div>
+ </div>
+ </Show>
+
+ <Show when={shouldShowFindingLifecycle(finding)}>
<div class="mt-3 p-2 rounded border border-border bg-surface-alt">
<div class="text-xs font-medium text-base-content mb-2">Lifecycle</div>
<div class="space-y-1">
@@ -1277,139 +1387,167 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
class="mt-3 flex flex-wrap items-start gap-2 text-xs"
onClick={(e) => e.stopPropagation()}
>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- void openFindingInAssistant(finding);
- }}
- class="inline-flex items-center gap-1 rounded bg-blue-600 px-3 py-1.5 font-semibold text-white transition-colors hover:bg-blue-700"
- title={getPrimaryAssistantFindingAction(finding).title}
- >
- <svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
- />
- </svg>
- {getPrimaryAssistantFindingAction(finding).label}
- </button>
-
- <details onClick={(e) => e.stopPropagation()}>
- <summary class="list-none cursor-pointer rounded border border-border bg-surface px-3 py-1.5 font-medium text-base-content hover:bg-surface-hover">
- Manage
- </summary>
- <div class="mt-1 flex min-w-48 flex-col gap-1 rounded border border-border bg-surface p-1 shadow-sm">
- <Show when={editingNoteId() !== finding.id && !finding.userNote}>
- <button
- type="button"
- onClick={(e) => handleStartEditNote(finding, e)}
- class="rounded px-2 py-1 text-left hover:bg-surface-hover"
- >
- Add Note
- </button>
- </Show>
- <button
- type="button"
- onClick={(e) => handleCopyFindingSummary(finding, e)}
- class="rounded px-2 py-1 text-left hover:bg-surface-hover"
+ <Show when={primaryAction}>
+ {(action) => (
+ <a
+ href={action().href}
+ onClick={(e) => e.stopPropagation()}
+ class="inline-flex items-center gap-1 rounded bg-blue-600 px-3 py-1.5 font-semibold text-white transition-colors hover:bg-blue-700"
>
- Copy summary
- </button>
- <Show when={finding.status === 'active'}>
- <Show when={manualControls.acknowledge && !finding.acknowledgedAt}>
+ {action().label}
+ </a>
+ )}
+ </Show>
+ <Show when={!primaryAction && shouldShowAssistantPrimaryAction}>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ void openFindingInAssistant(finding);
+ }}
+ class="inline-flex items-center gap-1 rounded bg-blue-600 px-3 py-1.5 font-semibold text-white transition-colors hover:bg-blue-700"
+ title={getPrimaryAssistantFindingAction(finding).title}
+ >
+ <svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
+ />
+ </svg>
+ {getPrimaryAssistantFindingAction(finding).label}
+ </button>
+ </Show>
+
+ <Show when={shouldShowExpandedManageMenu}>
+ <details onClick={(e) => e.stopPropagation()}>
+ <summary class="list-none cursor-pointer rounded border border-border bg-surface px-3 py-1.5 font-medium text-base-content hover:bg-surface-hover">
+ Manage
+ </summary>
+ <div class="mt-1 flex min-w-48 flex-col gap-1 rounded border border-border bg-surface p-1 shadow-sm">
+ <Show when={shouldShowAssistantManageAction}>
<button
type="button"
- onClick={(e) => handleAcknowledge(finding, e)}
- class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
- disabled={actionLoading() === finding.id}
+ onClick={(e) => {
+ e.stopPropagation();
+ void openFindingInAssistant(finding);
+ }}
+ class="rounded px-2 py-1 text-left hover:bg-surface-hover"
+ title={getPrimaryAssistantFindingAction(finding).title}
>
- Acknowledge
+ {getPrimaryAssistantFindingAction(finding).label}
</button>
</Show>
- <Show when={manualControls.acknowledge}>
+ <Show when={editingNoteId() !== finding.id && !finding.userNote}>
<button
type="button"
- onClick={(e) => handleResolve(finding, e)}
- class="rounded px-2 py-1 text-left text-emerald-700 hover:bg-emerald-50 disabled:opacity-50 dark:text-emerald-300 dark:hover:bg-emerald-900"
- disabled={actionLoading() === finding.id}
+ onClick={(e) => handleStartEditNote(finding, e)}
+ class="rounded px-2 py-1 text-left hover:bg-surface-hover"
>
- Mark resolved
+ Add Note
</button>
</Show>
- <Show when={manualControls.snooze}>
- <button
- type="button"
- onClick={(e) => handleSnooze(finding, 1, e)}
- class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
- disabled={actionLoading() === finding.id}
- >
- Snooze 1h
- </button>
- <button
- type="button"
- onClick={(e) => handleSnooze(finding, 24, e)}
- class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
- disabled={actionLoading() === finding.id}
- >
- Snooze 24h
- </button>
- <button
- type="button"
- onClick={(e) => handleSnooze(finding, 168, e)}
- class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
- disabled={actionLoading() === finding.id}
- >
- Snooze 7d
- </button>
- </Show>
- <Show when={manualControls.dismiss}>
- <button
- type="button"
- onClick={(e) => handleStartDismiss(finding, 'not_an_issue', e)}
- class="rounded px-2 py-1 text-left text-red-600 hover:bg-red-50 disabled:opacity-50 dark:text-red-400 dark:hover:bg-red-900"
- disabled={actionLoading() === finding.id}
- >
- Dismiss: Not an issue
- </button>
- <button
- type="button"
- onClick={(e) => handleStartDismiss(finding, 'expected_behavior', e)}
- class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
- disabled={actionLoading() === finding.id}
- >
- Remember as expected
- </button>
- <button
- type="button"
- onClick={(e) => handleStartDismiss(finding, 'will_fix_later', e)}
- class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
- disabled={actionLoading() === finding.id}
- >
- Dismiss: Later
- </button>
- <button
- type="button"
- onClick={(e) => handleStartCreateRule(finding, e)}
- class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
- disabled={
- actionLoading() === finding.id ||
- !getFindingSuppressionRuleScope(finding).canCreate
- }
- title={
- getFindingSuppressionRuleScope(finding).canCreate
- ? 'Promote this dismissal into a permanent rule for this resource and category'
- : 'This finding is missing the resource or category needed for a scoped rule'
- }
- >
- Create rule from this
- </button>
+ <button
+ type="button"
+ onClick={(e) => handleCopyFindingSummary(finding, e)}
+ class="rounded px-2 py-1 text-left hover:bg-surface-hover"
+ >
+ Copy summary
+ </button>
+ <Show when={finding.status === 'active'}>
+ <Show when={manualControls.acknowledge && !finding.acknowledgedAt}>
+ <button
+ type="button"
+ onClick={(e) => handleAcknowledge(finding, e)}
+ class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
+ disabled={actionLoading() === finding.id}
+ >
+ Acknowledge
+ </button>
+ </Show>
+ <Show when={manualControls.acknowledge}>
+ <button
+ type="button"
+ onClick={(e) => handleResolve(finding, e)}
+ class="rounded px-2 py-1 text-left text-emerald-700 hover:bg-emerald-50 disabled:opacity-50 dark:text-emerald-300 dark:hover:bg-emerald-900"
+ disabled={actionLoading() === finding.id}
+ >
+ Mark resolved
+ </button>
+ </Show>
+ <Show when={manualControls.snooze}>
+ <button
+ type="button"
+ onClick={(e) => handleSnooze(finding, 1, e)}
+ class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
+ disabled={actionLoading() === finding.id}
+ >
+ Snooze 1h
+ </button>
+ <button
+ type="button"
+ onClick={(e) => handleSnooze(finding, 24, e)}
+ class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
+ disabled={actionLoading() === finding.id}
+ >
+ Snooze 24h
+ </button>
+ <button
+ type="button"
+ onClick={(e) => handleSnooze(finding, 168, e)}
+ class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
+ disabled={actionLoading() === finding.id}
+ >
+ Snooze 7d
+ </button>
+ </Show>
+ <Show when={manualControls.dismiss}>
+ <button
+ type="button"
+ onClick={(e) => handleStartDismiss(finding, 'not_an_issue', e)}
+ class="rounded px-2 py-1 text-left text-red-600 hover:bg-red-50 disabled:opacity-50 dark:text-red-400 dark:hover:bg-red-900"
+ disabled={actionLoading() === finding.id}
+ >
+ Dismiss: Not an issue
+ </button>
+ <button
+ type="button"
+ onClick={(e) => handleStartDismiss(finding, 'expected_behavior', e)}
+ class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
+ disabled={actionLoading() === finding.id}
+ >
+ Remember as expected
+ </button>
+ <button
+ type="button"
+ onClick={(e) => handleStartDismiss(finding, 'will_fix_later', e)}
+ class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
+ disabled={actionLoading() === finding.id}
+ >
+ Dismiss: Later
+ </button>
+ <button
+ type="button"
+ onClick={(e) => handleStartCreateRule(finding, e)}
+ class="rounded px-2 py-1 text-left hover:bg-surface-hover disabled:opacity-50"
+ disabled={
+ actionLoading() === finding.id ||
+ !getFindingSuppressionRuleScope(finding).canCreate
+ }
+ title={
+ getFindingSuppressionRuleScope(finding).canCreate
+ ? 'Promote this dismissal into a permanent rule for this resource and category'
+ : 'This finding is missing the resource or category needed for a scoped rule'
+ }
+ >
+ Create rule from this
+ </button>
+ </Show>
</Show>
- </Show>
- </div>
- </details>
+ </div>
+ </details>
+ </Show>
</div>
{/* Inline create-rule confirmation. Confirms scope (resource +
category) and requires a reason so the persisted rule has
@@ -1560,6 +1698,7 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
(finding.investigationOutcome === 'fix_queued' ||
finding.investigationOutcome === 'fix_executed' ||
finding.investigationOutcome === 'fix_failed' ||
+ finding.investigationOutcome === 'fix_rejected' ||
finding.investigationOutcome === 'fix_verified' ||
finding.investigationOutcome === 'fix_verification_failed' ||
finding.investigationOutcome === 'fix_verification_unknown')
@@ -1646,7 +1785,7 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</button>
</Show>
</div>
- <Show when={patrolFindings().length > 1}>
+ <Show when={patrolFindingDisplayGroups().length > 1}>
<FormSelect
label="Sort findings"
labelClass="sr-only"
@@ -1678,9 +1817,9 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
<Card padding="none" class="overflow-hidden">
{/* Content */}
<div class="divide-y divide-border-subtle">
- <Show when={patrolFindings().length === 0}>
+ <Show when={patrolFindingDisplayGroups().length === 0}>
<div class="p-6 text-sm text-muted text-center">
- <Show when={filter() === 'active'}>
+ <Show when={shouldShowRichEmptyState()}>
<div class="flex flex-col items-center gap-3">
<Show
when={emptyStateCopy().tone === 'success'}
@@ -1691,9 +1830,7 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
<Show
when={emptyStateCopy().tone === 'warning'}
fallback={
- <AlertCircleIcon
- class={`w-10 h-10 ${emptyStateTone().iconClass}`}
- />
+ <InfoIcon class={`w-10 h-10 ${emptyStateTone().iconClass}`} />
}
>
<AlertTriangleIcon
@@ -1724,14 +1861,38 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
filter() !== 'active' &&
filter() !== 'attention' &&
filter() !== 'approvals' &&
- filter() !== 'overdue'
+ filter() !== 'overdue' &&
+ props.runSnapshot === undefined
}
>
{emptyStateCopy().title}
</Show>
</div>
</Show>
- <For each={patrolFindings()}>{(finding) => renderFindingItem(finding, false)}</For>
+ <For each={patrolFindingDisplayGroups()}>
+ {(group) => (
+ <Show
+ when={group.findings.length > 1}
+ fallback={renderFindingItem(group.primaryFinding, false)}
+ >
+ <section
+ class="divide-y divide-border-subtle"
+ aria-label={`${group.resourceLabel}: ${getPatrolFindingIssueCountLabel(group.findings.length)}`}
+ >
+ <div class="flex flex-wrap items-center justify-between gap-2 bg-surface-alt/60 px-3 py-2 text-xs">
+ <span class="font-semibold text-base-content">{group.resourceLabel}</span>
+ <span class="text-muted">
+ {getPatrolFindingIssueCountLabel(group.findings.length)}
+ </span>
+ </div>
+ {renderFindingItem(group.primaryFinding, false, {
+ hideSubject: true,
+ relatedFindings: group.relatedFindings,
+ })}
+ </section>
+ </Show>
+ )}
+ </For>
</div>
</Card>
</Show>
diff --git a/frontend-modern/src/components/AI/__tests__/AICostDashboard.test.tsx b/frontend-modern/src/components/AI/__tests__/AICostDashboard.test.tsx
index 07f814b6c8..5deef8e438 100644
--- a/frontend-modern/src/components/AI/__tests__/AICostDashboard.test.tsx
+++ b/frontend-modern/src/components/AI/__tests__/AICostDashboard.test.tsx
@@ -432,8 +432,8 @@ describe('AICostDashboard', () => {
baseSummary({
targets: [
{
- target_type: 'vm',
- target_id: '100',
+ target_type: 'assistant_session_title',
+ target_id: '7f5941d9-a503-416d-b84e-5a46c9e1e11f',
calls: 5,
input_tokens: 10000,
output_tokens: 2000,
@@ -446,9 +446,11 @@ describe('AICostDashboard', () => {
);
renderDashboard();
await waitFor(() => {
- expect(screen.getByText('Top targets')).toBeInTheDocument();
+ expect(screen.getByText('Usage by task')).toBeInTheDocument();
});
- expect(screen.getByText('vm:100')).toBeInTheDocument();
+ expect(screen.getByText('Assistant sessions')).toBeInTheDocument();
+ expect(screen.queryByText(/assistant_session_title/)).not.toBeInTheDocument();
+ expect(screen.queryByText(/7f5941d9/)).not.toBeInTheDocument();
expect(screen.getByText('12,000')).toBeInTheDocument();
});
@@ -457,7 +459,7 @@ describe('AICostDashboard', () => {
await waitFor(() => {
expect(screen.getByText('Estimated spend')).toBeInTheDocument();
});
- expect(screen.queryByText('Top targets')).not.toBeInTheDocument();
+ expect(screen.queryByText('Usage by task')).not.toBeInTheDocument();
});
// ---- error states ----
diff --git a/frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx b/frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx
index 6c9d510d77..3329ea44bf 100644
--- a/frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx
+++ b/frontend-modern/src/components/AI/__tests__/FindingsPanel.links.test.tsx
@@ -46,7 +46,7 @@ const mockState = vi.hoisted(() => {
status: 'active',
},
];
- const patrolFindings = [
+ const patrolFindings: Array<Record<string, unknown>> = [
{
id: 'finding-provider-issue',
source: 'ai-patrol',
@@ -58,6 +58,7 @@ const mockState = vi.hoisted(() => {
severity: 'warning',
title: 'Provider connection issue',
description: 'Pulse Patrol could not complete provider analysis.',
+ impact: 'Patrol cannot analyze infrastructure until provider setup is fixed.',
detectedAt: '2026-03-30T11:00:00Z',
lastSeenAt: '2026-03-30T11:05:00Z',
status: 'active',
@@ -65,12 +66,20 @@ const mockState = vi.hoisted(() => {
];
return {
+ initialFindings: findings,
+ initialPatrolFindings: patrolFindings,
findings,
findingsError: null as string | null,
findingsLoading: false,
patrolFindings,
patrolFindingsError: null as string | null,
patrolFindingsLoading: false,
+ patrolPendingApprovals: [] as Array<{
+ status: string;
+ toolId: string;
+ targetId: string;
+ expiresAt?: string;
+ }>,
getResource,
getRemediationPlans,
loadFindings,
@@ -165,6 +174,9 @@ vi.mock('@/stores/aiIntelligence', () => ({
get patrolPendingApprovalCount() {
return 0;
},
+ get patrolPendingApprovals() {
+ return mockState.patrolPendingApprovals;
+ },
get remediationPlans() {
return [];
},
@@ -178,6 +190,8 @@ vi.mock('@/stores/aiIntelligence', () => ({
describe('FindingsPanel resource links', () => {
beforeEach(() => {
+ mockState.findings = [...mockState.initialFindings];
+ mockState.patrolFindings = [...mockState.initialPatrolFindings];
mockState.loadFindings.mockClear();
mockState.loadPatrolFindings.mockClear();
mockState.getRemediationPlans.mockClear();
@@ -186,6 +200,7 @@ describe('FindingsPanel resource links', () => {
mockState.findingsError = null;
mockState.patrolFindingsLoading = false;
mockState.patrolFindingsError = null;
+ mockState.patrolPendingApprovals = [];
if (typeof window.requestAnimationFrame !== 'function') {
window.requestAnimationFrame = ((callback: FrameRequestCallback) =>
@@ -201,7 +216,11 @@ describe('FindingsPanel resource links', () => {
await waitFor(() => expect(mockState.loadFindings).toHaveBeenCalled());
- fireEvent.click(screen.getByText('Nextcloud failed readiness checks'));
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: 'View details for Nextcloud failed readiness checks',
+ }),
+ );
expect(
screen.getByText('Nextcloud is unreachable for users until readiness recovers.'),
@@ -212,9 +231,50 @@ describe('FindingsPanel resource links', () => {
expect(
screen.queryByRole('link', { name: 'Open related infrastructure for Nextcloud' }),
).toBeNull();
- expect(
- screen.queryByRole('link', { name: 'Open related workloads for Nextcloud' }),
- ).toBeNull();
+ expect(screen.queryByRole('link', { name: 'Open related workloads for Nextcloud' })).toBeNull();
+ });
+
+ it('keeps Patrol runtime setup findings primary-action-only when expanded', async () => {
+ mockState.patrolFindings = [
+ {
+ id: 'finding-provider-runtime',
+ source: 'ai-patrol',
+ resourceId: 'ai-service',
+ resourceName: 'Pulse Patrol Service',
+ resourceType: 'service',
+ alertIdentifier: 'ai-service::patrol/runtime',
+ category: 'runtime',
+ severity: 'warning',
+ title: 'Pulse Patrol: Provider billing or quota issue',
+ description: 'Pulse Patrol could not maintain a healthy provider connection.',
+ impact: 'Patrol cannot analyze infrastructure until provider setup is fixed.',
+ detectedAt: '2026-03-30T11:00:00Z',
+ lastSeenAt: '2026-03-30T11:05:00Z',
+ status: 'active',
+ },
+ ];
+
+ render(() => <FindingsPanel findingsSource="patrol" />);
+
+ await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
+
+ expect(screen.getByRole('link', { name: 'Open Provider & Models' })).toHaveAttribute(
+ 'href',
+ '/settings/pulse-intelligence/provider',
+ );
+
+ fireEvent.click(
+ screen.getByRole('button', {
+ name: 'View details for Provider billing or quota issue',
+ }),
+ );
+
+ expect(screen.getByRole('link', { name: 'Open Provider & Models' })).toHaveAttribute(
+ 'href',
+ '/settings/pulse-intelligence/provider',
+ );
+ expect(screen.queryByRole('button', { name: 'Open in Assistant' })).not.toBeInTheDocument();
+ expect(screen.queryByText('Manage')).not.toBeInTheDocument();
});
it('keeps finding disclosure separate from inline manual controls', async () => {
@@ -223,7 +283,7 @@ describe('FindingsPanel resource links', () => {
await waitFor(() => expect(mockState.loadFindings).toHaveBeenCalled());
const disclosure = screen.getByRole('button', {
- name: /Nextcloud failed readiness checks/,
+ name: 'View details for Nextcloud failed readiness checks',
});
const acknowledge = screen.getByRole('button', { name: 'Acknowledge' });
@@ -236,6 +296,243 @@ describe('FindingsPanel resource links', () => {
).toBeInTheDocument();
});
+ it('keeps Patrol queue rows free of inline triage controls until expanded', async () => {
+ render(() => <FindingsPanel findingsSource="patrol" />);
+
+ await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
+
+ const disclosure = screen.getByRole('button', {
+ name: 'View details for Provider connection issue',
+ });
+
+ expect(
+ screen.getAllByRole('button', {
+ name: 'View details for Provider connection issue',
+ }),
+ ).toHaveLength(1);
+ expect(disclosure).toHaveTextContent('Details');
+ expect(screen.queryByRole('button', { name: 'Acknowledge' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Snooze 24h' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Dismiss' })).not.toBeInTheDocument();
+
+ fireEvent.click(disclosure);
+
+ expect(
+ screen.getByRole('button', {
+ name: 'Hide details for Provider connection issue',
+ }),
+ ).toHaveTextContent('Hide');
+ expect(screen.getByText('Manage')).toBeInTheDocument();
+ const assistantHandoff = screen.getByRole('button', { name: 'Open in Assistant' });
+ expect(assistantHandoff.closest('details')).not.toBeNull();
+ expect(screen.getByRole('button', { name: 'Acknowledge' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Snooze 24h' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Dismiss: Later' })).toBeInTheDocument();
+ });
+
+ it('keeps default Patrol workflow states out of collapsed issue badges', async () => {
+ mockState.patrolFindings = [
+ {
+ id: 'finding-default-workflow',
+ source: 'ai-patrol',
+ resourceId: 'vm-101',
+ resourceName: 'database-01',
+ resourceType: 'vm',
+ category: 'reliability',
+ severity: 'warning',
+ title: 'Database latency spike',
+ description: 'Patrol saw the database latency threshold trip.',
+ impact: 'Database-backed apps may respond slowly.',
+ detectedAt: '2026-03-30T11:00:00Z',
+ lastSeenAt: '2026-03-30T11:05:00Z',
+ status: 'active',
+ loopState: 'detected',
+ },
+ ];
+
+ render(() => <FindingsPanel findingsSource="patrol" />);
+
+ await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
+
+ expect(screen.getByText('warning')).toBeInTheDocument();
+ expect(screen.getByText('Database latency spike')).toBeInTheDocument();
+ expect(screen.queryByText('detected')).not.toBeInTheDocument();
+ expect(screen.queryByText('Review finding')).not.toBeInTheDocument();
+ });
+
+ it('keeps Patrol process states out of collapsed issue badges', async () => {
+ mockState.patrolFindings = [
+ {
+ id: 'finding-investigating',
+ source: 'ai-patrol',
+ resourceId: 'vm-101',
+ resourceName: 'database-01',
+ resourceType: 'vm',
+ category: 'reliability',
+ severity: 'warning',
+ title: 'Database latency spike',
+ description: 'Patrol saw the database latency threshold trip.',
+ impact: 'Database-backed apps may respond slowly.',
+ detectedAt: '2026-03-30T11:00:00Z',
+ lastSeenAt: '2026-03-30T11:05:00Z',
+ status: 'active',
+ loopState: 'investigating',
+ investigationStatus: 'running',
+ },
+ {
+ id: 'finding-verifying',
+ source: 'ai-patrol',
+ resourceId: 'vm-102',
+ resourceName: 'web-01',
+ resourceType: 'vm',
+ category: 'availability',
+ severity: 'warning',
+ title: 'Web service restart loop',
+ description: 'Patrol saw repeated restarts.',
+ detectedAt: '2026-03-30T11:01:00Z',
+ lastSeenAt: '2026-03-30T11:06:00Z',
+ status: 'active',
+ investigationOutcome: 'fix_executed',
+ },
+ ];
+
+ render(() => <FindingsPanel findingsSource="patrol" />);
+
+ await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
+
+ expect(screen.getByText('Database latency spike')).toBeInTheDocument();
+ expect(screen.getByText('Web service restart loop')).toBeInTheDocument();
+ expect(screen.queryByText('Patrol investigating')).not.toBeInTheDocument();
+ expect(screen.queryByText('Verify outcome')).not.toBeInTheDocument();
+ expect(screen.queryByText('Review finding')).not.toBeInTheDocument();
+ });
+
+ it('shows pending Patrol approval as the user decision, not as a process badge', async () => {
+ mockState.patrolFindings = [
+ {
+ id: 'finding-approval',
+ source: 'ai-patrol',
+ resourceId: 'vm-103',
+ resourceName: 'worker-01',
+ resourceType: 'vm',
+ category: 'availability',
+ severity: 'critical',
+ title: 'Worker disk is full',
+ description: 'Patrol found the worker disk is full.',
+ detectedAt: '2026-03-30T11:02:00Z',
+ lastSeenAt: '2026-03-30T11:07:00Z',
+ status: 'active',
+ investigationOutcome: 'fix_queued',
+ },
+ ];
+ mockState.patrolPendingApprovals = [
+ {
+ status: 'pending',
+ toolId: 'investigation_fix',
+ targetId: 'finding-approval',
+ expiresAt: '2999-01-01T00:00:00Z',
+ },
+ ];
+
+ render(() => <FindingsPanel findingsSource="patrol" />);
+
+ await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
+
+ const approvalAction = screen.getByRole('button', { name: 'Approve or reject' });
+ expect(approvalAction).toBeInTheDocument();
+ expect(screen.queryByText('Review finding')).not.toBeInTheDocument();
+
+ fireEvent.click(approvalAction);
+
+ expect(
+ screen.getByRole('button', {
+ name: 'Hide details for Worker disk is full',
+ }),
+ ).toHaveTextContent('Hide');
+ });
+
+ it('keeps selected Patrol run issue rows simple and expandable', async () => {
+ mockState.patrolFindings = [
+ {
+ id: 'finding-array-parity',
+ source: 'ai-patrol',
+ resourceId: 'storage:tower-array',
+ resourceName: 'Tower Array',
+ resourceType: 'storage',
+ category: 'availability',
+ severity: 'critical',
+ title: 'Unraid array running without parity protection while at 86% capacity',
+ description:
+ 'The Unraid array on Tower is running without parity protection while capacity is high.',
+ impact: 'A disk failure before parity is rebuilt could cause unrecoverable data loss.',
+ detectedAt: '2026-03-30T11:00:00Z',
+ lastSeenAt: '2026-03-30T11:05:00Z',
+ status: 'active',
+ loopState: 'detected',
+ },
+ {
+ id: 'finding-array-usage',
+ source: 'ai-patrol',
+ resourceId: 'storage:tower-array',
+ resourceName: 'Tower Array',
+ resourceType: 'storage',
+ category: 'capacity',
+ severity: 'warning',
+ title: 'Storage pool Tower Array at 85.9% usage',
+ description: 'Tower Array is nearing the configured storage capacity threshold.',
+ detectedAt: '2026-03-30T11:01:00Z',
+ lastSeenAt: '2026-03-30T11:05:00Z',
+ status: 'active',
+ loopState: 'detected',
+ },
+ ];
+
+ render(() => (
+ <FindingsPanel
+ findingsSource="patrol"
+ filterOverride="all"
+ filterFindingIds={['finding-array-parity', 'finding-array-usage']}
+ runSnapshot={{
+ resources_checked: 72,
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ finding_ids: ['finding-array-parity', 'finding-array-usage'],
+ status: 'critical',
+ error_count: 0,
+ }}
+ />
+ ));
+
+ await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
+
+ expect(screen.getByText('critical')).toBeInTheDocument();
+ expect(screen.getByText('warning')).toBeInTheDocument();
+ expect(
+ screen.getByText('Unraid array running without parity protection while at 86% capacity'),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Storage pool Tower Array at 85.9% usage')).toBeInTheDocument();
+ expect(screen.queryByText('detected')).not.toBeInTheDocument();
+ expect(screen.queryByText('Review finding')).not.toBeInTheDocument();
+
+ const disclosure = screen.getByRole('button', {
+ name: 'View details for Unraid array running without parity protection while at 86% capacity',
+ });
+ expect(disclosure).toHaveAttribute('aria-expanded', 'false');
+
+ fireEvent.click(disclosure);
+
+ expect(
+ screen.getByRole('button', {
+ name: 'Hide details for Unraid array running without parity protection while at 86% capacity',
+ }),
+ ).toHaveAttribute('aria-expanded', 'true');
+ expect(
+ screen.getByText(
+ 'The Unraid array on Tower is running without parity protection while capacity is high.',
+ ),
+ ).toBeInTheDocument();
+ });
+
it('can render Patrol findings from the direct Patrol source', async () => {
render(() => <FindingsPanel findingsSource="patrol" />);
@@ -267,4 +564,35 @@ describe('FindingsPanel resource links', () => {
expect(screen.queryByText('Loading findings...')).not.toBeInTheDocument();
expect(screen.getByText('Provider connection issue')).toBeInTheDocument();
});
+
+ it('renders a selected Patrol run empty snapshot while Patrol findings are loading', async () => {
+ mockState.patrolFindings = [];
+ mockState.patrolFindingsLoading = true;
+
+ render(() => (
+ <FindingsPanel
+ findingsSource="patrol"
+ filterOverride="all"
+ filterFindingIds={[]}
+ runSnapshot={{
+ resources_checked: 67,
+ scope_resource_ids: ['node-a'],
+ effective_scope_resource_ids: ['node-a'],
+ finding_ids: [],
+ status: 'error',
+ error_count: 1,
+ }}
+ />
+ ));
+
+ await waitFor(() => expect(mockState.loadPatrolFindings).toHaveBeenCalled());
+
+ expect(screen.queryByText('Loading findings...')).not.toBeInTheDocument();
+ expect(screen.getByText('No findings recorded for this run')).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ 'Checked 67 scoped resources. This run recorded no Patrol findings, but it ended with issues requiring review.',
+ ),
+ ).toBeInTheDocument();
+ });
});
diff --git a/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts b/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts
index 4e5a6064ad..9b8e8ddae3 100644
--- a/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts
+++ b/frontend-modern/src/components/AI/__tests__/FindingsPanel.test.ts
@@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
import {
+ buildPatrolFindingDisplayGroups,
buildFindingFilterOptions,
formatFindingForClipboard,
formatFindingLifecycleType,
@@ -14,6 +15,8 @@ import {
getFindingPrimaryActionPresentation,
getFindingSubjectPresentation,
getFindingTitlePresentation,
+ getFindingPatrolWorkflowPresentation,
+ getPatrolFindingIssueCountLabel,
getPatrolFindingClassification,
getFindingSeverityCompactLabel,
getFindingSeveritySortOrder,
@@ -51,6 +54,14 @@ const patrolWorkspaceSource = readFileSync(
resolve(__dirname, '..', '..', '..', 'features', 'patrol', 'PatrolIntelligenceWorkspace.tsx'),
'utf-8',
);
+const patrolInvestigationContextModelSource = readFileSync(
+ resolve(__dirname, '..', '..', '..', 'features', 'patrol', 'patrolInvestigationContextModel.ts'),
+ 'utf-8',
+);
+const aiFindingPresentationSource = readFileSync(
+ resolve(__dirname, '..', '..', '..', 'utils', 'aiFindingPresentation.ts'),
+ 'utf-8',
+);
describe('FindingsPanel assistant handoff', () => {
it('routes finding loading indicators through the shared LoadingSpinner primitive', () => {
@@ -60,19 +71,29 @@ describe('FindingsPanel assistant handoff', () => {
});
it('routes Patrol investigation records into the Assistant briefing context', () => {
- expect(findingsPanelSource).toContain('buildPatrolAssistantFindingHandoff');
+ expect(findingsPanelSource).toContain('buildPatrolAssistantFindingHandoffFromUnifiedFinding');
expect(findingsPanelSource).toContain('buildPatrolAssistantApprovalBriefingInput');
- expect(findingsPanelSource).toContain('buildPatrolAssistantProposedFixBriefingInput');
+ expect(findingsPanelSource).toContain(
+ 'buildPatrolAssistantProposedFixBriefingInputFromApproval',
+ );
expect(findingsPanelSource).toContain('aiChatStore.open(handoff.context)');
expect(findingsPanelSource).not.toContain('autoSendInitialPrompt');
expect(findingsPanelSource).not.toContain('openWithPrompt');
- expect(findingsPanelSource).toContain('investigationOutcome: finding.investigationOutcome');
- expect(findingsPanelSource).toContain('investigationStatus: finding.investigationStatus');
- expect(findingsPanelSource).toContain('remediationId: finding.remediationPlanId');
- expect(findingsPanelSource).toContain('resourceId: finding.resourceId');
- expect(findingsPanelSource).toContain('detectedAt: finding.detectedAt');
- expect(findingsPanelSource).toContain('lastSeenAt: finding.lastSeenAt');
- expect(findingsPanelSource).toContain('investigationRecord: finding.investigationRecord');
+ expect(patrolInvestigationContextModelSource).toContain(
+ 'investigationOutcome: finding.investigationOutcome',
+ );
+ expect(patrolInvestigationContextModelSource).toContain(
+ 'investigationStatus: finding.investigationStatus',
+ );
+ expect(patrolInvestigationContextModelSource).toContain(
+ 'remediationId: finding.remediationPlanId',
+ );
+ expect(patrolInvestigationContextModelSource).toContain('resourceId: finding.resourceId');
+ expect(patrolInvestigationContextModelSource).toContain('detectedAt: finding.detectedAt');
+ expect(patrolInvestigationContextModelSource).toContain('lastSeenAt: finding.lastSeenAt');
+ expect(patrolInvestigationContextModelSource).toContain(
+ 'investigationRecord: finding.investigationRecord',
+ );
expect(findingsPanelSource).toContain('pendingApproval: pendingApprovalBriefing');
expect(findingsPanelSource).toContain('proposedFix,');
expect(findingsPanelSource).not.toContain('nextStepAction,');
@@ -120,12 +141,20 @@ describe('FindingsPanel assistant handoff', () => {
it('keeps collapsed finding disclosure separate from inline manual controls', () => {
// The collapsed finding row contains acknowledge/snooze/dismiss controls.
- // Those controls must remain siblings of the disclosure button so the row
- // does not expose one interactive control nested inside another.
- expect(findingsPanelSource).not.toContain('role="button"');
+ // Those controls must remain siblings of the disclosure area, while the
+ // row body itself opens the same details panel for normal scanning.
+ expect(findingsPanelSource).toContain('role="button"');
+ expect(findingsPanelSource).toContain('tabIndex={0}');
+ expect(findingsPanelSource).toContain('class="min-w-0 flex-1 cursor-pointer rounded text-left');
expect(findingsPanelSource).toContain('aria-expanded={expandedId() === finding.id}');
+ expect(findingsPanelSource).toContain(
+ "aria-label={`${expandedId() === finding.id ? 'Close issue details' : 'Open issue details'} for ${title.label}`}",
+ );
+ expect(findingsPanelSource).toContain(
+ "aria-label={`${expandedId() === finding.id ? 'Hide' : 'View'} details for ${title.label}`}",
+ );
+ expect(findingsPanelSource).toContain("e.key === 'Enter' || e.key === ' '");
expect(findingsPanelSource).toContain('onClick={toggleExpanded}');
- expect(findingsPanelSource).toContain('</button>\n {/* Actions */}');
});
it('previews the will_fix_later remind-at deadline before the operator confirms dismiss', () => {
@@ -160,13 +189,50 @@ describe('FindingsPanel assistant handoff', () => {
expect(findingsPanelSource).toMatch(/>\s*Copy summary\s*</);
});
- it('keeps expanded finding actions behind a primary Assistant action and compact Manage menu', () => {
+ it('keeps expanded finding actions behind a canonical primary action and compact Manage menu', () => {
+ expect(findingsPanelSource).toContain('getFindingPrimaryActionPresentation(finding)');
expect(findingsPanelSource).toContain('getPrimaryAssistantFindingAction');
+ expect(findingsPanelSource).toContain('const shouldShowAssistantPrimaryAction =');
+ expect(findingsPanelSource).toContain('const shouldShowAssistantManageAction =');
+ expect(findingsPanelSource).toContain(
+ '<Show when={!primaryAction && shouldShowAssistantPrimaryAction}>',
+ );
+ expect(findingsPanelSource).toContain('<Show when={shouldShowAssistantManageAction}>');
+ expect(findingsPanelSource).not.toContain(
+ 'fallback={\n <button\n type="button"\n onClick={(e) => {\n e.stopPropagation();\n void openFindingInAssistant(finding);',
+ );
expect(findingsPanelSource).toContain('Manage');
expect(findingsPanelSource).toContain('min-w-48');
expect(findingsPanelSource).not.toContain('min-w-40');
});
+ it('keeps primary-action Patrol runtime findings out of secondary action clutter', () => {
+ // Runtime/setup findings already have one canonical recovery path:
+ // provider settings. The expanded card must not add the Assistant
+ // secondary button or generic Manage menu beside that primary action.
+ expect(findingsPanelSource).toContain('const shouldShowExpandedManageMenu =');
+ expect(findingsPanelSource).toContain('!primaryAction ||');
+ expect(findingsPanelSource).toContain('<Show when={shouldShowExpandedManageMenu}>');
+ expect(findingsPanelSource).toContain('when={primaryAction}');
+ expect(findingsPanelSource).not.toContain(
+ 'getPrimaryAssistantFindingAction(finding).label}\n </button>\n </>',
+ );
+ });
+
+ it('surfaces primary Patrol issue actions before expansion', () => {
+ expect(findingsPanelSource).toContain('shouldShowCollapsedPrimaryAction');
+ expect(findingsPanelSource).toContain('isPatrolFindingsSource()');
+ expect(findingsPanelSource).toContain("finding.status === 'active'");
+ expect(findingsPanelSource).toContain('props.runSnapshot === undefined');
+ expect(findingsPanelSource).toContain('expandedId() !== finding.id');
+ expect(findingsPanelSource).toContain(
+ 'const rowPrimaryAction = getFindingPrimaryActionPresentation(finding)',
+ );
+ expect(findingsPanelSource).toContain(
+ 'shouldShowCollapsedPrimaryAction(finding) && rowPrimaryAction',
+ );
+ });
+
it('exposes a manual Mark resolved action that goes through the patrol resolve store action', () => {
// The /api/ai/patrol/resolve endpoint exists server-side but had no
// operator path on the canonical Patrol surface. An operator fixing
@@ -214,6 +280,32 @@ describe('FindingsPanel assistant handoff', () => {
expect(regressionIndex).toBeGreaterThan(confidenceIndex);
});
+ it('surfaces only actionable Patrol workflow states from the shared presentation model', () => {
+ // Collapsed Patrol rows should stay issue-focused. Workflow state can
+ // drive a direct approval action, but it must not add process badges such
+ // as "detected", "investigating", or "verify outcome" to the scan view.
+ expect(findingsPanelSource).toContain('getFindingPatrolWorkflowPresentation');
+ expect(findingsPanelSource).toContain(
+ 'getFindingPatrolWorkflowPresentation(finding, aiIntelligenceStore.patrolPendingApprovals)',
+ );
+ expect(findingsPanelSource).toContain("workflow?.stage === 'approval'");
+ expect(findingsPanelSource).not.toContain("workflow.stage === 'investigating'");
+ expect(findingsPanelSource).not.toContain("workflow.stage === 'verification'");
+ expect(findingsPanelSource).not.toContain("workflow.stage === 'attention'");
+ expect(findingsPanelSource).not.toContain("workflow.stage === 'recorded'");
+ expect(findingsPanelSource).not.toContain("workflow.stage === 'paused'");
+ });
+
+ it('turns approval-required Patrol findings into a direct collapsed action', () => {
+ expect(findingsPanelSource).toContain('const collapsedApprovalAction = () => {');
+ expect(findingsPanelSource).toContain("workflow?.stage === 'approval'");
+ expect(findingsPanelSource).toContain(
+ '<Show when={expandedId() !== finding.id ? collapsedApprovalAction() : undefined}>',
+ );
+ expect(findingsPanelSource).toContain('title={action().detail}');
+ expect(findingsPanelSource).toContain('{action().label}');
+ });
+
it('warns the operator before dismissing a recurrent finding as not_an_issue or expected_behavior', () => {
// not_an_issue and expected_behavior both stay quiet forever after dismiss.
// If the finding has already regressed before, the operator may be
@@ -266,6 +358,20 @@ describe('FindingsPanel assistant handoff', () => {
expect(findingsPanelSource).toContain('>Impact:</span> {finding.impact}');
expect(findingsPanelSource).not.toContain('>Recommendation:</span>');
});
+
+ it('keeps active Patrol lifecycle history out of the default issue expansion', () => {
+ // Current issues should answer "what needs doing" first. Raw lifecycle
+ // history is still available when the operator chooses all/resolved history
+ // or a run record, but it should not be dumped into the default active
+ // Patrol issue expansion.
+ expect(findingsPanelSource).toContain('shouldShowFindingLifecycle');
+ expect(findingsPanelSource).toContain('!isPatrolFindingsSource()');
+ expect(findingsPanelSource).toContain("finding.status !== 'active'");
+ expect(findingsPanelSource).toContain('props.runSnapshot !== undefined');
+ expect(findingsPanelSource).toContain("filter() === 'all'");
+ expect(findingsPanelSource).toContain("filter() === 'resolved'");
+ expect(findingsPanelSource).toContain('Show when={shouldShowFindingLifecycle(finding)}');
+ });
});
describe('aiFindingPresentation', () => {
@@ -478,6 +584,15 @@ describe('aiFindingPresentation', () => {
});
describe('patrolFindingClassification', () => {
+ it('describes grouped Patrol findings as issues instead of internal signals', () => {
+ expect(getPatrolFindingIssueCountLabel(0)).toBe('0 issues');
+ expect(getPatrolFindingIssueCountLabel(1)).toBe('1 issue');
+ expect(getPatrolFindingIssueCountLabel(2)).toBe('2 issues');
+ expect(getPatrolFindingIssueCountLabel(2.9)).toBe('2 issues');
+ expect(aiFindingPresentationSource).toContain('getPatrolFindingIssueCountLabel');
+ expect(aiFindingPresentationSource).not.toContain('getPatrolFindingSignalCountLabel');
+ });
+
it('classifies ai-service findings as patrol runtime issues', () => {
expect(
getPatrolFindingClassification({
@@ -677,6 +792,7 @@ describe('aiFindingPresentation', () => {
expect(findingsPanelSource).toContain('getFindingPrimaryActionPresentation');
expect(findingsPanelSource).toContain('{action().label}');
expect(findingsPanelSource).toContain('href={action().href}');
+ expect(findingsPanelSource).toContain('shouldShowAssistantManageAction');
});
it('does not cross-jump expanded findings to broad Infrastructure or aggregate workspace routes', () => {
@@ -696,6 +812,16 @@ describe('aiFindingPresentation', () => {
expect(findingsPanelSource).toContain('manualControls.dismiss');
});
+ it('keeps inline manual controls out of the default Patrol queue rows', () => {
+ expect(findingsPanelSource).toContain('const shouldShowInlineManualControls =');
+ expect(findingsPanelSource).toContain(
+ "finding.status === 'active' && !isPatrolFindingsSource()",
+ );
+ expect(findingsPanelSource).toContain(
+ '<Show when={shouldShowInlineManualControls(finding)}>',
+ );
+ });
+
it('loads remediation artifacts through the shared Patrol store instead of probing the API directly', () => {
expect(findingsPanelSource).toContain('aiIntelligenceStore.loadRemediationPlans()');
expect(findingsPanelSource).toContain('aiIntelligenceStore.remediationPlans');
@@ -718,13 +844,31 @@ describe('aiFindingPresentation', () => {
expect(patrolWorkspaceSource).toContain('findingsSource="patrol"');
});
+ it('passes Patrol history regression evidence into the findings empty-state helper', () => {
+ expect(findingsPanelSource).toContain('historicalRegressionCount?: number');
+ expect(findingsPanelSource).toContain(
+ 'historicalRegressionCount: props.historicalRegressionCount',
+ );
+ expect(patrolWorkspaceSource).toContain(
+ 'historicalRegressionCount={state.historicalRegressionCount()}',
+ );
+ });
+
+ it('uses an informational icon for non-warning Patrol empty-state context', () => {
+ expect(findingsPanelSource).toContain("import InfoIcon from 'lucide-solid/icons/info';");
+ expect(findingsPanelSource).toContain("when={emptyStateCopy().tone === 'warning'}");
+ expect(findingsPanelSource).toContain(
+ '<InfoIcon class={`w-10 h-10 ${emptyStateTone().iconClass}`} />',
+ );
+ });
+
it('routes same-severity ordering through the shared patrol runtime sort helper', () => {
expect(findingsPanelSource).toContain('getFindingActiveRuntimeSortOrder(a)');
expect(findingsPanelSource).toContain('getFindingActiveRuntimeSortOrder(b)');
});
it('only shows the sort control when there are multiple Patrol findings to sort', () => {
- expect(findingsPanelSource).toContain('<Show when={patrolFindings().length > 1}>');
+ expect(findingsPanelSource).toContain('patrolFindingDisplayGroups().length > 1');
expect(findingsPanelSource).toContain('FormSelect');
expect(findingsPanelSource).toContain('label="Sort findings"');
expect(findingsPanelSource).toContain('<option value="severity">By Severity</option>');
@@ -761,17 +905,29 @@ describe('aiFindingPresentation', () => {
);
});
+ it('does not let global Patrol loading mask a selected run empty snapshot', () => {
+ expect(findingsPanelSource).toContain('const hasEmptyRunSnapshot = createMemo(');
+ expect(findingsPanelSource).toContain(
+ 'const canRenderRunSnapshotWithoutSourceFindings = createMemo(',
+ );
+ expect(findingsPanelSource).toContain('!canRenderRunSnapshotWithoutSourceFindings()');
+ expect(findingsPanelSource).toContain('const shouldShowRichEmptyState = createMemo(');
+ expect(findingsPanelSource).toContain("filter() === 'active' || props.runSnapshot");
+ });
+
it('uses explicit textual separators in finding metadata instead of relying on visual spacing', () => {
expect(findingsPanelSource).toContain("{' · '}acknowledged");
expect(findingsPanelSource).toContain("{' · '}last investigated");
expect(findingsPanelSource).toContain("{' · '}snoozed until");
});
- it('uses explicit textual separators for patrol tab badges instead of css-only spacing', () => {
+ it('uses shared metadata badges for the current Patrol queue resource count only', () => {
expect(patrolWorkspaceSource).toContain('aria-hidden="true"');
- expect(patrolWorkspaceSource).toContain("{' '}");
- expect(patrolWorkspaceSource).toContain('{state.findingsTabBadgeCount()}');
- expect(patrolWorkspaceSource).toContain('{state.displayRunHistory().length}');
+ expect(patrolWorkspaceSource).toContain('<MetadataBadge');
+ expect(patrolWorkspaceSource).toContain('getPatrolQueueBadgeLabel');
+ expect(patrolWorkspaceSource).toContain('queueAffectedResourceCount');
+ expect(patrolWorkspaceSource).toContain('{queueBadgeLabel()}');
+ expect(patrolWorkspaceSource).not.toContain('{runHistoryCount()}');
});
it('routes the findings tab badge tone through the shared patrol findings badge helper', () => {
@@ -782,10 +938,45 @@ describe('aiFindingPresentation', () => {
expect(patrolWorkspaceSource).not.toContain('findingsBadgePresentation().toneClasses');
});
- it('does not stack a detected loop-state badge on top of acknowledged active findings', () => {
+ it('does not stack a default detected loop-state badge on active findings', () => {
+ expect(findingsPanelSource).toContain('const shouldShowLoopStateBadge = () =>');
+ expect(findingsPanelSource).toContain('!isPatrolFindingsSource()');
+ expect(findingsPanelSource).toContain("finding.status === 'active'");
+ expect(findingsPanelSource).toContain("finding.source !== 'ai-patrol'");
+ expect(findingsPanelSource).toContain("finding.loopState !== 'detected'");
+ expect(findingsPanelSource).toContain('when={shouldShowLoopStateBadge()}');
+ expect(findingsPanelSource).toContain('Patrol status:');
+ expect(findingsPanelSource).not.toContain('Patrol loop:');
+ });
+
+ it('keeps raw Patrol process badges out of the collapsed Patrol issue row', () => {
+ expect(findingsPanelSource).toContain('const shouldShowInvestigationStatusBadge = () =>');
+ expect(findingsPanelSource).toContain('const shouldShowInvestigationOutcomeBadge = () =>');
+ expect(findingsPanelSource).toContain('const shouldShowInvestigationConfidenceBadge = () =>');
+ expect(findingsPanelSource).toContain('!isPatrolFindingsSource() &&');
+ expect(findingsPanelSource).not.toContain('const collapsedPatrolStatusBadge = () => {');
+ expect(findingsPanelSource).not.toContain(
+ "workflow?.stage === 'review' ? undefined : workflow",
+ );
+ expect(findingsPanelSource).not.toContain('<Show when={collapsedPatrolStatusBadge()}>');
+ });
+
+ it('groups active Patrol queue findings by resource without changing run records', () => {
+ expect(findingsPanelSource).toContain('buildPatrolFindingDisplayGroups');
+ expect(findingsPanelSource).toContain('getPatrolFindingIssueCountLabel');
+ expect(findingsPanelSource).toContain('const shouldGroupPatrolFindingsByResource');
+ expect(findingsPanelSource).toContain("filter() === 'active'");
+ expect(findingsPanelSource).toContain('props.runSnapshot === undefined');
+ expect(findingsPanelSource).toContain(
+ 'aria-label={`${group.resourceLabel}: ${getPatrolFindingIssueCountLabel(',
+ );
expect(findingsPanelSource).toContain(
- "!(finding.acknowledgedAt && finding.loopState === 'detected')",
+ '{getPatrolFindingIssueCountLabel(group.findings.length)}',
);
+ expect(findingsPanelSource).toContain('renderFindingItem(group.primaryFinding, false, {');
+ expect(findingsPanelSource).toContain('relatedFindings: group.relatedFindings');
+ expect(findingsPanelSource).not.toContain('<For each={group.findings}>');
+ expect(findingsPanelSource).toContain('hideSubject: true');
});
it('uses canonical finding recency presentation instead of raw detected timestamps for active rows', () => {
@@ -878,6 +1069,8 @@ describe('aiFindingPresentation', () => {
expect(getInvestigationOutcomeLabel('fix_verified')).toBe('Fix verified');
expect(getInvestigationOutcomeBadgeClasses('fix_failed')).toContain('red');
expect(getInvestigationOutcomeBadgeTone('fix_failed')).toBe('danger');
+ expect(getInvestigationOutcomeLabel('fix_rejected')).toBe('Fix rejected');
+ expect(getInvestigationOutcomeBadgeTone('fix_rejected')).toBe('warning');
expect(getInvestigationOutcomeBadgeClasses('cannot_fix')).toContain('bg-surface-alt');
expect(getInvestigationOutcomeBadgeTone('cannot_fix')).toBe('muted');
expect(getInvestigationOutcomeSortOrder('fix_failed')).toBe(0);
@@ -1024,6 +1217,220 @@ describe('aiFindingPresentation', () => {
});
});
+ describe('Patrol workflow presentation', () => {
+ const baseFinding = {
+ id: 'finding-1',
+ source: 'ai-patrol',
+ status: 'active',
+ resourceId: 'vm-101',
+ resourceName: 'database-01',
+ title: 'Disk pressure',
+ } as const;
+
+ it('does not invent a workflow badge for plain active Patrol findings', () => {
+ expect(getFindingPatrolWorkflowPresentation(baseFinding)).toBeUndefined();
+ });
+
+ it('keeps Patrol runtime setup copy neutral to watch-only and paid control modes', () => {
+ expect(
+ getFindingPatrolWorkflowPresentation({
+ ...baseFinding,
+ resourceId: 'ai-service',
+ resourceName: 'Pulse Patrol service',
+ title: 'Pulse Patrol: Provider connection issue',
+ }),
+ ).toMatchObject({
+ stage: 'attention',
+ label: 'Fix Patrol setup',
+ detail:
+ 'Patrol needs runtime or provider setup before it can check infrastructure reliably.',
+ tone: 'info',
+ });
+ });
+
+ it('promotes live governed approvals above generic review context', () => {
+ expect(
+ getFindingPatrolWorkflowPresentation(
+ {
+ ...baseFinding,
+ investigationOutcome: 'fix_queued',
+ },
+ [
+ {
+ status: 'pending',
+ toolId: 'investigation_fix',
+ targetId: 'finding-1',
+ expiresAt: '2026-06-20T18:15:00Z',
+ },
+ ],
+ Date.parse('2026-06-20T18:00:00Z'),
+ ),
+ ).toMatchObject({
+ stage: 'approval',
+ label: 'Approve or reject',
+ tone: 'warning',
+ });
+ });
+
+ it('asks the operator to recover a queued fix when no live approval exists', () => {
+ expect(
+ getFindingPatrolWorkflowPresentation(
+ {
+ ...baseFinding,
+ investigationOutcome: 'fix_queued',
+ },
+ [
+ {
+ status: 'pending',
+ toolId: 'investigation_fix',
+ targetId: 'finding-1',
+ expiresAt: '2026-06-20T17:59:00Z',
+ },
+ ],
+ Date.parse('2026-06-20T18:00:00Z'),
+ ),
+ ).toMatchObject({
+ stage: 'approval',
+ label: 'Review fix',
+ tone: 'warning',
+ });
+ });
+
+ it('separates rejected, executed, and verified outcomes into distinct operator next steps', () => {
+ expect(
+ getFindingPatrolWorkflowPresentation({
+ ...baseFinding,
+ investigationOutcome: 'fix_rejected',
+ }),
+ ).toMatchObject({
+ stage: 'attention',
+ label: 'Decide follow-up',
+ });
+
+ expect(
+ getFindingPatrolWorkflowPresentation({
+ ...baseFinding,
+ investigationOutcome: 'fix_executed',
+ }),
+ ).toMatchObject({
+ stage: 'verification',
+ label: 'Verify outcome',
+ });
+
+ expect(
+ getFindingPatrolWorkflowPresentation({
+ ...baseFinding,
+ investigationOutcome: 'fix_verified',
+ }),
+ ).toMatchObject({
+ stage: 'recorded',
+ label: 'Outcome recorded',
+ });
+ });
+
+ it('uses concrete labels for failed or input-needed Patrol outcomes', () => {
+ expect(
+ getFindingPatrolWorkflowPresentation({
+ ...baseFinding,
+ investigationOutcome: 'fix_failed',
+ }),
+ ).toMatchObject({
+ stage: 'attention',
+ label: 'Fix failed',
+ });
+
+ expect(
+ getFindingPatrolWorkflowPresentation({
+ ...baseFinding,
+ investigationOutcome: 'needs_attention',
+ }),
+ ).toMatchObject({
+ stage: 'attention',
+ label: 'Needs input',
+ });
+ });
+
+ it('does not attach the Patrol operations loop to threshold alerts', () => {
+ expect(
+ getFindingPatrolWorkflowPresentation({
+ ...baseFinding,
+ source: 'threshold',
+ }),
+ ).toBeUndefined();
+ });
+ });
+
+ describe('Patrol finding display groups', () => {
+ it('groups findings with the same resource identity while preserving sorted order', () => {
+ const groups = buildPatrolFindingDisplayGroups([
+ {
+ id: 'critical',
+ resourceId: 'storage:tower-array',
+ resourceName: 'Tower Array',
+ resourceType: 'storage',
+ title: 'No parity protection',
+ },
+ {
+ id: 'warning',
+ resourceId: 'storage:tower-array',
+ resourceName: 'Tower Array',
+ resourceType: 'storage',
+ title: 'High usage',
+ },
+ {
+ id: 'provider',
+ resourceId: 'ai-service',
+ resourceName: 'Pulse Patrol service',
+ resourceType: 'service',
+ title: 'Provider connection issue',
+ },
+ ]);
+
+ expect(groups).toHaveLength(2);
+ expect(groups[0]).toMatchObject({
+ resourceKey: 'subject:tower array (storage)',
+ resourceLabel: 'Tower Array (storage)',
+ });
+ expect(groups[0].primaryFinding.id).toBe('critical');
+ expect(groups[0].findings.map((finding) => finding.id)).toEqual(['critical', 'warning']);
+ expect(groups[0].relatedFindings.map((finding) => finding.id)).toEqual(['warning']);
+ expect(groups[1].findings.map((finding) => finding.id)).toEqual(['provider']);
+ expect(groups[1].relatedFindings).toEqual([]);
+ });
+
+ it('groups display-identical resources even when backend finding ids differ', () => {
+ const groups = buildPatrolFindingDisplayGroups([
+ {
+ id: 'array-risk',
+ resourceId: 'unraid:array:tower',
+ resourceName: 'Tower Array',
+ resourceType: 'storage',
+ title: 'No parity protection',
+ },
+ {
+ id: 'pool-usage',
+ resourceId: 'unraid:pool:tower-array',
+ resourceName: 'Tower Array',
+ resourceType: 'storage',
+ title: 'High usage',
+ },
+ ]);
+
+ expect(groups).toHaveLength(1);
+ expect(groups[0].findings.map((finding) => finding.id)).toEqual(['array-risk', 'pool-usage']);
+ });
+
+ it('keeps findings without resource identity separate instead of inventing duplicates', () => {
+ const groups = buildPatrolFindingDisplayGroups([
+ { id: 'a', resourceId: '', resourceName: '', resourceType: '', title: 'First' },
+ { id: 'b', resourceId: '', resourceName: '', resourceType: '', title: 'Second' },
+ ]);
+
+ expect(groups).toHaveLength(2);
+ expect(groups.map((group) => group.resourceKey)).toEqual(['finding:a', 'finding:b']);
+ });
+ });
+
describe('lifecycleLabels', () => {
it('has detected label', () => {
expect(formatFindingLifecycleType('detected')).toBe('Detected');
diff --git a/frontend-modern/src/components/Discovery/DiscoveryTab.tsx b/frontend-modern/src/components/Discovery/DiscoveryTab.tsx
index 7c6e2be4dd..a6b961213e 100644
--- a/frontend-modern/src/components/Discovery/DiscoveryTab.tsx
+++ b/frontend-modern/src/components/Discovery/DiscoveryTab.tsx
@@ -146,9 +146,10 @@ export const DiscoveryTab: Component<DiscoveryTabProps> = (props) => {
<div class="flex items-start gap-2.5">
<TriangleAlertIcon class="mt-0.5 h-4 w-4 flex-shrink-0 text-amber-600 dark:text-amber-400" />
<div class="text-xs text-amber-800 dark:text-amber-200">
- <p class="mb-1 font-medium">AI Discovery Disabled</p>
+ <p class="mb-1 font-medium">Service Context Disabled</p>
<p class="text-amber-700 dark:text-amber-300">
- Enable infrastructure discovery in Settings -&gt; AI before using this tab.
+ Enable service context in Settings -&gt; Pulse Intelligence -&gt; Service Context
+ before using this tab.
</p>
</div>
</div>
diff --git a/frontend-modern/src/components/Discovery/discoveryReadiness.ts b/frontend-modern/src/components/Discovery/discoveryReadiness.ts
index 8ff5aab029..657bac91d4 100644
--- a/frontend-modern/src/components/Discovery/discoveryReadiness.ts
+++ b/frontend-modern/src/components/Discovery/discoveryReadiness.ts
@@ -15,7 +15,7 @@ export type DiscoveryReadinessStatus =
| 'ready';
export interface DiscoveryReadinessInputs {
- /** The discovery feature toggle (Settings → AI → Workload Discovery). */
+ /** The service context toggle (Settings -> Pulse Intelligence -> Service Context). */
discoveryEnabled: boolean;
/** Whether at least one AI provider has credentials configured. */
aiProviderConfigured: boolean;
diff --git a/frontend-modern/src/components/Discovery/useDiscoveryTabState.ts b/frontend-modern/src/components/Discovery/useDiscoveryTabState.ts
index bbb7866951..d993b5fb01 100644
--- a/frontend-modern/src/components/Discovery/useDiscoveryTabState.ts
+++ b/frontend-modern/src/components/Discovery/useDiscoveryTabState.ts
@@ -198,7 +198,9 @@ export function useDiscoveryTabState(props: DiscoveryTabStateProps) {
const handleTriggerDiscovery = async (force = false) => {
if (!discoveryFeatureEnabled()) {
- setScanError('AI discovery is disabled in Settings -> AI.');
+ setScanError(
+ 'Service context is disabled in Settings -> Pulse Intelligence -> Service Context.',
+ );
return;
}
diff --git a/frontend-modern/src/components/Infrastructure/ResourceChangeSummary.tsx b/frontend-modern/src/components/Infrastructure/ResourceChangeSummary.tsx
index 39710a0f3f..b9abb4f125 100644
--- a/frontend-modern/src/components/Infrastructure/ResourceChangeSummary.tsx
+++ b/frontend-modern/src/components/Infrastructure/ResourceChangeSummary.tsx
@@ -18,6 +18,7 @@ interface ResourceChangeSummaryProps {
resolveResourceLabel?: (resourceId: string) => string | null | undefined;
maxChanges?: number;
compact?: boolean;
+ showMetadataBadges?: boolean;
class?: string;
}
@@ -34,6 +35,7 @@ export const ResourceChangeSummary: Component<ResourceChangeSummaryProps> = (pro
const headlineText = () => (compact() ? 'text-[11px]' : 'text-sm');
const badgeText = () => (compact() ? 'text-[10px]' : 'text-[11px]');
const gapSize = () => (compact() ? 'gap-2' : 'gap-3');
+ const showMetadataBadges = () => props.showMetadataBadges ?? true;
const renderRelatedResource = (resourceId: string) => {
const label = resolveResourceLabel?.(resourceId)?.trim() || resourceId;
@@ -77,6 +79,8 @@ export const ResourceChangeSummary: Component<ResourceChangeSummaryProps> = (pro
<For each={visibleChanges()}>
{(change) => {
const headline = formatResourceChangeHeadline(change);
+ const reason = change.reason?.trim() ?? '';
+ const shouldShowReason = reason.length > 0 && reason !== headline;
const resourceHref = buildResourceHref(change.resourceId);
const relatedResources = (change.relatedResources ?? []).slice(0, 3);
const kindPresentation = getResourceChangeKindPresentation(change.kind);
@@ -91,9 +95,7 @@ export const ResourceChangeSummary: Component<ResourceChangeSummaryProps> = (pro
<li class={`rounded-md border border-border-subtle bg-base ${itemPadding()}`}>
<div class={`flex flex-wrap items-start justify-between ${gapSize()}`}>
<div class="min-w-0">
- <p class={headlineText()}>
- {headline}
- </p>
+ <p class={headlineText()}>{headline}</p>
<p class={`mt-1 ${itemText()} text-muted`}>
{resourceHref ? (
<a
@@ -115,40 +117,44 @@ export const ResourceChangeSummary: Component<ResourceChangeSummaryProps> = (pro
<Show when={change.actor}>
<p class={`mt-1 ${itemText()} text-muted`}>By {change.actor}</p>
</Show>
- <Show when={change.reason}>
- <p class={`mt-1 ${itemText()} text-muted`}>{change.reason}</p>
+ <Show when={shouldShowReason}>
+ <p class={`mt-1 ${itemText()} text-muted`}>{reason}</p>
</Show>
</div>
- <div class="flex flex-wrap items-center gap-1.5">
- <span
- class={`rounded-full border px-2 py-0.5 ${badgeText()} font-medium ${
- kindPresentation.className
- }`}
- >
- {kindPresentation.label}
- </span>
- <span
- class={`rounded-full border px-2 py-0.5 ${badgeText()} font-medium ${
- sourceTypePresentation.className
- }`}
- >
- {sourceTypePresentation.label}
- </span>
- <Show when={sourceAdapterPresentation}>
+ <Show when={showMetadataBadges()}>
+ <div class="flex flex-wrap items-center gap-1.5">
<span
class={`rounded-full border px-2 py-0.5 ${badgeText()} font-medium ${
- sourceAdapterPresentation!.className
+ kindPresentation.className
}`}
>
- {sourceAdapterPresentation!.label}
+ {kindPresentation.label}
</span>
- </Show>
- </div>
+ <span
+ class={`rounded-full border px-2 py-0.5 ${badgeText()} font-medium ${
+ sourceTypePresentation.className
+ }`}
+ >
+ {sourceTypePresentation.label}
+ </span>
+ <Show when={sourceAdapterPresentation}>
+ <span
+ class={`rounded-full border px-2 py-0.5 ${badgeText()} font-medium ${
+ sourceAdapterPresentation!.className
+ }`}
+ >
+ {sourceAdapterPresentation!.label}
+ </span>
+ </Show>
+ </div>
+ </Show>
</div>
<Show when={(change.relatedResources ?? []).length > 0}>
- <div class={`mt-2 flex flex-wrap items-center gap-1.5 ${itemText()} text-muted`}>
+ <div
+ class={`mt-2 flex flex-wrap items-center gap-1.5 ${itemText()} text-muted`}
+ >
<span>Related:</span>
<For each={relatedResources}>{renderRelatedResource}</For>
</div>
diff --git a/frontend-modern/src/components/Infrastructure/ResourceCorrelationSummary.tsx b/frontend-modern/src/components/Infrastructure/ResourceCorrelationSummary.tsx
index ba95c18c81..39d74a5995 100644
--- a/frontend-modern/src/components/Infrastructure/ResourceCorrelationSummary.tsx
+++ b/frontend-modern/src/components/Infrastructure/ResourceCorrelationSummary.tsx
@@ -121,7 +121,7 @@ export const ResourceCorrelationSummary: Component<ResourceCorrelationSummaryPro
{targetLabel}
</span>
)}
- <span class="inline-flex items-center rounded bg-surface-alt px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-muted">
+ <span class="inline-flex items-center rounded bg-surface-alt px-1.5 py-0.5 text-[9px] text-muted">
{typeLabel}
</span>
</div>
@@ -247,7 +247,7 @@ export const ResourceCorrelationSummary: Component<ResourceCorrelationSummaryPro
{targetLabel}
</span>
)}
- <span class="inline-flex items-center rounded bg-surface-alt px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-muted">
+ <span class="inline-flex items-center rounded bg-surface-alt px-1.5 py-0.5 text-[9px] text-muted">
{patternLabel}
</span>
</div>
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceChangeSummary.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceChangeSummary.test.tsx
index fc51f46016..ce76968d9a 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceChangeSummary.test.tsx
+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceChangeSummary.test.tsx
@@ -72,4 +72,32 @@ describe('ResourceChangeSummary', () => {
expect(screen.getByText('Latest canonical change')).toBeInTheDocument();
expect(screen.getByText('No canonical changes were recorded.')).toBeInTheDocument();
});
+
+ it('can suppress metadata badges for compact operator context', () => {
+ render(() => (
+ <ResourceChangeSummary
+ title="Nearby activity"
+ changes={[
+ {
+ id: 'change-1',
+ resourceId: 'storage-1',
+ kind: 'alert_resolved',
+ reason: 'Alert resolved: ZFS pool recovered',
+ observedAt: '2026-03-18T12:00:00Z',
+ sourceType: 'platform_event',
+ sourceAdapter: 'proxmox_adapter',
+ confidence: 'medium',
+ },
+ ]}
+ showMetadataBadges={false}
+ />
+ ));
+
+ expect(screen.getByText('Nearby activity')).toBeInTheDocument();
+ expect(screen.getByText('Alert resolved: ZFS pool recovered')).toBeInTheDocument();
+ expect(screen.getByText('storage-1')).toBeInTheDocument();
+ expect(screen.queryByText('Platform event')).toBeNull();
+ expect(screen.queryByText('Proxmox adapter')).toBeNull();
+ expect(screen.queryByText('Heuristic')).toBeNull();
+ });
});
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceCorrelationSummary.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceCorrelationSummary.test.tsx
index 48f2cb131f..d2e7a06511 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceCorrelationSummary.test.tsx
+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceCorrelationSummary.test.tsx
@@ -23,6 +23,20 @@ describe('ResourceCorrelationSummary', () => {
last_seen: '2026-03-01T00:15:00Z',
description: 'Disk pressure often precedes restarts',
},
+ {
+ source_id: 'storage-2',
+ source_name: 'Storage 2',
+ source_type: 'storage',
+ target_id: 'host-2',
+ target_name: 'Host 2',
+ target_type: 'vm',
+ event_pattern: 'ALERT → ALERT',
+ occurrences: 1,
+ avg_delay: 125000000000,
+ confidence: 0.5,
+ last_seen: '2026-03-01T00:10:00Z',
+ description: 'Alerts often cluster together',
+ },
]}
summaryText="5 total"
/>
@@ -36,6 +50,9 @@ describe('ResourceCorrelationSummary', () => {
expect(screen.getByText('Storage 1')).toBeInTheDocument();
expect(screen.getByText('Host 1')).toBeInTheDocument();
expect(screen.getByText('Disk Full → Restart')).toBeInTheDocument();
+ const alertPattern = screen.getByText('Alert → Alert');
+ expect(alertPattern).toBeInTheDocument();
+ expect(alertPattern.className).not.toContain('uppercase');
expect(screen.getByText(/2 occurrences · avg delay 2m · 88% confidence/)).toBeInTheDocument();
expect(screen.getByText('Disk pressure often precedes restarts')).toBeInTheDocument();
expect(screen.queryByText(/last seen/i)).toBeNull();
@@ -102,7 +119,9 @@ describe('ResourceCorrelationSummary', () => {
expect(screen.getByText('PVE 1')).toBeInTheDocument();
expect(screen.getAllByText('VM Child').length).toBeGreaterThan(0);
expect(screen.getByText('Storage 1 alias')).toBeInTheDocument();
- expect(screen.getByText('Runs On')).toBeInTheDocument();
+ const relationshipType = screen.getByText('Runs On');
+ expect(relationshipType).toBeInTheDocument();
+ expect(relationshipType.className).not.toContain('uppercase');
expect(screen.getByText(/100% confidence · Proxmox Adapter · last seen/)).toBeInTheDocument();
expect(screen.getAllByText(/last seen/i).length).toBeGreaterThanOrEqual(2);
});
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.discovery.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.discovery.test.ts
index 4a3ede9136..b51f3deb08 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.discovery.test.ts
+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.discovery.test.ts
@@ -2,6 +2,9 @@ import { describe, expect, it } from 'vitest';
import type { Resource } from '@/types/resource';
import type { ResourceDiscovery } from '@/types/discovery';
+import discoveryTabSource from '@/components/Discovery/DiscoveryTab.tsx?raw';
+import discoveryReadinessSource from '@/components/Discovery/discoveryReadiness.ts?raw';
+import discoveryTabStateSource from '@/components/Discovery/useDiscoveryTabState.ts?raw';
import { toDiscoveryConfig } from '@/components/Infrastructure/resourceDetailDiscoveryModel';
import { hasMeaningfulDiscoveryContext } from '@/utils/discoveryPresentation';
@@ -355,6 +358,19 @@ describe('toDiscoveryConfig', () => {
});
describe('resource drawer discovery promotion', () => {
+ it('points disabled discovery readiness at Pulse Intelligence service context settings', () => {
+ expect(discoveryTabSource).toContain('Service Context Disabled');
+ expect(discoveryTabSource).toContain(
+ 'Settings -&gt; Pulse Intelligence -&gt; Service Context',
+ );
+ expect(discoveryTabStateSource).toContain(
+ 'Service context is disabled in Settings -> Pulse Intelligence -> Service Context.',
+ );
+ expect(discoveryReadinessSource).toContain(
+ 'Settings -> Pulse Intelligence -> Service Context',
+ );
+ });
+
it('does not treat command-only diagnostic records as meaningful resource context', () => {
const discovery: ResourceDiscovery = {
id: 'system-container:pve4:152',
diff --git a/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx b/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx
index cb1590a24b..e3cfe19435 100644
--- a/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx
+++ b/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx
@@ -4,7 +4,6 @@ import { isModelProviderConfigured } from '@/components/Settings/aiSettingsModel
import type { AISettingsState } from '@/components/Settings/useAISettingsState';
import { AIModelPicker } from '@/components/shared/AIModelPicker';
import { formField, labelClass, controlClass } from '@/components/shared/Form';
-import { AI_SETTINGS_MODEL_OVERRIDES_TITLE } from '@/utils/aiSettingsPresentation';
import {
formatAIModelRouteLabel,
getAIProviderDisplayName,
@@ -15,21 +14,56 @@ interface AIModelSelectionSectionProps {
state: AISettingsState;
}
+type AIModelOverrideKind = 'assistant' | 'patrol' | 'discovery';
+
+const MODEL_OVERRIDE_CONFIG: Record<
+ AIModelOverrideKind,
+ {
+ formKey: 'chatModel' | 'patrolModel' | 'discoveryModel';
+ label: string;
+ description: string;
+ ariaLabel: string;
+ title: string;
+ }
+> = {
+ assistant: {
+ formKey: 'chatModel',
+ label: 'Pulse Assistant model',
+ description: 'Used for chat, explanations, and review. Patrol handles infrastructure work.',
+ ariaLabel: 'Pulse Assistant model identifier',
+ title: 'Select Pulse Assistant model',
+ },
+ patrol: {
+ formKey: 'patrolModel',
+ label: 'Patrol model',
+ description: 'Used when Patrol watches, investigates, and verifies work.',
+ ariaLabel: 'Patrol model identifier',
+ title: 'Select Patrol model',
+ },
+ discovery: {
+ formKey: 'discoveryModel',
+ label: 'Service context model',
+ description: 'Used for model-backed service identification and scheduled context refreshes.',
+ ariaLabel: 'Service context model identifier',
+ title: 'Select service context model',
+ },
+};
+
const stripModelProvider = (modelId: string) => {
const trimmed = modelId.trim();
const colon = trimmed.indexOf(':');
return colon === -1 ? trimmed : trimmed.slice(colon + 1);
};
-const PatrolPreflightControl: Component<{ state: AISettingsState }> = (controlProps) => {
+export const PatrolPreflightControl: Component<{ state: AISettingsState }> = (controlProps) => {
const { state } = controlProps;
const result = state.patrolPreflightResult;
// The cached result may be for a model the operator already moved away
// from in the form (e.g. they changed the dropdown but haven't clicked
- // Verify Patrol yet). When that happens, surface a hint so the green
+ // Check Patrol model yet). When that happens, surface a hint so the green
// "verified" badge doesn't silently mislead. The backend reads the
- // form's pending patrolModel on Verify Patrol click, so refreshing
+ // form's pending patrolModel on Check Patrol model click, so refreshing
// resolves the staleness.
const pendingFormModel = () => stripModelProvider(state.form.patrolModel || '');
const cachedResultModel = () => result()?.model?.trim() || '';
@@ -68,19 +102,25 @@ const PatrolPreflightControl: Component<{ state: AISettingsState }> = (controlPr
return `Verified result is for ${cachedResultModel()}, your current selection is ${pendingFormModel()}`;
}
if (r.success) {
- return 'Tool calling verified';
+ return 'Patrol model ready';
}
if (r.cause === 'model_tool_support_unverified') {
- return 'Provider accepted the request but the model did not call the tool';
+ return 'Patrol model needs a real run to confirm';
}
- return r.message || 'Patrol preflight failed';
+ return r.message || 'Patrol model check failed';
};
const detail = () => {
const r = result();
if (!r) return '';
if (isStaleAgainstFormSelection()) {
- return 'Click Verify Patrol to test the pending selection.';
+ return 'Click Check Patrol model to test the pending selection.';
+ }
+ if (r.success) {
+ return 'The selected model can run Patrol work on this install.';
+ }
+ if (r.cause === 'model_tool_support_unverified') {
+ return 'Run Patrol once to confirm this model works correctly in practice.';
}
return r.summary || r.message || '';
};
@@ -107,9 +147,7 @@ const PatrolPreflightControl: Component<{ state: AISettingsState }> = (controlPr
<div class="mt-2 flex flex-col gap-2">
<div class="flex items-center justify-between gap-2">
<p class="text-[11px] text-muted">
- Verify that this Patrol model can actually call tools — different from{' '}
- <span class="font-medium">Run Preflight</span>, which only checks each provider's
- connection.
+ Check that this model can run Patrol work, not just connect to the provider.
</p>
<button
type="button"
@@ -117,7 +155,7 @@ const PatrolPreflightControl: Component<{ state: AISettingsState }> = (controlPr
disabled={state.patrolPreflightRunning() || state.saving()}
class="inline-flex min-h-9 items-center rounded-md px-3 py-1.5 text-sm bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 hover:bg-blue-200 dark:hover:bg-blue-800 disabled:opacity-50 whitespace-nowrap"
>
- {state.patrolPreflightRunning() ? 'Verifying...' : 'Verify Patrol'}
+ {state.patrolPreflightRunning() ? 'Checking...' : 'Check Patrol model'}
</button>
</div>
<Show when={result()}>
@@ -154,8 +192,15 @@ const PatrolPreflightControl: Component<{ state: AISettingsState }> = (controlPr
);
};
-export const AIModelSelectionSection: Component<AIModelSelectionSectionProps> = (props) => {
+export const AIModelOverrideField: Component<{
+ state: AISettingsState;
+ kind: AIModelOverrideKind;
+ includePatrolPreflight?: boolean;
+}> = (props) => {
const { state } = props;
+ const config = () => MODEL_OVERRIDE_CONFIG[props.kind];
+ const selectedModel = () => state.form[config().formKey];
+ const setSelectedModel = (modelId: string) => state.setForm(config().formKey, modelId);
const modelLabel = (modelId: string) => {
const trimmed = modelId.trim();
if (!trimmed) {
@@ -164,6 +209,86 @@ export const AIModelSelectionSection: Component<AIModelSelectionSectionProps> =
const match = state.availableModels().find((model) => model.id === trimmed);
return formatAIModelRouteLabel(match || trimmed);
};
+ const selectableModels = () => {
+ const selected = selectedModel().trim();
+ return state
+ .availableModels()
+ .filter(
+ (model) => isModelProviderConfigured(model.id, state.settings()) || model.id === selected,
+ );
+ };
+ const pickerButtonClass = () =>
+ `${controlClass()} flex items-center gap-2 justify-between text-left disabled:cursor-not-allowed disabled:opacity-60`;
+ const sharedDefaultDescription = () =>
+ state.form.model ? `Currently ${modelLabel(state.form.model)}` : 'No shared default model set';
+
+ return (
+ <div class={formField}>
+ <label class="block text-xs font-medium text-muted mb-0.5">{config().label}</label>
+ <p class="text-[11px] text-muted mb-1">{config().description}</p>
+ <Show
+ when={selectableModels().length > 0}
+ fallback={
+ <input
+ type="text"
+ value={selectedModel()}
+ onInput={(e) => setSelectedModel(e.currentTarget.value)}
+ placeholder="Use shared default model"
+ aria-label={config().ariaLabel}
+ class={controlClass()}
+ disabled={state.saving()}
+ />
+ }
+ >
+ <AIModelPicker
+ models={selectableModels()}
+ selectedModel={selectedModel()}
+ onModelSelect={setSelectedModel}
+ defaultOption={{
+ label: 'Use shared default',
+ description: sharedDefaultDescription(),
+ }}
+ emptySelectionLabel="Use shared default"
+ title={config().title}
+ searchPlaceholder="Search configured provider models"
+ customModelDescription="Custom provider:model ID"
+ disabled={state.saving()}
+ align="left"
+ buttonClass={pickerButtonClass()}
+ buttonLabelClass="min-w-0 flex-1 truncate text-left font-normal"
+ dropdownClass="w-[calc(100vw-2rem)] max-w-xl"
+ />
+ </Show>
+ <Show when={selectedModel() && !isModelProviderConfigured(selectedModel(), state.settings())}>
+ <p class="text-xs text-amber-600 dark:text-amber-400 mt-1 flex items-center gap-1">
+ <svg
+ class="w-3.5 h-3.5 flex-shrink-0"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
+ />
+ </svg>
+ This model requires{' '}
+ {getAIProviderDisplayName(getProviderFromModelId(selectedModel())) ||
+ getProviderFromModelId(selectedModel())}{' '}
+ to be configured. Add an API key on Provider & Models or select a different model.
+ </p>
+ </Show>
+ <Show when={props.includePatrolPreflight}>
+ <PatrolPreflightControl state={state} />
+ </Show>
+ </div>
+ );
+};
+
+export const AIModelSelectionSection: Component<AIModelSelectionSectionProps> = (props) => {
+ const { state } = props;
const selectableModels = (selectedModel: string) => {
const selected = selectedModel.trim();
return state
@@ -173,15 +298,10 @@ export const AIModelSelectionSection: Component<AIModelSelectionSectionProps> =
);
};
const sharedModelOptions = () => selectableModels(state.form.model);
- const chatModelOptions = () => selectableModels(state.form.chatModel);
- const patrolModelOptions = () => selectableModels(state.form.patrolModel);
- const discoveryModelOptions = () => selectableModels(state.form.discoveryModel);
const pickerButtonClass = () =>
`${controlClass()} flex items-center gap-2 justify-between text-left disabled:cursor-not-allowed disabled:opacity-60`;
const pickerLabelClass = 'min-w-0 flex-1 truncate text-left font-normal';
const pickerDropdownClass = 'w-[calc(100vw-2rem)] max-w-xl';
- const sharedDefaultDescription = () =>
- state.form.model ? `Currently ${modelLabel(state.form.model)}` : 'No shared default model set';
return (
<>
@@ -294,185 +414,6 @@ export const AIModelSelectionSection: Component<AIModelSelectionSectionProps> =
</p>
</div>
- <div class="border border-border rounded-md overflow-hidden">
- <button
- type="button"
- class="w-full min-h-10 sm:min-h-9 px-3 py-2.5 flex items-center justify-between bg-surface-alt hover:bg-surface-hover transition-colors text-left"
- onClick={() => state.setShowAdvancedModels(!state.showAdvancedModels())}
- >
- <div class="flex items-center gap-2">
- <svg
- class="w-4 h-4 text-slate-500"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"
- />
- </svg>
- <span class="text-sm font-medium text-base-content">
- {AI_SETTINGS_MODEL_OVERRIDES_TITLE}
- </span>
- <Show
- when={state.form.chatModel || state.form.patrolModel || state.form.discoveryModel}
- >
- <span class="px-1.5 py-0.5 text-[10px] font-semibold bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 rounded">
- Customized
- </span>
- </Show>
- </div>
- <svg
- class={`w-4 h-4 text-slate-500 transition-transform ${state.showAdvancedModels() ? 'rotate-180' : ''}`}
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M19 9l-7 7-7-7"
- />
- </svg>
- </button>
- <Show when={state.showAdvancedModels()}>
- <div class="px-3 py-3 bg-surface border-t border-border space-y-3">
- <p class="text-xs text-muted">
- Override the shared default for Pulse Assistant, Patrol, or Discovery. Leave empty to
- use the shared default model.
- </p>
- <div>
- <label class="block text-xs font-medium text-muted mb-0.5">
- Pulse Assistant Model
- </label>
- <p class="text-[11px] text-muted mb-1">
- Used for live chat and approved fix execution — a more capable model is recommended.
- </p>
- <Show
- when={chatModelOptions().length > 0}
- fallback={
- <input
- type="text"
- value={state.form.chatModel}
- onInput={(e) => state.setForm('chatModel', e.currentTarget.value)}
- placeholder="Use shared default model"
- aria-label="Pulse Assistant model identifier"
- class={controlClass()}
- disabled={state.saving()}
- />
- }
- >
- <AIModelPicker
- models={chatModelOptions()}
- selectedModel={state.form.chatModel}
- onModelSelect={(modelId) => state.setForm('chatModel', modelId)}
- defaultOption={{
- label: 'Use shared default',
- description: sharedDefaultDescription(),
- }}
- emptySelectionLabel="Use shared default"
- title="Select Pulse Assistant model"
- searchPlaceholder="Search configured provider models"
- customModelDescription="Custom provider:model ID"
- disabled={state.saving()}
- align="left"
- buttonClass={pickerButtonClass()}
- buttonLabelClass={pickerLabelClass}
- dropdownClass={pickerDropdownClass}
- />
- </Show>
- </div>
- <div>
- <label class="block text-xs font-medium text-muted mb-0.5">
- Patrol Verification Model
- </label>
- <p class="text-[11px] text-muted mb-1">
- Used for recurring verification and finding generation — a smaller, cheaper model
- keeps costs low.
- </p>
- <Show
- when={patrolModelOptions().length > 0}
- fallback={
- <input
- type="text"
- value={state.form.patrolModel}
- onInput={(e) => state.setForm('patrolModel', e.currentTarget.value)}
- placeholder="Use shared default model"
- aria-label="Patrol Verification model identifier"
- class={controlClass()}
- disabled={state.saving()}
- />
- }
- >
- <AIModelPicker
- models={patrolModelOptions()}
- selectedModel={state.form.patrolModel}
- onModelSelect={(modelId) => state.setForm('patrolModel', modelId)}
- defaultOption={{
- label: 'Use shared default',
- description: sharedDefaultDescription(),
- }}
- emptySelectionLabel="Use shared default"
- title="Select Patrol verification model"
- searchPlaceholder="Search configured provider models"
- customModelDescription="Custom provider:model ID"
- disabled={state.saving()}
- align="left"
- buttonClass={pickerButtonClass()}
- buttonLabelClass={pickerLabelClass}
- dropdownClass={pickerDropdownClass}
- />
- </Show>
- <PatrolPreflightControl state={state} />
- </div>
- <div>
- <label class="block text-xs font-medium text-muted mb-0.5">Discovery Model</label>
- <p class="text-[11px] text-muted mb-1">
- Used for one-shot service identification on a single resource — a cheaper model like
- Haiku is usually sufficient.
- </p>
- <Show
- when={discoveryModelOptions().length > 0}
- fallback={
- <input
- type="text"
- value={state.form.discoveryModel}
- onInput={(e) => state.setForm('discoveryModel', e.currentTarget.value)}
- placeholder="Use shared default model"
- aria-label="Discovery model identifier"
- class={controlClass()}
- disabled={state.saving()}
- />
- }
- >
- <AIModelPicker
- models={discoveryModelOptions()}
- selectedModel={state.form.discoveryModel}
- onModelSelect={(modelId) => state.setForm('discoveryModel', modelId)}
- defaultOption={{
- label: 'Use shared default',
- description: sharedDefaultDescription(),
- }}
- emptySelectionLabel="Use shared default"
- title="Select Discovery model"
- searchPlaceholder="Search configured provider models"
- customModelDescription="Custom provider:model ID"
- disabled={state.saving()}
- align="left"
- buttonClass={pickerButtonClass()}
- buttonLabelClass={pickerLabelClass}
- dropdownClass={pickerDropdownClass}
- />
- </Show>
- </div>
- </div>
- </Show>
- </div>
-
<div class={formField}>
<AIProviderConfigurationSection
settings={state.settings}
diff --git a/frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx b/frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx
index 7aea86a882..4ad945d582 100644
--- a/frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx
+++ b/frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx
@@ -26,49 +26,28 @@ interface AIRuntimeControlsSectionProps {
export const AIRuntimeControlsSection: Component<AIRuntimeControlsSectionProps> = (props) => {
const { state } = props;
- const showAutonomousControlOption = () =>
- !state.autoFixLocked() ||
- state.showUpgradePrompts() ||
- state.form.controlLevel === 'autonomous';
-
return (
<>
- <div class="rounded-md border border-blue-200 dark:border-blue-800 overflow-hidden">
- <button
- type="button"
- class="w-full min-h-10 sm:min-h-9 px-3 py-2.5 flex items-center justify-between bg-blue-50 dark:bg-blue-900 hover:bg-blue-100 dark:hover:bg-blue-900 transition-colors text-left"
- onClick={() => state.setShowDiscoverySettings(!state.showDiscoverySettings())}
- >
- <div class="flex items-center gap-2">
- <svg
- class="w-4 h-4 text-blue-600 dark:text-blue-400"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- stroke-width="2"
- d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
- />
- </svg>
- <span class="text-sm font-medium text-base-content">Workload Discovery</span>
- <Show when={state.form.discoveryEnabled}>
- <span class="px-1.5 py-0.5 text-[10px] font-medium bg-blue-100 dark:bg-blue-800 text-blue-700 dark:text-blue-300 rounded">
- {state.form.discoveryIntervalHours > 0
- ? `Auto ${state.form.discoveryIntervalHours}h`
- : 'Manual only'}
- </span>
- </Show>
- <Show when={!state.form.discoveryEnabled}>
- <span class="px-1.5 py-0.5 text-[10px] font-medium bg-surface-hover text-muted rounded">
- Off
- </span>
- </Show>
- </div>
+ <AIDiscoveryControlsSection state={state} />
+ <AIProviderRuntimeControlsSection state={state} />
+ <AIAssistantCommandAccessSection state={state} />
+ </>
+ );
+};
+
+export const AIDiscoveryControlsSection: Component<AIRuntimeControlsSectionProps> = (props) => {
+ const { state } = props;
+
+ return (
+ <div class="rounded-md border border-blue-200 dark:border-blue-800 overflow-hidden">
+ <button
+ type="button"
+ class="w-full min-h-10 sm:min-h-9 px-3 py-2.5 flex items-center justify-between bg-blue-50 dark:bg-blue-900 hover:bg-blue-100 dark:hover:bg-blue-900 transition-colors text-left"
+ onClick={() => state.setShowDiscoverySettings(!state.showDiscoverySettings())}
+ >
+ <div class="flex items-center gap-2">
<svg
- class={`w-4 h-4 transition-transform ${state.showDiscoverySettings() ? 'rotate-180' : ''}`}
+ class="w-4 h-4 text-blue-600 dark:text-blue-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
@@ -77,83 +56,119 @@ export const AIRuntimeControlsSection: Component<AIRuntimeControlsSectionProps>
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
- d="M19 9l-7 7-7-7"
+ d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
/>
</svg>
- </button>
- <Show when={state.showDiscoverySettings()}>
- <div class="px-3 py-3 bg-surface border-t border-border space-y-3">
- <div class="flex items-center justify-between gap-2">
- <label class="text-xs font-medium text-muted flex items-center gap-1.5">
- Enable workload discovery
- <HelpIcon inline={getAISettingsWorkloadDiscoveryHelpContent()} size="xs" />
- </label>
- <Toggle
- checked={state.form.discoveryEnabled}
- onChange={(event) => state.setForm('discoveryEnabled', event.currentTarget.checked)}
- disabled={state.saving()}
- />
- </div>
-
- <Show when={state.form.discoveryEnabled}>
- <div class="flex flex-col gap-1">
- <FormSelect
- id="ai-workload-discovery-scan-interval"
- label="Scan Interval"
- value={String(state.form.discoveryIntervalHours)}
- onChange={(e) =>
- state.setForm('discoveryIntervalHours', parseInt(e.currentTarget.value, 10))
- }
- disabled={state.saving()}
- fieldBaseClass="flex"
- fieldClass="items-center gap-3"
- labelClass="text-xs font-medium text-muted w-32 flex-shrink-0"
- selectBaseClass="flex-1 px-2 py-1 text-sm border border-border rounded bg-surface"
- >
- <option value="0">Manual only</option>
- <option value="6">Every 6 hours</option>
- <option value="12">Every 12 hours</option>
- <option value="24">Every 24 hours</option>
- <option value="48">Every 2 days</option>
- <option value="168">Every 7 days</option>
- </FormSelect>
- <p class="text-[10px] text-muted ml-32 pl-3">
- {state.form.discoveryIntervalHours === 0
- ? 'Automatic workload scans are off. Only manual refreshes will run.'
- : 'Automatic workload scans will run at this interval.'}
- </p>
- </div>
- </Show>
+ <span class="text-sm font-medium text-base-content">Service Context</span>
+ <Show when={state.form.discoveryEnabled}>
+ <span class="px-1.5 py-0.5 text-[10px] font-medium bg-blue-100 dark:bg-blue-800 text-blue-700 dark:text-blue-300 rounded">
+ {state.form.discoveryIntervalHours > 0
+ ? `Auto ${state.form.discoveryIntervalHours}h`
+ : 'Manual only'}
+ </span>
+ </Show>
+ <Show when={!state.form.discoveryEnabled}>
+ <span class="px-1.5 py-0.5 text-[10px] font-medium bg-surface-hover text-muted rounded">
+ Off
+ </span>
+ </Show>
+ </div>
+ <svg
+ class={`w-4 h-4 transition-transform ${state.showDiscoverySettings() ? 'rotate-180' : ''}`}
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ d="M19 9l-7 7-7-7"
+ />
+ </svg>
+ </button>
+ <Show when={state.showDiscoverySettings()}>
+ <div class="px-3 py-3 bg-surface border-t border-border space-y-3">
+ <div class="flex items-center justify-between gap-2">
+ <label class="text-xs font-medium text-muted flex items-center gap-1.5">
+ Enable service context scans
+ <HelpIcon inline={getAISettingsWorkloadDiscoveryHelpContent()} size="xs" />
+ </label>
+ <Toggle
+ checked={state.form.discoveryEnabled}
+ onChange={(event) => state.setForm('discoveryEnabled', event.currentTarget.checked)}
+ disabled={state.saving()}
+ />
+ </div>
- <div class="flex flex-col gap-2 rounded border border-border bg-surface-alt px-3 py-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
- <p class="text-[10px] text-muted sm:flex-1">
- {state.form.discoveryEnabled && state.form.discoveryIntervalHours > 0
- ? 'Runs the pending workload sweep used by the schedule.'
- : state.form.discoveryEnabled
- ? 'Manual-only mode: runs the pending workload sweep once without enabling recurring scans.'
- : 'Runs a one-time workload discovery refresh without changing the schedule.'}
- </p>
- <button
- type="button"
- class="inline-flex min-h-10 items-center gap-1.5 self-start rounded-md border border-border px-3 py-1.5 text-xs font-medium text-base-content hover:bg-surface-hover disabled:cursor-not-allowed disabled:opacity-50 sm:min-h-9 sm:self-auto sm:flex-shrink-0"
- onClick={() => void state.handleRunDiscoveryRefresh()}
- disabled={state.saving() || state.discoveryRunRunning()}
+ <Show when={state.form.discoveryEnabled}>
+ <div class="flex flex-col gap-1">
+ <FormSelect
+ id="ai-workload-discovery-scan-interval"
+ label="Scan Interval"
+ value={String(state.form.discoveryIntervalHours)}
+ onChange={(e) =>
+ state.setForm('discoveryIntervalHours', parseInt(e.currentTarget.value, 10))
+ }
+ disabled={state.saving()}
+ fieldBaseClass="flex"
+ fieldClass="items-center gap-3"
+ labelClass="text-xs font-medium text-muted w-32 flex-shrink-0"
+ selectBaseClass="flex-1 px-2 py-1 text-sm border border-border rounded bg-surface"
>
- <Show
- when={state.discoveryRunRunning()}
- fallback={<RefreshCwIcon class="h-3.5 w-3.5" />}
- >
- <RefreshCwIcon class="h-3.5 w-3.5 animate-spin" />
- </Show>
- {state.discoveryRunRunning() ? 'Running...' : 'Run discovery now'}
- </button>
+ <option value="0">Manual only</option>
+ <option value="6">Every 6 hours</option>
+ <option value="12">Every 12 hours</option>
+ <option value="24">Every 24 hours</option>
+ <option value="48">Every 2 days</option>
+ <option value="168">Every 7 days</option>
+ </FormSelect>
+ <p class="text-[10px] text-muted ml-32 pl-3">
+ {state.form.discoveryIntervalHours === 0
+ ? 'Recurring service context scans are off. Only manual refreshes will run.'
+ : 'Recurring service context scans will run at this interval.'}
+ </p>
</div>
+ </Show>
- <p class="text-[10px] text-muted">{getAISettingsWorkloadDiscoverySummary().text}</p>
+ <div class="flex flex-col gap-2 rounded border border-border bg-surface-alt px-3 py-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
+ <p class="text-[10px] text-muted sm:flex-1">
+ {state.form.discoveryEnabled && state.form.discoveryIntervalHours > 0
+ ? 'Runs the same scan used by the schedule.'
+ : state.form.discoveryEnabled
+ ? 'Manual-only mode: runs one scan without enabling recurring scans.'
+ : 'Runs one service context scan without changing the schedule.'}
+ </p>
+ <button
+ type="button"
+ class="inline-flex min-h-10 items-center gap-1.5 self-start rounded-md border border-border px-3 py-1.5 text-xs font-medium text-base-content hover:bg-surface-hover disabled:cursor-not-allowed disabled:opacity-50 sm:min-h-9 sm:self-auto sm:flex-shrink-0"
+ onClick={() => void state.handleRunDiscoveryRefresh()}
+ disabled={state.saving() || state.discoveryRunRunning()}
+ >
+ <Show
+ when={state.discoveryRunRunning()}
+ fallback={<RefreshCwIcon class="h-3.5 w-3.5" />}
+ >
+ <RefreshCwIcon class="h-3.5 w-3.5 animate-spin" />
+ </Show>
+ {state.discoveryRunRunning() ? 'Running...' : 'Run context scan'}
+ </button>
</div>
- </Show>
- </div>
+ <p class="text-[10px] text-muted">{getAISettingsWorkloadDiscoverySummary().text}</p>
+ </div>
+ </Show>
+ </div>
+ );
+};
+
+export const AIProviderRuntimeControlsSection: Component<AIRuntimeControlsSectionProps> = (
+ props,
+) => {
+ const { state } = props;
+
+ return (
+ <>
<div class="flex items-center gap-3 p-3 rounded-md border border-border bg-surface-alt">
<svg
class="w-4 h-4 text-muted flex-shrink-0"
@@ -233,7 +248,23 @@ export const AIRuntimeControlsSection: Component<AIRuntimeControlsSectionProps>
<p class="text-[10px] text-muted -mt-4 ml-1">
Increase for slower Ollama hardware (default: 300s / 5 min)
</p>
+ </>
+ );
+};
+export const AIAssistantCommandAccessSection: Component<AIRuntimeControlsSectionProps> = (
+ props,
+) => {
+ const { state } = props;
+ const showAutonomousControlOption = () =>
+ !state.autoFixLocked() ||
+ state.showUpgradePrompts() ||
+ state.form.controlLevel === 'autonomous';
+ const assistantCommandAccessBadgeLabel = () =>
+ state.form.controlLevel === 'autonomous' ? 'Allowed' : 'Ask first';
+
+ return (
+ <>
<div
class={`space-y-3 p-4 rounded-md border ${getAIControlLevelPanelClass(state.form.controlLevel)}`}
>
@@ -258,14 +289,18 @@ export const AIRuntimeControlsSection: Component<AIRuntimeControlsSectionProps>
<span
class={`px-1.5 py-0.5 text-[10px] font-medium rounded ${getAIControlLevelBadgeClass(state.form.controlLevel)}`}
>
- {state.form.controlLevel}
+ {assistantCommandAccessBadgeLabel()}
</span>
</Show>
</div>
+ <p class="text-[10px] text-muted">
+ This controls actions started from Assistant chat only. Patrol handles infrastructure
+ work from the Patrol page.
+ </p>
<FormSelect
id="ai-control-mode-select"
- label="Control mode"
+ label="Chat action mode"
value={state.form.controlLevel}
onChange={(e) => state.setForm('controlLevel', e.currentTarget.value as AIControlLevel)}
disabled={state.saving()}
@@ -274,11 +309,11 @@ export const AIRuntimeControlsSection: Component<AIRuntimeControlsSectionProps>
labelClass="text-xs font-medium text-muted w-28 flex-shrink-0"
selectBaseClass="flex-1 min-h-10 sm:min-h-9 px-2 py-2 text-sm border border-border rounded bg-surface"
>
- <option value="read_only">Read-only - Pulse Assistant can observe only</option>
- <option value="controlled">Controlled - Pulse Assistant asks before actions</option>
+ <option value="read_only">Observe only - Assistant cannot take chat actions</option>
+ <option value="controlled">Ask first - Assistant asks before chat-only actions</option>
<Show when={showAutonomousControlOption()}>
<option value="autonomous">
- Autonomous - Pulse Assistant can run eligible actions
+ Allow chat-only actions - Assistant may take eligible chat actions
</option>
</Show>
</FormSelect>
@@ -287,8 +322,9 @@ export const AIRuntimeControlsSection: Component<AIRuntimeControlsSectionProps>
</p>
<Show when={state.form.controlLevel === 'autonomous'}>
<div class="p-2 bg-amber-100 dark:bg-amber-900 rounded border border-amber-200 dark:border-amber-800 text-[10px] text-amber-800 dark:text-amber-200">
- <strong>Legal Disclaimer:</strong> Model-driven systems can hallucinate. You are
- responsible for any damage caused by autonomous actions. See{' '}
+ <strong>Important:</strong> Assistant may take eligible chat-only actions from this
+ mode. Infrastructure changes stay with Patrol mode. Keep protected guests set for
+ anything Assistant must not touch. See{' '}
<ExternalTextLink href={TERMS_DOC_URL} variant="compactInherit">
Terms of Service
</ExternalTextLink>
@@ -309,7 +345,7 @@ export const AIRuntimeControlsSection: Component<AIRuntimeControlsSectionProps>
>
{UPGRADE_ACTION_LABEL}
</UpgradeLink>{' '}
- to review autonomous-mode options.
+ to review eligible chat action options.
</p>
</Show>
@@ -328,8 +364,7 @@ export const AIRuntimeControlsSection: Component<AIRuntimeControlsSectionProps>
disabled={state.saving()}
/>
<p class="text-[10px] text-muted mt-1">
- Comma-separated VMIDs or names that Pulse Assistant cannot control, even when
- command execution is enabled.
+ Comma-separated VMIDs or names Assistant cannot touch when chat actions are allowed.
</p>
</div>
</div>
diff --git a/frontend-modern/src/components/Settings/AISettings.tsx b/frontend-modern/src/components/Settings/AISettings.tsx
index a243bf13b0..af31ee292c 100644
--- a/frontend-modern/src/components/Settings/AISettings.tsx
+++ b/frontend-modern/src/components/Settings/AISettings.tsx
@@ -2,10 +2,19 @@ import { Component, Show } from 'solid-js';
import { useNavigate } from '@solidjs/router';
import { AIChatMaintenanceSection } from '@/components/Settings/AIChatMaintenanceSection';
import { AISettingsDialogs } from '@/components/Settings/AISettingsDialogs';
-import { AIModelSelectionSection } from '@/components/Settings/AIModelSelectionSection';
-import { AIRuntimeControlsSection } from '@/components/Settings/AIRuntimeControlsSection';
+import AgentIntegrationsPanel from '@/components/Settings/AgentIntegrationsPanel';
+import {
+ AIModelOverrideField,
+ AIModelSelectionSection,
+} from '@/components/Settings/AIModelSelectionSection';
+import {
+ AIAssistantCommandAccessSection,
+ AIDiscoveryControlsSection,
+ AIProviderRuntimeControlsSection,
+} from '@/components/Settings/AIRuntimeControlsSection';
import { AISettingsStatusAndActions } from '@/components/Settings/AISettingsStatusAndActions';
import { useAISettingsState } from '@/components/Settings/useAISettingsState';
+import { FormSelect } from '@/components/shared/FormSelect';
import { LoadingSpinner } from '@/components/shared/LoadingSpinner';
import SettingsPanel from '@/components/shared/SettingsPanel';
import { Toggle } from '@/components/shared/Toggle';
@@ -17,119 +26,367 @@ import {
getAISettingsRetryLabel,
} from '@/utils/aiSettingsPresentation';
-export const AISettings: Component = () => {
+type AISettingsPage = 'provider' | 'patrol' | 'assistant' | 'discovery';
+
+const AI_SETTINGS_PAGE_META: Record<
+ AISettingsPage,
+ {
+ resetLabel: string;
+ saveErrorFallback: string;
+ savedLabel: string;
+ saveLabel: string;
+ savingLabel: string;
+ title: string;
+ }
+> = {
+ provider: {
+ resetLabel: 'Reset provider settings',
+ saveErrorFallback: 'Unable to save Provider & Models settings.',
+ savedLabel: 'Provider & Models settings saved',
+ saveLabel: 'Save provider settings',
+ savingLabel: 'Saving provider settings...',
+ title: AI_SETTINGS_PANEL_TITLE,
+ },
+ patrol: {
+ resetLabel: 'Reset Patrol settings',
+ saveErrorFallback: 'Unable to save Patrol settings.',
+ savedLabel: 'Patrol settings saved',
+ saveLabel: 'Save Patrol settings',
+ savingLabel: 'Saving Patrol settings...',
+ title: 'Patrol',
+ },
+ assistant: {
+ resetLabel: 'Reset Assistant settings',
+ saveErrorFallback: 'Unable to save Assistant settings.',
+ savedLabel: 'Assistant settings saved',
+ saveLabel: 'Save Assistant settings',
+ savingLabel: 'Saving Assistant settings...',
+ title: 'Assistant',
+ },
+ discovery: {
+ resetLabel: 'Reset service context settings',
+ saveErrorFallback: 'Unable to save service context settings.',
+ savedLabel: 'Service context settings saved',
+ saveLabel: 'Save service context settings',
+ savingLabel: 'Saving service context settings...',
+ title: 'Service Context',
+ },
+};
+
+const formatPatrolInterval = (minutes: number): string => {
+ if (minutes <= 0) return 'Manual only';
+ if (minutes < 60) return `Every ${minutes} minute${minutes === 1 ? '' : 's'}`;
+ const hours = Math.round(minutes / 60);
+ return `Every ${hours} hour${hours === 1 ? '' : 's'}`;
+};
+
+const ProviderSettingsContent: Component<{ state: ReturnType<typeof useAISettingsState> }> = (
+ props,
+) => (
+ <div class="space-y-6 p-4 sm:p-6">
+ <AIModelSelectionSection state={props.state} />
+ <AIProviderRuntimeControlsSection state={props.state} />
+ </div>
+);
+
+const PatrolSettingsContent: Component<{ state: ReturnType<typeof useAISettingsState> }> = (
+ props,
+) => {
const navigate = useNavigate();
- const state = useAISettingsState();
+ const intervalOptions = [
+ { value: 0, label: 'Manual only' },
+ { value: 60, label: 'Every hour' },
+ { value: 180, label: 'Every 3 hours' },
+ { value: 360, label: 'Every 6 hours' },
+ { value: 720, label: 'Every 12 hours' },
+ { value: 1440, label: 'Daily' },
+ ];
return (
- <>
- <SettingsPanel
- title={AI_SETTINGS_PANEL_TITLE}
- action={(() => {
- return (
- <Toggle
- checked={state.form.enabled}
- onChange={async (event) => {
- const newValue = event.currentTarget.checked;
- await state.handleEnableRequest(newValue);
- }}
- disabled={state.loading() || state.saving() || state.loadError()}
- containerClass="items-center gap-2"
- ariaLabel="Enable Assistant and Patrol"
- label={
- <span class="text-xs font-medium text-muted">
- {state.form.enabled ? 'Enabled' : 'Disabled'}
- </span>
- }
- />
- );
- })()}
- noPadding
- >
- <form class="divide-y divide-border" onSubmit={state.handleSave}>
- <Show when={state.loading()}>
- <div class="flex items-center gap-3 text-sm text-muted p-4 sm:p-6">
- <LoadingSpinner size="md" tone="current" />
- {getAISettingsLoadingState().text}
- </div>
- </Show>
+ <div class="space-y-6 p-4 sm:p-6">
+ <div class="rounded-md border border-border bg-surface-alt p-4">
+ <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div>
+ <h3 class="text-sm font-semibold text-base-content">Patrol mode</h3>
+ <p class="mt-1 text-xs text-muted">
+ Choose a Patrol mode on the Patrol page. Keep schedule, triggers, and model readiness
+ here.
+ </p>
+ </div>
+ <button
+ type="button"
+ class="inline-flex min-h-10 items-center justify-center rounded-md border border-blue-300 px-3 py-2 text-sm font-medium text-blue-700 hover:bg-blue-50 dark:border-blue-700 dark:text-blue-300 dark:hover:bg-blue-900 sm:min-h-9"
+ onClick={() => navigate(PATROL_PATH)}
+ >
+ Open Patrol
+ </button>
+ </div>
+ </div>
- <Show when={!state.loading() && state.loadError()}>
- <div
- role="alert"
- aria-live="assertive"
- class="flex items-center justify-between gap-3 p-4 sm:p-6 bg-red-50 dark:bg-red-900/30 border-b border-red-200 dark:border-red-800"
- >
- <div class="flex items-center gap-2 text-sm text-red-700 dark:text-red-300">
- <svg
- class="h-4 w-4 flex-shrink-0"
- fill="none"
- viewBox="0 0 24 24"
- stroke="currentColor"
- stroke-width="2"
- >
- <path
- stroke-linecap="round"
- stroke-linejoin="round"
- d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
- />
- </svg>
- <span>{getAISettingsLoadErrorMessage()}</span>
+ <div class="grid gap-4 lg:grid-cols-2">
+ <FormSelect
+ id="ai-patrol-schedule"
+ label="Schedule"
+ value={String(props.state.form.patrolIntervalMinutes)}
+ onChange={(event) =>
+ props.state.setForm('patrolIntervalMinutes', parseInt(event.currentTarget.value, 10))
+ }
+ disabled={props.state.saving()}
+ fieldClass="gap-2"
+ labelClass="text-xs font-medium text-muted"
+ selectBaseClass="w-full min-h-10 rounded-md border border-border bg-surface px-3 py-2 text-sm"
+ >
+ {intervalOptions.map((option) => (
+ <option value={option.value}>{option.label}</option>
+ ))}
+ </FormSelect>
+
+ <div class="rounded-md border border-border bg-surface-alt p-3">
+ <p class="text-xs font-medium text-base-content">Current schedule</p>
+ <p class="mt-1 text-sm text-muted">
+ {formatPatrolInterval(props.state.form.patrolIntervalMinutes)}
+ </p>
+ </div>
+ </div>
+
+ <div class="space-y-3">
+ <h3 class="text-sm font-semibold text-base-content">Triggers</h3>
+
+ <div class="grid gap-3 lg:grid-cols-2">
+ <div class="rounded-md border border-border bg-surface-alt p-3">
+ <div class="flex items-center justify-between gap-3">
+ <div>
+ <p class="text-sm font-medium text-base-content">Alert-triggered Patrols</p>
+ <p class="mt-1 text-xs text-muted">Start Patrol when alerts fire or clear.</p>
</div>
- <button
- type="button"
- class="flex-shrink-0 px-3 py-1.5 text-sm font-medium text-red-700 dark:text-red-300 border border-red-300 dark:border-red-700 rounded-md hover:bg-red-100 dark:hover:bg-red-900/50"
- onClick={() => state.loadSettings()}
+ <Toggle
+ checked={props.state.form.patrolAlertTriggers}
+ onChange={(event) =>
+ props.state.setForm('patrolAlertTriggers', event.currentTarget.checked)
+ }
+ disabled={props.state.saving()}
+ ariaLabel="Enable alert-triggered Patrols"
+ />
+ </div>
+
+ <Show when={props.state.form.patrolAlertTriggers}>
+ <FormSelect
+ id="ai-patrol-alert-min-severity"
+ label="Investigate alerts at or above"
+ value={props.state.form.patrolAlertTriggerMinSeverity}
+ onChange={(event) =>
+ props.state.setForm(
+ 'patrolAlertTriggerMinSeverity',
+ event.currentTarget.value === 'warning' ? 'warning' : 'critical',
+ )
+ }
+ disabled={props.state.saving()}
+ fieldClass="mt-3 gap-2"
+ labelClass="text-xs font-medium text-muted"
+ selectBaseClass="w-full min-h-10 rounded-md border border-border bg-surface px-3 py-2 text-sm"
>
- {getAISettingsRetryLabel()}
- </button>
+ <option value="critical">Critical only</option>
+ <option value="warning">Warning and critical</option>
+ </FormSelect>
+ </Show>
+ </div>
+
+ <div class="rounded-md border border-border bg-surface-alt p-3">
+ <div class="flex items-center justify-between gap-3">
+ <div>
+ <p class="text-sm font-medium text-base-content">Anomaly-triggered Patrols</p>
+ <p class="mt-1 text-xs text-muted">Start Patrol from learned baseline changes.</p>
+ </div>
+ <Toggle
+ checked={props.state.form.patrolAnomalyTriggers}
+ onChange={(event) =>
+ props.state.setForm('patrolAnomalyTriggers', event.currentTarget.checked)
+ }
+ disabled={props.state.saving()}
+ ariaLabel="Enable anomaly-triggered Patrols"
+ />
+ </div>
+ </div>
+
+ <div class="rounded-md border border-border bg-surface-alt p-3 lg:col-span-2">
+ <div class="flex items-center justify-between gap-3">
+ <div>
+ <p class="text-sm font-medium text-base-content">Container update risk</p>
+ <p class="mt-1 text-xs text-muted">
+ Assess risk when container-update alerts fire.
+ </p>
+ </div>
+ <Toggle
+ checked={props.state.form.alertTriggeredAnalysis}
+ onChange={(event) =>
+ props.state.setForm('alertTriggeredAnalysis', event.currentTarget.checked)
+ }
+ disabled={props.state.saving() || props.state.alertAnalysisLocked()}
+ ariaLabel="Enable container update risk analysis"
+ />
</div>
+ </div>
+ </div>
+ </div>
+
+ <div class="space-y-3">
+ <h3 class="text-sm font-semibold text-base-content">Model readiness</h3>
+ <AIModelOverrideField state={props.state} kind="patrol" includePatrolPreflight />
+ </div>
+ </div>
+ );
+};
+
+const AssistantSettingsContent: Component<{ state: ReturnType<typeof useAISettingsState> }> = (
+ props,
+) => (
+ <div class="space-y-6 p-4 sm:p-6">
+ <AIModelOverrideField state={props.state} kind="assistant" />
+ <AIAssistantCommandAccessSection state={props.state} />
+ <AIChatMaintenanceSection state={props.state} />
+ </div>
+);
+
+const DiscoverySettingsContent: Component<{ state: ReturnType<typeof useAISettingsState> }> = (
+ props,
+) => (
+ <div class="space-y-6 p-4 sm:p-6">
+ <div class="rounded-md border border-border bg-surface-alt p-4">
+ <h3 class="text-sm font-semibold text-base-content">Service context</h3>
+ <p class="mt-1 text-xs text-muted">
+ These settings control the service facts Assistant and Patrol can use. Normal infrastructure
+ discovery and onboarding stay under Infrastructure.
+ </p>
+ </div>
+ <AIModelOverrideField state={props.state} kind="discovery" />
+ <AIDiscoveryControlsSection state={props.state} />
+ </div>
+);
+
+const AISettingsPageContent: Component<{
+ page: AISettingsPage;
+ state: ReturnType<typeof useAISettingsState>;
+}> = (props) => (
+ <Show
+ when={props.page === 'provider'}
+ fallback={
+ <Show
+ when={props.page === 'patrol'}
+ fallback={
+ <Show
+ when={props.page === 'assistant'}
+ fallback={<DiscoverySettingsContent state={props.state} />}
+ >
+ <AssistantSettingsContent state={props.state} />
</Show>
+ }
+ >
+ <PatrolSettingsContent state={props.state} />
+ </Show>
+ }
+ >
+ <ProviderSettingsContent state={props.state} />
+ </Show>
+);
+
+export const AISettings: Component<{ page?: AISettingsPage }> = (props) => {
+ const page = () => props.page ?? 'provider';
+ const pageMeta = () => AI_SETTINGS_PAGE_META[page()];
+ const state = useAISettingsState({
+ get saveErrorFallback() {
+ return pageMeta().saveErrorFallback;
+ },
+ get savedLabel() {
+ return pageMeta().savedLabel;
+ },
+ });
+ const isProviderPage = () => page() === 'provider';
+ const showExternalAgentAccess = () => page() === 'assistant';
+
+ return (
+ <>
+ <div class="space-y-6">
+ <SettingsPanel
+ title={pageMeta().title}
+ action={
+ isProviderPage() ? (
+ <Toggle
+ checked={state.form.enabled}
+ onChange={async (event) => {
+ const newValue = event.currentTarget.checked;
+ await state.handleEnableRequest(newValue);
+ }}
+ disabled={state.loading() || state.saving() || state.loadError()}
+ containerClass="items-center gap-2"
+ ariaLabel="Enable Pulse Intelligence"
+ label={
+ <span class="text-xs font-medium text-muted">
+ {state.form.enabled ? 'Enabled' : 'Disabled'}
+ </span>
+ }
+ />
+ ) : undefined
+ }
+ noPadding
+ >
+ <form class="divide-y divide-border" onSubmit={state.handleSave}>
+ <Show when={state.loading()}>
+ <div class="flex items-center gap-3 text-sm text-muted p-4 sm:p-6">
+ <LoadingSpinner size="md" tone="current" />
+ {getAISettingsLoadingState().text}
+ </div>
+ </Show>
- <Show when={!state.loading() && !state.loadError()}>
- <Show when={state.form.enabled}>
- <div class="p-4 sm:p-6">
- <div class="flex items-start gap-2 text-xs text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900 border border-blue-200 dark:border-blue-800 rounded-md p-3">
+ <Show when={!state.loading() && state.loadError()}>
+ <div
+ role="alert"
+ aria-live="assertive"
+ class="flex items-center justify-between gap-3 p-4 sm:p-6 bg-red-50 dark:bg-red-900/30 border-b border-red-200 dark:border-red-800"
+ >
+ <div class="flex items-center gap-2 text-sm text-red-700 dark:text-red-300">
<svg
- class="w-4 h-4 mt-0.5 shrink-0"
+ class="h-4 w-4 flex-shrink-0"
fill="none"
- stroke="currentColor"
viewBox="0 0 24 24"
+ stroke="currentColor"
+ stroke-width="2"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
- stroke-width="2"
- d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
+ d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
/>
</svg>
- <span>
- Patrol runs automatically every{' '}
- {state.form.patrolIntervalMinutes >= 60
- ? `${Math.round(state.form.patrolIntervalMinutes / 60)} hour${Math.round(state.form.patrolIntervalMinutes / 60) === 1 ? '' : 's'}`
- : `${state.form.patrolIntervalMinutes} minute${state.form.patrolIntervalMinutes === 1 ? '' : 's'}`}{' '}
- to verify your infrastructure continuously.{' '}
- <button
- type="button"
- class="inline-flex min-h-10 sm:min-h-9 items-center rounded-md px-1 py-1 text-sm underline hover:text-blue-800 dark:hover:text-blue-300"
- onClick={() => navigate(PATROL_PATH)}
- >
- Configure schedule & autonomy
- </button>
- </span>
+ <span>{getAISettingsLoadErrorMessage()}</span>
</div>
+ <button
+ type="button"
+ class="flex-shrink-0 px-3 py-1.5 text-sm font-medium text-red-700 dark:text-red-300 border border-red-300 dark:border-red-700 rounded-md hover:bg-red-100 dark:hover:bg-red-900/50"
+ onClick={() => state.loadSettings()}
+ >
+ {getAISettingsRetryLabel()}
+ </button>
</div>
</Show>
- <div class="space-y-6 p-4 sm:p-6">
- <AIModelSelectionSection state={state} />
- <AIRuntimeControlsSection state={state} />
- <AIChatMaintenanceSection state={state} />
- </div>
- <AISettingsStatusAndActions state={state} />
- </Show>
- </form>
- </SettingsPanel>
+ <Show when={!state.loading() && !state.loadError()}>
+ <AISettingsPageContent page={page()} state={state} />
+
+ <AISettingsStatusAndActions
+ resetLabel={pageMeta().resetLabel}
+ saveLabel={pageMeta().saveLabel}
+ savingLabel={pageMeta().savingLabel}
+ state={state}
+ showConnectionControls={isProviderPage()}
+ />
+ </Show>
+ </form>
+ </SettingsPanel>
+
+ <Show when={showExternalAgentAccess()}>
+ <AgentIntegrationsPanel />
+ </Show>
+ </div>
<AISettingsDialogs
showSetupModal={state.showSetupModal}
@@ -147,4 +404,8 @@ export const AISettings: Component = () => {
);
};
+export const AIPatrolSettings: Component = () => <AISettings page="patrol" />;
+export const AIAssistantSettings: Component = () => <AISettings page="assistant" />;
+export const AIDiscoverySettings: Component = () => <AISettings page="discovery" />;
+
export default AISettings;
diff --git a/frontend-modern/src/components/Settings/AISettingsStatusAndActions.tsx b/frontend-modern/src/components/Settings/AISettingsStatusAndActions.tsx
index 260e6d7ab5..a569fbcefa 100644
--- a/frontend-modern/src/components/Settings/AISettingsStatusAndActions.tsx
+++ b/frontend-modern/src/components/Settings/AISettingsStatusAndActions.tsx
@@ -3,7 +3,11 @@ import type { AISettingsState } from '@/components/Settings/useAISettingsState';
import { formatAIModelRouteLabel } from '@/utils/aiProviderPresentation';
interface AISettingsStatusAndActionsProps {
+ resetLabel?: string;
+ saveLabel?: string;
+ savingLabel?: string;
state: AISettingsState;
+ showConnectionControls?: boolean;
}
export const AISettingsStatusAndActions: Component<AISettingsStatusAndActionsProps> = (props) => {
@@ -19,7 +23,7 @@ export const AISettingsStatusAndActions: Component<AISettingsStatusAndActionsPro
return (
<>
- <Show when={state.settings()}>
+ <Show when={props.showConnectionControls && state.settings()}>
<div class="p-4 sm:p-6">
<div
class={`flex items-center gap-2 p-3 rounded-md ${state.settingsReadiness().containerClassName}`}
@@ -38,7 +42,7 @@ export const AISettingsStatusAndActions: Component<AISettingsStatusAndActionsPro
</Show>
<div class="sticky bottom-0 bg-surface px-4 sm:px-6 py-4 flex flex-col sm:flex-row sm:flex-wrap sm:items-center sm:justify-between gap-3">
- <Show when={state.settings()?.configured}>
+ <Show when={props.showConnectionControls && state.settings()?.configured}>
<button
type="button"
class="w-full sm:w-auto min-h-10 sm:min-h-9 px-4 py-2.5 text-sm border border-blue-300 dark:border-blue-700 text-blue-700 dark:text-blue-300 rounded-md hover:bg-blue-50 dark:hover:bg-blue-900 disabled:opacity-50 disabled:cursor-not-allowed"
@@ -55,14 +59,16 @@ export const AISettingsStatusAndActions: Component<AISettingsStatusAndActionsPro
onClick={() => state.resetForm(state.settings())}
disabled={state.saving() || state.loading()}
>
- Reset
+ {props.resetLabel ?? 'Reset'}
</button>
<button
type="submit"
class="w-full sm:w-auto min-h-10 sm:min-h-9 px-4 py-2.5 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
disabled={state.saving() || state.loading()}
>
- {state.saving() ? 'Saving...' : 'Save changes'}
+ {state.saving()
+ ? (props.savingLabel ?? 'Saving...')
+ : (props.saveLabel ?? 'Save changes')}
</button>
</div>
</div>
diff --git a/frontend-modern/src/components/Settings/APIAccessPanel.tsx b/frontend-modern/src/components/Settings/APIAccessPanel.tsx
index 6147d5ff3a..6facb4bcaf 100644
--- a/frontend-modern/src/components/Settings/APIAccessPanel.tsx
+++ b/frontend-modern/src/components/Settings/APIAccessPanel.tsx
@@ -4,7 +4,6 @@ import { ButtonLink } from '@/components/shared/Button';
import { API_TOKEN_ACCESS_PANEL_DESCRIPTION } from '@/utils/apiTokenPresentation';
import { API_TOKEN_SCOPES_DOC_URL } from '@/utils/docsLinks';
import APITokenManager from './APITokenManager';
-import AgentIntegrationsPanel from './AgentIntegrationsPanel';
interface APIAccessPanelProps {
currentTokenHint?: string;
@@ -31,14 +30,14 @@ export const APIAccessPanel: Component<APIAccessPanelProps> = (props) => {
</div>
</SettingsPanel>
- <APITokenManager
- currentTokenHint={props.currentTokenHint}
- onTokensChanged={props.onTokensChanged}
- refreshing={props.refreshing}
- canManage={props.canManage}
- />
-
- <AgentIntegrationsPanel />
+ <div data-testid="api-access-token-section">
+ <APITokenManager
+ currentTokenHint={props.currentTokenHint}
+ onTokensChanged={props.onTokensChanged}
+ refreshing={props.refreshing}
+ canManage={props.canManage}
+ />
+ </div>
</div>
);
};
diff --git a/frontend-modern/src/components/Settings/APITokenManager.tsx b/frontend-modern/src/components/Settings/APITokenManager.tsx
index 9f16def4e4..91fbf8eb2f 100644
--- a/frontend-modern/src/components/Settings/APITokenManager.tsx
+++ b/frontend-modern/src/components/Settings/APITokenManager.tsx
@@ -13,6 +13,7 @@ import {
getAPITokenDockerPodmanUsageSummary,
getAPITokenDockerPodmanUsageTitle,
} from '@/utils/apiTokenPresentation';
+import { API_TOKEN_CREATE_ANCHOR } from '@/routing/resourceLinks';
import { useAPITokenManagerState } from './useAPITokenManagerState';
import type { APITokenRecord } from '@/types/api';
@@ -29,8 +30,10 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
API_SCOPE_LABELS,
API_TOKEN_SCOPES_DOC_URL,
agentTokenUsage,
+ applyFullAccessPreset,
applyScopePreset,
canManage,
+ canGenerateToken,
clearScopes,
copyNewMonitoringKioskLink,
createHighlight,
@@ -41,6 +44,7 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
handleDelete,
handleGenerate,
hasWildcardTokens,
+ hasScopeSelection,
isFullAccessSelected,
isGenerating,
isRevealActiveForCurrentToken,
@@ -406,6 +410,7 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
</Show>
<Card
+ id={API_TOKEN_CREATE_ANCHOR}
padding="none"
class={`border border-border transition-shadow ${
createHighlight() ? 'ring-2 ring-blue-500 shadow-sm' : ''
@@ -422,7 +427,12 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
/>
<button
onClick={handleGenerate}
- disabled={!canManage() || isGenerating()}
+ disabled={!canGenerateToken()}
+ title={
+ hasScopeSelection()
+ ? undefined
+ : 'Choose a scope preset or custom scope before generating a token.'
+ }
class="inline-flex min-h-10 sm:min-h-10 items-center justify-center rounded-md bg-blue-600 px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-60 dark:bg-blue-500 dark:hover:bg-blue-400"
>
{isGenerating() ? 'Generating…' : 'Generate'}
@@ -463,14 +473,14 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
<div class="flex flex-wrap gap-2">
<SelectablePillButton
active={isFullAccessSelected()}
- onClick={clearScopes}
+ onClick={applyFullAccessPreset}
disabled={!canManage()}
title="Legacy wildcard – all permissions"
>
Full access
</SelectablePillButton>
- <For each={scopePresets}>
+ <For each={scopePresets()}>
{(preset) => (
<SelectablePillButton
active={presetMatchesSelection(preset.scopes)}
@@ -483,6 +493,11 @@ export const APITokenManager: Component<APITokenManagerProps> = (props) => {
)}
</For>
</div>
+ <Show when={!hasScopeSelection()}>
+ <p class="text-xs text-muted">
+ Choose a scoped preset for least privilege, or deliberately choose Full access.
+ </p>
+ </Show>
</div>
<details class="group rounded-md border border-border bg-surface-hover p-4 text-sm transition">
diff --git a/frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx b/frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx
index 42f6192ab5..9a15c3e94d 100644
--- a/frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx
+++ b/frontend-modern/src/components/Settings/AgentIntegrationsPanel.tsx
@@ -1,87 +1,45 @@
-import { Component, createMemo, createResource, createSignal, For, Show } from 'solid-js';
+import {
+ Component,
+ createEffect,
+ createMemo,
+ createResource,
+ createSignal,
+ For,
+ onCleanup,
+ onMount,
+ Show,
+} from 'solid-js';
+import {
+ AGENT_MCP_TOKEN_PLACEHOLDER,
+ AGENT_SURFACE_ID_PULSE_MCP,
+ AGENT_WORKFLOW_PROMPT_OPERATIONS_LOOP,
+ fetchAgentCapabilitiesManifest,
+ formatAgentMCPServersConfig,
+ formatAgentOpenCodeMCPConfig,
+ getAgentCapabilityErrorCodeSummaries,
+ getAgentWorkflowPrompts,
+ getAgentManifestSurfaceToolContract,
+ getAgentMCPConfigFamilyByShape,
+ getAgentSurfaceToolPosturePresentation,
+ getAgentSurfaceContractEntries,
+ groupAgentCapabilitiesByManifestCategories,
+ normalizeAgentMCPAdapter,
+} from '@/api/agentCapabilities';
+import { Button, ButtonLink } from '@/components/shared/Button';
import { ExternalTextLink } from '@/components/shared/ExternalTextLink';
import SettingsPanel from '@/components/shared/SettingsPanel';
+import {
+ EXTERNAL_AGENT_SETUP_ANCHOR,
+ PATROL_CONTROL_PATH,
+ isExternalAgentSetupHash,
+ PULSE_MCP_SETUP_ANCHOR,
+ PULSE_MCP_TOKEN_SETUP_PATH,
+} from '@/routing/resourceLinks';
import { AGENT_SUBSTRATE_DOC_URL } from '@/utils/docsLinks';
+import KeyRoundIcon from 'lucide-solid/icons/key-round';
+import SettingsIcon from 'lucide-solid/icons/settings';
import CopyCommandBlock from './CopyCommandBlock';
-
-// AgentCapability mirrors the wire shape of one entry in
-// /api/agent/capabilities. Defined inline so this component does
-// not depend on a shared API client; the manifest endpoint is
-// public and stable.
-interface AgentCapability {
- name: string;
- description: string;
- category: string;
- method: string;
- path: string;
- scope: string;
- responseShape?: string;
- errorCodes?: string[];
- requestBodyShape?: string;
-}
-
-interface AgentCapabilitiesManifest {
- version: string;
- capabilities: AgentCapability[];
-}
-
-// Category presentation order on screen. Matches the closed set
-// the backend pin enforces (see TestAgentCapabilitiesManifest_
-// CategoriesAreClosed). Capabilities with an unknown category are
-// rendered last under a generic "other" heading so a future
-// addition that the panel does not yet know about still renders.
-const CATEGORY_ORDER: ReadonlyArray<{ id: string; label: string; description: string }> = [
- {
- id: 'context',
- label: 'Context',
- description: 'Discovery and read-only situated reads. Agents start here.',
- },
- {
- id: 'operator-state',
- label: 'Operator state',
- description:
- 'Per-resource intent: intentionally-offline, never-auto-remediate, maintenance windows.',
- },
- {
- id: 'finding',
- label: 'Patrol findings',
- description: 'Acknowledge, snooze, dismiss, or resolve findings the patrol runtime raised.',
- },
- {
- id: 'action',
- label: 'Action governance',
- description: 'Plan, approve, and execute capability invocations against a resource.',
- },
-];
-
-async function fetchManifest(): Promise<AgentCapabilitiesManifest> {
- const response = await fetch('/api/agent/capabilities', {
- headers: { Accept: 'application/json' },
- });
- if (!response.ok) {
- throw new Error(`manifest fetch failed: ${response.status}`);
- }
- return (await response.json()) as AgentCapabilitiesManifest;
-}
-
-// formatMcpConfig builds the JSON snippet an integrator drops into
-// claude_desktop_config.json (or .mcp.json for Claude Code). The
-// host is the deployment's own origin so the snippet is correct
-// for whatever URL the operator is reading the panel from.
-function formatMcpConfig(origin: string): string {
- const config = {
- mcpServers: {
- pulse: {
- command: 'pulse-mcp',
- args: ['--base-url', origin],
- env: {
- PULSE_API_TOKEN: '<your-api-token>',
- },
- },
- },
- };
- return JSON.stringify(config, null, 2);
-}
+import { API_TOKEN_PATROL_EXTERNAL_AGENT_PRESET_LABEL } from './apiTokenManagerModel';
// All three external resources (the MCP adapter README, the agent-probe HTTP
// example, the substrate design notes) are consolidated under the shipped
@@ -89,182 +47,611 @@ function formatMcpConfig(origin: string): string {
// frontend-runtime links pointing at unpinned GitHub main paths.
export const AgentIntegrationsPanel: Component = () => {
- const [manifest] = createResource(fetchManifest);
+ const [manifest] = createResource(fetchAgentCapabilitiesManifest);
const [copied, setCopied] = createSignal<string | null>(null);
+ const [routeHash, setRouteHash] = createSignal('');
+ const [panelHighlight, setPanelHighlight] = createSignal(false);
+ const [installerCommandsOpen, setInstallerCommandsOpen] = createSignal(false);
+ const [clientConfigOpen, setClientConfigOpen] = createSignal(false);
+ const [advancedClientDetailsOpen, setAdvancedClientDetailsOpen] = createSignal(false);
+ const [setupOpen, setSetupOpen] = createSignal(false);
const origin = typeof window !== 'undefined' ? window.location.origin : 'http://localhost:7655';
- const mcpConfig = formatMcpConfig(origin);
+ const mcpInstallShellCommand =
+ 'curl -fsSL https://github.com/rcourtman/Pulse/releases/latest/download/install-mcp.sh | bash';
+ const mcpInstallPowerShellCommand =
+ 'irm https://github.com/rcourtman/Pulse/releases/latest/download/install-mcp.ps1 | iex';
+ let highlightTimer: number | undefined;
+ let routeFocusTimer: number | undefined;
+ const mcpAdapter = createMemo(() => normalizeAgentMCPAdapter(manifest()?.mcpAdapter));
+ const openCodeConfigFamily = createMemo(() =>
+ getAgentMCPConfigFamilyByShape(mcpAdapter(), 'opencode_mcp'),
+ );
+ const mcpServersConfigFamily = createMemo(() =>
+ getAgentMCPConfigFamilyByShape(mcpAdapter(), 'mcp_servers'),
+ );
+ const claudeMcpConfig = createMemo(() => formatAgentMCPServersConfig(mcpAdapter(), origin));
+ const openCodeMcpConfig = createMemo(() => formatAgentOpenCodeMCPConfig(mcpAdapter(), origin));
+ const requiredScopes = createMemo(() =>
+ (manifest()?.requiredScopes ?? []).map((scope) => scope.trim()).filter(Boolean),
+ );
+ const surfaceContractEntries = createMemo(() => getAgentSurfaceContractEntries(manifest()));
+ const workflowPrompts = createMemo(() => getAgentWorkflowPrompts(manifest()));
+ const mcpSurfaceToolPosture = createMemo(() =>
+ getAgentSurfaceToolPosturePresentation(
+ getAgentManifestSurfaceToolContract(manifest(), AGENT_SURFACE_ID_PULSE_MCP),
+ ),
+ );
+ const errorCodeSummaries = createMemo(() => getAgentCapabilityErrorCodeSummaries(manifest()));
+ const grouped = createMemo(() => groupAgentCapabilitiesByManifestCategories(manifest()));
+ const hasManifestInventory = createMemo(
+ () =>
+ workflowPrompts().length > 0 ||
+ requiredScopes().length > 0 ||
+ errorCodeSummaries().length > 0 ||
+ Boolean(manifest() && grouped().length > 0),
+ );
+ const hasClientBuilderDetails = createMemo(
+ () => surfaceContractEntries().length > 0 || hasManifestInventory(),
+ );
- const grouped = createMemo(() => {
- const m = manifest();
- if (!m) return [];
- // Index capabilities by category, then return them in
- // CATEGORY_ORDER. Unknown categories spill into a generic
- // "other" bucket so the panel never silently drops a
- // capability the operator should be able to see.
- const byCategory = new Map<string, AgentCapability[]>();
- for (const cap of m.capabilities) {
- const list = byCategory.get(cap.category) ?? [];
- list.push(cap);
- byCategory.set(cap.category, list);
- }
- const sections: Array<{
- id: string;
- label: string;
- description?: string;
- entries: AgentCapability[];
- }> = [];
- for (const known of CATEGORY_ORDER) {
- const entries = byCategory.get(known.id);
- if (entries && entries.length > 0) {
- sections.push({
- id: known.id,
- label: known.label,
- description: known.description,
- entries,
- });
- byCategory.delete(known.id);
+ const handleCopySnippet = (snippet: string) => {
+ setCopied(snippet);
+ window.setTimeout(() => setCopied(null), 2000);
+ };
+
+ const readRouteHash = () => (typeof window === 'undefined' ? '' : window.location.hash);
+
+ const getPanelElement = () =>
+ typeof document === 'undefined'
+ ? null
+ : (document.getElementById(EXTERNAL_AGENT_SETUP_ANCHOR) as HTMLElement | null);
+
+ const findScrollableAncestor = (element: HTMLElement): HTMLElement | null => {
+ let current = element.parentElement;
+ while (current) {
+ const style = window.getComputedStyle(current);
+ const canScroll =
+ (style.overflowY === 'auto' || style.overflowY === 'scroll') &&
+ current.scrollHeight > current.clientHeight;
+ if (canScroll) {
+ return current;
}
+ current = current.parentElement;
+ }
+ return null;
+ };
+
+ const focusPanel = (): boolean => {
+ const panelElement = getPanelElement();
+ if (!panelElement) return false;
+ if (typeof panelElement.scrollIntoView === 'function') {
+ panelElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
- for (const [unknownCategory, entries] of byCategory) {
- sections.push({ id: unknownCategory, label: unknownCategory, entries });
+ const scrollParent = findScrollableAncestor(panelElement);
+ if (scrollParent && typeof scrollParent.scrollTo === 'function') {
+ const parentRect = scrollParent.getBoundingClientRect();
+ const panelRect = panelElement.getBoundingClientRect();
+ scrollParent.scrollTo({
+ top: Math.max(0, scrollParent.scrollTop + panelRect.top - parentRect.top - 16),
+ behavior: 'smooth',
+ });
}
- return sections;
- });
+ setPanelHighlight(true);
+ window.clearTimeout(highlightTimer);
+ highlightTimer = window.setTimeout(() => setPanelHighlight(false), 1600);
+ const panelRect = panelElement.getBoundingClientRect();
+ return panelRect.top >= 0 && panelRect.top < 220;
+ };
- const handleCopySnippet = async (snippet: string) => {
- await navigator.clipboard.writeText(snippet);
- setCopied(snippet);
- window.setTimeout(() => setCopied(null), 2000);
+ const focusPanelUntilLayoutSettles = (hash: string, attempt = 0) => {
+ if (readRouteHash() !== hash) return;
+ const panelReached = focusPanel();
+ if (panelReached || attempt >= 8) return;
+ window.clearTimeout(routeFocusTimer);
+ routeFocusTimer = window.setTimeout(
+ () => focusPanelUntilLayoutSettles(hash, attempt + 1),
+ attempt < 2 ? 100 : 250,
+ );
};
+ onMount(() => {
+ const updateRouteHash = () => setRouteHash(readRouteHash());
+ updateRouteHash();
+ window.addEventListener('hashchange', updateRouteHash);
+ window.addEventListener('popstate', updateRouteHash);
+ onCleanup(() => {
+ window.removeEventListener('hashchange', updateRouteHash);
+ window.removeEventListener('popstate', updateRouteHash);
+ });
+ });
+
+ onCleanup(() => {
+ if (highlightTimer) window.clearTimeout(highlightTimer);
+ if (routeFocusTimer) window.clearTimeout(routeFocusTimer);
+ });
+
+ createEffect(() => {
+ const hash = routeHash();
+ if (!isExternalAgentSetupHash(hash) || !getPanelElement()) {
+ return;
+ }
+
+ setSetupOpen(true);
+ window.clearTimeout(routeFocusTimer);
+ const canonicalHash = `#${EXTERNAL_AGENT_SETUP_ANCHOR}`;
+ if (hash === `#${PULSE_MCP_SETUP_ANCHOR}` && window.location.hash === hash) {
+ window.history.replaceState(
+ window.history.state,
+ '',
+ `${window.location.pathname}${window.location.search}${canonicalHash}`,
+ );
+ setRouteHash(canonicalHash);
+ focusPanelUntilLayoutSettles(canonicalHash);
+ return;
+ }
+
+ focusPanelUntilLayoutSettles(hash);
+ });
+
return (
- <SettingsPanel title="Agent integrations" noPadding>
+ <SettingsPanel
+ id={EXTERNAL_AGENT_SETUP_ANCHOR}
+ title="External agents"
+ noPadding
+ class={`scroll-mt-20 transition-shadow ${
+ panelHighlight() ? 'ring-2 ring-blue-500 shadow-sm' : ''
+ }`}
+ >
+ <span id={PULSE_MCP_SETUP_ANCHOR} class="sr-only" aria-hidden="true" />
<div class="space-y-5 p-4 sm:p-6">
- <div class="space-y-2 text-sm text-muted">
- <p>
- Pulse exposes a manifest-driven agent surface for MCP and HTTP clients. An external
- agent (Claude Desktop, Claude Code, or a custom integration) discovers what it can do
- via <code class="font-mono text-xs">/api/agent/capabilities</code>, then calls the
- declared endpoints with an API token.
- </p>
- <p>
- The capabilities below are read live from this Pulse instance. Adding a capability on
- the backend adds it here automatically; nothing in this panel is hardcoded.
- </p>
- </div>
-
- <div class="space-y-3">
- <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
- <h3 class="text-sm font-semibold text-base-content">
- Claude Desktop / Claude Code config
- </h3>
- <Show when={copied() === mcpConfig}>
- <span class="text-xs text-emerald-600 dark:text-emerald-400">
- Copied to clipboard
- </span>
+ <div class="flex flex-col gap-3 text-sm text-muted lg:flex-row lg:items-start lg:justify-between">
+ <div class="max-w-3xl space-y-2">
+ <p>Connect external tools to read Pulse context and request Patrol work.</p>
+ <p>Patrol mode and scoped tokens control what connected agents can do.</p>
+ </div>
+ <div class="flex shrink-0 flex-wrap gap-2">
+ <Show when={!setupOpen()}>
+ <ButtonLink
+ href={PATROL_CONTROL_PATH}
+ variant="secondary"
+ size="settingsAction"
+ class="w-fit gap-2 font-semibold"
+ >
+ <SettingsIcon class="h-4 w-4" aria-hidden="true" />
+ Choose Patrol mode
+ </ButtonLink>
</Show>
+ <Button
+ variant="secondary"
+ size="settingsAction"
+ class="w-fit font-semibold"
+ aria-controls="external-agent-setup-details"
+ aria-expanded={setupOpen()}
+ onClick={() => setSetupOpen((open) => !open)}
+ >
+ {setupOpen() ? 'Hide connector setup' : 'Show connector setup'}
+ </Button>
</div>
- <p class="text-xs text-muted">
- First, install <code class="font-mono">pulse-mcp</code>. The fastest path:{' '}
- <code class="font-mono">
- curl -fsSL https://github.com/rcourtman/Pulse/releases/latest/download/install-mcp.sh
- | bash
- </code>{' '}
- (or <code class="font-mono">irm .../install-mcp.ps1 | iex</code> on Windows). Then drop
- this block into{' '}
- <code class="font-mono">
- ~/Library/Application Support/Claude/claude_desktop_config.json
- </code>{' '}
- (Claude Desktop) or your project's <code class="font-mono">.mcp.json</code> (Claude
- Code). Mint a token below with <code class="font-mono">monitoring:read</code> (and{' '}
- <code class="font-mono">monitoring:write</code> for the operator-state write tools),
- then replace <code class="font-mono">&lt;your-api-token&gt;</code>.
- </p>
- <CopyCommandBlock
- command={mcpConfig}
- onCopy={handleCopySnippet}
- codeClass="block whitespace-pre overflow-x-auto rounded-md border border-border bg-base p-3 font-mono text-xs text-base-content"
- />
- <p class="text-xs text-muted">
- See{' '}
- <ExternalTextLink href={AGENT_SUBSTRATE_DOC_URL} variant="inlineSubtle">
- docs/AGENT_SUBSTRATE.md
- </ExternalTextLink>{' '}
- for build instructions on <code class="font-mono">cmd/pulse-mcp</code> (including the{' '}
- <code class="font-mono">--emit-notifications</code> flag and known limitations), the
- companion HTTP example at <code class="font-mono">cmd/agent-probe</code>, and the
- substrate's design notes.
- </p>
</div>
- <Show when={manifest.loading}>
- <p class="text-sm text-muted">Loading capabilities…</p>
- </Show>
-
- <Show when={manifest.error}>
- <p class="text-sm text-red-600 dark:text-red-300">
- Could not load <code class="font-mono">/api/agent/capabilities</code>:{' '}
- {String(manifest.error)}
- </p>
- </Show>
-
- <Show when={manifest() && grouped().length > 0}>
- <div class="space-y-4">
- <div class="flex items-center justify-between">
- <h3 class="text-sm font-semibold text-base-content">
- Declared capabilities (manifest {manifest()?.version})
- </h3>
- <span class="text-xs text-muted">{manifest()?.capabilities.length ?? 0} total</span>
+ <Show when={setupOpen()}>
+ <div id="external-agent-setup-details" class="space-y-3">
+ <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
+ <h3 class="text-sm font-semibold text-base-content">Connector setup</h3>
</div>
- <For each={grouped()}>
- {(section) => (
- <div class="space-y-2">
- <div>
+ <ol class="divide-y divide-border rounded-md border border-border text-sm">
+ <li class="flex flex-col gap-3 p-3 sm:flex-row sm:items-center sm:justify-between">
+ <div class="space-y-1">
+ <p class="text-[11px] font-semibold uppercase tracking-wide text-muted">Step 1</p>
+ <p class="font-semibold text-base-content">Choose Patrol mode</p>
+ <p class="text-xs text-muted">Required before agents can request Patrol work.</p>
+ </div>
+ <ButtonLink
+ href={PATROL_CONTROL_PATH}
+ variant="secondary"
+ size="settingsAction"
+ class="w-fit shrink-0 gap-2 font-semibold"
+ >
+ <SettingsIcon class="h-4 w-4" aria-hidden="true" />
+ Choose Patrol mode
+ </ButtonLink>
+ </li>
+ <li class="flex flex-col gap-3 p-3 sm:flex-row sm:items-center sm:justify-between">
+ <div class="space-y-1">
+ <p class="text-[11px] font-semibold uppercase tracking-wide text-muted">Step 2</p>
+ <p class="font-semibold text-base-content">Create a scoped token</p>
+ <p class="text-xs text-muted">
+ Create a token with the{' '}
+ <span class="font-medium text-base-content">
+ {API_TOKEN_PATROL_EXTERNAL_AGENT_PRESET_LABEL}
+ </span>{' '}
+ preset.
+ </p>
+ </div>
+ <ButtonLink
+ href={PULSE_MCP_TOKEN_SETUP_PATH}
+ hardNavigation
+ variant="secondary"
+ size="settingsAction"
+ class="w-fit shrink-0 gap-2 font-semibold"
+ >
+ <KeyRoundIcon class="h-4 w-4" aria-hidden="true" />
+ Create token
+ </ButtonLink>
+ </li>
+ <li class="space-y-1 p-3">
+ <p class="text-[11px] font-semibold uppercase tracking-wide text-muted">Step 3</p>
+ <p class="font-semibold text-base-content">Connect the agent</p>
+ <p class="text-xs text-muted">
+ Install the connector, paste the client config, and replace{' '}
+ <code class="font-mono">{AGENT_MCP_TOKEN_PLACEHOLDER}</code>.
+ </p>
+ </li>
+ </ol>
+ <details
+ class="rounded-md border border-border bg-surface-alt/40 p-3"
+ onToggle={(event) => setInstallerCommandsOpen(event.currentTarget.open)}
+ >
+ <summary class="cursor-pointer text-sm font-semibold text-base-content">
+ Installer commands
+ </summary>
+ <Show when={installerCommandsOpen()}>
+ <div class="mt-3 grid gap-3 lg:grid-cols-2">
+ <div class="space-y-2">
<h4 class="text-xs font-semibold uppercase tracking-wide text-muted">
- {section.label}
+ macOS / Linux
</h4>
- <Show when={section.description}>
- <p class="text-xs text-muted">{section.description}</p>
- </Show>
+ <CopyCommandBlock
+ command={mcpInstallShellCommand}
+ onCopy={handleCopySnippet}
+ codeClass="block whitespace-pre overflow-x-auto rounded-md border border-border bg-base p-3 font-mono text-xs text-base-content"
+ />
+ </div>
+ <div class="space-y-2">
+ <h4 class="text-xs font-semibold uppercase tracking-wide text-muted">
+ Windows
+ </h4>
+ <CopyCommandBlock
+ command={mcpInstallPowerShellCommand}
+ onCopy={handleCopySnippet}
+ codeClass="block whitespace-pre overflow-x-auto rounded-md border border-border bg-base p-3 font-mono text-xs text-base-content"
+ />
</div>
- <ul class="divide-y divide-border rounded-md border border-border">
- <For each={section.entries}>
- {(cap) => (
- <li class="space-y-1 p-3">
- <div class="flex flex-wrap items-baseline gap-2">
- <code class="font-mono text-sm font-semibold text-base-content">
- {cap.name}
- </code>
- <span class="text-xs text-muted">
- <code class="font-mono">{cap.method}</code> {cap.path}
- </span>
- <span class="ml-auto rounded-full border border-border bg-surface-alt px-2 py-0.5 text-[10px] uppercase tracking-wide text-muted">
- {cap.scope}
- </span>
- </div>
- <p class="text-xs text-muted">{cap.description}</p>
- <Show when={cap.errorCodes && cap.errorCodes.length > 0}>
- <p class="text-[11px] text-muted">
- <span class="font-semibold">Stable error codes:</span>{' '}
- <For each={cap.errorCodes}>
- {(code, idx) => (
+ </div>
+ </Show>
+ </details>
+ <details
+ class="rounded-md border border-border bg-surface-alt/40 p-3"
+ onToggle={(event) => setClientConfigOpen(event.currentTarget.open)}
+ >
+ <summary class="cursor-pointer text-sm font-semibold text-base-content">
+ Client config
+ </summary>
+ <Show when={clientConfigOpen()}>
+ <div class="mt-3 space-y-4">
+ <p class="text-xs text-muted">
+ Both snippets point at this Pulse instance and use the same token placeholder:{' '}
+ <code class="font-mono">{AGENT_MCP_TOKEN_PLACEHOLDER}</code>.
+ </p>
+ <div class="space-y-2">
+ <div class="flex items-center justify-between">
+ <h4 class="text-xs font-semibold uppercase tracking-wide text-muted">
+ {openCodeConfigFamily()?.label ?? 'OpenCode'}{' '}
+ <code class="font-mono normal-case">opencode.json</code>
+ </h4>
+ <Show when={copied() === openCodeMcpConfig()}>
+ <span class="text-xs text-emerald-600 dark:text-emerald-400">
+ OpenCode config copied
+ </span>
+ </Show>
+ </div>
+ <CopyCommandBlock
+ command={openCodeMcpConfig()}
+ onCopy={handleCopySnippet}
+ codeClass="block whitespace-pre overflow-x-auto rounded-md border border-border bg-base p-3 font-mono text-xs text-base-content"
+ />
+ </div>
+ <div class="space-y-2">
+ <div class="flex items-center justify-between">
+ <h4 class="text-xs font-semibold uppercase tracking-wide text-muted">
+ {mcpServersConfigFamily()?.label ?? 'Claude-style clients'}{' '}
+ <code class="font-mono normal-case">mcpServers</code>
+ </h4>
+ <Show when={copied() === claudeMcpConfig()}>
+ <span class="text-xs text-emerald-600 dark:text-emerald-400">
+ mcpServers config copied
+ </span>
+ </Show>
+ </div>
+ <CopyCommandBlock
+ command={claudeMcpConfig()}
+ onCopy={handleCopySnippet}
+ codeClass="block whitespace-pre overflow-x-auto rounded-md border border-border bg-base p-3 font-mono text-xs text-base-content"
+ />
+ </div>
+ </div>
+ </Show>
+ </details>
+ <Show when={hasClientBuilderDetails()}>
+ <details
+ class="rounded-md border border-border bg-surface-alt/40 p-3"
+ onToggle={(event) => setAdvancedClientDetailsOpen(event.currentTarget.open)}
+ >
+ <summary class="cursor-pointer text-sm font-semibold text-base-content">
+ Developer details
+ </summary>
+ <Show when={advancedClientDetailsOpen()}>
+ <div class="mt-3 space-y-3">
+ <p class="text-xs text-muted">
+ Only open this when you are building or debugging a client against this Pulse
+ instance. Normal setup only needs Patrol mode, a scoped token, the connector,
+ and the client config above.
+ </p>
+ <Show when={mcpSurfaceToolPosture()}>
+ {(posture) => (
+ <div
+ class="flex w-fit flex-wrap items-center gap-1.5 rounded-md border border-border bg-base px-2 py-1 text-[11px] font-medium text-muted"
+ title={posture().title}
+ data-testid="agent-mcp-tool-posture"
+ >
+ <span
+ class="h-1.5 w-1.5 rounded-full bg-emerald-500"
+ aria-hidden="true"
+ />
+ <span>
+ External agents expose {posture().label}{' '}
+ <span class="text-muted/80">through Patrol mode</span>
+ </span>
+ </div>
+ )}
+ </Show>
+ <Show when={surfaceContractEntries().length > 0}>
+ <details class="rounded-md border border-border bg-base p-3">
+ <summary class="cursor-pointer text-sm font-semibold text-base-content">
+ Patrol access model
+ </summary>
+ <div class="mt-3 space-y-2">
+ <p class="text-xs text-muted">
+ Built-in Pulse views and connected clients all sit behind the same
+ Patrol policy. Connected agents do not get separate powers.
+ </p>
+ <ul class="divide-y divide-border rounded-md border border-border bg-surface-alt/40">
+ <For each={surfaceContractEntries()}>
+ {(entry) => (
+ <li class="space-y-1 p-3">
+ <div class="flex flex-wrap items-center gap-2">
+ <span class="text-sm font-semibold text-base-content">
+ {entry.id === AGENT_SURFACE_ID_PULSE_MCP
+ ? 'External agents'
+ : entry.label}
+ </span>
+ <For each={entry.badges}>
+ {(badge) => (
+ <span class="rounded-full border border-border bg-base px-2 py-0.5 text-[10px] uppercase tracking-wide text-muted">
+ {badge}
+ </span>
+ )}
+ </For>
+ </div>
+ <Show when={entry.description}>
+ <p class="text-xs text-muted">{entry.description}</p>
+ </Show>
+ </li>
+ )}
+ </For>
+ </ul>
+ </div>
+ </details>
+ </Show>
+ <Show when={hasManifestInventory()}>
+ <details class="rounded-md border border-border bg-base p-3">
+ <summary class="cursor-pointer text-sm font-semibold text-base-content">
+ Live manifest details
+ </summary>
+ <div class="mt-3 space-y-4">
+ <p class="text-xs text-muted">
+ These values come from{' '}
+ <code class="font-mono">/api/agent/capabilities</code>. Use them to
+ build clients against this instance; they do not change Patrol mode.
+ </p>
+ <Show when={workflowPrompts().length > 0}>
+ <details class="rounded-md border border-border bg-surface-alt/40 p-3">
+ <summary class="cursor-pointer text-sm font-semibold text-base-content">
+ <span>Agent starting points</span>{' '}
+ <span class="ml-2 text-xs font-normal text-muted">
+ ({workflowPrompts().length} from manifest)
+ </span>
+ </summary>
+ <div class="mt-3 space-y-2">
+ <ul class="divide-y divide-border rounded-md border border-border bg-base">
+ <For each={workflowPrompts()}>
+ {(prompt) => (
+ <li class="space-y-1 p-3">
+ <div class="flex flex-wrap items-baseline gap-2">
+ <span class="text-sm font-semibold text-base-content">
+ {prompt.label ?? prompt.name}
+ </span>
+ <Show
+ when={
+ prompt.name === AGENT_WORKFLOW_PROMPT_OPERATIONS_LOOP
+ }
+ >
+ <span class="rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-300">
+ Patrol
+ </span>
+ </Show>
+ </div>
+ <Show when={prompt.description}>
+ <p class="text-xs text-muted">{prompt.description}</p>
+ </Show>
+ <p class="text-[11px] text-muted">
+ <span class="font-semibold">Wire name:</span>{' '}
+ <code class="font-mono">{prompt.name}</code>
+ </p>
+ <Show when={(prompt.arguments?.length ?? 0) > 0}>
+ <p class="text-[11px] text-muted">
+ <span class="font-semibold">Arguments:</span>{' '}
+ <For each={prompt.arguments}>
+ {(arg, index) => (
+ <>
+ <code class="font-mono">{arg.name}</code>
+ {arg.required ? ' required' : ' optional'}
+ {index() < (prompt.arguments?.length ?? 0) - 1
+ ? ', '
+ : ''}
+ </>
+ )}
+ </For>
+ </p>
+ </Show>
+ </li>
+ )}
+ </For>
+ </ul>
+ </div>
+ </details>
+ </Show>
+ <Show when={requiredScopes().length > 0}>
+ <p class="text-xs text-muted">
+ Manifest scopes:{' '}
+ <For each={requiredScopes()}>
+ {(scope, index) => (
<>
- <code class="font-mono">{code}</code>
- {idx() < cap.errorCodes!.length - 1 ? ', ' : ''}
+ <code class="font-mono">{scope}</code>
+ {index() < requiredScopes().length - 1 ? ', ' : ''}
</>
)}
</For>
+ . Use narrower tokens when the client should only perform part of the
+ allowed work; each capability below shows its required scope.
</p>
</Show>
- </li>
- )}
- </For>
- </ul>
- </div>
- )}
- </For>
+ <Show when={errorCodeSummaries().length > 0}>
+ <details class="rounded-md border border-border bg-surface-alt/40 p-3 text-xs text-muted">
+ <summary class="cursor-pointer text-sm font-semibold text-base-content">
+ Failure codes{' '}
+ <span class="ml-2 text-xs font-normal text-muted">
+ ({errorCodeSummaries().length} from the live manifest)
+ </span>
+ </summary>
+ <div class="mt-3 space-y-2">
+ <p>
+ Connected agents should branch on these codes instead of scraping
+ response text.
+ </p>
+ <div class="flex flex-wrap gap-2">
+ <For each={errorCodeSummaries()}>
+ {(summary) => (
+ <span
+ class="rounded-md border border-border bg-base px-2 py-1"
+ title={`Declared by ${summary.capabilityNames.join(', ')}`}
+ >
+ <code class="font-mono">{summary.code}</code>
+ </span>
+ )}
+ </For>
+ </div>
+ </div>
+ </details>
+ </Show>
+ <p class="text-xs text-muted">
+ See{' '}
+ <ExternalTextLink href={AGENT_SUBSTRATE_DOC_URL} variant="inlineSubtle">
+ docs/AGENT_SUBSTRATE.md
+ </ExternalTextLink>{' '}
+ for build instructions on <code class="font-mono">cmd/pulse-mcp</code>{' '}
+ (including the <code class="font-mono">--emit-notifications</code> flag
+ and known limitations), the companion HTTP example at{' '}
+ <code class="font-mono">cmd/agent-probe</code>, and the substrate's
+ design notes.
+ </p>
+ <Show when={manifest() && grouped().length > 0}>
+ <details class="rounded-md border border-border bg-surface-alt/40 p-3">
+ <summary class="cursor-pointer text-sm font-semibold text-base-content">
+ Agent capabilities{' '}
+ <span class="ml-2 text-xs font-normal text-muted">
+ (manifest {manifest()?.version} -{' '}
+ {manifest()?.capabilities.length ?? 0} total)
+ </span>
+ </summary>
+ <div class="mt-3 space-y-4">
+ <For each={grouped()}>
+ {(section) => (
+ <div class="space-y-2">
+ <div>
+ <h4 class="text-xs font-semibold uppercase tracking-wide text-muted">
+ {section.label}
+ </h4>
+ <Show when={section.description}>
+ <p class="text-xs text-muted">{section.description}</p>
+ </Show>
+ </div>
+ <ul class="divide-y divide-border rounded-md border border-border bg-base">
+ <For each={section.entries}>
+ {(cap) => (
+ <li class="space-y-1 p-3">
+ <div class="flex flex-wrap items-baseline gap-2">
+ <code class="font-mono text-sm font-semibold text-base-content">
+ {cap.name}
+ </code>
+ <span class="text-xs text-muted">
+ <code class="font-mono">{cap.method}</code>{' '}
+ {cap.path}
+ </span>
+ <span class="ml-auto rounded-full border border-border bg-surface-alt px-2 py-0.5 text-[10px] uppercase tracking-wide text-muted">
+ {cap.scope}
+ </span>
+ </div>
+ <p class="text-xs text-muted">{cap.description}</p>
+ <Show
+ when={cap.errorCodes && cap.errorCodes.length > 0}
+ >
+ <p class="text-[11px] text-muted">
+ <span class="font-semibold">
+ Stable error codes:
+ </span>{' '}
+ <For each={cap.errorCodes}>
+ {(code, idx) => (
+ <>
+ <code class="font-mono">{code}</code>
+ {idx() < cap.errorCodes!.length - 1
+ ? ', '
+ : ''}
+ </>
+ )}
+ </For>
+ </p>
+ </Show>
+ </li>
+ )}
+ </For>
+ </ul>
+ </div>
+ )}
+ </For>
+ </div>
+ </details>
+ </Show>
+ </div>
+ </details>
+ </Show>
+ </div>
+ </Show>
+ </details>
+ </Show>
</div>
</Show>
+
+ <Show when={manifest.loading}>
+ <p class="text-sm text-muted">Loading capabilities…</p>
+ </Show>
+
+ <Show when={manifest.error}>
+ <p class="text-sm text-red-600 dark:text-red-300">
+ Could not load <code class="font-mono">/api/agent/capabilities</code>:{' '}
+ {String(manifest.error)}
+ </p>
+ </Show>
</div>
</SettingsPanel>
);
diff --git a/frontend-modern/src/components/Settings/CopyCommandBlock.tsx b/frontend-modern/src/components/Settings/CopyCommandBlock.tsx
index 617a9bc4f2..1f60bddc8e 100644
--- a/frontend-modern/src/components/Settings/CopyCommandBlock.tsx
+++ b/frontend-modern/src/components/Settings/CopyCommandBlock.tsx
@@ -1,4 +1,5 @@
import { CommandCopyButton } from '@/components/shared/Button';
+import { copyToClipboard } from '@/utils/clipboard';
interface CopyCommandBlockProps {
command: string;
@@ -14,11 +15,11 @@ const DEFAULT_CODE_CLASS =
export function CopyCommandBlock(props: CopyCommandBlockProps) {
const handleCopy = () => {
- if (props.onCopy) {
- void props.onCopy(props.command);
- return;
- }
- void navigator.clipboard.writeText(props.command);
+ void (async () => {
+ const copied = await copyToClipboard(props.command);
+ if (!copied) return;
+ await props.onCopy?.(props.command);
+ })();
};
return (
diff --git a/frontend-modern/src/components/Settings/DiagnosticsResultsPanel.tsx b/frontend-modern/src/components/Settings/DiagnosticsResultsPanel.tsx
index a1cd6d1eda..f46fa6c95a 100644
--- a/frontend-modern/src/components/Settings/DiagnosticsResultsPanel.tsx
+++ b/frontend-modern/src/components/Settings/DiagnosticsResultsPanel.tsx
@@ -470,22 +470,24 @@ export const DiagnosticsResultsPanel: Component<DiagnosticsResultsPanelProps> =
/>
</div>
<div class="mt-3 flex items-center justify-between border-t border-border-subtle pt-3 text-xs">
- <span class="text-muted">MCP Connection</span>
+ <span class="text-muted">Assistant runtime</span>
<div class="flex items-center gap-1.5">
<Show
- when={props.diagnosticsData?.aiChat?.mcpConnected}
+ when={props.diagnosticsData?.aiChat?.assistantRuntimeConnected}
fallback={<XCircle class="h-3.5 w-3.5 text-rose-400" />}
>
<CheckCircle class="h-3.5 w-3.5 text-emerald-400" />
</Show>
<span
class={
- props.diagnosticsData?.aiChat?.mcpConnected
+ props.diagnosticsData?.aiChat?.assistantRuntimeConnected
? 'text-green-700 dark:text-green-300'
: 'text-slate-500'
}
>
- {props.diagnosticsData?.aiChat?.mcpConnected ? 'Connected' : 'Disconnected'}
+ {props.diagnosticsData?.aiChat?.assistantRuntimeConnected
+ ? 'Connected'
+ : 'Disconnected'}
</span>
</div>
</div>
diff --git a/frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx b/frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx
index 29bae71c67..8ef5d41df6 100644
--- a/frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx
+++ b/frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx
@@ -302,8 +302,9 @@ export const InfrastructureInstallerSection: Component<InfrastructureInstallerSe
<li class="flex items-start">
<span class="mr-2 mt-0.5 text-emerald-500">✓</span>
<span>
- Read-only by default. Assistant control and host shell stay off until you opt in
- per host from <span class="font-medium">Settings → Infrastructure</span>.
+ Read-only by default. Assistant chat actions and host shell stay off until you
+ opt in per host from{' '}
+ <span class="font-medium">Settings → Infrastructure</span>.
</span>
</li>
<li class="flex items-start">
diff --git a/frontend-modern/src/components/Settings/ProLicensePanel.tsx b/frontend-modern/src/components/Settings/ProLicensePanel.tsx
index 5087a1a131..4869850d66 100644
--- a/frontend-modern/src/components/Settings/ProLicensePanel.tsx
+++ b/frontend-modern/src/components/Settings/ProLicensePanel.tsx
@@ -89,7 +89,6 @@ const ProLicensePanelContent: Component = () => {
<div class="space-y-6">
<ProLicensePlanSection
activationSuccessSummary={state.activationSuccessSummary()}
- activationProof={state.activationProof()}
commercialMigrationNotice={state.commercialMigrationNotice()}
commercialPlanModel={state.commercialPlanModel()}
currentPlanSummary={state.currentPlanSummary()}
@@ -98,8 +97,9 @@ const ProLicensePanelContent: Component = () => {
hasLicenseDetails={state.hasLicenseDetails()}
loading={state.loading()}
onReload={() => void state.loadPanelData()}
- planSelectionPrompt={state.planSelectionPrompt()}
planComparisonSummary={state.planComparisonSummary()}
+ planSelectionPrompt={state.planSelectionPrompt()}
+ planStatus={state.planStatus()}
purchaseActivationAction={state.purchaseActivationAction()}
purchaseActivationNotice={state.purchaseActivationNotice()}
/>
diff --git a/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx b/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx
index 89c7ddff84..345b061697 100644
--- a/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx
+++ b/frontend-modern/src/components/Settings/ProLicensePlanSection.tsx
@@ -6,9 +6,10 @@ import { licenseEntitlementsLoadError } from '@/stores/licenseEntitlements';
import {
getLicenseStatusLoadingState,
getNoActiveSelfHostedActivationState,
+ type SelfHostedPatrolControlActionIntent,
} from '@/utils/licensePresentation';
+import { isExternalUpgradeHref, type UpgradeDestination } from '@/utils/upgradeNavigation';
import { SELF_HOSTED_PRO_BILLING_PRESENTATION } from './selfHostedBillingPresentation';
-import type { UpgradeDestination } from '@/utils/upgradeNavigation';
import { CommercialStatGrid } from './CommercialBillingSections';
interface Notice {
@@ -31,16 +32,7 @@ interface ProLicensePlanSectionProps {
highlights: string[];
actionLabel?: string;
actionUrl?: string;
- } | null;
- activationProof: {
- title: string;
- body: string;
- items: Array<{
- label: string;
- statusLabel: string;
- state: 'active' | 'partial' | 'missing';
- detail: string;
- }>;
+ actionIntent?: SelfHostedPatrolControlActionIntent;
} | null;
commercialMigrationNotice: Notice | null;
commercialPlanModel: {
@@ -62,6 +54,11 @@ interface ProLicensePlanSectionProps {
actionLabel: string;
actionUrl: string;
};
+ patrolControlAction?: {
+ actionLabel: string;
+ actionUrl: string;
+ actionIntent: SelfHostedPatrolControlActionIntent;
+ };
};
entitlements: {
in_grace_period?: boolean;
@@ -83,6 +80,16 @@ interface ProLicensePlanSectionProps {
} | null;
};
planSelectionPrompt: ActionNotice | null;
+ planStatus: {
+ title: string;
+ body: string;
+ items: Array<{
+ label: string;
+ statusLabel: string;
+ state: 'active' | 'partial' | 'missing';
+ detail: string;
+ }>;
+ } | null;
purchaseActivationNotice: Notice | null;
purchaseActivationAction: {
label: string;
@@ -97,7 +104,7 @@ const formatDate = (value?: string | null) => {
return date.toLocaleDateString();
};
-const proofStateClass = (state: 'active' | 'partial' | 'missing') => {
+const statusStateClass = (state: 'active' | 'partial' | 'missing') => {
switch (state) {
case 'active':
return 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900 dark:text-emerald-200';
@@ -109,6 +116,30 @@ const proofStateClass = (state: 'active' | 'partial' | 'missing') => {
};
export const ProLicensePlanSection: Component<ProLicensePlanSectionProps> = (props) => {
+ const getCurrentPlanPatrolControlAction = () => {
+ const action = props.currentPlanSummary.patrolControlAction;
+ if (!action) {
+ return null;
+ }
+ if (props.activationSuccessSummary?.actionIntent === action.actionIntent) {
+ return null;
+ }
+ return action;
+ };
+ const getPlanStatusSummary = () => {
+ const status = props.planStatus;
+ if (!status) {
+ return '';
+ }
+ const attentionCount = status.items.filter((item) => item.state !== 'active').length;
+ if (attentionCount > 0) {
+ return attentionCount === 1
+ ? '1 item needs attention'
+ : `${attentionCount} items need attention`;
+ }
+ return status.items.length === 1 ? '1 item ready' : `${status.items.length} items ready`;
+ };
+
return (
<>
<Show when={props.activationSuccessSummary}>
@@ -130,7 +161,7 @@ export const ProLicensePlanSection: Component<ProLicensePlanSectionProps> = (pro
{(action) => (
<ButtonLink
href={action().href}
- target="_blank"
+ target={isExternalUpgradeHref(action().href) ? '_blank' : undefined}
variant="outline"
size="settingsActionXs"
class="mt-3 gap-1"
@@ -233,6 +264,19 @@ export const ProLicensePlanSection: Component<ProLicensePlanSectionProps> = (pro
</ButtonLink>
)}
</Show>
+ <Show when={getCurrentPlanPatrolControlAction()}>
+ {(action) => (
+ <ButtonLink
+ href={action().actionUrl}
+ target={isExternalUpgradeHref(action().actionUrl) ? '_blank' : undefined}
+ variant="outline"
+ size="settingsActionXs"
+ class="mt-3 gap-1"
+ >
+ {action().actionLabel}
+ </ButtonLink>
+ )}
+ </Show>
<Show when={props.currentPlanSummary.unlockedFeatures.length > 0}>
<div class="mt-4">
<p class="text-xs uppercase tracking-wide text-muted mb-2">
@@ -268,31 +312,36 @@ export const ProLicensePlanSection: Component<ProLicensePlanSectionProps> = (pro
</div>
</Show>
</div>
- <Show when={props.activationProof}>
- {(proof) => (
- <div class="mb-4 rounded-md border border-border bg-surface p-4">
- <p class="text-sm font-medium text-base-content">{proof().title}</p>
- <p class="mt-1 text-xs text-muted">{proof().body}</p>
- <ul class="mt-4 grid gap-3">
- <For each={proof().items}>
- {(item) => (
- <li class="border-t border-border pt-3 first:border-t-0 first:pt-0">
- <div class="flex flex-wrap items-center gap-2">
- <p class="text-sm font-medium text-base-content">{item.label}</p>
- <span
- class={`rounded-full px-2 py-1 text-[11px] font-medium ${proofStateClass(
- item.state,
- )}`}
- >
- {item.statusLabel}
- </span>
- </div>
- <p class="mt-1 text-xs text-muted">{item.detail}</p>
- </li>
- )}
- </For>
- </ul>
- </div>
+ <Show when={props.planStatus}>
+ {(status) => (
+ <details class="mb-4 rounded-md border border-border bg-surface p-4">
+ <summary class="cursor-pointer text-sm font-medium text-base-content">
+ <span>{status().title}</span>{' '}
+ <span class="text-xs font-normal text-muted">({getPlanStatusSummary()})</span>
+ </summary>
+ <div class="mt-3">
+ <p class="text-xs text-muted">{status().body}</p>
+ <ul class="mt-4 grid gap-3">
+ <For each={status().items}>
+ {(item) => (
+ <li class="border-t border-border pt-3 first:border-t-0 first:pt-0">
+ <div class="flex flex-wrap items-center gap-2">
+ <p class="text-sm font-medium text-base-content">{item.label}</p>
+ <span
+ class={`rounded-full px-2 py-1 text-[11px] font-medium ${statusStateClass(
+ item.state,
+ )}`}
+ >
+ {item.statusLabel}
+ </span>
+ </div>
+ <p class="mt-1 text-xs text-muted">{item.detail}</p>
+ </li>
+ )}
+ </For>
+ </ul>
+ </div>
+ </details>
)}
</Show>
<Show when={props.planComparisonSummary.cards.length > 0}>
diff --git a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
index 66049ea497..ca6a1b599f 100644
--- a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
@@ -2,9 +2,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
import { Route, Router } from '@solidjs/router';
+import { PULSE_MCP_TOKEN_SETUP_PATH } from '@/routing/resourceLinks';
import { resetAIRuntimeState } from '@/stores/aiRuntimeState';
import type { AISettings as AISettingsType } from '@/types/ai';
-import { AISettings } from '../AISettings';
+import {
+ AIAssistantSettings,
+ AIDiscoverySettings,
+ AISettings,
+ AIPatrolSettings,
+} from '../AISettings';
const getSettingsMock = vi.fn();
const updateSettingsMock = vi.fn();
@@ -12,6 +18,7 @@ const getModelsMock = vi.fn();
const testProviderMock = vi.fn();
const testConnectionMock = vi.fn();
const runDiscoveryRefreshMock = vi.fn();
+const fetchAgentCapabilitiesManifestMock = vi.fn();
const listSessionsMock = vi.fn();
const summarizeSessionMock = vi.fn();
const notificationSuccessMock = vi.fn();
@@ -48,6 +55,15 @@ vi.mock('@/api/discovery', () => ({
runDiscoveryRefresh: (...args: unknown[]) => runDiscoveryRefreshMock(...args),
}));
+vi.mock('@/api/agentCapabilities', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/api/agentCapabilities')>();
+ return {
+ ...actual,
+ fetchAgentCapabilitiesManifest: (...args: unknown[]) =>
+ fetchAgentCapabilitiesManifestMock(...args),
+ };
+});
+
vi.mock('@/stores/notifications', () => ({
notificationStore: {
success: (...args: unknown[]) => notificationSuccessMock(...args),
@@ -100,12 +116,29 @@ const baseSettings = (): AISettingsType => ({
configured_providers: [],
});
-const renderComponent = () =>
- render(() => (
+type AISettingsTestPage = 'provider' | 'patrol' | 'assistant' | 'discovery';
+
+const getTestComponent = (page: AISettingsTestPage) => {
+ switch (page) {
+ case 'patrol':
+ return AIPatrolSettings;
+ case 'assistant':
+ return AIAssistantSettings;
+ case 'discovery':
+ return AIDiscoverySettings;
+ default:
+ return AISettings;
+ }
+};
+
+const renderComponent = (page: AISettingsTestPage = 'provider') => {
+ const Component = getTestComponent(page);
+ return render(() => (
<Router>
- <Route path="/" component={() => <AISettings />} />
+ <Route path="/" component={() => <Component />} />
</Router>
));
+};
const resetAllMocks = () => {
getSettingsMock.mockReset();
@@ -114,6 +147,7 @@ const resetAllMocks = () => {
testProviderMock.mockReset();
testConnectionMock.mockReset();
runDiscoveryRefreshMock.mockReset();
+ fetchAgentCapabilitiesManifestMock.mockReset();
listSessionsMock.mockReset();
summarizeSessionMock.mockReset();
notificationSuccessMock.mockReset();
@@ -153,6 +187,7 @@ const setupDefaultMocks = () => {
failed_count: 0,
last_run: '2026-05-15T12:00:00Z',
});
+ fetchAgentCapabilitiesManifestMock.mockResolvedValue(null);
listSessionsMock.mockResolvedValue([]);
summarizeSessionMock.mockResolvedValue(undefined);
presentationPolicyHidesUpgradePromptsMock.mockReturnValue(false);
@@ -169,6 +204,138 @@ describe('AISettings model loading error states', () => {
cleanup();
});
+ it('separates Patrol mode from Assistant chat actions on the settings page', async () => {
+ getSettingsMock.mockResolvedValue({
+ ...baseSettings(),
+ enabled: true,
+ configured: true,
+ patrol_interval_minutes: 180,
+ control_level: 'controlled',
+ });
+
+ renderComponent('assistant');
+
+ expect(await screen.findByText('Assistant chat actions')).toBeInTheDocument();
+ expect(
+ screen.getByText('This controls actions started from Assistant chat only', { exact: false }),
+ ).toBeInTheDocument();
+ expect(screen.getByLabelText('Chat action mode')).toBeInTheDocument();
+ expect(screen.getByRole('option', { name: /Ask first/i })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Save Assistant settings/i })).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'External agents' })).toBeInTheDocument();
+ expect(
+ screen.getByText('Optional connector access for Claude Desktop', { exact: false }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Show connector setup' })).toBeInTheDocument();
+ expect(
+ screen.queryByRole('heading', { name: 'Connector setup' }),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Create token' })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Show connector setup' }));
+
+ expect(screen.getByRole('link', { name: 'Create token' })).toHaveAttribute(
+ 'href',
+ PULSE_MCP_TOKEN_SETUP_PATH,
+ );
+ });
+
+ it('keeps Provider & Models focused on provider setup and runtime cost controls', async () => {
+ getSettingsMock.mockResolvedValue({
+ ...baseSettings(),
+ enabled: true,
+ configured: true,
+ });
+
+ renderComponent();
+
+ expect(await screen.findByText('Provider Configuration')).toBeInTheDocument();
+ expect(screen.getByText('30-day Budget')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Enable Pulse Intelligence' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Test Connection/i })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Save provider settings/i })).toBeInTheDocument();
+ expect(screen.queryByText('Assistant chat actions')).not.toBeInTheDocument();
+ expect(screen.queryByText('External agents')).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Service Context/i })).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol mode')).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Open Patrol/i })).not.toBeInTheDocument();
+ expect(screen.queryByText(/Set how much Patrol can do/i)).not.toBeInTheDocument();
+ });
+
+ it('shows Patrol scheduling and readiness without rendering the operator loop', async () => {
+ getSettingsMock.mockResolvedValue({
+ ...baseSettings(),
+ enabled: true,
+ configured: true,
+ patrol_interval_minutes: 180,
+ alert_triggered_analysis: true,
+ patrol_alert_triggers_enabled: true,
+ patrol_anomaly_triggers_enabled: false,
+ patrol_alert_trigger_min_severity: 'warning',
+ });
+
+ renderComponent('patrol');
+
+ expect(await screen.findByText('Patrol mode')).toBeInTheDocument();
+ expect(screen.getByLabelText('Schedule')).toHaveValue('180');
+ expect(screen.getByLabelText('Enable alert-triggered Patrols')).toBeInTheDocument();
+ expect(screen.getByLabelText('Enable anomaly-triggered Patrols')).toBeInTheDocument();
+ expect(screen.getByLabelText('Enable container update risk analysis')).toBeInTheDocument();
+ expect(screen.getByLabelText('Investigate alerts at or above')).toHaveValue('warning');
+ expect(screen.getByText('Model readiness')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Open Patrol/i })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Save Patrol settings/i })).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', { name: 'Enable Pulse Intelligence' }),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Test Connection/i })).not.toBeInTheDocument();
+ expect(screen.queryByText('Provider Configuration')).not.toBeInTheDocument();
+ expect(screen.queryByText('External agents')).not.toBeInTheDocument();
+ });
+
+ it('saves Patrol trigger settings from Pulse Intelligence Patrol settings', async () => {
+ getSettingsMock.mockResolvedValue({
+ ...baseSettings(),
+ enabled: true,
+ configured: true,
+ patrol_alert_triggers_enabled: true,
+ patrol_anomaly_triggers_enabled: false,
+ patrol_alert_trigger_min_severity: 'critical',
+ alert_triggered_analysis: true,
+ });
+ updateSettingsMock.mockImplementation(async (payload: Record<string, unknown>) => ({
+ ...baseSettings(),
+ enabled: true,
+ configured: true,
+ ...payload,
+ }));
+
+ renderComponent('patrol');
+
+ await screen.findByLabelText('Enable alert-triggered Patrols');
+ fireEvent.change(screen.getByLabelText('Investigate alerts at or above'), {
+ target: { value: 'warning' },
+ });
+ fireEvent.click(screen.getByLabelText('Enable alert-triggered Patrols'));
+ fireEvent.click(screen.getByLabelText('Enable anomaly-triggered Patrols'));
+ fireEvent.click(screen.getByLabelText('Enable container update risk analysis'));
+ fireEvent.click(screen.getByRole('button', { name: /Save Patrol settings/i }));
+
+ await waitFor(() => {
+ expect(updateSettingsMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ patrol_alert_triggers_enabled: false,
+ patrol_anomaly_triggers_enabled: true,
+ patrol_alert_trigger_min_severity: 'warning',
+ alert_triggered_analysis: false,
+ }),
+ );
+ });
+ await waitFor(() => {
+ expect(notificationSuccessMock).toHaveBeenCalledWith('Patrol settings saved');
+ });
+ });
+
it('shows inline warning when getModels throws a network error', async () => {
getSettingsMock.mockResolvedValue({
...baseSettings(),
@@ -376,13 +543,13 @@ describe('AISettings model loading error states', () => {
hasFeatureMock.mockImplementation((feature: string) => feature !== 'ai_autofix');
presentationPolicyHidesUpgradePromptsMock.mockReturnValue(true);
- renderComponent();
+ renderComponent('assistant');
await waitFor(() => {
expect(getSettingsMock).toHaveBeenCalledTimes(1);
});
- expect(screen.queryByRole('option', { name: /Autonomous/i })).not.toBeInTheDocument();
+ expect(screen.queryByRole('option', { name: /Allow chat-only actions/i })).not.toBeInTheDocument();
});
it('keeps an existing autonomous setting visible even when upgrade prompts are hidden', async () => {
@@ -393,13 +560,13 @@ describe('AISettings model loading error states', () => {
control_level: 'autonomous',
});
- renderComponent();
+ renderComponent('assistant');
await waitFor(() => {
expect(getSettingsMock).toHaveBeenCalledTimes(1);
});
- expect(screen.getByRole('option', { name: /Autonomous/i })).toBeInTheDocument();
+ expect(screen.getByRole('option', { name: /Allow chat-only actions/i })).toBeInTheDocument();
expect(screen.queryByText('(Pro)')).not.toBeInTheDocument();
});
});
@@ -420,14 +587,14 @@ describe('AISettings load failure error state', () => {
renderComponent();
await waitFor(() => {
- expect(screen.getByText(/Unable to load Assistant & Patrol settings/)).toBeInTheDocument();
+ expect(screen.getByText(/Unable to load Provider & Models settings/)).toBeInTheDocument();
});
// Retry button should be present
expect(screen.getByRole('button', { name: /retry/i })).toBeInTheDocument();
// Save button should NOT be present (form is hidden)
- expect(screen.queryByRole('button', { name: /save changes/i })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Save .* settings/i })).not.toBeInTheDocument();
});
it('clears error and shows form after successful retry', async () => {
@@ -436,7 +603,7 @@ describe('AISettings load failure error state', () => {
renderComponent();
await waitFor(() => {
- expect(screen.getByText(/Unable to load Assistant & Patrol settings/)).toBeInTheDocument();
+ expect(screen.getByText(/Unable to load Provider & Models settings/)).toBeInTheDocument();
});
// Now mock a successful response for retry
@@ -452,20 +619,18 @@ describe('AISettings load failure error state', () => {
// Wait for the form to fully render after successful retry (not just banner disappearing during loading)
await waitFor(() => {
- expect(screen.getByRole('button', { name: /save changes/i })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Save provider settings/i })).toBeInTheDocument();
});
// Error banner should be gone
- expect(
- screen.queryByText(/Unable to load Assistant & Patrol settings/),
- ).not.toBeInTheDocument();
+ expect(screen.queryByText(/Unable to load Provider & Models settings/)).not.toBeInTheDocument();
// Verify retry actually called getSettings again
expect(getSettingsMock).toHaveBeenCalledTimes(2);
});
});
-describe('AISettings workload discovery persistence', () => {
+describe('AISettings service context persistence', () => {
beforeEach(() => {
resetAllMocks();
setupDefaultMocks();
@@ -475,7 +640,7 @@ describe('AISettings workload discovery persistence', () => {
cleanup();
});
- it('saves workload discovery enablement and scan interval as an explicit pair', async () => {
+ it('saves service context enablement and scan interval as an explicit pair', async () => {
getSettingsMock.mockResolvedValue({
...baseSettings(),
discovery_enabled: true,
@@ -487,14 +652,14 @@ describe('AISettings workload discovery persistence', () => {
discovery_interval_hours: payload.discovery_interval_hours as number,
}));
- renderComponent();
+ renderComponent('discovery');
await waitFor(() => {
expect(
- screen.getByRole('button', { name: /Workload Discovery Auto 24h/i }),
+ screen.getByRole('button', { name: /Service Context Auto 24h/i }),
).toBeInTheDocument();
});
- fireEvent.click(screen.getByRole('button', { name: /Workload Discovery Auto 24h/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Service Context Auto 24h/i }));
const intervalSelect = screen.getByLabelText('Scan Interval');
expect(intervalSelect).toHaveValue('24');
@@ -503,7 +668,7 @@ describe('AISettings workload discovery persistence', () => {
});
expect(intervalSelect).toHaveValue('6');
- fireEvent.click(screen.getByRole('button', { name: /save changes/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Save service context settings/i }));
await waitFor(() => {
expect(updateSettingsMock).toHaveBeenCalledWith(
@@ -515,22 +680,22 @@ describe('AISettings workload discovery persistence', () => {
});
});
- it('runs a manual discovery refresh from workload discovery settings', async () => {
+ it('runs a manual service context refresh from settings', async () => {
getSettingsMock.mockResolvedValue({
...baseSettings(),
discovery_enabled: true,
discovery_interval_hours: 0,
});
- renderComponent();
+ renderComponent('discovery');
await waitFor(() => {
expect(
- screen.getByRole('button', { name: /Workload Discovery Manual only/i }),
+ screen.getByRole('button', { name: /Service Context Manual only/i }),
).toBeInTheDocument();
});
- fireEvent.click(screen.getByRole('button', { name: /Workload Discovery Manual only/i }));
- fireEvent.click(screen.getByRole('button', { name: /Run discovery now/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Service Context Manual only/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Run context scan/i }));
await waitFor(() => {
expect(runDiscoveryRefreshMock).toHaveBeenCalledTimes(1);
@@ -547,19 +712,19 @@ describe('AISettings workload discovery persistence', () => {
discovery_interval_hours: 0,
});
- renderComponent();
+ renderComponent('discovery');
await waitFor(() => {
- expect(screen.getByRole('button', { name: /Workload Discovery Off/i })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Service Context Off/i })).toBeInTheDocument();
});
- fireEvent.click(screen.getByRole('button', { name: /Workload Discovery Off/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Service Context Off/i }));
expect(screen.queryByLabelText('Scan Interval')).not.toBeInTheDocument();
expect(
- screen.getByText('Runs a one-time workload discovery refresh without changing the schedule.'),
+ screen.getByText('Runs one service context scan without changing the schedule.'),
).toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: /Run discovery now/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Run context scan/i }));
await waitFor(() => {
expect(runDiscoveryRefreshMock).toHaveBeenCalledTimes(1);
@@ -586,15 +751,15 @@ describe('AISettings workload discovery persistence', () => {
last_run: '2026-05-15T12:00:00Z',
});
- renderComponent();
+ renderComponent('discovery');
await waitFor(() => {
expect(
- screen.getByRole('button', { name: /Workload Discovery Manual only/i }),
+ screen.getByRole('button', { name: /Service Context Manual only/i }),
).toBeInTheDocument();
});
- fireEvent.click(screen.getByRole('button', { name: /Workload Discovery Manual only/i }));
- fireEvent.click(screen.getByRole('button', { name: /Run discovery now/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Service Context Manual only/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Run context scan/i }));
await waitFor(() => {
expect(notificationInfoMock).toHaveBeenCalledWith(
@@ -638,7 +803,7 @@ describe('AISettings OpenRouter flow', () => {
fireEvent.input(await screen.findByPlaceholderText('sk-or-...'), {
target: { value: 'sk-or-configured' },
});
- fireEvent.click(screen.getByRole('button', { name: /save changes/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Save provider settings/i }));
await waitFor(() => {
expect(updateSettingsMock).toHaveBeenCalledWith(
@@ -703,7 +868,7 @@ describe('AISettings Ollama provider options', () => {
fireEvent.input(await screen.findByLabelText('Ollama Keep Alive'), {
target: { value: '24h' },
});
- fireEvent.click(screen.getByRole('button', { name: /save changes/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Save provider settings/i }));
await waitFor(() => {
expect(updateSettingsMock).toHaveBeenCalledWith(
@@ -751,12 +916,12 @@ describe('AISettings provider save failure context', () => {
provider === 'openrouter' ? 'Provider authentication issue' : `${provider} reachable`,
recommendation:
provider === 'openrouter'
- ? 'Check the API key or provider authentication in Assistant and Patrol settings, then retry.'
+ ? 'Check the API key or provider authentication in Provider & Models settings, then retry.'
: undefined,
cause: provider === 'openrouter' ? 'provider_auth' : undefined,
provider,
}));
- updateSettingsMock.mockRejectedValue(new Error('Unable to save Assistant & Patrol settings.'));
+ updateSettingsMock.mockRejectedValue(new Error('Unable to save Provider & Models settings.'));
renderComponent();
@@ -764,7 +929,7 @@ describe('AISettings provider save failure context', () => {
expect(testProviderMock).toHaveBeenCalledWith('openrouter');
});
- fireEvent.click(screen.getByRole('button', { name: /save changes/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Save provider settings/i }));
await waitFor(() => {
expect(notificationErrorMock).toHaveBeenCalledWith(
@@ -775,7 +940,7 @@ describe('AISettings provider save failure context', () => {
expect(message).toContain('model openrouter:deepseek/deepseek-r1');
expect(message).toContain('Provider authentication issue');
expect(message).toContain('Check the API key or provider authentication');
- expect(message).toContain('Unable to save Assistant & Patrol settings.');
+ expect(message).toContain('Unable to save Provider & Models settings.');
});
it('warns with Patrol provider and model when settings save but Patrol is not ready', async () => {
@@ -811,21 +976,21 @@ describe('AISettings provider save failure context', () => {
renderComponent();
await waitFor(() => {
- expect(screen.getByRole('button', { name: /save changes/i })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Save provider settings/i })).toBeInTheDocument();
});
- fireEvent.click(screen.getByRole('button', { name: /save changes/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Save provider settings/i }));
await waitFor(() => {
expect(notificationWarningMock).toHaveBeenCalledWith(
- expect.stringContaining('Assistant & Patrol settings saved, but Patrol is not ready'),
+ expect.stringContaining('Provider & Models settings saved, but Patrol is not ready'),
);
});
const message = String(notificationWarningMock.mock.calls.at(-1)?.[0] ?? '');
expect(message).toContain('Provider: OpenRouter');
expect(message).toContain('Model: openrouter:deepseek/deepseek-r1');
expect(message).toContain('reasoning-only model family');
- expect(notificationSuccessMock).not.toHaveBeenCalledWith('Assistant & Patrol settings saved');
+ expect(notificationSuccessMock).not.toHaveBeenCalledWith('Provider & Models settings saved');
});
it('does not attach provider context to specific backend validation errors', async () => {
@@ -850,7 +1015,7 @@ describe('AISettings provider save failure context', () => {
expect(testProviderMock).toHaveBeenCalledWith('openrouter');
});
- fireEvent.click(screen.getByRole('button', { name: /save changes/i }));
+ fireEvent.click(screen.getByRole('button', { name: /Save provider settings/i }));
await waitFor(() => {
expect(notificationErrorMock).toHaveBeenCalledWith(
@@ -900,16 +1065,16 @@ describe('AISettings provider setup flow', () => {
expect(getSettingsMock).toHaveBeenCalledTimes(1);
});
- fireEvent.click(screen.getByRole('button', { name: /enable assistant and patrol/i }));
+ fireEvent.click(screen.getByRole('button', { name: /enable pulse intelligence/i }));
const setupDialog = await screen.findByRole('dialog', {
- name: 'Set up Assistant and Patrol',
+ name: 'Set up Pulse Intelligence',
});
- expect(within(setupDialog).getByText('Set Up Assistant & Patrol')).toBeInTheDocument();
+ expect(within(setupDialog).getByText('Set Up Pulse Intelligence')).toBeInTheDocument();
fireEvent.click(within(setupDialog).getByRole('button', { name: /OpenRouter/i }));
fireEvent.input(screen.getByPlaceholderText('sk-or-...'), {
target: { value: 'sk-or-test' },
});
- fireEvent.click(screen.getByRole('button', { name: 'Enable Assistant & Patrol' }));
+ fireEvent.click(within(setupDialog).getByRole('button', { name: 'Enable Pulse Intelligence' }));
await waitFor(() => {
expect(updateSettingsMock).toHaveBeenCalledWith({
@@ -919,7 +1084,7 @@ describe('AISettings provider setup flow', () => {
});
await waitFor(() => {
expect(notificationWarningMock).toHaveBeenCalledWith(
- expect.stringContaining('Assistant & Patrol enabled, but Patrol is not ready'),
+ expect.stringContaining('Pulse Intelligence enabled, but Patrol is not ready'),
);
});
const message = String(notificationWarningMock.mock.calls.at(-1)?.[0] ?? '');
@@ -927,12 +1092,12 @@ describe('AISettings provider setup flow', () => {
expect(message).toContain('Model: openrouter:deepseek/deepseek-r1');
expect(message).toContain('reasoning-only model family');
expect(notificationSuccessMock).not.toHaveBeenCalledWith(
- 'Assistant & Patrol enabled! You can customize settings below.',
+ 'Pulse Intelligence enabled. You can customize settings below.',
);
});
it('names the setup provider when provider setup save fails generically', async () => {
- updateSettingsMock.mockRejectedValue(new Error('Unable to save Assistant & Patrol settings.'));
+ updateSettingsMock.mockRejectedValue(new Error('Unable to save Provider & Models settings.'));
renderComponent();
@@ -940,16 +1105,16 @@ describe('AISettings provider setup flow', () => {
expect(getSettingsMock).toHaveBeenCalledTimes(1);
});
- fireEvent.click(screen.getByRole('button', { name: /enable assistant and patrol/i }));
+ fireEvent.click(screen.getByRole('button', { name: /enable pulse intelligence/i }));
const setupDialog = await screen.findByRole('dialog', {
- name: 'Set up Assistant and Patrol',
+ name: 'Set up Pulse Intelligence',
});
- expect(within(setupDialog).getByText('Set Up Assistant & Patrol')).toBeInTheDocument();
+ expect(within(setupDialog).getByText('Set Up Pulse Intelligence')).toBeInTheDocument();
fireEvent.click(within(setupDialog).getByRole('button', { name: /OpenRouter/i }));
fireEvent.input(screen.getByPlaceholderText('sk-or-...'), {
target: { value: 'sk-or-test' },
});
- fireEvent.click(screen.getByRole('button', { name: 'Enable Assistant & Patrol' }));
+ fireEvent.click(within(setupDialog).getByRole('button', { name: 'Enable Pulse Intelligence' }));
await waitFor(() => {
expect(notificationErrorMock).toHaveBeenCalledWith(
@@ -957,7 +1122,7 @@ describe('AISettings provider setup flow', () => {
);
});
expect(String(notificationErrorMock.mock.calls.at(-1)?.[0] ?? '')).toContain(
- 'Unable to save Assistant & Patrol settings.',
+ 'Unable to save Provider & Models settings.',
);
});
@@ -975,13 +1140,13 @@ describe('AISettings provider setup flow', () => {
expect(getSettingsMock).toHaveBeenCalledTimes(1);
});
- fireEvent.click(screen.getByRole('button', { name: /enable assistant and patrol/i }));
+ fireEvent.click(screen.getByRole('button', { name: /enable pulse intelligence/i }));
expect(getModelsMock).not.toHaveBeenCalled();
expect(updateSettingsMock).not.toHaveBeenCalled();
- expect(await screen.findByText('Set Up Assistant & Patrol')).toBeInTheDocument();
+ expect(await screen.findByText('Set Up Pulse Intelligence')).toBeInTheDocument();
expect(
- screen.getByText('Connect a provider to power Pulse Assistant and Patrol.'),
+ screen.getByText('Connect a provider to power Patrol, Assistant, and service context.'),
).toBeInTheDocument();
expect(
screen.queryByText(/Patrol quickstart ready • 25\/25 runs left • no API key needed yet/i),
@@ -1001,12 +1166,12 @@ describe('AISettings provider setup flow', () => {
expect(getSettingsMock).toHaveBeenCalledTimes(1);
});
- fireEvent.click(screen.getByRole('button', { name: /enable assistant and patrol/i }));
+ fireEvent.click(screen.getByRole('button', { name: /enable pulse intelligence/i }));
expect(updateSettingsMock).not.toHaveBeenCalled();
- expect(await screen.findByText('Set Up Assistant & Patrol')).toBeInTheDocument();
+ expect(await screen.findByText('Set Up Pulse Intelligence')).toBeInTheDocument();
expect(
- screen.getByText('Connect a provider to power Pulse Assistant and Patrol.'),
+ screen.getByText('Connect a provider to power Patrol, Assistant, and service context.'),
).toBeInTheDocument();
expect(
screen.queryByText(/Hosted quickstart requires an activated entitlement/i),
@@ -1028,12 +1193,12 @@ describe('AISettings provider setup flow', () => {
expect(getSettingsMock).toHaveBeenCalledTimes(1);
});
- fireEvent.click(screen.getByRole('button', { name: /enable assistant and patrol/i }));
+ fireEvent.click(screen.getByRole('button', { name: /enable pulse intelligence/i }));
expect(updateSettingsMock).not.toHaveBeenCalled();
- expect(await screen.findByText('Set Up Assistant & Patrol')).toBeInTheDocument();
+ expect(await screen.findByText('Set Up Pulse Intelligence')).toBeInTheDocument();
expect(
- screen.getByText('Connect a provider to power Pulse Assistant and Patrol.'),
+ screen.getByText('Connect a provider to power Patrol, Assistant, and service context.'),
).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /open hosted handoff/i })).not.toBeInTheDocument();
expect(
diff --git a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
index 460e6f01b7..117282607b 100644
--- a/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/APITokenManager.test.tsx
@@ -1,27 +1,37 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
+import { Route, Router } from '@solidjs/router';
import type { APITokenRecord } from '@/api/security';
import type { Resource } from '@/types/resource';
import {
+ AI_EXECUTE_SCOPE,
AGENT_REPORT_SCOPE,
AUDIT_READ_SCOPE,
DOCKER_MANAGE_SCOPE,
DOCKER_REPORT_SCOPE,
+ MONITORING_READ_SCOPE,
+ MONITORING_WRITE_SCOPE,
+ SETTINGS_READ_SCOPE,
+ SETTINGS_WRITE_SCOPE,
} from '@/constants/apiScopes';
+import { API_TOKEN_CREATE_ANCHOR, PULSE_MCP_TOKEN_SETUP_PATH } from '@/routing/resourceLinks';
import apiAccessPanelSource from '../APIAccessPanel.tsx?raw';
import apiTokenManagerSource from '../APITokenManager.tsx?raw';
+import { APIAccessPanel } from '../APIAccessPanel';
import { APITokenManager } from '../APITokenManager';
const listTokensMock = vi.fn();
const createTokenMock = vi.fn();
const deleteTokenMock = vi.fn();
+const fetchAgentCapabilitiesManifestMock = vi.fn();
const notificationSuccessMock = vi.fn();
const notificationErrorMock = vi.fn();
const showTokenRevealMock = vi.fn();
const loggerErrorMock = vi.fn();
const markDockerRuntimesTokenRevokedMock = vi.fn();
const markAgentsTokenRevokedMock = vi.fn();
+const scrollIntoViewMock = vi.fn();
let mockResources: Resource[] = [];
@@ -33,6 +43,15 @@ vi.mock('@/api/security', () => ({
},
}));
+vi.mock('@/api/agentCapabilities', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/api/agentCapabilities')>();
+ return {
+ ...actual,
+ fetchAgentCapabilitiesManifest: (...args: unknown[]) =>
+ fetchAgentCapabilitiesManifestMock(...args),
+ };
+});
+
vi.mock('@/stores/notifications', () => ({
notificationStore: {
success: (...args: unknown[]) => notificationSuccessMock(...args),
@@ -101,20 +120,27 @@ const makeResource = (overrides: Partial<Resource> = {}): Resource => ({
...overrides,
});
+const renderAPIAccessPanel = () =>
+ render(() => (
+ <Router>
+ <Route
+ path="/*"
+ component={() => <APIAccessPanel onTokensChanged={vi.fn()} refreshing={false} canManage />}
+ />
+ </Router>
+ ));
+
describe('APITokenManager security surface', () => {
// The API Access tab is the canonical security surface for
- // operator-controlled machine access. Tokens minted here are
- // the credential the agent integrations panel directs operators
- // to use for MCP / HTTP agent wiring. Pin that the agent
- // integrations panel sits on this same tab so the security
- // story stays coherent: minting a token and seeing what an
- // agent does with it live side-by-side, not split across tabs.
- it('hosts the agent integrations panel on the same security surface as token management', () => {
- expect(apiAccessPanelSource).toContain(
- "import AgentIntegrationsPanel from './AgentIntegrationsPanel';",
- );
- expect(apiAccessPanelSource).toContain('<AgentIntegrationsPanel />');
+ // operator-controlled machine access. Pulse Intelligence owns
+ // external-agent setup; API Access only mints and manages the
+ // scoped token that setup links to when credentials are needed.
+ it('keeps API Access separate from Pulse Intelligence external-agent setup', () => {
expect(apiAccessPanelSource).toContain('<APITokenManager');
+ expect(apiAccessPanelSource).toContain('api-access-token-section');
+ expect(apiAccessPanelSource).not.toContain('AgentIntegrationsPanel');
+ expect(apiAccessPanelSource).not.toContain('isExternalAgentSetupHash');
+ expect(apiAccessPanelSource).not.toContain('api-access-external-agent-section');
});
});
@@ -129,9 +155,37 @@ describe('APITokenManager', () => {
loggerErrorMock.mockReset();
markDockerRuntimesTokenRevokedMock.mockReset();
markAgentsTokenRevokedMock.mockReset();
+ fetchAgentCapabilitiesManifestMock.mockReset();
+ scrollIntoViewMock.mockReset();
+ Element.prototype.scrollIntoView = scrollIntoViewMock;
mockResources = [];
listTokensMock.mockResolvedValue([]);
+ fetchAgentCapabilitiesManifestMock.mockResolvedValue({
+ version: 'v1',
+ surfaceContract: {
+ core: { id: 'pulse_intelligence_core', label: 'Pulse Intelligence Core', description: '' },
+ proactiveEngine: { id: 'pulse_patrol', label: 'Pulse Patrol', description: '' },
+ operatorSurfaces: [],
+ },
+ mcpAdapter: {
+ serverName: 'pulse',
+ command: 'pulse-mcp',
+ baseUrlFlag: '--base-url',
+ defaultBaseUrl: 'http://localhost:7655',
+ tokenEnv: 'PULSE_API_TOKEN',
+ configFamilies: [],
+ },
+ requiredScopes: [
+ MONITORING_READ_SCOPE,
+ MONITORING_WRITE_SCOPE,
+ SETTINGS_READ_SCOPE,
+ SETTINGS_WRITE_SCOPE,
+ AI_EXECUTE_SCOPE,
+ ],
+ categories: [],
+ capabilities: [],
+ });
createTokenMock.mockResolvedValue({
token: 'pulse_secret_value',
record: makeToken({
@@ -145,6 +199,20 @@ describe('APITokenManager', () => {
afterEach(() => {
cleanup();
+ window.history.pushState({}, '', '/');
+ });
+
+ it('keeps API Access focused on token management', async () => {
+ window.history.pushState({}, '', '/settings/security/api');
+
+ renderAPIAccessPanel();
+
+ const tokenHeading = await screen.findByRole('heading', { name: 'API tokens' });
+ const tokenSection = tokenHeading.closest('[data-testid="api-access-token-section"]');
+
+ expect(tokenSection).not.toBeNull();
+ expect(screen.queryByRole('heading', { name: 'External agents' })).not.toBeInTheDocument();
+ expect(document.querySelector('[data-testid="api-access-external-agent-section"]')).toBeNull();
});
it('creates scoped tokens from the canonical preset path', async () => {
@@ -204,6 +272,136 @@ describe('APITokenManager', () => {
});
});
+ it('requires an explicit scope selection before generating a token', async () => {
+ render(() => <APITokenManager onTokensChanged={vi.fn()} canManage />);
+
+ await waitFor(() => {
+ expect(listTokensMock).toHaveBeenCalledTimes(1);
+ });
+
+ expect(screen.getByRole('button', { name: 'Full access' })).toHaveAttribute(
+ 'aria-pressed',
+ 'false',
+ );
+ expect(screen.getByRole('button', { name: 'Generate' })).toBeDisabled();
+ expect(
+ screen.getByText(
+ 'Choose a scoped preset for least privilege, or deliberately choose Full access.',
+ ),
+ ).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Kiosk / Monitoring' }));
+
+ expect(screen.getByRole('button', { name: 'Generate' })).not.toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Kiosk / Monitoring' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ expect(screen.getByRole('button', { name: 'Full access' })).toHaveAttribute(
+ 'aria-pressed',
+ 'false',
+ );
+ });
+
+ it('creates Patrol external agent tokens from the live manifest scopes', async () => {
+ createTokenMock.mockResolvedValueOnce({
+ token: 'pulse_agent_secret',
+ record: makeToken({
+ id: 'token-agent',
+ name: 'OpenCode Pulse',
+ scopes: [
+ AI_EXECUTE_SCOPE,
+ MONITORING_READ_SCOPE,
+ MONITORING_WRITE_SCOPE,
+ SETTINGS_READ_SCOPE,
+ SETTINGS_WRITE_SCOPE,
+ ],
+ }),
+ });
+
+ render(() => <APITokenManager onTokensChanged={vi.fn()} canManage />);
+
+ await waitFor(() => {
+ expect(fetchAgentCapabilitiesManifestMock).toHaveBeenCalledTimes(1);
+ expect(listTokensMock).toHaveBeenCalledTimes(1);
+ });
+
+ const preset = await screen.findByRole('button', { name: 'Patrol external agent' });
+ expect(preset).toHaveAttribute(
+ 'title',
+ 'Scopes for connected agents that read Pulse context and request Patrol work.',
+ );
+
+ fireEvent.input(screen.getByPlaceholderText('e.g. Docker / Podman automation'), {
+ target: { value: 'OpenCode Pulse' },
+ });
+ fireEvent.click(preset);
+ fireEvent.click(screen.getByRole('button', { name: 'Generate' }));
+
+ await waitFor(() => {
+ expect(createTokenMock).toHaveBeenCalledWith('OpenCode Pulse', [
+ AI_EXECUTE_SCOPE,
+ MONITORING_READ_SCOPE,
+ MONITORING_WRITE_SCOPE,
+ SETTINGS_READ_SCOPE,
+ SETTINGS_WRITE_SCOPE,
+ ]);
+ });
+
+ expect(showTokenRevealMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ token: 'pulse_agent_secret',
+ source: 'security',
+ record: expect.objectContaining({
+ id: 'token-agent',
+ name: 'OpenCode Pulse',
+ }),
+ }),
+ );
+ });
+
+ it('preselects the Patrol external agent preset from the MCP setup route', async () => {
+ window.history.pushState({}, '', PULSE_MCP_TOKEN_SETUP_PATH);
+ createTokenMock.mockResolvedValueOnce({
+ token: 'pulse_mcp_secret',
+ record: makeToken({
+ id: 'token-mcp',
+ name: 'Patrol external agent',
+ scopes: [
+ AI_EXECUTE_SCOPE,
+ MONITORING_READ_SCOPE,
+ MONITORING_WRITE_SCOPE,
+ SETTINGS_READ_SCOPE,
+ SETTINGS_WRITE_SCOPE,
+ ],
+ }),
+ });
+
+ render(() => <APITokenManager onTokensChanged={vi.fn()} canManage />);
+
+ await waitFor(() => {
+ expect(fetchAgentCapabilitiesManifestMock).toHaveBeenCalledTimes(1);
+ expect(listTokensMock).toHaveBeenCalledTimes(1);
+ });
+ await screen.findByDisplayValue('Patrol external agent');
+ await waitFor(() => {
+ expect(scrollIntoViewMock).toHaveBeenCalledWith({ behavior: 'smooth', block: 'start' });
+ });
+ expect(document.getElementById(API_TOKEN_CREATE_ANCHOR)?.className).toContain('ring-2');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Generate' }));
+
+ await waitFor(() => {
+ expect(createTokenMock).toHaveBeenCalledWith('Patrol external agent', [
+ AI_EXECUTE_SCOPE,
+ MONITORING_READ_SCOPE,
+ MONITORING_WRITE_SCOPE,
+ SETTINGS_READ_SCOPE,
+ SETTINGS_WRITE_SCOPE,
+ ]);
+ });
+ });
+
it('surfaces the dedicated audit scope in presets and grouped custom scopes', async () => {
createTokenMock.mockResolvedValueOnce({
token: 'pulse_audit_secret',
@@ -223,6 +421,15 @@ describe('APITokenManager', () => {
expect(screen.getByRole('button', { name: 'Audit read' })).toBeInTheDocument();
fireEvent.click(screen.getByText('Custom scopes'));
+ expect(screen.getByText('AI')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Pulse Assistant chat' })).toHaveAttribute(
+ 'title',
+ 'Use interactive Pulse Assistant sessions, models, and knowledge endpoints.',
+ );
+ expect(screen.getByRole('button', { name: 'Pulse Intelligence actions' })).toHaveAttribute(
+ 'title',
+ 'Use governed Patrol actions for plans, approvals, policy-allowed fixes, verification, and history.',
+ );
expect(screen.getByText('Security')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Audit logs (read)' })).toBeInTheDocument();
diff --git a/frontend-modern/src/components/Settings/__tests__/AgentIntegrationsPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/AgentIntegrationsPanel.test.tsx
new file mode 100644
index 0000000000..b6f6723823
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/AgentIntegrationsPanel.test.tsx
@@ -0,0 +1,378 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
+import { Route, Router } from '@solidjs/router';
+import type { AgentCapabilitiesManifest } from '@/api/agentCapabilities';
+import {
+ EXTERNAL_AGENT_SETUP_ANCHOR,
+ PATROL_CONTROL_PATH,
+ PULSE_MCP_SETUP_ANCHOR,
+ PULSE_MCP_TOKEN_SETUP_PATH,
+} from '@/routing/resourceLinks';
+import { AgentIntegrationsPanel } from '../AgentIntegrationsPanel';
+
+const mocks = vi.hoisted(() => ({
+ fetchAgentCapabilitiesManifest: vi.fn(),
+}));
+const scrollIntoViewMock = vi.fn();
+
+vi.mock('@/api/agentCapabilities', async () => {
+ const actual =
+ await vi.importActual<typeof import('@/api/agentCapabilities')>('@/api/agentCapabilities');
+ return {
+ ...actual,
+ fetchAgentCapabilitiesManifest: (...args: unknown[]) =>
+ mocks.fetchAgentCapabilitiesManifest(...args),
+ };
+});
+
+const manifest: AgentCapabilitiesManifest = {
+ version: 'v1',
+ surfaceContract: {
+ core: {
+ id: 'pulse_intelligence_core',
+ label: 'Pulse Intelligence Core',
+ description:
+ 'Canonical context, governed actions, safety gates, approval state, action audit, and verification.',
+ },
+ proactiveEngine: {
+ id: 'pulse_patrol',
+ label: 'Pulse Patrol',
+ description: 'The proactive detection and investigation engine.',
+ },
+ operatorSurfaces: [
+ {
+ id: 'pulse_assistant',
+ label: 'Pulse Assistant',
+ description: 'The first-party in-app surface.',
+ native: true,
+ externalAdapter: false,
+ affordances: {
+ tools: true,
+ interactiveQuestions: true,
+ },
+ },
+ {
+ id: 'pulse_mcp',
+ label: 'Pulse MCP',
+ description: 'The external-agent adapter.',
+ native: false,
+ externalAdapter: true,
+ affordances: {
+ tools: true,
+ resources: true,
+ prompts: true,
+ capabilityMetadata: true,
+ },
+ },
+ ],
+ },
+ surfaceToolContracts: [
+ {
+ surfaceId: 'pulse_mcp',
+ surfaceLabel: 'Pulse MCP',
+ toolSource: 'capability_manifest',
+ toolNames: ['get_resource_context'],
+ capabilityNames: ['get_resource_context'],
+ affordances: {
+ tools: true,
+ resources: true,
+ prompts: true,
+ capabilityMetadata: true,
+ },
+ },
+ ],
+ mcpAdapter: {
+ serverName: 'pulse-test',
+ command: 'pulse-test-mcp',
+ baseUrlFlag: '--pulse-url',
+ defaultBaseUrl: 'https://pulse.test',
+ tokenEnv: 'PULSE_TEST_TOKEN',
+ configFamilies: [
+ {
+ id: 'opencode',
+ label: 'Test OpenCode',
+ shape: 'opencode_mcp',
+ clientLabels: ['OpenCode'],
+ },
+ {
+ id: 'claude-style',
+ label: 'Test MCP servers',
+ shape: 'mcp_servers',
+ clientLabels: ['Claude Desktop', 'Claude Code'],
+ },
+ {
+ id: 'custom-mcp',
+ label: 'custom clients',
+ shape: 'custom',
+ clientLabels: ['custom clients'],
+ },
+ ],
+ },
+ requiredScopes: [
+ 'monitoring:read',
+ 'monitoring:write',
+ 'settings:read',
+ 'settings:write',
+ 'ai:execute',
+ ],
+ categories: [
+ {
+ id: 'context',
+ label: 'Context (read-only)',
+ description: 'Discovery and read-only situated reads. Agents start here.',
+ },
+ ],
+ workflowPrompts: [
+ {
+ name: 'pulse_operations_loop',
+ label: 'Ask Patrol to handle an issue',
+ presentationKind: 'workflow',
+ description:
+ 'Have Patrol investigate active findings, follow the configured Patrol mode, take approved actions, verify the outcome, and record what happened.',
+ },
+ {
+ name: 'pulse_investigate_resource',
+ label: 'Investigate resource',
+ presentationKind: 'resource',
+ description: 'Investigate one resource.',
+ arguments: [
+ {
+ name: 'resourceId',
+ description: 'Canonical resource id.',
+ required: true,
+ },
+ ],
+ },
+ ],
+ capabilities: [
+ {
+ name: 'get_fleet_context',
+ description: 'Return a thin per-resource triage rollup.',
+ category: 'context',
+ method: 'GET',
+ path: '/api/agent/fleet-context',
+ scope: 'monitoring:read',
+ actionMode: 'read',
+ approvalPolicy: 'scope_only',
+ errorCodes: ['resource_not_found'],
+ },
+ {
+ name: 'subscribe_events',
+ description: 'Subscribe to Pulse Intelligence events.',
+ category: 'events',
+ method: 'GET',
+ path: '/api/agent/events',
+ scope: 'monitoring:read',
+ actionMode: 'read',
+ approvalPolicy: 'scope_only',
+ },
+ ],
+};
+
+const renderPanel = () =>
+ render(() => (
+ <Router>
+ <Route path="/" component={() => <AgentIntegrationsPanel />} />
+ </Router>
+ ));
+
+describe('AgentIntegrationsPanel', () => {
+ beforeEach(() => {
+ mocks.fetchAgentCapabilitiesManifest.mockReset();
+ mocks.fetchAgentCapabilitiesManifest.mockResolvedValue(manifest);
+ scrollIntoViewMock.mockReset();
+ Element.prototype.scrollIntoView = scrollIntoViewMock;
+ });
+
+ afterEach(() => {
+ cleanup();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('keeps external agent setup brief and governed by Patrol mode', async () => {
+ renderPanel();
+
+ expect(
+ (await screen.findByRole('heading', { name: 'External agents' })).closest(
+ `#${EXTERNAL_AGENT_SETUP_ANCHOR}`,
+ ),
+ ).not.toBeNull();
+ expect(
+ await screen.findByText('Connect external tools to read Pulse context', {
+ exact: false,
+ }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText('Patrol mode and scoped tokens control', { exact: false }),
+ ).toBeInTheDocument();
+ expect(document.body.textContent).not.toContain('Patrol remains the operator');
+ expect(document.body.textContent).not.toContain('Connected tools do not get separate powers');
+ expect(screen.getByRole('link', { name: 'Choose Patrol mode' })).toHaveAttribute(
+ 'href',
+ PATROL_CONTROL_PATH,
+ );
+ expect(screen.getByRole('button', { name: 'Show connector setup' })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ expect(screen.getAllByRole('link', { name: 'Choose Patrol mode' })).toHaveLength(1);
+ expect(
+ screen.queryByRole('heading', { name: 'Connector setup' }),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Create token' })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Show connector setup' }));
+
+ expect(screen.getByRole('button', { name: 'Hide connector setup' })).toHaveAttribute(
+ 'aria-expanded',
+ 'true',
+ );
+ expect(screen.getByRole('heading', { name: 'Connector setup' })).toBeInTheDocument();
+ expect(screen.getByText('Step 1')).toBeInTheDocument();
+ expect(screen.getAllByRole('link', { name: 'Choose Patrol mode' })).toHaveLength(1);
+ expect(screen.getByRole('link', { name: 'Choose Patrol mode' })).toHaveAttribute(
+ 'href',
+ PATROL_CONTROL_PATH,
+ );
+ expect(
+ screen.getByText(
+ 'Required before agents can request Patrol work',
+ {
+ exact: false,
+ },
+ ),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Step 2')).toBeInTheDocument();
+ expect(screen.getByText('Create a scoped token')).toBeInTheDocument();
+ expect(screen.getByText('Patrol external agent')).toBeInTheDocument();
+ expect(
+ screen.getByText('Create a token with the', {
+ exact: false,
+ }),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Step 3')).toBeInTheDocument();
+ expect(screen.getByText('Connect the agent')).toBeInTheDocument();
+ expect(document.body.textContent).toContain('Install the connector');
+ expect(document.body.textContent).toContain('paste the client config');
+ expect(document.body.textContent).not.toContain('The installer and client snippets are below');
+ expect(document.body.textContent).not.toContain('Install the Pulse MCP bridge');
+ expect(document.body.textContent).not.toContain('on the machine that runs the external tool');
+
+ const createTokenLink = screen.getByRole('link', { name: 'Create token' });
+ expect(createTokenLink).toHaveAttribute('href', PULSE_MCP_TOKEN_SETUP_PATH);
+ const installerCommands = screen.getByText('Installer commands').closest('details');
+ expect(installerCommands).not.toBeNull();
+ expect(installerCommands).not.toHaveAttribute('open');
+ expect(document.body.textContent).not.toContain(
+ 'https://github.com/rcourtman/Pulse/releases/latest/download/install-mcp.sh',
+ );
+ expect(document.body.textContent).not.toContain(
+ 'https://github.com/rcourtman/Pulse/releases/latest/download/install-mcp.ps1',
+ );
+ installerCommands!.open = true;
+ fireEvent(installerCommands!, new Event('toggle'));
+ expect(document.body.textContent).toContain(
+ 'https://github.com/rcourtman/Pulse/releases/latest/download/install-mcp.sh',
+ );
+ expect(document.body.textContent).toContain(
+ 'https://github.com/rcourtman/Pulse/releases/latest/download/install-mcp.ps1',
+ );
+ const clientConfigSnippets = screen.getByText('Client config').closest('details');
+ expect(clientConfigSnippets).not.toBeNull();
+ expect(clientConfigSnippets).not.toHaveAttribute('open');
+ expect(document.body.textContent).not.toContain('pulse-test-mcp');
+ expect(document.body.textContent).not.toContain('--pulse-url');
+ expect(document.body.textContent).not.toContain('PULSE_TEST_TOKEN');
+ clientConfigSnippets!.open = true;
+ fireEvent(clientConfigSnippets!, new Event('toggle'));
+ expect(document.body.textContent).toContain('pulse-test-mcp');
+ expect(document.body.textContent).toContain('--pulse-url');
+ expect(document.body.textContent).toContain('PULSE_TEST_TOKEN');
+ expect(screen.getByText('Test OpenCode', { exact: false })).toBeInTheDocument();
+ expect(screen.getByText('Test MCP servers', { exact: false })).toBeInTheDocument();
+ expect(screen.getAllByText('"pulse-test":', { exact: false }).length).toBeGreaterThan(0);
+ const advancedDetails = screen.getByText('Developer details').closest('details');
+ expect(advancedDetails).not.toBeNull();
+ expect(advancedDetails).not.toHaveAttribute('open');
+ expect(
+ screen.queryByText('Only open this when you are building or debugging a client', {
+ exact: false,
+ }),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol access model')).not.toBeInTheDocument();
+ expect(screen.queryByText('Live manifest details')).not.toBeInTheDocument();
+ advancedDetails!.open = true;
+ fireEvent(advancedDetails!, new Event('toggle'));
+ expect(
+ screen.getByText('Only open this when you are building or debugging a client', {
+ exact: false,
+ }),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Patrol access model')).toBeInTheDocument();
+ expect(
+ screen.getByText('Built-in Pulse views and connected clients all sit behind', {
+ exact: false,
+ }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText('Connected agents do not get separate powers', { exact: false }),
+ ).toBeInTheDocument();
+ expect(screen.getAllByText('External agents').length).toBeGreaterThanOrEqual(2);
+ expect(screen.queryByText('Pulse MCP')).not.toBeInTheDocument();
+ expect(screen.getByText('External adapter')).toBeInTheDocument();
+ expect(screen.getAllByText('Actions').length).toBeGreaterThanOrEqual(2);
+ expect(screen.getByText('Interactive questions')).toBeInTheDocument();
+ expect(screen.getByText('Capability metadata')).toBeInTheDocument();
+ expect(screen.getByText('Live manifest details')).toBeInTheDocument();
+ expect(screen.getByText('Manifest scopes:', { exact: false })).toBeInTheDocument();
+ expect(screen.getByText('ai:execute')).toBeInTheDocument();
+ expect(screen.getByText('Agent starting points')).toBeInTheDocument();
+ expect(screen.getByText('(2 from manifest)')).toBeInTheDocument();
+ expect(screen.getByText('Ask Patrol to handle an issue')).toBeInTheDocument();
+ expect(screen.getAllByText('Wire name:').length).toBeGreaterThan(0);
+ expect(screen.getByText('pulse_operations_loop')).toBeInTheDocument();
+ expect(screen.getByText('Patrol')).toBeInTheDocument();
+ expect(screen.getByText('Investigate resource')).toBeInTheDocument();
+ expect(screen.getByText('resourceId')).toBeInTheDocument();
+ expect(screen.getByText('resourceId').closest('p')).toHaveTextContent(
+ 'Arguments: resourceId required',
+ );
+ const mcpToolPosture = screen.getByTestId('agent-mcp-tool-posture');
+ expect(mcpToolPosture.closest('details')).toBe(advancedDetails);
+ expect(mcpToolPosture).toHaveTextContent('External agents expose 1 capability');
+ expect(mcpToolPosture).toHaveTextContent('through Patrol mode');
+ expect(mcpToolPosture.getAttribute('title') || '').toContain('Capability manifest');
+ expect(screen.getByText('Failure codes')).toBeInTheDocument();
+ expect(screen.getByText('(1 from the live manifest)')).toBeInTheDocument();
+ expect(screen.getAllByText('resource_not_found').length).toBeGreaterThanOrEqual(2);
+ expect(screen.getByText('branch on these codes', { exact: false })).toBeInTheDocument();
+ });
+
+ it('scrolls direct setup links to External agents instead of the API token top', async () => {
+ window.history.pushState({}, '', `/#${EXTERNAL_AGENT_SETUP_ANCHOR}`);
+ renderPanel();
+
+ const heading = await screen.findByRole('heading', { name: 'External agents' });
+ const panel = heading.closest(`#${EXTERNAL_AGENT_SETUP_ANCHOR}`);
+
+ await waitFor(() => {
+ expect(scrollIntoViewMock).toHaveBeenCalledWith({ behavior: 'smooth', block: 'start' });
+ });
+ expect(panel?.className).toContain('ring-2');
+ expect(screen.getByRole('heading', { name: 'Connector setup' })).toBeInTheDocument();
+ });
+
+ it('normalizes legacy MCP setup links to external agent setup', async () => {
+ window.history.pushState({}, '', `/#${PULSE_MCP_SETUP_ANCHOR}`);
+ renderPanel();
+
+ const heading = await screen.findByRole('heading', { name: 'External agents' });
+ expect(heading.closest(`#${EXTERNAL_AGENT_SETUP_ANCHOR}`)).not.toBeNull();
+
+ await waitFor(() => {
+ expect(window.location.hash).toBe(`#${EXTERNAL_AGENT_SETUP_ANCHOR}`);
+ });
+ expect(scrollIntoViewMock).toHaveBeenCalledWith({ behavior: 'smooth', block: 'start' });
+ expect(screen.getByRole('heading', { name: 'Connector setup' })).toBeInTheDocument();
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/CopyCommandBlock.test.tsx b/frontend-modern/src/components/Settings/__tests__/CopyCommandBlock.test.tsx
new file mode 100644
index 0000000000..9b776eda31
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/CopyCommandBlock.test.tsx
@@ -0,0 +1,39 @@
+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { CopyCommandBlock } from '../CopyCommandBlock';
+import { copyToClipboard } from '@/utils/clipboard';
+
+vi.mock('@/utils/clipboard', () => ({
+ copyToClipboard: vi.fn(async () => true),
+}));
+
+describe('CopyCommandBlock', () => {
+ afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ });
+
+ it('copies through the shared clipboard utility before notifying callers', async () => {
+ const command = 'pulse-mcp --base-url http://localhost:7655';
+ const onCopy = vi.fn();
+
+ render(() => <CopyCommandBlock command={command} onCopy={onCopy} />);
+
+ await fireEvent.click(screen.getByRole('button', { name: 'Copy to clipboard' }));
+
+ await waitFor(() => expect(copyToClipboard).toHaveBeenCalledWith(command));
+ expect(onCopy).toHaveBeenCalledWith(command);
+ });
+
+ it('does not report copied state when clipboard copy fails', async () => {
+ vi.mocked(copyToClipboard).mockResolvedValueOnce(false);
+ const onCopy = vi.fn();
+
+ render(() => <CopyCommandBlock command="install command" onCopy={onCopy} />);
+
+ await fireEvent.click(screen.getByRole('button', { name: 'Copy to clipboard' }));
+
+ await waitFor(() => expect(copyToClipboard).toHaveBeenCalledWith('install command'));
+ expect(onCopy).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/DiagnosticsResultsPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/DiagnosticsResultsPanel.test.tsx
index d0a09375ec..7f1c70d121 100644
--- a/frontend-modern/src/components/Settings/__tests__/DiagnosticsResultsPanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/DiagnosticsResultsPanel.test.tsx
@@ -8,6 +8,45 @@ describe('DiagnosticsResultsPanel', () => {
cleanup();
});
+ it('labels Pulse Assistant diagnostics as native runtime status', () => {
+ const diagnosticsData = {
+ version: '6.0.0',
+ runtime: 'go',
+ uptime: 3600,
+ nodes: [],
+ pbs: [],
+ system: {
+ os: 'linux',
+ arch: 'amd64',
+ goVersion: 'go1.25',
+ numCPU: 8,
+ numGoroutine: 32,
+ memoryMB: 128,
+ },
+ aiChat: {
+ enabled: true,
+ running: true,
+ healthy: true,
+ model: 'ollama:llama3',
+ assistantRuntimeConnected: true,
+ notes: [],
+ },
+ errors: [],
+ } as DiagnosticsData;
+
+ render(() => (
+ <DiagnosticsResultsPanel
+ diagnosticsData={diagnosticsData}
+ loading={false}
+ onRunDiagnostics={() => {}}
+ />
+ ));
+
+ expect(screen.getByText('Pulse Assistant Service')).toBeInTheDocument();
+ expect(screen.getByText('Assistant runtime')).toBeInTheDocument();
+ expect(screen.queryByText('MCP Connection')).not.toBeInTheDocument();
+ });
+
it('does not render internal analytics fields from diagnostics payloads', () => {
const diagnosticsData = {
version: '6.0.0',
diff --git a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx
index aad55235df..6f7b066cd6 100644
--- a/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/ProLicensePanel.test.tsx
@@ -3,6 +3,7 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/te
import { Route, Router } from '@solidjs/router';
import type { LicenseEntitlements } from '@/api/license';
+import type { AgentOperationsLoopStatus } from '@/api/agentCapabilities';
import { ProLicensePanel } from '../ProLicensePanel';
import proLicensePanelSource from '../ProLicensePanel.tsx?raw';
import proLicensePanelStateSource from '../useProLicensePanelState.ts?raw';
@@ -25,6 +26,8 @@ import {
SELF_HOSTED_PRO_BILLING_USAGE_SECTION_ID,
SELF_HOSTED_PRO_BILLING_PLAN_ROUTE,
} from '@/utils/pricingHandoff';
+import { PATROL_CONTROL_STARTER_URL } from '@/utils/licensePresentation';
+import { PATROL_CONTROL_PATH } from '@/routing/resourceLinks';
let mockEntitlements: LicenseEntitlements | null = null;
@@ -54,6 +57,43 @@ const useLocationMock = vi.fn(() => ({
const navigateMock = vi.fn();
const getUpgradeActionDestinationMock = vi.hoisted(() => vi.fn());
const getUpgradeActionUrlOrFallbackMock = vi.hoisted(() => vi.fn());
+const fetchAgentOperationsLoopStatusMock = vi.hoisted(() => vi.fn());
+
+const buildOperationsLoopStatus = (
+ overrides: Partial<AgentOperationsLoopStatus> = {},
+): AgentOperationsLoopStatus => ({
+ nextAction: 'run_patrol',
+ progressLabel: 'No Patrol work activity yet.',
+ steps: [],
+ patrolEvidenceCount: 0,
+ patrolIssueEvidenceCount: 0,
+ activeFindingCount: 0,
+ pendingApprovalCount: 0,
+ governedActionCount: 0,
+ approvedDecisionCount: 0,
+ rejectedDecisionCount: 0,
+ verifiedOutcomeCount: 0,
+ operationsLoopStarterCount: 0,
+ assistantOperationsLoopStarterCount: 0,
+ patrolOperationsLoopStarterCount: 0,
+ patrolControlOperationsLoopStarterCount: 0,
+ patrolControlCompletedOperationsLoopCount: 0,
+ patrolControlResolvedOperationsLoopCount: 0,
+ patrolControlValueState: 'not_started',
+ patrolAutonomyOperationsLoopStarterCount: 0,
+ patrolAutonomyCompletedOperationsLoopCount: 0,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ patrolAutonomyValueState: 'not_started',
+ proActivationOperationsLoopStarterCount: 0,
+ proActivationCompletedOperationsLoopCount: 0,
+ proActivationResolvedOperationsLoopCount: 0,
+ proActivationValueProofState: 'not_started',
+ mcpOperationsLoopStarterCount: 0,
+ externalAgentReady: false,
+ windowStart: '2026-06-21T00:00:00Z',
+ generatedAt: '2026-06-21T00:00:00Z',
+ ...overrides,
+});
vi.mock('@solidjs/router', async (importOriginal) => {
const actual = await importOriginal<typeof import('@solidjs/router')>();
@@ -95,6 +135,11 @@ vi.mock('@/api/license', () => ({
},
}));
+vi.mock('@/api/agentCapabilities', () => ({
+ fetchAgentOperationsLoopStatus: (...args: unknown[]) =>
+ fetchAgentOperationsLoopStatusMock(...args),
+}));
+
vi.mock('@/stores/notifications', () => ({
notificationStore: {
success: (...args: unknown[]) => notificationSuccessMock(...args),
@@ -136,9 +181,11 @@ describe('ProLicensePanel', () => {
navigateMock.mockReset();
getUpgradeActionDestinationMock.mockReset();
getUpgradeActionUrlOrFallbackMock.mockReset();
+ fetchAgentOperationsLoopStatusMock.mockReset();
loadRuntimeLicenseStatusMock.mockResolvedValue(undefined);
loadCommercialPostureMock.mockResolvedValue(undefined);
loadLicenseEntitlementsMock.mockResolvedValue(undefined);
+ fetchAgentOperationsLoopStatusMock.mockResolvedValue(buildOperationsLoopStatus());
licenseEntitlementsLoadErrorMock.mockReturnValue(null);
startProTrialMock.mockResolvedValue(undefined);
activateLicenseMock.mockResolvedValue({ success: true });
@@ -189,7 +236,7 @@ describe('ProLicensePanel', () => {
expect(loadCommercialPostureMock).not.toHaveBeenCalled();
expect(screen.getByText('License and billing details are hidden')).toBeInTheDocument();
expect(screen.getByText(/instead of creating a demo license/i)).toBeInTheDocument();
- expect(screen.queryByText('Self-hosted plan')).not.toBeInTheDocument();
+ expect(screen.queryByText('Plans & Billing')).not.toBeInTheDocument();
expect(screen.queryByText('Monitored Systems')).not.toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /start 14-day pro trial/i }),
@@ -203,7 +250,7 @@ describe('ProLicensePanel', () => {
expect(loadLicenseEntitlementsMock).toHaveBeenCalled();
});
- expect(screen.getByText('Self-hosted plan')).toBeInTheDocument();
+ expect(screen.getByText('Plans & Billing')).toBeInTheDocument();
expect(screen.getByText('Current plan: Community')).toBeInTheDocument();
expect(screen.queryByRole('tab', { name: 'Usage' })).not.toBeInTheDocument();
expect(
@@ -220,11 +267,11 @@ describe('ProLicensePanel', () => {
expect(screen.getByText('Current plan: Community')).toBeInTheDocument();
expect(screen.queryByText(/^Expired$/)).not.toBeInTheDocument();
- expect(screen.queryByText('Compare self-hosted plans')).not.toBeInTheDocument();
- expect(screen.queryByText('Optional extras')).not.toBeInTheDocument();
- expect(screen.queryByText('What Relay adds')).not.toBeInTheDocument();
- expect(screen.queryByText('What Pulse Pro adds')).not.toBeInTheDocument();
- expect(screen.queryByRole('link', { name: 'Compare plans' })).not.toBeInTheDocument();
+ expect(screen.queryByText('Select a plan')).not.toBeInTheDocument();
+ expect(screen.queryByText('Available plans')).not.toBeInTheDocument();
+ expect(screen.queryByText('Relay plan')).not.toBeInTheDocument();
+ expect(screen.queryByText('Pulse Pro plan')).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'View plans' })).not.toBeInTheDocument();
});
it('opens compare-plan checkout from the explicit self-hosted billing handoff', async () => {
@@ -240,7 +287,7 @@ describe('ProLicensePanel', () => {
expect(loadLicenseEntitlementsMock).toHaveBeenCalled();
});
- await fireEvent.click(screen.getAllByRole('link', { name: 'Compare plans' })[0]);
+ await fireEvent.click(screen.getAllByRole('link', { name: 'View plans' })[0]);
});
it('keeps explicit self-hosted plan comparison focused on optional paid extras', async () => {
@@ -256,19 +303,19 @@ describe('ProLicensePanel', () => {
expect(loadLicenseEntitlementsMock).toHaveBeenCalled();
});
- expect(screen.getByText('Compare self-hosted plans')).toBeInTheDocument();
- expect(screen.getByText('Optional extras')).toBeInTheDocument();
- expect(screen.getByText('What Relay adds')).toBeInTheDocument();
- expect(screen.getByText('What Pulse Pro adds')).toBeInTheDocument();
- expect(screen.getByText('Pulse Relay (Remote Access)')).toBeInTheDocument();
- expect(screen.getByText('Pulse Mobile Pairing')).toBeInTheDocument();
- expect(screen.getByText('Push Notifications')).toBeInTheDocument();
- expect(screen.getByText('Alert Root-Cause Analysis')).toBeInTheDocument();
- expect(screen.getByText('Safe Remediation Workflows')).toBeInTheDocument();
+ expect(screen.getByText('Select a plan')).toBeInTheDocument();
+ expect(screen.getByText('Available plans')).toBeInTheDocument();
+ expect(screen.getByText('Relay plan')).toBeInTheDocument();
+ expect(screen.getByText('Pulse Pro plan')).toBeInTheDocument();
+ expect(screen.getByText('Remote web access via Relay')).toBeInTheDocument();
+ expect(screen.getByText('Pulse Mobile pairing')).toBeInTheDocument();
+ expect(screen.getByText('Push notifications')).toBeInTheDocument();
+ expect(screen.getByText('Choose Patrol mode')).toBeInTheDocument();
+ expect(screen.getByText('Patrol investigates issues')).toBeInTheDocument();
+ expect(screen.getByText('Patrol handles safe fixes')).toBeInTheDocument();
expect(screen.getByText('90-day metric history')).toBeInTheDocument();
- expect(screen.getByText('Audit Logging')).toBeInTheDocument();
- expect(screen.getByText('PDF/CSV Reporting')).toBeInTheDocument();
- expect(screen.getByText('Centralized Agent Profiles')).toBeInTheDocument();
+ expect(screen.getByText('RBAC and audit logging')).toBeInTheDocument();
+ expect(screen.getByText('Agent profiles · PDF/CSV reports')).toBeInTheDocument();
expect(screen.queryByText(/unlimited/i)).not.toBeInTheDocument();
expect(screen.queryByText(/trial/i)).not.toBeInTheDocument();
@@ -295,6 +342,32 @@ describe('ProLicensePanel', () => {
expect(screen.queryByText('Your Pro trial has ended')).not.toBeInTheDocument();
});
+ it.each([
+ ['Community', 'community'],
+ ['Relay', 'relay'],
+ ])('does not load Patrol operator status for %s plans', async (planName, tier) => {
+ mockEntitlements = {
+ capabilities: [],
+ limits: [],
+ subscription_state: 'active',
+ upgrade_reasons: [],
+ tier,
+ trial_eligible: false,
+ };
+
+ renderPanel();
+
+ await waitFor(() => {
+ expect(loadLicenseEntitlementsMock).toHaveBeenCalled();
+ });
+ await waitFor(() => {
+ expect(screen.getByText(`Current plan: ${planName}`)).toBeInTheDocument();
+ });
+
+ expect(fetchAgentOperationsLoopStatusMock).not.toHaveBeenCalled();
+ expect(screen.queryByText('Patrol work')).not.toBeInTheDocument();
+ });
+
it('renders trial countdown from entitlements payload', async () => {
mockEntitlements = {
capabilities: ['ai_patrol', 'ai_autofix'],
@@ -318,7 +391,262 @@ describe('ProLicensePanel', () => {
expect(screen.getAllByText('Trial').length).toBeGreaterThan(0);
expect(screen.getByText('7')).toBeInTheDocument();
- expect(screen.getByText('Safe Remediation Workflows')).toBeInTheDocument();
+ expect(screen.getByText('Patrol Handles Safe Fixes')).toBeInTheDocument();
+ });
+
+ it('keeps the Patrol mode entry point visible for existing active Pro plans', async () => {
+ mockEntitlements = {
+ capabilities: ['relay', 'mobile_app', 'push_notifications', 'ai_autofix'],
+ limits: [],
+ subscription_state: 'active',
+ upgrade_reasons: [],
+ tier: 'pro',
+ licensed_email: '[email protected]',
+ trial_eligible: false,
+ runtime: PRO_RUNTIME_IDENTITY,
+ };
+
+ renderPanel();
+
+ await waitFor(() => {
+ expect(screen.getByText('Current plan: Pulse Pro')).toBeInTheDocument();
+ });
+
+ expect(screen.queryByText('Pulse Pro is now active')).not.toBeInTheDocument();
+ const patrolControlLink = screen.getByRole('link', { name: 'Choose Patrol mode' });
+ expect(patrolControlLink).toHaveAttribute('href', PATROL_CONTROL_STARTER_URL);
+ expect(patrolControlLink).not.toHaveAttribute('target');
+ patrolControlLink.addEventListener('click', (event) => event.preventDefault());
+ fireEvent.click(patrolControlLink);
+ });
+
+ it('keeps external-agent proof behind Patrol mode presentation', async () => {
+ mockEntitlements = {
+ capabilities: [
+ 'relay',
+ 'mobile_app',
+ 'push_notifications',
+ 'ai_alerts',
+ 'ai_autofix',
+ 'rbac',
+ 'audit_logging',
+ 'advanced_reporting',
+ 'agent_profiles',
+ ],
+ limits: [],
+ subscription_state: 'active',
+ upgrade_reasons: [],
+ tier: 'pro',
+ licensed_email: '[email protected]',
+ max_history_days: 90,
+ trial_eligible: false,
+ runtime: PRO_RUNTIME_IDENTITY,
+ };
+ fetchAgentOperationsLoopStatusMock.mockResolvedValue(
+ buildOperationsLoopStatus({
+ nextAction: 'open_mcp',
+ progressLabel: 'Legacy status asked for MCP readiness after the outcome was verified.',
+ patrolControlOperationsLoopStarterCount: 1,
+ patrolControlResolvedOperationsLoopCount: 0,
+ patrolControlValueState: 'verified_needs_mcp',
+ externalAgentReady: false,
+ }),
+ );
+
+ renderPanel();
+
+ await waitFor(() => {
+ expect(screen.getByText('Current plan: Pulse Pro')).toBeInTheDocument();
+ });
+
+ await waitFor(() => {
+ expect(fetchAgentOperationsLoopStatusMock).toHaveBeenCalled();
+ });
+ expect(screen.queryByText('Patrol work')).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol autonomy loop')).not.toBeInTheDocument();
+ expect(screen.queryByText('Verified')).not.toBeInTheDocument();
+ expect(
+ screen.queryByText(
+ 'Patrol handled an infrastructure issue, verified the outcome, and recorded what happened.',
+ ),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByText('Legacy status asked for MCP readiness after the outcome was verified.'),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText(/Continue through Patrol investigation/i)).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Patrol history' })).not.toBeInTheDocument();
+ const patrolControlLink = screen.getByRole('link', { name: 'Choose Patrol mode' });
+ expect(patrolControlLink).toHaveAttribute('href', PATROL_CONTROL_STARTER_URL);
+ });
+
+ it('does not turn legacy Pro activation starter evidence into plan-page Patrol work', async () => {
+ mockEntitlements = {
+ capabilities: [
+ 'relay',
+ 'mobile_app',
+ 'push_notifications',
+ 'ai_alerts',
+ 'ai_autofix',
+ 'rbac',
+ 'audit_logging',
+ 'advanced_reporting',
+ 'agent_profiles',
+ ],
+ limits: [],
+ subscription_state: 'active',
+ upgrade_reasons: [],
+ tier: 'pro',
+ licensed_email: '[email protected]',
+ max_history_days: 90,
+ trial_eligible: false,
+ runtime: PRO_RUNTIME_IDENTITY,
+ };
+ fetchAgentOperationsLoopStatusMock.mockResolvedValue(
+ buildOperationsLoopStatus({
+ nextAction: 'run_patrol',
+ progressLabel: 'Legacy Pro activation entry recorded.',
+ proActivationOperationsLoopStarterCount: 1,
+ proActivationCompletedOperationsLoopCount: 0,
+ proActivationResolvedOperationsLoopCount: 0,
+ proActivationValueProofState: 'in_progress',
+ externalAgentReady: false,
+ }),
+ );
+
+ renderPanel();
+
+ await waitFor(() => {
+ expect(screen.getByText('Current plan: Pulse Pro')).toBeInTheDocument();
+ });
+
+ await waitFor(() => {
+ expect(fetchAgentOperationsLoopStatusMock).toHaveBeenCalled();
+ });
+ expect(screen.queryByText('Patrol work')).not.toBeInTheDocument();
+ expect(screen.queryByText('Started')).not.toBeInTheDocument();
+ expect(screen.queryByText('Legacy Pro activation entry recorded.')).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Continue Patrol work' })).not.toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Choose Patrol mode' })).toHaveAttribute(
+ 'href',
+ PATROL_CONTROL_STARTER_URL,
+ );
+ });
+
+ it('keeps terminal Patrol decisions out of plan capability details', async () => {
+ mockEntitlements = {
+ capabilities: [
+ 'relay',
+ 'mobile_app',
+ 'push_notifications',
+ 'ai_alerts',
+ 'ai_autofix',
+ 'rbac',
+ 'audit_logging',
+ 'advanced_reporting',
+ 'agent_profiles',
+ ],
+ limits: [],
+ subscription_state: 'active',
+ upgrade_reasons: [],
+ tier: 'pro',
+ licensed_email: '[email protected]',
+ max_history_days: 90,
+ trial_eligible: false,
+ runtime: PRO_RUNTIME_IDENTITY,
+ };
+ fetchAgentOperationsLoopStatusMock.mockResolvedValue(
+ buildOperationsLoopStatus({
+ nextAction: 'complete',
+ progressLabel:
+ 'Patrol recorded a rejected change decision. Nothing was changed; approve a safer fix before marking the issue resolved.',
+ patrolControlOperationsLoopStarterCount: 1,
+ patrolControlCompletedOperationsLoopCount: 1,
+ patrolControlResolvedOperationsLoopCount: 0,
+ patrolControlValueState: 'governed_decision_recorded',
+ externalAgentReady: false,
+ }),
+ );
+
+ renderPanel();
+
+ await waitFor(() => {
+ expect(screen.getByText('Current plan: Pulse Pro')).toBeInTheDocument();
+ });
+
+ await waitFor(() => {
+ expect(fetchAgentOperationsLoopStatusMock).toHaveBeenCalled();
+ });
+ expect(screen.queryByText('Patrol work')).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol autonomy loop')).not.toBeInTheDocument();
+ expect(screen.queryByText('Decision recorded')).not.toBeInTheDocument();
+ expect(
+ screen.getByText(
+ 'Pulse Pro is active on this instance. Review the current Patrol decision.',
+ ),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(/External-agent setup/i)).not.toBeInTheDocument();
+ const patrolControlLink = screen.getByRole('link', { name: 'Review Patrol decision' });
+ expect(patrolControlLink).toHaveAttribute('href', PATROL_CONTROL_PATH);
+ patrolControlLink.addEventListener('click', (event) => event.preventDefault());
+ fireEvent.click(patrolControlLink);
+ });
+
+ it('keeps verified Patrol history behind the Patrol mode action', async () => {
+ mockEntitlements = {
+ capabilities: [
+ 'relay',
+ 'mobile_app',
+ 'push_notifications',
+ 'ai_alerts',
+ 'ai_autofix',
+ 'rbac',
+ 'audit_logging',
+ 'advanced_reporting',
+ 'agent_profiles',
+ ],
+ limits: [],
+ subscription_state: 'active',
+ upgrade_reasons: [],
+ tier: 'pro',
+ licensed_email: '[email protected]',
+ max_history_days: 90,
+ trial_eligible: false,
+ runtime: PRO_RUNTIME_IDENTITY,
+ };
+ fetchAgentOperationsLoopStatusMock.mockResolvedValue(
+ buildOperationsLoopStatus({
+ nextAction: 'complete',
+ progressLabel:
+ 'Patrol verified the issue outcome and recorded the governed action history.',
+ patrolControlOperationsLoopStarterCount: 1,
+ patrolControlResolvedOperationsLoopCount: 1,
+ patrolControlValueState: 'verified',
+ externalAgentReady: true,
+ }),
+ );
+
+ renderPanel();
+
+ await waitFor(() => {
+ expect(screen.getByText('Current plan: Pulse Pro')).toBeInTheDocument();
+ });
+
+ await waitFor(() => {
+ expect(fetchAgentOperationsLoopStatusMock).toHaveBeenCalled();
+ });
+ expect(screen.queryByText('Patrol work')).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol autonomy loop')).not.toBeInTheDocument();
+ expect(screen.queryByText('Verified')).not.toBeInTheDocument();
+ expect(
+ screen.queryByText(
+ 'Patrol handled an infrastructure issue, verified the outcome, and recorded what happened.',
+ ),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Patrol history' })).not.toBeInTheDocument();
+ const patrolControlLink = screen.getByRole('link', { name: 'Choose Patrol mode' });
+ expect(patrolControlLink).toHaveAttribute('href', PATROL_CONTROL_STARTER_URL);
+ patrolControlLink.addEventListener('click', (event) => event.preventDefault());
+ fireEvent.click(patrolControlLink);
});
it('shows active recurring v5 plan terms as unmetered even if stale limit metadata is present', async () => {
@@ -378,9 +706,7 @@ describe('ProLicensePanel', () => {
expect(screen.getByText('V5 Lifetime Grandfathered')).toBeInTheDocument();
expect(
- screen.getByText(
- 'See which self-hosted tier this instance is using and which capabilities are available on this install.',
- ),
+ screen.getByText('Current tier and enabled capabilities.'),
).toBeInTheDocument();
expect(screen.queryByText('Included Monitored Systems')).not.toBeInTheDocument();
expect(screen.queryByText('Guest Capacity')).not.toBeInTheDocument();
@@ -499,27 +825,45 @@ describe('ProLicensePanel', () => {
expect(screen.getByText('Current plan: Pulse Pro')).toBeInTheDocument();
expect(
screen.getByText(
- 'Pulse Pro is active on this instance. Root-cause analysis, safe remediation workflows, 90-day history, and admin/reporting extras are available right now.',
+ 'Pulse Pro is active on this instance. It includes Patrol modes, 90-day metric history, RBAC, audit logs, reports, and agent profiles.',
),
).toBeInTheDocument();
expect(screen.getByText('Primary capabilities')).toBeInTheDocument();
- expect(screen.getByText('Alert Root-Cause Analysis')).toBeInTheDocument();
- expect(screen.getByText('Safe Remediation Workflows')).toBeInTheDocument();
+ expect(screen.getByText('Patrol Investigates Issues')).toBeInTheDocument();
+ expect(screen.getByText('Patrol Handles Safe Fixes')).toBeInTheDocument();
expect(screen.getByText('Included extras')).toBeInTheDocument();
- expect(screen.getByText('Pulse Pro value proof')).toBeInTheDocument();
+ expect(screen.getByText('Capability details')).toBeInTheDocument();
+ expect(screen.getByText('(5 items ready)')).toBeInTheDocument();
+ const readinessDetails = screen
+ .getByText('Capability details')
+ .closest('details') as HTMLDetailsElement | null;
+ expect(readinessDetails).not.toBeNull();
+ expect(readinessDetails?.open).toBe(false);
expect(
screen.getByText(
- "These checks come from this instance's entitlement and runtime payloads, not from public pricing copy.",
+ 'Open this only when a Pro capability looks unavailable. Normal setup is choosing Patrol mode.',
),
).toBeInTheDocument();
expect(screen.getByText('Remote access, pairing, and push')).toBeInTheDocument();
- expect(screen.getByText('Root-cause analysis and remediation')).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ 'Relay, Pulse Mobile pairing, and push notifications are available on this instance.',
+ ),
+ ).toBeInTheDocument();
+ expect(screen.getByText('Patrol investigation and remediation')).toBeInTheDocument();
expect(screen.getByText('Team and admin controls')).toBeInTheDocument();
expect(screen.getAllByText('Active').length).toBeGreaterThanOrEqual(4);
+ expect(
+ screen.queryByText(new RegExp(['optional', 'activation'].join(' '), 'i')),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByText(new RegExp(['recover', 'activation'].join(' '), 'i')),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText(/entitlement payload/i)).not.toBeInTheDocument();
expect(screen.queryByText('Needs attention')).not.toBeInTheDocument();
- expect(screen.queryByText('Optional extras')).not.toBeInTheDocument();
+ expect(screen.queryByText('Available plans')).not.toBeInTheDocument();
expect(screen.getByText('90 days')).toBeInTheDocument();
- expect(screen.getByText('Analysis, remediation, and admin controls')).toBeInTheDocument();
+ expect(screen.getByText('Patrol modes, history, and admin controls')).toBeInTheDocument();
expect(screen.queryByText('Guest Capacity')).not.toBeInTheDocument();
expect(screen.queryByText('Included Monitored Systems')).not.toBeInTheDocument();
expect(screen.queryByText('Monitored-system policy')).not.toBeInTheDocument();
@@ -547,14 +891,14 @@ describe('ProLicensePanel', () => {
expect(
screen.getByText(
- 'Relay is active on this instance. Remote web access, Pulse Mobile pairing, push notifications, and longer history are available right now.',
+ 'Relay is active on this instance. It includes remote web access, Pulse Mobile pairing, push notifications, and 14-day metric history.',
),
).toBeInTheDocument();
- expect(screen.queryByText('Optional extras')).not.toBeInTheDocument();
- expect(screen.queryByText('What Relay adds')).not.toBeInTheDocument();
- expect(screen.queryByText('What Pulse Pro adds')).not.toBeInTheDocument();
- expect(screen.queryByRole('link', { name: 'See all plans' })).not.toBeInTheDocument();
- expect(screen.getByText('Relay value proof')).toBeInTheDocument();
+ expect(screen.queryByText('Available plans')).not.toBeInTheDocument();
+ expect(screen.queryByText('Relay plan')).not.toBeInTheDocument();
+ expect(screen.queryByText('Pulse Pro plan')).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'View plans' })).not.toBeInTheDocument();
+ expect(screen.getByText('Relay status')).toBeInTheDocument();
expect(screen.getByText('Remote access, pairing, and push')).toBeInTheDocument();
expect(screen.getAllByText('14-day metric history').length).toBeGreaterThan(0);
expect(screen.getByText('Pulse Relay (Remote Access)')).toBeInTheDocument();
@@ -734,8 +1078,8 @@ describe('ProLicensePanel', () => {
// Verify self-hosted displayable capabilities render with their expected labels.
expect(screen.getByText('Pulse Patrol')).toBeInTheDocument();
- expect(screen.getByText('Alert Root-Cause Analysis')).toBeInTheDocument();
- expect(screen.getByText('Safe Remediation Workflows')).toBeInTheDocument();
+ expect(screen.getByText('Patrol Investigates Issues')).toBeInTheDocument();
+ expect(screen.getByText('Patrol Handles Safe Fixes')).toBeInTheDocument();
expect(screen.getByText('Update Alerts')).toBeInTheDocument();
expect(screen.getByText('Role-Based Access Control (RBAC)')).toBeInTheDocument();
expect(screen.getByText('Audit Logging')).toBeInTheDocument();
@@ -755,29 +1099,27 @@ describe('ProLicensePanel', () => {
it('shows migration guidance when the pasted key looks like a legacy v5 license', async () => {
renderPanel();
- fireEvent.click(screen.getByText('Use existing key'));
+ fireEvent.click(screen.getByText('Manual key recovery'));
- fireEvent.input(screen.getByLabelText(/license or activation key/i), {
+ fireEvent.input(screen.getByLabelText(/license key/i), {
target: { value: 'header.payload.signature' },
});
expect(screen.getByText('Legacy v5 license detected')).toBeInTheDocument();
- expect(
- screen.getByText(/exchange this key into the v6 activation model automatically/i),
- ).toBeInTheDocument();
+ expect(screen.getByText(/migrate this key automatically/i)).toBeInTheDocument();
});
it.each([
{
purchase: SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED,
title: 'Pulse Pro is now active',
- actionLabel: null,
- actionHref: null,
+ actionLabel: 'Choose Patrol mode',
+ actionHref: PATROL_CONTROL_STARTER_URL,
},
{
purchase: SELF_HOSTED_PRO_BILLING_PURCHASE_CANCELLED,
title: 'Checkout cancelled',
- actionLabel: 'Compare plans',
+ actionLabel: 'View plans',
actionHref: getSelfHostedPurchaseStartUrl(SELF_HOSTED_PRO_BILLING_PLAN_SELECTION_INTENT),
redirectedHref: getSelfHostedBillingHref('plan', {
intent: SELF_HOSTED_PRO_BILLING_PLAN_SELECTION_INTENT,
@@ -786,12 +1128,12 @@ describe('ProLicensePanel', () => {
{
purchase: SELF_HOSTED_PRO_BILLING_PURCHASE_EXPIRED,
title: 'Upgrade return expired',
- actionLabel: 'Compare plans',
+ actionLabel: 'View plans',
actionHref: getSelfHostedPurchaseStartUrl(),
},
{
purchase: SELF_HOSTED_PRO_BILLING_PURCHASE_FAILED,
- title: 'Activation needs attention',
+ title: 'Plan needs attention',
actionLabel: 'Open recovery',
actionHref: getSelfHostedBillingHref('plan', {
detail: SELF_HOSTED_PRO_BILLING_RECOVERY_DETAIL,
@@ -841,10 +1183,18 @@ describe('ProLicensePanel', () => {
expect(screen.getByText(title)).toBeInTheDocument();
if (purchase === SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED) {
expect(
- screen.getByText(/Checkout completed and this instance is now running Pulse Pro/i),
+ screen.getByText(
+ /Checkout completed and Pulse Pro is active\. Choose Patrol mode\./i,
+ ),
).toBeInTheDocument();
expect(screen.getByText('Available now on this instance')).toBeInTheDocument();
- expect(screen.getAllByText('Safe Remediation Workflows').length).toBeGreaterThan(0);
+ expect(screen.getAllByText('Patrol Handles Safe Fixes').length).toBeGreaterThan(0);
+ expect(screen.getAllByRole('link', { name: 'Choose Patrol mode' })).toHaveLength(1);
+ const patrolControlLink = screen.getByRole('link', { name: 'Choose Patrol mode' });
+ expect(patrolControlLink).toHaveAttribute('href', PATROL_CONTROL_STARTER_URL);
+ expect(patrolControlLink).not.toHaveAttribute('target');
+ patrolControlLink.addEventListener('click', (event) => event.preventDefault());
+ fireEvent.click(patrolControlLink);
}
if (actionLabel && actionHref) {
const actionLinks = screen.getAllByRole('link', { name: actionLabel });
@@ -859,6 +1209,49 @@ describe('ProLicensePanel', () => {
},
);
+ it('keeps purchase activation success on Patrol mode when history is already verified', async () => {
+ mockEntitlements = {
+ capabilities: ['relay', 'mobile_app', 'push_notifications', 'ai_autofix'],
+ limits: [],
+ subscription_state: 'active',
+ upgrade_reasons: [],
+ tier: 'pro',
+ licensed_email: '[email protected]',
+ trial_eligible: false,
+ runtime: PRO_RUNTIME_IDENTITY,
+ };
+ fetchAgentOperationsLoopStatusMock.mockResolvedValue(
+ buildOperationsLoopStatus({
+ nextAction: 'complete',
+ progressLabel:
+ 'Patrol verified the issue outcome and recorded the governed action history.',
+ patrolControlOperationsLoopStarterCount: 1,
+ patrolControlCompletedOperationsLoopCount: 1,
+ patrolControlResolvedOperationsLoopCount: 1,
+ patrolControlValueState: 'verified',
+ externalAgentReady: true,
+ }),
+ );
+ useLocationMock.mockReturnValue({
+ search: `?purchase=${SELF_HOSTED_PRO_BILLING_PURCHASE_ACTIVATED}`,
+ pathname: '/settings/system/billing/plan',
+ hash: '',
+ });
+
+ renderPanel();
+
+ expect(screen.getByText('Pulse Pro is now active')).toBeInTheDocument();
+ await waitFor(() => {
+ expect(screen.getByRole('link', { name: 'Choose Patrol mode' })).toBeInTheDocument();
+ });
+
+ expect(screen.queryByRole('link', { name: 'Patrol history' })).not.toBeInTheDocument();
+ const patrolControlLink = screen.getByRole('link', { name: 'Choose Patrol mode' });
+ expect(patrolControlLink).toHaveAttribute('href', PATROL_CONTROL_STARTER_URL);
+ patrolControlLink.addEventListener('click', (event) => event.preventDefault());
+ fireEvent.click(patrolControlLink);
+ });
+
it('returns self-hosted plan purchases to the plan surface instead of the legacy usage tab', async () => {
mockEntitlements = {
capabilities: ['relay', 'mobile_app', 'push_notifications', 'ai_autofix'],
@@ -880,11 +1273,13 @@ describe('ProLicensePanel', () => {
expect(screen.getByText('Pulse Pro is now active')).toBeInTheDocument();
expect(
- screen.getByText(/Checkout completed and this instance is now running Pulse Pro/i),
+ screen.getByText(
+ /Checkout completed and Pulse Pro is active\. Choose Patrol mode\./i,
+ ),
).toBeInTheDocument();
- expect(screen.queryByText('Compare self-hosted plans')).not.toBeInTheDocument();
- expect(screen.getAllByText('Safe Remediation Workflows').length).toBeGreaterThan(0);
- expect(screen.queryByText('Optional extras')).not.toBeInTheDocument();
+ expect(screen.queryByText('Select a plan')).not.toBeInTheDocument();
+ expect(screen.getAllByText('Patrol Handles Safe Fixes').length).toBeGreaterThan(0);
+ expect(screen.queryByText('Available plans')).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Review plan' })).not.toBeInTheDocument();
});
@@ -903,10 +1298,12 @@ describe('ProLicensePanel', () => {
expect(screen.queryByText('Pulse Pro is now active')).not.toBeInTheDocument();
expect(
- screen.queryByText(/Checkout completed and this instance is now running Pulse Pro/i),
+ screen.queryByText(
+ /Checkout completed and Pulse Pro is active\. Choose Patrol mode\./i,
+ ),
).not.toBeInTheDocument();
expect(screen.getByText('Current plan: Community')).toBeInTheDocument();
- expect(screen.queryByText('Safe Remediation Workflows')).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol Handles Safe Fixes')).not.toBeInTheDocument();
expect(screen.queryByText('Available now on this instance')).not.toBeInTheDocument();
expect(navigateMock).toHaveBeenCalledWith(SELF_HOSTED_PRO_BILLING_PLAN_HREF, {
replace: true,
@@ -923,7 +1320,7 @@ describe('ProLicensePanel', () => {
renderPanel();
- const recoveryDisclosure = screen.getAllByText('Use existing key')[0]?.closest('details');
+ const recoveryDisclosure = screen.getAllByText('Manual key recovery')[0]?.closest('details');
expect(recoveryDisclosure).toHaveAttribute('open');
});
@@ -997,9 +1394,10 @@ describe('ProLicensePanel', () => {
renderPanel();
- expect(screen.getAllByText('Compare self-hosted plans').length).toBeGreaterThan(0);
+ expect(screen.getAllByText('Select a plan').length).toBeGreaterThan(0);
expect(screen.getByText(/Community is active on this instance/i)).toBeInTheDocument();
- const compareLinks = screen.getAllByRole('link', { name: 'Compare plans' });
+ expect(screen.getAllByText('Watch-only Patrol').length).toBeGreaterThan(0);
+ const compareLinks = screen.getAllByRole('link', { name: 'View plans' });
expect(
compareLinks.some(
(link) =>
@@ -1096,7 +1494,7 @@ describe('ProLicensePanel', () => {
expect(screen.getByText('v5 license migration pending')).toBeInTheDocument();
expect(screen.getByText(/rate-limited right now/i)).toBeInTheDocument();
- expect(screen.getByText(/retry activation from this instance/i)).toBeInTheDocument();
+ expect(screen.getByText(/retry from this instance/i)).toBeInTheDocument();
});
it('shows reason-specific guidance when the v5 key is unsupported', async () => {
@@ -1159,6 +1557,7 @@ describe('ProLicensePanel', () => {
expect(proLicensePanelStateSource).not.toContain('getSelfHostedBillingUsageDetail');
expect(proLicensePanelStateSource).toContain('const setActiveSection = (section: string) => {');
expect(proLicensePanelStateSource).toContain('loadLicenseEntitlements(true)');
+ expect(proLicensePanelStateSource).toContain('fetchAgentOperationsLoopStatus');
expect(proLicensePanelStateSource).toContain('loadCommercialPosture(true)');
expect(proLicensePanelStateSource).toContain('loadRuntimeCapabilities(true)');
expect(proLicensePanelStateSource).toContain('buildSelfHostedCommercialPlanModel');
@@ -1168,7 +1567,7 @@ describe('ProLicensePanel', () => {
expect(proLicensePanelStateSource).toContain('getSelfHostedActivationSuccessPresentation({');
expect(proLicensePanelStateSource).not.toContain('runStartProTrialAction({');
expect(proLicensePanelStateSource).not.toContain('startProTrial()');
- expect(proLicensePanelStateSource).toContain("'A license or activation key is required'");
+ expect(proLicensePanelStateSource).toContain("'A license key is required'");
expect(proLicensePanelSource).toContain('@/components/shared/Button');
expect(proLicensePanelSource).toContain('variant="outline"');
expect(proLicensePanelSource).toContain('size="settingsAction"');
@@ -1215,9 +1614,7 @@ describe('ProLicensePanel', () => {
"resolveSelfHostedPurchaseStartDestination('self_hosted_plan')",
);
expect(proLicensePlanSectionSource).not.toContain('Your Pro trial has ended');
- expect(proLicensePlanSectionSource).not.toContain(
- 'Turn alert noise into root-cause analysis, safe remediation workflows, and 90-day history.',
- );
+ expect(proLicensePlanSectionSource).not.toContain('Turn alert noise into');
expect(selfHostedCommercialRecoverySectionSource).toContain(
'SELF_HOSTED_RECOVERY_PRESENTATION',
);
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index 256373565e..77a3d6f335 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -3,6 +3,7 @@ import settingsSource from '../Settings.tsx?raw';
import { EN_MESSAGES } from '@/i18n/messages';
import settingsDialogsSource from '../SettingsDialogs.tsx?raw';
import settingsPageShellSource from '../SettingsPageShell.tsx?raw';
+import aiSettingsSource from '../AISettings.tsx?raw';
import aiSettingsDialogsSource from '../AISettingsDialogs.tsx?raw';
import aiSettingsStatusAndActionsSource from '../AISettingsStatusAndActions.tsx?raw';
import aiChatMaintenanceSectionSource from '../AIChatMaintenanceSection.tsx?raw';
@@ -25,6 +26,7 @@ import apiTokenManagerSource from '../APITokenManager.tsx?raw';
import apiTokenManagerModelSource from '../apiTokenManagerModel.ts?raw';
import apiTokenManagerStateSource from '../useAPITokenManagerState.ts?raw';
import agentIntegrationsPanelSource from '../AgentIntegrationsPanel.tsx?raw';
+import agentCapabilitiesApiSource from '@/api/agentCapabilities.ts?raw';
import dataHandlingPanelSource from '../DataHandlingPanel.tsx?raw';
import auditLogPanelSource from '../AuditLogPanel.tsx?raw';
import auditWebhookPanelSource from '../AuditWebhookPanel.tsx?raw';
@@ -85,6 +87,7 @@ import ssoProvidersStateSource from '../useSSOProvidersState.ts?raw';
import infrastructureOnboardingPresentationSource from '../../../utils/infrastructureOnboardingPresentation.ts?raw';
import selfHostedBillingPresentationSource from '../selfHostedBillingPresentation.ts?raw';
import systemSettingsPresentationSource from '../../../utils/systemSettingsPresentation.ts?raw';
+import aiSettingsPresentationSource from '../../../utils/aiSettingsPresentation.ts?raw';
import auditLogPresentationSource from '../../../utils/auditLogPresentation.ts?raw';
import statusIndicatorBadgeSource from '../../shared/StatusIndicatorBadge.tsx?raw';
@@ -157,6 +160,34 @@ describe('settings architecture guardrails', () => {
);
});
+ it('keeps Assistant OAuth callback compatibility on the shared settings shell', () => {
+ expect(settingsNavigationModelSource).toContain(
+ 'export const SETTINGS_PROVIDER_MODELS_PATH = `${SETTINGS_PULSE_INTELLIGENCE_PATH}/provider`;',
+ );
+ expect(settingsNavigationModelSource).toContain(
+ "const LEGACY_SYSTEM_AI_PREFIX = '/settings/system-ai';",
+ );
+ expect(settingsNavigationModelSource).toContain('normalizedPath === LEGACY_SYSTEM_AI_PREFIX');
+ expect(settingsNavigationModelSource).toContain(
+ "case 'system-ai':\n return PULSE_INTELLIGENCE_PROVIDER_PREFIX;",
+ );
+ expect(settingsNavigationModelSource).toContain(
+ 'export function isAISettingsOAuthCallbackQuery(search: string): boolean',
+ );
+ expect(settingsNavigationModelSource).toContain(
+ "return params.has('ai_oauth_success') || params.has('ai_oauth_error');",
+ );
+ expect(settingsNavigationModelSource).toContain(
+ "if (isAISettingsOAuthCallbackQuery(search)) return 'system-ai';",
+ );
+ expect(settingsNavigationHookSource).toContain(
+ "resolvedTab === 'system-ai' && isAISettingsOAuthCallbackQuery(search)",
+ );
+ expect(settingsNavigationHookSource).toContain(
+ 'const targetHref = shouldPreserveQuery ? `${target}${search}${hash}` : target;',
+ );
+ });
+
it('keeps retired operations paths out of the settings routing model', () => {
expect(settingsNavigationModelSource).toContain(
"const RETIRED_SETTINGS_OPERATIONS_PREFIX = '/settings/operations';",
@@ -184,31 +215,41 @@ describe('settings architecture guardrails', () => {
'params.securityStatus()?.proxyAuthUsername',
);
expect(settingsPanelRegistryContextSource).toContain(
- '|| params.securityStatus()?.ssoSessionUsername',
- );
- expect(settingsPanelRegistryContextSource).toContain(
- '|| params.securityStatus()?.authUsername;',
+ 'params.securityStatus()?.ssoSessionUsername',
);
+ expect(settingsPanelRegistryContextSource).toContain('params.securityStatus()?.authUsername;');
expect(settingsPanelRegistryContextSource).toContain('getOrganizationOverviewPanelProps');
expect(settingsPanelRegistryContextSource).toContain('getOrganizationAccessPanelProps');
expect(settingsPanelRegistryContextSource).toContain('getOrganizationSharingPanelProps');
});
it('keeps self-hosted commercial settings plan-owned under one shared presentation model', () => {
- expect(selfHostedBillingPresentationSource).toContain("navLabel: 'Plans'");
- expect(selfHostedBillingPresentationSource).toContain("shellTitle: 'Self-hosted plan'");
+ expect(selfHostedBillingPresentationSource).toContain("navLabel: 'Plans & Billing'");
+ expect(selfHostedBillingPresentationSource).toContain("shellTitle: 'Plans & Billing'");
expect(selfHostedBillingPresentationSource).toContain(
- "shellDescription:\n 'Review the plan this instance is using and the optional capabilities connected to it.'",
+ 'Plan, license, and Patrol mode for this instance.',
);
expect(selfHostedBillingPresentationSource).toContain("planSectionTitle: 'Current plan'");
expect(selfHostedBillingPresentationSource).toContain(
- "recoverySectionTitle: 'Existing purchases'",
+ "recoverySectionTitle: 'License recovery'",
);
expect(settingsNavCatalogSource).toContain(
'label: SELF_HOSTED_PRO_BILLING_PRESENTATION.navLabel',
);
- expect(settingsNavCatalogSource).toContain('hideFromSidebar: true');
+ const pulseIntelligenceNavBlock = settingsNavCatalogSource.match(
+ /id: 'pulse-intelligence',[\s\S]*?id: 'organization',/,
+ );
+ expect(pulseIntelligenceNavBlock?.[0]).toContain("id: 'system-billing'");
+ const systemBillingNavBlock = settingsNavCatalogSource.match(
+ /id: 'system-billing',[\s\S]*?hideWhenCommercialHidden: true,\n\s*},/,
+ );
+ expect(systemBillingNavBlock?.[0]).toContain(
+ 'label: SELF_HOSTED_PRO_BILLING_PRESENTATION.navLabel',
+ );
+ expect(systemBillingNavBlock?.[0]).not.toContain('hideFromSidebar');
+ const systemNavBlock = settingsNavCatalogSource.match(/id: 'system',[\s\S]*?id: 'support',/);
+ expect(systemNavBlock?.[0]).not.toContain("id: 'system-billing'");
expect(settingsNavCatalogSource).toContain("features: ['rbac']");
expect(settingsNavCatalogSource).toContain("features: ['audit_logging']");
expect(settingsNavCatalogSource).toContain("features: ['relay']");
@@ -271,11 +312,33 @@ describe('settings architecture guardrails', () => {
expect(aiRuntimeControlsSectionSource).toContain('showAutonomousControlOption');
expect(aiRuntimeControlsSectionSource).toContain("state.form.controlLevel === 'autonomous'");
expect(aiRuntimeControlsSectionSource).toContain(
- 'Controlled - Pulse Assistant asks before actions',
+ 'Ask first - Assistant asks before chat-only actions',
);
expect(aiRuntimeControlsSectionSource).toContain(
- 'Autonomous - Pulse Assistant can run eligible actions',
+ 'Allow chat-only actions - Assistant may take eligible chat actions',
);
+ expect(aiRuntimeControlsSectionSource).toContain(
+ 'This controls actions started from Assistant chat only',
+ );
+ expect(aiRuntimeControlsSectionSource).toContain('Patrol handles infrastructure');
+ expect(aiRuntimeControlsSectionSource).not.toContain('Command auto-run');
+ expect(aiRuntimeControlsSectionSource).not.toContain('without per-command approval');
+ expect(aiRuntimeControlsSectionSource).not.toContain('Legal Disclaimer');
+ expect(aiRuntimeControlsSectionSource).not.toContain('Patrol uses the mode configured on');
+ expect(aiRuntimeControlsSectionSource).toContain('label="Chat action mode"');
+ expect(aiRuntimeControlsSectionSource).not.toContain('label="Command mode"');
+ expect(aiSettingsPresentationSource).toContain('Assistant chat actions');
+ expect(aiSettingsPresentationSource).not.toContain('Assistant chat command access');
+ expect(aiSettingsPresentationSource).not.toContain('Assistant command access');
+ expect(aiSettingsSource).toContain('AI_SETTINGS_PAGE_META');
+ expect(aiSettingsSource).toContain("saveLabel: 'Save provider settings'");
+ expect(aiSettingsSource).toContain("saveLabel: 'Save Patrol settings'");
+ expect(aiSettingsSource).toContain("saveLabel: 'Save Assistant settings'");
+ expect(aiSettingsSource).toContain("saveLabel: 'Save service context settings'");
+ expect(aiSettingsStatusAndActionsSource).toContain('props.saveLabel');
+ expect(aiSettingsStatusAndActionsSource).not.toContain('Save changes</button>');
+ expect(aiSettingsStateSource).toContain('options.savedLabel');
+ expect(aiSettingsStateSource).toContain('notificationStore.success(savedLabel)');
expect(aiRuntimeControlsSectionSource).not.toContain('without approval (Pro)');
expect(aiRuntimeControlsSectionSource).not.toContain(
'Pulse Assistant executes without approval',
@@ -561,10 +624,13 @@ describe('settings architecture guardrails', () => {
'aggregate self-hosted adoption',
);
expect(EN_MESSAGES['settings.general.telemetry.description']).toContain(
- 'counts, and coarse feature flags',
+ 'counts, coarse feature flags, and coarse Patrol, Assistant, and external-agent usage counters',
+ );
+ expect(EN_MESSAGES['settings.general.telemetry.description']).not.toContain(
+ 'Pulse Intelligence loop adoption',
);
expect(EN_MESSAGES['settings.general.telemetry.description']).toContain(
- 'identifiers, prompts, chat messages, or personal information are sent.',
+ 'identifiers, prompts, chat messages, command text, action output, token values, or personal information are sent.',
);
expect(generalSettingsPanelSource).toContain('settings.general.telemetry.payloadAriaLabel');
expect(generalSettingsPanelSource).toContain('settings.general.telemetry.resetId');
@@ -627,7 +693,7 @@ describe('settings architecture guardrails', () => {
});
it('keeps Patrol tool-call preflight wired through the canonical settings state', () => {
- // The Verify Patrol button must drive the canonical
+ // The Check Patrol model button must drive the canonical
// /api/ai/patrol/preflight endpoint via the typed runPatrolPreflight
// client and surface the result through state, not via inline fetch
// calls in the section component.
@@ -643,7 +709,7 @@ describe('settings architecture guardrails', () => {
expect(aiModelSelectionSectionSource).not.toContain("fetch('/api/ai/patrol/preflight");
});
- it('keeps workload discovery manual refresh on the canonical settings state', () => {
+ it('keeps service context manual refresh on the canonical settings state', () => {
expect(aiSettingsStateSource).toContain(
"import { runDiscoveryRefresh } from '@/api/discovery';",
);
@@ -651,20 +717,18 @@ describe('settings architecture guardrails', () => {
expect(aiSettingsStateSource).toContain('const result = await runDiscoveryRefresh();');
expect(aiSettingsStateSource).toContain('discoveryRunRunning');
expect(aiRuntimeControlsSectionSource).toContain('state.handleRunDiscoveryRefresh()');
- expect(aiRuntimeControlsSectionSource).toContain('Run discovery now');
+ expect(aiRuntimeControlsSectionSource).toContain('Run context scan');
expect(aiRuntimeControlsSectionSource).toContain('Auto ${state.form.discoveryIntervalHours}h');
expect(aiRuntimeControlsSectionSource).toContain('Manual only');
expect(aiRuntimeControlsSectionSource).toContain(
- 'Automatic workload scans will run at this interval.',
+ 'Recurring service context scans will run at this interval.',
);
expect(aiRuntimeControlsSectionSource).toContain(
- 'Automatic workload scans are off. Only manual refreshes will run.',
+ 'Recurring service context scans are off. Only manual refreshes will run.',
);
+ expect(aiRuntimeControlsSectionSource).toContain('Runs the same scan used by the schedule.');
expect(aiRuntimeControlsSectionSource).toContain(
- 'Runs the pending workload sweep used by the schedule.',
- );
- expect(aiRuntimeControlsSectionSource).toContain(
- 'Manual-only mode: runs the pending workload sweep once without enabling recurring scans.',
+ 'Manual-only mode: runs one scan without enabling recurring scans.',
);
expect(aiRuntimeControlsSectionSource).not.toContain("fetch('/api/discovery/run");
});
@@ -681,8 +745,8 @@ describe('settings architecture guardrails', () => {
expect(aiModelSelectionSectionSource).toContain('last verified');
});
- it("passes the form's pending patrolModel to runPatrolPreflight so Verify Patrol tests the unsaved selection", () => {
- // Without this, clicking Verify Patrol after changing the model
+ it("passes the form's pending patrolModel to runPatrolPreflight so the model check tests the unsaved selection", () => {
+ // Without this, clicking Check Patrol model after changing the model
// dropdown silently tested the previously-saved model and the
// operator would believe their pending selection was verified.
expect(aiSettingsStateSource).toContain('form.patrolModel');
@@ -702,7 +766,7 @@ describe('settings architecture guardrails', () => {
expect(aiModelSelectionSectionSource).toContain('cachedResultModel');
expect(aiModelSelectionSectionSource).toContain('Verified result is for');
expect(aiModelSelectionSectionSource).toContain(
- 'Click Verify Patrol to test the pending selection',
+ 'Click Check Patrol model to test the pending selection',
);
});
@@ -912,12 +976,25 @@ describe('settings architecture guardrails', () => {
expect(aiModelSelectionSectionSource).not.toContain('<select');
expect(aiModelSelectionSectionSource).not.toContain('<optgroup');
- expect(aiModelSelectionSectionSource).toContain('Pulse Assistant Model');
- expect(aiModelSelectionSectionSource).toContain('Patrol Verification Model');
- expect(aiModelSelectionSectionSource).toContain('Discovery Model');
- expect(aiModelSelectionSectionSource).toContain('chatModelOptions');
- expect(aiModelSelectionSectionSource).toContain('patrolModelOptions');
- expect(aiModelSelectionSectionSource).toContain('discoveryModelOptions');
+ expect(aiModelSelectionSectionSource).toContain('type AIModelOverrideKind');
+ expect(aiModelSelectionSectionSource).toContain("formKey: 'chatModel' | 'patrolModel'");
+ expect(aiModelSelectionSectionSource).toContain("label: 'Pulse Assistant model'");
+ expect(aiModelSelectionSectionSource).toContain(
+ 'Used for chat, explanations, and review. Patrol handles infrastructure work.',
+ );
+ expect(aiModelSelectionSectionSource).not.toContain('approved fix execution');
+ expect(aiModelSelectionSectionSource).toContain("label: 'Patrol model'");
+ expect(aiModelSelectionSectionSource).toContain("label: 'Service context model'");
+ expect(aiModelSelectionSectionSource).toContain('export const AIModelOverrideField');
+ expect(aiSettingsSource).toContain(
+ '<AIModelOverrideField state={props.state} kind="assistant" />',
+ );
+ expect(aiSettingsSource).toContain(
+ '<AIModelOverrideField state={props.state} kind="patrol" includePatrolPreflight />',
+ );
+ expect(aiSettingsSource).toContain(
+ '<AIModelOverrideField state={props.state} kind="discovery" />',
+ );
expect(aiSettingsStateSource).toContain('discoveryModel:');
expect(aiSettingsStateSource).toContain('payload.discovery_model = form.discoveryModel');
@@ -930,13 +1007,25 @@ describe('settings architecture guardrails', () => {
});
it('keeps system AI save feedback tied to provider and Patrol readiness context', () => {
+ expect(aiSettingsSource).toContain('Choose a Patrol mode on the Patrol page.');
+ expect(aiSettingsSource).toContain('Open Patrol');
+ expect(aiSettingsSource).toContain("const isProviderPage = () => page() === 'provider';");
+ expect(aiSettingsSource).toContain('showConnectionControls={isProviderPage()}');
+ expect(aiSettingsStatusAndActionsSource).toContain('showConnectionControls?: boolean');
+ expect(aiSettingsStatusAndActionsSource).toContain(
+ 'props.showConnectionControls && state.settings()?.configured',
+ );
+ expect(aiSettingsSource).not.toContain(
+ 'Set how much Patrol can do on its own from the Patrol page',
+ );
+ expect(aiSettingsSource).not.toContain('Patrol autonomy is the operations policy');
expect(aiSettingsStateSource).toContain(
"import { apiErrorDetails } from '@/api/responseUtils';",
);
expect(aiSettingsStateSource).toContain('resolveAISettingsSaveProviderFailure');
expect(aiSettingsStateSource).toContain('getAISettingsPatrolReadinessSaveMessage(');
expect(aiSettingsStateSource).toContain(
- "getAISettingsPatrolReadinessSaveMessage(\n updated.patrol_readiness,\n 'Assistant & Patrol enabled',",
+ "getAISettingsPatrolReadinessSaveMessage(\n updated.patrol_readiness,\n 'Pulse Intelligence enabled',",
);
expect(aiSettingsStateSource).toContain('notificationStore.warning(patrolReadinessMessage);');
expect(aiSettingsStateSource).toContain('getAISettingsSaveProviderFailureMessage(');
@@ -1161,19 +1250,187 @@ describe('settings architecture guardrails', () => {
);
});
- it('exposes the agent integrations panel under API Access without growing the settings tab inventory', () => {
- // The agent integrations panel sits as a sibling section
- // under the existing API Access tab rather than as its own
- // navigation entry. This pin keeps the operator's mental
- // model coherent (one tab for machine-driven access:
- // tokens + what those tokens unlock) and prevents drift
- // toward fragmenting the agent surface across tabs.
- expect(apiAccessPanelSource).toContain(
- "import AgentIntegrationsPanel from './AgentIntegrationsPanel';",
- );
- expect(apiAccessPanelSource).toContain('<AgentIntegrationsPanel />');
+ it('exposes external-agent setup from Pulse Intelligence while API Access stays token-only', () => {
+ // External agents are a Pulse Intelligence access path over the same
+ // governed Patrol policy, not a generic Security API feature. API Access
+ // remains the place to mint the scoped credential when setup needs one.
+ expect(aiSettingsSource).toContain(
+ "import AgentIntegrationsPanel from '@/components/Settings/AgentIntegrationsPanel';",
+ );
+ expect(aiSettingsSource).toContain(
+ "const showExternalAgentAccess = () => page() === 'assistant';",
+ );
+ expect(aiSettingsSource).toContain('<AgentIntegrationsPanel />');
+ expect(apiAccessPanelSource).not.toContain('AgentIntegrationsPanel');
+ expect(apiAccessPanelSource).not.toContain('isExternalAgentSetupHash');
+ expect(apiAccessPanelSource).not.toContain('api-access-external-agent-section');
+ expect(apiAccessPanelSource).toContain('api-access-token-section');
expect(agentIntegrationsPanelSource).toContain('ExternalTextLink');
expect(agentIntegrationsPanelSource).not.toContain('rel="noreferrer"');
+ expect(agentIntegrationsPanelSource).toContain('External agents');
+ expect(agentIntegrationsPanelSource).toContain('Connect external tools');
+ expect(agentIntegrationsPanelSource).toContain('read Pulse context');
+ expect(agentIntegrationsPanelSource).toContain('request Patrol work');
+ expect(agentIntegrationsPanelSource).toContain('Patrol mode and scoped tokens control');
+ expect(agentIntegrationsPanelSource).not.toContain('Optional connector access for Claude Desktop');
+ expect(agentIntegrationsPanelSource).not.toContain('Patrol remains the operator');
+ expect(agentIntegrationsPanelSource).not.toContain('Connected tools');
+ expect(agentIntegrationsPanelSource).toContain('setupOpen');
+ expect(agentIntegrationsPanelSource).toContain('Show connector setup');
+ expect(agentIntegrationsPanelSource).toContain('Hide connector setup');
+ expect(agentIntegrationsPanelSource).toContain('<Show when={!setupOpen()}>');
+ expect(agentIntegrationsPanelSource).not.toContain(
+ [
+ 'Choose',
+ 'what',
+ 'Patrol',
+ 'may',
+ 'handle',
+ 'automatically',
+ 'before',
+ 'any',
+ 'external',
+ 'agent',
+ 'can',
+ ].join(' '),
+ );
+ expect(agentIntegrationsPanelSource).toContain(
+ 'Required before agents can request Patrol work.',
+ );
+ expect(agentIntegrationsPanelSource).not.toContain(
+ 'Set the Patrol mode before connected agents can request work.',
+ );
+ expect(agentIntegrationsPanelSource).toContain('Choose Patrol mode');
+ expect(agentIntegrationsPanelSource).toContain('PATROL_CONTROL_PATH');
+ expect(agentIntegrationsPanelSource).not.toContain("settingsTabPath('system-ai')");
+ expect(agentIntegrationsPanelSource).toContain('EXTERNAL_AGENT_SETUP_ANCHOR');
+ expect(agentIntegrationsPanelSource).toContain('PULSE_MCP_SETUP_ANCHOR');
+ expect(agentIntegrationsPanelSource).toContain('focusPanelUntilLayoutSettles');
+ expect(agentIntegrationsPanelSource).toContain('findScrollableAncestor');
+ expect(agentIntegrationsPanelSource).toContain(
+ 'document.getElementById(EXTERNAL_AGENT_SETUP_ANCHOR)',
+ );
+ expect(agentIntegrationsPanelSource).toContain('window.history.replaceState');
+ expect(agentIntegrationsPanelSource).not.toContain('Use Pulse MCP only');
+ expect(agentIntegrationsPanelSource).not.toContain('outside client');
+ expect(agentIntegrationsPanelSource).not.toContain('Pulse Intelligence surfaces');
+ expect(agentIntegrationsPanelSource).toContain('Connector setup');
+ expect(agentIntegrationsPanelSource).toContain('Connect the agent');
+ expect(agentIntegrationsPanelSource).toContain('Developer details');
+ expect(agentIntegrationsPanelSource).toContain('advancedClientDetailsOpen');
+ expect(agentIntegrationsPanelSource).toContain(
+ 'Only open this when you are building or debugging a client',
+ );
+ expect(agentIntegrationsPanelSource).toContain('Patrol access model');
+ expect(agentIntegrationsPanelSource).toContain(
+ 'Built-in Pulse views and connected clients all sit behind',
+ );
+ expect(agentIntegrationsPanelSource).toContain('Live manifest details');
+ expect(agentIntegrationsPanelSource).not.toContain('Build a custom client');
+ expect(agentIntegrationsPanelSource).not.toContain('Instance manifest details');
+ expect(agentIntegrationsPanelSource).not.toContain('MCP client config');
+ expect(agentIntegrationsPanelSource).toContain('normalizeAgentMCPAdapter');
+ expect(agentIntegrationsPanelSource).not.toContain('getAgentMCPClientExamples');
+ expect(agentIntegrationsPanelSource).toContain('getAgentWorkflowPrompts');
+ expect(agentIntegrationsPanelSource).toContain('Agent starting points');
+ expect(agentIntegrationsPanelSource).toContain('Patrol');
+ expect(agentIntegrationsPanelSource).not.toContain('Operations loop');
+ expect(agentIntegrationsPanelSource).toContain('OpenCode');
+ expect(agentIntegrationsPanelSource).toContain(
+ "import { Button, ButtonLink } from '@/components/shared/Button';",
+ );
+ expect(agentIntegrationsPanelSource).toContain(
+ "import KeyRoundIcon from 'lucide-solid/icons/key-round';",
+ );
+ expect(agentIntegrationsPanelSource).toContain('API_TOKEN_PATROL_EXTERNAL_AGENT_PRESET_LABEL');
+ expect(agentIntegrationsPanelSource).toContain('PULSE_MCP_TOKEN_SETUP_PATH');
+ expect(agentIntegrationsPanelSource).toContain('hardNavigation');
+ expect(apiTokenManagerSource).toContain('API_TOKEN_CREATE_ANCHOR');
+ expect(agentIntegrationsPanelSource).toContain('formatAgentOpenCodeMCPConfig');
+ expect(agentIntegrationsPanelSource).toContain('formatAgentMCPServersConfig');
+ expect(agentIntegrationsPanelSource).toContain('Installer commands');
+ expect(agentIntegrationsPanelSource).toContain('installerCommandsOpen');
+ expect(agentIntegrationsPanelSource).toContain('mcpInstallShellCommand');
+ expect(agentIntegrationsPanelSource).toContain('mcpInstallPowerShellCommand');
+ expect(agentIntegrationsPanelSource).toContain('Client config');
+ expect(agentIntegrationsPanelSource).toContain('clientConfigOpen');
+ expect(agentIntegrationsPanelSource).toContain('Install the connector');
+ expect(agentIntegrationsPanelSource).toContain('paste the client config');
+ expect(agentIntegrationsPanelSource).not.toContain('The installer and');
+ expect(agentIntegrationsPanelSource).not.toContain('on the machine that runs the external tool');
+ expect(agentIntegrationsPanelSource).not.toContain('Install the Pulse MCP bridge');
+ expect(agentIntegrationsPanelSource).not.toContain(
+ 'Use the OpenCode or Claude-style snippet below',
+ );
+ expect(agentIntegrationsPanelSource).toContain('opencode.json');
+ expect(agentCapabilitiesApiSource).toContain("type: 'local'");
+ expect(agentCapabilitiesApiSource).toContain('environment');
+ expect(agentIntegrationsPanelSource).toContain('mcpServersConfigFamily');
+ expect(agentCapabilitiesApiSource).toContain('custom clients');
+ expect(agentIntegrationsPanelSource).toContain('requiredScopes');
+ expect(agentIntegrationsPanelSource).toContain('Manifest scopes');
+ expect(agentIntegrationsPanelSource).not.toContain('published contract');
+ expect(agentIntegrationsPanelSource).toContain('External agents expose');
+ expect(agentCapabilitiesApiSource).toContain('surfaceLabel,');
+ expect(agentIntegrationsPanelSource).toContain('capability below shows its required scope');
+ expect(agentIntegrationsPanelSource).toContain('getAgentSurfaceContractEntries');
+ expect(agentIntegrationsPanelSource).toContain('surfaceContractEntries');
+ expect(agentIntegrationsPanelSource).toContain('Built-in Pulse views');
+ expect(agentCapabilitiesApiSource).toContain('AgentSurfaceAffordanceContract');
+ expect(agentCapabilitiesApiSource).toContain('AgentSurfaceToolContract');
+ expect(agentCapabilitiesApiSource).toContain('normalizeSurfaceAffordances');
+ expect(agentCapabilitiesApiSource).toContain('surfaceAffordanceLabels');
+ expect(agentCapabilitiesApiSource).toContain('AGENT_SURFACE_ID_PULSE_MCP');
+ expect(agentCapabilitiesApiSource).toContain('getAgentManifestSurfaceToolContract');
+ expect(agentCapabilitiesApiSource).toContain('getAgentManifestSurfaceToolContracts');
+ expect(agentIntegrationsPanelSource).toContain('AGENT_SURFACE_ID_PULSE_MCP');
+ expect(agentIntegrationsPanelSource).toContain('getAgentManifestSurfaceToolContract');
+ expect(agentIntegrationsPanelSource).toContain('getAgentSurfaceToolPosturePresentation');
+ expect(agentIntegrationsPanelSource).toContain('mcpSurfaceToolPosture');
+ expect(agentIntegrationsPanelSource).toContain('data-testid="agent-mcp-tool-posture"');
+ expect(agentIntegrationsPanelSource).toContain('External agents expose {posture().label}');
+ expect(agentCapabilitiesApiSource).toContain('capability availability');
+ expect(agentCapabilitiesApiSource).toContain("if (affordances.tools) labels.push('Actions')");
+ expect(agentCapabilitiesApiSource).not.toContain('runtime tool availability');
+ expect(agentIntegrationsPanelSource).toContain('getAgentCapabilityErrorCodeSummaries');
+ expect(agentIntegrationsPanelSource).toContain('errorCodeSummaries');
+ expect(agentIntegrationsPanelSource).toContain('Failure codes');
+ expect(agentIntegrationsPanelSource).toContain('from the live manifest');
+ expect(agentIntegrationsPanelSource).toContain('groupAgentCapabilitiesByManifestCategories');
+ expect(agentIntegrationsPanelSource).toContain("from '@/api/agentCapabilities'");
+ expect(agentIntegrationsPanelSource).not.toContain("fetch('/api/agent/capabilities'");
+ expect(agentCapabilitiesApiSource).toContain(
+ "export const AGENT_CAPABILITIES_PATH = '/api/agent/capabilities'",
+ );
+ expect(agentCapabilitiesApiSource).toContain("from './generated/agentCapabilities'");
+ expect(agentCapabilitiesApiSource).toContain('skipAuth: true');
+ expect(agentCapabilitiesApiSource).toContain('manifest.categories');
+ expect(agentCapabilitiesApiSource).toContain('AgentMCPAdapterContract');
+ expect(agentCapabilitiesApiSource).toContain('manifest?.surfaceToolContracts');
+ expect(agentCapabilitiesApiSource).toContain('manifest?.mcpAdapter');
+ expect(agentCapabilitiesApiSource).toContain('getAgentMCPClientExamples');
+ expect(agentCapabilitiesApiSource).toContain('formatAgentOpenCodeMCPConfig');
+ expect(agentCapabilitiesApiSource).toContain('formatAgentMCPServersConfig');
+ expect(agentCapabilitiesApiSource).toContain('getAgentCapabilityErrorCodeSummaries');
+ expect(agentCapabilitiesApiSource).not.toContain('export interface AgentCapability {');
+ expect(agentCapabilitiesApiSource).not.toContain(
+ 'export interface AgentCapabilitiesManifest {',
+ );
+ expect(agentCapabilitiesApiSource).not.toContain('getAgentMCPSurfaceToolContract');
+ expect(agentIntegrationsPanelSource).not.toContain('MCP_CLIENT_EXAMPLES');
+ expect(agentIntegrationsPanelSource).not.toContain('function formatClaudeMcpConfig');
+ expect(agentIntegrationsPanelSource).not.toContain('function formatOpenCodeMcpConfig');
+ expect(agentIntegrationsPanelSource).not.toContain('CATEGORY_ORDER');
+ expect(agentIntegrationsPanelSource).not.toContain('Claude Desktop / Claude Code config');
+ expect(agentIntegrationsPanelSource).not.toContain('any MCP client that accepts');
+ expect(agentIntegrationsPanelSource).not.toContain('getAgentMCPSurfaceToolContract');
+ expect(agentIntegrationsPanelSource).not.toContain('subscribe_events');
+ expect(agentIntegrationsPanelSource).not.toContain('capability.name');
+ expect(agentIntegrationsPanelSource).not.toContain('Interactive questions');
+ expect(agentIntegrationsPanelSource).not.toContain('Capability metadata');
+ expect(agentIntegrationsPanelSource).not.toContain(
+ 'monitoring:write for the operator-state write tools',
+ );
});
it('keeps internal analytics off the user diagnostics boundary', () => {
@@ -1182,8 +1439,15 @@ describe('settings architecture guardrails', () => {
expect(diagnosticsResultsPanelSource).not.toContain('commercialFunnel');
expect(diagnosticsResultsPanelSource).not.toContain('infrastructureOnboarding');
expect(diagnosticsResultsPanelSource).not.toContain("apiFetchJSON('/api/diagnostics')");
+ expect(diagnosticsResultsPanelSource).toContain('Assistant runtime');
+ expect(diagnosticsResultsPanelSource).toContain('assistantRuntimeConnected');
+ expect(diagnosticsResultsPanelSource).not.toContain('MCP Connection');
+ expect(diagnosticsResultsPanelSource).not.toContain('mcpConnected');
expect(diagnosticsModelSource).toContain('stripInternalAnalyticsDiagnosticsFields');
+ expect(diagnosticsModelSource).toContain('assistantRuntimeConnected');
+ expect(diagnosticsModelSource).not.toContain('mcpConnected');
+ expect(diagnosticsModelSource).not.toContain('mcpToolCount');
expect(diagnosticsModelSource).not.toContain('export interface CommercialFunnelDiagnostic');
expect(diagnosticsModelSource).not.toContain('export interface CommercialFunnelSummary');
expect(diagnosticsModelSource).not.toContain(
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsLocalization.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsLocalization.test.ts
index a4cc45baae..1a017e87e5 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsLocalization.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsLocalization.test.ts
@@ -19,9 +19,13 @@ describe('settings localization catalog', () => {
it('keeps the canonical English settings catalog as the static baseline', () => {
expect(SETTINGS_NAV_GROUPS[0]?.label).toBe('Infrastructure');
expect(SETTINGS_HEADER_META['system-billing']).toEqual({
- title: 'Self-hosted plan',
+ title: 'Plans & Billing',
+ description: 'Plan, license, and Patrol mode for this instance.',
+ });
+ expect(SETTINGS_HEADER_META['system-ai-discovery']).toEqual({
+ title: 'Service Context',
description:
- 'Review the plan this instance is using and the optional capabilities connected to it.',
+ 'Configure the model-backed service context Assistant and Patrol use. Infrastructure discovery and onboarding stay under Infrastructure.',
});
});
@@ -30,13 +34,17 @@ describe('settings localization catalog', () => {
expect(groups[0]?.label).toBe('Infrastruktur');
expect(groups[0]?.items[0]?.label).toBe('Infrastruktur');
expect(getSettingsNavItem('system-updates', 'de')?.label).toBe('Updates');
+ expect(getSettingsNavItem('system-ai-discovery', 'de')?.label).toBe('Service-Kontext');
expect(getSettingsNavItem('security-data-handling', 'de')?.label).toBe('Ressourcenschutz');
});
it('localizes settings navigation groups and items for Spanish', () => {
const groups = getSettingsNavGroups('es');
expect(groups.find((group) => group.id === 'system')?.label).toBe('Sistema');
- expect(getSettingsNavItem('system-ai', 'es')?.label).toBe('Assistant y Patrol');
+ expect(getSettingsNavItem('system-ai', 'es')?.label).toBe('Proveedores y modelos');
+ expect(getSettingsNavItem('system-ai-patrol', 'es')?.label).toBe('Patrol');
+ expect(getSettingsNavItem('system-ai-assistant', 'es')?.label).toBe('Assistant');
+ expect(getSettingsNavItem('system-ai-discovery', 'es')?.label).toBe('Contexto de servicio');
expect(getSettingsNavItem('support-diagnostics', 'es')?.label).toBe('Diagnóstico y salud');
});
@@ -46,6 +54,38 @@ describe('settings localization catalog', () => {
title: 'Red',
description: 'Configura la URL pública, CORS, inserción y límites de red para webhooks.',
});
+ expect(spanishMeta['system-ai']).toEqual({
+ title: 'Proveedores y modelos',
+ description:
+ 'Configura proveedores, modelos predeterminados, salud de proveedores, presupuesto y uso para Pulse Intelligence.',
+ });
+ expect(spanishMeta['system-ai-assistant']).toEqual({
+ title: 'Assistant',
+ description:
+ 'Configura el comportamiento del chat, los permisos de acciones y las sesiones del Assistant.',
+ });
+ expect(spanishMeta['system-billing']).toEqual({
+ title: 'Planes y facturacion',
+ description: 'Plan, licencia y modo de Patrol para esta instancia.',
+ });
+ expect(getSettingsHeaderMeta('de')['system-ai']).toEqual({
+ title: 'Anbieter & Modelle',
+ description:
+ 'Konfigurieren Sie Anbieter, Standardmodelle, Anbieterzustand, Budget und Nutzung fuer Pulse Intelligence.',
+ });
+ expect(getSettingsHeaderMeta('de')['system-ai-discovery']).toEqual({
+ title: 'Service-Kontext',
+ description:
+ 'Konfigurieren Sie den KI-gestuetzten Service-Kontext fuer Assistant und Patrol. Infrastruktur-Erkennung und Onboarding bleiben unter Infrastruktur.',
+ });
+ expect(getSettingsHeaderMeta('de')['system-ai-assistant']).toEqual({
+ title: 'Assistant',
+ description: 'Konfigurieren Sie Chatverhalten, Aktionsrechte und Sitzungen des Assistant.',
+ });
+ expect(getSettingsHeaderMeta('de')['system-billing']).toEqual({
+ title: 'Plaene & Abrechnung',
+ description: 'Plan, Lizenz und Patrol-Modus fuer diese Instanz.',
+ });
expect(getInfrastructureReadOnlyHeaderDescription('es')).toContain('solo lectura');
});
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx b/frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx
index 349635a13d..92f30c7c7e 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/settingsNavigation.integration.test.tsx
@@ -12,9 +12,12 @@ const canonicalTabPaths = {
'system-network': '/settings/system-network',
'system-updates': '/settings/system-updates',
'system-recovery': '/settings/system-recovery',
- 'system-ai': '/settings/system-ai',
+ 'system-ai': '/settings/pulse-intelligence/provider',
+ 'system-ai-patrol': '/settings/pulse-intelligence/patrol',
+ 'system-ai-assistant': '/settings/pulse-intelligence/assistant',
+ 'system-ai-discovery': '/settings/pulse-intelligence/discovery',
'system-relay': '/settings/system-relay',
- 'system-billing': '/settings/system/billing/plan',
+ 'system-billing': '/settings/pulse-intelligence/billing/plan',
'support-diagnostics': '/settings/support/diagnostics',
'support-reporting': '/settings/support/reporting',
'support-logs': '/settings/support/logs',
@@ -111,10 +114,11 @@ describe('settingsNavigation integration scaffold', () => {
).toBe(true);
});
- it('keeps self-hosted billing as a direct route instead of a sidebar item', () => {
+ it('keeps self-hosted billing discoverable from Pulse Intelligence settings', () => {
+ expect(deriveTabFromPath('/settings/pulse-intelligence/billing/plan')).toBe('system-billing');
expect(deriveTabFromPath('/settings/system/billing/plan')).toBe('system-billing');
- expect(settingsTabPath('system-billing')).toBe('/settings/system/billing/plan');
- expect(getSettingsNavItem('system-billing')?.hideFromSidebar).toBe(true);
+ expect(settingsTabPath('system-billing')).toBe('/settings/pulse-intelligence/billing/plan');
+ expect(getSettingsNavItem('system-billing')?.hideFromSidebar).not.toBe(true);
});
it('keeps resource privacy route-backed but out of the normal sidebar', () => {
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsRouting.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsRouting.test.ts
index 6ebfd4745a..c678ad271e 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsRouting.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsRouting.test.ts
@@ -4,6 +4,7 @@ import {
DEFAULT_SETTINGS_TAB,
deriveTabFromPath,
deriveTabFromQuery,
+ isAISettingsOAuthCallbackQuery,
isRetiredSettingsCompatibilityPath,
isRouteableSettingsLocation,
isRouteableSettingsPath,
@@ -23,9 +24,12 @@ const canonicalTabPaths = {
'system-network': '/settings/system-network',
'system-updates': '/settings/system-updates',
'system-recovery': '/settings/system-recovery',
- 'system-ai': '/settings/system-ai',
+ 'system-ai': '/settings/pulse-intelligence/provider',
+ 'system-ai-patrol': '/settings/pulse-intelligence/patrol',
+ 'system-ai-assistant': '/settings/pulse-intelligence/assistant',
+ 'system-ai-discovery': '/settings/pulse-intelligence/discovery',
'system-relay': '/settings/system-relay',
- 'system-billing': '/settings/system/billing/plan',
+ 'system-billing': '/settings/pulse-intelligence/billing/plan',
'support-diagnostics': '/settings/support/diagnostics',
'support-reporting': '/settings/support/reporting',
'support-logs': '/settings/support/logs',
@@ -82,6 +86,18 @@ describe('settingsNavigationModel', () => {
expect(resolveCanonicalSettingsPath('/settings/monitoring/availability')).toBe(
'/settings/monitoring/availability',
);
+ expect(resolveCanonicalSettingsPath('/settings/pulse-intelligence')).toBe(
+ '/settings/pulse-intelligence/provider',
+ );
+ expect(resolveCanonicalSettingsPath('/settings/pulse-intelligence/provider')).toBe(
+ '/settings/pulse-intelligence/provider',
+ );
+ expect(resolveCanonicalSettingsPath('/settings/system-ai')).toBe(
+ '/settings/pulse-intelligence/provider',
+ );
+ expect(resolveCanonicalSettingsPath('/settings/pulse-intelligence/patrol')).toBe(
+ '/settings/pulse-intelligence/patrol',
+ );
expect(resolveCanonicalSettingsPath('/settings/infrastructure/install')).toBeNull();
expect(resolveCanonicalSettingsPath('/settings/infrastructure/platforms')).toBeNull();
expect(resolveCanonicalSettingsPath('/settings/infrastructure/platforms/truenas')).toBeNull();
@@ -93,8 +109,17 @@ describe('settingsNavigationModel', () => {
expect(resolveCanonicalSettingsPath('/settings/operations')).toBeNull();
expect(resolveCanonicalSettingsPath('/settings/operations/reporting')).toBeNull();
expect(resolveCanonicalSettingsPath('/settings/operations/logs')).toBeNull();
+ expect(resolveCanonicalSettingsPath('/settings/pulse-intelligence/billing')).toBe(
+ '/settings/pulse-intelligence/billing/plan',
+ );
expect(resolveCanonicalSettingsPath('/settings/system/billing')).toBe(
- '/settings/system/billing/plan',
+ '/settings/pulse-intelligence/billing/plan',
+ );
+ expect(resolveCanonicalSettingsPath('/settings/system/billing/plan')).toBe(
+ '/settings/pulse-intelligence/billing/plan',
+ );
+ expect(resolveCanonicalSettingsPath('/settings/system/billing/usage')).toBe(
+ '/settings/pulse-intelligence/billing/usage',
);
expect(resolveCanonicalSettingsPath('/settings/system-pro')).toBeNull();
expect(resolveCanonicalSettingsPath('/not-settings')).toBeNull();
@@ -127,6 +152,15 @@ describe('settingsNavigationModel', () => {
expect(isRouteableSettingsPath('/settings')).toBe(true);
expect(isRouteableSettingsPath('/settings/infrastructure')).toBe(true);
expect(isRouteableSettingsPath('/settings/monitoring/availability')).toBe(true);
+ expect(isRouteableSettingsPath('/settings/pulse-intelligence/provider')).toBe(true);
+ expect(isRouteableSettingsPath('/settings/system-ai')).toBe(true);
+ expect(isRouteableSettingsPath('/settings/pulse-intelligence/patrol')).toBe(true);
+ expect(isRouteableSettingsPath('/settings/pulse-intelligence/assistant')).toBe(true);
+ expect(isRouteableSettingsPath('/settings/pulse-intelligence/discovery')).toBe(true);
+ expect(isRouteableSettingsPath('/settings/pulse-intelligence/billing/plan')).toBe(true);
+ expect(isRouteableSettingsPath('/settings/pulse-intelligence/billing/usage')).toBe(true);
+ expect(isRouteableSettingsPath('/settings/system/billing/plan')).toBe(true);
+ expect(isRouteableSettingsPath('/settings/system/billing/usage')).toBe(true);
expect(isRouteableSettingsPath('/settings/security/api')).toBe(true);
expect(isRouteableSettingsPath('/settings/unknown')).toBe(false);
});
@@ -157,6 +191,8 @@ describe('settingsNavigationModel', () => {
});
it('maps plan and usage billing subroutes back to the billing tab', () => {
+ expect(deriveTabFromPath('/settings/pulse-intelligence/billing/plan')).toBe('system-billing');
+ expect(deriveTabFromPath('/settings/pulse-intelligence/billing/usage')).toBe('system-billing');
expect(deriveTabFromPath('/settings/system/billing/plan')).toBe('system-billing');
expect(deriveTabFromPath('/settings/system/billing/usage')).toBe('system-billing');
});
@@ -167,6 +203,11 @@ describe('settingsNavigationModel', () => {
['?tab=availability', 'monitoring-availability'],
['?tab=monitoring-availability', 'monitoring-availability'],
['?tab=system-ai', 'system-ai'],
+ ['?tab=patrol', 'system-ai-patrol'],
+ ['?tab=assistant', 'system-ai-assistant'],
+ ['?tab=discovery', 'system-ai-discovery'],
+ ['?ai_oauth_error=unsupported', 'system-ai'],
+ ['?ai_oauth_success=true', 'system-ai'],
['?tab=system-relay', 'system-relay'],
['?tab=system-billing', 'system-billing'],
['?tab=diagnostics', 'support-diagnostics'],
@@ -189,6 +230,13 @@ describe('settingsNavigationModel', () => {
}
});
+ it('detects Assistant OAuth callback queries so the settings shell preserves them', () => {
+ expect(isAISettingsOAuthCallbackQuery('?ai_oauth_error=unsupported')).toBe(true);
+ expect(isAISettingsOAuthCallbackQuery('?ai_oauth_success=true')).toBe(true);
+ expect(isAISettingsOAuthCallbackQuery('?tab=system-ai')).toBe(false);
+ expect(isAISettingsOAuthCallbackQuery('')).toBe(false);
+ });
+
it('evaluates feature-lock behavior contracts', () => {
expect(isFeatureLocked(undefined, hasFeatures([]), () => true)).toBe(false);
expect(isFeatureLocked([], hasFeatures([]), () => true)).toBe(false);
diff --git a/frontend-modern/src/components/Settings/__tests__/useSettingsNavigation.test.tsx b/frontend-modern/src/components/Settings/__tests__/useSettingsNavigation.test.tsx
index f5e4c293e4..637ce9368b 100644
--- a/frontend-modern/src/components/Settings/__tests__/useSettingsNavigation.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/useSettingsNavigation.test.tsx
@@ -55,6 +55,50 @@ describe('useSettingsNavigation', () => {
});
});
+ it('preserves Assistant OAuth callback queries while routing /settings to Provider & Models', async () => {
+ renderHarness('/settings', '?ai_oauth_error=unsupported');
+
+ await waitFor(() => {
+ expect(navigateSpy).toHaveBeenCalledWith(
+ '/settings/pulse-intelligence/provider?ai_oauth_error=unsupported',
+ {
+ replace: true,
+ scroll: false,
+ },
+ );
+ });
+ });
+
+ it('routes legacy external-agent API hashes to Pulse Intelligence Assistant', async () => {
+ for (const hash of ['#external-agent-setup', '#pulse-mcp-setup']) {
+ cleanup();
+ navigateSpy.mockReset();
+ renderHarness('/settings/security/api', '', hash);
+
+ await waitFor(() => {
+ expect(navigateSpy).toHaveBeenCalledWith(
+ '/settings/pulse-intelligence/assistant#external-agent-setup',
+ {
+ replace: true,
+ scroll: false,
+ },
+ );
+ });
+ }
+ });
+
+ it('keeps token creation preset links on API Access', async () => {
+ renderHarness(
+ '/settings/security/api',
+ '?tokenPreset=pulse-intelligence-agent',
+ '#api-token-create',
+ );
+
+ await waitFor(() => {
+ expect(navigateSpy).not.toHaveBeenCalled();
+ });
+ });
+
it('routes setup-oriented infrastructure tab clicks back to systems when the session is read-only', () => {
presentationPolicyIsReadOnlyMock.mockReturnValue(true);
renderHarness('/settings/system-general');
diff --git a/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts b/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts
index 0536b58e2b..6f053dafa6 100644
--- a/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/useSystemSettingsState.test.ts
@@ -1,5 +1,6 @@
import { createRoot, createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { TelemetryPingPreview } from '@/api/settings';
import type { SettingsTab } from '../settingsNavigationModel';
type UseSystemSettingsStateModule = typeof import('../useSystemSettingsState');
@@ -9,6 +10,111 @@ const flushAsync = async () => {
await Promise.resolve();
};
+const buildTelemetryPreviewPayload = (
+ overrides: Partial<TelemetryPingPreview> = {},
+): TelemetryPingPreview => ({
+ install_id: 'preview-install-id',
+ version: '6.0.0',
+ version_channel: 'stable',
+ version_is_development: false,
+ version_is_published_release: true,
+ platform: 'docker',
+ os: 'linux',
+ arch: 'amd64',
+ event: 'heartbeat',
+ pve_nodes: 1,
+ pbs_instances: 0,
+ pmg_instances: 0,
+ vms: 2,
+ containers: 3,
+ agent_hosts: 1,
+ docker_hosts: 0,
+ docker_containers: 0,
+ kubernetes_clusters: 0,
+ kubernetes_nodes: 0,
+ kubernetes_pods: 0,
+ kubernetes_deployments: 0,
+ storage_pools: 1,
+ physical_disks: 2,
+ ceph_clusters: 0,
+ network_shares: 0,
+ truenas_systems: 0,
+ truenas_vms: 0,
+ truenas_apps: 0,
+ vmware_hosts: 0,
+ vmware_vms: 0,
+ vmware_datastores: 0,
+ availability_targets: 1,
+ ai_enabled: false,
+ patrol_enabled: false,
+ discovery_enabled: false,
+ notifications_enabled: false,
+ ai_actions_enabled: false,
+ active_alerts: 0,
+ relay_enabled: false,
+ sso_enabled: false,
+ multi_tenant: false,
+ paid_license: false,
+ has_api_tokens: true,
+ pulse_intelligence_loop_configured: false,
+ pulse_intelligence_loop_active_30d: false,
+ pulse_intelligence_complete_operations_loop_30d: false,
+ pulse_intelligence_approved_execution_loop_30d: false,
+ pulse_intelligence_resolved_operations_loop_30d: false,
+ pulse_intelligence_patrol_control_completed_operations_loop_30d: false,
+ pulse_intelligence_patrol_control_resolved_operations_loop_30d: false,
+ pulse_intelligence_patrol_control_paid_completed_operations_loop_30d: false,
+ pulse_intelligence_patrol_control_paid_resolved_operations_loop_30d: false,
+ pulse_intelligence_pro_activation_completed_operations_loop_30d: false,
+ pulse_intelligence_pro_activation_resolved_operations_loop_30d: false,
+ pulse_intelligence_pro_activation_paid_completed_operations_loop_30d: false,
+ pulse_intelligence_pro_activation_paid_resolved_operations_loop_30d: false,
+ pulse_intelligence_governed_action_active_30d: false,
+ pulse_intelligence_assistant_operations_loop_30d: false,
+ pulse_intelligence_assistant_approved_execution_loop_30d: false,
+ pulse_intelligence_assistant_approved_action_success_loop_30d: false,
+ pulse_intelligence_assistant_resolved_operations_loop_30d: false,
+ pulse_intelligence_external_agent_operations_loop_30d: false,
+ pulse_intelligence_external_agent_approved_execution_loop_30d: false,
+ pulse_intelligence_external_agent_approved_action_success_loop_30d: false,
+ pulse_intelligence_external_agent_resolved_operations_loop_30d: false,
+ pulse_intelligence_mcp_adapter_operations_loop_30d: false,
+ pulse_intelligence_mcp_adapter_approved_execution_loop_30d: false,
+ pulse_intelligence_mcp_adapter_approved_action_success_loop_30d: false,
+ pulse_intelligence_mcp_adapter_resolved_operations_loop_30d: false,
+ pulse_intelligence_operations_loop_starter_requests_30d: 0,
+ pulse_intelligence_assistant_operations_loop_starter_requests_30d: 0,
+ pulse_intelligence_patrol_operations_loop_starter_requests_30d: 0,
+ pulse_intelligence_patrol_control_operations_loop_starter_requests_30d: 0,
+ pulse_intelligence_pro_activation_operations_loop_starter_requests_30d: 0,
+ pulse_intelligence_mcp_operations_loop_starter_requests_30d: 0,
+ pulse_intelligence_assistant_ai_calls_30d: 0,
+ pulse_intelligence_assistant_context_ai_calls_30d: 0,
+ pulse_intelligence_assistant_tool_calls_30d: 0,
+ pulse_intelligence_patrol_ai_calls_30d: 0,
+ pulse_intelligence_patrol_runs_30d: 0,
+ pulse_intelligence_patrol_new_findings_30d: 0,
+ pulse_intelligence_patrol_investigations_30d: 0,
+ pulse_intelligence_patrol_resolved_findings_30d: 0,
+ pulse_intelligence_patrol_autofixes_30d: 0,
+ pulse_intelligence_external_agent_enabled: false,
+ pulse_intelligence_external_agent_used_30d: false,
+ pulse_intelligence_mcp_adapter_used_30d: false,
+ pulse_intelligence_external_agent_context_requests_30d: 0,
+ pulse_intelligence_external_agent_event_stream_requests_30d: 0,
+ pulse_intelligence_external_agent_provisioning_requests_30d: 0,
+ pulse_intelligence_external_agent_operator_state_requests_30d: 0,
+ pulse_intelligence_external_agent_finding_requests_30d: 0,
+ pulse_intelligence_external_agent_action_requests_30d: 0,
+ pulse_intelligence_action_plans_30d: 0,
+ pulse_intelligence_approval_requests_30d: 0,
+ pulse_intelligence_rejected_action_decisions_30d: 0,
+ pulse_intelligence_approved_action_decisions_30d: 0,
+ pulse_intelligence_approved_action_attempts_30d: 0,
+ pulse_intelligence_approved_action_successes_30d: 0,
+ ...overrides,
+});
+
describe('useSystemSettingsState', () => {
let useSystemSettingsState: UseSystemSettingsStateModule['useSystemSettingsState'];
let getSystemSettingsMock: ReturnType<typeof vi.fn>;
@@ -303,51 +409,7 @@ describe('useSystemSettingsState', () => {
it('loads the telemetry preview payload on demand', async () => {
getTelemetryPreviewMock.mockResolvedValue({
enabled: true,
- payload: {
- install_id: 'preview-install-id',
- version: '6.0.0',
- version_channel: 'stable',
- version_is_development: false,
- version_is_published_release: true,
- platform: 'docker',
- os: 'linux',
- arch: 'amd64',
- event: 'heartbeat',
- pve_nodes: 1,
- pbs_instances: 0,
- pmg_instances: 0,
- vms: 2,
- containers: 3,
- agent_hosts: 1,
- docker_hosts: 0,
- docker_containers: 0,
- kubernetes_clusters: 0,
- kubernetes_nodes: 0,
- kubernetes_pods: 0,
- kubernetes_deployments: 0,
- storage_pools: 1,
- physical_disks: 2,
- ceph_clusters: 0,
- network_shares: 0,
- truenas_systems: 0,
- truenas_vms: 0,
- truenas_apps: 0,
- vmware_hosts: 0,
- vmware_vms: 0,
- vmware_datastores: 0,
- availability_targets: 1,
- ai_enabled: false,
- patrol_enabled: false,
- discovery_enabled: false,
- notifications_enabled: false,
- ai_actions_enabled: false,
- active_alerts: 0,
- relay_enabled: false,
- sso_enabled: false,
- multi_tenant: false,
- paid_license: false,
- has_api_tokens: true,
- },
+ payload: buildTelemetryPreviewPayload(),
});
const { hookState, dispose } = mountHookWithTab('system-general');
@@ -357,6 +419,9 @@ describe('useSystemSettingsState', () => {
expect(getTelemetryPreviewMock).toHaveBeenCalledOnce();
expect(hookState.telemetryPreviewPayload()).toContain('"install_id": "preview-install-id"');
+ expect(hookState.telemetryPreviewPayload()).toContain(
+ '"pulse_intelligence_patrol_control_completed_operations_loop_30d": false',
+ );
expect(hookState.telemetryPreviewEnabled()).toBe(true);
dispose();
});
@@ -364,51 +429,7 @@ describe('useSystemSettingsState', () => {
it('copies the loaded telemetry preview payload', async () => {
getTelemetryPreviewMock.mockResolvedValue({
enabled: false,
- payload: {
- install_id: 'preview-install-id',
- version: '6.0.0',
- version_channel: 'stable',
- version_is_development: false,
- version_is_published_release: true,
- platform: 'docker',
- os: 'linux',
- arch: 'amd64',
- event: 'heartbeat',
- pve_nodes: 1,
- pbs_instances: 0,
- pmg_instances: 0,
- vms: 2,
- containers: 3,
- agent_hosts: 1,
- docker_hosts: 0,
- docker_containers: 0,
- kubernetes_clusters: 0,
- kubernetes_nodes: 0,
- kubernetes_pods: 0,
- kubernetes_deployments: 0,
- storage_pools: 1,
- physical_disks: 2,
- ceph_clusters: 0,
- network_shares: 0,
- truenas_systems: 0,
- truenas_vms: 0,
- truenas_apps: 0,
- vmware_hosts: 0,
- vmware_vms: 0,
- vmware_datastores: 0,
- availability_targets: 1,
- ai_enabled: false,
- patrol_enabled: false,
- discovery_enabled: false,
- notifications_enabled: false,
- ai_actions_enabled: false,
- active_alerts: 0,
- relay_enabled: false,
- sso_enabled: false,
- multi_tenant: false,
- paid_license: false,
- has_api_tokens: true,
- },
+ payload: buildTelemetryPreviewPayload(),
});
const { hookState, dispose } = mountHookWithTab('system-general');
@@ -418,7 +439,9 @@ describe('useSystemSettingsState', () => {
await hookState.handleCopyTelemetryPreview();
await flushAsync();
- expect(copyToClipboardMock).toHaveBeenCalledWith(expect.stringContaining('"event": "heartbeat"'));
+ expect(copyToClipboardMock).toHaveBeenCalledWith(
+ expect.stringContaining('"pulse_intelligence_resolved_operations_loop_30d": false'),
+ );
expect(notificationStore.success).toHaveBeenCalledWith(
'Telemetry payload copied to clipboard',
2000,
@@ -430,51 +453,17 @@ describe('useSystemSettingsState', () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
resetTelemetryInstallIDMock.mockResolvedValue({
enabled: true,
- payload: {
+ payload: buildTelemetryPreviewPayload({
install_id: 'rotated-install-id',
- version: '6.0.0',
- version_channel: 'stable',
- version_is_development: false,
- version_is_published_release: true,
platform: 'binary',
- os: 'linux',
- arch: 'amd64',
- event: 'heartbeat',
pve_nodes: 0,
- pbs_instances: 0,
- pmg_instances: 0,
vms: 0,
containers: 0,
agent_hosts: 0,
- docker_hosts: 0,
- docker_containers: 0,
- kubernetes_clusters: 0,
- kubernetes_nodes: 0,
- kubernetes_pods: 0,
- kubernetes_deployments: 0,
storage_pools: 0,
physical_disks: 0,
- ceph_clusters: 0,
- network_shares: 0,
- truenas_systems: 0,
- truenas_vms: 0,
- truenas_apps: 0,
- vmware_hosts: 0,
- vmware_vms: 0,
- vmware_datastores: 0,
availability_targets: 0,
- ai_enabled: false,
- patrol_enabled: false,
- discovery_enabled: false,
- notifications_enabled: false,
- ai_actions_enabled: false,
- active_alerts: 0,
- relay_enabled: false,
- sso_enabled: false,
- multi_tenant: false,
- paid_license: false,
- has_api_tokens: true,
- },
+ }),
});
const { hookState, dispose } = mountHookWithTab('system-general');
diff --git a/frontend-modern/src/components/Settings/apiTokenManagerModel.ts b/frontend-modern/src/components/Settings/apiTokenManagerModel.ts
index 76571d227c..a5610d1b15 100644
--- a/frontend-modern/src/components/Settings/apiTokenManagerModel.ts
+++ b/frontend-modern/src/components/Settings/apiTokenManagerModel.ts
@@ -27,8 +27,18 @@ import type { Resource } from '@/types/resource';
export const API_TOKEN_SCOPES_DOC_URL = SHIPPED_API_TOKEN_SCOPES_DOC_URL;
export const API_TOKEN_WILDCARD_SCOPE = '*';
+export const API_TOKEN_KIOSK_PRESET_ID = 'kiosk_monitoring';
+export const API_TOKEN_PULSE_INTELLIGENCE_AGENT_PRESET_ID = 'pulse_intelligence_agent';
+export const API_TOKEN_PATROL_EXTERNAL_AGENT_PRESET_LABEL = 'Patrol external agent';
+export const API_TOKEN_AGENT_PRESET_ID = 'agent';
+export const API_TOKEN_DOCKER_REPORT_PRESET_ID = 'docker_podman_reporting';
+export const API_TOKEN_DOCKER_MANAGE_PRESET_ID = 'docker_podman_lifecycle';
+export const API_TOKEN_SETTINGS_READ_PRESET_ID = 'settings_read';
+export const API_TOKEN_SETTINGS_ADMIN_PRESET_ID = 'settings_admin';
+export const API_TOKEN_AUDIT_READ_PRESET_ID = 'audit_read';
export interface APITokenPreset {
+ id: string;
label: string;
scopes: string[];
description: string;
@@ -42,47 +52,83 @@ export interface APITokenUsageEntry {
type ScopeGroup = (typeof API_SCOPE_OPTIONS)[number]['group'];
type ScopeOption = (typeof API_SCOPE_OPTIONS)[number];
-const API_TOKEN_SCOPE_GROUP_ORDER: ScopeGroup[] = ['Monitoring', 'Agents', 'Settings', 'Security'];
-
-export const getAPITokenScopePresets = (): APITokenPreset[] => [
- {
- label: 'Kiosk / Monitoring',
- scopes: [MONITORING_READ_SCOPE],
- description:
- 'Read-only access for wall displays. Use ?token=xxx&kiosk=1 in the URL to hide navigation and filters.',
- },
- {
- label: 'Agent',
- scopes: [AGENT_REPORT_SCOPE],
- description: 'Allow the Pulse agent to submit OS, CPU, and disk metrics.',
- },
- {
- label: API_TOKEN_DOCKER_REPORT_PRESET_LABEL,
- scopes: [DOCKER_REPORT_SCOPE],
- description: API_TOKEN_DOCKER_REPORT_PRESET_DESCRIPTION,
- },
- {
- label: API_TOKEN_DOCKER_MANAGE_PRESET_LABEL,
- scopes: [DOCKER_REPORT_SCOPE, DOCKER_MANAGE_SCOPE],
- description: API_TOKEN_DOCKER_MANAGE_PRESET_DESCRIPTION,
- },
- {
- label: 'Settings read',
- scopes: [SETTINGS_READ_SCOPE],
- description: 'Read configuration snapshots and diagnostics without modifying anything.',
- },
- {
- label: 'Settings admin',
- scopes: [SETTINGS_READ_SCOPE, SETTINGS_WRITE_SCOPE],
- description: 'Full settings read/write – equivalent to automation with admin privileges.',
- },
- {
- label: 'Audit read',
- scopes: [AUDIT_READ_SCOPE],
- description: 'Read audit events, verification history, summaries, and export activity.',
- },
+const API_TOKEN_SCOPE_GROUP_ORDER: ScopeGroup[] = [
+ 'Monitoring',
+ 'AI',
+ 'Agents',
+ 'Settings',
+ 'Security',
];
+const normalizePresetScopes = (scopes: readonly string[] | undefined): string[] =>
+ Array.from(new Set((scopes ?? []).map((scope) => scope.trim()).filter(Boolean)));
+
+export const getAPITokenScopePresets = (
+ pulseIntelligenceRequiredScopes: readonly string[] = [],
+): APITokenPreset[] => {
+ const pulseIntelligenceScopes = normalizePresetScopes(pulseIntelligenceRequiredScopes);
+ const presets: APITokenPreset[] = [
+ {
+ id: API_TOKEN_KIOSK_PRESET_ID,
+ label: 'Kiosk / Monitoring',
+ scopes: [MONITORING_READ_SCOPE],
+ description:
+ 'Read-only access for wall displays. Use ?token=xxx&kiosk=1 in the URL to hide navigation and filters.',
+ },
+ ];
+
+ if (pulseIntelligenceScopes.length > 0) {
+ presets.push({
+ id: API_TOKEN_PULSE_INTELLIGENCE_AGENT_PRESET_ID,
+ label: API_TOKEN_PATROL_EXTERNAL_AGENT_PRESET_LABEL,
+ scopes: pulseIntelligenceScopes,
+ description:
+ 'Scopes for connected agents that read Pulse context and request Patrol work.',
+ });
+ }
+
+ presets.push(
+ {
+ id: API_TOKEN_AGENT_PRESET_ID,
+ label: 'Agent',
+ scopes: [AGENT_REPORT_SCOPE],
+ description: 'Allow the Pulse agent to submit OS, CPU, and disk metrics.',
+ },
+ {
+ id: API_TOKEN_DOCKER_REPORT_PRESET_ID,
+ label: API_TOKEN_DOCKER_REPORT_PRESET_LABEL,
+ scopes: [DOCKER_REPORT_SCOPE],
+ description: API_TOKEN_DOCKER_REPORT_PRESET_DESCRIPTION,
+ },
+ {
+ id: API_TOKEN_DOCKER_MANAGE_PRESET_ID,
+ label: API_TOKEN_DOCKER_MANAGE_PRESET_LABEL,
+ scopes: [DOCKER_REPORT_SCOPE, DOCKER_MANAGE_SCOPE],
+ description: API_TOKEN_DOCKER_MANAGE_PRESET_DESCRIPTION,
+ },
+ {
+ id: API_TOKEN_SETTINGS_READ_PRESET_ID,
+ label: 'Settings read',
+ scopes: [SETTINGS_READ_SCOPE],
+ description: 'Read configuration snapshots and diagnostics without modifying anything.',
+ },
+ {
+ id: API_TOKEN_SETTINGS_ADMIN_PRESET_ID,
+ label: 'Settings admin',
+ scopes: [SETTINGS_READ_SCOPE, SETTINGS_WRITE_SCOPE],
+ description: 'Full settings read/write - equivalent to automation with admin privileges.',
+ },
+ {
+ id: API_TOKEN_AUDIT_READ_PRESET_ID,
+ label: 'Audit read',
+ scopes: [AUDIT_READ_SCOPE],
+ description: 'Read audit events, verification history, summaries, and export activity.',
+ },
+ );
+
+ return presets;
+};
+
export const hasAgentScopeResource = (resource: Resource): boolean => {
if (resource.type === 'docker-host') return false;
return (
@@ -203,6 +249,7 @@ export const countWildcardTokens = (tokens: APITokenRecord[]): number => {
export const groupAPITokenScopes = (): [ScopeGroup, ScopeOption[]][] => {
const grouped: Record<ScopeGroup, ScopeOption[]> = {
Monitoring: [],
+ AI: [],
Agents: [],
Settings: [],
Security: [],
diff --git a/frontend-modern/src/components/Settings/diagnosticsModel.ts b/frontend-modern/src/components/Settings/diagnosticsModel.ts
index d53095359a..199b9cea05 100644
--- a/frontend-modern/src/components/Settings/diagnosticsModel.ts
+++ b/frontend-modern/src/components/Settings/diagnosticsModel.ts
@@ -116,8 +116,7 @@ export interface AIChatDiagnostic {
port?: number;
url?: string;
model?: string;
- mcpConnected: boolean;
- mcpToolCount?: number;
+ assistantRuntimeConnected: boolean;
notes?: string[];
}
diff --git a/frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts b/frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts
index 56c0be92c6..aaeb738e1a 100644
--- a/frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts
+++ b/frontend-modern/src/components/Settings/selfHostedBillingPresentation.ts
@@ -32,22 +32,20 @@ export interface SelfHostedProBillingPresentation {
}
export const SELF_HOSTED_PRO_BILLING_PRESENTATION: SelfHostedProBillingPresentation = {
- navLabel: 'Plans',
- shellTitle: 'Self-hosted plan',
- shellDescription:
- 'Review the plan this instance is using and the optional capabilities connected to it.',
- infrastructureRouteReferral: 'Billing and self-hosted plan changes live in Plans.',
+ navLabel: 'Plans & Billing',
+ shellTitle: 'Plans & Billing',
+ shellDescription: 'Plan, license, and Patrol mode for this instance.',
+ infrastructureRouteReferral: 'Billing and self-hosted plan changes live in Plans & Billing.',
infrastructureWorkspaceReferral:
- 'Self-hosted plan status, optional activation, and available capabilities live in Plans, not here.',
- sectionSelectorAriaLabel: 'Self-hosted plans section',
+ 'Self-hosted plan status, Patrol mode, and available capabilities live in Plans & Billing, not here.',
+ sectionSelectorAriaLabel: 'Plans and billing section',
refreshLabel: 'Refresh',
planTabLabel: 'Plan',
usageTabLabel: 'Usage',
planSectionTitle: 'Current plan',
- planSectionDescription:
- 'See which self-hosted tier this instance is using and which capabilities are available on this install.',
- planComparisonSectionTitle: 'Optional extras',
- planComparisonActionLabel: 'See all plans',
+ planSectionDescription: 'Current tier and enabled capabilities.',
+ planComparisonSectionTitle: 'Available plans',
+ planComparisonActionLabel: 'View plans',
usageSectionTitle: 'Usage',
hiddenShellTitle: 'Demo mode',
hiddenShellDescription: 'Commercial settings are hidden for this session.',
@@ -57,16 +55,14 @@ export const SELF_HOSTED_PRO_BILLING_PRESENTATION: SelfHostedProBillingPresentat
policyLoadingTitle: 'Loading settings access',
policyLoadingBody:
'Pulse waits for the session presentation policy before showing license, billing, or usage details.',
- planSelectionPromptTitle: 'Compare self-hosted plans',
- planSelectionPromptBody:
- 'Community includes core monitoring at no cost. Relay is optional for secure access from anywhere, and Pulse Pro adds root-cause analysis, safe remediation workflows, and 90-day history.',
- planSelectionPromptActionLabel: 'Compare plans',
+ planSelectionPromptTitle: 'Select a plan',
+ planSelectionPromptBody: 'Choose the plan for this install.',
+ planSelectionPromptActionLabel: 'View plans',
purchaseActivatedPlanActionLabel: 'Review plan',
- purchaseCancelledActionLabel: 'Compare plans',
- purchaseExpiredActionLabel: 'Compare plans',
+ purchaseCancelledActionLabel: 'View plans',
+ purchaseExpiredActionLabel: 'View plans',
purchaseFailedActionLabel: 'Open recovery',
purchaseUnavailableActionLabel: 'Try again',
- recoverySectionTitle: 'Existing purchases',
- recoverySectionDescription:
- 'Add an activation key you already have, recover a previous self-hosted purchase, or clear a local key from this instance.',
+ recoverySectionTitle: 'License recovery',
+ recoverySectionDescription: 'Paste a license key or clear the license on this install.',
};
diff --git a/frontend-modern/src/components/Settings/settingsHeaderMeta.ts b/frontend-modern/src/components/Settings/settingsHeaderMeta.ts
index 4a4a84a115..a2d35fb9d3 100644
--- a/frontend-modern/src/components/Settings/settingsHeaderMeta.ts
+++ b/frontend-modern/src/components/Settings/settingsHeaderMeta.ts
@@ -36,6 +36,19 @@ export const SETTINGS_HEADER_META: SettingsHeaderMetaMap = {
title: AI_SETTINGS_PANEL_TITLE,
description: AI_SETTINGS_PANEL_DESCRIPTION,
},
+ 'system-ai-patrol': {
+ title: 'Patrol',
+ description: 'Set when Patrol runs, what starts it, and which model it uses.',
+ },
+ 'system-ai-assistant': {
+ title: 'Assistant',
+ description: 'Configure Assistant chat behavior, chat action permissions, and sessions.',
+ },
+ 'system-ai-discovery': {
+ title: 'Service Context',
+ description:
+ 'Configure the model-backed service context Assistant and Patrol use. Infrastructure discovery and onboarding stay under Infrastructure.',
+ },
'system-relay': {
title: 'Remote Access',
description: RELAY_SETTINGS_DESCRIPTION,
@@ -149,6 +162,18 @@ const SETTINGS_HEADER_META_KEYS = {
title: 'settings.header.systemAi.title',
description: 'settings.header.systemAi.description',
},
+ 'system-ai-patrol': {
+ title: 'settings.header.systemAiPatrol.title',
+ description: 'settings.header.systemAiPatrol.description',
+ },
+ 'system-ai-assistant': {
+ title: 'settings.header.systemAiAssistant.title',
+ description: 'settings.header.systemAiAssistant.description',
+ },
+ 'system-ai-discovery': {
+ title: 'settings.header.systemAiDiscovery.title',
+ description: 'settings.header.systemAiDiscovery.description',
+ },
'system-relay': {
title: 'settings.header.systemRelay.title',
description: 'settings.header.systemRelay.description',
diff --git a/frontend-modern/src/components/Settings/settingsNavCatalog.ts b/frontend-modern/src/components/Settings/settingsNavCatalog.ts
index 8a9e1e681e..8494aaf7bf 100644
--- a/frontend-modern/src/components/Settings/settingsNavCatalog.ts
+++ b/frontend-modern/src/components/Settings/settingsNavCatalog.ts
@@ -53,6 +53,42 @@ export const SETTINGS_NAV_GROUPS: SettingsNavGroup[] = [
},
],
},
+ {
+ id: 'pulse-intelligence',
+ label: 'Pulse Intelligence',
+ items: [
+ {
+ id: 'system-ai',
+ label: 'Provider & Models',
+ icon: Sparkles,
+ iconProps: { strokeWidth: 2 },
+ },
+ {
+ id: 'system-ai-patrol',
+ label: 'Patrol',
+ icon: Activity,
+ iconProps: { strokeWidth: 2 },
+ },
+ {
+ id: 'system-billing',
+ label: SELF_HOSTED_PRO_BILLING_PRESENTATION.navLabel,
+ icon: PulseLogoIcon,
+ hideWhenCommercialHidden: true,
+ },
+ {
+ id: 'system-ai-assistant',
+ label: 'Assistant',
+ icon: Terminal,
+ iconProps: { strokeWidth: 2 },
+ },
+ {
+ id: 'system-ai-discovery',
+ label: 'Service Context',
+ icon: Network,
+ iconProps: { strokeWidth: 2 },
+ },
+ ],
+ },
{
id: 'organization',
label: 'Organization',
@@ -140,19 +176,6 @@ export const SETTINGS_NAV_GROUPS: SettingsNavGroup[] = [
iconProps: { strokeWidth: 2 },
saveBehavior: 'system',
},
- {
- id: 'system-ai',
- label: 'Assistant & Patrol',
- icon: Sparkles,
- iconProps: { strokeWidth: 2 },
- },
- {
- id: 'system-billing',
- label: SELF_HOSTED_PRO_BILLING_PRESENTATION.navLabel,
- icon: PulseLogoIcon,
- hideFromSidebar: true,
- hideWhenCommercialHidden: true,
- },
],
},
{
@@ -273,6 +296,7 @@ export const SETTINGS_NAV_GROUPS: SettingsNavGroup[] = [
const SETTINGS_NAV_GROUP_LABEL_KEYS = {
infrastructure: 'settings.nav.group.infrastructure',
monitoring: 'settings.nav.group.monitoring',
+ 'pulse-intelligence': 'settings.nav.group.pulseIntelligence',
organization: 'settings.nav.group.organization',
system: 'settings.nav.group.system',
support: 'settings.nav.group.support',
@@ -286,7 +310,10 @@ const SETTINGS_NAV_ITEM_LABEL_KEYS = {
'system-network': 'settings.nav.item.network',
'system-updates': 'settings.nav.item.updates',
'system-recovery': 'settings.nav.item.recovery',
- 'system-ai': 'settings.nav.item.assistantPatrol',
+ 'system-ai': 'settings.nav.item.providerModels',
+ 'system-ai-patrol': 'settings.nav.item.patrol',
+ 'system-ai-assistant': 'settings.nav.item.assistant',
+ 'system-ai-discovery': 'settings.nav.item.discovery',
'system-relay': 'settings.nav.item.remoteAccess',
'system-billing': 'settings.nav.item.plans',
'support-diagnostics': 'settings.nav.item.diagnosticsHealth',
diff --git a/frontend-modern/src/components/Settings/settingsNavigationModel.ts b/frontend-modern/src/components/Settings/settingsNavigationModel.ts
index f99aa0d678..3ff1fd9ded 100644
--- a/frontend-modern/src/components/Settings/settingsNavigationModel.ts
+++ b/frontend-modern/src/components/Settings/settingsNavigationModel.ts
@@ -11,9 +11,14 @@ import {
shouldOpenAvailabilityTargetAddDialog,
} from './availabilitySettingsModel';
import {
+ LEGACY_SELF_HOSTED_PRO_BILLING_PLAN_ROUTE,
+ LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE,
+ LEGACY_SELF_HOSTED_PRO_BILLING_USAGE_ROUTE,
SELF_HOSTED_PRO_BILLING_PLAN_ROUTE,
SELF_HOSTED_PRO_BILLING_ROUTE,
+ SELF_HOSTED_PRO_BILLING_USAGE_ROUTE,
} from '@/utils/pricingHandoff';
+import { SETTINGS_API_ACCESS_PATH } from '@/routing/resourceLinks';
export type SettingsTab =
| 'infrastructure-systems'
@@ -23,6 +28,9 @@ export type SettingsTab =
| 'system-updates'
| 'system-recovery'
| 'system-ai'
+ | 'system-ai-patrol'
+ | 'system-ai-assistant'
+ | 'system-ai-discovery'
| 'system-relay'
| 'system-billing'
| 'support-diagnostics'
@@ -54,6 +62,7 @@ export type ProxmoxPlatformType = Extract<
export type SettingsNavGroupId =
| 'infrastructure'
| 'monitoring'
+ | 'pulse-intelligence'
| 'organization'
| 'system'
| 'support'
@@ -98,6 +107,14 @@ export const DEFAULT_SETTINGS_TAB: SettingsTab = 'infrastructure-systems';
const INFRASTRUCTURE_SYSTEMS_PREFIX = '/settings/infrastructure';
const MONITORING_PREFIX = '/settings/monitoring';
const MONITORING_AVAILABILITY_PREFIX = `${MONITORING_PREFIX}/availability`;
+export const SETTINGS_PULSE_INTELLIGENCE_PATH = '/settings/pulse-intelligence';
+export const SETTINGS_PROVIDER_MODELS_PATH = `${SETTINGS_PULSE_INTELLIGENCE_PATH}/provider`;
+const PULSE_INTELLIGENCE_PREFIX = SETTINGS_PULSE_INTELLIGENCE_PATH;
+const PULSE_INTELLIGENCE_PROVIDER_PREFIX = SETTINGS_PROVIDER_MODELS_PATH;
+const PULSE_INTELLIGENCE_PATROL_PREFIX = `${PULSE_INTELLIGENCE_PREFIX}/patrol`;
+const PULSE_INTELLIGENCE_ASSISTANT_PREFIX = `${PULSE_INTELLIGENCE_PREFIX}/assistant`;
+const PULSE_INTELLIGENCE_DISCOVERY_PREFIX = `${PULSE_INTELLIGENCE_PREFIX}/discovery`;
+const LEGACY_SYSTEM_AI_PREFIX = '/settings/system-ai';
const RETIRED_SETTINGS_WORKLOADS_PREFIX = '/settings/workloads';
const RETIRED_SETTINGS_OPERATIONS_PREFIX = '/settings/operations';
const RETIRED_SETTINGS_INTEGRATIONS_API_PREFIX = '/settings/integrations/api';
@@ -106,8 +123,9 @@ const SUPPORT_PREFIX = '/settings/support';
const SUPPORT_DIAGNOSTICS_PREFIX = `${SUPPORT_PREFIX}/diagnostics`;
const SUPPORT_REPORTING_PREFIX = `${SUPPORT_PREFIX}/reporting`;
const SUPPORT_LOGS_PREFIX = `${SUPPORT_PREFIX}/logs`;
-const SECURITY_API_PREFIX = '/settings/security/api';
-const SYSTEM_BILLING_PREFIX = SELF_HOSTED_PRO_BILLING_ROUTE;
+const SECURITY_API_PREFIX = SETTINGS_API_ACCESS_PATH;
+const SELF_HOSTED_BILLING_PREFIX = SELF_HOSTED_PRO_BILLING_ROUTE;
+const LEGACY_SYSTEM_BILLING_PREFIX = LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE;
const PROXMOX_AGENT_META: Record<
AgentKey,
@@ -171,12 +189,26 @@ export function resolveCanonicalSettingsPath(path: string): string | null {
if (normalizedPath === MONITORING_PREFIX) {
return MONITORING_AVAILABILITY_PREFIX;
}
+ if (
+ normalizedPath === PULSE_INTELLIGENCE_PREFIX ||
+ normalizedPath === PULSE_INTELLIGENCE_PROVIDER_PREFIX ||
+ normalizedPath === LEGACY_SYSTEM_AI_PREFIX
+ ) {
+ return settingsTabPath('system-ai');
+ }
if (normalizedPath === SUPPORT_PREFIX) {
return SUPPORT_DIAGNOSTICS_PREFIX;
}
- if (normalizedPath === SYSTEM_BILLING_PREFIX) {
+ if (
+ normalizedPath === SELF_HOSTED_BILLING_PREFIX ||
+ normalizedPath === LEGACY_SYSTEM_BILLING_PREFIX ||
+ normalizedPath === LEGACY_SELF_HOSTED_PRO_BILLING_PLAN_ROUTE
+ ) {
return SELF_HOSTED_PRO_BILLING_PLAN_ROUTE;
}
+ if (normalizedPath === LEGACY_SELF_HOSTED_PRO_BILLING_USAGE_ROUTE) {
+ return SELF_HOSTED_PRO_BILLING_USAGE_ROUTE;
+ }
return normalizedPath;
}
@@ -190,6 +222,18 @@ export function deriveTabFromPath(path: string): SettingsTab {
if (canonicalPath.startsWith(MONITORING_AVAILABILITY_PREFIX)) {
return 'monitoring-availability';
}
+ if (canonicalPath.startsWith(PULSE_INTELLIGENCE_PATROL_PREFIX)) {
+ return 'system-ai-patrol';
+ }
+ if (canonicalPath.startsWith(PULSE_INTELLIGENCE_ASSISTANT_PREFIX)) {
+ return 'system-ai-assistant';
+ }
+ if (canonicalPath.startsWith(PULSE_INTELLIGENCE_DISCOVERY_PREFIX)) {
+ return 'system-ai-discovery';
+ }
+ if (canonicalPath.startsWith(PULSE_INTELLIGENCE_PROVIDER_PREFIX)) {
+ return 'system-ai';
+ }
if (canonicalPath.includes('/settings/system-general')) return 'system-general';
if (canonicalPath.includes('/settings/system-network')) return 'system-network';
@@ -197,7 +241,7 @@ export function deriveTabFromPath(path: string): SettingsTab {
if (canonicalPath.includes('/settings/system-recovery')) return 'system-recovery';
if (canonicalPath.includes('/settings/system-ai')) return 'system-ai';
if (canonicalPath.includes('/settings/system-relay')) return 'system-relay';
- if (canonicalPath.includes(SYSTEM_BILLING_PREFIX)) return 'system-billing';
+ if (canonicalPath.includes(SELF_HOSTED_BILLING_PREFIX)) return 'system-billing';
if (canonicalPath.startsWith(SUPPORT_LOGS_PREFIX)) return 'support-logs';
if (canonicalPath.startsWith(SUPPORT_REPORTING_PREFIX)) return 'support-reporting';
if (canonicalPath.startsWith(SUPPORT_DIAGNOSTICS_PREFIX) || canonicalPath === SUPPORT_PREFIX)
@@ -251,6 +295,8 @@ export function agentKeyFromPlatformType(value: string | null | undefined): Agen
export function deriveTabFromQuery(search: string): SettingsTab | null {
const params = new URLSearchParams(search);
+ if (isAISettingsOAuthCallbackQuery(search)) return 'system-ai';
+
const tab = params.get('tab')?.trim().toLowerCase();
if (!tab) return null;
@@ -269,7 +315,19 @@ export function deriveTabFromQuery(search: string): SettingsTab | null {
case 'system-general':
return 'system-general';
case 'system-ai':
+ case 'pulse-intelligence':
+ case 'provider-models':
+ case 'provider':
return 'system-ai';
+ case 'system-ai-patrol':
+ case 'patrol':
+ return 'system-ai-patrol';
+ case 'system-ai-assistant':
+ case 'assistant':
+ return 'system-ai-assistant';
+ case 'system-ai-discovery':
+ case 'discovery':
+ return 'system-ai-discovery';
case 'system-relay':
return 'system-relay';
case 'system-billing':
@@ -318,6 +376,11 @@ export function deriveTabFromQuery(search: string): SettingsTab | null {
}
}
+export function isAISettingsOAuthCallbackQuery(search: string): boolean {
+ const params = new URLSearchParams(search);
+ return params.has('ai_oauth_success') || params.has('ai_oauth_error');
+}
+
export function settingsTabPath(tab: SettingsTab): string {
switch (tab) {
case 'infrastructure-systems':
@@ -338,6 +401,14 @@ export function settingsTabPath(tab: SettingsTab): string {
return '/settings/organization/billing-admin';
case 'api':
return SECURITY_API_PREFIX;
+ case 'system-ai':
+ return PULSE_INTELLIGENCE_PROVIDER_PREFIX;
+ case 'system-ai-patrol':
+ return PULSE_INTELLIGENCE_PATROL_PREFIX;
+ case 'system-ai-assistant':
+ return PULSE_INTELLIGENCE_ASSISTANT_PREFIX;
+ case 'system-ai-discovery':
+ return PULSE_INTELLIGENCE_DISCOVERY_PREFIX;
case 'system-relay':
return '/settings/system-relay';
case 'system-billing':
@@ -361,9 +432,12 @@ const ROUTEABLE_SETTINGS_PATHS = new Set<string>([
settingsTabPath('system-updates'),
settingsTabPath('system-recovery'),
settingsTabPath('system-ai'),
+ settingsTabPath('system-ai-patrol'),
+ settingsTabPath('system-ai-assistant'),
+ settingsTabPath('system-ai-discovery'),
settingsTabPath('system-relay'),
settingsTabPath('system-billing'),
- `${SYSTEM_BILLING_PREFIX}/usage`,
+ SELF_HOSTED_PRO_BILLING_USAGE_ROUTE,
settingsTabPath('support-diagnostics'),
settingsTabPath('support-reporting'),
settingsTabPath('support-logs'),
diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistry.ts b/frontend-modern/src/components/Settings/settingsPanelRegistry.ts
index 4582f863c2..4fdf62b676 100644
--- a/frontend-modern/src/components/Settings/settingsPanelRegistry.ts
+++ b/frontend-modern/src/components/Settings/settingsPanelRegistry.ts
@@ -28,6 +28,9 @@ export interface SettingsPanelRegistryContext {
getInfrastructurePanelProps: () => Parameters<typeof InfrastructureWorkspaceType>[0];
systemGeneralPanel: Component;
systemAiPanel: Component;
+ systemAiPatrolPanel: Component;
+ systemAiAssistantPanel: Component;
+ systemAiDiscoveryPanel: Component;
systemBillingPanel: Component;
securitySsoPanel: Component;
getNetworkPanelProps: () => Parameters<typeof NetworkSettingsPanelType>[0];
@@ -72,6 +75,15 @@ export const createSettingsPanelRegistry = (
'system-ai': {
component: context.systemAiPanel,
},
+ 'system-ai-patrol': {
+ component: context.systemAiPatrolPanel,
+ },
+ 'system-ai-assistant': {
+ component: context.systemAiAssistantPanel,
+ },
+ 'system-ai-discovery': {
+ component: context.systemAiDiscoveryPanel,
+ },
'system-relay': {
component: SETTINGS_PANEL_REGISTRY_LOADERS.RelaySettingsPanel,
getProps: context.getRelayPanelProps,
diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
index 662619255e..f7b1541517 100644
--- a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
+++ b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
@@ -2,7 +2,12 @@ import type { Accessor, Component, Setter } from 'solid-js';
import type { VersionInfo } from '@/api/updates';
import type { SecurityStatus as SecurityStatusInfo } from '@/types/config';
import { AICostDashboard } from '@/components/AI/AICostDashboard';
-import { AISettings } from './AISettings';
+import {
+ AIAssistantSettings,
+ AIDiscoverySettings,
+ AISettings,
+ AIPatrolSettings,
+} from './AISettings';
import { ProLicensePanel } from './ProLicensePanel';
import { SSOProvidersPanel } from './SSOProvidersPanel';
import type { InfrastructurePlatformSettingsProps } from './proxmoxSettingsModel';
@@ -35,9 +40,9 @@ export function buildSettingsPanelRegistryContext(
): SettingsPanelRegistryContext {
const settingsCapabilities = () => params.securityStatus()?.settingsCapabilities ?? null;
const currentUser = () =>
- params.securityStatus()?.proxyAuthUsername
- || params.securityStatus()?.ssoSessionUsername
- || params.securityStatus()?.authUsername;
+ params.securityStatus()?.proxyAuthUsername ||
+ params.securityStatus()?.ssoSessionUsername ||
+ params.securityStatus()?.authUsername;
const systemAiPanel: Component = () => (
<div class="space-y-6">
@@ -52,6 +57,10 @@ export function buildSettingsPanelRegistryContext(
</div>
);
+ const systemAiPatrolPanel: Component = () => <AIPatrolSettings />;
+ const systemAiAssistantPanel: Component = () => <AIAssistantSettings />;
+ const systemAiDiscoveryPanel: Component = () => <AIDiscoverySettings />;
+
const securitySsoPanel: Component = () => (
<div class="space-y-6">
<SSOProvidersPanel
@@ -65,6 +74,9 @@ export function buildSettingsPanelRegistryContext(
getInfrastructurePanelProps: params.getInfrastructurePanelProps,
systemGeneralPanel: params.systemPanels.systemGeneralPanel,
systemAiPanel,
+ systemAiPatrolPanel,
+ systemAiAssistantPanel,
+ systemAiDiscoveryPanel,
systemBillingPanel,
securitySsoPanel,
getNetworkPanelProps: params.systemPanels.getNetworkPanelProps,
diff --git a/frontend-modern/src/components/Settings/useAISettingsState.ts b/frontend-modern/src/components/Settings/useAISettingsState.ts
index 28b3c4c62f..891c5a183a 100644
--- a/frontend-modern/src/components/Settings/useAISettingsState.ts
+++ b/frontend-modern/src/components/Settings/useAISettingsState.ts
@@ -44,6 +44,11 @@ type AISettingsSaveProviderFailure = {
providerMessage?: string;
};
+interface AISettingsStateOptions {
+ saveErrorFallback?: string;
+ savedLabel?: string;
+}
+
const AI_SETTINGS_PROVIDER_PAYLOAD_FIELDS: Record<AIProvider, string[]> = {
anthropic: ['anthropic_api_key'],
openai: ['openai_api_key', 'openai_base_url'],
@@ -100,9 +105,13 @@ const isGenericAISettingsSaveFailure = (error: unknown): boolean => {
if (!message) return true;
return (
message === 'failed to save assistant & patrol settings' ||
+ message === 'failed to save provider & models settings' ||
message === 'unable to save assistant & patrol settings.' ||
message === 'unable to save assistant & patrol settings' ||
+ message === 'unable to save provider & models settings.' ||
+ message === 'unable to save provider & models settings' ||
message.includes('failed to save assistant & patrol settings') ||
+ message.includes('failed to save provider & models settings') ||
message.startsWith('request failed with status')
);
};
@@ -110,8 +119,9 @@ const isGenericAISettingsSaveFailure = (error: unknown): boolean => {
export function getAISettingsSaveProviderFailureMessage(
message: string | undefined,
failure?: AISettingsSaveProviderFailure | null,
+ fallback?: string,
): string {
- const baseMessage = getAISettingsSaveErrorMessage(message);
+ const baseMessage = getAISettingsSaveErrorMessage(message, fallback);
if (!failure?.provider) return baseMessage;
const providerLabel = getAIProviderDisplayName(failure.provider);
@@ -129,7 +139,7 @@ export function getAISettingsSaveProviderFailureMessage(
export function getAISettingsPatrolReadinessSaveMessage(
readiness: AISettingsType['patrol_readiness'] | null | undefined,
- savedLabel = 'Assistant & Patrol settings saved',
+ savedLabel = 'Provider & Models settings saved',
): string | null {
if (!readiness || readiness.status === 'ready') return null;
@@ -209,7 +219,7 @@ export function resolveAISettingsSaveProviderFailure(input: {
return null;
}
-export const useAISettingsState = () => {
+export const useAISettingsState = (options: AISettingsStateOptions = {}) => {
const [settings, setSettings] = createSignal<AISettingsType | null>(null);
const [loading, setLoading] = createSignal(false);
const [loadError, setLoadError] = createSignal(false);
@@ -244,7 +254,7 @@ export const useAISettingsState = () => {
// hydratePatrolPreflightFromSettings projects the cached preflight
// snapshot from /api/settings/ai into the same response shape the
- // manual Verify Patrol button writes, so the inline result panel can
+ // manual Check Patrol model button writes, so the inline result panel can
// render the most-recent outcome on page load without forcing a
// re-click. Returns null when preflight has never run on the
// current Pulse instance.
@@ -288,6 +298,9 @@ export const useAISettingsState = () => {
authMethod: 'api_key' as AuthMethod,
patrolIntervalMinutes: 360,
alertTriggeredAnalysis: true,
+ patrolAlertTriggers: true,
+ patrolAnomalyTriggers: true,
+ patrolAlertTriggerMinSeverity: 'critical' as 'warning' | 'critical',
patrolAutoFix: false,
anthropicApiKey: '',
openaiApiKey: '',
@@ -315,6 +328,7 @@ export const useAISettingsState = () => {
}),
);
const autoFixLocked = createMemo(() => !hasFeature('ai_autofix'));
+ const alertAnalysisLocked = createMemo(() => !hasFeature('ai_alerts'));
const providerIssueCount = createMemo(
() => AI_PROVIDERS.filter((provider) => providerHealth[provider].status === 'error').length,
);
@@ -363,6 +377,9 @@ export const useAISettingsState = () => {
authMethod: 'api_key',
patrolIntervalMinutes: 360,
alertTriggeredAnalysis: true,
+ patrolAlertTriggers: true,
+ patrolAnomalyTriggers: true,
+ patrolAlertTriggerMinSeverity: 'critical',
patrolAutoFix: false,
anthropicApiKey: '',
openaiApiKey: '',
@@ -382,6 +399,9 @@ export const useAISettingsState = () => {
return;
}
+ const legacyEventTriggersEnabled =
+ data.patrol_event_triggers_enabled ?? data.alert_triggered_analysis !== false;
+
setForm({
enabled: data.enabled,
model: data.model || '',
@@ -392,6 +412,10 @@ export const useAISettingsState = () => {
authMethod: data.auth_method || 'api_key',
patrolIntervalMinutes: data.patrol_interval_minutes ?? 360,
alertTriggeredAnalysis: data.alert_triggered_analysis !== false,
+ patrolAlertTriggers: data.patrol_alert_triggers_enabled ?? legacyEventTriggersEnabled,
+ patrolAnomalyTriggers: data.patrol_anomaly_triggers_enabled ?? legacyEventTriggersEnabled,
+ patrolAlertTriggerMinSeverity:
+ data.patrol_alert_trigger_min_severity === 'warning' ? 'warning' : 'critical',
patrolAutoFix: data.patrol_auto_fix || false,
anthropicApiKey: '',
openaiApiKey: '',
@@ -596,7 +620,7 @@ export const useAISettingsState = () => {
// which only confirms each provider's model catalog is reachable.
//
// Passes the form's pending patrolModel as a model override so clicking
- // Verify Patrol after changing the dropdown actually tests the operator's
+ // Check Patrol model after changing the dropdown actually tests the operator's
// pending selection, not whatever was previously saved. Empty form value
// means "use the shared default" — the backend handles the fallback.
const runPatrolToolPreflight = async () => {
@@ -702,12 +726,12 @@ export const useAISettingsState = () => {
handleCloseSetupModal();
const patrolReadinessMessage = getAISettingsPatrolReadinessSaveMessage(
updated.patrol_readiness,
- 'Assistant & Patrol enabled',
+ 'Pulse Intelligence enabled',
);
if (patrolReadinessMessage) {
notificationStore.warning(patrolReadinessMessage);
} else {
- notificationStore.success('Assistant & Patrol enabled! You can customize settings below.');
+ notificationStore.success('Pulse Intelligence enabled. You can customize settings below.');
}
} catch (error) {
logger.error('[AISettings] Setup failed:', error);
@@ -806,6 +830,18 @@ export const useAISettingsState = () => {
if (form.alertTriggeredAnalysis !== settings()?.alert_triggered_analysis) {
payload.alert_triggered_analysis = form.alertTriggeredAnalysis;
}
+ if (form.patrolAlertTriggers !== (settings()?.patrol_alert_triggers_enabled ?? true)) {
+ payload.patrol_alert_triggers_enabled = form.patrolAlertTriggers;
+ }
+ if (form.patrolAnomalyTriggers !== (settings()?.patrol_anomaly_triggers_enabled ?? true)) {
+ payload.patrol_anomaly_triggers_enabled = form.patrolAnomalyTriggers;
+ }
+ if (
+ form.patrolAlertTriggerMinSeverity !==
+ (settings()?.patrol_alert_trigger_min_severity ?? 'critical')
+ ) {
+ payload.patrol_alert_trigger_min_severity = form.patrolAlertTriggerMinSeverity;
+ }
if (form.patrolAutoFix !== settings()?.patrol_auto_fix) {
payload.patrol_auto_fix = form.patrolAutoFix;
}
@@ -888,13 +924,15 @@ export const useAISettingsState = () => {
syncModelCatalogForSettings(updated);
hydratePatrolPreflightFromSettings(updated);
void runProviderPreflight(updated);
+ const savedLabel = options.savedLabel ?? 'Provider & Models settings saved';
const patrolReadinessMessage = getAISettingsPatrolReadinessSaveMessage(
updated.patrol_readiness,
+ savedLabel,
);
if (patrolReadinessMessage) {
notificationStore.warning(patrolReadinessMessage);
} else {
- notificationStore.success('Assistant & Patrol settings saved');
+ notificationStore.success(savedLabel);
}
} catch (error) {
logger.error('[AISettings] Failed to save settings:', error);
@@ -914,6 +952,7 @@ export const useAISettingsState = () => {
getAISettingsSaveProviderFailureMessage(
error instanceof Error ? error.message : '',
providerFailure,
+ options.saveErrorFallback,
),
);
} finally {
@@ -1051,7 +1090,7 @@ export const useAISettingsState = () => {
syncModelCatalogForSettings(updated);
void runProviderPreflight(updated);
notificationStore.success(
- newValue ? 'Assistant & Patrol enabled' : 'Assistant & Patrol disabled',
+ newValue ? 'Pulse Intelligence enabled' : 'Pulse Intelligence disabled',
);
} catch (error) {
setForm('enabled', !newValue);
@@ -1095,6 +1134,7 @@ export const useAISettingsState = () => {
});
return {
+ alertAnalysisLocked,
autoFixLocked,
availableModels,
chatSessions,
diff --git a/frontend-modern/src/components/Settings/useAPITokenManagerState.ts b/frontend-modern/src/components/Settings/useAPITokenManagerState.ts
index ceddfbee16..51b6355b6a 100644
--- a/frontend-modern/src/components/Settings/useAPITokenManagerState.ts
+++ b/frontend-modern/src/components/Settings/useAPITokenManagerState.ts
@@ -1,8 +1,20 @@
-import { createEffect, createMemo, createSignal, onCleanup, onMount } from 'solid-js';
+import {
+ createEffect,
+ createMemo,
+ createResource,
+ createSignal,
+ onCleanup,
+ onMount,
+} from 'solid-js';
+import { fetchAgentCapabilitiesManifest } from '@/api/agentCapabilities';
import type { APITokenRecord } from '@/api/security';
import { SecurityAPI } from '@/api/security';
import { useWebSocket } from '@/contexts/appRuntime';
import { MONITORING_READ_SCOPE, API_SCOPE_LABELS } from '@/constants/apiScopes';
+import {
+ API_TOKEN_PRESET_QUERY_PARAM,
+ PULSE_INTELLIGENCE_AGENT_TOKEN_PRESET,
+} from '@/routing/resourceLinks';
import { useResources } from '@/hooks/useResources';
import { notificationStore } from '@/stores/notifications';
import { showTokenReveal, useTokenRevealState } from '@/stores/tokenReveal';
@@ -19,6 +31,7 @@ import { logger } from '@/utils/logger';
import { getPulseBaseUrl } from '@/utils/url';
import {
API_TOKEN_SCOPES_DOC_URL,
+ API_TOKEN_PULSE_INTELLIGENCE_AGENT_PRESET_ID,
API_TOKEN_WILDCARD_SCOPE,
agentActionIdForResource,
buildAgentTokenUsage,
@@ -64,6 +77,7 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
const [newTokenRecord, setNewTokenRecord] = createSignal<APITokenRecord | null>(null);
const [nameInput, setNameInput] = createSignal('');
const [selectedScopes, setSelectedScopes] = createSignal<string[]>([]);
+ const [agentCapabilitiesManifest] = createResource(fetchAgentCapabilitiesManifest);
const tokenRevealState = useTokenRevealState();
const canManage = () => props.canManage !== false;
@@ -73,21 +87,66 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
const scopedTokenCount = createMemo(() => totalTokens() - wildcardCount());
const hasWildcardTokens = createMemo(() => wildcardCount() > 0);
const scopeGroups = createMemo(() => groupAPITokenScopes());
- const scopePresets = getAPITokenScopePresets();
- const isFullAccessSelected = () =>
- selectedScopes().length === 0 || selectedScopes().includes(API_TOKEN_WILDCARD_SCOPE);
+ const scopePresets = createMemo(() =>
+ getAPITokenScopePresets(agentCapabilitiesManifest()?.requiredScopes ?? []),
+ );
+ const pulseIntelligenceAgentPreset = createMemo(() =>
+ scopePresets().find((preset) => preset.id === API_TOKEN_PULSE_INTELLIGENCE_AGENT_PRESET_ID),
+ );
+ const hasScopeSelection = () => selectedScopes().length > 0;
+ const isFullAccessSelected = () => selectedScopes().includes(API_TOKEN_WILDCARD_SCOPE);
+ const canGenerateToken = () => canManage() && hasScopeSelection() && !isGenerating();
let createSectionRef: HTMLDivElement | undefined;
const [createHighlight, setCreateHighlight] = createSignal(false);
+ const [createSectionReady, setCreateSectionReady] = createSignal(false);
+ const [requestedTokenPreset, setRequestedTokenPreset] = createSignal('');
+ const [appliedRoutePreset, setAppliedRoutePreset] = createSignal('');
+ const [focusedRoutePreset, setFocusedRoutePreset] = createSignal('');
let highlightTimer: number | undefined;
+ let routeFocusTimer: number | undefined;
+
+ const readRequestedTokenPreset = () => {
+ if (typeof window === 'undefined') return '';
+ return (
+ new URLSearchParams(window.location.search).get(API_TOKEN_PRESET_QUERY_PARAM)?.trim() ?? ''
+ );
+ };
const setCreateSectionRef = (element: HTMLDivElement) => {
createSectionRef = element;
+ setCreateSectionReady(true);
+ };
+
+ const findScrollableAncestor = (element: HTMLElement): HTMLElement | null => {
+ let current = element.parentElement;
+ while (current) {
+ const style = window.getComputedStyle(current);
+ const canScroll =
+ (style.overflowY === 'auto' || style.overflowY === 'scroll') &&
+ current.scrollHeight > current.clientHeight;
+ if (canScroll) {
+ return current;
+ }
+ current = current.parentElement;
+ }
+ return null;
};
const focusCreateSection = () => {
if (!createSectionRef) return;
- createSectionRef.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ if (typeof createSectionRef.scrollIntoView === 'function') {
+ createSectionRef.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ }
+ const scrollParent = findScrollableAncestor(createSectionRef);
+ if (scrollParent && typeof scrollParent.scrollTo === 'function') {
+ const parentRect = scrollParent.getBoundingClientRect();
+ const sectionRect = createSectionRef.getBoundingClientRect();
+ scrollParent.scrollTo({
+ top: Math.max(0, scrollParent.scrollTop + sectionRect.top - parentRect.top - 16),
+ behavior: 'smooth',
+ });
+ }
setCreateHighlight(true);
window.clearTimeout(highlightTimer);
highlightTimer = window.setTimeout(() => setCreateHighlight(false), 1600);
@@ -95,6 +154,7 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
onCleanup(() => {
if (highlightTimer) window.clearTimeout(highlightTimer);
+ if (routeFocusTimer) window.clearTimeout(routeFocusTimer);
});
const loadTokens = async () => {
@@ -113,7 +173,63 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
};
onMount(() => {
+ setRequestedTokenPreset(readRequestedTokenPreset());
+ const handleRoutePresetChange = () => {
+ setRequestedTokenPreset(readRequestedTokenPreset());
+ };
+ window.addEventListener('hashchange', handleRoutePresetChange);
+ window.addEventListener('popstate', handleRoutePresetChange);
void loadTokens();
+ onCleanup(() => {
+ window.removeEventListener('hashchange', handleRoutePresetChange);
+ window.removeEventListener('popstate', handleRoutePresetChange);
+ });
+ });
+
+ createEffect(() => {
+ const requestedPreset = requestedTokenPreset();
+ if (
+ requestedPreset !== PULSE_INTELLIGENCE_AGENT_TOKEN_PRESET ||
+ appliedRoutePreset() === requestedPreset
+ ) {
+ return;
+ }
+
+ const preset = pulseIntelligenceAgentPreset();
+ if (!preset || preset.scopes.length === 0) {
+ return;
+ }
+
+ applyScopePreset(preset.scopes);
+ if (!nameInput().trim()) {
+ setNameInput(preset.label);
+ }
+ setAppliedRoutePreset(requestedPreset);
+ });
+
+ createEffect(() => {
+ const requestedPreset = requestedTokenPreset();
+ if (requestedPreset !== PULSE_INTELLIGENCE_AGENT_TOKEN_PRESET) {
+ setFocusedRoutePreset('');
+ return;
+ }
+ if (
+ !createSectionReady() ||
+ loading() ||
+ appliedRoutePreset() !== requestedPreset ||
+ focusedRoutePreset() === requestedPreset
+ ) {
+ return;
+ }
+
+ focusCreateSection();
+ window.clearTimeout(routeFocusTimer);
+ routeFocusTimer = window.setTimeout(() => {
+ if (requestedTokenPreset() === requestedPreset) {
+ focusCreateSection();
+ }
+ }, 0);
+ setFocusedRoutePreset(requestedPreset);
});
createEffect(() => {
@@ -163,6 +279,8 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
setSelectedScopes(Array.from(new Set(scopes)).filter(Boolean));
};
+ const applyFullAccessPreset = () => applyScopePreset([API_TOKEN_WILDCARD_SCOPE]);
+
const clearScopes = () => setSelectedScopes([]);
const toggleScope = (scope: string) => {
@@ -176,6 +294,10 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
const handleGenerate = async () => {
if (!canManage()) return;
+ if (!hasScopeSelection()) {
+ notificationStore.error('Choose a scope preset or custom scope before generating a token.');
+ return;
+ }
setIsGenerating(true);
try {
const trimmedName = nameInput().trim() || undefined;
@@ -313,6 +435,7 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
API_SCOPE_LABELS,
API_TOKEN_SCOPES_DOC_URL,
agentTokenUsage,
+ applyFullAccessPreset,
applyScopePreset,
canManage,
clearScopes,
@@ -325,6 +448,7 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
handleDelete,
handleGenerate,
hasWildcardTokens,
+ hasScopeSelection,
isFullAccessSelected,
isGenerating,
isRevealActiveForCurrentToken,
@@ -347,5 +471,6 @@ export const useAPITokenManagerState = (props: APITokenManagerProps) => {
wildcardCount,
presetMatchesSelection: (presetScopes: string[]) =>
matchesScopePreset(selectedScopes(), presetScopes),
+ canGenerateToken,
};
};
diff --git a/frontend-modern/src/components/Settings/useProLicensePanelState.ts b/frontend-modern/src/components/Settings/useProLicensePanelState.ts
index 928c9c7858..46c7a844c5 100644
--- a/frontend-modern/src/components/Settings/useProLicensePanelState.ts
+++ b/frontend-modern/src/components/Settings/useProLicensePanelState.ts
@@ -8,13 +8,17 @@ import {
licenseEntitlementsLoadError,
loadLicenseEntitlements,
} from '@/stores/licenseEntitlements';
+import {
+ fetchAgentOperationsLoopStatus,
+ type AgentOperationsLoopStatus,
+} from '@/api/agentCapabilities';
import { LicenseAPI } from '@/api/license';
import {
formatLicensePlanVersion,
getSelfHostedActivationSuccessPresentation,
getCommercialMigrationNotice,
getGrandfatheredPriceContinuityNotice,
- getSelfHostedActivationProofPresentation,
+ getSelfHostedPlanStatusPresentation,
getSelfHostedPlanComparisonPresentation,
getSelfHostedCurrentPlanPresentation,
getLicenseFeatureLabel,
@@ -84,11 +88,34 @@ export function useProLicensePanelState() {
const [activationSuccessSource, setActivationSuccessSource] = createSignal<
'manual' | 'purchase' | null
>(null);
+ const [agentOperationsStatus, setAgentOperationsStatus] =
+ createSignal<AgentOperationsLoopStatus | null>(null);
const entitlements = createMemo(() => licenseEntitlements());
const subscriptionState = createMemo(() => entitlements()?.subscription_state);
const trialExpiryUnix = createMemo(() => entitlements()?.trial_expires_at);
const trialDaysRemaining = createMemo(() => entitlements()?.trial_days_remaining);
+ const selfHostedPlanDefinition = createMemo(() =>
+ getSelfHostedPlanDefinitionForBillingTier(entitlements()?.tier),
+ );
+
+ const loadPatrolOperatorStatus = async () => {
+ try {
+ setAgentOperationsStatus(await fetchAgentOperationsLoopStatus());
+ } catch {
+ setAgentOperationsStatus(null);
+ }
+ };
+
+ const shouldLoadPatrolOperatorStatus = () => selfHostedPlanDefinition()?.tier === 'pro';
+
+ const loadPatrolOperatorStatusIfNeeded = async () => {
+ if (!shouldLoadPatrolOperatorStatus()) {
+ setAgentOperationsStatus(null);
+ return;
+ }
+ await loadPatrolOperatorStatus();
+ };
const loadPanelData = async () => {
setLoading(true);
@@ -125,20 +152,18 @@ export function useProLicensePanelState() {
}
if (purchaseResult) {
const nextSearch = params.toString();
- const nextPath = `${location.pathname}${nextSearch ? `?${nextSearch}` : ''}${location.hash ?? ''}`;
+ const nextPath = `${SELF_HOSTED_PRO_BILLING_PLAN_ROUTE}${nextSearch ? `?${nextSearch}` : ''}${location.hash ?? ''}`;
navigate(nextPath, { replace: true, scroll: false });
}
- void loadPanelData();
+ void loadPanelData().then(() => {
+ void loadPatrolOperatorStatusIfNeeded();
+ });
});
const requestedSection = createMemo<SelfHostedBillingSection>(() =>
resolveSelfHostedBillingSection(location.pathname, location.search, location.hash),
);
- const selfHostedPlanDefinition = createMemo(() =>
- getSelfHostedPlanDefinitionForBillingTier(entitlements()?.tier),
- );
-
const activeSection = createMemo<SelfHostedBillingSection>(() => {
return requestedSection() === 'usage' ? 'plan' : requestedSection();
});
@@ -257,10 +282,34 @@ export function useProLicensePanelState() {
}
return getPurchaseActivationNotice(purchaseActivationResult());
});
+ const patrolOperatorStatus = createMemo(() => {
+ const status = agentOperationsStatus();
+ if (!status) {
+ return null;
+ }
+ return {
+ nextAction: status.nextAction,
+ progressLabel: status.progressLabel,
+ patrolControlOperationsLoopStarterCount: status.patrolControlOperationsLoopStarterCount,
+ patrolControlCompletedOperationsLoopCount: status.patrolControlCompletedOperationsLoopCount,
+ patrolControlResolvedOperationsLoopCount: status.patrolControlResolvedOperationsLoopCount,
+ patrolControlValueState: status.patrolControlValueState,
+ patrolAutonomyOperationsLoopStarterCount: status.patrolAutonomyOperationsLoopStarterCount,
+ patrolAutonomyCompletedOperationsLoopCount: status.patrolAutonomyCompletedOperationsLoopCount,
+ patrolAutonomyResolvedOperationsLoopCount: status.patrolAutonomyResolvedOperationsLoopCount,
+ patrolAutonomyValueState: status.patrolAutonomyValueState,
+ proActivationOperationsLoopStarterCount: status.proActivationOperationsLoopStarterCount,
+ proActivationCompletedOperationsLoopCount: status.proActivationCompletedOperationsLoopCount,
+ proActivationResolvedOperationsLoopCount: status.proActivationResolvedOperationsLoopCount,
+ proActivationValueProofState: status.proActivationValueProofState,
+ externalAgentReady: status.externalAgentReady,
+ };
+ });
const activationSuccessSummary = createMemo(() =>
getSelfHostedActivationSuccessPresentation({
entitlements: entitlements(),
displayableCapabilities: formattedFeatures(),
+ patrolOperatorStatus: patrolOperatorStatus(),
source: activationSuccessSource(),
}),
);
@@ -336,6 +385,7 @@ export function useProLicensePanelState() {
const summary = getSelfHostedCurrentPlanPresentation({
entitlements: entitlements(),
displayableCapabilities: formattedFeatures(),
+ patrolOperatorStatus: patrolOperatorStatus(),
});
return {
...summary,
@@ -343,7 +393,7 @@ export function useProLicensePanelState() {
statusLabel: status.label,
};
});
- const activationProof = createMemo(() => getSelfHostedActivationProofPresentation(entitlements()));
+ const planStatus = createMemo(() => getSelfHostedPlanStatusPresentation(entitlements()));
const planComparisonSummary = createMemo(() => {
if (!showPlanSelectionPrompt()) {
return { cards: [], action: null };
@@ -368,7 +418,7 @@ export function useProLicensePanelState() {
const handleActivate = async () => {
const trimmedKey = licenseKey().trim();
if (!trimmedKey) {
- notificationStore.error('A license or activation key is required');
+ notificationStore.error('A license key is required');
return;
}
setActivating(true);
@@ -386,6 +436,7 @@ export function useProLicensePanelState() {
loadCommercialPosture(true),
loadRuntimeCapabilities(true),
]);
+ await loadPatrolOperatorStatusIfNeeded();
} catch (error) {
notificationStore.error(
error instanceof Error ? error.message : 'Failed to activate license',
@@ -409,6 +460,7 @@ export function useProLicensePanelState() {
loadCommercialPosture(true),
loadRuntimeCapabilities(true),
]);
+ await loadPatrolOperatorStatusIfNeeded();
} catch (error) {
notificationStore.error(error instanceof Error ? error.message : 'Failed to clear license');
} finally {
@@ -421,7 +473,7 @@ export function useProLicensePanelState() {
activating,
clearing,
activationSuccessSummary,
- activationProof,
+ planStatus,
commercialMigrationNotice,
commercialPlanModel,
currentPlanSummary,
diff --git a/frontend-modern/src/components/Settings/useSettingsNavigation.ts b/frontend-modern/src/components/Settings/useSettingsNavigation.ts
index 2b89f9446e..7b2d28b303 100644
--- a/frontend-modern/src/components/Settings/useSettingsNavigation.ts
+++ b/frontend-modern/src/components/Settings/useSettingsNavigation.ts
@@ -5,10 +5,16 @@ import {
} from '@/stores/sessionPresentationPolicy';
import { resolveCanonicalSelfHostedBillingHref } from '@/utils/pricingHandoff';
import { buildInfrastructureWorkspacePath } from './infrastructureWorkspaceModel';
+import {
+ EXTERNAL_AGENT_SETUP_PATH,
+ SETTINGS_API_ACCESS_PATH,
+ isExternalAgentSetupHash,
+} from '@/routing/resourceLinks';
import {
DEFAULT_SETTINGS_TAB,
deriveTabFromPath,
deriveTabFromQuery,
+ isAISettingsOAuthCallbackQuery,
resolveCanonicalSettingsPath,
settingsTabPath,
type AgentKey,
@@ -65,9 +71,13 @@ export function useSettingsNavigation({ navigate, location }: UseSettingsNavigat
const queryTab = deriveTabFromQuery(search);
const resolvedTab = queryTab ?? DEFAULT_SETTINGS_TAB;
const target = resolveTabPath(resolvedTab);
+ const shouldPreserveQuery =
+ resolvedTab === 'system-ai' && isAISettingsOAuthCallbackQuery(search);
+ const targetHref = shouldPreserveQuery ? `${target}${search}${hash}` : target;
+ const currentHref = `${path}${search}${hash}`;
- if (target !== path) {
- navigate(target, { replace: true, scroll: false });
+ if (targetHref !== currentHref) {
+ navigate(targetHref, { replace: true, scroll: false });
return;
}
@@ -87,6 +97,14 @@ export function useSettingsNavigation({ navigate, location }: UseSettingsNavigat
return;
}
+ if (path === SETTINGS_API_ACCESS_PATH && isExternalAgentSetupHash(hash)) {
+ navigate(EXTERNAL_AGENT_SETUP_PATH, {
+ replace: true,
+ scroll: false,
+ });
+ return;
+ }
+
if (
sessionPresentationPolicyResolved() &&
presentationPolicyIsReadOnly() &&
diff --git a/frontend-modern/src/components/Workloads/GuestRow.tsx b/frontend-modern/src/components/Workloads/GuestRow.tsx
index fb1ba3598d..b5f8c21ab2 100644
--- a/frontend-modern/src/components/Workloads/GuestRow.tsx
+++ b/frontend-modern/src/components/Workloads/GuestRow.tsx
@@ -353,6 +353,7 @@ export function GuestRow(props: GuestRowProps) {
total={props.guest.memory?.total || 0}
percentOnly={memoryPercentOnly()}
cache={props.guest.memory?.cache || 0}
+ cacheInclusiveLabel="Shown in Proxmox"
balloon={props.guest.memory?.balloon || 0}
swapUsed={props.guest.memory?.swapUsed || 0}
swapTotal={props.guest.memory?.swapTotal || 0}
diff --git a/frontend-modern/src/components/Workloads/__tests__/stackedMemoryBarModel.test.ts b/frontend-modern/src/components/Workloads/__tests__/stackedMemoryBarModel.test.ts
index 4be52779cc..be61885d98 100644
--- a/frontend-modern/src/components/Workloads/__tests__/stackedMemoryBarModel.test.ts
+++ b/frontend-modern/src/components/Workloads/__tests__/stackedMemoryBarModel.test.ts
@@ -5,7 +5,7 @@ import { buildStackedMemoryBarPresentation } from '../stackedMemoryBarModel';
const GiB = 1024 ** 3;
describe('buildStackedMemoryBarPresentation', () => {
- it('renders the v5 used | reclaimable cache split with the Proxmox reconciliation row', () => {
+ it('renders the used | reclaimable cache split with a source-neutral reconciliation row', () => {
const presentation = buildStackedMemoryBarPresentation(
{ used: 4 * GiB, total: 16 * GiB, cache: 6 * GiB },
400,
@@ -23,7 +23,21 @@ describe('buildStackedMemoryBarPresentation', () => {
expect(rows['Reclaimable cache']).toBe('6.00 GB');
// Truly free excludes the reclaimable cache: 16 - 4 - 6.
expect(rows['Free']).toBe('6.00 GB');
- // Proxmox counts cache as used: (4 + 6) / 16.
+ expect(rows['Used with cache']).toBe('63%');
+ });
+
+ it('allows provider-owned surfaces to name the cache-inclusive comparison', () => {
+ const presentation = buildStackedMemoryBarPresentation(
+ {
+ used: 4 * GiB,
+ total: 16 * GiB,
+ cache: 6 * GiB,
+ cacheInclusiveLabel: 'Shown in Proxmox',
+ },
+ 400,
+ );
+
+ const rows = Object.fromEntries(presentation.tooltipRows.map((row) => [row.label, row.value]));
expect(rows['Shown in Proxmox']).toBe('63%');
});
diff --git a/frontend-modern/src/components/Workloads/stackedMemoryBarModel.ts b/frontend-modern/src/components/Workloads/stackedMemoryBarModel.ts
index 30ffa42949..51af923a37 100644
--- a/frontend-modern/src/components/Workloads/stackedMemoryBarModel.ts
+++ b/frontend-modern/src/components/Workloads/stackedMemoryBarModel.ts
@@ -15,6 +15,7 @@ export interface StackedMemoryBarProps {
percentOnly?: number;
/** Reclaimable buff/cache (available - truly free); used + cache + free ≈ total. */
cache?: number;
+ cacheInclusiveLabel?: string;
swapUsed?: number;
swapTotal?: number;
balloon?: number;
@@ -188,12 +189,12 @@ function getTooltipRows(
value: formatBytes(Math.max(0, ceiling - props.used - cache)),
});
- // Proxmox's UI counts reclaimable cache as used; this row explains why
- // Pulse's percentage reads lower than the same guest in Proxmox.
+ // Some providers count reclaimable cache as used; keep the shared default
+ // source-neutral and let provider-owned surfaces name their comparison UI.
if (cache > 0) {
rows.push({
borderTop: true,
- label: 'Shown in Proxmox',
+ label: props.cacheInclusiveLabel ?? 'Used with cache',
labelClass: 'text-slate-500 italic',
value: formatPercent(((props.used + cache) / props.total) * 100),
});
diff --git a/frontend-modern/src/components/__tests__/CommercialMigrationBanner.test.tsx b/frontend-modern/src/components/__tests__/CommercialMigrationBanner.test.tsx
index 79ba43785a..55a3c72461 100644
--- a/frontend-modern/src/components/__tests__/CommercialMigrationBanner.test.tsx
+++ b/frontend-modern/src/components/__tests__/CommercialMigrationBanner.test.tsx
@@ -135,7 +135,7 @@ describe('CommercialMigrationBanner', () => {
fireEvent.click(screen.getByText('Open license settings'));
- expect(navigateMock).toHaveBeenCalledWith('/settings/system/billing/plan');
+ expect(navigateMock).toHaveBeenCalledWith('/settings/pulse-intelligence/billing/plan');
});
/* ---------- Dismiss ---------- */
diff --git a/frontend-modern/src/components/patrol/ApprovalBanner.tsx b/frontend-modern/src/components/patrol/ApprovalBanner.tsx
index e5e0424b2c..4092aa884e 100644
--- a/frontend-modern/src/components/patrol/ApprovalBanner.tsx
+++ b/frontend-modern/src/components/patrol/ApprovalBanner.tsx
@@ -69,9 +69,9 @@ export const ApprovalBanner: Component<ApprovalBannerProps> = (props) => {
setActionLoading(approval.id);
try {
await aiIntelligenceStore.denyInvestigationFix(approval.id);
- notificationStore.success('Fix denied');
+ notificationStore.success('Fix rejected');
} catch (err) {
- notificationStore.error((err as Error).message || 'Failed to deny fix');
+ notificationStore.error((err as Error).message || 'Failed to reject fix');
} finally {
setActionLoading(null);
}
@@ -143,7 +143,7 @@ export const ApprovalBanner: Component<ApprovalBannerProps> = (props) => {
<Show when={actionLoading() !== firstApproval()!.id}>
<CheckIcon class="w-3.5 h-3.5" />
</Show>
- Approve & Execute
+ Approve fix
</Button>
<Button
type="button"
@@ -154,7 +154,7 @@ export const ApprovalBanner: Component<ApprovalBannerProps> = (props) => {
class="gap-1.5"
>
<XIcon class="w-3.5 h-3.5" />
- Deny
+ Reject
</Button>
</Show>
<Show when={pending().length > 1}>
diff --git a/frontend-modern/src/components/patrol/ApprovalSection.tsx b/frontend-modern/src/components/patrol/ApprovalSection.tsx
index c1304ae72d..fb915f944a 100644
--- a/frontend-modern/src/components/patrol/ApprovalSection.tsx
+++ b/frontend-modern/src/components/patrol/ApprovalSection.tsx
@@ -7,7 +7,8 @@
import CheckIcon from 'lucide-solid/icons/check';
import MessageSquareIcon from 'lucide-solid/icons/message-square';
-import { Component, Show, createSignal, createResource, createMemo } from 'solid-js';
+import XIcon from 'lucide-solid/icons/x';
+import { Component, For, Show, createSignal, createResource, createMemo } from 'solid-js';
import { aiIntelligenceStore } from '@/stores/aiIntelligence';
import { notificationStore } from '@/stores/notifications';
import { aiChatStore } from '@/stores/aiChat';
@@ -112,6 +113,7 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
'fix_queued',
'fix_executed',
'fix_failed',
+ 'fix_rejected',
'fix_verified',
'fix_verification_failed',
'fix_verification_unknown',
@@ -164,6 +166,7 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
props.investigationOutcome === 'fix_verification_failed' ||
(executionResult() && !executionResult()!.success),
);
+ const isRejected = createMemo(() => props.investigationOutcome === 'fix_rejected');
// Show section only when there's something to display
const shouldShow = createMemo(
@@ -173,6 +176,7 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
isQueuedWithoutDetails() ||
isExecuted() ||
isFailed() ||
+ isRejected() ||
executionResult(),
);
@@ -203,9 +207,9 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
setActionLoading(approval.id);
try {
await aiIntelligenceStore.denyInvestigationFix(approval.id);
- notificationStore.success('Fix denied');
+ notificationStore.success('Fix rejected');
} catch (err) {
- notificationStore.error((err as Error).message || 'Failed to deny fix');
+ notificationStore.error((err as Error).message || 'Failed to reject fix');
} finally {
setActionLoading(null);
}
@@ -234,6 +238,32 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
}
};
+ const renderTechnicalCommandDetails = (commands: readonly string[] | string | undefined) => {
+ const commandList = Array.isArray(commands)
+ ? commands.filter(Boolean)
+ : commands
+ ? [commands]
+ : [];
+ if (commandList.length === 0) {
+ return null;
+ }
+
+ return (
+ <details class="rounded border border-border bg-surface-alt px-2 py-1.5 text-xs">
+ <summary class="cursor-pointer font-medium text-muted">Technical details</summary>
+ <div class="mt-2 space-y-1">
+ <For each={commandList}>
+ {(command) => (
+ <code class="block break-all rounded bg-surface px-2 py-1 font-mono text-base-content">
+ {command}
+ </code>
+ )}
+ </For>
+ </div>
+ </details>
+ );
+ };
+
const renderRecoveryActions = (assistantLabel: string, onAssistantClick: (e: Event) => void) => (
<div class="flex items-center gap-2 mt-3 pt-3 border-t border-border-subtle">
<Show when={canAutoFix()}>
@@ -251,7 +281,7 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
<Show when={actionLoading() !== 'reapprove'}>
<CheckIcon class="w-3.5 h-3.5" />
</Show>
- Re-approve & Execute
+ Re-approve fix
</Button>
</Show>
<Show when={!canAutoFix()}>
@@ -300,9 +330,10 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
</div>
<div class="space-y-2 text-sm">
<div class="text-muted">{approval.context}</div>
- <div class="bg-surface-alt rounded p-2 font-mono text-xs text-base-content break-all">
- {approval.command}
- </div>
+ <Show when={approval.targetName}>
+ <div class="text-xs text-muted">Target: {approval.targetName}</div>
+ </Show>
+ {renderTechnicalCommandDetails(approval.command)}
</div>
<div class="flex items-center gap-2 mt-3 pt-3 border-t border-border-subtle">
<Show when={canAutoFix()}>
@@ -320,7 +351,7 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
<Show when={actionLoading() !== approval.id}>
<CheckIcon class="w-3.5 h-3.5" />
</Show>
- Approve & Execute
+ Approve fix
</Button>
<Button
type="button"
@@ -330,7 +361,7 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
disabled={actionLoading() === approval.id}
class="text-muted"
>
- Deny
+ Reject
</Button>
</Show>
<Show when={!canAutoFix()}>
@@ -382,14 +413,10 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
</div>
<div class="space-y-2 text-sm">
<div class="text-muted">{fix.description}</div>
- <Show when={fix.commands && fix.commands.length > 0}>
- <div class="bg-surface-alt rounded p-2 font-mono text-xs text-base-content break-all">
- {fix.commands![0]}
- </div>
- </Show>
<Show when={fix.target_host}>
<div class="text-xs text-muted">Target: {fix.target_host}</div>
</Show>
+ {renderTechnicalCommandDetails(fix.commands)}
</div>
{renderRecoveryActions('Fix with Assistant', (e) =>
handleFixWithAssistant(null, fix, e),
@@ -465,20 +492,35 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
{(fix) => (
<div class="mt-2 space-y-1 text-sm">
<div class="text-muted">{fix().description}</div>
- <Show when={fix().commands && fix().commands!.length > 0}>
- <div class="bg-surface-alt rounded p-2 font-mono text-xs text-base-content break-all">
- {fix().commands![0]}
- </div>
- </Show>
<Show when={fix().target_host}>
<div class="text-xs text-muted">Target: {fix().target_host}</div>
</Show>
<Show when={fix().rationale}>
<div class="text-xs text-muted whitespace-pre-line mt-1">{fix().rationale}</div>
</Show>
+ {renderTechnicalCommandDetails(fix().commands)}
+ </div>
+ )}
+ </Show>
+ </Show>
+
+ {/* Rejected by operator */}
+ <Show when={isRejected() && !executionResult()}>
+ <div class="flex items-center gap-2 text-amber-700 dark:text-amber-300">
+ <XIcon class="w-4 h-4" />
+ <span class="text-sm font-medium">Fix rejected before execution</span>
+ </div>
+ <Show when={investigation()?.proposed_fix}>
+ {(fix) => (
+ <div class="mt-2 space-y-1 text-sm">
+ <div class="text-muted">{fix().description}</div>
+ <Show when={fix().target_host}>
+ <div class="text-xs text-muted">Target: {fix().target_host}</div>
+ </Show>
</div>
)}
</Show>
+ {renderRecoveryActions('Discuss with Assistant', handleDiscussQueuedFix)}
</Show>
{/* Failed (from backend state, no local result) */}
@@ -502,17 +544,13 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
{(fix) => (
<div class="mt-2 space-y-1 text-sm">
<div class="text-muted">{fix().description}</div>
- <Show when={fix().commands && fix().commands!.length > 0}>
- <div class="bg-surface-alt rounded p-2 font-mono text-xs text-base-content break-all">
- {fix().commands![0]}
- </div>
- </Show>
<Show when={fix().target_host}>
<div class="text-xs text-muted">Target: {fix().target_host}</div>
</Show>
<Show when={fix().rationale}>
<div class="text-xs text-muted whitespace-pre-line mt-1">{fix().rationale}</div>
</Show>
+ {renderTechnicalCommandDetails(fix().commands)}
</div>
)}
</Show>
diff --git a/frontend-modern/src/components/patrol/InvestigationSection.tsx b/frontend-modern/src/components/patrol/InvestigationSection.tsx
index 03bd3bc97e..e610997859 100644
--- a/frontend-modern/src/components/patrol/InvestigationSection.tsx
+++ b/frontend-modern/src/components/patrol/InvestigationSection.tsx
@@ -96,6 +96,7 @@ export const InvestigationSection: Component<InvestigationSectionProps> = (props
inv.status === 'needs_attention' ||
inv.outcome === 'cannot_fix' ||
inv.outcome === 'timed_out' ||
+ inv.outcome === 'fix_rejected' ||
inv.outcome === 'fix_verification_failed' ||
inv.outcome === 'fix_verification_unknown' ||
inv.outcome === 'fix_failed'
@@ -327,6 +328,7 @@ export const InvestigationSection: Component<InvestigationSectionProps> = (props
(inv().status === 'failed' ||
inv().outcome === 'timed_out' ||
inv().outcome === 'fix_failed' ||
+ inv().outcome === 'fix_rejected' ||
inv().outcome === 'fix_verification_failed' ||
inv().outcome === 'fix_verification_unknown' ||
inv().outcome === 'needs_attention' ||
diff --git a/frontend-modern/src/components/patrol/PatrolStatusBar.tsx b/frontend-modern/src/components/patrol/PatrolStatusBar.tsx
deleted file mode 100644
index 7a73a50527..0000000000
--- a/frontend-modern/src/components/patrol/PatrolStatusBar.tsx
+++ /dev/null
@@ -1,238 +0,0 @@
-/**
- * PatrolStatusBar
- *
- * One-line status bar replacing the Activity tab.
- * Shows: Running status, last run time + trigger, today's run count + new findings.
- */
-
-import { Component, createMemo, createResource, Show } from 'solid-js';
-import {
- getPatrolRunHistory,
- type PatrolRunRecord,
- type PatrolRuntimeState,
- type PatrolTriggerStatus,
-} from '@/api/patrol';
-import { MetadataBadge } from '@/components/shared/MetadataBadge';
-import { StatusIndicatorBadge } from '@/components/shared/StatusIndicatorBadge';
-import { aiIntelligenceStore } from '@/stores/aiIntelligence';
-import { formatRelativeTime } from '@/utils/format';
-import { formatTriggerReason } from '@/utils/patrolFormat';
-import {
- formatPatrolActivityBreakdown,
- getPatrolActivityBreakdown,
- getPatrolTriggerStatusSummary,
- getPatrolRunKindLabel,
- getPatrolRunStatusPresentation,
-} from '@/utils/patrolRunPresentation';
-import { getPatrolRuntimePresentation } from '@/utils/patrolRuntimePresentation';
-import ActivityIcon from 'lucide-solid/icons/activity';
-import AlertCircleIcon from 'lucide-solid/icons/alert-circle';
-import AlertTriangleIcon from 'lucide-solid/icons/alert-triangle';
-
-interface PatrolStatusBarProps {
- enabled?: boolean;
- refreshTrigger?: number;
- runtimeState?: PatrolRuntimeState;
- blockedReason?: string;
- triggerStatus?: PatrolTriggerStatus;
-}
-
-function normalizePatrolRunType(type: string | undefined): string {
- return String(type || '')
- .trim()
- .toLowerCase()
- .replace(/\s+/g, '_');
-}
-
-export const PatrolStatusBar: Component<PatrolStatusBarProps> = (props) => {
- const [runs] = createResource(
- () => props.refreshTrigger ?? 0,
- async (): Promise<PatrolRunRecord[]> => {
- try {
- return await getPatrolRunHistory(100);
- } catch {
- return [];
- }
- },
- );
-
- const stats = createMemo(() => {
- const allRuns = runs() || [];
- if (allRuns.length === 0) return null;
-
- const activityBreakdown = getPatrolActivityBreakdown(allRuns);
-
- const lastRun = allRuns[0];
- const lastRunTime = lastRun ? new Date(lastRun.completed_at || lastRun.started_at) : null;
- const lastRunType = normalizePatrolRunType(lastRun?.type);
- const lastRunStatus = getPatrolRunStatusPresentation(
- lastRun?.status ?? 'unknown',
- lastRun?.error_count ?? 0,
- lastRun?.finding_ids !== undefined,
- );
- return {
- activityBreakdown,
- activityBreakdownLabel: formatPatrolActivityBreakdown(activityBreakdown),
- lastRun,
- runsToday: activityBreakdown.totalRuns,
- newFindingsToday: activityBreakdown.newFindings,
- lastRunTime: lastRunTime ? formatRelativeTime(lastRunTime, { compact: true }) : null,
- lastRunTimeLabel:
- lastRunType === '' || lastRunType === 'full' || lastRunType === 'patrol'
- ? 'Last full patrol'
- : 'Last activity',
- lastRunTrigger: formatTriggerReason(lastRun?.trigger_reason),
- lastRunTypeLabel: getPatrolRunKindLabel(lastRun?.type),
- lastRunStatus,
- lastRunHasFindingsSnapshot: lastRun?.finding_ids !== undefined,
- };
- });
-
- const circuitBreaker = () => aiIntelligenceStore.circuitBreakerStatus;
- const runtimePresentation = createMemo(() =>
- getPatrolRuntimePresentation(props.runtimeState, props.blockedReason),
- );
- const showRuntimeState = createMemo(() => {
- const runtimeState = props.runtimeState;
- return (
- runtimeState === 'blocked' || runtimeState === 'disabled' || runtimeState === 'unavailable'
- );
- });
- const showRunInProgress = createMemo(() => props.runtimeState === 'running');
- const triggerStatusSummary = createMemo(() => getPatrolTriggerStatusSummary(props.triggerStatus));
- const resolvedStats = createMemo(() => (!runs.loading ? stats() : null));
-
- return (
- <Show when={resolvedStats()}>
- <div class="bg-surface rounded-md border border-border px-4 py-2">
- {/* Circuit breaker warning */}
- <Show when={circuitBreaker()?.state === 'open'}>
- <div class="flex items-center gap-1.5 mb-1.5 pb-1.5 border-b border-red-200 dark:border-red-800">
- <AlertTriangleIcon class="w-3.5 h-3.5 text-red-500" />
- <span class="text-red-600 dark:text-red-400 font-medium text-xs">
- Provider circuit breaker tripped — Patrol paused after{' '}
- {circuitBreaker()!.consecutive_failures} consecutive failures
- </span>
- </div>
- </Show>
- <Show when={circuitBreaker()?.state === 'half-open'}>
- <div class="flex items-center gap-1.5 mb-1.5 pb-1.5 border-b border-amber-200 dark:border-amber-800">
- <AlertCircleIcon class="w-3.5 h-3.5 text-amber-500" />
- <span class="text-amber-600 dark:text-amber-400 font-medium text-xs">
- Provider circuit breaker recovering — testing with next patrol run
- </span>
- </div>
- </Show>
- <div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
- {/* Status */}
- <div class="flex items-center gap-1.5">
- <Show
- when={showRuntimeState()}
- fallback={
- <>
- <ActivityIcon class="w-3.5 h-3.5 text-blue-500" />
- <span class="text-blue-600 dark:text-blue-400 font-medium text-xs">
- Recent activity
- </span>
- <Show when={showRunInProgress()}>
- <StatusIndicatorBadge
- label="Run in progress"
- variant="info"
- size="xs"
- shape="rounded"
- />
- </Show>
- </>
- }
- >
- <Show
- when={runtimePresentation().tone === 'warning'}
- fallback={
- <Show
- when={runtimePresentation().tone === 'error'}
- fallback={<AlertCircleIcon class="w-3.5 h-3.5 text-blue-500" />}
- >
- <AlertTriangleIcon class="w-3.5 h-3.5 text-red-500" />
- </Show>
- }
- >
- <AlertTriangleIcon class="w-3.5 h-3.5 text-amber-500" />
- </Show>
- <span
- class={`font-medium text-xs ${
- runtimePresentation().tone === 'warning'
- ? 'text-amber-600 dark:text-amber-400'
- : runtimePresentation().tone === 'error'
- ? 'text-red-600 dark:text-red-400'
- : 'text-blue-600 dark:text-blue-400'
- }`}
- >
- {runtimePresentation().label}
- </span>
- </Show>
- </div>
-
- <span class="hidden sm:inline text-slate-300 ">|</span>
-
- {/* Last run */}
- <Show when={resolvedStats()!.lastRunTime}>
- <span class="text-xs text-muted">
- {resolvedStats()!.lastRunTimeLabel}: {resolvedStats()!.lastRunTime}
- <Show when={resolvedStats()!.lastRunTrigger}>
- <span class=" "> ({resolvedStats()!.lastRunTrigger})</span>
- </Show>
- </span>
- </Show>
-
- <span class="hidden sm:inline text-slate-300 ">|</span>
-
- <Show when={resolvedStats()!.lastRun}>
- <span class="text-xs text-muted">
- Latest: {resolvedStats()!.lastRunTypeLabel} <span class="text-muted">·</span>{' '}
- <StatusIndicatorBadge
- label={resolvedStats()!.lastRunStatus.label}
- variant={resolvedStats()!.lastRunStatus.variant}
- size="xs"
- shape="rounded"
- />
- <Show when={resolvedStats()!.lastRunHasFindingsSnapshot === false}>
- {' '}
- <span class="text-muted">·</span>{' '}
- <MetadataBadge tone="info" size="xs" shape="rounded">
- Findings snapshot unavailable
- </MetadataBadge>
- </Show>
- </span>
- </Show>
-
- <span class="hidden sm:inline text-slate-300 ">|</span>
-
- {/* Today */}
- <span class="text-xs text-muted">
- Today: {resolvedStats()!.runsToday} run{resolvedStats()!.runsToday === 1 ? '' : 's'}
- <Show when={resolvedStats()!.newFindingsToday > 0}>
- <span class="text-amber-600 dark:text-amber-400">
- , {resolvedStats()!.newFindingsToday} new finding
- {resolvedStats()!.newFindingsToday === 1 ? '' : 's'}
- </span>
- </Show>
- </span>
-
- <Show when={resolvedStats()!.activityBreakdownLabel}>
- <span class="hidden sm:inline text-slate-300 ">|</span>
- <span class="text-xs text-muted">
- Recent activity mix: {resolvedStats()!.activityBreakdownLabel}
- </span>
- </Show>
-
- <Show when={triggerStatusSummary()}>
- <span class="hidden sm:inline text-slate-300 ">|</span>
- <span class="text-xs text-muted">Trigger mode: {triggerStatusSummary()}</span>
- </Show>
- </div>
- </div>
- </Show>
- );
-};
-
-export default PatrolStatusBar;
diff --git a/frontend-modern/src/components/patrol/RunHistoryEntry.tsx b/frontend-modern/src/components/patrol/RunHistoryEntry.tsx
index 72de5b3ce9..d9ea3ffd13 100644
--- a/frontend-modern/src/components/patrol/RunHistoryEntry.tsx
+++ b/frontend-modern/src/components/patrol/RunHistoryEntry.tsx
@@ -21,6 +21,7 @@ import {
getPatrolRunCoverageSummary,
getPatrolRunResourcesHeading,
getPatrolRunPrimaryActionPresentation,
+ getPatrolRunOperatorRecordPresentation,
getPatrolRunStatusPresentation,
isPatrolRunHealthy,
} from '@/utils/patrolRunPresentation';
@@ -71,6 +72,7 @@ interface RunHistoryEntryProps {
export function RunHistoryEntry(props: RunHistoryEntryProps) {
const [showRunAnalysis, setShowRunAnalysis] = createSignal(true);
+ const [showTechnicalDetails, setShowTechnicalDetails] = createSignal(false);
// Live in-progress entry
if (props.isLive) {
@@ -151,8 +153,6 @@ export function RunHistoryEntry(props: RunHistoryEntryProps) {
// Completed run entry
const run = props.run;
- const scopeSummary = formatScope(run);
- const duration = formatDurationMs(run.duration_ms);
const canonicalScopeResourceIds = getCanonicalScopeResourceIds(run);
const runIsHealthy = isPatrolRunHealthy(run.status, run.error_count);
const coverageSummary = getPatrolRunCoverageSummary(run);
@@ -162,6 +162,7 @@ export function RunHistoryEntry(props: RunHistoryEntryProps) {
run.error_count,
hasFindingsSnapshot,
);
+ const operatorRecord = getPatrolRunOperatorRecordPresentation(run);
const runErrorSummary = formatPatrolRuntimeFailureDetail(run.error_summary);
const runErrorDetail = formatPatrolRuntimeFailureDetail(run.error_detail);
const hasRunErrorDetail = run.error_count > 0 && (runErrorSummary || runErrorDetail);
@@ -185,37 +186,20 @@ export function RunHistoryEntry(props: RunHistoryEntryProps) {
onClick={() => props.onSelect(props.selected ? null : run)}
class={`w-full text-left px-3 py-2 rounded-md transition-colors ${!props.selected ? 'hover:bg-surface-hover' : ''}`}
>
- <div class="flex flex-wrap items-center gap-2 text-xs text-muted">
- <span class="text-base-content font-medium">
- {formatRelativeTime(run.started_at, { compact: true })}
- </span>
- <StatusIndicatorBadge
- label={runStatus.label}
- variant={runStatus.variant}
- size="xs"
- shape="rounded"
- />
- <span>{formatTriggerReason(run.trigger_reason)}</span>
- <Show when={scopeSummary && !coverageSummary}>
- <span>• {scopeSummary}</span>
- </Show>
- <Show when={duration}>
- <span>• {duration}</span>
- </Show>
- <Show when={coverageSummary}>
- <span>• {coverageSummary}</span>
- </Show>
- <Show when={run.new_findings}>
- <span>• {run.new_findings} new</span>
- </Show>
- <Show when={run.rejected_findings}>
- <span class="text-muted">• {run.rejected_findings} rejected</span>
- </Show>
- <Show
- when={!hasFindingsSnapshot && run.new_findings === 0 && run.existing_findings === 0}
- >
- <span class="text-blue-600 dark:text-blue-400">• Findings snapshot unavailable</span>
- </Show>
+ <div class="min-w-0">
+ <div class="flex flex-wrap items-center gap-2 text-xs text-muted">
+ <span class="text-base-content font-medium">
+ {formatRelativeTime(run.started_at, { compact: true })}
+ </span>
+ <StatusIndicatorBadge
+ label={runStatus.label}
+ variant={runStatus.variant}
+ size="xs"
+ shape="rounded"
+ />
+ <span class="font-medium text-base-content">{operatorRecord.headline}</span>
+ </div>
+ <p class="mt-1 text-xs leading-5 text-muted">{operatorRecord.detail}</p>
</div>
</button>
@@ -227,70 +211,7 @@ export function RunHistoryEntry(props: RunHistoryEntryProps) {
<div class="flex min-w-0 flex-1 items-start gap-2 text-sm text-base-content">
<SparklesIcon class="w-4 h-4 text-blue-500 dark:text-blue-400 mt-0.5 flex-shrink-0" />
<p>
- {coverageSummary ? (
- <>
- {coverageSummary}{' '}
- {formatDurationMs(run.duration_ms) ? (
- <>
- in <strong>{formatDurationMs(run.duration_ms)}</strong>
- </>
- ) : (
- ''
- )}{' '}
- {run.tool_call_count > 0 ? (
- <>
- using <strong>{run.tool_call_count}</strong> tool call
- {run.tool_call_count !== 1 ? 's' : ''}
- </>
- ) : (
- ''
- )}
- .{' '}
- </>
- ) : (
- <>
- Patrol completed
- {formatDurationMs(run.duration_ms) ? (
- <>
- {' '}
- in <strong>{formatDurationMs(run.duration_ms)}</strong>
- </>
- ) : (
- ''
- )}
- .{' '}
- </>
- )}
- {run.new_findings > 0 ? (
- <>
- Found <strong>{run.new_findings}</strong> new issue
- {run.new_findings !== 1 ? 's' : ''}
- {run.auto_fix_count > 0 ? (
- <>
- , remediated <strong>{run.auto_fix_count}</strong>
- </>
- ) : (
- ''
- )}
- .
- </>
- ) : run.existing_findings > 0 ? (
- <>
- No new issues, but <strong>{run.existing_findings}</strong> existing issue
- {run.existing_findings !== 1 ? 's remain' : ' remains'}.
- </>
- ) : !hasFindingsSnapshot ? (
- <span class="text-blue-600 dark:text-blue-400">
- This run predates findings snapshots, so run-specific findings cannot be fully
- verified.
- </span>
- ) : runIsHealthy ? (
- <span class="text-green-600 dark:text-green-400">All clear — no new issues.</span>
- ) : (
- <span class="text-amber-600 dark:text-amber-400">
- Patrol completed with issues requiring review.
- </span>
- )}
+ <strong>{operatorRecord.headline}.</strong> {operatorRecord.detail}
</p>
</div>
<button
@@ -432,7 +353,7 @@ export function RunHistoryEntry(props: RunHistoryEntryProps) {
when={!hasFindingsSnapshot && run.new_findings === 0 && run.existing_findings === 0}
>
<MetadataBadge tone="info">
- <ActivityIcon class="w-3 h-3" /> Snapshot unavailable
+ <ActivityIcon class="w-3 h-3" /> Finding record unavailable
</MetadataBadge>
</Show>
<Show
@@ -450,44 +371,7 @@ export function RunHistoryEntry(props: RunHistoryEntryProps) {
</div>
</div>
- {/* Section 4: AI Effort Bar */}
- <div class="mt-3 flex flex-wrap items-center gap-3 px-3 py-2 rounded-md bg-surface-alt text-xs text-muted">
- <Show when={formatDurationMs(run.duration_ms)}>
- <span class="inline-flex items-center gap-1">
- <ClockIcon class="w-3.5 h-3.5" /> {formatDurationMs(run.duration_ms)}
- </span>
- </Show>
- <Show when={run.tool_call_count > 0}>
- <span class="inline-flex items-center gap-1">
- <ZapIcon class="w-3.5 h-3.5" /> {run.tool_call_count} tool call
- {run.tool_call_count !== 1 ? 's' : ''}
- </span>
- </Show>
- <Show when={run.triage_flags > 0}>
- <span class="inline-flex items-center gap-1">
- <ShieldAlertIcon class="w-3.5 h-3.5" /> {run.triage_flags} triage flag
- {run.triage_flags !== 1 ? 's' : ''}
- </span>
- </Show>
- <Show when={run.triage_skipped_llm}>
- <span class="inline-flex items-center gap-1 text-amber-700 dark:text-amber-300">
- <BrainCircuitIcon class="w-3.5 h-3.5" /> LLM skipped
- </span>
- </Show>
- <Show when={(run.input_tokens || 0) + (run.output_tokens || 0) > 0}>
- <span class="inline-flex items-center gap-1">
- <BrainCircuitIcon class="w-3.5 h-3.5" />{' '}
- {((run.input_tokens || 0) + (run.output_tokens || 0)).toLocaleString()} tokens
- </span>
- </Show>
- <Show when={run.type === 'scoped' && !coverageSummary}>
- <MetadataBadge tone="info" size="xs" shape="rounded">
- {formatScope(run) || 'Scoped'}
- </MetadataBadge>
- </Show>
- </div>
-
- {/* Section 5: Patrol Analysis */}
+ {/* Section 4: Patrol Analysis */}
<Show when={run.ai_analysis}>
<div class="mt-3">
<div class="flex items-center justify-between">
@@ -515,10 +399,58 @@ export function RunHistoryEntry(props: RunHistoryEntryProps) {
</div>
</Show>
- {/* Section 6: Tool Call Trace */}
- <RunToolCallTrace runId={run.id} toolCallCount={run.tool_call_count} />
+ {/* Technical run trace: useful for debugging, hidden from the default operator record. */}
+ <details
+ class="mt-3 rounded-md border border-border bg-surface-alt px-3 py-2 text-xs text-muted"
+ onToggle={(event) => setShowTechnicalDetails(event.currentTarget.open)}
+ >
+ <summary class="cursor-pointer font-medium text-base-content">
+ Technical details
+ </summary>
+ <div class="mt-2 flex flex-wrap items-center gap-3">
+ <Show when={formatDurationMs(run.duration_ms)}>
+ <span class="inline-flex items-center gap-1">
+ <ClockIcon class="w-3.5 h-3.5" /> {formatDurationMs(run.duration_ms)}
+ </span>
+ </Show>
+ <Show when={run.tool_call_count > 0}>
+ <span class="inline-flex items-center gap-1">
+ <ZapIcon class="w-3.5 h-3.5" /> {run.tool_call_count} tool call
+ {run.tool_call_count !== 1 ? 's' : ''}
+ </span>
+ </Show>
+ <Show when={run.triage_flags > 0}>
+ <span class="inline-flex items-center gap-1">
+ <ShieldAlertIcon class="w-3.5 h-3.5" /> {run.triage_flags} triage flag
+ {run.triage_flags !== 1 ? 's' : ''}
+ </span>
+ </Show>
+ <Show when={run.triage_skipped_llm}>
+ <span class="inline-flex items-center gap-1 text-amber-700 dark:text-amber-300">
+ <BrainCircuitIcon class="w-3.5 h-3.5" /> LLM skipped
+ </span>
+ </Show>
+ <Show when={(run.input_tokens || 0) + (run.output_tokens || 0) > 0}>
+ <span class="inline-flex items-center gap-1">
+ <BrainCircuitIcon class="w-3.5 h-3.5" />{' '}
+ {((run.input_tokens || 0) + (run.output_tokens || 0)).toLocaleString()} tokens
+ </span>
+ </Show>
+ <Show when={run.type === 'scoped' && !coverageSummary}>
+ <MetadataBadge tone="info" size="xs" shape="rounded">
+ {formatScope(run) || 'Scoped'}
+ </MetadataBadge>
+ </Show>
+ <Show when={formatTriggerReason(run.trigger_reason)}>
+ <span>{formatTriggerReason(run.trigger_reason)}</span>
+ </Show>
+ </div>
+ <Show when={showTechnicalDetails()}>
+ <RunToolCallTrace runId={run.id} toolCallCount={run.tool_call_count} />
+ </Show>
+ </details>
- {/* Section 7: Inline Findings */}
+ {/* Section 5: Inline Findings */}
<div class="mt-3 pt-3 border-t border-blue-200 dark:border-blue-800">
<FindingsPanel
filterFindingIds={run.finding_ids}
diff --git a/frontend-modern/src/components/patrol/RunHistoryPanel.tsx b/frontend-modern/src/components/patrol/RunHistoryPanel.tsx
index b9f57557cb..246b4b8ca0 100644
--- a/frontend-modern/src/components/patrol/RunHistoryPanel.tsx
+++ b/frontend-modern/src/components/patrol/RunHistoryPanel.tsx
@@ -1,4 +1,4 @@
-import { For, Show } from 'solid-js';
+import { createMemo, createSignal, For, Show } from 'solid-js';
import type { Accessor } from 'solid-js';
import type { PatrolRunRecord } from '@/api/patrol';
import { EmptyState } from '@/components/shared/EmptyState';
@@ -11,6 +11,8 @@ import { RunHistoryEntry } from './RunHistoryEntry';
import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';
+const INITIAL_VISIBLE_RUN_HISTORY_COUNT = 8;
+
interface PatrolStreamState {
phase: Accessor<string>;
currentTool: Accessor<string>;
@@ -34,22 +36,25 @@ interface RunHistoryPanelProps {
}
export function RunHistoryPanel(props: RunHistoryPanelProps) {
+ const [showOlderRuns, setShowOlderRuns] = createSignal(false);
+ const visibleRuns = createMemo(() =>
+ showOlderRuns() ? props.runs : props.runs.slice(0, INITIAL_VISIBLE_RUN_HISTORY_COUNT),
+ );
+ const hiddenRunCount = createMemo(() => Math.max(props.runs.length - visibleRuns().length, 0));
+
return (
<div class="bg-surface rounded-md border border-border p-4">
- <div class="flex items-center justify-between mb-4">
- <div>
- <h2 class="text-sm font-semibold text-base-content">Recent patrol runs</h2>
- <p class="text-xs text-muted">
- {getRunHistorySelectionHint(props.runs, props.selectedRun)}
- </p>
- </div>
+ <div class="mb-4 flex items-center justify-between gap-3">
+ <p class="min-w-0 text-xs text-muted">
+ {getRunHistorySelectionHint(props.runs, props.selectedRun)}
+ </p>
<Show when={props.selectedRun}>
<button
type="button"
onClick={() => props.onSelectRun(null)}
- class="text-xs font-medium text-blue-600 dark:text-blue-400 hover:underline"
+ class="shrink-0 text-xs font-medium text-blue-600 hover:underline dark:text-blue-400"
>
- Clear filter
+ Show all runs
</button>
</Show>
</div>
@@ -67,18 +72,35 @@ export function RunHistoryPanel(props: RunHistoryPanelProps) {
</Show>
<Show when={!props.loading && props.runs.length > 0}>
- <div class="space-y-2">
- <For each={props.runs}>
- {(run) => (
- <RunHistoryEntry
- run={run}
- isLive={run.id === '__live__'}
- patrolStream={props.patrolStream}
- selected={props.selectedRun?.id === run.id}
- onSelect={props.onSelectRun}
- />
- )}
- </For>
+ <div class="space-y-3">
+ <div class="max-h-[28rem] space-y-2 overflow-y-auto pr-1">
+ <For each={visibleRuns()}>
+ {(run) => (
+ <RunHistoryEntry
+ run={run}
+ isLive={run.id === '__live__'}
+ patrolStream={props.patrolStream}
+ selected={props.selectedRun?.id === run.id}
+ onSelect={props.onSelectRun}
+ />
+ )}
+ </For>
+ </div>
+
+ <Show when={props.runs.length > INITIAL_VISIBLE_RUN_HISTORY_COUNT}>
+ <button
+ type="button"
+ onClick={() => setShowOlderRuns((expanded) => !expanded)}
+ class="w-full rounded-md border border-border-subtle bg-surface-alt px-3 py-2 text-xs font-medium text-muted transition-colors hover:bg-surface-hover hover:text-base-content"
+ >
+ <Show
+ when={!showOlderRuns()}
+ fallback={`Show recent ${INITIAL_VISIBLE_RUN_HISTORY_COUNT} runs`}
+ >
+ Show {hiddenRunCount()} older runs
+ </Show>
+ </button>
+ </Show>
</div>
</Show>
</div>
diff --git a/frontend-modern/src/components/patrol/__tests__/ApprovalBanner.test.tsx b/frontend-modern/src/components/patrol/__tests__/ApprovalBanner.test.tsx
index eae8661ec3..b1d7aa07a4 100644
--- a/frontend-modern/src/components/patrol/__tests__/ApprovalBanner.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/ApprovalBanner.test.tsx
@@ -66,6 +66,17 @@ describe('ApprovalBanner', () => {
expect(approvalBannerSource).not.toContain('px-3 py-1.5 bg-amber-600 hover:bg-amber-700');
});
+ it('uses governed decision wording for a single approval', () => {
+ state.pendingApprovals = [approvalRequest()];
+
+ render(() => <ApprovalBanner />);
+
+ expect(screen.getByRole('button', { name: 'Approve fix' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Reject' })).toBeInTheDocument();
+ expect(screen.queryByText('Approve & Execute')).not.toBeInTheDocument();
+ expect(screen.queryByText('Deny')).not.toBeInTheDocument();
+ });
+
it('reviews the first approval-linked finding in canonical urgency order', () => {
state.pendingApprovals = [
{
diff --git a/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx b/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx
index 7d2e6b3b91..628fd2f4e4 100644
--- a/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/ApprovalSection.test.tsx
@@ -107,10 +107,47 @@ describe('ApprovalSection', () => {
);
});
+ it('demotes raw commands behind technical details instead of making them the approval body', () => {
+ expect(approvalSectionSource).toContain('renderTechnicalCommandDetails');
+ expect(approvalSectionSource).toContain('Technical details');
+ expect(approvalSectionSource).toContain('{renderTechnicalCommandDetails(approval.command)}');
+ expect(approvalSectionSource).toContain('{renderTechnicalCommandDetails(fix.commands)}');
+ expect(approvalSectionSource).toContain('{renderTechnicalCommandDetails(fix().commands)}');
+ expect(approvalSectionSource).not.toContain('{approval.command}</div>');
+ expect(approvalSectionSource).not.toContain('{fix.commands![0]}</div>');
+ expect(approvalSectionSource).not.toContain('{fix().commands![0]}</div>');
+ });
+
afterEach(() => {
cleanup();
});
+ it('uses governed decision wording for live approvals', async () => {
+ state.hasAutoFix = true;
+ state.pendingApprovals = [
+ {
+ id: 'approval-1',
+ toolId: 'investigation_fix',
+ command: 'systemctl restart nginx',
+ targetType: 'investigation',
+ targetId: 'finding-1',
+ targetName: 'node-1',
+ context: 'Restart the workload service',
+ riskLevel: 'high',
+ status: 'pending',
+ requestedAt: new Date().toISOString(),
+ expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(),
+ },
+ ];
+
+ render(() => <ApprovalSection findingId="finding-1" investigationOutcome="fix_queued" />);
+
+ expect(await screen.findByRole('button', { name: /approve fix/i })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /reject/i })).toBeInTheDocument();
+ expect(screen.queryByText(/approve & execute/i)).not.toBeInTheDocument();
+ expect(screen.queryByText(/^deny$/i)).not.toBeInTheDocument();
+ });
+
it('keeps fix approvals out of commercial trial prompts', () => {
expect(approvalSectionSource).not.toContain('canStartCommercialTrial');
expect(approvalSectionSource).not.toContain('runStartProTrialAction');
@@ -371,8 +408,8 @@ describe('ApprovalSection', () => {
render(() => <ApprovalSection findingId="finding-2" investigationOutcome="fix_queued" />);
- expect(await screen.findAllByRole('button', { name: /re-approve & execute/i })).toHaveLength(1);
- fireEvent.click(screen.getByRole('button', { name: /re-approve & execute/i }));
+ expect(await screen.findAllByRole('button', { name: /re-approve fix/i })).toHaveLength(1);
+ fireEvent.click(screen.getByRole('button', { name: /re-approve fix/i }));
await waitFor(() => {
expect(reapproveInvestigationFixMock).toHaveBeenCalledWith('finding-2');
diff --git a/frontend-modern/src/components/patrol/__tests__/PatrolStatusBar.test.tsx b/frontend-modern/src/components/patrol/__tests__/PatrolStatusBar.test.tsx
deleted file mode 100644
index aa9881c113..0000000000
--- a/frontend-modern/src/components/patrol/__tests__/PatrolStatusBar.test.tsx
+++ /dev/null
@@ -1,541 +0,0 @@
-import { createSignal } from 'solid-js';
-import { cleanup, render, screen, waitFor, within } from '@solidjs/testing-library';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import type { PatrolRunRecord, PatrolTriggerStatus } from '@/api/patrol';
-import { PatrolStatusBar } from '../PatrolStatusBar';
-
-const getPatrolRunHistoryMock = vi.hoisted(() => vi.fn<() => Promise<PatrolRunRecord[]>>());
-
-vi.mock('@/api/patrol', () => ({
- getPatrolRunHistory: getPatrolRunHistoryMock,
-}));
-
-vi.mock('@/stores/aiIntelligence', () => ({
- aiIntelligenceStore: {
- circuitBreakerStatus: null,
- },
-}));
-
-describe('PatrolStatusBar', () => {
- beforeEach(() => {
- getPatrolRunHistoryMock.mockReset();
- });
-
- afterEach(() => {
- cleanup();
- });
-
- it('shows recent activity instead of a healthy verdict for healthy patrol runs', async () => {
- getPatrolRunHistoryMock.mockResolvedValue([
- {
- id: 'run-healthy',
- started_at: '2026-03-12T10:00:00Z',
- completed_at: '2026-03-12T10: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,
- auto_fix_count: 0,
- findings_summary: 'All clear',
- finding_ids: [],
- error_count: 0,
- status: 'healthy',
- triage_flags: 0,
- tool_call_count: 0,
- },
- ]);
-
- render(() => <PatrolStatusBar refreshTrigger={1} />);
-
- await waitFor(() => {
- expect(screen.getByText('Recent activity')).toBeInTheDocument();
- });
-
- expect(screen.getByText('Latest: Full patrol')).toBeInTheDocument();
- expect(screen.getByText('healthy')).toBeInTheDocument();
- });
-
- it('flags latest runs whose findings snapshot is unavailable', async () => {
- getPatrolRunHistoryMock.mockResolvedValue([
- {
- id: 'run-legacy-healthy',
- started_at: '2026-03-12T10:00:00Z',
- completed_at: '2026-03-12T10: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,
- auto_fix_count: 0,
- findings_summary: 'All clear',
- finding_ids: undefined,
- error_count: 0,
- status: 'healthy',
- triage_flags: 0,
- tool_call_count: 0,
- },
- ]);
-
- render(() => <PatrolStatusBar refreshTrigger={1} />);
-
- await waitFor(() => {
- expect(screen.getByText('Recent activity')).toBeInTheDocument();
- });
-
- const latestRunSection = screen.getByText('Latest: Full patrol').closest('span');
- expect(latestRunSection).not.toBeNull();
- expect(latestRunSection).toHaveTextContent(
- 'Latest: Full patrol · completed · Findings snapshot unavailable',
- );
- });
-
- it('shows patrol paused when the runtime is blocked even if the last run was healthy', async () => {
- getPatrolRunHistoryMock.mockResolvedValue([
- {
- id: 'run-healthy',
- started_at: '2026-03-12T10:00:00Z',
- completed_at: '2026-03-12T10: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,
- auto_fix_count: 0,
- findings_summary: 'All clear',
- finding_ids: [],
- error_count: 0,
- status: 'healthy',
- triage_flags: 0,
- tool_call_count: 0,
- },
- ]);
-
- render(() => (
- <PatrolStatusBar
- refreshTrigger={1}
- runtimeState="blocked"
- blockedReason="Quickstart credits exhausted. Connect your API key to continue using Patrol."
- />
- ));
-
- await waitFor(() => {
- expect(screen.getByText('Patrol Paused')).toBeInTheDocument();
- });
-
- expect(screen.queryByText('Recent activity')).not.toBeInTheDocument();
- });
-
- it('shows the latest full-patrol result when the last patrol run found issues', async () => {
- getPatrolRunHistoryMock.mockResolvedValue([
- {
- id: 'run-critical',
- started_at: '2026-03-12T10:00:00Z',
- completed_at: '2026-03-12T10: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: 1,
- existing_findings: 0,
- rejected_findings: 0,
- resolved_findings: 0,
- auto_fix_count: 0,
- findings_summary: 'Critical issue detected',
- finding_ids: ['finding-1'],
- error_count: 0,
- status: 'critical',
- triage_flags: 0,
- tool_call_count: 0,
- },
- ]);
-
- render(() => <PatrolStatusBar refreshTrigger={1} />);
-
- await waitFor(() => {
- expect(screen.getByText('Recent activity')).toBeInTheDocument();
- });
-
- expect(screen.getByText('Latest: Full patrol')).toBeInTheDocument();
- expect(screen.getByText('critical')).toBeInTheDocument();
- });
-
- it('shows scoped/erroring activity factually instead of a healthy summary', async () => {
- getPatrolRunHistoryMock.mockResolvedValue([
- {
- id: 'run-error-count',
- started_at: '2026-03-12T10:00:00Z',
- completed_at: '2026-03-12T10:01:00Z',
- duration_ms: 60000,
- type: 'scoped',
- trigger_reason: 'alert_fired',
- 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,
- auto_fix_count: 0,
- findings_summary: 'Run completed with errors',
- finding_ids: [],
- error_count: 2,
- status: 'healthy',
- triage_flags: 0,
- tool_call_count: 0,
- },
- ]);
-
- render(() => <PatrolStatusBar refreshTrigger={1} />);
-
- await waitFor(() => {
- expect(screen.getByText('Recent activity')).toBeInTheDocument();
- });
-
- const latestRunSection = screen.getByText('Latest: Scoped run').closest('span');
- expect(latestRunSection).not.toBeNull();
- expect(latestRunSection).toHaveTextContent('Latest: Scoped run · error');
- expect(within(latestRunSection as HTMLElement).queryByText('healthy')).not.toBeInTheDocument();
- expect(within(latestRunSection as HTMLElement).getByText('error')).toBeInTheDocument();
- });
-
- it('keeps running patrols factual with a run-in-progress indicator', async () => {
- getPatrolRunHistoryMock.mockResolvedValue([
- {
- id: 'run-startup',
- started_at: '2026-03-12T10:00:00Z',
- completed_at: '2026-03-12T10:01:00Z',
- duration_ms: 60000,
- type: 'patrol',
- trigger_reason: 'startup',
- resources_checked: 57,
- 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,
- auto_fix_count: 0,
- findings_summary: 'Completed with errors',
- finding_ids: [],
- error_count: 1,
- status: 'error',
- triage_flags: 0,
- tool_call_count: 0,
- },
- ]);
-
- render(() => <PatrolStatusBar refreshTrigger={1} runtimeState="running" />);
-
- await waitFor(() => {
- expect(screen.getByText('Recent activity')).toBeInTheDocument();
- });
-
- expect(screen.getByText('Run in progress')).toBeInTheDocument();
- expect(screen.queryByText('Patrol Running')).not.toBeInTheDocument();
- });
-
- it('shows a same-day activity breakdown and scoped trigger state when Patrol is noisy', async () => {
- const referenceDay = new Date();
- const atTime = (hour: number, minute: number) =>
- new Date(
- referenceDay.getFullYear(),
- referenceDay.getMonth(),
- referenceDay.getDate(),
- hour,
- minute,
- 0,
- ).toISOString();
-
- getPatrolRunHistoryMock.mockResolvedValue([
- {
- id: 'run-alert',
- started_at: atTime(10, 0),
- completed_at: atTime(10, 1),
- duration_ms: 60000,
- type: 'scoped',
- trigger_reason: 'alert_fired',
- 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,
- auto_fix_count: 0,
- findings_summary: 'ok',
- finding_ids: [],
- error_count: 0,
- status: 'healthy',
- triage_flags: 0,
- tool_call_count: 0,
- },
- {
- id: 'run-anomaly',
- started_at: atTime(9, 0),
- completed_at: atTime(9, 1),
- duration_ms: 60000,
- type: 'scoped',
- trigger_reason: 'anomaly',
- 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,
- auto_fix_count: 0,
- findings_summary: 'ok',
- finding_ids: [],
- error_count: 0,
- status: 'healthy',
- triage_flags: 0,
- tool_call_count: 0,
- },
- {
- id: 'run-full',
- started_at: atTime(8, 0),
- completed_at: atTime(8, 5),
- duration_ms: 300000,
- type: 'patrol',
- resources_checked: 58,
- 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,
- auto_fix_count: 0,
- findings_summary: 'ok',
- finding_ids: [],
- error_count: 0,
- status: 'healthy',
- triage_flags: 0,
- tool_call_count: 0,
- },
- ]);
-
- render(() => (
- <PatrolStatusBar
- refreshTrigger={1}
- triggerStatus={{
- running: true,
- pending_triggers: 4,
- current_interval_ms: 300000,
- recent_events: 6,
- is_busy_mode: true,
- alert_triggers_enabled: true,
- anomaly_triggers_enabled: false,
- }}
- />
- ));
-
- await waitFor(() => {
- expect(
- screen.getByText('Recent activity mix: 1 full, 1 alert-triggered, 1 anomaly-triggered'),
- ).toBeInTheDocument();
- });
-
- expect(
- screen.getByText('Trigger mode: 4 queued · busy mode · anomalies off'),
- ).toBeInTheDocument();
- });
-
- it('surfaces runtime-blocked event triggers in the activity bar', async () => {
- getPatrolRunHistoryMock.mockResolvedValue([
- {
- id: 'run-latest',
- started_at: '2026-03-12T10:00:00Z',
- completed_at: '2026-03-12T10: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,
- auto_fix_count: 0,
- findings_summary: 'ok',
- finding_ids: [],
- error_count: 0,
- status: 'healthy',
- triage_flags: 0,
- tool_call_count: 0,
- },
- ]);
-
- render(() => (
- <PatrolStatusBar
- refreshTrigger={1}
- triggerStatus={{
- running: true,
- pending_triggers: 0,
- current_interval_ms: 300000,
- recent_events: 0,
- is_busy_mode: false,
- alert_triggers_enabled: true,
- anomaly_triggers_enabled: true,
- 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.',
- }}
- />
- ));
-
- await waitFor(() => {
- expect(
- screen.getByText(
- 'Trigger mode: Automatic Patrol checks from alerts and anomalies are paused by the local development safety guard. Manual Patrol still works.',
- ),
- ).toBeInTheDocument();
- });
- });
-
- it('updates scoped trigger status when trigger data arrives after the initial render', async () => {
- getPatrolRunHistoryMock.mockResolvedValue([
- {
- id: 'run-busy-scoped',
- started_at: '2026-03-12T10:00:00Z',
- completed_at: '2026-03-12T10:01:00Z',
- duration_ms: 60000,
- type: 'scoped',
- trigger_reason: 'alert_fired',
- 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,
- auto_fix_count: 0,
- findings_summary: 'ok',
- finding_ids: [],
- error_count: 0,
- status: 'healthy',
- triage_flags: 0,
- tool_call_count: 0,
- },
- ]);
-
- const [triggerStatus, setTriggerStatus] = createSignal<PatrolTriggerStatus | undefined>(
- undefined,
- );
-
- render(() => <PatrolStatusBar refreshTrigger={1} triggerStatus={triggerStatus()} />);
-
- await waitFor(() => {
- expect(screen.getByText('Recent activity')).toBeInTheDocument();
- });
-
- expect(screen.queryByText(/Trigger mode:/)).not.toBeInTheDocument();
-
- setTriggerStatus({
- running: true,
- pending_triggers: 4,
- current_interval_ms: 300000,
- recent_events: 6,
- is_busy_mode: true,
- alert_triggers_enabled: true,
- anomaly_triggers_enabled: false,
- });
-
- await waitFor(() => {
- expect(
- screen.getByText('Trigger mode: 4 queued · busy mode · anomalies off'),
- ).toBeInTheDocument();
- });
- });
-});
diff --git a/frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx b/frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx
index 02c988b002..b318537bfa 100644
--- a/frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/RunHistoryEntry.test.tsx
@@ -1,6 +1,7 @@
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { PatrolRunRecord } from '@/api/patrol';
+import runHistoryEntrySource from '../RunHistoryEntry.tsx?raw';
import { RunHistoryEntry } from '../RunHistoryEntry';
const { findingsPanelState, openMock } = vi.hoisted(() => ({
@@ -142,7 +143,7 @@ describe('RunHistoryEntry', () => {
/>
));
- expect(screen.getByText('• Findings snapshot unavailable')).toBeInTheDocument();
+ expect(screen.getByText('Completed check')).toBeInTheDocument();
expect(screen.getByText('completed')).toBeInTheDocument();
expect(screen.getByTestId('findings-panel')).toBeInTheDocument();
expect(findingsPanelState.latestProps).toMatchObject({
@@ -160,11 +161,13 @@ describe('RunHistoryEntry', () => {
},
});
expect(
- screen.getByText(
- 'This run predates findings snapshots, so run-specific findings cannot be fully verified.',
- ),
- ).toBeInTheDocument();
- expect(screen.getByText('Snapshot unavailable')).toBeInTheDocument();
+ screen.getAllByText(
+ (_, element) =>
+ element?.tagName === 'P' &&
+ (element.textContent?.includes('This older run has no issue list.') ?? false),
+ ).length,
+ ).toBeGreaterThan(0);
+ expect(screen.getByText('Finding record unavailable')).toBeInTheDocument();
expect(screen.queryByText('All clear — no new issues.')).not.toBeInTheDocument();
expect(screen.queryByText(/^All clear$/)).not.toBeInTheDocument();
expect(screen.queryByText('healthy')).not.toBeInTheDocument();
@@ -190,20 +193,25 @@ describe('RunHistoryEntry', () => {
/>
));
- expect(screen.getByText('• Checked 1 of 2 scoped resources')).toBeInTheDocument();
+ expect(screen.getByText('Patrol needs attention')).toBeInTheDocument();
+ expect(
+ screen.getAllByText(
+ 'Checked 1 of 2 scoped resources in 453ms. Runtime issue: 1 Patrol runtime error recorded.',
+ ).length,
+ ).toBeGreaterThan(0);
expect(screen.getByText('Resources checked (1 of 2 scoped)')).toBeInTheDocument();
expect(screen.queryByText('• 1 resources')).not.toBeInTheDocument();
expect(screen.queryByText('Scoped to 2 resources')).not.toBeInTheDocument();
expect(
- screen.getByText(
+ screen.getAllByText(
(_, element) =>
element?.tagName === 'P' &&
(element.textContent?.includes('Checked 1 of 2 scoped resources') ?? false) &&
(element.textContent?.includes('453ms') ?? false) &&
- (element.textContent?.includes('Patrol completed with issues requiring review.') ??
+ (element.textContent?.includes('Runtime issue: 1 Patrol runtime error recorded.') ??
false),
- ),
- ).toBeInTheDocument();
+ ).length,
+ ).toBeGreaterThan(0);
});
it('surfaces structured Patrol runtime error details on expanded runs', () => {
@@ -226,13 +234,13 @@ describe('RunHistoryEntry', () => {
));
expect(screen.getByText('Selected model does not support Patrol tools')).toBeInTheDocument();
- expect(screen.getByText(/Provider rejected Patrol tool calls/)).toBeInTheDocument();
+ expect(screen.getAllByText(/Provider rejected Patrol tool calls/).length).toBeGreaterThan(0);
expect(screen.queryByText(/tool_choice/)).toBeNull();
expect(screen.queryByText(/No endpoints found/)).toBeNull();
expect(screen.getByText('error')).toBeInTheDocument();
- expect(screen.getByRole('link', { name: 'Open Patrol provider settings' })).toHaveAttribute(
+ expect(screen.getByRole('link', { name: 'Open Provider & Models' })).toHaveAttribute(
'href',
- '/settings/system-ai',
+ '/settings/pulse-intelligence/provider',
);
});
@@ -252,7 +260,7 @@ describe('RunHistoryEntry', () => {
/>
));
- expect(screen.queryByRole('link', { name: 'Open Patrol provider settings' })).toBeNull();
+ expect(screen.queryByRole('link', { name: 'Open Provider & Models' })).toBeNull();
});
it('opens Assistant with structured run history context', () => {
@@ -292,7 +300,7 @@ describe('RunHistoryEntry', () => {
handoffMetadata: {
kind: 'patrol_run',
runId: 'run-runtime-error',
- runType: 'Scoped run',
+ runType: 'Targeted check',
runStatus: 'error',
runtimeFailure: true,
},
@@ -332,18 +340,23 @@ describe('RunHistoryEntry', () => {
/>
));
- expect(screen.getByText('• Checked 0 of 2 scoped resources')).toBeInTheDocument();
+ expect(screen.getByText('Patrol needs attention')).toBeInTheDocument();
+ expect(
+ screen.getAllByText(
+ 'Checked 0 of 2 scoped resources in 453ms. Runtime issue: 1 Patrol runtime error recorded.',
+ ).length,
+ ).toBeGreaterThan(0);
expect(screen.queryByText('Scoped to 2 resources')).not.toBeInTheDocument();
expect(
- screen.getByText(
+ screen.getAllByText(
(_, element) =>
element?.tagName === 'P' &&
(element.textContent?.includes('Checked 0 of 2 scoped resources') ?? false) &&
(element.textContent?.includes('453ms') ?? false) &&
- (element.textContent?.includes('Patrol completed with issues requiring review.') ??
+ (element.textContent?.includes('Runtime issue: 1 Patrol runtime error recorded.') ??
false),
- ),
- ).toBeInTheDocument();
+ ).length,
+ ).toBeGreaterThan(0);
expect(screen.queryByText(/^Patrol completed in 453ms/)).not.toBeInTheDocument();
});
@@ -364,18 +377,13 @@ describe('RunHistoryEntry', () => {
/>
));
- expect(
- screen.getByText(
- (_, element) =>
- element?.tagName === 'P' &&
- (element.textContent?.includes('No new issues, but 2 existing issues remain.') ?? false),
- ),
- ).toBeInTheDocument();
+ expect(screen.getByText('2 issues still open')).toBeInTheDocument();
+ expect(screen.getAllByText('Patrol ran in 1m. No new issues.').length).toBeGreaterThan(0);
expect(screen.queryByText('All clear — no new issues.')).not.toBeInTheDocument();
expect(screen.queryByText(/^All clear$/)).not.toBeInTheDocument();
});
- it('uses singular verb agreement when a single existing issue remains', () => {
+ it('uses singular issue wording when a single issue remains open', () => {
render(() => (
<RunHistoryEntry
run={{
@@ -392,13 +400,8 @@ describe('RunHistoryEntry', () => {
/>
));
- expect(
- screen.getByText(
- (_, element) =>
- element?.tagName === 'P' &&
- (element.textContent?.includes('No new issues, but 1 existing issue remains.') ?? false),
- ),
- ).toBeInTheDocument();
+ expect(screen.getByText('1 issue still open')).toBeInTheDocument();
+ expect(screen.getAllByText('Patrol ran in 1m. No new issues.').length).toBeGreaterThan(0);
// Guard against the regression: the prior wording was "1 existing issue remain."
expect(
screen.queryByText(
@@ -431,6 +434,39 @@ describe('RunHistoryEntry', () => {
expect(screen.getByText('LLM skipped')).toBeInTheDocument();
});
+ it('keeps technical run trace behind an explicit details disclosure', () => {
+ expect(runHistoryEntrySource).toContain('const [showTechnicalDetails');
+ expect(runHistoryEntrySource).toContain('Technical details');
+ expect(runHistoryEntrySource).toContain('onToggle={(event) => setShowTechnicalDetails');
+ expect(runHistoryEntrySource).toContain('<Show when={showTechnicalDetails()}>');
+
+ render(() => (
+ <RunHistoryEntry
+ run={{
+ ...run,
+ id: 'run-technical-details',
+ duration_ms: 60_000,
+ tool_call_count: 2,
+ triage_flags: 1,
+ }}
+ isLive={false}
+ patrolStream={patrolStream}
+ selected={true}
+ onSelect={vi.fn()}
+ />
+ ));
+
+ expect(screen.getByText('Technical details')).toBeInTheDocument();
+ expect(screen.queryByTestId('tool-call-trace')).not.toBeInTheDocument();
+
+ const technicalDetails = screen.getByText('Technical details').closest('details');
+ expect(technicalDetails).not.toBeNull();
+ technicalDetails!.open = true;
+ fireEvent(technicalDetails!, new Event('toggle'));
+
+ expect(screen.getByTestId('tool-call-trace')).toBeInTheDocument();
+ });
+
it('renders TrueNAS run coverage separately from agent hosts', () => {
render(() => (
<RunHistoryEntry
diff --git a/frontend-modern/src/components/patrol/__tests__/RunHistoryPanel.test.tsx b/frontend-modern/src/components/patrol/__tests__/RunHistoryPanel.test.tsx
index dca344d724..363a0acc5c 100644
--- a/frontend-modern/src/components/patrol/__tests__/RunHistoryPanel.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/RunHistoryPanel.test.tsx
@@ -1,10 +1,12 @@
-import { cleanup, render, screen } from '@solidjs/testing-library';
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { PatrolRunRecord } from '@/api/patrol';
import { RunHistoryPanel } from '../RunHistoryPanel';
vi.mock('../RunHistoryEntry', () => ({
- RunHistoryEntry: () => <div data-testid="run-history-entry" />,
+ RunHistoryEntry: (props: { run: PatrolRunRecord }) => (
+ <div data-testid="run-history-entry">{props.run.id}</div>
+ ),
}));
describe('RunHistoryPanel', () => {
@@ -59,7 +61,7 @@ describe('RunHistoryPanel', () => {
cleanup();
});
- it('warns that some older runs do not include findings snapshots', () => {
+ it('frames history as Patrol checks even when older runs lack finding records', () => {
render(() => (
<RunHistoryPanel
runs={[baseRun, { ...baseRun, id: 'run-legacy', finding_ids: undefined }]}
@@ -70,14 +72,15 @@ describe('RunHistoryPanel', () => {
/>
));
+ expect(screen.queryByRole('heading', { name: 'History' })).not.toBeInTheDocument();
expect(
screen.getByText(
- 'Select a run to filter findings when available. Some older runs do not include findings snapshots.',
+ 'Open a check to review what Patrol found. Older checks may not have issue lists.',
),
).toBeInTheDocument();
});
- it('explains when the selected run predates findings snapshots', () => {
+ it('explains when the selected run lacks finding records', () => {
const legacyRun = { ...baseRun, id: 'run-legacy', finding_ids: undefined };
render(() => (
@@ -92,8 +95,40 @@ describe('RunHistoryPanel', () => {
expect(
screen.getByText(
- 'Selected run predates findings snapshots; run-scoped findings cannot be fully verified.',
+ 'This older check has no issue list.',
),
).toBeInTheDocument();
});
+
+ it('keeps older run snapshots behind an explicit expansion', () => {
+ const runs = Array.from({ length: 10 }, (_, index) => ({
+ ...baseRun,
+ id: `run-${index + 1}`,
+ }));
+
+ render(() => (
+ <RunHistoryPanel
+ runs={runs}
+ loading={false}
+ selectedRun={null}
+ onSelectRun={vi.fn()}
+ patrolStream={patrolStream}
+ />
+ ));
+
+ expect(screen.getAllByTestId('run-history-entry')).toHaveLength(8);
+ expect(screen.getByText('run-1')).toBeInTheDocument();
+ expect(screen.getByText('run-8')).toBeInTheDocument();
+ expect(screen.queryByText('run-9')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Show 2 older runs' }));
+
+ expect(screen.getAllByTestId('run-history-entry')).toHaveLength(10);
+ expect(screen.getByText('run-10')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Show recent 8 runs' }));
+
+ expect(screen.getAllByTestId('run-history-entry')).toHaveLength(8);
+ expect(screen.queryByText('run-10')).not.toBeInTheDocument();
+ });
});
diff --git a/frontend-modern/src/components/shared/FilterButtonGroup.test.tsx b/frontend-modern/src/components/shared/FilterButtonGroup.test.tsx
index d559b5a480..c739160e89 100644
--- a/frontend-modern/src/components/shared/FilterButtonGroup.test.tsx
+++ b/frontend-modern/src/components/shared/FilterButtonGroup.test.tsx
@@ -173,7 +173,7 @@ describe('FilterButtonGroup', () => {
it('supports equal-width segmented controls for compact feature settings', () => {
render(() => (
<FilterButtonGroup
- ariaLabel="Patrol autonomy level"
+ ariaLabel="Patrol control"
options={[
{ value: 'monitor', label: 'Monitor' },
{ value: 'approval', label: 'Investigate', disabled: true },
@@ -185,7 +185,7 @@ describe('FilterButtonGroup', () => {
/>
));
- const group = screen.getByRole('group', { name: 'Patrol autonomy level' });
+ const group = screen.getByRole('group', { name: 'Patrol control' });
const activeButton = within(group).getByRole('button', { name: 'Monitor' });
const disabledButton = within(group).getByRole('button', { name: 'Investigate' });
diff --git a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
index b4b6b7d11c..267448c122 100644
--- a/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
+++ b/frontend-modern/src/components/shared/SharedPrimitives.guardrails.test.ts
@@ -278,7 +278,6 @@ import resourcePickerSource from '@/components/Settings/ResourcePicker.tsx?raw';
import settingsPageShellSource from '@/components/Settings/SettingsPageShell.tsx?raw';
import loginSource from '@/components/Login.tsx?raw';
import patrolIntelligenceHeaderSource from '@/features/patrol/PatrolIntelligenceHeader.tsx?raw';
-import patrolIntelligenceSummarySource from '@/features/patrol/PatrolIntelligenceSummary.tsx?raw';
import patrolIntelligenceWorkspaceSource from '@/features/patrol/PatrolIntelligenceWorkspace.tsx?raw';
import approvalBannerSource from '@/components/patrol/ApprovalBanner.tsx?raw';
import approvalSectionSource from '@/components/patrol/ApprovalSection.tsx?raw';
@@ -287,7 +286,6 @@ import investigationSectionSource from '@/components/patrol/InvestigationSection
import runHistoryPanelSource from '@/components/patrol/RunHistoryPanel.tsx?raw';
import runHistoryEntrySource from '@/components/patrol/RunHistoryEntry.tsx?raw';
import runToolCallTraceSource from '@/components/patrol/RunToolCallTrace.tsx?raw';
-import patrolStatusBarSource from '@/components/patrol/PatrolStatusBar.tsx?raw';
import filterBarSource from '@/components/shared/FilterBar/FilterBar.tsx?raw';
import filterChipSource from '@/components/shared/FilterBar/FilterChip.tsx?raw';
import featureGateSectionSource from '@/components/shared/FeatureGateSection.tsx?raw';
@@ -493,8 +491,9 @@ describe('shared primitive guardrails', () => {
expect(reportingPanelSource).not.toContain('getReportingToggleButtonClass');
expect(reportingPanelSource).not.toContain('<For each={REPORTING_RANGE_OPTIONS}>');
expect(patrolIntelligenceHeaderSource).toContain('FilterButtonGroup');
- expect(patrolIntelligenceHeaderSource).toContain('variant="segmented"');
- expect(patrolIntelligenceHeaderSource).toContain('selectedAutonomyLevel');
+ expect(patrolIntelligenceHeaderSource).toContain("variant={options.variant ?? 'segmented'}");
+ expect(patrolIntelligenceHeaderSource).not.toContain("variant: 'prominent'");
+ expect(patrolIntelligenceHeaderSource).toContain('selectedAutonomyPolicy');
expect(patrolIntelligenceHeaderSource).not.toContain(
'flex items-center bg-base rounded-md p-1 border shadow-inner',
);
@@ -657,7 +656,6 @@ describe('shared primitive guardrails', () => {
'src/features/alerts/AlertAppriseDestinationsSection.tsx',
'src/features/alerts/AlertEscalationSection.tsx',
'src/features/alerts/AlertQuietHoursSection.tsx',
- 'src/features/patrol/PatrolIntelligenceHeader.tsx',
]);
expect(registeredGuard?.canonical?.path).toBe('src/components/shared/FormSelect.tsx');
expect(registeredGuard?.canonical?.export).toBe('FormSelect');
@@ -1954,8 +1952,6 @@ describe('shared primitive guardrails', () => {
'src/components/Settings/AgentProfilesPanel.tsx',
'src/components/Settings/DiagnosticsResultsPanel.tsx',
'src/components/patrol/RunHistoryEntry.tsx',
- 'src/components/patrol/PatrolStatusBar.tsx',
- 'src/features/patrol/PatrolIntelligenceSummary.tsx',
]);
expect(registeredGuard?.canonical?.path).toBe('src/components/shared/StatusIndicatorBadge.tsx');
expect(registeredGuard?.canonical?.export).toBe('StatusIndicatorBadge');
@@ -1977,16 +1973,7 @@ describe('shared primitive guardrails', () => {
expect(diagnosticsResultsPanelSource).not.toContain('getStatusIndicatorBadgeToneClasses');
expect(runHistoryEntrySource).toContain('StatusIndicatorBadge');
expect(runHistoryEntrySource).not.toContain('runStatus.badgeClass');
- expect(patrolStatusBarSource).toContain('StatusIndicatorBadge');
- expect(patrolStatusBarSource).not.toContain('lastRunStatus.badgeClass');
- expect(patrolStatusBarSource).not.toContain(
- 'rounded border border-blue-200 bg-blue-50 px-1.5 py-0.5 text-[10px] font-medium text-blue-700',
- );
- expect(patrolIntelligenceSummarySource).toContain('StatusIndicatorBadge');
- expect(patrolIntelligenceSummarySource).not.toContain('runtimeShellPresentation().badgeClass');
- expect(patrolIntelligenceSummarySource).not.toContain(
- 'inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em]',
- );
+ expect(patrolIntelligenceWorkspaceSource).not.toContain('runtimeShellPresentation()');
});
it('keeps platform alert severity indicators and filters on shared alert severity primitives', () => {
@@ -2410,7 +2397,6 @@ describe('shared primitive guardrails', () => {
'src/components/patrol/InvestigationSection.tsx',
'src/components/patrol/RunHistoryEntry.tsx',
'src/components/patrol/RunToolCallTrace.tsx',
- 'src/components/patrol/PatrolStatusBar.tsx',
'src/features/proxmox/proxmoxBackupsTableShared.tsx',
'src/features/patrol/PatrolIntelligenceWorkspace.tsx',
]);
@@ -2511,10 +2497,6 @@ describe('shared primitive guardrails', () => {
expect(runHistoryEntrySource).not.toContain(
'inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-blue-50',
);
- expect(patrolStatusBarSource).toContain('MetadataBadge');
- expect(patrolStatusBarSource).not.toContain(
- 'text-blue-600 dark:text-blue-400">Findings snapshot unavailable',
- );
expect(patrolIntelligenceWorkspaceSource).toContain('MetadataBadge');
expect(patrolIntelligenceWorkspaceSource).toContain('findingsBadgePresentation().tone');
expect(patrolIntelligenceWorkspaceSource).not.toContain(
@@ -2699,7 +2681,6 @@ describe('shared primitive guardrails', () => {
'src/components/patrol/InvestigationMessages.tsx',
'src/components/patrol/InvestigationSection.tsx',
'src/components/patrol/RunToolCallTrace.tsx',
- 'src/features/patrol/PatrolIntelligenceHeader.tsx',
]);
expect(registeredGuard?.canonical?.path).toBe('src/components/shared/LoadingSpinner.tsx');
expect(registeredGuard?.canonical?.export).toBe('LoadingSpinner');
@@ -2824,7 +2805,6 @@ describe('shared primitive guardrails', () => {
investigationMessagesSource,
investigationSectionSource,
runToolCallTraceSource,
- patrolIntelligenceHeaderSource,
]) {
expect(source).toContain('LoadingSpinner');
expect(source).not.toMatch(/border(?:-\d)?[^\n]*border-t-transparent[^\n]*animate-spin/);
diff --git a/frontend-modern/src/constants/apiScopes.ts b/frontend-modern/src/constants/apiScopes.ts
index f36614058e..7ef5ad1b9a 100644
--- a/frontend-modern/src/constants/apiScopes.ts
+++ b/frontend-modern/src/constants/apiScopes.ts
@@ -4,7 +4,7 @@ export interface APIScopeOption {
value: string;
label: string;
description?: string;
- group: 'Monitoring' | 'Agents' | 'Settings' | 'Security';
+ group: 'Monitoring' | 'AI' | 'Agents' | 'Settings' | 'Security';
}
export const AGENT_REPORT_SCOPE = 'agent:report';
@@ -14,6 +14,8 @@ export const DOCKER_MANAGE_SCOPE = 'docker:manage';
export const KUBERNETES_REPORT_SCOPE = 'kubernetes:report';
export const KUBERNETES_MANAGE_SCOPE = 'kubernetes:manage';
export const AGENT_EXEC_SCOPE = 'agent:exec';
+export const AI_EXECUTE_SCOPE = 'ai:execute';
+export const AI_CHAT_SCOPE = 'ai:chat';
export const MONITORING_READ_SCOPE = 'monitoring:read';
export const MONITORING_WRITE_SCOPE = 'monitoring:write';
export const SETTINGS_READ_SCOPE = 'settings:read';
@@ -35,6 +37,19 @@ export const API_SCOPE_OPTIONS: APIScopeOption[] = [
description: 'Acknowledge, silence, and clear alerts.',
group: 'Monitoring',
},
+ {
+ value: AI_CHAT_SCOPE,
+ label: 'Pulse Assistant chat',
+ description: 'Use interactive Pulse Assistant sessions, models, and knowledge endpoints.',
+ group: 'AI',
+ },
+ {
+ value: AI_EXECUTE_SCOPE,
+ label: 'Pulse Intelligence actions',
+ description:
+ 'Use governed Patrol actions for plans, approvals, policy-allowed fixes, verification, and history.',
+ group: 'AI',
+ },
{
value: DOCKER_REPORT_SCOPE,
label: `${DOCKER_PODMAN_SOURCE_LABEL} reporting`,
diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx
index 4aff00e564..9441d03f3c 100644
--- a/frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx
+++ b/frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx
@@ -1,11 +1,16 @@
-import { Show } from 'solid-js';
+import { createMemo, Show } from 'solid-js';
+import DownloadIcon from 'lucide-solid/icons/download';
+import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';
import ShieldAlertIcon from 'lucide-solid/icons/shield-alert';
import SettingsIcon from 'lucide-solid/icons/settings';
import { AnimatedNumber } from '@/components/shared/AnimatedNumber';
+import { UpgradeButtonLink } from '@/components/shared/UpgradeLink';
+import { getUpgradeActionDestination } from '@/stores/licenseCommercial';
import { presentationPolicyHidesUpgradePrompts } from '@/stores/sessionPresentationPolicy';
import { formatRelativeTime } from '@/utils/format';
import { getAIProviderDisplayName } from '@/utils/aiProviderPresentation';
import { PATROL_PROVIDER_SETTINGS_ACTION } from '@/utils/patrolRuntimeActions';
+import { getPatrolAutonomyAvailabilityPresentation } from './patrolAutonomyAvailability';
import type { PatrolIntelligenceState } from './usePatrolIntelligenceState';
// Strip a provider prefix ("deepseek:deepseek-v4-flash" -> "deepseek-v4-flash")
@@ -19,6 +24,17 @@ function modelIdWithoutProviderPrefix(modelId: string | undefined): string {
export function PatrolIntelligenceBanners(props: { state: PatrolIntelligenceState }) {
const state = props.state;
+ const autonomyAvailability = createMemo(() =>
+ getPatrolAutonomyAvailabilityPresentation({
+ autoFixLocked: state.autoFixLocked(),
+ runtimeCapabilityBlock: state.autoFixCapabilityBlock(),
+ runtime: state.licenseRuntimeIdentity(),
+ planUpgradeDestination: getUpgradeActionDestination('ai_autofix'),
+ }),
+ );
+ const shouldShowReadinessAction = createMemo(
+ () => state.patrolReadiness()?.status !== 'not_ready',
+ );
return (
<>
@@ -50,24 +66,71 @@ export function PatrolIntelligenceBanners(props: { state: PatrolIntelligenceStat
</div>
</Show>
+ <Show when={state.patrolLoadError()}>
+ <div class="flex-shrink-0 border-b border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-800 dark:bg-amber-900">
+ <div class="flex flex-wrap items-center justify-between gap-3">
+ <div>
+ <p class="text-sm font-semibold text-amber-900 dark:text-amber-100">
+ Patrol could not refresh
+ </p>
+ <p class="text-xs text-amber-700 dark:text-amber-300">
+ Last known issues are shown if available.
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => void state.handleRefreshPatrol()}
+ disabled={state.isManualRefreshRunning()}
+ class="inline-flex items-center justify-center gap-2 rounded-md border border-amber-200 bg-amber-100 px-3 py-1.5 text-xs font-semibold text-amber-900 transition-colors hover:bg-amber-200 disabled:cursor-wait disabled:opacity-60 dark:border-amber-700 dark:bg-amber-900 dark:text-amber-100 dark:hover:bg-amber-900"
+ >
+ <RefreshCwIcon
+ class={`h-3.5 w-3.5 ${state.isManualRefreshRunning() ? 'animate-spin' : ''}`}
+ />
+ Retry
+ </button>
+ </div>
+ </div>
+ </Show>
+
<Show
when={
!presentationPolicyHidesUpgradePrompts() &&
state.licenseRequired() &&
+ autonomyAvailability().locked &&
+ autonomyAvailability().kind === 'runtime_locked' &&
!state.showBlockedBanner()
}
>
<div class="flex-shrink-0 bg-blue-50 dark:bg-blue-900 border-b border-blue-200 dark:border-blue-800 px-3 py-2">
<div class="flex flex-wrap items-center justify-between gap-2">
<p class="text-xs text-blue-700 dark:text-blue-300">
- Safe remediation workflows and alert-triggered root-cause analysis are not enabled on
- this plan.
+ <span class="font-semibold text-blue-900 dark:text-blue-100">
+ {autonomyAvailability().title}.
+ </span>{' '}
+ {autonomyAvailability().body}
</p>
+ <Show when={autonomyAvailability().destination?.href}>
+ <UpgradeButtonLink
+ destination={autonomyAvailability().destination!}
+ size="xs"
+ mobileFullWidth={false}
+ class="shrink-0"
+ >
+ <DownloadIcon class="h-3.5 w-3.5" />
+ {autonomyAvailability().actionLabel}
+ </UpgradeButtonLink>
+ </Show>
</div>
</div>
</Show>
- <Show when={state.showReadinessBanner() && !state.showBlockedBanner()}>
+ <Show
+ when={
+ state.showReadinessBanner() &&
+ !state.showBlockedBanner() &&
+ !state.shouldShowPatrolSetupOnly()
+ }
+ >
<div
class={`flex-shrink-0 border-b px-4 py-3 ${
state.patrolReadiness()?.status === 'not_ready'
@@ -101,8 +164,8 @@ export function PatrolIntelligenceBanners(props: { state: PatrolIntelligenceStat
}`}
>
{state.patrolReadiness()?.status === 'not_ready'
- ? 'Patrol readiness issue'
- : 'Patrol readiness warning'}
+ ? 'Provider issue'
+ : 'Provider warning'}
</p>
<p
class={`text-xs ${
@@ -113,15 +176,10 @@ export function PatrolIntelligenceBanners(props: { state: PatrolIntelligenceStat
>
{state.patrolReadiness()?.summary}
</p>
- {/* Concrete diagnosis: which provider and model failed, and
- the preflight recommendation. Without these the banner
- summary alone ("Provider connection issue") leaves the
- operator with nothing actionable. */}
- <Show
- when={
- state.patrolReadiness()?.provider || state.patrolReadiness()?.model
- }
- >
+ {/* Keep the Patrol page at operator level: show the provider
+ and model that need attention, while raw diagnostics stay
+ in Provider & Models. */}
+ <Show when={state.patrolReadiness()?.provider || state.patrolReadiness()?.model}>
<p
class={`text-xs mt-1 ${
state.patrolReadiness()?.status === 'not_ready'
@@ -134,9 +192,7 @@ export function PatrolIntelligenceBanners(props: { state: PatrolIntelligenceStat
{getAIProviderDisplayName(state.patrolReadiness()!.provider!)}
</Show>
<Show
- when={
- state.patrolReadiness()?.provider && state.patrolReadiness()?.model
- }
+ when={state.patrolReadiness()?.provider && state.patrolReadiness()?.model}
>
{' · '}
</Show>
@@ -153,11 +209,8 @@ export function PatrolIntelligenceBanners(props: { state: PatrolIntelligenceStat
}
>
{' · '}
- <span class="font-medium">Preflight:</span>{' '}
+ <span class="font-medium">Model check:</span>{' '}
{(state.patrolPreflight()!.duration_ms / 1000).toFixed(1)}s
- <Show when={state.patrolPreflight()?.tool_call_observed === false}>
- , no tool call observed
- </Show>
</Show>
</p>
</Show>
@@ -174,17 +227,15 @@ export function PatrolIntelligenceBanners(props: { state: PatrolIntelligenceStat
</Show>
</div>
</div>
- <a
- href={PATROL_PROVIDER_SETTINGS_ACTION.href}
- class={`inline-flex items-center justify-center gap-2 px-3 py-1.5 text-xs font-semibold rounded-md border transition-colors ${
- state.patrolReadiness()?.status === 'not_ready'
- ? 'text-red-900 dark:text-red-100 bg-red-100 dark:bg-red-900 border-red-200 dark:border-red-700 hover:bg-red-200 dark:hover:bg-red-900'
- : 'text-amber-900 dark:text-amber-100 bg-amber-100 dark:bg-amber-900 border-amber-200 dark:border-amber-700 hover:bg-amber-200 dark:hover:bg-amber-900'
- }`}
- >
- <SettingsIcon class="w-3.5 h-3.5" />
- {PATROL_PROVIDER_SETTINGS_ACTION.label}
- </a>
+ <Show when={shouldShowReadinessAction()}>
+ <a
+ href={PATROL_PROVIDER_SETTINGS_ACTION.href}
+ class="inline-flex items-center justify-center gap-2 px-3 py-1.5 text-xs font-semibold rounded-md border border-amber-200 bg-amber-100 text-amber-900 transition-colors hover:bg-amber-200 dark:border-amber-700 dark:bg-amber-900 dark:text-amber-100 dark:hover:bg-amber-900"
+ >
+ <SettingsIcon class="w-3.5 h-3.5" />
+ {PATROL_PROVIDER_SETTINGS_ACTION.label}
+ </a>
+ </Show>
</div>
</div>
</Show>
diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx
index ea5863c89f..5c051f5b11 100644
--- a/frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx
+++ b/frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx
@@ -1,31 +1,35 @@
-import { createMemo, createUniqueId, For, Show } from 'solid-js';
-import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';
+import { createMemo, Show } from 'solid-js';
+import { A } from '@solidjs/router';
import PlayIcon from 'lucide-solid/icons/play';
-import CircleHelpIcon from 'lucide-solid/icons/circle-help';
-import MessageSquareIcon from 'lucide-solid/icons/message-square';
-import XIcon from 'lucide-solid/icons/x';
import SettingsIcon from 'lucide-solid/icons/settings';
+import DownloadIcon from 'lucide-solid/icons/download';
+import CreditCardIcon from 'lucide-solid/icons/credit-card';
import { PulsePatrolLogo } from '@/components/Brand/PulsePatrolLogo';
import { PageHeader } from '@/components/shared/PageHeader';
-import { Toggle, TogglePrimitive } from '@/components/shared/Toggle';
+import { TogglePrimitive } from '@/components/shared/Toggle';
import { CountdownTimer } from '@/components/patrol';
-import { FormSelect } from '@/components/shared/FormSelect';
import { FilterButtonGroup, type FilterOption } from '@/components/shared/FilterButtonGroup';
-import { LoadingSpinner } from '@/components/shared/LoadingSpinner';
+import { UpgradeButtonLink } from '@/components/shared/UpgradeLink';
import type { PatrolAutonomyLevel } from '@/api/patrol';
-import { presentationPolicyHidesUpgradePrompts } from '@/stores/sessionPresentationPolicy';
+import { settingsTabPath } from '@/components/Settings/settingsNavigationModel';
+import { getUpgradeActionDestination } from '@/stores/licenseCommercial';
+import {
+ presentationPolicyHidesCommercialSurfaces,
+ presentationPolicyHidesUpgradePrompts,
+} from '@/stores/sessionPresentationPolicy';
import { formatRelativeTime } from '@/utils/format';
-import { groupModelsByProvider } from '@/utils/patrolFormat';
import { getPatrolPageHeaderMeta } from '@/utils/patrolPagePresentation';
import { getPatrolTriggerStatusSummary } from '@/utils/patrolRunPresentation';
-import { buildPatrolScheduleOptions } from '@/utils/aiPatrolSchedulePresentation';
import { getPatrolRuntimePresentation } from '@/utils/patrolRuntimePresentation';
+import { getPatrolProviderSettingsAction } from '@/utils/patrolRuntimeActions';
import { getPatrolRecencyPresentation } from '@/utils/patrolSummaryPresentation';
-import { PATROL_PROVIDER_SETTINGS_ACTION } from '@/utils/patrolRuntimeActions';
+import { PATROL_CONTROL_ANCHOR, PATROL_OPERATIONS_LOOP_ANCHOR } from '@/routing/resourceLinks';
import type { PatrolConfigurationFailureInput } from './patrolInvestigationContextModel';
+import { getPatrolAutonomyAvailabilityPresentation } from './patrolAutonomyAvailability';
+import { PATROL_AUTONOMY_POLICY_PRESENTATION } from './patrolControlPresentation';
import type { PatrolIntelligenceState } from './usePatrolIntelligenceState';
-type PatrolSelectableAutonomyLevel = Exclude<PatrolAutonomyLevel, 'full'>;
+export { PATROL_AUTONOMY_POLICY_PRESENTATION } from './patrolControlPresentation';
const isNonEmptyConfigurationDetail = (value?: string | null): value is string =>
Boolean(value?.trim());
@@ -40,7 +44,7 @@ export function getPatrolConfigurationFailureInlineDetails(
return [
codeAndCause || undefined,
- readiness?.summary ? `Readiness: ${readiness.summary}` : undefined,
+ readiness?.summary ? `Setup: ${readiness.summary}` : undefined,
readiness?.provider ? `Provider: ${readiness.provider}` : undefined,
readiness?.model ? `Model: ${readiness.model}` : undefined,
].filter(isNonEmptyConfigurationDetail);
@@ -48,20 +52,11 @@ export function getPatrolConfigurationFailureInlineDetails(
export function PatrolIntelligenceHeader(props: { state: PatrolIntelligenceState }) {
const state = props.state;
- const fieldIdPrefix = `patrol-config-${createUniqueId()}`;
- const fieldIds = {
- alertTriggeredAnalysis: `${fieldIdPrefix}-alert-triggered-analysis`,
- patrolAlertTriggers: `${fieldIdPrefix}-alert-triggered-patrols`,
- patrolAlertTriggerMinSeverity: `${fieldIdPrefix}-alert-trigger-min-severity`,
- patrolAnomalyTriggers: `${fieldIdPrefix}-anomaly-triggered-patrols`,
- autonomousCriticalRemediation: `${fieldIdPrefix}-autonomous-critical-remediation`,
- };
- const headerMeta = getPatrolPageHeaderMeta();
- const scheduleOptions = createMemo(() => buildPatrolScheduleOptions(state.patrolInterval()));
- const selectedScheduleLabel = createMemo(
- () =>
- scheduleOptions().find((option) => option.value === state.patrolInterval())?.label ??
- `${state.patrolInterval()} minutes`,
+ const headerMeta = createMemo(() =>
+ getPatrolPageHeaderMeta({
+ autonomyLevel: state.autonomyLevel(),
+ autonomyLocked: state.autoFixLocked(),
+ }),
);
const runtimePresentation = createMemo(() =>
getPatrolRuntimePresentation(state.runtimeState(), state.blockedReason()),
@@ -74,110 +69,258 @@ export function PatrolIntelligenceHeader(props: { state: PatrolIntelligenceState
}),
);
const triggerStatusSummary = createMemo(() =>
- getPatrolTriggerStatusSummary(state.patrolStatus()?.trigger_status),
+ getPatrolTriggerStatusSummary(state.patrolStatus()?.trigger_status, {
+ manualRunAvailable: state.canTriggerPatrol(),
+ manualRunBlockedReason: state.triggerPatrolDisabledReason(),
+ }),
+ );
+ const providerSetupAction = getPatrolProviderSettingsAction();
+ const runControlBusy = createMemo(
+ () =>
+ state.isTriggeringPatrol() || state.manualRunRequested() || state.patrolStream.isStreaming(),
+ );
+ const runBlockedByProviderSetup = createMemo(
+ () =>
+ !runControlBusy() &&
+ state.patrolEnabledLocal() &&
+ state.runtimeState() === 'active' &&
+ state.patrolReadiness()?.status === 'not_ready',
+ );
+ const runButtonDisabled = createMemo(() => runControlBusy() || !state.canTriggerPatrol());
+ const runButtonLabel = createMemo(() =>
+ state.isTriggeringPatrol()
+ ? 'Starting…'
+ : state.manualRunRequested() || state.patrolStream.isStreaming()
+ ? 'Running…'
+ : 'Run Patrol',
+ );
+ const renderRunControl = (className: string) => (
+ <Show
+ when={!runBlockedByProviderSetup()}
+ fallback={
+ <A
+ href={providerSetupAction.href}
+ aria-label={`Fix Patrol provider: ${state.triggerPatrolDisabledReason() || 'Provider needs attention'}`}
+ title={state.triggerPatrolDisabledReason() || 'Open Provider & Models'}
+ class={className}
+ >
+ <SettingsIcon class="w-4 h-4" />
+ Fix provider
+ </A>
+ }
+ >
+ <button
+ onClick={() => state.handleRunPatrol()}
+ disabled={runButtonDisabled()}
+ title={state.triggerPatrolDisabledReason()}
+ class={className}
+ >
+ <PlayIcon class={`w-4 h-4 ${runControlBusy() ? 'animate-pulse' : ''}`} />
+ {runButtonLabel()}
+ </button>
+ </Show>
+ );
+ const effectiveAutonomyLevel = createMemo<PatrolAutonomyLevel>(() =>
+ state.autoFixLocked() ? 'monitor' : state.autonomyLevel(),
+ );
+ const selectedAutonomyPolicy = createMemo(
+ () => PATROL_AUTONOMY_POLICY_PRESENTATION[effectiveAutonomyLevel()],
+ );
+ const upgradePromptsHidden = createMemo(() => presentationPolicyHidesUpgradePrompts());
+ const commercialSurfacesHidden = createMemo(() => presentationPolicyHidesCommercialSurfaces());
+ const canChooseAutonomyLevel = createMemo(() => !state.autoFixLocked());
+ const autonomyAvailability = createMemo(() =>
+ getPatrolAutonomyAvailabilityPresentation({
+ autoFixLocked: state.autoFixLocked(),
+ upgradePromptsHidden: upgradePromptsHidden(),
+ commercialSurfacesHidden: commercialSurfacesHidden(),
+ runtimeCapabilityBlock: state.autoFixCapabilityBlock(),
+ runtime: state.licenseRuntimeIdentity(),
+ planUpgradeDestination: getUpgradeActionDestination('ai_autofix'),
+ }),
+ );
+ const shouldShowAutonomyOptions = createMemo(
+ () => canChooseAutonomyLevel() || autonomyAvailability().kind === 'runtime_locked',
+ );
+ const showAutonomyUpgradeAction = createMemo(
+ () =>
+ !presentationPolicyHidesUpgradePrompts() &&
+ state.autoFixLocked() &&
+ autonomyAvailability().kind === 'runtime_locked',
+ );
+ const showAutonomyPlanBillingAction = createMemo(
+ () =>
+ state.autoFixLocked() &&
+ autonomyAvailability().kind === 'plan_locked' &&
+ Boolean(autonomyAvailability().actionLabel && autonomyAvailability().destination?.href),
+ );
+ const shouldShowAutonomyActionColumn = createMemo(
+ () => shouldShowAutonomyOptions() || showAutonomyPlanBillingAction(),
+ );
+ const showAutonomyAvailabilityPrompt = createMemo(
+ () =>
+ state.autoFixLocked() &&
+ autonomyAvailability().kind === 'runtime_locked' &&
+ Boolean(autonomyAvailability().actionLabel),
+ );
+ const showAutonomyAvailabilityNote = createMemo(
+ () =>
+ state.autoFixLocked() &&
+ autonomyAvailability().kind === 'runtime_locked' &&
+ !autonomyAvailability().actionLabel,
+ );
+ const autonomyLevelOptions = createMemo<FilterOption<PatrolAutonomyLevel>[]>(() =>
+ (['monitor', 'approval', 'assisted', 'full'] as const).map((level) => {
+ const presentation = PATROL_AUTONOMY_POLICY_PRESENTATION[level];
+ const lockedPaidMode = state.autoFixLocked() && level !== 'monitor';
+ const showProBadge = lockedPaidMode && !commercialSurfacesHidden();
+ return {
+ value: level,
+ label: presentation.label,
+ compactLabel: presentation.compactLabel,
+ ariaLabel: showProBadge ? `${presentation.label} Pro` : undefined,
+ title: lockedPaidMode
+ ? `${presentation.detail} Available with Pulse Pro.`
+ : presentation.detail,
+ disabled: lockedPaidMode,
+ visualLabel: showProBadge ? (
+ <>
+ <span>{presentation.label}</span>
+ <span class="rounded border border-blue-200 bg-blue-50 px-1 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-blue-700 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-300">
+ Pro
+ </span>
+ </>
+ ) : undefined,
+ };
+ }),
+ );
+ const renderAutonomyPolicyControl = (options: {
+ ariaLabel: string;
+ layoutClass: string;
+ controlClass: string;
+ variant?: 'segmented' | 'prominent';
+ }) => (
+ <>
+ <div class={options.layoutClass}>
+ <div class="min-w-0">
+ <div class="flex flex-wrap items-center gap-2">
+ <span class="text-xs font-semibold uppercase tracking-wider text-muted">
+ Patrol mode
+ </span>
+ <span class="rounded border border-border-subtle bg-surface px-2 py-0.5 text-xs font-medium text-base-content">
+ {selectedAutonomyPolicy().label}
+ </span>
+ </div>
+ <p class="mt-1 text-sm leading-5 text-muted">{selectedAutonomyPolicy().detail}</p>
+ </div>
+
+ <Show when={shouldShowAutonomyActionColumn()}>
+ <div class="flex w-full flex-col gap-2 lg:w-auto">
+ <Show when={shouldShowAutonomyOptions()}>
+ <FilterButtonGroup
+ ariaLabel={options.ariaLabel}
+ class={options.controlClass}
+ disabled={!state.patrolEnabledLocal()}
+ options={autonomyLevelOptions()}
+ value={effectiveAutonomyLevel()}
+ onChange={(level) => state.handleAutonomyChange(level)}
+ variant={options.variant ?? 'segmented'}
+ />
+ </Show>
+ <Show when={showAutonomyPlanBillingAction()}>
+ <UpgradeButtonLink
+ destination={autonomyAvailability().destination!}
+ size="sm"
+ mobileFullWidth={false}
+ class="self-start lg:self-end"
+ >
+ <CreditCardIcon class="h-4 w-4" />
+ {autonomyAvailability().actionLabel}
+ </UpgradeButtonLink>
+ </Show>
+ </div>
+ </Show>
+ </div>
+
+ <Show when={showAutonomyAvailabilityNote()}>
+ <p class="mt-2 text-xs leading-5 text-muted">{autonomyAvailability().body}</p>
+ </Show>
+ <Show when={showAutonomyAvailabilityPrompt()}>
+ <div class="mt-3 flex flex-col gap-3 rounded-md border border-blue-200 bg-blue-50 px-3 py-3 dark:border-blue-800 dark:bg-blue-950/40 sm:flex-row sm:items-center sm:justify-between">
+ <div class="min-w-0">
+ <p class="text-sm font-semibold text-blue-950 dark:text-blue-100">
+ {autonomyAvailability().title}
+ </p>
+ <p class="mt-1 text-xs leading-5 text-blue-800 dark:text-blue-200">
+ {autonomyAvailability().body}
+ </p>
+ </div>
+ <Show when={showAutonomyUpgradeAction() && autonomyAvailability().destination?.href}>
+ <UpgradeButtonLink
+ destination={autonomyAvailability().destination!}
+ size="sm"
+ mobileFullWidth={false}
+ class="shrink-0"
+ >
+ <DownloadIcon class="h-4 w-4" />
+ {autonomyAvailability().actionLabel}
+ </UpgradeButtonLink>
+ </Show>
+ </div>
+ </Show>
+ <Show when={state.isUpdatingAutonomy()}>
+ <div role="status" class="sr-only">
+ Saving Patrol mode
+ </div>
+ </Show>
+ </>
);
- const patrolModelStale = createMemo(() => {
- const model = state.patrolModel();
- const models = state.availableModels();
- if (!model || models.length === 0) return false;
- return !models.some((candidate) => candidate.id === model);
- });
- const selectedAutonomyLevel = createMemo<PatrolSelectableAutonomyLevel>(() => {
- const level = state.autonomyLevel();
- return level === 'full' ? 'assisted' : level;
- });
- const getAutonomyOptionTitle = (level: PatrolSelectableAutonomyLevel) => {
- const isProLocked = () => state.autoFixLocked() && level !== 'monitor';
- if (!presentationPolicyHidesUpgradePrompts() && isProLocked()) {
- return level === 'approval'
- ? 'Investigation is not enabled on this plan'
- : 'Safe remediation workflows are not enabled on this plan';
- }
- return undefined;
- };
- const autonomyLevelOptions = createMemo<FilterOption<PatrolSelectableAutonomyLevel>[]>(() => [
- { value: 'monitor', label: 'Monitor' },
- {
- value: 'approval',
- label: 'Investigate',
- disabled: state.autoFixLocked(),
- title: getAutonomyOptionTitle('approval'),
- },
- {
- value: 'assisted',
- label: 'Remediate',
- disabled: state.autoFixLocked(),
- title: getAutonomyOptionTitle('assisted'),
- },
- ]);
return (
<div class="space-y-4">
<PageHeader
id="patrol-title"
- description={headerMeta.description}
+ description={headerMeta().description}
title={
- <span class="inline-flex items-center gap-3" title={headerMeta.titleTooltip}>
+ <span class="inline-flex items-center gap-3" title={headerMeta().titleTooltip}>
<PulsePatrolLogo class="w-6 h-6 text-base-content" decorative />
- <span>{headerMeta.title}</span>
+ <span>{headerMeta().title}</span>
</span>
}
class="relative z-[200] mb-3"
actions={
<div class="hidden sm:flex flex-wrap items-center justify-end gap-3">
- <Show when={recency().timestamp}>
- <div class="flex items-center gap-3 text-xs text-muted">
- <span>
- {recency().label}:{' '}
- {formatRelativeTime(recency().timestamp, {
- compact: true,
- emptyText: 'Never',
- })}
- <Show when={recency().resourcesCheckedLabel}>
- {' '}
- <span class="text-muted">— {recency().resourcesCheckedLabel}</span>
- </Show>
- </span>
- <Show when={state.patrolStatus()?.next_patrol_at}>
- <span class="text-muted">|</span>
- <CountdownTimer
- targetDate={state.patrolStatus()!.next_patrol_at!}
- prefix="Next run: "
- class="font-variant-numeric tabular-nums font-medium text-blue-600 dark:text-blue-400"
- />
+ <Show when={!state.shouldShowPatrolSetupOnly()}>
+ <>
+ <Show when={recency().timestamp}>
+ <div class="flex items-center gap-3 text-xs text-muted">
+ <span>
+ {recency().label}:{' '}
+ {formatRelativeTime(recency().timestamp, {
+ compact: true,
+ emptyText: 'Never',
+ })}
+ <Show when={recency().resourcesCheckedLabel}>
+ {' '}
+ <span class="text-muted">— {recency().resourcesCheckedLabel}</span>
+ </Show>
+ </span>
+ <Show when={state.patrolStatus()?.next_patrol_at}>
+ <span class="text-muted">|</span>
+ <CountdownTimer
+ targetDate={state.patrolStatus()!.next_patrol_at!}
+ prefix="Next run: "
+ class="font-variant-numeric tabular-nums font-medium text-blue-600 dark:text-blue-400"
+ />
+ </Show>
+ </div>
</Show>
- </div>
- </Show>
-
- <button
- onClick={() => state.handleRunPatrol()}
- disabled={
- state.isTriggeringPatrol() ||
- !state.canTriggerPatrol() ||
- state.manualRunRequested() ||
- state.patrolStream.isStreaming()
- }
- title={state.triggerPatrolDisabledReason()}
- class="flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:bg-surface-alt disabled:text-muted rounded-md transition-colors"
- >
- <PlayIcon
- class={`w-4 h-4 ${state.isTriggeringPatrol() || state.manualRunRequested() || state.patrolStream.isStreaming() ? 'animate-pulse' : ''}`}
- />
- {state.isTriggeringPatrol()
- ? 'Starting…'
- : state.manualRunRequested() || state.patrolStream.isStreaming()
- ? 'Running…'
- : 'Run Patrol'}
- </button>
- <button
- onClick={() => state.loadAllData()}
- disabled={state.isRefreshing()}
- class="flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-base-content bg-surface border border-border rounded-md hover:bg-surface-hover disabled:opacity-50 transition-colors"
- >
- <RefreshCwIcon class={`w-4 h-4 ${state.isRefreshing() ? 'animate-spin' : ''}`} />
- Refresh
- </button>
+ {renderRunControl(
+ 'flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:bg-surface-alt disabled:text-muted rounded-md transition-colors',
+ )}
+ </>
+ </Show>
</div>
}
/>
@@ -194,360 +337,39 @@ export function PatrolIntelligenceHeader(props: { state: PatrolIntelligenceState
<span class="text-sm font-medium text-base-content">{runtimePresentation().label}</span>
</div>
- <Show when={triggerStatusSummary()}>
- <span class="max-w-full text-xs leading-5 text-muted">
- Trigger status: {triggerStatusSummary()}
- </span>
+ <Show when={!state.shouldShowPatrolSetupOnly() && triggerStatusSummary()}>
+ <span class="max-w-full text-xs leading-5 text-muted">{triggerStatusSummary()}</span>
</Show>
- <div class="flex flex-wrap items-center gap-2 sm:ml-auto">
- <button
- onClick={() => state.handleRunPatrol()}
- disabled={
- state.isTriggeringPatrol() ||
- !state.canTriggerPatrol() ||
- state.manualRunRequested() ||
- state.patrolStream.isStreaming()
- }
- title={state.triggerPatrolDisabledReason()}
- class="sm:hidden flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:bg-surface-alt disabled:text-muted rounded-md transition-colors"
- >
- <PlayIcon
- class={`w-4 h-4 ${state.isTriggeringPatrol() || state.manualRunRequested() || state.patrolStream.isStreaming() ? 'animate-pulse' : ''}`}
- />
- {state.isTriggeringPatrol()
- ? 'Starting…'
- : state.manualRunRequested() || state.patrolStream.isStreaming()
- ? 'Running…'
- : 'Run Patrol'}
- </button>
-
- <button
- onClick={() => state.loadAllData()}
- disabled={state.isRefreshing()}
- aria-label="Refresh"
- class="sm:hidden flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-base-content bg-surface border border-border rounded-md hover:bg-surface-hover disabled:opacity-50 transition-colors"
- >
- <RefreshCwIcon class={`w-4 h-4 ${state.isRefreshing() ? 'animate-spin' : ''}`} />
- <span class="sr-only sm:not-sr-only">Refresh</span>
- </button>
+ <Show when={!state.shouldShowPatrolSetupOnly()}>
+ <div class="flex flex-wrap items-center gap-2 sm:ml-auto">
+ {renderRunControl(
+ 'sm:hidden flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:bg-surface-alt disabled:text-muted rounded-md transition-colors',
+ )}
- <div class="relative z-[120]" ref={state.setAdvancedSettingsRef}>
- <button
- onClick={() => state.setShowAdvancedSettings(!state.showAdvancedSettings())}
- disabled={!state.patrolEnabledLocal()}
- aria-label="Configure Patrol"
- title="Configure Patrol"
- class={`flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-md transition-all shadow-sm ${state.showAdvancedSettings() ? 'bg-blue-50 text-blue-700 border border-blue-200 dark:bg-blue-900 dark:text-blue-300 dark:border-blue-800' : ' text-base-content border border-border hover:bg-surface-alt'} ${!state.patrolEnabledLocal() ? 'opacity-50 cursor-not-allowed hidden' : ''}`}
+ <A
+ href={settingsTabPath('system-ai-patrol')}
+ aria-label="Open Patrol settings"
+ title="Open Patrol settings"
+ class="flex items-center gap-2 rounded-md border border-border px-3 py-1.5 text-sm font-medium text-base-content shadow-sm transition-colors hover:bg-surface-alt"
>
<SettingsIcon class="w-4 h-4" />
- <span class="sr-only sm:not-sr-only">Configure Patrol</span>
- </button>
-
- <Show when={state.showAdvancedSettings()}>
- <div
- role="dialog"
- aria-label="Patrol Configuration"
- class="fixed right-4 top-32 z-[9999] isolate max-h-[calc(100vh-10rem)] w-[calc(100vw-2rem)] overflow-y-auto rounded-md border border-border bg-surface p-5 shadow-sm animate-slide-up transform origin-top-right sm:right-8 sm:top-[13rem] sm:max-h-[calc(100vh-14rem)] sm:w-[340px]"
- >
- <div class="flex items-center justify-between mb-5 pb-3 border-b border-border-subtle">
- <h4 class="text-base font-semibold tracking-tight text-base-content">
- Patrol Configuration
- </h4>
- <button
- onClick={() => state.setShowAdvancedSettings(false)}
- aria-label="Close patrol configuration"
- title="Close"
- class="p-1 rounded-md hover:text-base-content hover:bg-surface-hover transition-colors"
- >
- <XIcon class="w-4 h-4" />
- </button>
- </div>
-
- <div class="space-y-6">
- <div class="grid grid-cols-2 gap-4">
- <FormSelect
- label="Provider model"
- labelClass="text-xs font-semibold uppercase tracking-wider text-muted"
- fieldClass="space-y-1.5"
- ref={state.setPatrolModelSelectRef}
- value={state.patrolModel()}
- onChange={(e) => state.handleModelChange(e.currentTarget.value)}
- disabled={state.isUpdatingSettings() || !state.patrolEnabledLocal()}
- selectBaseClass="w-full text-sm bg-base border border-border rounded-md py-2 pl-3 pr-8 text-base-content focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:opacity-50"
- >
- <option value="">
- Default ({state.defaultModel().split(':').pop() || 'not set'})
- </option>
- <Show when={patrolModelStale()}>
- <option value={state.patrolModel()} disabled>
- {state.patrolModel().split(':').pop()} (unavailable)
- </option>
- </Show>
- {Array.from(groupModelsByProvider(state.availableModels()).entries()).map(
- ([provider, models]) => (
- <optgroup label={provider.charAt(0).toUpperCase() + provider.slice(1)}>
- {models.map((model) => (
- <option value={model.id}>
- {model.name || model.id.split(':').pop()}
- </option>
- ))}
- </optgroup>
- ),
- )}
- </FormSelect>
-
- <FormSelect
- label="Run Every"
- labelClass="text-xs font-semibold uppercase tracking-wider text-muted"
- fieldClass="space-y-1.5"
- value={state.patrolInterval()}
- onChange={(e) =>
- state.handleIntervalChange(parseInt(e.currentTarget.value, 10))
- }
- disabled={state.isUpdatingSettings() || !state.patrolEnabledLocal()}
- selectBaseClass="w-full text-sm bg-base border border-border rounded-md py-2 pl-3 pr-8 text-base-content focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:opacity-50"
- >
- <For each={scheduleOptions()}>
- {(preset) => <option value={preset.value}>{preset.label}</option>}
- </For>
- </FormSelect>
- </div>
-
- <div class="space-y-2">
- <div class="flex items-center justify-between">
- <label class="text-xs font-semibold uppercase tracking-wider text-muted flex items-center gap-1.5">
- Operational Mode
- <div class="relative group">
- <CircleHelpIcon class="w-3.5 h-3.5 cursor-help" />
- <div class="absolute left-1/2 -translate-x-1/2 bottom-full mb-2 hidden group-hover:block w-64 p-3 bg-surface text-white rounded-md shadow-md text-xs z-50 pointer-events-none before:absolute before:top-full before:left-1/2 before:-translate-x-1/2 before:border-4 before:border-transparent before:border-t-slate-800">
- <strong>Monitor:</strong> Detect only.
- <br />
- <strong>Investigate:</strong> Detect & propose fixes.
- <br />
- <strong>Remediate:</strong> Execute approved safe actions under policy.
- </div>
- </div>
- </label>
- </div>
-
- <FilterButtonGroup
- ariaLabel="Patrol autonomy level"
- class="w-full"
- disabled={!state.patrolEnabledLocal()}
- options={autonomyLevelOptions()}
- value={selectedAutonomyLevel()}
- onChange={(level) => state.handleAutonomyChange(level)}
- variant="segmented"
- />
- <Show when={!presentationPolicyHidesUpgradePrompts() && state.autoFixLocked()}>
- <div class="pl-1 text-[11px] text-muted">
- Investigation and safe remediation workflows are not enabled on this plan.
- </div>
- </Show>
- </div>
-
- <div class="space-y-4 pt-4 border-t border-border-subtle">
- <div class="rounded-md border border-border-subtle bg-surface-alt/60 px-3 py-2.5">
- <p class="text-[11px] font-medium text-base-content">
- {state.patrolInterval() === 0
- ? 'Scheduled full patrols are off. Manual runs and alert/anomaly triggers still work.'
- : `Full patrols run every ${selectedScheduleLabel().toLowerCase()}.`}
- </p>
- <p class="mt-1 text-[11px] leading-tight text-muted">
- Alert and anomaly triggers run targeted scoped checks that update{' '}
- <span class="font-medium text-base-content">Last activity</span> without
- resetting{' '}
- <span class="font-medium text-base-content">Last full patrol</span>.
- </p>
- </div>
-
- <div class="flex items-start justify-between gap-3">
- <div class="flex-1">
- <span
- id={fieldIds.patrolAlertTriggers}
- class="text-sm font-medium text-base-content"
- >
- Alert-Triggered Patrols
- </span>
- <p class="text-[11px] text-muted mt-0.5 leading-tight">
- Run a focused Patrol investigation of the alert's issue when it fires or
- clears.
- </p>
- </div>
- <Toggle
- checked={state.patrolAlertTriggers()}
- onChange={(e) =>
- state.handlePatrolAlertTriggersChange(e.currentTarget.checked)
- }
- disabled={state.isUpdatingSettings() || !state.patrolEnabledLocal()}
- ariaLabelledBy={fieldIds.patrolAlertTriggers}
- />
- </div>
-
- <Show when={state.patrolAlertTriggers()}>
- <div class="pl-3 border-l-2 border-border ml-0.5">
- <FormSelect
- label="Investigate alerts at or above"
- labelClass="text-[11px] font-semibold uppercase tracking-wider text-muted"
- fieldClass="space-y-1"
- value={state.patrolAlertTriggerMinSeverity()}
- onChange={(e) =>
- state.handlePatrolAlertTriggerMinSeverityChange(
- e.currentTarget.value === 'warning' ? 'warning' : 'critical',
- )
- }
- disabled={state.isUpdatingSettings() || !state.patrolEnabledLocal()}
- id={fieldIds.patrolAlertTriggerMinSeverity}
- selectBaseClass="w-full text-sm bg-base border border-border rounded-md py-1.5 pl-3 pr-8 text-base-content focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:opacity-50"
- >
- <option value="critical">Critical only</option>
- <option value="warning">Warning and critical</option>
- </FormSelect>
- </div>
- </Show>
-
- <div class="flex items-start justify-between gap-3">
- <div class="flex-1">
- <span
- id={fieldIds.patrolAnomalyTriggers}
- class="text-sm font-medium text-base-content"
- >
- Anomaly-Triggered Patrols
- </span>
- <p class="text-[11px] text-muted mt-0.5 leading-tight">
- Run scoped Patrol checks when learned baselines detect high-signal
- anomalies.
- </p>
- </div>
- <Toggle
- checked={state.patrolAnomalyTriggers()}
- onChange={(e) =>
- state.handlePatrolAnomalyTriggersChange(e.currentTarget.checked)
- }
- disabled={state.isUpdatingSettings() || !state.patrolEnabledLocal()}
- ariaLabelledBy={fieldIds.patrolAnomalyTriggers}
- />
- </div>
-
- <div class="flex items-start justify-between gap-3">
- <div class="flex-1">
- <span
- id={fieldIds.alertTriggeredAnalysis}
- class="text-sm font-medium text-base-content"
- >
- Container Update Risk
- </span>
- <p class="text-[11px] text-muted mt-0.5 leading-tight">
- Assess upgrade risk with AI when a container-update alert fires.
- </p>
- </div>
- <Toggle
- checked={state.alertTriggeredAnalysis()}
- onChange={(e) =>
- state.handleAlertTriggeredAnalysisChange(e.currentTarget.checked)
- }
- disabled={state.isUpdatingSettings() || state.alertAnalysisLocked()}
- ariaLabelledBy={fieldIds.alertTriggeredAnalysis}
- />
- </div>
-
- <Show
- when={!presentationPolicyHidesUpgradePrompts() && state.alertAnalysisLocked()}
- >
- <div class="-my-1 pl-1 text-[11px]">
- Container update risk analysis is not enabled on this plan.
- </div>
- </Show>
-
- <div class="flex items-start justify-between gap-3">
- <div class="flex-1">
- <span
- id={fieldIds.autonomousCriticalRemediation}
- class="text-sm font-medium text-red-600 dark:text-red-400"
- >
- Autonomous critical remediation
- </span>
- <p class="text-[11px] text-muted mt-0.5 leading-tight">
- Permit Patrol to execute critical remediation actions without approval.
- </p>
- </div>
- <Toggle
- checked={!state.autoFixLocked() && state.fullModeUnlocked()}
- onChange={(e) => state.setFullModeUnlocked(e.currentTarget.checked)}
- disabled={
- state.autoFixLocked() ||
- !(
- state.autonomyLevel() === 'assisted' || state.autonomyLevel() === 'full'
- )
- }
- ariaLabelledBy={fieldIds.autonomousCriticalRemediation}
- />
- </div>
- </div>
-
- <div class="pt-4 border-t border-border-subtle">
- <Show when={state.advancedSettingsError()}>
- {(failure) => (
- <div
- role="alert"
- data-testid="patrol-configuration-error"
- class="mb-3 rounded-md border border-red-300 bg-red-50 px-3 py-2.5 text-red-950 dark:border-red-800 dark:bg-red-950/30 dark:text-red-100"
- >
- <p class="text-xs font-semibold">
- {failure().saved
- ? 'Patrol configuration needs attention'
- : 'Patrol configuration was not saved'}
- </p>
- <p class="mt-1 text-xs leading-relaxed">{failure().message}</p>
- <Show
- when={getPatrolConfigurationFailureInlineDetails(failure()).length > 0}
- >
- <ul class="mt-1 space-y-0.5 text-[11px] leading-relaxed opacity-80">
- <For each={getPatrolConfigurationFailureInlineDetails(failure())}>
- {(detail) => <li>{detail}</li>}
- </For>
- </ul>
- </Show>
- <div class="mt-2 flex flex-wrap items-center gap-2">
- <button
- type="button"
- data-testid="patrol-configuration-error-assistant-button"
- onClick={state.openAdvancedSettingsErrorInAssistant}
- class="inline-flex items-center gap-1.5 rounded-md border border-red-300 bg-white/80 px-2 py-1 text-xs font-medium text-red-950 transition-colors hover:bg-white dark:border-red-700 dark:bg-red-950/40 dark:text-red-100 dark:hover:bg-red-900/50"
- >
- <MessageSquareIcon class="h-3.5 w-3.5" />
- Discuss with Assistant
- </button>
- <a
- href={PATROL_PROVIDER_SETTINGS_ACTION.href}
- data-testid="patrol-configuration-error-settings-link"
- class="inline-flex items-center gap-1.5 rounded-md border border-red-300 bg-white/80 px-2 py-1 text-xs font-medium text-red-950 transition-colors hover:bg-white dark:border-red-700 dark:bg-red-950/40 dark:text-red-100 dark:hover:bg-red-900/50"
- >
- <SettingsIcon class="h-3.5 w-3.5" />
- {PATROL_PROVIDER_SETTINGS_ACTION.label}
- </a>
- </div>
- </div>
- )}
- </Show>
-
- <button
- onClick={state.saveAdvancedSettings}
- disabled={state.isSavingAdvanced()}
- class="w-full py-2.5 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md shadow-sm transition-all focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:cursor-not-allowed disabled:bg-blue-300 disabled:hover:bg-blue-300 dark:disabled:bg-blue-900 flex items-center justify-center gap-2"
- >
- <Show when={state.isSavingAdvanced()}>
- <LoadingSpinner size="md" />
- </Show>
- <Show when={!state.isSavingAdvanced()}>Apply Configuration</Show>
- </button>
- </div>
- </div>
- </div>
- </Show>
+ <span class="sr-only sm:not-sr-only">Settings</span>
+ </A>
</div>
- </div>
+ </Show>
+ </div>
+
+ <div
+ id={PATROL_CONTROL_ANCHOR}
+ class="rounded-md border border-border-subtle bg-surface-alt/50 px-3 py-3"
+ >
+ <span id={PATROL_OPERATIONS_LOOP_ANCHOR} class="sr-only" aria-hidden="true" />
+ {renderAutonomyPolicyControl({
+ ariaLabel: 'Patrol mode',
+ layoutClass: 'flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between',
+ controlClass: 'w-full lg:w-[34rem]',
+ })}
</div>
</div>
);
diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx
deleted file mode 100644
index 752cb6f0f3..0000000000
--- a/frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx
+++ /dev/null
@@ -1,243 +0,0 @@
-import { createMemo, Show } from 'solid-js';
-import AlertCircleIcon from 'lucide-solid/icons/alert-circle';
-import {
- getPatrolAssessmentShellPresentation,
- getPatrolAssessmentPresentation,
- getPatrolRecencyPresentation,
- getPatrolSummaryMetricState,
-} from '@/utils/patrolSummaryPresentation';
-import { StatusIndicatorBadge } from '@/components/shared/StatusIndicatorBadge';
-import {
- formatPatrolActivityBreakdown,
- getPatrolActivityBreakdown,
- getPatrolTriggerStatusSummary,
-} from '@/utils/patrolRunPresentation';
-import { getPatrolRuntimePresentation } from '@/utils/patrolRuntimePresentation';
-import { formatRelativeTime } from '@/utils/format';
-import type { PatrolIntelligenceState } from './usePatrolIntelligenceState';
-
-function PatrolAssessmentLoadingShell() {
- return (
- <section
- data-testid="patrol-summary-loading"
- class="overflow-hidden rounded-md border border-border bg-surface shadow-sm animate-pulse pointer-events-none select-none"
- >
- <div class="flex flex-wrap items-center justify-between gap-3 border-b border-border-subtle px-4 py-3">
- <div class="h-5 w-32 rounded bg-surface-hover" />
- <div class="h-5 w-24 rounded bg-surface-hover" />
- </div>
-
- <div class="px-4 py-4 sm:px-5 sm:py-5">
- <div class="flex items-start gap-3">
- <div class="h-11 w-11 rounded-md border border-border-subtle bg-surface-alt/60" />
- <div class="min-w-0 flex-1 space-y-2">
- <div class="h-5 w-44 rounded bg-surface-hover" />
- <div class="h-4 max-w-3xl rounded bg-surface-hover" />
- <div class="h-4 w-2/3 rounded bg-surface-hover" />
- </div>
- </div>
-
- <div class="mt-5 overflow-hidden rounded-md border border-border-subtle bg-surface-alt/60">
- <div class="grid divide-y divide-border-subtle lg:grid-cols-[minmax(0,1.35fr)_minmax(0,1fr)] lg:divide-x lg:divide-y-0">
- <div class="space-y-2 p-3">
- <div class="h-3 w-20 rounded bg-surface-hover" />
- <div class="h-4 w-40 rounded bg-surface-hover" />
- <div class="h-4 w-full rounded bg-surface-hover" />
- <div class="h-4 w-3/4 rounded bg-surface-hover" />
- </div>
- <div class="space-y-2 p-3">
- <div class="h-3 w-24 rounded bg-surface-hover" />
- <div class="h-4 w-36 rounded bg-surface-hover" />
- <div class="h-4 w-full rounded bg-surface-hover" />
- <div class="h-4 w-2/3 rounded bg-surface-hover" />
- </div>
- </div>
- </div>
- </div>
- </section>
- );
-}
-
-export function PatrolIntelligenceSummary(props: { state: PatrolIntelligenceState }) {
- const state = props.state;
- const summaryStats = createMemo(() => state.summaryStats());
- const metricState = createMemo(() =>
- getPatrolSummaryMetricState({
- activeFindings: state.activePatrolFindings(),
- fixedCount: summaryStats().fixedCount,
- }),
- );
- const runtimePresentation = createMemo(() =>
- getPatrolRuntimePresentation(state.runtimeState(), state.blockedReason()),
- );
- const runtimeShellPresentation = createMemo(() =>
- getPatrolAssessmentShellPresentation(runtimePresentation().tone),
- );
- const showRuntimeSummary = createMemo(() => {
- const runtimeState = state.runtimeState();
- return (
- runtimeState === 'blocked' || runtimeState === 'disabled' || runtimeState === 'unavailable'
- );
- });
- const hasLoadedPatrolEvidence = createMemo(
- () =>
- summaryStats().hasAnyPatrolFindings ||
- (state.patrolRunHistory.value()?.length ?? 0) > 0 ||
- Boolean(state.patrolStatus()),
- );
- const showLoadingSummary = createMemo(
- () =>
- !showRuntimeSummary() &&
- !state.intelligenceSummary() &&
- !state.initialSurfaceReady() &&
- !hasLoadedPatrolEvidence(),
- );
- const assessment = createMemo(() =>
- getPatrolAssessmentPresentation({
- overallHealth: state.intelligenceSummary()?.overall_health,
- runtimeState: state.runtimeState(),
- blockedReason: state.blockedReason(),
- criticalFindings: summaryStats().criticalFindings,
- warningFindings: summaryStats().warningFindings,
- activeFindings: state.activePatrolFindings(),
- runs: state.patrolRunHistory.value() ?? [],
- }),
- );
- const activityBreakdownLabel = createMemo(() =>
- formatPatrolActivityBreakdown(getPatrolActivityBreakdown(state.patrolRunHistory.value() ?? [])),
- );
- const triggerStatusSummary = createMemo(() =>
- getPatrolTriggerStatusSummary(state.patrolStatus()?.trigger_status),
- );
- const recency = createMemo(() =>
- getPatrolRecencyPresentation({
- runs: state.patrolRunHistory.value() ?? [],
- lastPatrolAt: state.patrolStatus()?.last_patrol_at,
- lastActivityAt: state.patrolStatus()?.last_activity_at,
- }),
- );
- const compactRiskSummary = createMemo(() => {
- const stats = summaryStats();
- const parts: string[] = [];
- const hasRuntimeIssues =
- metricState().secondaryLabel === 'Runtime issues' && metricState().secondaryValue > 0;
-
- if (stats.criticalFindings > 0) {
- parts.push(`${stats.criticalFindings} critical`);
- }
-
- if (stats.warningFindings > 0 && !hasRuntimeIssues) {
- parts.push(`${stats.warningFindings} warning`);
- }
-
- if (hasRuntimeIssues) {
- parts.push(
- `${metricState().secondaryValue} runtime ${
- metricState().secondaryValue === 1 ? 'issue' : 'issues'
- }`,
- );
- }
-
- if (parts.length === 0 && stats.totalActive > 0) {
- parts.push(`${stats.totalActive} active`);
- }
-
- return parts.join(' · ');
- });
- const compactAssessmentSummary = createMemo(() => {
- const overallHealth = state.intelligenceSummary()?.overall_health;
- const parts: string[] = [compactRiskSummary() || assessment().compactLabel];
- const regressedCount = state.patrolStatus()?.trust?.regressed_at_least_once ?? 0;
-
- if (regressedCount > 0) {
- parts.push(`${regressedCount} regressed`);
- }
-
- if (overallHealth) {
- parts.push(`${Math.round(overallHealth.score)}/100`);
- }
-
- return parts.join(' · ');
- });
- return (
- <>
- <Show when={showLoadingSummary()}>
- <PatrolAssessmentLoadingShell />
- </Show>
-
- <Show when={showRuntimeSummary()}>
- <section class="overflow-hidden rounded-md border border-border bg-surface shadow-sm">
- <div
- class={`flex flex-wrap items-center justify-between gap-3 border-b border-border-subtle px-4 py-3 ${runtimeShellPresentation().headerClass}`}
- >
- <StatusIndicatorBadge
- label="Patrol runtime"
- variant={runtimeShellPresentation().badgeVariant}
- size="md"
- uppercase
- />
- <Show when={recency().timestamp}>
- <p class="text-xs font-medium text-muted">
- {recency().label}{' '}
- {formatRelativeTime(recency().timestamp!, {
- compact: true,
- emptyText: 'never',
- })}
- </p>
- </Show>
- </div>
-
- <div class="px-4 py-4 sm:px-5 sm:py-5">
- <div class="flex items-start gap-3">
- <div
- class={`flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-md border ${runtimeShellPresentation().iconContainerClass}`}
- >
- <AlertCircleIcon class={`w-5 h-5 ${runtimeShellPresentation().iconClass}`} />
- </div>
- <div class="min-w-0">
- <h2 class="text-lg font-semibold tracking-tight text-base-content">
- {runtimePresentation().label}
- </h2>
- <p class="mt-1.5 max-w-3xl text-sm leading-6 text-muted">
- {runtimePresentation().description}
- </p>
- </div>
- </div>
- </div>
- </section>
- </Show>
-
- <Show when={!showRuntimeSummary() && !showLoadingSummary()}>
- <Show when={state.intelligenceSummary()}>
- <section class="border-y border-border-subtle py-2">
- <div class="flex flex-col gap-2 lg:flex-row lg:items-center lg:justify-between">
- <div class="min-w-0 space-y-1">
- <div class="flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-1 text-sm">
- <span class="text-[11px] font-semibold uppercase tracking-[0.14em] text-muted">
- {assessment().eyebrow}
- </span>
- <span class="font-semibold text-base-content">{compactAssessmentSummary()}</span>
- </div>
- <Show when={activityBreakdownLabel() || triggerStatusSummary()}>
- <div class="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted">
- <Show when={activityBreakdownLabel()}>
- <span>Recent activity mix: {activityBreakdownLabel()}</span>
- </Show>
- <Show when={activityBreakdownLabel() && triggerStatusSummary()}>
- <span aria-hidden="true" class="text-slate-300">
- |
- </span>
- </Show>
- <Show when={triggerStatusSummary()}>
- <span>Trigger mode: {triggerStatusSummary()}</span>
- </Show>
- </div>
- </Show>
- </div>
- </div>
- </section>
- </Show>
- </Show>
- </>
- );
-}
diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx
index 765a9ac0db..45f554a1b5 100644
--- a/frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx
+++ b/frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx
@@ -1,7 +1,6 @@
import { usePatrolIntelligenceState } from './usePatrolIntelligenceState';
import { PatrolIntelligenceHeader } from './PatrolIntelligenceHeader';
import { PatrolIntelligenceBanners } from './PatrolIntelligenceBanners';
-import { PatrolIntelligenceSummary } from './PatrolIntelligenceSummary';
import { PatrolIntelligenceWorkspace } from './PatrolIntelligenceWorkspace';
export function PatrolIntelligenceSurface() {
@@ -15,7 +14,6 @@ export function PatrolIntelligenceSurface() {
<div
class={`space-y-4 transition-opacity ${!state.patrolEnabledLocal() ? 'opacity-50 pointer-events-none' : ''}`}
>
- <PatrolIntelligenceSummary state={state} />
<PatrolIntelligenceWorkspace state={state} />
</div>
</div>
diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx
index d9f6fcc9b3..cd378cd126 100644
--- a/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx
+++ b/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx
@@ -1,30 +1,112 @@
-import { Show } from 'solid-js';
+import { createMemo, Show } from 'solid-js';
+import HistoryIcon from 'lucide-solid/icons/history';
+import SettingsIcon from 'lucide-solid/icons/settings';
import { FindingsPanel } from '@/components/AI/FindingsPanel';
import { ApprovalBanner, RunHistoryPanel } from '@/components/patrol';
-import { getPatrolFindingsBadgePresentation } from '@/utils/aiFindingPresentation';
+import {
+ getFindingTitlePresentation,
+ buildPatrolFindingDisplayGroups,
+ getPatrolFindingsBadgePresentation,
+ isPatrolRuntimeFinding,
+} from '@/utils/aiFindingPresentation';
import { formatRelativeTime } from '@/utils/format';
import { formatTriggerReason } from '@/utils/patrolFormat';
-import { ResourcePolicySummary } from '@/components/Infrastructure/ResourcePolicySummary';
-import { ResourceCorrelationSummary } from '@/components/Infrastructure/ResourceCorrelationSummary';
-import { ResourceChangeSummary } from '@/components/Infrastructure/ResourceChangeSummary';
-import { Button } from '@/components/shared/Button';
+import {
+ getPatrolRunRecordSummaryPresentation,
+ getPatrolRunStatusPresentation,
+ PATROL_FINDING_RECORD_UNAVAILABLE_LABEL,
+} from '@/utils/patrolRunPresentation';
+import { Button, ButtonLink } from '@/components/shared/Button';
import { MetadataBadge } from '@/components/shared/MetadataBadge';
+import { StatusIndicatorBadge } from '@/components/shared/StatusIndicatorBadge';
+import { getPatrolProviderSettingsAction } from '@/utils/patrolRuntimeActions';
import {
- getPatrolSupportingContextCorrelationSummary,
- getPatrolSupportingContextToggleLabel,
- PATROL_SUPPORTING_CONTEXT_CHANGE_SUBTITLE,
- PATROL_SUPPORTING_CONTEXT_DESCRIPTION,
- PATROL_SUPPORTING_CONTEXT_EVIDENCE_LABEL,
- PATROL_SUPPORTING_CONTEXT_EVIDENCE_NOTE,
- PATROL_SUPPORTING_CONTEXT_POLICY_SUBTITLE,
- PATROL_SUPPORTING_CONTEXT_TITLE,
-} from './patrolSupportingContextPresentation';
+ getPatrolQueueBadgeLabel,
+ getPatrolQueueWorkspaceDescription,
+ getPatrolSetupIssueReason,
+ PATROL_WORKSPACE_HISTORY_DESCRIPTION,
+ PATROL_WORKSPACE_QUEUE_TITLE,
+ PATROL_WORKSPACE_RUN_RECORD_DESCRIPTION,
+ PATROL_WORKSPACE_RUN_RECORD_TITLE,
+ PATROL_WORKSPACE_SETUP_DESCRIPTION,
+ PATROL_WORKSPACE_SETUP_TITLE,
+} from './patrolControlPresentation';
import type { PatrolIntelligenceState } from './usePatrolIntelligenceState';
export function PatrolIntelligenceWorkspace(props: { state: PatrolIntelligenceState }) {
const state = props.state;
const findingsBadgePresentation = () =>
getPatrolFindingsBadgePresentation(state.findingsTabBadgeFindings());
+ const queueDisplayGroups = createMemo(() =>
+ buildPatrolFindingDisplayGroups(state.findingsTabBadgeFindings()),
+ );
+ const queueIssueCount = createMemo(
+ () => state.findingsTabBadgeCount() ?? state.findingsTabBadgeFindings().length,
+ );
+ const queueAffectedResourceCount = createMemo(() => queueDisplayGroups().length);
+ const queueBadgeLabel = createMemo(() =>
+ getPatrolQueueBadgeLabel({
+ affectedResourceCount: queueAffectedResourceCount(),
+ findingCount: queueIssueCount(),
+ }),
+ );
+ const isHistoryOpen = () => state.activeTab() === 'history';
+ const isSetupOnly = () =>
+ !isHistoryOpen() && !state.selectedRun() && state.shouldShowPatrolSetupOnly();
+ const setupAction = getPatrolProviderSettingsAction();
+ const setupFinding = () => state.findingsTabBadgeFindings().find(isPatrolRuntimeFinding);
+ const setupReason = () => {
+ const finding = setupFinding();
+ return getPatrolSetupIssueReason({
+ setupFindingTitle: finding ? getFindingTitlePresentation(finding).label : undefined,
+ readinessSummary: state.patrolReadiness()?.summary,
+ triggerDisabledReason: state.triggerPatrolDisabledReason(),
+ blockedReason: state.blockedReason(),
+ });
+ };
+ const workspaceTitle = () =>
+ isHistoryOpen()
+ ? 'Patrol history'
+ : isSetupOnly()
+ ? PATROL_WORKSPACE_SETUP_TITLE
+ : state.selectedRun()
+ ? PATROL_WORKSPACE_RUN_RECORD_TITLE
+ : PATROL_WORKSPACE_QUEUE_TITLE;
+ const workspaceDescription = () =>
+ isHistoryOpen()
+ ? PATROL_WORKSPACE_HISTORY_DESCRIPTION
+ : isSetupOnly()
+ ? PATROL_WORKSPACE_SETUP_DESCRIPTION
+ : state.selectedRun()
+ ? PATROL_WORKSPACE_RUN_RECORD_DESCRIPTION
+ : getPatrolQueueWorkspaceDescription({
+ autonomyLevel: state.autonomyLevel(),
+ autonomyLocked: state.autoFixLocked(),
+ affectedResourceCount: queueAffectedResourceCount(),
+ findingCount: queueIssueCount(),
+ });
+ const openHistory = () => {
+ state.setActiveTab('history');
+ state.setFindingsFilterOverride(undefined);
+ };
+ const closeHistory = () => {
+ state.setActiveTab('findings');
+ };
+ const selectHistoryRun = (run: ReturnType<typeof state.selectedRun>) => {
+ state.setSelectedRun(run);
+ if (run) {
+ state.setActiveTab('findings');
+ }
+ };
+ const selectedRunStatus = () => {
+ const run = state.selectedRun();
+ if (!run) return null;
+ return getPatrolRunStatusPresentation(run.status ?? 'unknown', run.error_count ?? 0);
+ };
+ const selectedRunSummary = () => {
+ const run = state.selectedRun();
+ return run ? getPatrolRunRecordSummaryPresentation(run) : null;
+ };
return (
<>
@@ -44,80 +126,135 @@ export function PatrolIntelligenceWorkspace(props: { state: PatrolIntelligenceSt
}}
/>
- <div class="flex items-center gap-1 border-b border-border">
- <button
- type="button"
- onClick={() => state.setActiveTab('findings')}
- class={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
- state.activeTab() === 'findings'
- ? 'border-blue-500 text-base-content'
- : 'border-transparent text-muted hover:text-base-content hover:border-border'
- }`}
- >
- Findings
- <Show when={(state.findingsTabBadgeCount() ?? 0) > 0}>
- {' '}
- <MetadataBadge aria-hidden="true" tone={findingsBadgePresentation().tone} size="xs">
- {state.findingsTabBadgeCount()}
- </MetadataBadge>
- </Show>
- </button>
- <button
- type="button"
- onClick={() => {
- state.setActiveTab('history');
- state.setFindingsFilterOverride(undefined);
- }}
- class={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
- state.activeTab() === 'history'
- ? 'border-blue-500 text-base-content'
- : 'border-transparent text-muted hover:text-base-content hover:border-border'
- }`}
- >
- Runs
- <Show when={state.displayRunHistory().length > 0}>
- {' '}
- <MetadataBadge aria-hidden="true" tone="muted" size="xs">
- {state.displayRunHistory().length}
- </MetadataBadge>
- </Show>
- </button>
+ <div class="flex flex-wrap items-start justify-between gap-3 border-b border-border pb-3">
+ <div class="min-w-0">
+ <div class="flex min-w-0 flex-wrap items-center gap-2">
+ <h2 class="text-sm font-semibold text-base-content">{workspaceTitle()}</h2>
+ <Show
+ when={
+ !isHistoryOpen() &&
+ !isSetupOnly() &&
+ !state.selectedRun() &&
+ Boolean(queueBadgeLabel())
+ }
+ >
+ <MetadataBadge aria-hidden="true" tone={findingsBadgePresentation().tone} size="xs">
+ {queueBadgeLabel()}
+ </MetadataBadge>
+ </Show>
+ </div>
+ <p class="mt-1 text-xs text-muted">{workspaceDescription()}</p>
+ </div>
+ <Show when={!isSetupOnly()}>
+ <div class="flex flex-wrap items-center gap-2">
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ class="gap-1.5"
+ onClick={() => (isHistoryOpen() ? closeHistory() : openHistory())}
+ >
+ <HistoryIcon class="h-4 w-4" />
+ {isHistoryOpen() ? PATROL_WORKSPACE_QUEUE_TITLE : 'History'}
+ </Button>
+ </div>
+ </Show>
</div>
<Show when={state.activeTab() === 'findings'}>
<Show when={state.selectedRun()}>
{(run) => (
- <div class="flex items-center justify-between px-3 py-2 rounded-md bg-blue-50 dark:bg-blue-900 border border-blue-200 dark:border-blue-800 text-xs text-blue-700 dark:text-blue-300">
- <span>
- Filtered to run {formatRelativeTime(run().started_at, { compact: true })} (
- {formatTriggerReason(run().trigger_reason)})
- <Show when={state.selectedRunHasFindingsSnapshot() === false}>
- {' · '}Findings snapshot unavailable
+ <div class="flex flex-col gap-3 rounded-md border border-blue-200 bg-blue-50 px-3 py-3 text-blue-800 dark:border-blue-800 dark:bg-blue-950/40 dark:text-blue-200 sm:flex-row sm:items-start sm:justify-between">
+ <div class="min-w-0 space-y-1">
+ <div class="flex flex-wrap items-center gap-2 text-xs">
+ <span class="font-semibold text-blue-950 dark:text-blue-100">
+ Patrol run {formatRelativeTime(run().started_at, { compact: true })}
+ </span>
+ <span>{formatTriggerReason(run().trigger_reason)}</span>
+ <Show when={selectedRunStatus()}>
+ {(status) => (
+ <StatusIndicatorBadge
+ label={status().label}
+ variant={status().variant}
+ size="xs"
+ shape="rounded"
+ />
+ )}
+ </Show>
+ <Show when={state.selectedRunHasFindingsSnapshot() === false}>
+ <MetadataBadge tone="info" size="xs" shape="rounded">
+ {PATROL_FINDING_RECORD_UNAVAILABLE_LABEL}
+ </MetadataBadge>
+ </Show>
+ </div>
+ <Show when={selectedRunSummary()}>
+ {(summary) => (
+ <p class="text-xs leading-5 text-blue-800 dark:text-blue-200">
+ {summary().summary} {summary().outcome}
+ </p>
+ )}
+ </Show>
+ <Show when={selectedRunSummary()?.action}>
+ {(action) => (
+ <ButtonLink
+ href={action().href}
+ variant="secondary"
+ size="sm"
+ class="mt-1 gap-1.5"
+ >
+ <SettingsIcon class="h-4 w-4" aria-hidden="true" />
+ {action().label}
+ </ButtonLink>
+ )}
</Show>
- </span>
+ </div>
<button
type="button"
onClick={() => state.setSelectedRun(null)}
- class="font-medium hover:underline"
+ class="w-fit shrink-0 text-xs font-medium text-blue-700 hover:underline dark:text-blue-300"
>
- Clear filter
+ Show current work
</button>
</div>
)}
</Show>
- <FindingsPanel
- filterOverride={state.selectedRun() ? 'all' : state.findingsFilterOverride()}
- filterFindingIds={state.selectedRunFindingIds()}
- scopeResourceIds={state.selectedRunScopeResourceIds()}
- scopeResourceTypes={state.selectedRun()?.scope_resource_types}
- showScopeWarnings={Boolean(state.selectedRun())}
- runtimeState={state.runtimeState()}
- blockedReason={state.blockedReason()}
- overallHealth={state.intelligenceSummary()?.overall_health}
- findingsSource="patrol"
- runSnapshot={state.selectedRun() ?? undefined}
- />
+ <Show
+ when={isSetupOnly()}
+ fallback={
+ <FindingsPanel
+ filterOverride={state.selectedRun() ? 'all' : state.findingsFilterOverride()}
+ filterFindingIds={state.selectedRunFindingIds()}
+ scopeResourceIds={state.selectedRunScopeResourceIds()}
+ scopeResourceTypes={state.selectedRun()?.scope_resource_types}
+ showScopeWarnings={Boolean(state.selectedRun())}
+ runtimeState={state.runtimeState()}
+ blockedReason={state.blockedReason()}
+ overallHealth={state.intelligenceSummary()?.overall_health}
+ historicalRegressionCount={state.historicalRegressionCount()}
+ patrolRuns={state.patrolRunHistory.value() ?? []}
+ findingsSource="patrol"
+ runSnapshot={state.selectedRun() ?? undefined}
+ showControls={!state.selectedRun()}
+ onAssistantHandoff={(finding) => state.handleAssistantFindingHandoff(finding.id)}
+ />
+ }
+ >
+ <div class="rounded-md border border-border bg-surface-alt p-4">
+ <div class="flex flex-wrap items-start justify-between gap-3">
+ <div class="min-w-0 max-w-2xl">
+ <h3 class="text-sm font-semibold text-base-content">
+ Provider needs attention
+ </h3>
+ <p class="mt-2 text-xs text-muted">Issue: {setupReason()}</p>
+ </div>
+ <ButtonLink href={setupAction.href} variant="primary" size="sm" class="gap-1.5">
+ <SettingsIcon class="h-4 w-4" aria-hidden="true" />
+ {setupAction.label}
+ </ButtonLink>
+ </div>
+ </div>
+ </Show>
</Show>
<Show when={state.activeTab() === 'history'}>
@@ -125,79 +262,10 @@ export function PatrolIntelligenceWorkspace(props: { state: PatrolIntelligenceSt
runs={state.displayRunHistory()}
loading={state.patrolRunHistory.loading()}
selectedRun={state.selectedRun()}
- onSelectRun={state.setSelectedRun}
+ onSelectRun={selectHistoryRun}
patrolStream={state.patrolStream}
/>
</Show>
-
- <Show when={state.shouldSurfaceInvestigationContext()}>
- <section class="rounded-md border border-border-subtle bg-surface-alt/40 p-3">
- <div class="flex flex-wrap items-start justify-between gap-3">
- <div>
- <p class="text-xs font-semibold uppercase tracking-[0.16em] text-muted">
- {PATROL_SUPPORTING_CONTEXT_TITLE}
- </p>
- <p class="mt-1 text-sm text-muted">{PATROL_SUPPORTING_CONTEXT_DESCRIPTION}</p>
- <Show when={state.investigationContextSummary()}>
- <p class="mt-1 text-xs text-base-content">{state.investigationContextSummary()}</p>
- </Show>
- </div>
-
- <Button
- type="button"
- variant="secondary"
- size="sm"
- class="px-3"
- onClick={() => state.setShowInvestigationContext((value) => !value)}
- >
- {getPatrolSupportingContextToggleLabel(state.showInvestigationContext())}
- </Button>
- </div>
-
- <Show when={state.showInvestigationContext()}>
- <div class="mt-4 space-y-4">
- <div class="rounded-md border border-border-subtle bg-base px-3 py-2">
- <p class="text-[11px] font-semibold uppercase tracking-[0.16em] text-muted">
- {PATROL_SUPPORTING_CONTEXT_EVIDENCE_LABEL}
- </p>
- <p class="mt-1 text-xs text-muted">{PATROL_SUPPORTING_CONTEXT_EVIDENCE_NOTE}</p>
- </div>
-
- <div class="grid gap-4 lg:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)]">
- <Show when={state.recentChangeCount() > 0}>
- <ResourceChangeSummary
- class="space-y-0"
- title="Recent changes"
- subtitle={PATROL_SUPPORTING_CONTEXT_CHANGE_SUBTITLE}
- changes={state.supportingRecentChanges()}
- maxChanges={3}
- compact
- />
- </Show>
-
- <div class="space-y-4">
- <Show when={state.correlations().length > 0}>
- <ResourceCorrelationSummary
- title="Learned correlations"
- correlations={state.correlations()}
- summaryText={getPatrolSupportingContextCorrelationSummary(
- state.correlationTotal(),
- )}
- />
- </Show>
-
- <ResourcePolicySummary
- posture={state.policyPosture()}
- title="Policy coverage"
- subtitle={PATROL_SUPPORTING_CONTEXT_POLICY_SUBTITLE}
- resourceCountLabel="policy-covered resources"
- />
- </div>
- </div>
- </div>
- </Show>
- </section>
- </Show>
</>
);
}
diff --git a/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceHeader.test.ts b/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceHeader.test.ts
index 1a404f5a36..fd7f3b0adf 100644
--- a/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceHeader.test.ts
+++ b/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceHeader.test.ts
@@ -2,7 +2,14 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
-import { getPatrolConfigurationFailureInlineDetails } from '../PatrolIntelligenceHeader';
+import {
+ PATROL_AUTONOMY_POLICY_PRESENTATION,
+ getPatrolConfigurationFailureInlineDetails,
+} from '../PatrolIntelligenceHeader';
+import {
+ getPatrolAutonomyAvailabilityPresentation,
+ PATROL_AUTONOMY_RUNTIME_REQUIRED_REASON,
+} from '../patrolAutonomyAvailability';
const headerSource = readFileSync(
resolve(__dirname, '..', 'PatrolIntelligenceHeader.tsx'),
@@ -10,10 +17,10 @@ const headerSource = readFileSync(
);
describe('PatrolIntelligenceHeader', () => {
- it('keeps Patrol configuration readiness context visible inline', () => {
+ it('keeps Patrol mode readiness context visible inline', () => {
expect(
getPatrolConfigurationFailureInlineDetails({
- message: 'Patrol configuration could not be saved.',
+ message: 'Patrol mode could not be saved.',
code: 'patrol_readiness_not_ready',
readiness: {
status: 'not_ready',
@@ -26,7 +33,7 @@ describe('PatrolIntelligenceHeader', () => {
}),
).toEqual([
'patrol_readiness_not_ready · model_unsupported_tools',
- 'Readiness: The selected Patrol model is a reasoning-only model family that commonly does not emit tool calls.',
+ 'Setup: The selected Patrol model is a reasoning-only model family that commonly does not emit tool calls.',
'Provider: openrouter',
'Model: openrouter:deepseek/deepseek-r1',
]);
@@ -35,23 +42,245 @@ describe('PatrolIntelligenceHeader', () => {
it('falls back to the blocked cause when readiness cause is absent', () => {
expect(
getPatrolConfigurationFailureInlineDetails({
- message: 'Patrol configuration could not be saved.',
+ message: 'Patrol mode could not be saved.',
code: 'patrol_autonomy_pro_required',
blockedCause: 'license_required',
}),
).toEqual(['patrol_autonomy_pro_required · license_required']);
});
- it('keeps trigger runtime status in the always-visible header chrome', () => {
+ it('keeps trigger runtime status in the header chrome after setup', () => {
expect(headerSource).toContain('getPatrolTriggerStatusSummary');
expect(headerSource).toContain('state.patrolStatus()?.trigger_status');
- expect(headerSource).toContain('Trigger status:');
+ expect(headerSource).toContain('!state.shouldShowPatrolSetupOnly() && triggerStatusSummary()');
+ expect(headerSource).not.toContain('Automation:');
+ expect(headerSource).not.toContain('Trigger status:');
+ });
+
+ it('keeps Patrol mode visible while setup blocks running and configuration', () => {
+ const setupOnlyGateCount = headerSource.match(/!state\.shouldShowPatrolSetupOnly\(\)/g)?.length;
+
+ expect(setupOnlyGateCount).toBeGreaterThanOrEqual(3);
+ expect(headerSource).toContain('<Show when={!state.shouldShowPatrolSetupOnly()}>');
+ expect(headerSource).toContain('id={PATROL_CONTROL_ANCHOR}');
+ expect(headerSource).not.toContain(
+ '<Show when={!state.shouldShowPatrolSetupOnly()}>\n <div\n id={PATROL_CONTROL_ANCHOR}',
+ );
+ expect(headerSource).toContain('Open Patrol settings');
+ expect(headerSource).toContain("settingsTabPath('system-ai-patrol')");
+ expect(headerSource).not.toContain('Patrol schedule and model settings');
+ expect(headerSource).toContain('Run Patrol');
+ });
+
+ it('turns provider-blocked manual run controls into setup actions', () => {
+ expect(headerSource).toContain('runBlockedByProviderSetup');
+ expect(headerSource).toContain("state.patrolReadiness()?.status === 'not_ready'");
+ expect(headerSource).toContain('getPatrolProviderSettingsAction');
+ expect(headerSource).toContain('providerSetupAction.href');
+ expect(headerSource).toContain('Fix provider');
+ expect(headerSource).toContain('Fix Patrol provider:');
+ expect(headerSource).toContain('runButtonDisabled');
+ expect(headerSource).not.toContain('!state.canTriggerPatrol() ||');
+ });
+
+ it('keeps manual page sync out of the primary Patrol header actions', () => {
+ expect(headerSource).not.toContain('handleRefreshPatrol');
+ expect(headerSource).not.toContain('Sync page data');
+ expect(headerSource).not.toContain('RefreshCwIcon');
+ expect(headerSource).not.toContain('animate-spin');
+ expect(headerSource).not.toContain('Refresh Patrol');
+ });
+
+ it('makes Patrol mode a simple four-level choice without rendering plan-locked paid modes', () => {
+ expect(PATROL_AUTONOMY_POLICY_PRESENTATION).toEqual({
+ monitor: {
+ label: 'Watch only',
+ detail: 'Patrol reports issues without making changes.',
+ compactLabel: 'Watch only',
+ },
+ approval: {
+ label: 'Ask first',
+ detail: 'Patrol investigates issues and prepares fixes. You approve every change.',
+ compactLabel: 'Ask first',
+ },
+ assisted: {
+ label: 'Safe auto-fix',
+ detail: 'Patrol fixes safe policy-allowed issues. It asks before anything riskier.',
+ compactLabel: 'Safe auto-fix',
+ },
+ full: {
+ label: 'Autopilot',
+ detail:
+ 'Patrol handles policy-approved issues automatically. It asks only when policy requires approval.',
+ compactLabel: 'Autopilot',
+ },
+ });
+ expect(headerSource).toContain("['monitor', 'approval', 'assisted', 'full']");
+ expect(headerSource).toContain("state.autoFixLocked() ? 'monitor' : state.autonomyLevel()");
+ expect(headerSource).toContain('value={effectiveAutonomyLevel()}');
+ expect(headerSource).toContain('canChooseAutonomyLevel');
+ expect(headerSource).toContain('shouldShowAutonomyOptions');
+ expect(headerSource).toContain('shouldShowAutonomyActionColumn');
+ expect(headerSource).toContain("autonomyAvailability().kind === 'runtime_locked'");
+ expect(headerSource).toContain('<Show when={shouldShowAutonomyOptions()}>');
+ expect(headerSource).toContain('<Show when={shouldShowAutonomyActionColumn()}>');
+ expect(headerSource).toContain(
+ "const lockedPaidMode = state.autoFixLocked() && level !== 'monitor'",
+ );
+ expect(headerSource).toContain('disabled: lockedPaidMode');
+ expect(headerSource).toContain('compactLabel: presentation.compactLabel');
+ expect(headerSource).not.toContain('showPlanLockedModeAction');
+ expect(headerSource).toContain('Patrol mode');
+ expect(headerSource).not.toContain('getPatrolAutonomyContractPresentation');
+ expect(headerSource).not.toContain('selectedAutonomyContract');
+ expect(headerSource).not.toContain('showControlDetails');
+ expect(headerSource).not.toContain("'Limits'");
+ expect(headerSource).not.toContain('Hide limits');
+ expect(headerSource).not.toContain('Hard limits');
+ expect(headerSource).not.toContain('requires Pulse Pro');
+ expect(headerSource).not.toContain('const isProLocked = () =>');
+ expect(headerSource).not.toContain('visualLabel: proLocked');
+ expect(headerSource).not.toContain('Current mode:');
+ expect(headerSource).not.toContain('How much can Patrol do?');
+ expect(headerSource).not.toContain("level === 'full' ? 'assisted'");
+ expect(headerSource).not.toContain('Autonomous critical remediation');
+ });
+
+ it('keeps Patrol mode inline and routes configuration to settings', () => {
+ const autonomyControlCallCount =
+ headerSource.match(/renderAutonomyPolicyControl\(\{/g)?.length ?? 0;
+ const configurationAutonomyIndex = headerSource.indexOf("ariaLabel: 'Patrol mode'");
+
+ expect(autonomyControlCallCount).toBe(1);
+ expect(configurationAutonomyIndex).toBeGreaterThan(-1);
+ expect(headerSource).toContain('Open Patrol settings');
+ expect(headerSource).toContain("settingsTabPath('system-ai-patrol')");
+ expect(headerSource).not.toContain('Schedule & model');
+ expect(headerSource).not.toContain('Patrol schedule and model settings');
+ expect(headerSource).not.toContain('label="Provider model"');
+ expect(headerSource).not.toContain('label="Run Every"');
+ expect(headerSource).not.toContain('FormSelect');
+ expect(headerSource).not.toContain('showAdvancedSettings');
+ expect(headerSource).not.toContain('Advanced settings');
+ expect(headerSource).not.toContain('Advanced Patrol settings');
+ expect(headerSource).not.toContain('Done');
+ expect(headerSource).not.toContain('Set Patrol mode');
+ expect(headerSource).not.toContain('Save Patrol mode');
+ expect(headerSource).not.toContain('Patrol policy');
+ expect(headerSource).not.toContain("variant: 'prominent'");
+ expect(headerSource).not.toContain('Patrol Configuration');
+ expect(headerSource).not.toContain('Apply Configuration');
+ });
+
+ it('keeps the Patrol model catalog out of the operator page', () => {
+ expect(headerSource).not.toContain('showModelCatalog');
+ expect(headerSource).not.toContain('Provider model');
+ expect(headerSource).not.toContain('Change model');
+ expect(headerSource).not.toContain('Hide model list');
+ expect(headerSource).not.toContain('Choose available model');
+ expect(headerSource).not.toContain('formatPatrolModelOptionLabel(model)');
+ });
+
+ it('explains when Patrol mode is locked by plan or runtime', () => {
+ expect(
+ getPatrolAutonomyAvailabilityPresentation({
+ autoFixLocked: false,
+ planUpgradeDestination: {
+ href: '/settings/pulse-intelligence/billing/plan',
+ external: false,
+ },
+ }),
+ ).toMatchObject({
+ kind: 'available',
+ locked: false,
+ title: 'Patrol mode available',
+ body: 'Choose the mode for this install.',
+ });
+
+ expect(
+ getPatrolAutonomyAvailabilityPresentation({
+ autoFixLocked: true,
+ planUpgradeDestination: {
+ href: '/settings/pulse-intelligence/billing/plan',
+ external: false,
+ },
+ }),
+ ).toMatchObject({
+ kind: 'plan_locked',
+ locked: true,
+ title: 'Watch only',
+ body: 'This install watches infrastructure and shows issues.',
+ actionLabel: 'Plans & Billing',
+ destination: {
+ href: '/settings/pulse-intelligence/billing/plan',
+ external: false,
+ },
+ });
+ expect(headerSource).toContain('showAutonomyPlanBillingAction');
+ expect(headerSource).toContain("autonomyAvailability().kind === 'plan_locked'");
+ expect(headerSource).toContain('CreditCardIcon');
+ expect(headerSource).toContain('{autonomyAvailability().actionLabel}');
+
+ const hiddenUpgradePresentation = getPatrolAutonomyAvailabilityPresentation({
+ autoFixLocked: true,
+ upgradePromptsHidden: true,
+ planUpgradeDestination: {
+ href: '/settings/pulse-intelligence/billing/plan',
+ external: false,
+ },
+ });
+ expect(hiddenUpgradePresentation).toMatchObject({
+ kind: 'plan_locked',
+ locked: true,
+ title: 'Watch only',
+ body: 'This install watches infrastructure and shows issues.',
+ });
+ expect(hiddenUpgradePresentation).not.toHaveProperty('actionLabel');
+ expect(hiddenUpgradePresentation).not.toHaveProperty('destination');
+
+ const hiddenCommercialPresentation = getPatrolAutonomyAvailabilityPresentation({
+ autoFixLocked: true,
+ commercialSurfacesHidden: true,
+ planUpgradeDestination: {
+ href: '/settings/pulse-intelligence/billing/plan',
+ external: false,
+ },
+ });
+ expect(hiddenCommercialPresentation).toMatchObject({
+ kind: 'plan_locked',
+ locked: true,
+ title: 'Watch only',
+ body: 'This install watches infrastructure and shows issues.',
+ });
+ expect(hiddenCommercialPresentation).not.toHaveProperty('actionLabel');
+ expect(hiddenCommercialPresentation).not.toHaveProperty('destination');
+
+ expect(
+ getPatrolAutonomyAvailabilityPresentation({
+ autoFixLocked: true,
+ runtimeCapabilityBlock: {
+ key: 'ai_autofix',
+ reason: PATROL_AUTONOMY_RUNTIME_REQUIRED_REASON,
+ action_url: 'https://pulserelay.pro/download.html',
+ },
+ runtime: { build: 'community', label: 'Pulse Community runtime' },
+ planUpgradeDestination: {
+ href: '/settings/pulse-intelligence/billing/plan',
+ external: false,
+ },
+ }),
+ ).toMatchObject({
+ kind: 'runtime_locked',
+ locked: true,
+ title: 'Pulse Pro runtime required',
+ actionLabel: 'Open Pro downloads',
+ destination: { href: 'https://pulserelay.pro/download.html', external: true },
+ });
});
it('keeps trust counters out of the page header chrome', () => {
- // The Patrol assessment strip owns the default status readout. The header
- // should stay focused on title, recency, and controls rather than adding
- // another active/regressed summary row.
+ // Current work and deliberate history review own trust
+ // state. The header should stay focused on title, recency, and controls.
expect(headerSource).not.toContain('aria-label="Patrol trust summary header"');
expect(headerSource).not.toContain('state.patrolStatus()?.trust');
expect(headerSource).not.toContain('trust.currently_active');
diff --git a/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceSummary.test.tsx b/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceSummary.test.tsx
deleted file mode 100644
index 07daac3490..0000000000
--- a/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceSummary.test.tsx
+++ /dev/null
@@ -1,438 +0,0 @@
-import { cleanup, render, screen } from '@solidjs/testing-library';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-
-import type { PatrolRunRecord } from '@/api/patrol';
-import { PatrolIntelligenceSummary } from '../PatrolIntelligenceSummary';
-import type { PatrolIntelligenceState } from '../usePatrolIntelligenceState';
-
-describe('PatrolIntelligenceSummary', () => {
- afterEach(() => {
- cleanup();
- vi.restoreAllMocks();
- });
-
- it('keeps the compact assessment strip descriptive only', () => {
- const patrolState = createPatrolState();
- render(() => <PatrolIntelligenceSummary state={patrolState} />);
-
- expect(screen.getByText('Patrol assessment')).toBeInTheDocument();
- expect(screen.getByText('1 critical · 84/100')).toBeInTheDocument();
- expect(screen.queryByTestId('patrol-recommended-next-step')).not.toBeInTheDocument();
- expect(screen.queryByTestId('patrol-recommended-next-step-action')).not.toBeInTheDocument();
- expect(screen.queryByTestId('patrol-summary-details-toggle')).not.toBeInTheDocument();
- expect(screen.queryByTestId('patrol-summary-details')).not.toBeInTheDocument();
- expect(screen.queryByTestId('patrol-assessment-assistant-button')).not.toBeInTheDocument();
- });
-
- it('surfaces recent activity mix and trigger mode in the compact assessment strip', () => {
- const patrolState = {
- ...createPatrolState(),
- patrolRunHistory: makePatrolRunHistory([
- makePatrolRunRecord({
- id: 'run-alert-scoped',
- started_at: todayAt(11, 0),
- completed_at: todayAt(11, 2),
- type: 'scoped',
- trigger_reason: 'alert_fired',
- new_findings: 1,
- }),
- makePatrolRunRecord({
- id: 'run-anomaly-scoped',
- started_at: todayAt(10, 15),
- completed_at: todayAt(10, 16),
- type: 'scoped',
- trigger_reason: 'anomaly',
- }),
- makePatrolRunRecord({
- id: 'run-full-review',
- started_at: todayAt(9, 0),
- completed_at: todayAt(9, 3),
- type: 'full',
- trigger_reason: 'scheduled',
- }),
- ]),
- patrolStatus: () => ({
- trigger_status: {
- running: false,
- pending_triggers: 4,
- current_interval_ms: 10000,
- recent_events: 12,
- is_busy_mode: true,
- alert_triggers_enabled: true,
- anomaly_triggers_enabled: false,
- },
- }),
- } as unknown as PatrolIntelligenceState;
-
- render(() => <PatrolIntelligenceSummary state={patrolState} />);
-
- expect(
- screen.getByText('Recent activity mix: 1 full, 1 alert-triggered, 1 anomaly-triggered'),
- ).toBeInTheDocument();
- expect(
- screen.getByText('Trigger mode: 4 queued · busy mode · anomalies off'),
- ).toBeInTheDocument();
- });
-
- it('explains runtime-blocked event triggers in the compact assessment strip', () => {
- const patrolState = {
- ...createPatrolState(),
- patrolStatus: () => ({
- trigger_status: {
- running: false,
- pending_triggers: 0,
- current_interval_ms: 300000,
- recent_events: 0,
- is_busy_mode: false,
- alert_triggers_enabled: true,
- anomaly_triggers_enabled: true,
- 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 unknown as PatrolIntelligenceState;
-
- render(() => <PatrolIntelligenceSummary state={patrolState} />);
-
- expect(
- screen.getByText(
- 'Trigger mode: Automatic Patrol checks from alerts and anomalies are paused by the local development safety guard. Manual Patrol still works.',
- ),
- ).toBeInTheDocument();
- });
-
- it('does not surface disabled run actions on the compact assessment strip', () => {
- const patrolState = {
- ...createPatrolState(),
- activePatrolFindings: () => [],
- canTriggerPatrol: () => false,
- correlationTotal: () => 0,
- correlations: () => [],
- intelligenceSummary: () => ({
- timestamp: '2026-05-06T12:15:00Z',
- overall_health: {
- grade: 'C',
- score: 65,
- trend: 'stable',
- factors: [
- {
- category: 'coverage',
- name: 'Coverage',
- impact: -10,
- description: 'Patrol coverage is incomplete.',
- },
- ],
- prediction: 'Patrol coverage is incomplete.',
- },
- findings_count: {
- critical: 0,
- warning: 0,
- watch: 0,
- info: 0,
- total: 0,
- },
- predictions_count: 0,
- recent_changes_count: 0,
- recent_changes: [],
- policy_posture: {
- total_resources: 4,
- sensitivity_counts: {},
- routing_counts: {},
- },
- learning: {
- resources_with_knowledge: 0,
- total_notes: 0,
- resources_with_baselines: 0,
- patterns_detected: 0,
- correlations_learned: 0,
- incidents_tracked: 0,
- },
- }),
- manualRunRequested: () => false,
- patrolRunHistory: makePatrolRunHistory([
- makePatrolRunRecord({
- id: 'run-scoped-1',
- started_at: '2026-05-06T12:00:00Z',
- completed_at: '2026-05-06T12:01:00Z',
- type: 'scoped',
- status: 'error',
- error_count: 1,
- }),
- ]),
- patrolStream: {
- phase: () => 'Running',
- currentTool: () => '',
- tokens: () => 0,
- resynced: () => false,
- resyncReason: () => '',
- bufferStartSeq: () => 0,
- bufferEndSeq: () => 0,
- outputTruncated: () => false,
- reconnectCount: () => 0,
- isStreaming: () => true,
- errorMessage: () => '',
- },
- runtimeState: () => 'running',
- summaryStats: () => ({
- criticalFindings: 0,
- warningFindings: 0,
- totalActive: 0,
- fixedCount: 0,
- hasAnyPatrolFindings: false,
- }),
- triggerPatrolDisabledReason: () => 'Patrol is already running',
- } satisfies PatrolIntelligenceState;
-
- render(() => <PatrolIntelligenceSummary state={patrolState} />);
-
- expect(screen.queryByTestId('patrol-recommended-next-step')).not.toBeInTheDocument();
- expect(screen.queryByTestId('patrol-recommended-next-step-action')).not.toBeInTheDocument();
- expect(screen.queryByTestId('patrol-summary-details-toggle')).not.toBeInTheDocument();
- });
-
- it('does not leave the loading shell behind once patrol evidence has rendered', () => {
- const patrolState = {
- ...createPatrolState(),
- initialSurfaceReady: () => false,
- intelligenceSummary: () => null,
- } satisfies PatrolIntelligenceState;
-
- render(() => <PatrolIntelligenceSummary state={patrolState} />);
-
- expect(screen.queryByTestId('patrol-summary-loading')).not.toBeInTheDocument();
- });
-});
-
-function todayAt(hours: number, minutes: number): string {
- const value = new Date();
- value.setHours(hours, minutes, 0, 0);
- return value.toISOString();
-}
-
-function createPatrolState(): PatrolIntelligenceState {
- return {
- activePatrolFindings: () => [
- {
- id: 'finding-1',
- source: 'ai-patrol',
- resourceId: 'vm-100',
- resourceName: 'web-server',
- resourceType: 'vm',
- category: 'performance',
- severity: 'critical',
- title: 'High CPU usage',
- description: 'CPU stayed above 95%.',
- detectedAt: '2026-05-06T12:00:00Z',
- lastSeenAt: '2026-05-06T12:10:00Z',
- status: 'active',
- investigationStatus: 'completed',
- investigationOutcome: 'fix_queued',
- loopState: 'awaiting_approval',
- timesRaised: 3,
- regressionCount: 1,
- investigationRecord: {
- id: 'record-1',
- finding_id: 'finding-1',
- subject: {
- resource_id: 'vm-100',
- resource_name: 'web-server',
- resource_type: 'vm',
- node: 'pve-1',
- },
- trigger: { detected_at: '2026-05-06T12:00:00Z' },
- status: 'completed',
- outcome: 'fix_queued',
- confidence: 'high',
- conclusion: 'Backup job saturated CPU.',
- recommended_action: 'Approve a controlled restart after the backup completes.',
- evidence: [{ kind: 'metrics', summary: 'CPU stayed above 95% for 10 minutes' }],
- proposed_fix: {
- id: 'fix-1',
- description: 'Restart the workload service',
- commands: ['systemctl restart workload.service'],
- risk_level: 'medium',
- destructive: false,
- },
- verification: ['CPU returned below 50%'],
- tools_used: ['ssh.exec'],
- started_at: '2026-05-06T12:00:00Z',
- },
- },
- ],
- blockedReason: () => undefined,
- canTriggerPatrol: () => true,
- circuitBreakerStatus: () => undefined,
- correlationTotal: () => 2,
- correlations: () => [
- {
- source_id: 'backup-job',
- source_name: 'Nightly backup job',
- source_type: 'job',
- target_id: 'vm-100',
- target_name: 'web-server',
- target_type: 'vm',
- event_pattern: 'backup_started -> cpu_spike',
- occurrences: 4,
- avg_delay: 120000000000,
- confidence: 0.92,
- last_seen: '2026-05-06T12:08:00Z',
- description: 'CPU pressure usually follows this backup job.',
- },
- ],
- hasInvestigationContext: () => true,
- initialSurfaceReady: () => true,
- isTriggeringPatrol: () => false,
- intelligenceSummary: () => ({
- overall_health: {
- grade: 'B',
- score: 84,
- factors: [],
- prediction: 'Patrol surfaced one active critical finding.',
- },
- recent_changes_count: 2,
- recent_changes: [
- {
- id: 'change-1',
- observedAt: '2026-05-06T12:08:00Z',
- resourceId: 'vm-100',
- kind: 'metric_anomaly',
- sourceType: 'heuristic',
- sourceAdapter: 'proxmox_adapter',
- confidence: 'high',
- relatedResources: ['backup-job'],
- reason: 'CPU spike after backup job',
- },
- {
- id: 'change-2',
- observedAt: '2026-05-06T12:07:00Z',
- resourceId: 'vm-100',
- kind: 'command_executed',
- sourceType: 'agent_action',
- sourceAdapter: 'agent:ops-helper',
- confidence: 'medium',
- reason: 'systemctl restart workload.service',
- metadata: {
- command: 'systemctl restart workload.service',
- },
- },
- ],
- policy_posture: {
- total_resources: 4,
- sensitivity_counts: {},
- routing_counts: {},
- },
- }),
- investigationContextSummary: () =>
- '2 recent changes · 2 correlations · 4 policy-covered resources',
- handleRunPatrol: vi.fn(),
- manualRunRequested: () => false,
- patrolRunHistory: makePatrolRunHistory([
- makePatrolRunRecord({
- id: 'run-1',
- started_at: '2026-05-06T12:00:00Z',
- completed_at: '2026-05-06T12:10:00Z',
- status: 'issues_found',
- resources_checked: 12,
- new_findings: 1,
- finding_ids: ['finding-1'],
- }),
- ]),
- patrolStatus: () => ({
- last_patrol_at: '2026-05-06T12:10:00Z',
- last_activity_at: '2026-05-06T12:10:00Z',
- }),
- policyPosture: () => ({
- total_resources: 4,
- sensitivity_counts: {},
- routing_counts: {},
- }),
- recentChangeCount: () => 2,
- runtimeState: () => 'active',
- patrolStream: {
- isStreaming: () => false,
- },
- supportingRecentChanges: () => [
- {
- id: 'change-1',
- observedAt: '2026-05-06T12:08:00Z',
- resourceId: 'vm-100',
- kind: 'metric_anomaly',
- sourceType: 'heuristic',
- sourceAdapter: 'proxmox_adapter',
- confidence: 'high',
- relatedResources: ['backup-job'],
- reason: 'CPU spike after backup job',
- },
- {
- id: 'change-2',
- observedAt: '2026-05-06T12:07:00Z',
- resourceId: 'vm-100',
- kind: 'command_executed',
- sourceType: 'agent_action',
- sourceAdapter: 'agent:ops-helper',
- confidence: 'medium',
- reason: 'systemctl restart workload.service',
- metadata: {
- command: 'systemctl restart workload.service',
- },
- },
- ],
- setActiveTab: vi.fn(),
- setFindingsFilterOverride: vi.fn(),
- setSelectedRun: vi.fn(),
- summaryStats: () => ({
- criticalFindings: 1,
- warningFindings: 0,
- totalActive: 1,
- fixedCount: 0,
- hasAnyPatrolFindings: true,
- }),
- triggerPatrolDisabledReason: () => '',
- } as unknown as PatrolIntelligenceState;
-}
-
-function makePatrolRunRecord(overrides: Partial<PatrolRunRecord>): PatrolRunRecord {
- return {
- id: 'run-1',
- started_at: '2026-05-06T12:00:00Z',
- completed_at: '2026-05-06T12:10:00Z',
- duration_ms: 600000,
- type: 'full',
- resources_checked: 0,
- 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,
- auto_fix_count: 0,
- findings_summary: '',
- finding_ids: [],
- error_count: 0,
- status: 'healthy',
- triage_flags: 0,
- tool_call_count: 0,
- ...overrides,
- };
-}
-
-function makePatrolRunHistory(
- runs: PatrolRunRecord[],
-): PatrolIntelligenceState['patrolRunHistory'] {
- return {
- error: () => null,
- loading: () => false,
- refetch: vi.fn(async () => runs),
- resolvedOnce: () => true,
- value: () => runs,
- };
-}
diff --git a/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceWorkspace.test.ts b/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceWorkspace.test.ts
index 5eb3d80981..b8d3d8e1b4 100644
--- a/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceWorkspace.test.ts
+++ b/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceWorkspace.test.ts
@@ -2,6 +2,15 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
+import {
+ PATROL_WORKSPACE_HISTORY_DESCRIPTION,
+ PATROL_WORKSPACE_QUEUE_TITLE,
+ PATROL_WORKSPACE_RUN_RECORD_DESCRIPTION,
+ PATROL_WORKSPACE_RUN_RECORD_TITLE,
+ PATROL_WORKSPACE_SETUP_DESCRIPTION,
+ PATROL_WORKSPACE_SETUP_TITLE,
+} from '../patrolControlPresentation';
+
const workspaceSource = readFileSync(
resolve(__dirname, '..', 'PatrolIntelligenceWorkspace.tsx'),
'utf-8',
@@ -9,9 +18,8 @@ const workspaceSource = readFileSync(
describe('PatrolIntelligenceWorkspace trust strip', () => {
it('does not render a standalone Trust strip above the workspace tabs', () => {
- // The Patrol assessment strip owns the default active/regressed status
- // readout. The workspace should move directly into Findings/Runs instead
- // of repeating the same counters in a second strip.
+ // Current work and deliberate history review own operator-facing trust state.
+ // The workspace should not add another standalone counter strip.
expect(workspaceSource).not.toContain('state.patrolStatus()?.trust');
expect(workspaceSource).not.toContain('aria-label="Patrol trust summary"');
expect(workspaceSource).not.toContain('trust.fix_verified');
@@ -24,4 +32,48 @@ describe('PatrolIntelligenceWorkspace trust strip', () => {
expect(workspaceSource).not.toMatch(/trust\.patrol_score/);
expect(workspaceSource).not.toMatch(/trust\.health_grade/);
});
+
+ it('frames findings and run records as Patrol operation records', () => {
+ expect(workspaceSource).toContain('state.shouldShowPatrolSetupOnly()');
+ expect(workspaceSource).not.toContain('PATROL_SUPPORTING_CONTEXT');
+ expect(workspaceSource).not.toContain('ResourceCorrelationSummary');
+ expect(workspaceSource).not.toContain('ResourcePolicySummary');
+ expect(workspaceSource).not.toContain('ResourceChangeSummary');
+ expect(workspaceSource).not.toContain('showInvestigationContext');
+ expect(workspaceSource).not.toContain('shouldSurfaceInvestigationContext');
+ expect(workspaceSource).toContain('PATROL_WORKSPACE_SETUP_TITLE');
+ expect(workspaceSource).toContain('PATROL_WORKSPACE_SETUP_DESCRIPTION');
+ expect(workspaceSource).toContain('buildPatrolFindingDisplayGroups');
+ expect(workspaceSource).toContain('getPatrolQueueBadgeLabel');
+ expect(workspaceSource).toContain('queueIssueCount');
+ expect(workspaceSource).toContain('queueAffectedResourceCount');
+ expect(workspaceSource).toContain('affectedResourceCount: queueAffectedResourceCount()');
+ expect(workspaceSource).toContain('findingCount: queueIssueCount()');
+ expect(workspaceSource).toContain('getPatrolQueueWorkspaceDescription');
+ expect(workspaceSource).toContain('autonomyLevel: state.autonomyLevel()');
+ expect(workspaceSource).toContain('autonomyLocked: state.autoFixLocked()');
+ expect(workspaceSource).toContain('Boolean(queueBadgeLabel())');
+ expect(workspaceSource).toContain('{queueBadgeLabel()}');
+ const removedAllModeCopy =
+ 'Current work Patrol can ' +
+ 'watch, investigate, ask you to approve, or record under your Patrol mode.';
+ expect(workspaceSource).not.toContain(removedAllModeCopy);
+ expect(workspaceSource).toContain('Provider needs attention');
+ expect(workspaceSource).toContain('Issue:');
+ expect(workspaceSource).toContain('getPatrolProviderSettingsAction');
+ expect(workspaceSource).toContain('<Show when={!isSetupOnly()}>');
+ expect(workspaceSource).not.toContain('showControls={!state.selectedRun() && !isSetupOnly()}');
+ expect(PATROL_WORKSPACE_SETUP_TITLE).toBe('Fix provider');
+ expect(PATROL_WORKSPACE_SETUP_DESCRIPTION).toBe(
+ 'Open Provider & Models, then run Patrol from this page.',
+ );
+ expect(PATROL_WORKSPACE_QUEUE_TITLE).toBe('Current work');
+ expect(workspaceSource).not.toContain('Current Patrol findings');
+ expect(workspaceSource).toContain('Show current work');
+ expect(workspaceSource).not.toContain('Show open issues');
+ expect(workspaceSource).toContain('!state.selectedRun()');
+ expect(PATROL_WORKSPACE_RUN_RECORD_TITLE).toBe('Check details');
+ expect(PATROL_WORKSPACE_RUN_RECORD_DESCRIPTION).toBe('What Patrol found during this run.');
+ expect(PATROL_WORKSPACE_HISTORY_DESCRIPTION).toBe('Past Patrol checks.');
+ });
});
diff --git a/frontend-modern/src/features/patrol/__tests__/patrolCommercialBoundary.test.ts b/frontend-modern/src/features/patrol/__tests__/patrolCommercialBoundary.test.ts
index 09c5610dcd..824f78a215 100644
--- a/frontend-modern/src/features/patrol/__tests__/patrolCommercialBoundary.test.ts
+++ b/frontend-modern/src/features/patrol/__tests__/patrolCommercialBoundary.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest';
+import patrolAutonomyAvailabilitySource from '../patrolAutonomyAvailability.ts?raw';
import patrolIntelligenceBannersSource from '../PatrolIntelligenceBanners.tsx?raw';
import patrolIntelligenceHeaderSource from '../PatrolIntelligenceHeader.tsx?raw';
@@ -8,34 +9,64 @@ describe('patrol commercial boundary', () => {
expect(patrolIntelligenceBannersSource).toContain('!presentationPolicyHidesUpgradePrompts()');
expect(patrolIntelligenceBannersSource).toContain('state.licenseRequired()');
expect(patrolIntelligenceBannersSource).toContain('!state.showBlockedBanner()');
+ expect(patrolIntelligenceBannersSource).toContain('!state.shouldShowPatrolSetupOnly()');
expect(patrolIntelligenceHeaderSource).toContain('presentationPolicyHidesUpgradePrompts');
+ expect(patrolIntelligenceHeaderSource).toContain('presentationPolicyHidesCommercialSurfaces');
+ expect(patrolIntelligenceHeaderSource).toContain('!presentationPolicyHidesUpgradePrompts()');
+ expect(patrolIntelligenceHeaderSource).toContain('!commercialSurfacesHidden()');
+ expect(patrolIntelligenceHeaderSource).toContain('state.autoFixLocked()');
expect(patrolIntelligenceHeaderSource).toContain(
- '!presentationPolicyHidesUpgradePrompts() && state.autoFixLocked()',
+ "autonomyAvailability().kind === 'runtime_locked'",
);
+ expect(patrolIntelligenceHeaderSource).toContain('showAutonomyPlanBillingAction');
expect(patrolIntelligenceHeaderSource).toContain(
- '!presentationPolicyHidesUpgradePrompts() && state.alertAnalysisLocked()',
+ "autonomyAvailability().kind === 'plan_locked'",
);
+ expect(patrolAutonomyAvailabilitySource).toContain('Plans & Billing');
+ expect(patrolAutonomyAvailabilitySource).toContain('input.upgradePromptsHidden');
+ expect(patrolIntelligenceHeaderSource).toContain('getPatrolAutonomyAvailabilityPresentation');
+ expect(patrolIntelligenceHeaderSource).toContain('!presentationPolicyHidesUpgradePrompts()');
+ expect(patrolIntelligenceHeaderSource).toContain('canChooseAutonomyLevel');
+ expect(patrolIntelligenceHeaderSource).toContain('shouldShowAutonomyOptions');
+ expect(patrolIntelligenceHeaderSource).toContain('shouldShowAutonomyActionColumn');
expect(patrolIntelligenceHeaderSource).toContain(
- '!presentationPolicyHidesUpgradePrompts() && isProLocked()',
+ "autonomyAvailability().kind === 'runtime_locked'",
);
+ expect(patrolIntelligenceHeaderSource).toContain('<Show when={shouldShowAutonomyOptions()}>');
+ expect(patrolIntelligenceHeaderSource).toContain(
+ '<Show when={shouldShowAutonomyActionColumn()}>',
+ );
+ expect(patrolIntelligenceHeaderSource).toContain('showProBadge');
+ expect(patrolIntelligenceHeaderSource).not.toContain('const isProLocked = () =>');
+ expect(patrolIntelligenceHeaderSource).not.toContain('requires Pulse Pro');
});
- it('keeps patrol configuration selects on the shared labelled primitive', () => {
- expect(patrolIntelligenceHeaderSource).toContain(
+ it('keeps patrol configuration out of the operator header', () => {
+ expect(patrolIntelligenceHeaderSource).toContain('Open Patrol settings');
+ expect(patrolIntelligenceHeaderSource).toContain("settingsTabPath('system-ai-patrol')");
+ expect(patrolIntelligenceHeaderSource).not.toContain(
"import { FormSelect } from '@/components/shared/FormSelect';",
);
- expect(patrolIntelligenceHeaderSource).toContain('label="Provider model"');
- expect(patrolIntelligenceHeaderSource).toContain('label="Run Every"');
+ expect(patrolIntelligenceHeaderSource).not.toContain('label="Provider model"');
+ expect(patrolIntelligenceHeaderSource).not.toContain('label="Run Every"');
expect(patrolIntelligenceHeaderSource).not.toContain('<select');
});
- it('keeps the patrol configuration panel above lower page actions', () => {
- expect(patrolIntelligenceHeaderSource).toContain('fixed right-4 top-32 z-[9999] isolate');
- expect(patrolIntelligenceHeaderSource).toContain('max-h-[calc(100vh-10rem)]');
- expect(patrolIntelligenceHeaderSource).toContain('sm:max-h-[calc(100vh-14rem)]');
- expect(patrolIntelligenceHeaderSource).toContain('overflow-y-auto');
- expect(patrolIntelligenceHeaderSource).toContain('sm:top-[13rem]');
- expect(patrolIntelligenceHeaderSource).not.toContain('sm:top-[17.5rem]');
- expect(patrolIntelligenceHeaderSource).not.toContain('disabled:opacity-70');
+ it('keeps blocked provider readiness to one primary action', () => {
+ expect(patrolIntelligenceBannersSource).toContain('shouldShowReadinessAction');
+ expect(patrolIntelligenceBannersSource).toContain(
+ "state.patrolReadiness()?.status !== 'not_ready'",
+ );
+ expect(patrolIntelligenceBannersSource).toContain('<Show when={shouldShowReadinessAction()}>');
+ expect(patrolIntelligenceHeaderSource).toContain('Fix provider');
+ });
+
+ it('does not carry the removed patrol configuration panel chrome', () => {
+ expect(patrolIntelligenceHeaderSource).not.toContain('fixed right-4 top-32 z-[9999] isolate');
+ expect(patrolIntelligenceHeaderSource).not.toContain('max-h-[calc(100vh-10rem)]');
+ expect(patrolIntelligenceHeaderSource).not.toContain('sm:max-h-[calc(100vh-14rem)]');
+ expect(patrolIntelligenceHeaderSource).not.toContain('sm:top-[13rem]');
+ expect(patrolIntelligenceHeaderSource).not.toContain('bg-white p-5 shadow-xl');
+ expect(patrolIntelligenceHeaderSource).not.toContain('invisible pointer-events-none');
});
});
diff --git a/frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.ts b/frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.ts
new file mode 100644
index 0000000000..389b36ab90
--- /dev/null
+++ b/frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.ts
@@ -0,0 +1,128 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PatrolAutonomyLevel } from '@/api/patrol';
+import {
+ getPatrolQueueBadgeLabel,
+ getPatrolQueueWorkspaceDescription,
+ getPatrolReadyWorkDetail,
+ getPatrolSetupIssueReason,
+ PATROL_AUTONOMY_POLICY_PRESENTATION,
+ PATROL_WORKSPACE_QUEUE_TITLE,
+} from '../patrolControlPresentation';
+
+describe('patrolControlPresentation', () => {
+ it('keeps the four Patrol mode options in user-facing language', () => {
+ expect(PATROL_AUTONOMY_POLICY_PRESENTATION).toEqual({
+ monitor: {
+ label: 'Watch only',
+ detail: 'Patrol reports issues without making changes.',
+ compactLabel: 'Watch only',
+ },
+ approval: {
+ label: 'Ask first',
+ detail: 'Patrol investigates issues and prepares fixes. You approve every change.',
+ compactLabel: 'Ask first',
+ },
+ assisted: {
+ label: 'Safe auto-fix',
+ detail: 'Patrol fixes safe policy-allowed issues. It asks before anything riskier.',
+ compactLabel: 'Safe auto-fix',
+ },
+ full: {
+ label: 'Autopilot',
+ detail:
+ 'Patrol handles policy-approved issues automatically. It asks only when policy requires approval.',
+ compactLabel: 'Autopilot',
+ },
+ });
+ });
+
+ it.each([
+ [
+ 'monitor',
+ 'Patrol is ready to check infrastructure and show issues.',
+ 'Problems Patrol finds appear here.',
+ ],
+ [
+ 'approval',
+ 'Patrol is ready to watch and investigate. You approve every change.',
+ 'Investigations and approval requests appear here.',
+ ],
+ [
+ 'assisted',
+ 'Patrol is ready to watch, investigate, and handle safe fixes when policy allows it.',
+ 'Issues Patrol is handling appear here. Approval requests appear when needed.',
+ ],
+ [
+ 'full',
+ 'Patrol is ready to watch, investigate, and act automatically within your policy.',
+ 'Issues Patrol is handling appear here. Approval requests appear when policy requires them.',
+ ],
+ ] satisfies Array<[PatrolAutonomyLevel, string, string]>)(
+ 'describes %s mode without generic control-level wording',
+ (autonomyLevel, currentWorkDetail, workspaceDescription) => {
+ expect(PATROL_WORKSPACE_QUEUE_TITLE).toBe('Current work');
+ expect(getPatrolReadyWorkDetail({ autonomyLevel })).toBe(currentWorkDetail);
+ expect(getPatrolQueueWorkspaceDescription({ autonomyLevel })).toBe(workspaceDescription);
+ },
+ );
+
+ it('does not advertise investigation or fixes while Patrol mode is locked', () => {
+ expect(getPatrolReadyWorkDetail({ autonomyLevel: 'full', autonomyLocked: true })).toBe(
+ 'Patrol is ready to check infrastructure and show issues.',
+ );
+ expect(
+ getPatrolQueueWorkspaceDescription({
+ autonomyLevel: 'full',
+ autonomyLocked: true,
+ }),
+ ).toBe('Problems Patrol finds appear here.');
+ });
+
+ it('summarizes the open queue by affected resource instead of raw findings', () => {
+ expect(getPatrolQueueBadgeLabel({ findingCount: 2, affectedResourceCount: 1 })).toBe(
+ '1 resource',
+ );
+ expect(getPatrolQueueBadgeLabel({ findingCount: 3, affectedResourceCount: 2 })).toBe(
+ '2 resources',
+ );
+ expect(getPatrolQueueBadgeLabel({ findingCount: 2, affectedResourceCount: 0 })).toBeUndefined();
+ expect(getPatrolQueueBadgeLabel({ findingCount: 0, affectedResourceCount: 0 })).toBeUndefined();
+ });
+
+ it('uses the grouped queue count when open findings exist', () => {
+ expect(
+ getPatrolQueueWorkspaceDescription({
+ autonomyLevel: 'monitor',
+ findingCount: 2,
+ affectedResourceCount: 1,
+ }),
+ ).toBe('2 issues on 1 affected resource.');
+ expect(
+ getPatrolQueueWorkspaceDescription({
+ autonomyLevel: 'approval',
+ findingCount: 1,
+ affectedResourceCount: 1,
+ }),
+ ).toBe('1 issue on 1 affected resource.');
+ });
+
+ it('keeps setup-only issue reasons short and actionable', () => {
+ expect(
+ getPatrolSetupIssueReason({
+ setupFindingTitle: 'Provider connection issue',
+ readinessSummary: 'The selected Patrol model is a reasoning-only model family.',
+ }),
+ ).toBe('Provider connection issue');
+ expect(
+ getPatrolSetupIssueReason({
+ readinessSummary:
+ 'The selected Patrol model is a reasoning-only model family that commonly does not emit tool calls.',
+ }),
+ ).toBe('Selected model cannot run Patrol tools.');
+ expect(getPatrolSetupIssueReason({ triggerDisabledReason: 'Patrol is paused' })).toBe(
+ 'Patrol is paused',
+ );
+ expect(getPatrolSetupIssueReason({})).toBe('Provider settings need attention');
+ });
+});
diff --git a/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts b/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts
index a08a9b4561..8f7cf613e4 100644
--- a/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts
+++ b/frontend-modern/src/features/patrol/__tests__/patrolInvestigationContextModel.test.ts
@@ -229,17 +229,17 @@ describe('patrolInvestigationContextModel', () => {
fixedValue: 2,
},
verification: {
- title: 'Full patrol verified recently',
+ title: 'Recently checked',
description: 'Latest full run completed with findings.',
lastFullRunAt: '2026-05-06T12:00:00Z',
- activityMixLabel: '1 full patrol · 2 scoped runs',
+ activityMixLabel: '1 full check · 2 targeted checks',
},
recency: {
label: 'Last patrol',
timestamp: '2026-05-06T12:10:00Z',
},
latestRun: {
- kindLabel: 'Full patrol',
+ kindLabel: 'Patrol check',
status: { label: 'issues found' },
timestamp: '2026-05-06T12:10:00Z',
coverageSummary: '12 resources checked',
@@ -396,12 +396,31 @@ describe('patrolInvestigationContextModel', () => {
expect(JSON.stringify(handoff)).not.toContain('systemctl restart workload.service');
});
+ it('uses operator-facing finding-record wording for legacy latest-run context', () => {
+ const handoff = buildPatrolAssessmentAssistantHandoff({
+ assessment: {
+ title: 'Patrol reviewed recent activity',
+ },
+ latestRun: {
+ kindLabel: 'Patrol check',
+ status: { label: 'completed' },
+ timestamp: '2026-05-06T12:10:00Z',
+ coverageSummary: '67 resources checked',
+ findingsSnapshotAvailable: false,
+ },
+ activeFindings: [],
+ });
+
+ expect(handoff.context.handoffContext).toContain('finding record unavailable');
+ expect(handoff.context.handoffContext).not.toContain('findings snapshot unavailable');
+ });
+
it('frames coverage-incomplete assessment handoffs as evidence-only context', () => {
const handoff = buildPatrolAssessmentAssistantHandoff({
assessment: {
title: 'Coverage incomplete',
description:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs, so overall infrastructure health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks. Run Patrol to check everything.',
eyebrow: 'Patrol assessment',
},
overallHealth: {
@@ -420,13 +439,13 @@ describe('patrolInvestigationContextModel', () => {
fixedValue: 0,
},
verification: {
- title: 'Recently verified',
- description: 'The most recent full patrol completed successfully.',
+ title: 'Recently checked',
+ description: 'The most recent Patrol check completed successfully.',
lastFullRunAt: '2026-05-04T21:38:51Z',
- activityMixLabel: '8 full, 3 alert-triggered',
+ activityMixLabel: '8 full checks, 3 alert-triggered checks',
},
latestRun: {
- kindLabel: 'Scoped run',
+ kindLabel: 'Targeted check',
status: { label: 'issues found' },
timestamp: '2026-05-07T21:39:18Z',
coverageSummary: 'Checked 1 of 2 scoped resources',
@@ -481,13 +500,14 @@ describe('patrolInvestigationContextModel', () => {
factors: [{ category: 'coverage' }],
},
verification: {
- title: 'Recently verified',
- description: 'The most recent full patrol completed successfully and checked 58 resources.',
+ title: 'Recently checked',
+ description:
+ 'The most recent Patrol check completed successfully and covered 58 resources.',
lastFullRunAt: '2026-05-12T21:22:35Z',
- activityMixLabel: '8 full, 3 alert-cleared',
+ activityMixLabel: '8 full checks, 3 alert-cleared checks',
},
latestRun: {
- kindLabel: 'Full patrol',
+ kindLabel: 'Patrol check',
status: { label: 'issues found' },
timestamp: '2026-05-12T21:22:35Z',
coverageSummary: 'Checked 58 resources',
@@ -668,7 +688,7 @@ describe('patrolInvestigationContextModel', () => {
expect(handoff.context.handoffMetadata).toEqual({
kind: 'patrol_run',
runId: 'run-runtime-error',
- runType: 'Scoped run',
+ runType: 'Targeted check',
runStatus: 'error',
runtimeFailure: true,
});
@@ -683,7 +703,7 @@ describe('patrolInvestigationContextModel', () => {
expect(JSON.stringify(handoff)).not.toContain('No endpoints found');
});
- it('builds a model-only Assistant handoff for a Patrol configuration failure', () => {
+ it('builds a model-only Assistant handoff for a Patrol mode save failure', () => {
const handoff = buildPatrolConfigurationFailureHandoff({
message: 'The selected Patrol model is a reasoning-only model family.',
code: 'patrol_readiness_not_ready',
@@ -713,7 +733,7 @@ describe('patrolInvestigationContextModel', () => {
kind: 'patrol_configuration_failure',
runtimeFailure: true,
});
- expect(handoff.context.handoffContext).toContain('[Patrol Configuration Failure Context]');
+ expect(handoff.context.handoffContext).toContain('[Patrol Control Save Failure Context]');
expect(handoff.context.handoffContext).toContain('Server Code: patrol_readiness_not_ready');
expect(handoff.context.handoffContext).toContain('Provider: ollama');
expect(handoff.context.handoffContext).toContain('Model: ollama:deepseek-r1:7b');
@@ -722,13 +742,13 @@ describe('patrolInvestigationContextModel', () => {
);
expect(handoff.context.briefing).toMatchObject({
sourceLabel: 'Pulse Patrol',
- title: 'Patrol configuration failure attached',
- actionLabel: 'Review Patrol configuration failure',
+ title: 'Patrol mode save failure attached',
+ actionLabel: 'Review Patrol mode save failure',
});
expect(JSON.stringify(handoff)).not.toContain('systemctl restart pulse.service');
});
- it('labels saved Patrol configuration readiness issues separately from save failures', () => {
+ it('labels saved Patrol mode readiness issues separately from save failures', () => {
const handoff = buildPatrolConfigurationFailureHandoff({
saved: true,
message: 'Patrol was saved, but the selected model cannot run Patrol tools yet.',
@@ -744,8 +764,8 @@ describe('patrolInvestigationContextModel', () => {
expect(handoff).not.toHaveProperty('prompt');
expect(handoff.context.briefing).toMatchObject({
- title: 'Patrol configuration issue attached',
- actionLabel: 'Review Patrol configuration issue',
+ title: 'Patrol mode issue attached',
+ actionLabel: 'Review Patrol mode issue',
});
});
@@ -1239,6 +1259,11 @@ describe('patrolInvestigationContextModel', () => {
investigationOutcome: 'fix_queued',
}),
).toBe(true);
+ expect(
+ patrolAssistantFindingHandoffRequiresApprovalMode({
+ investigationOutcome: 'fix_rejected',
+ }),
+ ).toBe(true);
expect(
patrolAssistantFindingHandoffRequiresApprovalMode({
investigationRecord: {
@@ -1438,12 +1463,11 @@ describe('Patrol page header IA framing', () => {
expect(headerSource).not.toContain('verified {recency().resourcesChecked}');
});
- it('keeps trust-at-a-glance state inside the primary assessment readout', () => {
- // The default Patrol scan path has one status owner: the assessment strip.
- // Regression trust counters may feed that compact readout, but the header
- // and workspace tabs should not repeat another active/regressed strip.
- const summarySource = readFileSync(
- resolve(__dirname, '..', 'PatrolIntelligenceSummary.tsx'),
+ it('keeps trust counters out of default Patrol chrome', () => {
+ // Trust counters remain backend/state evidence. The default Patrol surface
+ // should not reintroduce a second current-work/history strip to explain them.
+ const surfaceSource = readFileSync(
+ resolve(__dirname, '..', 'PatrolIntelligenceSurface.tsx'),
'utf-8',
);
const headerSource = readFileSync(
@@ -1454,28 +1478,34 @@ describe('Patrol page header IA framing', () => {
resolve(__dirname, '..', 'PatrolIntelligenceWorkspace.tsx'),
'utf-8',
);
- expect(summarySource).toContain('compactAssessmentSummary');
- expect(summarySource).toContain('state.patrolStatus()?.trust?.regressed_at_least_once');
+ expect(surfaceSource).not.toContain('PatrolIntelligenceSummary');
+ expect(surfaceSource).not.toContain('compactAssessmentSummary');
+ expect(surfaceSource).not.toContain('state.patrolStatus()?.trust?.regressed_at_least_once');
expect(headerSource).not.toContain('aria-label="Patrol trust summary header"');
expect(workspaceSource).not.toContain('aria-label="Patrol trust summary"');
});
- it('names the proactive trust loop on the canonical Patrol surface', async () => {
+ it('names the proactive trust loop on the canonical Patrol surface when control is available', async () => {
// The Patrol page header is the most visible piece of operator-facing
// copy on the canonical Patrol surface. The IA framing must keep the
- // product boundary clear: Pulse probes and assembles evidence, the
- // configured model reasons over it, and action stays approval-bound.
+ // product boundary clear without turning the page header into a
+ // mini spec for the full operations loop.
const { getPatrolPageHeaderMeta, PATROL_PAGE_DESCRIPTION, PATROL_PAGE_TITLE_TOOLTIP } =
await import('@/utils/patrolPagePresentation');
- expect(PATROL_PAGE_DESCRIPTION).toContain('Pulse checks your infrastructure');
- expect(PATROL_PAGE_DESCRIPTION).toContain('configured model');
- expect(PATROL_PAGE_DESCRIPTION).toContain('right evidence');
- expect(PATROL_PAGE_DESCRIPTION).toContain('approval policy');
+ expect(PATROL_PAGE_DESCRIPTION).toBe(
+ 'Patrol watches, investigates, acts within your chosen mode, verifies outcomes, and records what happened.',
+ );
+ expect(PATROL_PAGE_DESCRIPTION).toContain('acts within your chosen mode');
expect(PATROL_PAGE_TITLE_TOOLTIP).toBe(PATROL_PAGE_DESCRIPTION);
expect(getPatrolPageHeaderMeta()).toMatchObject({
title: 'Patrol',
description: PATROL_PAGE_DESCRIPTION,
titleTooltip: PATROL_PAGE_DESCRIPTION,
});
+ expect(getPatrolPageHeaderMeta({ autonomyLocked: true })).toMatchObject({
+ title: 'Patrol',
+ description: 'Patrol watches infrastructure and shows current issues.',
+ titleTooltip: 'Patrol watches infrastructure and shows current issues.',
+ });
});
});
diff --git a/frontend-modern/src/features/patrol/__tests__/patrolSupportingContextPresentation.test.ts b/frontend-modern/src/features/patrol/__tests__/patrolSupportingContextPresentation.test.ts
deleted file mode 100644
index d324f4bf6e..0000000000
--- a/frontend-modern/src/features/patrol/__tests__/patrolSupportingContextPresentation.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import {
- getPatrolSupportingContextCorrelationSummary,
- getPatrolSupportingContextToggleLabel,
- PATROL_SUPPORTING_CONTEXT_CHANGE_SUBTITLE,
- PATROL_SUPPORTING_CONTEXT_DESCRIPTION,
- PATROL_SUPPORTING_CONTEXT_EVIDENCE_LABEL,
- PATROL_SUPPORTING_CONTEXT_EVIDENCE_NOTE,
- PATROL_SUPPORTING_CONTEXT_POLICY_SUBTITLE,
- PATROL_SUPPORTING_CONTEXT_TITLE,
-} from '../patrolSupportingContextPresentation';
-
-describe('patrolSupportingContextPresentation', () => {
- it('exports the canonical supporting-context trust copy', () => {
- expect(PATROL_SUPPORTING_CONTEXT_TITLE).toBe('Supporting context');
- expect(PATROL_SUPPORTING_CONTEXT_DESCRIPTION).toBe(
- 'Recent changes, learned correlations, and policy coverage that may explain findings or incomplete verification.',
- );
- expect(PATROL_SUPPORTING_CONTEXT_EVIDENCE_LABEL).toBe('How to read this');
- expect(PATROL_SUPPORTING_CONTEXT_EVIDENCE_NOTE).toBe(
- 'Findings and run history are Patrol verification evidence. The cards below add explanatory context and do not count as a fresh full patrol.',
- );
- expect(PATROL_SUPPORTING_CONTEXT_CHANGE_SUBTITLE).toBe(
- 'Observed from the canonical timeline in the last 24 hours.',
- );
- expect(PATROL_SUPPORTING_CONTEXT_POLICY_SUBTITLE).toBe(
- 'Coverage posture for policy-covered resources.',
- );
- });
-
- it('builds canonical supporting-context action labels and correlation summaries', () => {
- expect(getPatrolSupportingContextToggleLabel(false)).toBe('View supporting context');
- expect(getPatrolSupportingContextToggleLabel(true)).toBe('Hide supporting context');
- expect(getPatrolSupportingContextCorrelationSummary(2)).toBe(
- '2 learned patterns · explanatory context',
- );
- expect(getPatrolSupportingContextCorrelationSummary(1)).toBe(
- '1 learned pattern · explanatory context',
- );
- expect(getPatrolSupportingContextCorrelationSummary(Number.NaN)).toBe(
- 'Learned pattern context',
- );
- });
-});
diff --git a/frontend-modern/src/features/patrol/__tests__/usePatrolIntelligenceState.test.ts b/frontend-modern/src/features/patrol/__tests__/usePatrolIntelligenceState.test.ts
index f20ee12efd..0d3131cd49 100644
--- a/frontend-modern/src/features/patrol/__tests__/usePatrolIntelligenceState.test.ts
+++ b/frontend-modern/src/features/patrol/__tests__/usePatrolIntelligenceState.test.ts
@@ -1,14 +1,36 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
+ PATROL_MANUAL_SYNC_TIMEOUT_MS,
PATROL_REFRESH_TIMEOUT_MS,
buildPatrolSettingsReadinessFailure,
+ openPatrolAssistantWorkflowHandoff,
+ recordPatrolControlStarterActivity,
+ recordPatrolWorkflowStarterActivity,
resolvePatrolAutonomyLevelForSave,
resolvePatrolAutonomySettingsForSave,
} from '../usePatrolIntelligenceState';
import patrolIntelligenceStateSource from '../usePatrolIntelligenceState.ts?raw';
+import type { AIChatContext } from '@/stores/aiChat';
import type { AISettings, PatrolReadiness } from '@/types/ai';
+const recordWorkflowPromptActivityMock = vi.hoisted(() => vi.fn());
+const loggerDebugMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@/api/aiChat', async (importOriginal) => ({
+ ...((await importOriginal()) as object),
+ AIChatAPI: {
+ recordWorkflowPromptActivity: recordWorkflowPromptActivityMock,
+ },
+}));
+
+vi.mock('@/utils/logger', async (importOriginal) => ({
+ ...((await importOriginal()) as object),
+ logger: {
+ debug: loggerDebugMock,
+ },
+}));
+
const settingsWithReadiness = (patrolReadiness: PatrolReadiness): AISettings => ({
enabled: true,
model: 'ollama:llama3',
@@ -29,31 +51,219 @@ const settingsWithReadiness = (patrolReadiness: PatrolReadiness): AISettings =>
});
describe('usePatrolIntelligenceState', () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
it('bounds refresh UI state with a generation-aware timeout', () => {
expect(PATROL_REFRESH_TIMEOUT_MS).toBe(15000);
+ expect(PATROL_MANUAL_SYNC_TIMEOUT_MS).toBe(5000);
expect(patrolIntelligenceStateSource).toContain('let refreshRequestId = 0;');
+ expect(patrolIntelligenceStateSource).toContain('let manualRefreshRequestId = 0;');
expect(patrolIntelligenceStateSource).toContain('const requestId = ++refreshRequestId;');
expect(patrolIntelligenceStateSource).toContain('if (requestId === refreshRequestId) {');
expect(patrolIntelligenceStateSource).toContain('setIsRefreshing(false);');
+ expect(patrolIntelligenceStateSource).toContain('setIsManualRefreshRunning(false);');
+ expect(patrolIntelligenceStateSource).toContain('handleRefreshPatrol');
expect(patrolIntelligenceStateSource).toContain('clearRefreshTimeout();');
+ expect(patrolIntelligenceStateSource).toContain('clearManualRefreshTimeout();');
+ expect(patrolIntelligenceStateSource).toContain('PATROL_MANUAL_SYNC_TIMEOUT_MS');
+ });
+
+ it('fails soft when Patrol data refreshes reject', () => {
+ expect(patrolIntelligenceStateSource).toContain('const [patrolLoadError, setPatrolLoadError]');
+ expect(patrolIntelligenceStateSource).toContain('rememberPatrolLoadError');
+ expect(patrolIntelligenceStateSource).toContain('Promise.allSettled([');
+ expect(patrolIntelligenceStateSource).toContain('setInitialSurfaceReady(true);');
+ expect(patrolIntelligenceStateSource).toContain("logger.debug('[Patrol] Failed to refresh Patrol data'");
+ expect(patrolIntelligenceStateSource).toContain('patrolLoadError,');
+ });
+
+ it('keeps manual status sync bounded to visible Patrol reads', () => {
+ const loadAllDataStart = patrolIntelligenceStateSource.indexOf('async function loadAllData()');
+ const loadAllDataEnd = patrolIntelligenceStateSource.indexOf(
+ 'async function loadVisiblePatrolData()',
+ loadAllDataStart,
+ );
+ const loadAllDataBody = patrolIntelligenceStateSource.slice(loadAllDataStart, loadAllDataEnd);
+ const manualRefreshStart = patrolIntelligenceStateSource.indexOf(
+ 'async function handleRefreshPatrol()',
+ );
+ const manualRefreshEnd = patrolIntelligenceStateSource.indexOf(
+ 'async function consumeRoutePatrolControlStarterHandoff()',
+ manualRefreshStart,
+ );
+ const manualRefreshBody = patrolIntelligenceStateSource.slice(
+ manualRefreshStart,
+ manualRefreshEnd,
+ );
+
+ expect(patrolIntelligenceStateSource).toContain('async function loadVisiblePatrolData()');
+ expect(patrolIntelligenceStateSource).toContain('refetchPatrolStatus()');
+ expect(patrolIntelligenceStateSource).toContain('aiIntelligenceStore.loadPatrolFindings()');
+ expect(patrolIntelligenceStateSource).toContain('aiIntelligenceStore.loadPendingApprovals()');
+ expect(patrolIntelligenceStateSource).toContain(
+ 'patrolRunHistory.refetch({ background: true })',
+ );
+ expect(patrolIntelligenceStateSource).toContain(
+ 'function loadSupportingPatrolDataInBackground()',
+ );
+ expect(loadAllDataBody).toContain('PATROL_REFRESH_TIMEOUT_MS');
+ expect(loadAllDataBody).not.toContain('PATROL_MANUAL_SYNC_TIMEOUT_MS');
+ expect(manualRefreshBody).toContain('await loadVisiblePatrolData();');
+ expect(manualRefreshBody).toContain('loadSupportingPatrolDataInBackground();');
+ expect(manualRefreshBody).toContain('PATROL_MANUAL_SYNC_TIMEOUT_MS');
+ expect(manualRefreshBody).not.toContain('PATROL_REFRESH_TIMEOUT_MS');
+ expect(manualRefreshBody).not.toContain('await loadAllData();');
+ });
+
+ it('counts rejected Patrol fixes as governed action decisions', () => {
+ expect(patrolIntelligenceStateSource).toContain('const PATROL_GOVERNED_ACTION_OUTCOMES');
+ expect(patrolIntelligenceStateSource).toContain("'fix_rejected'");
+ expect(patrolIntelligenceStateSource).toContain('patrolGovernedActionCount');
+ });
+
+ it('separates generic Patrol runs from issue-backed Patrol work evidence', () => {
+ expect(patrolIntelligenceStateSource).toContain('const patrolWorkIssueEvidenceCount');
+ expect(patrolIntelligenceStateSource).toContain("finding.status === 'active'");
+ expect(patrolIntelligenceStateSource).toContain("finding.status === 'resolved'");
+ expect(patrolIntelligenceStateSource).toContain('status?.findings_count');
+ expect(patrolIntelligenceStateSource).toContain('status?.trust?.fix_verified');
+ expect(patrolIntelligenceStateSource).toContain('patrolWorkIssueEvidenceCount,');
+ });
+
+ it('keeps MCP readiness out of first-party Patrol workflow state', () => {
+ expect(patrolIntelligenceStateSource).not.toContain('agentCapabilitiesManifest');
+ expect(patrolIntelligenceStateSource).not.toContain('fetchAgentCapabilitiesManifest');
+ expect(patrolIntelligenceStateSource).not.toContain('getAgentMCPOperationsLoopReadiness');
+ expect(patrolIntelligenceStateSource).not.toContain('mcpOperationsLoopReadiness');
+ });
+
+ it('keeps legacy operations-loop status out of Patrol workspace state', () => {
+ expect(patrolIntelligenceStateSource).not.toContain('fetchAgentOperationsLoopStatus');
+ expect(patrolIntelligenceStateSource).not.toContain('AgentOperationsLoopStatus');
+ expect(patrolIntelligenceStateSource).not.toContain('const [patrolWorkStatus');
+ expect(patrolIntelligenceStateSource).not.toContain('const [patrolWorkStatusChecked');
+ expect(patrolIntelligenceStateSource).not.toContain('loadPatrolWorkStatus');
+ expect(patrolIntelligenceStateSource).not.toContain('patrolWorkStatus,');
+ expect(patrolIntelligenceStateSource).not.toContain('patrolWorkStatusChecked,');
+ });
+
+ it('consumes route-backed Patrol mode starters before the initial status load', () => {
+ expect(patrolIntelligenceStateSource).toContain("typeof window === 'undefined'");
+ expect(patrolIntelligenceStateSource).toContain('window.location.search');
+ expect(patrolIntelligenceStateSource).toContain('window.history.replaceState');
+ expect(patrolIntelligenceStateSource).toContain('parsePatrolControlStarter');
+ expect(patrolIntelligenceStateSource).toContain('PATROL_CONTROL_STARTER');
+ expect(patrolIntelligenceStateSource).toContain('PATROL_CONTROL_STARTER_QUERY_PARAM');
+ expect(patrolIntelligenceStateSource).toContain('recordPatrolControlStarterActivity()');
+ expect(patrolIntelligenceStateSource).toContain(
+ 'await consumeRoutePatrolControlStarterHandoff();',
+ );
+ });
+
+ it('records direct Patrol workflow starters with the shared content-free activity route', () => {
+ recordWorkflowPromptActivityMock.mockResolvedValueOnce(undefined);
+
+ recordPatrolWorkflowStarterActivity();
+
+ expect(recordWorkflowPromptActivityMock).toHaveBeenCalledWith({
+ name: 'pulse_operations_loop',
+ surface: 'pulse_patrol',
+ });
+ expect(patrolIntelligenceStateSource).toContain('recordPatrolWorkflowStarterActivity,');
+ });
+
+ it('records route-backed Patrol mode starters with the shared content-free activity route', async () => {
+ recordWorkflowPromptActivityMock.mockResolvedValueOnce(undefined);
+
+ await recordPatrolControlStarterActivity();
+
+ expect(recordWorkflowPromptActivityMock).toHaveBeenCalledWith({
+ name: 'pulse_operations_loop',
+ surface: 'patrol_control',
+ });
+ });
+
+ it('records successful direct Patrol mode changes as first-party starters', () => {
+ expect(patrolIntelligenceStateSource).toContain('const controlLocked = autoFixLocked();');
+ expect(patrolIntelligenceStateSource).toContain('const shouldRecordPatrolControlStarter');
+ expect(patrolIntelligenceStateSource).toContain('!controlLocked &&');
+ expect(patrolIntelligenceStateSource).toContain('await updatePatrolAutonomySettings({');
+ expect(patrolIntelligenceStateSource).toContain('if (shouldRecordPatrolControlStarter) {');
+ expect(patrolIntelligenceStateSource).toContain('await recordPatrolControlStarterActivity();');
+ expect(patrolIntelligenceStateSource).toContain('await loadVisiblePatrolData();');
+ expect(patrolIntelligenceStateSource).not.toContain('await loadPatrolWorkStatus();');
+ });
+
+ it('keeps direct Patrol starter recording non-blocking when the marker route fails', async () => {
+ const error = new Error('offline');
+ recordWorkflowPromptActivityMock.mockRejectedValueOnce(error);
+
+ recordPatrolWorkflowStarterActivity();
+ await Promise.resolve();
+
+ expect(loggerDebugMock).toHaveBeenCalledWith(
+ '[Patrol] Failed to record Patrol workflow starter',
+ error,
+ );
+ });
+
+ it('records a Patrol starter before opening the Assistant workflow handoff', () => {
+ const callOrder: string[] = [];
+ const recordStarterActivity = vi.fn(() => callOrder.push('record'));
+ const openAssistant = vi.fn((context: AIChatContext) => {
+ callOrder.push('open');
+ expect(context).toMatchObject({
+ targetType: 'storage',
+ targetId: 'storage-1',
+ findingId: 'finding-1',
+ autonomousMode: false,
+ preferredWorkflowPromptName: 'pulse_operations_loop',
+ });
+ expect(context.handoffContext).toBe('Scoped Patrol context');
+ });
+
+ openPatrolAssistantWorkflowHandoff(
+ {
+ context: {
+ targetType: 'storage',
+ targetId: 'storage-1',
+ findingId: 'finding-1',
+ autonomousMode: false,
+ handoffContext: 'Scoped Patrol context',
+ preferredWorkflowPromptName: 'legacy_prompt',
+ },
+ },
+ {
+ recordStarterActivity,
+ openAssistant,
+ },
+ );
+
+ expect(recordStarterActivity).toHaveBeenCalledWith();
+ expect(openAssistant).toHaveBeenCalledTimes(1);
+ expect(callOrder).toEqual(['record', 'open']);
});
describe('resolvePatrolAutonomyLevelForSave', () => {
- it('clamps stale paid autonomy to monitor when safe remediation is locked', () => {
+ it('clamps stale paid autonomy to monitor when governed fixes are locked', () => {
expect(resolvePatrolAutonomyLevelForSave('full', true, true)).toBe('monitor');
expect(resolvePatrolAutonomyLevelForSave('assisted', false, true)).toBe('monitor');
expect(resolvePatrolAutonomyLevelForSave('approval', false, true)).toBe('monitor');
});
- it('preserves paid autonomy choices when safe remediation is available', () => {
+ it('preserves paid autonomy choices when governed fixes are available', () => {
expect(resolvePatrolAutonomyLevelForSave('assisted', false, false)).toBe('assisted');
- expect(resolvePatrolAutonomyLevelForSave('assisted', true, false)).toBe('full');
+ expect(resolvePatrolAutonomyLevelForSave('assisted', true, false)).toBe('assisted');
+ expect(resolvePatrolAutonomyLevelForSave('full', true, false)).toBe('full');
+ expect(resolvePatrolAutonomyLevelForSave('full', false, false)).toBe('assisted');
expect(resolvePatrolAutonomyLevelForSave('approval', false, false)).toBe('approval');
});
});
describe('resolvePatrolAutonomySettingsForSave', () => {
- it('clears stale full-mode state when safe remediation is locked', () => {
+ it('clears stale full-mode state when governed fixes are locked', () => {
expect(
resolvePatrolAutonomySettingsForSave({
level: 'full',
@@ -81,13 +291,21 @@ describe('usePatrolIntelligenceState', () => {
).toEqual({ autonomyLevel: 'approval', fullModeUnlocked: false });
});
- it('promotes remediation mode to full only when full mode is explicitly unlocked', () => {
+ it('keeps full control tied to the explicit full selection', () => {
expect(
resolvePatrolAutonomySettingsForSave({
level: 'assisted',
fullModeUnlocked: true,
autoFixLocked: false,
}),
+ ).toEqual({ autonomyLevel: 'assisted', fullModeUnlocked: false });
+
+ expect(
+ resolvePatrolAutonomySettingsForSave({
+ level: 'full',
+ fullModeUnlocked: true,
+ autoFixLocked: false,
+ }),
).toEqual({ autonomyLevel: 'full', fullModeUnlocked: true });
expect(
diff --git a/frontend-modern/src/features/patrol/patrolAutonomyAvailability.ts b/frontend-modern/src/features/patrol/patrolAutonomyAvailability.ts
new file mode 100644
index 0000000000..f23791bd33
--- /dev/null
+++ b/frontend-modern/src/features/patrol/patrolAutonomyAvailability.ts
@@ -0,0 +1,90 @@
+import type { LicenseRuntimeCapabilityBlock, LicenseRuntimeIdentity } from '@/api/license';
+import type { UpgradeDestination } from '@/utils/upgradeNavigation';
+import { resolveUpgradeDestination } from '@/utils/upgradeNavigation';
+
+export const PATROL_AUTONOMY_FEATURE_KEY = 'ai_autofix';
+export const PATROL_AUTONOMY_RUNTIME_REQUIRED_REASON = 'paid_runtime_required';
+
+export type PatrolAutonomyAvailabilityKind = 'available' | 'plan_locked' | 'runtime_locked';
+
+export interface PatrolAutonomyAvailabilityInput {
+ autoFixLocked: boolean;
+ upgradePromptsHidden?: boolean;
+ commercialSurfacesHidden?: boolean;
+ runtimeCapabilityBlock?: LicenseRuntimeCapabilityBlock;
+ runtime?: LicenseRuntimeIdentity;
+ planUpgradeDestination: UpgradeDestination;
+}
+
+export interface PatrolAutonomyAvailabilityPresentation {
+ kind: PatrolAutonomyAvailabilityKind;
+ locked: boolean;
+ title: string;
+ body: string;
+ actionLabel?: string;
+ destination?: UpgradeDestination;
+}
+
+function getRuntimeDownloadDestination(
+ block: LicenseRuntimeCapabilityBlock | undefined,
+ runtime: LicenseRuntimeIdentity | undefined,
+): UpgradeDestination | undefined {
+ const href = block?.action_url?.trim() || runtime?.download_url?.trim();
+ return href ? resolveUpgradeDestination(href) : undefined;
+}
+
+function getRuntimeLabel(runtime: LicenseRuntimeIdentity | undefined): string {
+ return runtime?.label?.trim() || 'this runtime';
+}
+
+export function getPatrolAutonomyAvailabilityPresentation(
+ input: PatrolAutonomyAvailabilityInput,
+): PatrolAutonomyAvailabilityPresentation {
+ if (!input.autoFixLocked) {
+ return {
+ kind: 'available',
+ locked: false,
+ title: 'Patrol mode available',
+ body: 'Choose the mode for this install.',
+ };
+ }
+
+ if (input.runtimeCapabilityBlock?.reason === PATROL_AUTONOMY_RUNTIME_REQUIRED_REASON) {
+ return {
+ kind: 'runtime_locked',
+ locked: true,
+ title: 'Pulse Pro runtime required',
+ body: `This install is running ${getRuntimeLabel(input.runtime)}. Install the Pulse Pro runtime to use Patrol modes.`,
+ ...(input.upgradePromptsHidden
+ ? {}
+ : {
+ actionLabel: 'Open Pro downloads',
+ destination:
+ getRuntimeDownloadDestination(input.runtimeCapabilityBlock, input.runtime) ??
+ input.planUpgradeDestination,
+ }),
+ };
+ }
+
+ if (input.commercialSurfacesHidden) {
+ return {
+ kind: 'plan_locked',
+ locked: true,
+ title: 'Watch only',
+ body: 'This install watches infrastructure and shows issues.',
+ };
+ }
+
+ return {
+ kind: 'plan_locked',
+ locked: true,
+ title: 'Watch only',
+ body: 'This install watches infrastructure and shows issues.',
+ ...(input.upgradePromptsHidden
+ ? {}
+ : {
+ actionLabel: 'Plans & Billing',
+ destination: input.planUpgradeDestination,
+ }),
+ };
+}
diff --git a/frontend-modern/src/features/patrol/patrolControlPresentation.ts b/frontend-modern/src/features/patrol/patrolControlPresentation.ts
new file mode 100644
index 0000000000..a9b5a45afc
--- /dev/null
+++ b/frontend-modern/src/features/patrol/patrolControlPresentation.ts
@@ -0,0 +1,151 @@
+import type { PatrolAutonomyLevel } from '@/api/patrol';
+import { getPatrolFindingIssueCountLabel } from '@/utils/aiFindingPresentation';
+
+export const PATROL_AUTONOMY_POLICY_PRESENTATION: Record<
+ PatrolAutonomyLevel,
+ { label: string; detail: string; compactLabel?: string }
+> = {
+ monitor: {
+ label: 'Watch only',
+ detail: 'Patrol reports issues without making changes.',
+ compactLabel: 'Watch only',
+ },
+ approval: {
+ label: 'Ask first',
+ detail: 'Patrol investigates issues and prepares fixes. You approve every change.',
+ compactLabel: 'Ask first',
+ },
+ assisted: {
+ label: 'Safe auto-fix',
+ detail: 'Patrol fixes safe policy-allowed issues. It asks before anything riskier.',
+ compactLabel: 'Safe auto-fix',
+ },
+ full: {
+ label: 'Autopilot',
+ detail:
+ 'Patrol handles policy-approved issues automatically. It asks only when policy requires approval.',
+ compactLabel: 'Autopilot',
+ },
+};
+
+export const PATROL_WORKSPACE_HISTORY_DESCRIPTION = 'Past Patrol checks.';
+
+export const PATROL_WORKSPACE_RUN_RECORD_DESCRIPTION = 'What Patrol found during this run.';
+
+export const PATROL_WORKSPACE_SETUP_TITLE = 'Fix provider';
+
+export const PATROL_WORKSPACE_SETUP_DESCRIPTION =
+ 'Open Provider & Models, then run Patrol from this page.';
+
+export const PATROL_WORKSPACE_QUEUE_TITLE = 'Current work';
+
+export const PATROL_WORKSPACE_RUN_RECORD_TITLE = 'Check details';
+
+interface PatrolControlCopyInput {
+ autonomyLevel?: PatrolAutonomyLevel;
+ autonomyLocked?: boolean;
+}
+
+interface PatrolQueueCountInput {
+ affectedResourceCount?: number;
+ findingCount?: number;
+}
+
+interface PatrolSetupIssueReasonInput {
+ setupFindingTitle?: string;
+ readinessSummary?: string;
+ triggerDisabledReason?: string;
+ blockedReason?: string;
+}
+
+function normalizeCount(value: number | undefined): number {
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
+ return 0;
+ }
+ return Math.max(0, Math.trunc(value));
+}
+
+function normalizeText(value: string | undefined): string {
+ return value?.trim() ?? '';
+}
+
+function formatCount(count: number, singular: string, plural = `${singular}s`): string {
+ return `${count} ${count === 1 ? singular : plural}`;
+}
+
+export function getPatrolSetupIssueReason(input: PatrolSetupIssueReasonInput): string {
+ const setupFindingTitle = normalizeText(input.setupFindingTitle);
+ if (setupFindingTitle) return setupFindingTitle;
+
+ const readinessSummary = normalizeText(input.readinessSummary);
+ if (readinessSummary) {
+ if (
+ /\btool(?:_| )?calls?\b/i.test(readinessSummary) ||
+ /\brun tools?\b/i.test(readinessSummary)
+ ) {
+ return 'Selected model cannot run Patrol tools.';
+ }
+ return readinessSummary;
+ }
+
+ return (
+ normalizeText(input.triggerDisabledReason) ||
+ normalizeText(input.blockedReason) ||
+ 'Provider settings need attention'
+ );
+}
+
+export function getPatrolReadyWorkDetail(input: PatrolControlCopyInput): string {
+ if (input.autonomyLocked) {
+ return 'Patrol is ready to check infrastructure and show issues.';
+ }
+
+ switch (input.autonomyLevel) {
+ case 'approval':
+ return 'Patrol is ready to watch and investigate. You approve every change.';
+ case 'assisted':
+ return 'Patrol is ready to watch, investigate, and handle safe fixes when policy allows it.';
+ case 'full':
+ return 'Patrol is ready to watch, investigate, and act automatically within your policy.';
+ case 'monitor':
+ default:
+ return 'Patrol is ready to check infrastructure and show issues.';
+ }
+}
+
+export function getPatrolQueueBadgeLabel(input: PatrolQueueCountInput): string | undefined {
+ const affectedResourceCount = normalizeCount(input.affectedResourceCount);
+ if (affectedResourceCount <= 0) {
+ return undefined;
+ }
+ return formatCount(affectedResourceCount, 'resource');
+}
+
+export function getPatrolQueueWorkspaceDescription(
+ input: PatrolControlCopyInput & PatrolQueueCountInput,
+): string {
+ const findingCount = normalizeCount(input.findingCount);
+ const affectedResourceCount = normalizeCount(input.affectedResourceCount);
+ if (findingCount > 0 && affectedResourceCount > 0) {
+ return `${getPatrolFindingIssueCountLabel(findingCount)} on ${formatCount(
+ affectedResourceCount,
+ 'affected resource',
+ )}.`;
+ }
+
+ if (input.autonomyLocked) {
+ return 'Problems Patrol finds appear here.';
+ }
+
+ switch (input.autonomyLevel) {
+ case 'approval':
+ return 'Investigations and approval requests appear here.';
+ case 'assisted':
+ return 'Issues Patrol is handling appear here. Approval requests appear when needed.';
+ case 'full':
+ return 'Issues Patrol is handling appear here. Approval requests appear when policy requires them.';
+ case 'monitor':
+ default:
+ return 'Problems Patrol finds appear here.';
+ }
+}
diff --git a/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts b/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts
index 5afe854a51..6354cd6ab4 100644
--- a/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts
+++ b/frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts
@@ -5,6 +5,7 @@ import type {
} from '@/types/aiIntelligence';
import type { ApprovalRequest, InvestigationRecord, RemediationPlan } from '@/api/ai';
import type { PatrolRunRecord } from '@/api/patrol';
+import type { UnifiedFinding } from '@/stores/aiIntelligence';
import type {
AIChatContext,
AIChatContextBriefing,
@@ -22,6 +23,10 @@ import {
formatResourceCorrelationSummary,
sortResourceCorrelations,
} from '@/utils/resourceCorrelationPresentation';
+import {
+ getFindingSubjectPresentation,
+ getFindingTitlePresentation,
+} from '@/utils/aiFindingPresentation';
import {
formatDurationMs,
formatPatrolRuntimeFailureSummary,
@@ -443,6 +448,66 @@ export function buildPatrolAssistantApprovalBriefingInput(
};
}
+export function buildPatrolAssistantProposedFixBriefingInputFromApproval(
+ approval?: ApprovalRequest | null,
+): PatrolAssistantProposedFixBriefingInput | undefined {
+ return buildPatrolAssistantProposedFixBriefingInput(
+ approval
+ ? {
+ description: approval.context,
+ riskLevel: approval.riskLevel,
+ targetHost: approval.targetName,
+ commandCount: approval.command ? 1 : 0,
+ }
+ : null,
+ );
+}
+
+export interface PatrolUnifiedFindingHandoffOptions {
+ pendingApproval?: PatrolAssistantApprovalBriefingInput | null;
+ proposedFix?: PatrolAssistantProposedFixBriefingInput | null;
+}
+
+export function buildPatrolAssistantFindingHandoffInputFromUnifiedFinding(
+ finding: UnifiedFinding,
+ options: PatrolUnifiedFindingHandoffOptions = {},
+): PatrolAssistantFindingHandoffInput {
+ const title = getFindingTitlePresentation(finding).label;
+ const subject = getFindingSubjectPresentation(finding).label;
+ return {
+ id: finding.id,
+ title,
+ subject,
+ description: finding.description,
+ severity: finding.severity,
+ findingStatus: finding.status,
+ investigationStatus: finding.investigationStatus,
+ investigationOutcome: finding.investigationOutcome,
+ loopState: finding.loopState,
+ timesRaised: finding.timesRaised,
+ regressionCount: finding.regressionCount,
+ lastRegressionAt: finding.lastRegressionAt,
+ remediationId: finding.remediationPlanId,
+ resourceId: finding.resourceId,
+ resourceName: finding.resourceName,
+ resourceType: finding.resourceType,
+ detectedAt: finding.detectedAt,
+ lastSeenAt: finding.lastSeenAt,
+ pendingApproval: options.pendingApproval,
+ proposedFix: options.proposedFix,
+ investigationRecord: finding.investigationRecord,
+ };
+}
+
+export function buildPatrolAssistantFindingHandoffFromUnifiedFinding(
+ finding: UnifiedFinding,
+ options: PatrolUnifiedFindingHandoffOptions = {},
+): PatrolAssistantFindingHandoff {
+ return buildPatrolAssistantFindingHandoff(
+ buildPatrolAssistantFindingHandoffInputFromUnifiedFinding(finding, options),
+ );
+}
+
export function buildPatrolAssessmentAssistantHandoff(
input: PatrolAssessmentAssistantHandoffInput,
): PatrolAssessmentAssistantHandoff {
@@ -570,9 +635,9 @@ export function buildPatrolRunAssistantHandoff(run: PatrolRunRecord): PatrolRunA
export function buildPatrolConfigurationFailureHandoff(
input: PatrolConfigurationFailureInput,
): PatrolConfigurationFailureHandoff {
- const message = normalizeText(input.message) || 'Patrol configuration could not be saved.';
+ const message = normalizeText(input.message) || 'Patrol mode could not be saved.';
const code = normalizeText(input.code);
- const issueLabel = input.saved ? 'Patrol configuration issue' : 'Patrol configuration failure';
+ const issueLabel = input.saved ? 'Patrol mode issue' : 'Patrol mode save failure';
const readinessSummary = normalizeText(input.readiness?.summary);
const cause = normalizeText(input.readiness?.cause) || normalizeText(input.blockedCause);
const provider = normalizeText(input.readiness?.provider);
@@ -607,7 +672,7 @@ export function buildPatrolConfigurationFailureHandoff(
evidence: formatConfigurationFailureDetails(input.details).slice(0, 4),
actionLabel: `Review ${issueLabel}`,
safetyNote:
- 'Assistant can explain the configuration state; provider changes, retries, and remediation remain operator-controlled.',
+ 'Assistant can explain the Patrol mode state; provider changes, retries, and remediation remain operator-controlled.',
},
context: {
source: 'pulse-patrol-configuration-failure',
@@ -870,14 +935,14 @@ function buildPatrolConfigurationFailureModelContext(
): string {
const details = formatConfigurationFailureDetails(input.details);
return [
- '[Patrol Configuration Failure Context]',
- 'Source: Pulse Patrol configuration surface',
+ '[Patrol Control Save Failure Context]',
+ 'Source: Pulse Patrol mode surface',
formatContextLine('Server Message', message),
formatContextLine('Server Code', input.code),
input.status ? `HTTP Status: ${input.status}` : undefined,
- ...detailLines.map((line) => formatContextLine('Configuration Detail', line)),
+ ...detailLines.map((line) => formatContextLine('Control Detail', line)),
...details.map((line) => formatContextLine('Backend Detail', line)),
- 'Model Boundary: This Patrol configuration handoff is model-only context for explanation and review. Provider changes, retries, diagnostics, remediation, and command execution require explicit governed operator action.',
+ 'Model Boundary: This Patrol mode handoff is model-only context for explanation and review. Provider changes, retries, diagnostics, remediation, and command execution require explicit governed operator action.',
]
.filter(isNonEmptyString)
.join('\n');
@@ -889,7 +954,7 @@ function formatConfigurationFailureSettings(
const settings = [
input.autonomyLevel ? `mode ${input.autonomyLevel}` : undefined,
typeof input.fullModeUnlocked === 'boolean'
- ? `autonomous critical remediation ${input.fullModeUnlocked ? 'enabled' : 'disabled'}`
+ ? `automatic critical fixes ${input.fullModeUnlocked ? 'enabled' : 'disabled'}`
: undefined,
typeof input.investigationBudget === 'number'
? `budget ${input.investigationBudget}`
@@ -1444,7 +1509,7 @@ function formatAssessmentLatestRun(
normalizeText(latestRun.status?.label),
normalizeText(latestRun.timestamp),
normalizeText(latestRun.coverageSummary),
- latestRun.findingsSnapshotAvailable === false ? 'findings snapshot unavailable' : undefined,
+ latestRun.findingsSnapshotAvailable === false ? 'finding record unavailable' : undefined,
]
.filter(isNonEmptyString)
.join('; ');
@@ -2209,6 +2274,7 @@ const GOVERNED_ACTION_OUTCOMES = new Set([
'fix_queued',
'fix_executed',
'fix_failed',
+ 'fix_rejected',
'fix_verified',
'fix_verification_failed',
'fix_verification_unknown',
diff --git a/frontend-modern/src/features/patrol/patrolSupportingContextPresentation.ts b/frontend-modern/src/features/patrol/patrolSupportingContextPresentation.ts
deleted file mode 100644
index d0a922f3a8..0000000000
--- a/frontend-modern/src/features/patrol/patrolSupportingContextPresentation.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-export const PATROL_SUPPORTING_CONTEXT_TITLE = 'Supporting context';
-export const PATROL_SUPPORTING_CONTEXT_DESCRIPTION =
- 'Recent changes, learned correlations, and policy coverage that may explain findings or incomplete verification.';
-export const PATROL_SUPPORTING_CONTEXT_EVIDENCE_LABEL = 'How to read this';
-export const PATROL_SUPPORTING_CONTEXT_EVIDENCE_NOTE =
- 'Findings and run history are Patrol verification evidence. The cards below add explanatory context and do not count as a fresh full patrol.';
-export const PATROL_SUPPORTING_CONTEXT_CHANGE_SUBTITLE =
- 'Observed from the canonical timeline in the last 24 hours.';
-export const PATROL_SUPPORTING_CONTEXT_POLICY_SUBTITLE =
- 'Coverage posture for policy-covered resources.';
-
-export function getPatrolSupportingContextToggleLabel(expanded: boolean) {
- return expanded ? 'Hide supporting context' : 'View supporting context';
-}
-
-export function getPatrolSupportingContextCorrelationSummary(count: number) {
- if (!Number.isFinite(count) || count <= 0) {
- return 'Learned pattern context';
- }
- return `${count} learned pattern${count === 1 ? '' : 's'} · explanatory context`;
-}
diff --git a/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts b/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts
index 078e6a2083..67808e63e8 100644
--- a/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts
+++ b/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts
@@ -11,38 +11,120 @@ import {
type PatrolRuntimeState,
type PatrolStatus,
} from '@/api/patrol';
+import {
+ AIChatAPI,
+ type AssistantWorkflowPromptActivitySurface,
+ PULSE_OPERATIONS_LOOP_WORKFLOW_PROMPT_NAME,
+ PULSE_PATROL_CONTROL_WORKFLOW_PROMPT_SURFACE,
+ PULSE_PATROL_WORKFLOW_PROMPT_SURFACE,
+} from '@/api/aiChat';
import { aiIntelligenceStore } from '@/stores/aiIntelligence';
import {
- aiRuntimeModels,
aiRuntimeSettings,
loadAIRuntimeModels,
loadAIRuntimeSettings,
syncAIRuntimeSettings,
} from '@/stores/aiRuntimeState';
-import { aiChatStore } from '@/stores/aiChat';
+import { aiChatStore, type AIChatContext } from '@/stores/aiChat';
import { notificationStore } from '@/stores/notifications';
import { usePatrolStream } from '@/hooks/usePatrolStream';
import { createNonSuspendingQuery } from '@/hooks/createNonSuspendingQuery';
-import { hasFeature, loadRuntimeCapabilities } from '@/stores/license';
+import {
+ getRuntimeCapabilityBlock,
+ hasFeature,
+ loadRuntimeCapabilities,
+ runtimeCapabilities,
+} from '@/stores/license';
+import { PATROL_AUTONOMY_FEATURE_KEY } from './patrolAutonomyAvailability';
import type { AISettings } from '@/types/ai';
+import {
+ hasFindingInvestigationHandoffPointer,
+ isPatrolRuntimeFinding,
+} from '@/utils/aiFindingPresentation';
import { getCanonicalScopeResourceIds } from '@/utils/patrolFormat';
import { normalizePatrolRuntimeBlockedReason } from '@/utils/patrolRuntimePresentation';
+import { logger } from '@/utils/logger';
+import {
+ parsePatrolControlStarter,
+ PATROL_CONTROL_STARTER,
+ PATROL_CONTROL_STARTER_QUERY_PARAM,
+ PATROL_OPERATIONS_LOOP_STARTER_QUERY_PARAM,
+} from '@/routing/resourceLinks';
import {
- buildPatrolConfigurationFailureHandoff,
- buildPatrolInvestigationContextSummary,
- selectPatrolSupportingRecentChanges,
+ buildPatrolAssistantApprovalBriefingInput,
+ buildPatrolAssistantFindingHandoffFromUnifiedFinding,
+ buildPatrolAssistantProposedFixBriefingInput,
+ buildPatrolAssistantProposedFixBriefingInputFromApproval,
+ patrolAssistantFindingHandoffRequiresApprovalMode,
+ type PatrolAssistantApprovalBriefingInput,
+ type PatrolAssistantFindingHandoff,
type PatrolConfigurationFailureInput,
} from './patrolInvestigationContextModel';
type PatrolTab = 'findings' | 'history';
-type PatrolAPIError = Error & {
- code?: string;
- details?: Record<string, string>;
- status?: number;
+const PATROL_GOVERNED_ACTION_OUTCOMES = new Set([
+ 'fix_executed',
+ 'fix_failed',
+ 'fix_rejected',
+ 'fix_verified',
+ 'fix_verification_failed',
+ 'fix_verification_unknown',
+]);
+const PATROL_VERIFIED_OUTCOMES = new Set(['fix_verified']);
+const PATROL_OPERATIONS_LOOP_WORKFLOW_PROMPT = PULSE_OPERATIONS_LOOP_WORKFLOW_PROMPT_NAME;
+
+const recordPatrolWorkflowStarterActivityForSurface = async (
+ surface: AssistantWorkflowPromptActivitySurface,
+ logContext: string,
+): Promise<void> => {
+ try {
+ await AIChatAPI.recordWorkflowPromptActivity({
+ name: PULSE_OPERATIONS_LOOP_WORKFLOW_PROMPT_NAME,
+ surface,
+ });
+ } catch (error) {
+ logger.debug(`[${logContext}] Failed to record Patrol workflow starter`, error);
+ }
};
export const PATROL_REFRESH_TIMEOUT_MS = 15000;
+export const PATROL_MANUAL_SYNC_TIMEOUT_MS = 5000;
+
+export function recordPatrolWorkflowStarterActivity(): void {
+ void recordPatrolWorkflowStarterActivityForSurface(
+ PULSE_PATROL_WORKFLOW_PROMPT_SURFACE,
+ 'Patrol',
+ );
+}
+
+export function recordPatrolControlStarterActivity(): Promise<void> {
+ return recordPatrolWorkflowStarterActivityForSurface(
+ PULSE_PATROL_CONTROL_WORKFLOW_PROMPT_SURFACE,
+ 'Patrol mode handoff',
+ );
+}
+
+interface PatrolAssistantWorkflowHandoffOptions {
+ recordStarterActivity?: () => void;
+ openAssistant?: (context: AIChatContext) => void;
+}
+
+export function openPatrolAssistantWorkflowHandoff(
+ handoff: PatrolAssistantFindingHandoff,
+ options: PatrolAssistantWorkflowHandoffOptions = {},
+): void {
+ const {
+ recordStarterActivity = recordPatrolWorkflowStarterActivity,
+ openAssistant = (context) => aiChatStore.open(context),
+ } = options;
+
+ recordStarterActivity();
+ openAssistant({
+ ...handoff.context,
+ preferredWorkflowPromptName: PATROL_OPERATIONS_LOOP_WORKFLOW_PROMPT,
+ });
+}
const patrolErrorMessage = (error: unknown, fallback: string) =>
error instanceof Error && error.message.trim() ? error.message : fallback;
@@ -66,7 +148,7 @@ export function resolvePatrolAutonomyLevelForSave(
autoFixLocked: boolean,
): PatrolAutonomyLevel {
if (autoFixLocked) return 'monitor';
- if (level === 'assisted' || level === 'full') {
+ if (level === 'full') {
return fullModeUnlocked ? 'full' : 'assisted';
}
return level;
@@ -81,12 +163,12 @@ export function resolvePatrolAutonomySettingsForSave({
fullModeUnlocked: boolean;
autoFixLocked: boolean;
}): { autonomyLevel: PatrolAutonomyLevel; fullModeUnlocked: boolean } {
- const canUseFullMode =
- !autoFixLocked && (level === 'assisted' || level === 'full') && fullModeUnlocked;
+ const canUseFullMode = !autoFixLocked && level === 'full' && fullModeUnlocked;
+ const autonomyLevel = resolvePatrolAutonomyLevelForSave(level, canUseFullMode, autoFixLocked);
return {
- autonomyLevel: resolvePatrolAutonomyLevelForSave(level, canUseFullMode, autoFixLocked),
- fullModeUnlocked: canUseFullMode,
+ autonomyLevel,
+ fullModeUnlocked: autonomyLevel === 'full',
};
}
@@ -141,11 +223,11 @@ export function buildPatrolSettingsReadinessFailure({
export function usePatrolIntelligenceState() {
const [initialSurfaceReady, setInitialSurfaceReady] = createSignal(false);
const [activeTab, setActiveTab] = createSignal<PatrolTab>('findings');
- const [showInvestigationContext, setShowInvestigationContext] = createSignal(false);
const [findingsFilterOverride, setFindingsFilterOverride] = createSignal<
'all' | 'active' | 'resolved' | 'approvals' | 'attention' | undefined
>(undefined);
const [isRefreshing, setIsRefreshing] = createSignal(false);
+ const [isManualRefreshRunning, setIsManualRefreshRunning] = createSignal(false);
const [autonomyLevel, setAutonomyLevel] = createSignal<PatrolAutonomyLevel>('monitor');
const [isUpdatingAutonomy, setIsUpdatingAutonomy] = createSignal(false);
const [activityRefreshTrigger, setActivityRefreshTrigger] = createSignal(0);
@@ -154,44 +236,23 @@ export function usePatrolIntelligenceState() {
const [liveRunStartedAt, setLiveRunStartedAt] = createSignal('');
const [investigationBudget, setInvestigationBudget] = createSignal(15);
const [investigationTimeout, setInvestigationTimeout] = createSignal(300);
- const [showAdvancedSettings, setShowAdvancedSettings] = createSignal(false);
- const [isSavingAdvanced, setIsSavingAdvanced] = createSignal(false);
- const [advancedSettingsError, setAdvancedSettingsError] =
- createSignal<PatrolConfigurationFailureInput | null>(null);
const [fullModeUnlocked, setFullModeUnlocked] = createSignal(false);
- const availableModels = aiRuntimeModels;
- const [patrolModel, setPatrolModel] = createSignal<string>('');
- const [defaultModel, setDefaultModel] = createSignal<string>('');
- const [patrolInterval, setPatrolInterval] = createSignal<number>(360);
- const [isUpdatingSettings, setIsUpdatingSettings] = createSignal(false);
const [isTogglingPatrol, setIsTogglingPatrol] = createSignal(false);
const [isTriggeringPatrol, setIsTriggeringPatrol] = createSignal(false);
- const [alertTriggeredAnalysis, setAlertTriggeredAnalysis] = createSignal<boolean>(false);
- const [patrolAlertTriggers, setPatrolAlertTriggers] = createSignal<boolean>(true);
- const [patrolAlertTriggerMinSeverity, setPatrolAlertTriggerMinSeverity] = createSignal<
- 'warning' | 'critical'
- >('critical');
- const [patrolAnomalyTriggers, setPatrolAnomalyTriggers] = createSignal<boolean>(true);
const [selectedRun, setSelectedRun] = createSignal<PatrolRunRecord | null>(null);
- const [patrolModelSelectElement, setPatrolModelSelectElement] = createSignal<HTMLSelectElement>();
+ const [assistantHandoffFindingId, setAssistantHandoffFindingId] = createSignal('');
+ const [patrolLoadError, setPatrolLoadError] = createSignal('');
- let advancedSettingsRef: HTMLDivElement | undefined;
let safetyTimerRef: ReturnType<typeof setTimeout> | undefined;
let scrollToFindingTimerRef: ReturnType<typeof setTimeout> | undefined;
let findingScrollTimerRef: ReturnType<typeof setTimeout> | undefined;
let refreshTimeoutRef: ReturnType<typeof setTimeout> | undefined;
+ let manualRefreshTimeoutRef: ReturnType<typeof setTimeout> | undefined;
let refreshRequestId = 0;
+ let manualRefreshRequestId = 0;
let refreshInterval: ReturnType<typeof setInterval>;
let approvalPollInterval: ReturnType<typeof setInterval>;
- const setAdvancedSettingsRef = (element: HTMLDivElement | undefined) => {
- advancedSettingsRef = element;
- };
-
- const setPatrolModelSelectRef = (element: HTMLSelectElement | undefined) => {
- setPatrolModelSelectElement(() => element);
- };
-
const clearSafetyTimer = () => {
if (safetyTimerRef !== undefined) {
clearTimeout(safetyTimerRef);
@@ -213,6 +274,13 @@ export function usePatrolIntelligenceState() {
}
};
+ const clearManualRefreshTimeout = () => {
+ if (manualRefreshTimeoutRef !== undefined) {
+ clearTimeout(manualRefreshTimeoutRef);
+ manualRefreshTimeoutRef = undefined;
+ }
+ };
+
const finishRefresh = (requestId: number) => {
if (requestId !== refreshRequestId) {
return;
@@ -221,6 +289,19 @@ export function usePatrolIntelligenceState() {
setIsRefreshing(false);
};
+ const rememberPatrolLoadError = (error: unknown, fallback: string) => {
+ const message = patrolErrorMessage(error, fallback);
+ setPatrolLoadError(message);
+ logger.debug('[Patrol] Failed to refresh Patrol data', error);
+ return message;
+ };
+
+ const clearPatrolLoadError = () => {
+ if (patrolLoadError()) {
+ setPatrolLoadError('');
+ }
+ };
+
const patrolStatusState = createNonSuspendingQuery<PatrolStatus | null, string>({
source: () => 'patrol-status',
cacheKey: () => 'patrol-status',
@@ -235,6 +316,10 @@ export function usePatrolIntelligenceState() {
});
const patrolStatus = patrolStatusState.value;
const refetchPatrolStatus = patrolStatusState.refetch;
+ const historicalRegressionCount = createMemo(() => {
+ const count = patrolStatus()?.trust?.regressed_at_least_once;
+ return typeof count === 'number' && Number.isFinite(count) ? Math.max(0, count) : 0;
+ });
const patrolStream = usePatrolStream({
running: () =>
@@ -252,48 +337,14 @@ export function usePatrolIntelligenceState() {
},
});
- const handleClickOutside = (event: MouseEvent) => {
- if (advancedSettingsRef && !advancedSettingsRef.contains(event.target as Node)) {
- if (advancedSettingsError()) return;
- setShowAdvancedSettings(false);
- }
- };
-
- createEffect(() => {
- if (showAdvancedSettings()) {
- document.addEventListener('mousedown', handleClickOutside);
- } else {
- document.removeEventListener('mousedown', handleClickOutside);
- setAdvancedSettingsError(null);
- }
- });
-
- createEffect(() => {
- const model = patrolModel();
- const select = patrolModelSelectElement();
- // Track model catalog changes so a valid selected model is reapplied after
- // async options are mounted into the configuration popover.
- availableModels();
- if (select) {
- select.value = model;
- }
- });
-
- const alertAnalysisLocked = createMemo(() => !hasFeature('ai_alerts'));
- const autoFixLocked = createMemo(() => !hasFeature('ai_autofix'));
+ const autoFixLocked = createMemo(() => !hasFeature(PATROL_AUTONOMY_FEATURE_KEY));
+ const autoFixCapabilityBlock = createMemo(() =>
+ getRuntimeCapabilityBlock(PATROL_AUTONOMY_FEATURE_KEY),
+ );
+ const licenseRuntimeIdentity = createMemo(() => runtimeCapabilities()?.runtime);
const applyPatrolAISettings = (data: AISettings | null | undefined) => {
- setPatrolModel(data?.patrol_model || '');
- setDefaultModel(data?.model || '');
- setPatrolInterval(data?.patrol_interval_minutes ?? 360);
setPatrolEnabledLocal(data?.patrol_enabled ?? true);
- setAlertTriggeredAnalysis(!alertAnalysisLocked() && data?.alert_triggered_analysis !== false);
- const legacyEventTriggersEnabled = data?.patrol_event_triggers_enabled !== false;
- setPatrolAlertTriggers(data?.patrol_alert_triggers_enabled ?? legacyEventTriggersEnabled);
- setPatrolAlertTriggerMinSeverity(
- data?.patrol_alert_trigger_min_severity === 'warning' ? 'warning' : 'critical',
- );
- setPatrolAnomalyTriggers(data?.patrol_anomaly_triggers_enabled ?? legacyEventTriggersEnabled);
};
createEffect(() => {
@@ -315,13 +366,14 @@ export function usePatrolIntelligenceState() {
blockedReason: blockedReason(),
blockedCause: patrolStatus()?.blocked_cause,
});
- setAdvancedSettingsError(failure);
+ if (failure) {
+ notificationStore.warning(failure.message);
+ }
};
async function handleTogglePatrol() {
if (isTogglingPatrol()) return;
setIsTogglingPatrol(true);
- setAdvancedSettingsError(null);
const previousValue = patrolEnabledLocal();
const newValue = !previousValue;
setPatrolEnabledLocal(newValue);
@@ -337,9 +389,6 @@ export function usePatrolIntelligenceState() {
} else {
setPatrolEnabledLocal(newValue);
}
- if (typeof data?.patrol_interval_minutes === 'number') {
- setPatrolInterval(data.patrol_interval_minutes);
- }
surfaceSavedPatrolReadinessIssue(
data,
'Patrol setting was saved, but Patrol is not ready to run.',
@@ -379,155 +428,19 @@ export function usePatrolIntelligenceState() {
try {
await triggerPatrolRun();
- await loadAllData();
} catch (err) {
console.error('Failed to trigger patrol run:', err);
setManualRunRequested(false);
notificationStore.error(patrolErrorMessage(err, 'Failed to start patrol run'));
clearSafetyTimer();
+ return;
} finally {
setIsTriggeringPatrol(false);
}
- }
- async function handleModelChange(modelId: string) {
- if (isUpdatingSettings()) return;
- setIsUpdatingSettings(true);
- setAdvancedSettingsError(null);
- try {
- const updated = await AIAPI.updateSettings({ patrol_model: modelId });
- syncAIRuntimeSettings(updated);
- setPatrolModel(updated.patrol_model || modelId);
- surfaceSavedPatrolReadinessIssue(
- updated,
- 'Patrol model was saved, but Patrol is not ready to run.',
- );
- await refetchPatrolStatus();
- } catch (err) {
- console.error('Failed to update patrol model:', err);
- setAdvancedSettingsError(buildAdvancedSettingsFailure(err, 'Failed to update Patrol model'));
- notificationStore.error(patrolErrorMessage(err, 'Failed to update patrol model'));
- } finally {
- setIsUpdatingSettings(false);
- }
- }
-
- async function handleIntervalChange(minutes: number) {
- if (isUpdatingSettings()) return;
- setIsUpdatingSettings(true);
- setAdvancedSettingsError(null);
- try {
- const updated = await AIAPI.updateSettings({ patrol_interval_minutes: minutes });
- syncAIRuntimeSettings(updated);
- setPatrolInterval(updated.patrol_interval_minutes ?? minutes);
- setPatrolEnabledLocal((updated.patrol_interval_minutes ?? minutes) > 0);
- surfaceSavedPatrolReadinessIssue(
- updated,
- 'Patrol schedule was saved, but Patrol is not ready to run.',
- );
- refetchPatrolStatus();
- } catch (err) {
- console.error('Failed to update patrol interval:', err);
- notificationStore.error(patrolErrorMessage(err, 'Failed to update patrol schedule'));
- } finally {
- setIsUpdatingSettings(false);
- }
- }
-
- async function handleAlertTriggeredAnalysisChange(enabled: boolean) {
- if (isUpdatingSettings()) return;
- setIsUpdatingSettings(true);
- setAdvancedSettingsError(null);
- const previous = alertTriggeredAnalysis();
- setAlertTriggeredAnalysis(enabled);
- try {
- const updated = await AIAPI.updateSettings({ alert_triggered_analysis: enabled });
- syncAIRuntimeSettings(updated);
- surfaceSavedPatrolReadinessIssue(
- updated,
- 'Patrol setting was saved, but Patrol is not ready to run.',
- );
- } catch (err) {
- console.error('Failed to update alert-triggered analysis:', err);
- setAlertTriggeredAnalysis(previous);
- notificationStore.error(patrolErrorMessage(err, 'Failed to update alert analysis setting'));
- } finally {
- setIsUpdatingSettings(false);
- }
- }
-
- async function handlePatrolAlertTriggersChange(enabled: boolean) {
- if (isUpdatingSettings()) return;
- setIsUpdatingSettings(true);
- setAdvancedSettingsError(null);
- const previous = patrolAlertTriggers();
- setPatrolAlertTriggers(enabled);
- try {
- const updated = await AIAPI.updateSettings({ patrol_alert_triggers_enabled: enabled });
- syncAIRuntimeSettings(updated);
- surfaceSavedPatrolReadinessIssue(
- updated,
- 'Patrol trigger setting was saved, but Patrol is not ready to run.',
- );
- } catch (err) {
- console.error('Failed to update alert-triggered patrols:', err);
- setPatrolAlertTriggers(previous);
- notificationStore.error(
- patrolErrorMessage(err, 'Failed to update alert-triggered Patrol setting'),
- );
- } finally {
- setIsUpdatingSettings(false);
- }
- }
-
- async function handlePatrolAlertTriggerMinSeverityChange(severity: 'warning' | 'critical') {
- if (isUpdatingSettings()) return;
- setIsUpdatingSettings(true);
- setAdvancedSettingsError(null);
- const previous = patrolAlertTriggerMinSeverity();
- setPatrolAlertTriggerMinSeverity(severity);
- try {
- const updated = await AIAPI.updateSettings({
- patrol_alert_trigger_min_severity: severity,
- });
- syncAIRuntimeSettings(updated);
- surfaceSavedPatrolReadinessIssue(
- updated,
- 'Patrol trigger setting was saved, but Patrol is not ready to run.',
- );
- } catch (err) {
- console.error('Failed to update alert-trigger severity threshold:', err);
- setPatrolAlertTriggerMinSeverity(previous);
- notificationStore.error(
- patrolErrorMessage(err, 'Failed to update alert-trigger severity threshold'),
- );
- } finally {
- setIsUpdatingSettings(false);
- }
- }
-
- async function handlePatrolAnomalyTriggersChange(enabled: boolean) {
- if (isUpdatingSettings()) return;
- setIsUpdatingSettings(true);
- setAdvancedSettingsError(null);
- const previous = patrolAnomalyTriggers();
- setPatrolAnomalyTriggers(enabled);
- try {
- const updated = await AIAPI.updateSettings({ patrol_anomaly_triggers_enabled: enabled });
- syncAIRuntimeSettings(updated);
- surfaceSavedPatrolReadinessIssue(
- updated,
- 'Patrol trigger setting was saved, but Patrol is not ready to run.',
- );
- } catch (err) {
- console.error('Failed to update anomaly-triggered patrols:', err);
- setPatrolAnomalyTriggers(previous);
- notificationStore.error(
- patrolErrorMessage(err, 'Failed to update anomaly-triggered Patrol setting'),
- );
- } finally {
- setIsUpdatingSettings(false);
- }
+ void loadAllData().catch((err) => {
+ console.error('Failed to refresh Patrol after starting run:', err);
+ });
}
const patrolRunHistory = createNonSuspendingQuery<PatrolRunRecord[], number>({
@@ -608,6 +521,9 @@ export function usePatrolIntelligenceState() {
const selectedRunScopeResourceIds = createMemo(() => getCanonicalScopeResourceIds(selectedRun()));
const allPatrolFindings = createMemo(() => aiIntelligenceStore.patrolFindings);
+ const patrolPendingApprovalCount = createMemo(
+ () => aiIntelligenceStore.patrolPendingApprovals.length,
+ );
const selectedRunPatrolFindings = createMemo(() => {
const run = selectedRun();
if (!run) return null;
@@ -618,29 +534,6 @@ export function usePatrolIntelligenceState() {
const intelligenceSummary = createMemo(() => aiIntelligenceStore.intelligenceSummary);
const circuitBreakerStatus = createMemo(() => aiIntelligenceStore.circuitBreakerStatus);
- const policyPosture = createMemo(() => intelligenceSummary()?.policy_posture);
- const supportingRecentChanges = createMemo(() =>
- selectPatrolSupportingRecentChanges(intelligenceSummary()?.recent_changes),
- );
- const supportingRecentChangeCount = createMemo(() => {
- if (Array.isArray(intelligenceSummary()?.recent_changes)) {
- return supportingRecentChanges().length;
- }
- return intelligenceSummary()?.recent_changes_count;
- });
- const investigationContext = createMemo(() =>
- buildPatrolInvestigationContextSummary({
- recentChangesCount: supportingRecentChangeCount(),
- correlations: aiIntelligenceStore.correlations,
- policyPosture: policyPosture(),
- }),
- );
- const correlationTotal = createMemo(() => investigationContext().correlationCount);
- const correlations = createMemo(() => aiIntelligenceStore.correlations?.correlations ?? []);
- const recentChangeCount = createMemo(() => investigationContext().recentChangeCount);
- const hasInvestigationContext = createMemo(() => investigationContext().hasContext);
- const investigationContextSummary = createMemo(() => investigationContext().summaryText);
-
const liveRunRecord = createMemo<PatrolRunRecord | null>(() => {
if (!shouldShowLiveRun()) return null;
return {
@@ -700,15 +593,20 @@ export function usePatrolIntelligenceState() {
async function handleAutonomyChange(level: PatrolAutonomyLevel) {
if (isUpdatingAutonomy()) return;
- if (autoFixLocked() && level !== 'monitor') return;
+ const controlLocked = autoFixLocked();
+ if (controlLocked && level !== 'monitor') return;
const previousLevel = autonomyLevel();
const previousFullModeUnlocked = fullModeUnlocked();
const effectiveSettings = resolvePatrolAutonomySettingsForSave({
level,
- fullModeUnlocked: fullModeUnlocked(),
- autoFixLocked: autoFixLocked(),
+ fullModeUnlocked: level === 'full',
+ autoFixLocked: controlLocked,
});
+ const shouldRecordPatrolControlStarter =
+ !controlLocked &&
+ (effectiveSettings.autonomyLevel !== previousLevel ||
+ effectiveSettings.fullModeUnlocked !== previousFullModeUnlocked);
setAutonomyLevel(effectiveSettings.autonomyLevel);
setFullModeUnlocked(effectiveSettings.fullModeUnlocked);
setIsUpdatingAutonomy(true);
@@ -720,102 +618,84 @@ export function usePatrolIntelligenceState() {
investigation_budget: investigationBudget(),
investigation_timeout_sec: investigationTimeout(),
});
+ if (shouldRecordPatrolControlStarter) {
+ await recordPatrolControlStarterActivity();
+ await loadVisiblePatrolData();
+ }
} catch (err) {
console.error('Failed to update autonomy:', err);
setAutonomyLevel(previousLevel);
setFullModeUnlocked(previousFullModeUnlocked);
- notificationStore.error((err as Error).message || 'Failed to update autonomy level');
+ notificationStore.error((err as Error).message || 'Failed to update Patrol mode');
} finally {
setIsUpdatingAutonomy(false);
}
}
- const buildAdvancedSettingsFailure = (
- err: unknown,
- fallback = 'Failed to save Patrol configuration',
- ): PatrolConfigurationFailureInput => {
- const apiError = err as PatrolAPIError;
- const message = patrolErrorMessage(err, fallback);
- const readiness = patrolReadiness();
- const apiDetails = apiError.details ?? {};
- const hasReadinessDetails =
- Boolean(apiDetails.status || apiDetails.provider || apiDetails.model) ||
- apiError.code === 'patrol_readiness_not_ready';
- const readinessSummary = apiDetails.readiness_summary ?? apiDetails.summary;
- return {
- message,
- code: apiError.code,
- status: apiError.status,
- details: apiError.details,
- autonomyLevel: autonomyLevel(),
- fullModeUnlocked: fullModeUnlocked(),
- investigationBudget: investigationBudget(),
- investigationTimeoutSec: investigationTimeout(),
- readiness: readiness
- ? {
- status: readiness.status,
- cause: readiness.cause,
- summary: readiness.summary,
- provider: readiness.provider,
- model: readiness.model,
- }
- : hasReadinessDetails
- ? {
- status: apiDetails.status,
- cause: apiDetails.cause,
- summary:
- readinessSummary ||
- (apiError.code === 'patrol_readiness_not_ready' ? message : undefined),
- provider: apiDetails.provider,
- model: apiDetails.model,
- }
- : null,
- runtimeState: runtimeState(),
- blockedReason: blockedReason(),
- blockedCause: patrolStatus()?.blocked_cause,
- };
- };
+ function handleAssistantFindingHandoff(findingId: string) {
+ setAssistantHandoffFindingId(findingId.trim());
+ }
+
+ const loadLatestInvestigationProposedFixBriefing = async (
+ finding: ReturnType<typeof allPatrolFindings>[number],
+ pendingApprovalBriefing: PatrolAssistantApprovalBriefingInput | undefined,
+ ) => {
+ if (finding.investigationRecord?.proposed_fix) {
+ return undefined;
+ }
+ const hasInvestigationPointer =
+ hasFindingInvestigationHandoffPointer(finding) || Boolean(pendingApprovalBriefing?.id);
+ if (!hasInvestigationPointer) {
+ return undefined;
+ }
+ if (
+ !patrolAssistantFindingHandoffRequiresApprovalMode({
+ investigationOutcome: finding.investigationOutcome,
+ remediationId: finding.remediationPlanId,
+ pendingApproval: pendingApprovalBriefing,
+ investigationRecord: finding.investigationRecord,
+ })
+ ) {
+ return undefined;
+ }
- async function saveAdvancedSettings() {
- setIsSavingAdvanced(true);
- setAdvancedSettingsError(null);
try {
- const effectiveSettings = resolvePatrolAutonomySettingsForSave({
- level: autonomyLevel(),
- fullModeUnlocked: fullModeUnlocked(),
- autoFixLocked: autoFixLocked(),
- });
- setAutonomyLevel(effectiveSettings.autonomyLevel);
- setFullModeUnlocked(effectiveSettings.fullModeUnlocked);
+ const investigation = await AIAPI.getInvestigation(finding.id);
+ return buildPatrolAssistantProposedFixBriefingInput(investigation?.proposed_fix);
+ } catch {
+ return undefined;
+ }
+ };
- const result = await updatePatrolAutonomySettings({
- autonomy_level: effectiveSettings.autonomyLevel,
- full_mode_unlocked: effectiveSettings.fullModeUnlocked,
- investigation_budget: investigationBudget(),
- investigation_timeout_sec: investigationTimeout(),
- });
- if (result.settings) {
- setAutonomyLevel(result.settings.autonomy_level);
- setFullModeUnlocked(result.settings.full_mode_unlocked);
- }
- setAdvancedSettingsError(null);
- setShowAdvancedSettings(false);
- } catch (err) {
- console.error('Failed to save advanced settings:', err);
- const failure = buildAdvancedSettingsFailure(err);
- setAdvancedSettingsError(failure);
- await refetchPatrolStatus();
- } finally {
- setIsSavingAdvanced(false);
+ async function openAssistantOperationsLoopForFinding(findingId: string): Promise<boolean> {
+ const normalizedFindingId = findingId.trim();
+ if (!normalizedFindingId) return false;
+
+ const finding = allPatrolFindings().find((candidate) => candidate.id === normalizedFindingId);
+ if (!finding) {
+ return false;
}
- }
- function openAdvancedSettingsErrorInAssistant() {
- const failure = advancedSettingsError();
- if (!failure) return;
- const handoff = buildPatrolConfigurationFailureHandoff(failure);
- aiChatStore.open(handoff.context);
- setShowAdvancedSettings(false);
+ await aiIntelligenceStore.loadPendingApprovals();
+ const pendingApproval = aiIntelligenceStore.patrolPendingApprovals.find(
+ (approval) => approval.toolId === 'investigation_fix' && approval.targetId === finding.id,
+ );
+ const pendingApprovalBriefing = buildPatrolAssistantApprovalBriefingInput(pendingApproval);
+ const latestInvestigationProposedFix = await loadLatestInvestigationProposedFixBriefing(
+ finding,
+ pendingApprovalBriefing,
+ );
+ const proposedFix =
+ latestInvestigationProposedFix ||
+ buildPatrolAssistantProposedFixBriefingInputFromApproval(pendingApproval);
+ const handoff = buildPatrolAssistantFindingHandoffFromUnifiedFinding(finding, {
+ pendingApproval: pendingApprovalBriefing,
+ proposedFix,
+ });
+
+ openPatrolAssistantWorkflowHandoff(handoff);
+ setAssistantHandoffFindingId(finding.id);
+ return true;
}
function startPolling() {
@@ -842,15 +722,88 @@ export function usePatrolIntelligenceState() {
}, PATROL_REFRESH_TIMEOUT_MS);
try {
- await Promise.all([aiIntelligenceStore.loadDashboardData(), refetchPatrolStatus()]);
+ await Promise.all([
+ aiIntelligenceStore.loadDashboardData(),
+ refetchPatrolStatus(),
+ ]);
if (requestId === refreshRequestId) {
+ clearPatrolLoadError();
setActivityRefreshTrigger((prev) => prev + 1);
}
+ } catch (error) {
+ if (requestId === refreshRequestId) {
+ rememberPatrolLoadError(error, 'Patrol could not refresh.');
+ }
} finally {
finishRefresh(requestId);
}
}
+ async function loadVisiblePatrolData() {
+ try {
+ await Promise.all([
+ refetchPatrolStatus(),
+ aiIntelligenceStore.loadPatrolFindings(),
+ aiIntelligenceStore.loadPendingApprovals(),
+ patrolRunHistory.refetch({ background: true }),
+ ]);
+ clearPatrolLoadError();
+ } catch (error) {
+ rememberPatrolLoadError(error, 'Patrol could not refresh.');
+ }
+ }
+
+ function loadSupportingPatrolDataInBackground() {
+ void Promise.allSettled([
+ aiIntelligenceStore.loadIntelligenceSummary(),
+ aiIntelligenceStore.loadFindings(),
+ aiIntelligenceStore.loadCircuitBreakerStatus(),
+ aiIntelligenceStore.loadCorrelations(),
+ ]);
+ }
+
+ async function handleRefreshPatrol() {
+ if (isManualRefreshRunning()) return;
+ const requestId = ++manualRefreshRequestId;
+ clearManualRefreshTimeout();
+ setIsManualRefreshRunning(true);
+ manualRefreshTimeoutRef = setTimeout(() => {
+ if (requestId === manualRefreshRequestId) {
+ manualRefreshTimeoutRef = undefined;
+ setIsManualRefreshRunning(false);
+ }
+ }, PATROL_MANUAL_SYNC_TIMEOUT_MS);
+
+ try {
+ await loadVisiblePatrolData();
+ loadSupportingPatrolDataInBackground();
+ } finally {
+ if (requestId === manualRefreshRequestId) {
+ clearManualRefreshTimeout();
+ setIsManualRefreshRunning(false);
+ }
+ }
+ }
+
+ async function consumeRoutePatrolControlStarterHandoff() {
+ if (typeof window === 'undefined') {
+ return;
+ }
+
+ const starter = parsePatrolControlStarter(window.location.search);
+ if (starter !== PATROL_CONTROL_STARTER) {
+ return;
+ }
+
+ const nextUrl = new URL(window.location.href);
+ nextUrl.searchParams.delete(PATROL_CONTROL_STARTER_QUERY_PARAM);
+ nextUrl.searchParams.delete(PATROL_OPERATIONS_LOOP_STARTER_QUERY_PARAM);
+ const nextPath = `${nextUrl.pathname}${nextUrl.search}${nextUrl.hash}`;
+
+ await recordPatrolControlStarterActivity();
+ window.history.replaceState(window.history.state, '', nextPath);
+ }
+
const summaryStats = () => {
const patrolFindings = allPatrolFindings();
const activeFindings = patrolFindings.filter((finding) => finding.status === 'active');
@@ -871,26 +824,61 @@ export function usePatrolIntelligenceState() {
const activePatrolFindings = () =>
allPatrolFindings().filter((finding) => finding.status === 'active');
- const shouldSurfaceInvestigationContext = createMemo(() => {
- if (!hasInvestigationContext()) {
- return false;
- }
-
- if (selectedRun()) {
+ const shouldShowPatrolSetupOnly = createMemo(() => {
+ const activeFindings = activePatrolFindings();
+ if (readinessBlocksPatrol() && activeFindings.length === 0) {
return true;
}
-
- if (activePatrolFindings().length > 0) {
- return true;
- }
-
- const overallHealth = intelligenceSummary()?.overall_health;
- if (!overallHealth) {
- return false;
- }
-
- return overallHealth.grade !== 'A' || overallHealth.factors.length > 0;
+ return activeFindings.length > 0 && activeFindings.every(isPatrolRuntimeFinding);
+ });
+ const patrolWorkIssueEvidenceCount = createMemo(() => {
+ const issueFindingCount = allPatrolFindings().filter(
+ (finding) =>
+ finding.status === 'active' ||
+ finding.status === 'resolved' ||
+ Boolean(finding.investigationSessionId) ||
+ Boolean(finding.investigationStatus) ||
+ Boolean(finding.investigationOutcome) ||
+ Boolean(finding.remediationPlanId),
+ ).length;
+ const status = patrolStatus();
+ const statusFindingCount =
+ (status?.findings_count ?? 0) +
+ (status?.fixed_count ?? 0) +
+ (status?.trust?.resolved ?? 0) +
+ (status?.trust?.fix_verified ?? 0);
+ return issueFindingCount + patrolPendingApprovalCount() + statusFindingCount;
});
+ const patrolWorkEvidenceCount = createMemo(
+ () =>
+ (patrolRunHistory.value()?.length ?? 0) +
+ allPatrolFindings().length +
+ (patrolStatus()?.last_patrol_at || patrolStatus()?.last_activity_at ? 1 : 0),
+ );
+ const patrolGovernedActionCount = createMemo(
+ () =>
+ allPatrolFindings().filter(
+ (finding) =>
+ finding.investigationOutcome &&
+ PATROL_GOVERNED_ACTION_OUTCOMES.has(finding.investigationOutcome),
+ ).length,
+ );
+ const patrolRejectedDecisionCount = createMemo(
+ () =>
+ allPatrolFindings().filter((finding) => finding.investigationOutcome === 'fix_rejected')
+ .length,
+ );
+ const patrolApprovedDecisionCount = createMemo(() =>
+ Math.max(0, patrolGovernedActionCount() - patrolRejectedDecisionCount()),
+ );
+ const patrolVerifiedOutcomeCount = createMemo(
+ () =>
+ allPatrolFindings().filter(
+ (finding) =>
+ finding.investigationOutcome &&
+ PATROL_VERIFIED_OUTCOMES.has(finding.investigationOutcome),
+ ).length,
+ );
const findingsTabBadgeFindings = createMemo(() => {
const snapshotFindings = selectedRunPatrolFindings();
if (snapshotFindings === null) {
@@ -911,13 +899,20 @@ export function usePatrolIntelligenceState() {
onMount(async () => {
try {
- await Promise.all([
+ await consumeRoutePatrolControlStarterHandoff();
+ const initialLoads = await Promise.allSettled([
loadRuntimeCapabilities(),
loadAllData(),
loadAutonomySettings(),
loadAIRuntimeModels(),
loadAIRuntimeSettings(),
]);
+ const failedLoad = initialLoads.find(
+ (result): result is PromiseRejectedResult => result.status === 'rejected',
+ );
+ if (failedLoad) {
+ rememberPatrolLoadError(failedLoad.reason, 'Patrol could not refresh.');
+ }
} finally {
setInitialSurfaceReady(true);
}
@@ -939,14 +934,15 @@ export function usePatrolIntelligenceState() {
onCleanup(() => {
document.removeEventListener('visibilitychange', handleVisibility);
clearRefreshTimeout();
+ clearManualRefreshTimeout();
});
});
onCleanup(() => {
- document.removeEventListener('mousedown', handleClickOutside);
stopPolling();
clearSafetyTimer();
clearScrollToFindingTimer();
+ clearManualRefreshTimeout();
if (findingScrollTimerRef !== undefined) {
clearTimeout(findingScrollTimerRef);
findingScrollTimerRef = undefined;
@@ -957,87 +953,72 @@ export function usePatrolIntelligenceState() {
activeTab,
activePatrolFindings,
activityRefreshTrigger,
- advancedSettingsError,
- alertAnalysisLocked,
- alertTriggeredAnalysis,
+ assistantHandoffFindingId,
autonomyLevel,
+ autoFixCapabilityBlock,
autoFixLocked,
- availableModels,
blockedAt,
blockedReason,
canTriggerPatrol,
circuitBreakerStatus,
- correlationTotal,
- correlations,
clearScrollToFindingTimer,
- defaultModel,
displayRunHistory,
findingsTabBadgeCount,
findingsTabBadgeFindings,
findingsFilterOverride,
fullModeUnlocked,
- handleAlertTriggeredAnalysisChange,
handleAutonomyChange,
- handleIntervalChange,
- handleModelChange,
- handlePatrolAlertTriggersChange,
- handlePatrolAlertTriggerMinSeverityChange,
- handlePatrolAnomalyTriggersChange,
+ handleAssistantFindingHandoff,
+ handleRefreshPatrol,
handleRunPatrol,
handleTogglePatrol,
- hasInvestigationContext,
+ historicalRegressionCount,
initialSurfaceReady,
intelligenceSummary,
- investigationContextSummary,
+ isManualRefreshRunning,
isRefreshing,
- isSavingAdvanced,
isTogglingPatrol,
isTriggeringPatrol,
- isUpdatingSettings,
+ isUpdatingAutonomy,
licenseRequired,
loadAllData,
+ licenseRuntimeIdentity,
manualRunRequested,
- openAdvancedSettingsErrorInAssistant,
+ openAssistantOperationsLoopForFinding,
patrolEnabledLocal,
- patrolAlertTriggers,
- patrolAlertTriggerMinSeverity,
- patrolAnomalyTriggers,
- patrolInterval,
- patrolModel,
+ patrolApprovedDecisionCount,
+ patrolGovernedActionCount,
patrolPreflight,
+ patrolLoadError,
+ patrolPendingApprovalCount,
patrolReadiness,
+ patrolRejectedDecisionCount,
patrolRunHistory,
+ patrolVerifiedOutcomeCount,
+ patrolWorkEvidenceCount,
+ patrolWorkIssueEvidenceCount,
runtimeState,
patrolStatus,
patrolStream,
- policyPosture,
- recentChangeCount,
- saveAdvancedSettings,
+ recordPatrolWorkflowStarterActivity,
selectedRun,
selectedRunFindingIds,
selectedRunHasFindingsSnapshot,
selectedRunScopeResourceIds,
setActiveTab,
- setAdvancedSettingsRef,
setFindingsFilterOverride,
setFullModeUnlocked,
- setPatrolModelSelectRef,
setSelectedRun,
- setShowAdvancedSettings,
- setShowInvestigationContext,
setFindingScrollTimer: (timer: ReturnType<typeof setTimeout> | undefined) => {
findingScrollTimerRef = timer;
},
setScrollToFindingTimer: (timer: ReturnType<typeof setTimeout> | undefined) => {
scrollToFindingTimerRef = timer;
},
- showAdvancedSettings,
showBlockedBanner,
showReadinessBanner,
- showInvestigationContext,
- shouldSurfaceInvestigationContext,
+ shouldShowPatrolSetupOnly,
summaryStats,
- supportingRecentChanges,
triggerPatrolDisabledReason,
};
}
diff --git a/frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx b/frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx
index 53d735036c..f4b0c8fd61 100644
--- a/frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx
+++ b/frontend-modern/src/features/proxmox/ProxmoxNodesTable.tsx
@@ -465,6 +465,7 @@ export const ProxmoxNodesTable: Component<{
total={memoryTotal()}
percentOnly={memoryPercentOnly()}
cache={drawerNode()?.memory?.cache || 0}
+ cacheInclusiveLabel="Shown in Proxmox"
swapUsed={drawerNode()?.memory?.swapUsed || 0}
swapTotal={drawerNode()?.memory?.swapTotal || 0}
/>
diff --git a/frontend-modern/src/features/proxmox/__tests__/ProxmoxNodesTable.test.tsx b/frontend-modern/src/features/proxmox/__tests__/ProxmoxNodesTable.test.tsx
index be45dc6156..fcc232d124 100644
--- a/frontend-modern/src/features/proxmox/__tests__/ProxmoxNodesTable.test.tsx
+++ b/frontend-modern/src/features/proxmox/__tests__/ProxmoxNodesTable.test.tsx
@@ -26,7 +26,12 @@ vi.mock('@/components/shared/responsive', () => ({
}));
vi.mock('@/components/Workloads/StackedMemoryBar', () => ({
- StackedMemoryBar: () => <div data-testid="stacked-memory-bar" />,
+ StackedMemoryBar: (props: { cacheInclusiveLabel?: string }) => (
+ <div
+ data-testid="stacked-memory-bar"
+ data-cache-inclusive-label={props.cacheInclusiveLabel}
+ />
+ ),
}));
vi.mock('@/components/Workloads/StackedDiskBar', () => ({
@@ -126,6 +131,33 @@ describe('ProxmoxNodesTable', () => {
).toHaveAttribute('href', 'https://pve-node-1:8006');
});
+ it('keeps the Proxmox cache-inclusive memory comparison label on node rows', () => {
+ render(() => (
+ <ProxmoxNodesTable
+ nodes={[
+ makeNodeResource({
+ memory: {
+ total: 8_000,
+ used: 3_200,
+ free: 3_800,
+ current: 40,
+ cache: 1_000,
+ } as Resource['memory'],
+ }),
+ ]}
+ guests={[]}
+ emptyIcon={<span />}
+ emptyTitle="No Proxmox VE nodes"
+ emptyDescription="No nodes"
+ />
+ ));
+
+ expect(screen.getByTestId('stacked-memory-bar')).toHaveAttribute(
+ 'data-cache-inclusive-label',
+ 'Shown in Proxmox',
+ );
+ });
+
it('restores the v5 row signals: alert accent, pending updates badge, full uptime, offline dimming', () => {
activeAlertsMock.value = {
'alert-1': {
diff --git a/frontend-modern/src/features/standalone/__tests__/AgentsMachinesTable.test.tsx b/frontend-modern/src/features/standalone/__tests__/AgentsMachinesTable.test.tsx
index b5191381cd..e3e09bf54e 100644
--- a/frontend-modern/src/features/standalone/__tests__/AgentsMachinesTable.test.tsx
+++ b/frontend-modern/src/features/standalone/__tests__/AgentsMachinesTable.test.tsx
@@ -61,6 +61,8 @@ vi.mock('@/components/Workloads/StackedMemoryBar', () => ({
total: number;
percentOnly?: number;
balloon?: number;
+ cache?: number;
+ cacheInclusiveLabel?: string;
swapUsed?: number;
swapTotal?: number;
resourceId?: string;
@@ -71,6 +73,8 @@ vi.mock('@/components/Workloads/StackedMemoryBar', () => ({
data-total={props.total}
data-percent-only={props.percentOnly}
data-balloon={props.balloon}
+ data-cache={props.cache}
+ data-cache-inclusive-label={props.cacheInclusiveLabel}
data-swap-used={props.swapUsed}
data-swap-total={props.swapTotal}
data-resource-id={props.resourceId}
@@ -140,6 +144,11 @@ describe('AgentsMachinesTable', () => {
osVersion: '7.2.2',
architecture: 'x86_64',
kernelVersion: '6.12.24',
+ memory: {
+ total: 100,
+ used: 32,
+ cache: 10,
+ },
networkInterfaces: [
{
name: 'br0',
@@ -187,6 +196,9 @@ describe('AgentsMachinesTable', () => {
expect(screen.getByRole('button', { name: 'Sort by IP' })).toBeInTheDocument();
expect(screen.getAllByText('192.168.0.10').length).toBeGreaterThan(0);
expect(screen.getByText('1 clean')).toBeInTheDocument();
+ const memoryBar = screen.getByTestId('agent-machine-memory-bar');
+ expect(memoryBar).toHaveAttribute('data-cache', '10');
+ expect(memoryBar).not.toHaveAttribute('data-cache-inclusive-label', 'Shown in Proxmox');
});
it('shows hostname and primary IP in the machine identity subtitle', () => {
diff --git a/frontend-modern/src/i18n/messages.de.ts b/frontend-modern/src/i18n/messages.de.ts
index 18541c9cb7..d61bf84307 100644
--- a/frontend-modern/src/i18n/messages.de.ts
+++ b/frontend-modern/src/i18n/messages.de.ts
@@ -306,7 +306,7 @@ export const DE_MESSAGE_OVERRIDES = {
'settings.general.temperature.title': 'Temperatureinheit',
'settings.general.telemetry.copyJson': 'JSON kopieren',
'settings.general.telemetry.description':
- 'Helfen Sie, Pulse zu verbessern, indem Sie anonyme ausgehende Nutzungsdaten teilen: eine rotierende Installations-ID, normalisierte Release-Identitaet, Laufzeitplattform, aggregierte Self-hosted-Nutzungszahlen und grobe Funktionsflags. Es werden keine Hostnamen, Zugangsdaten, Infrastrukturkennungen, Prompts, Chatnachrichten oder personenbezogenen Daten gesendet. Telemetriezeilen werden bis zu 90 Tage aufbewahrt, und IP-Adressen werden nicht in Telemetriezeilen gespeichert.',
+ 'Helfen Sie, Pulse zu verbessern, indem Sie anonyme ausgehende Nutzungsdaten teilen: eine rotierende Installations-ID, normalisierte Release-Identitaet, Laufzeitplattform, aggregierte Self-hosted-Nutzungszahlen, grobe Funktionsflags sowie grobe Nutzungszaehler fuer Patrol, Assistant und externe Agents. Es werden keine Hostnamen, Zugangsdaten, Infrastrukturkennungen, Prompts, Chatnachrichten, Befehlstexte, Aktionsausgaben, Token-Werte oder personenbezogenen Daten gesendet. Telemetriezeilen werden bis zu 90 Tage aufbewahrt, und IP-Adressen werden nicht in Telemetriezeilen gespeichert.',
'settings.general.telemetry.disabledPreview':
'Telemetrie ist derzeit deaktiviert. Diese Vorschau zeigt den Payload, den Pulse senden wuerde, wenn Sie sie aktivieren.',
'settings.general.telemetry.fullDetails': 'Details',
@@ -374,11 +374,20 @@ export const DE_MESSAGE_OVERRIDES = {
'Konfigurieren Sie die Echtzeit-Zustellung von Audit-Ereignissen an externe Systeme.',
'settings.header.securityWebhooks.title': 'Audit-Webhooks',
'settings.header.systemAi.description':
- 'Konfigurieren Sie Anbieter und Modelle fuer Pulse Assistant und Patrol.',
- 'settings.header.systemAi.title': 'Assistant & Patrol',
+ 'Konfigurieren Sie Anbieter, Standardmodelle, Anbieterzustand, Budget und Nutzung fuer Pulse Intelligence.',
+ 'settings.header.systemAi.title': 'Anbieter & Modelle',
+ 'settings.header.systemAiAssistant.description':
+ 'Konfigurieren Sie Chatverhalten, Aktionsrechte und Sitzungen des Assistant.',
+ 'settings.header.systemAiAssistant.title': 'Assistant',
+ 'settings.header.systemAiDiscovery.description':
+ 'Konfigurieren Sie den KI-gestuetzten Service-Kontext fuer Assistant und Patrol. Infrastruktur-Erkennung und Onboarding bleiben unter Infrastruktur.',
+ 'settings.header.systemAiDiscovery.title': 'Service-Kontext',
+ 'settings.header.systemAiPatrol.description':
+ 'Legen Sie fest, wann Patrol laeuft, was Patrol startet und welches Modell verwendet wird.',
+ 'settings.header.systemAiPatrol.title': 'Patrol',
'settings.header.systemBilling.description':
- 'Pruefen Sie, welchen Plan diese Instanz nutzt und welche optionalen Funktionen damit verbunden sind.',
- 'settings.header.systemBilling.title': 'Self-hosted-Plan',
+ 'Plan, Lizenz und Patrol-Modus fuer diese Instanz.',
+ 'settings.header.systemBilling.title': 'Plaene & Abrechnung',
'settings.header.systemGeneral.description':
'Verwalten Sie Darstellung, Layout und Standard-Monitoring-Takt.',
'settings.header.systemGeneral.title': 'Allgemein',
@@ -406,6 +415,7 @@ export const DE_MESSAGE_OVERRIDES = {
'settings.nav.group.infrastructure': 'Infrastruktur',
'settings.nav.group.monitoring': 'Monitoring',
'settings.nav.group.organization': 'Organisation',
+ 'settings.nav.group.pulseIntelligence': 'Pulse Intelligence',
'settings.nav.group.security': 'Sicherheit',
'settings.nav.group.support': 'Support',
'settings.nav.group.system': 'System',
@@ -418,12 +428,16 @@ export const DE_MESSAGE_OVERRIDES = {
'settings.nav.item.billingAdmin': 'Abrechnungsadmin',
'settings.nav.item.dataReports': 'Daten & Berichte',
'settings.nav.item.diagnosticsHealth': 'Diagnose & Zustand',
+ 'settings.nav.item.assistant': 'Assistant',
+ 'settings.nav.item.discovery': 'Service-Kontext',
'settings.nav.item.general': 'Allgemein',
'settings.nav.item.infrastructure': 'Infrastruktur',
'settings.nav.item.network': 'Netzwerk',
'settings.nav.item.organizationAccess': 'Zugriff',
'settings.nav.item.organizationOverview': 'Uebersicht',
- 'settings.nav.item.plans': 'Plaene',
+ 'settings.nav.item.patrol': 'Patrol',
+ 'settings.nav.item.plans': 'Plaene & Abrechnung',
+ 'settings.nav.item.providerModels': 'Anbieter & Modelle',
'settings.nav.item.recovery': 'Wiederherstellung',
'settings.nav.item.remoteAccess': 'Remote-Zugriff',
'settings.nav.item.resourcePrivacy': 'Ressourcenschutz',
@@ -434,7 +448,6 @@ export const DE_MESSAGE_OVERRIDES = {
'settings.nav.item.systemLogs': 'Systemprotokolle',
'settings.nav.item.updates': 'Updates',
'settings.nav.item.users': 'Benutzer',
- 'settings.nav.item.assistantPatrol': 'Assistant & Patrol',
'settings.shell.collapseSidebarLabel': 'Einstellungsnavigation einklappen',
'settings.shell.configurationLoading': 'Konfiguration wird geladen...',
'settings.shell.discardLabel': 'Verwerfen',
diff --git a/frontend-modern/src/i18n/messages.es.ts b/frontend-modern/src/i18n/messages.es.ts
index 75045fce32..37b53c7049 100644
--- a/frontend-modern/src/i18n/messages.es.ts
+++ b/frontend-modern/src/i18n/messages.es.ts
@@ -298,7 +298,7 @@ export const ES_MESSAGE_OVERRIDES = {
'settings.general.temperature.title': 'Unidad de temperatura',
'settings.general.telemetry.copyJson': 'Copiar JSON',
'settings.general.telemetry.description':
- 'Ayuda a mejorar Pulse compartiendo datos de uso salientes anónimos: un ID de instalación rotativo, identidad de versión normalizada, plataforma de ejecución, conteos agregados de adopción autohospedada y flags de funciones de alto nivel. No se envían hostnames, credenciales, identificadores de infraestructura, prompts, mensajes de chat ni información personal. Las filas de telemetría se conservan hasta 90 días y las direcciones IP no se guardan en filas de telemetría.',
+ 'Ayuda a mejorar Pulse compartiendo datos de uso salientes anónimos: un ID de instalación rotativo, identidad de versión normalizada, plataforma de ejecución, conteos agregados de adopción autohospedada, flags de funciones de alto nivel, y contadores generales de uso de Patrol, Assistant y agentes externos. No se envían hostnames, credenciales, identificadores de infraestructura, prompts, mensajes de chat, texto de comandos, salida de acciones, valores de tokens ni información personal. Las filas de telemetría se conservan hasta 90 días y las direcciones IP no se guardan en filas de telemetría.',
'settings.general.telemetry.disabledPreview':
'La telemetría está desactivada. Esta vista previa muestra el payload que Pulse enviaría si la activas.',
'settings.general.telemetry.fullDetails': 'Detalles completos',
@@ -366,11 +366,20 @@ export const ES_MESSAGE_OVERRIDES = {
'Configura la entrega en tiempo real de eventos de auditoría a sistemas externos.',
'settings.header.securityWebhooks.title': 'Webhooks de auditoría',
'settings.header.systemAi.description':
- 'Configura proveedores y modelos para Pulse Assistant y Patrol.',
- 'settings.header.systemAi.title': 'Assistant y Patrol',
+ 'Configura proveedores, modelos predeterminados, salud de proveedores, presupuesto y uso para Pulse Intelligence.',
+ 'settings.header.systemAi.title': 'Proveedores y modelos',
+ 'settings.header.systemAiAssistant.description':
+ 'Configura el comportamiento del chat, los permisos de acciones y las sesiones del Assistant.',
+ 'settings.header.systemAiAssistant.title': 'Assistant',
+ 'settings.header.systemAiDiscovery.description':
+ 'Configura el contexto de servicio asistido por IA que usan Assistant y Patrol. El descubrimiento y onboarding de infraestructura permanecen en Infraestructura.',
+ 'settings.header.systemAiDiscovery.title': 'Contexto de servicio',
+ 'settings.header.systemAiPatrol.description':
+ 'Configura cuando se ejecuta Patrol, que lo inicia y que modelo usa.',
+ 'settings.header.systemAiPatrol.title': 'Patrol',
'settings.header.systemBilling.description':
- 'Revisa el plan que usa esta instancia y las capacidades opcionales conectadas.',
- 'settings.header.systemBilling.title': 'Plan autohospedado',
+ 'Plan, licencia y modo de Patrol para esta instancia.',
+ 'settings.header.systemBilling.title': 'Planes y facturacion',
'settings.header.systemGeneral.description':
'Administra apariencia, diseño y cadencia predeterminada de supervisión.',
'settings.header.systemGeneral.title': 'General',
@@ -398,6 +407,7 @@ export const ES_MESSAGE_OVERRIDES = {
'settings.nav.group.infrastructure': 'Infraestructura',
'settings.nav.group.monitoring': 'Supervisión',
'settings.nav.group.organization': 'Organización',
+ 'settings.nav.group.pulseIntelligence': 'Pulse Intelligence',
'settings.nav.group.security': 'Seguridad',
'settings.nav.group.support': 'Soporte',
'settings.nav.group.system': 'Sistema',
@@ -410,12 +420,16 @@ export const ES_MESSAGE_OVERRIDES = {
'settings.nav.item.billingAdmin': 'Admin de facturación',
'settings.nav.item.dataReports': 'Datos e informes',
'settings.nav.item.diagnosticsHealth': 'Diagnóstico y salud',
+ 'settings.nav.item.assistant': 'Assistant',
+ 'settings.nav.item.discovery': 'Contexto de servicio',
'settings.nav.item.general': 'General',
'settings.nav.item.infrastructure': 'Infraestructura',
'settings.nav.item.network': 'Red',
'settings.nav.item.organizationAccess': 'Acceso',
'settings.nav.item.organizationOverview': 'Resumen',
- 'settings.nav.item.plans': 'Planes',
+ 'settings.nav.item.patrol': 'Patrol',
+ 'settings.nav.item.plans': 'Planes y facturacion',
+ 'settings.nav.item.providerModels': 'Proveedores y modelos',
'settings.nav.item.recovery': 'Recuperación',
'settings.nav.item.remoteAccess': 'Acceso remoto',
'settings.nav.item.resourcePrivacy': 'Privacidad de recursos',
@@ -426,7 +440,6 @@ export const ES_MESSAGE_OVERRIDES = {
'settings.nav.item.systemLogs': 'Logs del sistema',
'settings.nav.item.updates': 'Actualizaciones',
'settings.nav.item.users': 'Usuarios',
- 'settings.nav.item.assistantPatrol': 'Assistant y Patrol',
'settings.shell.collapseSidebarLabel': 'Contraer navegación de ajustes',
'settings.shell.configurationLoading': 'Cargando configuración...',
'settings.shell.discardLabel': 'Descartar',
diff --git a/frontend-modern/src/i18n/messages.ts b/frontend-modern/src/i18n/messages.ts
index 9ee468f57f..d906588252 100644
--- a/frontend-modern/src/i18n/messages.ts
+++ b/frontend-modern/src/i18n/messages.ts
@@ -292,7 +292,7 @@ export const EN_MESSAGES = {
'settings.general.temperature.title': 'Temperature unit',
'settings.general.telemetry.copyJson': 'Copy JSON',
'settings.general.telemetry.description':
- 'Help improve Pulse by sharing anonymous outbound usage data: a rotating install ID, normalized release identity, runtime platform, aggregate self-hosted adoption counts, and coarse feature flags. No hostnames, credentials, infrastructure identifiers, prompts, chat messages, or personal information are sent. Telemetry rows are retained for up to 90 days, and IP addresses are not stored in telemetry rows.',
+ 'Help improve Pulse by sharing anonymous outbound usage data: a rotating install ID, normalized release identity, runtime platform, aggregate self-hosted adoption counts, coarse feature flags, and coarse Patrol, Assistant, and external-agent usage counters. No hostnames, credentials, infrastructure identifiers, prompts, chat messages, command text, action output, token values, or personal information are sent. Telemetry rows are retained for up to 90 days, and IP addresses are not stored in telemetry rows.',
'settings.general.telemetry.disabledPreview':
'Telemetry is currently disabled. This preview shows the payload Pulse would send if you enable it.',
'settings.general.telemetry.fullDetails': 'Full details',
@@ -360,11 +360,19 @@ export const EN_MESSAGES = {
'Configure real-time delivery of audit events to external systems.',
'settings.header.securityWebhooks.title': 'Audit Webhooks',
'settings.header.systemAi.description':
- 'Configure providers and models for Pulse Assistant and Patrol.',
- 'settings.header.systemAi.title': 'Assistant & Patrol',
- 'settings.header.systemBilling.description':
- 'Review the plan this instance is using and the optional capabilities connected to it.',
- 'settings.header.systemBilling.title': 'Self-hosted plan',
+ 'Configure providers, default models, provider health, budget, and usage for Pulse Intelligence.',
+ 'settings.header.systemAi.title': 'Provider & Models',
+ 'settings.header.systemAiAssistant.description':
+ 'Configure Assistant chat behavior, chat action permissions, and sessions.',
+ 'settings.header.systemAiAssistant.title': 'Assistant',
+ 'settings.header.systemAiDiscovery.description':
+ 'Configure the model-backed service context Assistant and Patrol use. Infrastructure discovery and onboarding stay under Infrastructure.',
+ 'settings.header.systemAiDiscovery.title': 'Service Context',
+ 'settings.header.systemAiPatrol.description':
+ 'Set when Patrol runs, what starts it, and which model it uses.',
+ 'settings.header.systemAiPatrol.title': 'Patrol',
+ 'settings.header.systemBilling.description': 'Plan, license, and Patrol mode for this instance.',
+ 'settings.header.systemBilling.title': 'Plans & Billing',
'settings.header.systemGeneral.description':
'Manage appearance, layout, and default monitoring cadence.',
'settings.header.systemGeneral.title': 'General',
@@ -392,6 +400,7 @@ export const EN_MESSAGES = {
'settings.nav.group.infrastructure': 'Infrastructure',
'settings.nav.group.monitoring': 'Monitoring',
'settings.nav.group.organization': 'Organization',
+ 'settings.nav.group.pulseIntelligence': 'Pulse Intelligence',
'settings.nav.group.security': 'Security',
'settings.nav.group.support': 'Support',
'settings.nav.group.system': 'System',
@@ -404,12 +413,16 @@ export const EN_MESSAGES = {
'settings.nav.item.billingAdmin': 'Billing Admin',
'settings.nav.item.dataReports': 'Data & Reports',
'settings.nav.item.diagnosticsHealth': 'Diagnostics & Health',
+ 'settings.nav.item.assistant': 'Assistant',
+ 'settings.nav.item.discovery': 'Service Context',
'settings.nav.item.general': 'General',
'settings.nav.item.infrastructure': 'Infrastructure',
'settings.nav.item.network': 'Network',
'settings.nav.item.organizationAccess': 'Access',
'settings.nav.item.organizationOverview': 'Overview',
- 'settings.nav.item.plans': 'Plans',
+ 'settings.nav.item.patrol': 'Patrol',
+ 'settings.nav.item.plans': 'Plans & Billing',
+ 'settings.nav.item.providerModels': 'Provider & Models',
'settings.nav.item.recovery': 'Recovery',
'settings.nav.item.remoteAccess': 'Remote Access',
'settings.nav.item.resourcePrivacy': 'Resource Privacy',
@@ -420,7 +433,6 @@ export const EN_MESSAGES = {
'settings.nav.item.systemLogs': 'System Logs',
'settings.nav.item.updates': 'Updates',
'settings.nav.item.users': 'Users',
- 'settings.nav.item.assistantPatrol': 'Assistant & Patrol',
'settings.shell.collapseSidebarLabel': 'Collapse settings navigation',
'settings.shell.configurationLoading': 'Loading configuration...',
'settings.shell.discardLabel': 'Discard',
diff --git a/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx b/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx
index e8dff68116..7116133700 100644
--- a/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx
+++ b/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx
@@ -1,11 +1,21 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
-import { Suspense, createSignal } from 'solid-js';
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library';
+import { Suspense, createSignal, type JSX } from 'solid-js';
import { resetCreateNonSuspendingQueryCacheForTest } from '@/hooks/createNonSuspendingQuery';
+import {
+ PATROL_CONTROL_ANCHOR,
+ PATROL_CONTROL_STARTER,
+ PATROL_CONTROL_STARTER_QUERY_PARAM,
+ PATROL_OPERATIONS_LOOP_ANCHOR,
+} from '@/routing/resourceLinks';
import { resetAIRuntimeState } from '@/stores/aiRuntimeState';
-import { getPublicPricingUrl } from '@/utils/pricingHandoff';
+import {
+ getPublicPricingUrl,
+ SELF_HOSTED_PRO_BILLING_PLAN_SELECTION_HREF,
+} from '@/utils/pricingHandoff';
import patrolIntelligenceHeaderSource from '@/features/patrol/PatrolIntelligenceHeader.tsx?raw';
import patrolIntelligenceStateSource from '@/features/patrol/usePatrolIntelligenceState.ts?raw';
+import { AGENT_PATROL_CONTROL_STATUS_PATH } from '@/api/agentCapabilities';
import { AIIntelligence } from '../AIIntelligence';
@@ -104,14 +114,33 @@ const triggerPatrolRunMock = vi.fn();
const getPatrolRunHistoryMock = vi.fn();
const apiFetchJSONMock = vi.fn();
const hasFeatureMock = vi.fn();
+const runtimeCapabilitiesMock = vi.fn();
+const getRuntimeCapabilityBlockMock = vi.fn();
const licenseStatusMock = vi.fn();
const loadLicenseStatusMock = vi.fn();
const loadCommercialPostureMock = vi.fn();
const getUpgradeActionDestinationMock = vi.fn();
const getUpgradeActionUrlOrFallbackMock = vi.fn();
const presentationPolicyHidesUpgradePromptsMock = vi.fn();
+const presentationPolicyHidesCommercialSurfacesMock = vi.fn();
+
+vi.mock('@solidjs/router', () => ({
+ A: (props: {
+ href: string;
+ class?: string;
+ children?: JSX.Element;
+ 'aria-label'?: string;
+ title?: string;
+ }) => (
+ <a href={props.href} class={props.class} aria-label={props['aria-label']} title={props.title}>
+ {props.children}
+ </a>
+ ),
+ useLocation: () => ({ hash: '', pathname: '/patrol', search: '' }),
+}));
const notificationSuccessMock = vi.fn();
const notificationErrorMock = vi.fn();
+const recordWorkflowPromptActivityMock = vi.fn();
vi.mock('@/api/patrol', () => ({
getPatrolStatus: (...args: unknown[]) => getPatrolStatusMock(...args),
@@ -130,12 +159,23 @@ vi.mock('@/api/ai', () => ({
},
}));
+vi.mock('@/api/aiChat', () => ({
+ AIChatAPI: {
+ recordWorkflowPromptActivity: (...args: unknown[]) => recordWorkflowPromptActivityMock(...args),
+ },
+ PULSE_OPERATIONS_LOOP_WORKFLOW_PROMPT_NAME: 'pulse_operations_loop',
+ PULSE_PATROL_WORKFLOW_PROMPT_SURFACE: 'pulse_patrol',
+ PULSE_PATROL_CONTROL_WORKFLOW_PROMPT_SURFACE: 'patrol_control',
+}));
+
vi.mock('@/utils/apiClient', () => ({
apiFetchJSON: (...args: unknown[]) => apiFetchJSONMock(...args),
}));
vi.mock('@/stores/license', () => ({
hasFeature: (...args: unknown[]) => hasFeatureMock(...args),
+ getRuntimeCapabilityBlock: (...args: unknown[]) => getRuntimeCapabilityBlockMock(...args),
+ runtimeCapabilities: (...args: unknown[]) => runtimeCapabilitiesMock(...args),
loadRuntimeCapabilities: (...args: unknown[]) => loadLicenseStatusMock(...args),
}));
@@ -149,6 +189,7 @@ vi.mock('@/stores/licenseCommercial', () => ({
}));
vi.mock('@/stores/sessionPresentationPolicy', () => ({
+ presentationPolicyHidesCommercialSurfaces: () => presentationPolicyHidesCommercialSurfacesMock(),
presentationPolicyHidesUpgradePrompts: () => presentationPolicyHidesUpgradePromptsMock(),
}));
@@ -162,6 +203,7 @@ vi.mock('@/stores/notifications', () => ({
vi.mock('@/stores/aiIntelligence', () => {
const store = {
loadFindings: vi.fn().mockResolvedValue(undefined),
+ loadPatrolFindings: vi.fn().mockResolvedValue(undefined),
loadIntelligenceSummary: vi.fn().mockResolvedValue(undefined),
loadCircuitBreakerStatus: vi.fn().mockResolvedValue(undefined),
loadPendingApprovals: vi.fn().mockResolvedValue(undefined),
@@ -239,7 +281,6 @@ vi.mock('@/components/AI/FindingsPanel', () => ({
vi.mock('@/components/patrol', () => ({
ApprovalBanner: () => <div data-testid="approval-banner" />,
- PatrolStatusBar: () => <div data-testid="patrol-status-bar" />,
RunHistoryPanel: (props: { onSelectRun?: (run: Record<string, unknown> | null) => void }) => (
<div data-testid="run-history-panel">
<button type="button" onClick={() => props.onSelectRun?.(runHistoryState.selection)}>
@@ -338,15 +379,140 @@ const defaultAISettings = {
auto_fix_model: '',
};
+const defaultAgentCapabilitiesManifest = () => ({
+ version: 'v1',
+ surfaceContract: {
+ core: {
+ id: 'pulse_intelligence_core',
+ label: 'Pulse Intelligence Core',
+ description:
+ 'Canonical context, governed actions, safety gates, approval state, action audit, and verification.',
+ },
+ proactiveEngine: {
+ id: 'pulse_patrol',
+ label: 'Pulse Patrol',
+ description: 'The proactive detection and investigation engine.',
+ },
+ operatorSurfaces: [
+ {
+ id: 'pulse_mcp',
+ label: 'Pulse MCP',
+ description: 'The external-agent adapter.',
+ native: false,
+ externalAdapter: true,
+ affordances: {
+ tools: true,
+ resources: true,
+ prompts: true,
+ capabilityMetadata: true,
+ },
+ },
+ ],
+ },
+ surfaceToolContracts: [
+ {
+ surfaceId: 'pulse_mcp',
+ surfaceLabel: 'Pulse MCP',
+ toolSource: 'capability_manifest',
+ toolNames: [
+ 'get_patrol_control_status',
+ 'get_fleet_context',
+ 'get_resource_context',
+ 'list_findings',
+ 'plan_action',
+ 'decide_action',
+ 'execute_action',
+ 'resolve_finding',
+ ],
+ capabilityNames: [
+ 'get_patrol_control_status',
+ 'get_fleet_context',
+ 'get_resource_context',
+ 'list_findings',
+ 'plan_action',
+ 'decide_action',
+ 'execute_action',
+ 'resolve_finding',
+ ],
+ affordances: {
+ tools: true,
+ resources: true,
+ prompts: true,
+ capabilityMetadata: true,
+ },
+ },
+ ],
+ mcpAdapter: {
+ serverName: 'pulse',
+ command: 'pulse-mcp',
+ baseUrlFlag: '--base-url',
+ defaultBaseUrl: 'http://localhost:7655',
+ tokenEnv: 'PULSE_API_TOKEN',
+ configFamilies: [{ id: 'opencode', label: 'OpenCode', shape: 'opencode_mcp' }],
+ },
+ requiredScopes: [],
+ categories: [],
+ workflowPrompts: [{ name: 'pulse_operations_loop', label: 'Ask Patrol to handle an issue' }],
+ capabilities: [],
+});
+
+const defaultOperationsLoopStatus = (overrides: Record<string, unknown> = {}) => ({
+ nextAction: 'run_patrol',
+ progressLabel: 'Run Patrol to produce actionable issue evidence.',
+ steps: [
+ { id: 'patrol', label: 'Patrol', status: 'current', count: 0 },
+ { id: 'assistant', label: 'Assistant', status: 'pending' },
+ { id: 'governance', label: 'Governance', status: 'pending', count: 0 },
+ { id: 'verification', label: 'Verification', status: 'pending', count: 0 },
+ ],
+ patrolEvidenceCount: 0,
+ patrolIssueEvidenceCount: 0,
+ activeFindingCount: 0,
+ pendingApprovalCount: 0,
+ governedActionCount: 0,
+ approvedDecisionCount: 0,
+ rejectedDecisionCount: 0,
+ verifiedOutcomeCount: 0,
+ operationsLoopStarterCount: 0,
+ assistantOperationsLoopStarterCount: 0,
+ patrolOperationsLoopStarterCount: 0,
+ patrolControlOperationsLoopStarterCount: 0,
+ patrolControlCompletedOperationsLoopCount: 0,
+ patrolControlResolvedOperationsLoopCount: 0,
+ patrolControlValueState: 'not_started',
+ patrolAutonomyOperationsLoopStarterCount: 0,
+ patrolAutonomyCompletedOperationsLoopCount: 0,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ patrolAutonomyValueState: 'not_started',
+ proActivationOperationsLoopStarterCount: 0,
+ proActivationCompletedOperationsLoopCount: 0,
+ proActivationResolvedOperationsLoopCount: 0,
+ proActivationValueProofState: 'not_started',
+ mcpOperationsLoopStarterCount: 0,
+ externalAgentReady: true,
+ windowStart: '2026-06-01T00:00:00Z',
+ generatedAt: '2026-06-20T00:00:00Z',
+ ...overrides,
+});
+
describe('AIIntelligence entitlement gating', () => {
- it('keeps Patrol page refresh affordance bounded when supporting reads stall', () => {
+ it('keeps Patrol page data sync bounded without making it a primary action', () => {
expect(patrolIntelligenceStateSource).toContain('PATROL_REFRESH_TIMEOUT_MS');
expect(patrolIntelligenceStateSource).toContain('finishRefresh(requestId)');
expect(patrolIntelligenceStateSource).toContain('requestId === refreshRequestId');
+ expect(patrolIntelligenceStateSource).toContain('isManualRefreshRunning');
+ expect(patrolIntelligenceStateSource).toContain('handleRefreshPatrol');
+ expect(patrolIntelligenceStateSource).toContain('loadVisiblePatrolData');
+ expect(patrolIntelligenceStateSource).toContain('loadSupportingPatrolDataInBackground');
+ expect(patrolIntelligenceHeaderSource).not.toContain('state.handleRefreshPatrol()');
+ expect(patrolIntelligenceHeaderSource).not.toContain('Sync page data');
+ expect(patrolIntelligenceHeaderSource).not.toContain('animate-spin');
+ expect(patrolIntelligenceHeaderSource).not.toContain('Refresh Patrol');
});
- it('keeps Patrol header loading indicators on the shared LoadingSpinner primitive', () => {
- expect(patrolIntelligenceHeaderSource).toContain('LoadingSpinner');
+ it('keeps the advanced Patrol settings drawer out of the old save-spinner path', () => {
+ expect(patrolIntelligenceHeaderSource).not.toContain('LoadingSpinner');
+ expect(patrolIntelligenceHeaderSource).not.toContain('Save Patrol mode');
});
beforeEach(() => {
@@ -359,14 +525,18 @@ describe('AIIntelligence entitlement gating', () => {
getPatrolRunHistoryMock.mockReset();
apiFetchJSONMock.mockReset();
hasFeatureMock.mockReset();
+ runtimeCapabilitiesMock.mockReset();
+ getRuntimeCapabilityBlockMock.mockReset();
licenseStatusMock.mockReset();
loadLicenseStatusMock.mockReset();
loadCommercialPostureMock.mockReset();
getUpgradeActionDestinationMock.mockReset();
getUpgradeActionUrlOrFallbackMock.mockReset();
presentationPolicyHidesUpgradePromptsMock.mockReset();
+ presentationPolicyHidesCommercialSurfacesMock.mockReset();
notificationSuccessMock.mockReset();
notificationErrorMock.mockReset();
+ recordWorkflowPromptActivityMock.mockReset();
findingsPanelState.latestProps = null;
runHistoryState.selection = null;
intelligenceState.findings = [];
@@ -401,22 +571,41 @@ describe('AIIntelligence entitlement gating', () => {
if (path === '/api/settings/ai/update') {
return defaultAISettings;
}
+ if (path === '/api/agent/capabilities') {
+ return defaultAgentCapabilitiesManifest();
+ }
+ if (path === AGENT_PATROL_CONTROL_STATUS_PATH) {
+ return defaultOperationsLoopStatus();
+ }
return {};
});
hasFeatureMock.mockImplementation(
(feature: string) => !['ai_alerts', 'ai_autofix'].includes(feature),
);
+ runtimeCapabilitiesMock.mockReturnValue({
+ runtime: 'community',
+ capabilities: ['ai_intelligence'],
+ blocked_capabilities: [],
+ });
+ getRuntimeCapabilityBlockMock.mockReturnValue(undefined);
licenseStatusMock.mockReturnValue({ subscription_state: 'expired' });
loadLicenseStatusMock.mockResolvedValue(undefined);
loadCommercialPostureMock.mockResolvedValue(undefined);
- getUpgradeActionDestinationMock.mockImplementation((feature?: string) => ({
- href: getPublicPricingUrl(feature),
- external: true,
- }));
+ getUpgradeActionDestinationMock.mockImplementation((feature?: string) =>
+ feature === 'ai_autofix'
+ ? { href: SELF_HOSTED_PRO_BILLING_PLAN_SELECTION_HREF, external: false }
+ : {
+ href: getPublicPricingUrl(feature),
+ external: true,
+ },
+ );
getUpgradeActionUrlOrFallbackMock.mockImplementation((feature?: string) =>
getPublicPricingUrl(feature),
);
presentationPolicyHidesUpgradePromptsMock.mockReturnValue(false);
+ presentationPolicyHidesCommercialSurfacesMock.mockReturnValue(false);
+ recordWorkflowPromptActivityMock.mockResolvedValue(undefined);
+ window.history.replaceState({}, '', '/patrol');
getCorrelationsMock.mockResolvedValue({
correlations: [],
count: 0,
@@ -436,9 +625,108 @@ describe('AIIntelligence entitlement gating', () => {
expect(screen.getByTestId('pulse-patrol-logo')).toHaveAttribute('aria-hidden', 'true');
});
- it('surfaces Patrol readiness issues before a manual run can start', async () => {
+ it('keeps the Patrol route handoff anchored without rendering idle run prompts as current work', async () => {
+ getPatrolStatusMock.mockResolvedValue(defaultPatrolStatus({ license_required: false }));
+
+ render(() => <AIIntelligence />);
+
+ await waitFor(() => {
+ expect(screen.getByRole('heading', { name: 'Patrol' })).toBeInTheDocument();
+ });
+
+ expect(
+ screen.getByText('Patrol watches infrastructure and shows current issues.'),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(
+ 'Patrol watches, investigates, acts within the mode you choose, verifies outcomes, and records what happened.',
+ ),
+ ).not.toBeInTheDocument();
+ const patrolControlAnchor = document.getElementById(PATROL_CONTROL_ANCHOR);
+ const operationsLoopAnchor = document.getElementById(PATROL_OPERATIONS_LOOP_ANCHOR);
+ expect(patrolControlAnchor).not.toBeNull();
+ const patrolControl = within(patrolControlAnchor!);
+ expect(patrolControl.queryByRole('group', { name: 'Patrol mode' })).not.toBeInTheDocument();
+ expect(patrolControl.getByText('Patrol mode')).toBeInTheDocument();
+ expect(patrolControl.getAllByText('Watch only').length).toBeGreaterThan(0);
+ expect(
+ patrolControl.getByText('Patrol reports issues without making changes.'),
+ ).toBeInTheDocument();
+ expect(patrolControl.queryByRole('button', { name: 'Limits' })).not.toBeInTheDocument();
+ expect(patrolControl.queryByRole('button', { name: 'Ask first' })).toBeNull();
+ expect(patrolControl.queryByRole('button', { name: 'Safe auto-fix' })).toBeNull();
+ expect(patrolControl.queryByRole('button', { name: 'Autopilot' })).toBeNull();
+ expect(patrolControl.queryByText('Patrol handles')).not.toBeInTheDocument();
+ expect(patrolControl.queryByText('May do')).not.toBeInTheDocument();
+ expect(patrolControl.queryByText('Needs Pro for')).not.toBeInTheDocument();
+ expect(patrolControl.queryByText('Will not')).not.toBeInTheDocument();
+ expect(patrolControl.queryByText('Pro')).not.toBeInTheDocument();
+ expect(patrolControl.queryByRole('button', { name: 'Ask first Pro' })).toBeNull();
+ expect(patrolControl.queryByRole('button', { name: 'Safe auto-fix Pro' })).toBeNull();
+ expect(patrolControl.queryByRole('button', { name: 'Autopilot Pro' })).toBeNull();
+ expect(screen.getByRole('link', { name: 'Plans & Billing' })).toHaveAttribute(
+ 'href',
+ SELF_HOSTED_PRO_BILLING_PLAN_SELECTION_HREF,
+ );
+ expect(screen.queryByRole('link', { name: 'View plans' })).not.toBeInTheDocument();
+ expect(operationsLoopAnchor?.parentElement).toBe(patrolControlAnchor);
+ expect(screen.queryByTestId('patrol-current-work')).not.toBeInTheDocument();
+ expect(screen.getByText('Problems Patrol finds appear here.')).toBeInTheDocument();
+ expect(
+ screen.queryByText('Issues Patrol found. Infrastructure stays unchanged.'),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText('Current Patrol work')).not.toBeInTheDocument();
+ expect(screen.queryByText('Ready to run')).not.toBeInTheDocument();
+ expect(screen.queryByText('Current issue')).not.toBeInTheDocument();
+ expect(screen.queryByText('Recorded outcome')).not.toBeInTheDocument();
+ expect(screen.queryByText('Duty trail')).not.toBeInTheDocument();
+ expect(screen.queryByText('External agents')).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Pulse MCP' })).not.toBeInTheDocument();
+ expect(screen.getAllByRole('button', { name: 'Run Patrol' }).length).toBeGreaterThan(0);
+ });
+
+ it('consumes Patrol control route handoffs without loading legacy loop status', async () => {
+ window.history.replaceState(
+ {},
+ '',
+ `/patrol?${PATROL_CONTROL_STARTER_QUERY_PARAM}=${PATROL_CONTROL_STARTER}#${PATROL_CONTROL_ANCHOR}`,
+ );
+
+ render(() => <AIIntelligence />);
+
+ await waitFor(() => {
+ expect(recordWorkflowPromptActivityMock).toHaveBeenCalledWith({
+ name: 'pulse_operations_loop',
+ surface: 'patrol_control',
+ });
+ });
+
+ expect(
+ apiFetchJSONMock.mock.calls.some(([path]) => path === AGENT_PATROL_CONTROL_STATUS_PATH),
+ ).toBe(false);
+ await waitFor(() => {
+ expect(window.location.pathname).toBe('/patrol');
+ expect(window.location.search).toBe('');
+ expect(window.location.hash).toBe(`#${PATROL_CONTROL_ANCHOR}`);
+ });
+ });
+
+ it('surfaces provider issues before a manual run can start', async () => {
getPatrolStatusMock.mockResolvedValue(
defaultPatrolStatus({
+ trigger_status: {
+ running: false,
+ pending_triggers: 0,
+ current_interval_ms: 300000,
+ recent_events: 0,
+ is_busy_mode: false,
+ alert_triggers_enabled: true,
+ anomaly_triggers_enabled: true,
+ 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.',
+ },
readiness: {
status: 'not_ready',
ready: false,
@@ -463,20 +751,43 @@ describe('AIIntelligence entitlement gating', () => {
render(() => <AIIntelligence />);
await waitFor(() => {
- expect(screen.getByText('Patrol readiness issue')).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Fix provider' })).toBeInTheDocument();
});
expect(
- screen.getByText(
+ screen.getByText('Open Provider & Models, then run Patrol from this page.'),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(/Issue:\s*Selected model cannot run Patrol tools\./),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(
'The selected Patrol model is a reasoning-only model family that commonly does not emit tool calls.',
),
- ).toBeInTheDocument();
- for (const button of screen.getAllByRole('button', { name: /Run Patrol/i })) {
- expect(button).toBeDisabled();
- }
+ ).not.toBeInTheDocument();
+ expect(screen.queryByRole('heading', { name: 'Current work' })).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol setup issue')).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol readiness issue')).not.toBeInTheDocument();
+ expect(screen.queryByText(/Automation:/)).not.toBeInTheDocument();
+ expect(
+ screen.queryByText(
+ 'Trigger status: Automatic Patrol checks from alerts and anomalies are paused by the local development safety guard. Manual Patrol still works.',
+ ),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText(/Trigger status:/)).not.toBeInTheDocument();
+ expect(screen.queryByText(/local development safety guard/)).not.toBeInTheDocument();
+ const providerSettingsLinks = screen.getAllByRole('link', {
+ name: 'Open Provider & Models',
+ });
+ expect(providerSettingsLinks.length).toBeGreaterThan(0);
+ expect(providerSettingsLinks[0]).toHaveAttribute(
+ 'href',
+ '/settings/pulse-intelligence/provider',
+ );
+ expect(screen.queryByRole('button', { name: /Run Patrol/i })).not.toBeInTheDocument();
expect(triggerPatrolRunMock).not.toHaveBeenCalled();
});
- it('surfaces Patrol readiness warnings without blocking manual runs', async () => {
+ it('surfaces provider warnings without blocking manual runs', async () => {
getPatrolStatusMock.mockResolvedValue(
defaultPatrolStatus({
readiness: {
@@ -503,8 +814,9 @@ describe('AIIntelligence entitlement gating', () => {
render(() => <AIIntelligence />);
await waitFor(() => {
- expect(screen.getByText('Patrol readiness warning')).toBeInTheDocument();
+ expect(screen.getByText('Provider warning')).toBeInTheDocument();
});
+ expect(screen.queryByText('Patrol readiness warning')).not.toBeInTheDocument();
const runButtons = screen.getAllByRole('button', { name: /Run Patrol/i });
for (const button of runButtons) {
expect(button).not.toBeDisabled();
@@ -516,6 +828,24 @@ describe('AIIntelligence entitlement gating', () => {
});
});
+ it('moves manual Patrol runs out of Starting state once the start request is accepted', async () => {
+ render(() => <AIIntelligence />);
+
+ await waitFor(() => {
+ expect(screen.getByRole('heading', { name: 'Patrol' })).toBeInTheDocument();
+ });
+
+ getCorrelationsMock.mockImplementation(() => new Promise(() => {}));
+
+ fireEvent.click(screen.getAllByRole('button', { name: /Run Patrol/i })[0]);
+
+ await waitFor(() => {
+ expect(triggerPatrolRunMock).toHaveBeenCalled();
+ expect(screen.getAllByRole('button', { name: /Running/i }).length).toBeGreaterThan(0);
+ });
+ expect(screen.queryByRole('button', { name: /Starting/i })).not.toBeInTheDocument();
+ });
+
it('surfaces backend readiness rejection when a stale manual run request reaches the server', async () => {
triggerPatrolRunMock.mockRejectedValue(
new Error(
@@ -546,6 +876,8 @@ describe('AIIntelligence entitlement gating', () => {
await waitFor(() => {
expect(screen.getByRole('heading', { name: 'Patrol' })).toBeInTheDocument();
});
+ expect(screen.queryByText('Patrol setup issue')).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol setup warning')).not.toBeInTheDocument();
expect(screen.queryByText('Patrol readiness issue')).not.toBeInTheDocument();
expect(screen.queryByText('Patrol readiness warning')).not.toBeInTheDocument();
for (const button of screen.getAllByRole('button', { name: /Run Patrol/i })) {
@@ -553,10 +885,20 @@ describe('AIIntelligence entitlement gating', () => {
}
});
- it('renders canonical learned correlations in the summary page through the correlation card', async () => {
+ it('does not expose raw supporting context as a Patrol page details panel', async () => {
hasFeatureMock.mockReturnValue(true);
licenseStatusMock.mockReturnValue({ subscription_state: 'active' });
getPatrolStatusMock.mockResolvedValue(defaultPatrolStatus({ license_required: false }));
+ intelligenceState.findings = [
+ {
+ id: 'finding-storage-context',
+ status: 'active',
+ severity: 'warning',
+ resourceId: 'storage-2',
+ resourceName: 'Storage 2',
+ title: 'Storage issue needs Patrol context',
+ },
+ ];
intelligenceState.summary = {
timestamp: '2026-03-01T00:00:00Z',
overall_health: {
@@ -568,12 +910,12 @@ describe('AIIntelligence entitlement gating', () => {
name: 'Patrol coverage incomplete',
impact: -0.35,
description:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
category: 'coverage',
},
],
prediction:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
},
findings_count: {
critical: 0,
@@ -636,42 +978,38 @@ describe('AIIntelligence entitlement gating', () => {
render(() => <AIIntelligence />);
await waitFor(() => {
- expect(screen.getByText('Supporting context')).toBeInTheDocument();
- });
-
- expect(screen.queryByRole('heading', { name: 'Learned correlations' })).not.toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', { name: 'View supporting context' }));
- await waitFor(() => {
- expect(screen.getByRole('heading', { name: 'Learned correlations' })).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Current work' })).toBeInTheDocument();
});
-
- expect(screen.getByText('How to read this')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Details' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Hide details' })).not.toBeInTheDocument();
expect(
- screen.getByText(
- 'Findings and run history are Patrol verification evidence. The cards below add explanatory context and do not count as a fresh full patrol.',
- ),
- ).toBeInTheDocument();
- expect(screen.getByText('2 learned patterns · explanatory context')).toBeInTheDocument();
- expect(screen.getByText('Coverage posture for policy-covered resources.')).toBeInTheDocument();
- expect(screen.getByText('3 policy-covered resources')).toBeInTheDocument();
- // Cross-jump to /infrastructure?resource=... retired with the legacy
- // surface; correlation labels render as plain text and document order is
- // verified via the resource label spans instead of anchor tags.
+ screen.queryByText('Extra activity and policy context for the selected item.'),
+ ).not.toBeInTheDocument();
expect(
- screen.queryByRole('link', { name: /Open source resource .* in Infrastructure/ }),
- ).toBeNull();
- const storage2Label = screen.getByText('Storage 2');
- const storage1Label = screen.getByText('Storage 1');
+ screen.queryByText('Details available: related patterns, policy limits.'),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText('For reference')).not.toBeInTheDocument();
+ expect(
+ screen.queryByText(
+ 'This explains what Patrol saw. It does not change the finding or start a new patrol.',
+ ),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByRole('heading', { name: 'Nearby activity' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('heading', { name: 'Related patterns' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('heading', { name: 'Policy limits' })).not.toBeInTheDocument();
+ expect(screen.queryByText('2 related patterns Patrol can use')).not.toBeInTheDocument();
expect(
- storage2Label.compareDocumentPosition(storage1Label) & Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
- expect(screen.getByText('VM 200')).toBeInTheDocument();
- expect(screen.getByText('VM 100')).toBeInTheDocument();
- expect(screen.getByText('Cpu High → Restart')).toBeInTheDocument();
- expect(screen.getByText('Disk Full → Restart')).toBeInTheDocument();
- expect(screen.getByText(/2 occurrences .* 95% confidence/)).toBeInTheDocument();
- expect(screen.getByText(/1 occurrence .* 50% confidence/)).toBeInTheDocument();
- expect(screen.getByText('Disk pressure often precedes restarts')).toBeInTheDocument();
+ screen.queryByText('What Patrol was allowed to inspect or act on.'),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText('Storage 2')).not.toBeInTheDocument();
+ expect(screen.queryByText('VM 200')).not.toBeInTheDocument();
+ expect(screen.queryByText('Disk Full → Restart')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'History' }));
+ await waitFor(() => {
+ expect(screen.getByRole('heading', { name: 'Patrol history' })).toBeInTheDocument();
+ });
+ expect(screen.queryByRole('button', { name: 'Details' })).not.toBeInTheDocument();
});
afterEach(() => {
@@ -692,25 +1030,39 @@ describe('AIIntelligence entitlement gating', () => {
expect(getPatrolStatusMock).toHaveBeenCalled();
});
- fireEvent.click(screen.getByRole('button', { name: 'Configure Patrol' }));
-
- await screen.findByRole('button', { name: 'Investigate' });
-
- expect(screen.getByRole('button', { name: 'Investigate' })).toBeDisabled();
- expect(screen.getByRole('button', { name: 'Remediate' })).toBeDisabled();
- expect(
- screen.getByText(
- 'Safe remediation workflows and alert-triggered root-cause analysis are not enabled on this plan.',
- ),
- ).toBeInTheDocument();
+ const patrolControlAnchor = document.getElementById(PATROL_CONTROL_ANCHOR);
+ expect(patrolControlAnchor).not.toBeNull();
+ const patrolControl = within(patrolControlAnchor!);
+ expect(patrolControl.queryByRole('group', { name: 'Patrol mode' })).not.toBeInTheDocument();
+ expect(patrolControl.getByText('Patrol mode')).toBeInTheDocument();
+ expect(patrolControl.getAllByText('Watch only').length).toBeGreaterThan(0);
+ expect(patrolControl.queryByRole('button', { name: 'Limits' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Ask first, requires Pulse Pro' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Safe auto-fix, requires Pulse Pro' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Autopilot, requires Pulse Pro' })).toBeNull();
+ expect(patrolControl.queryByText('Pro')).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Ask first Pro' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Safe auto-fix Pro' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Autopilot Pro' })).toBeNull();
+ expect(screen.getByRole('link', { name: 'Plans & Billing' })).toHaveAttribute(
+ 'href',
+ SELF_HOSTED_PRO_BILLING_PLAN_SELECTION_HREF,
+ );
+ expect(screen.queryByRole('link', { name: 'View plans' })).not.toBeInTheDocument();
+ expect(screen.queryByText('Unlock Patrol mode')).not.toBeInTheDocument();
+ expect(screen.queryByText('More Patrol modes')).not.toBeInTheDocument();
expect(
- screen.getByText(
- 'Investigation and safe remediation workflows are not enabled on this plan.',
+ screen.queryByText(
+ 'This plan can only watch. Pulse Pro unlocks investigation, approval-backed fixes, and automatic policy-approved fixes.',
),
- ).toBeInTheDocument();
- expect(
- screen.getByText('Container update risk analysis is not enabled on this plan.'),
- ).toBeInTheDocument();
+ ).not.toBeInTheDocument();
+
+ expect(screen.getByRole('link', { name: 'Open Patrol settings' })).toHaveAttribute(
+ 'href',
+ '/settings/pulse-intelligence/patrol',
+ );
+ expect(screen.queryByRole('dialog', { name: 'Patrol schedule & model' })).toBeNull();
+ expect(screen.queryByText('Container update risk')).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Upgrade to Pro' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Upgrade' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /start free trial/i })).not.toBeInTheDocument();
@@ -731,18 +1083,60 @@ describe('AIIntelligence entitlement gating', () => {
expect(getPatrolStatusMock).toHaveBeenCalled();
});
- fireEvent.click(screen.getByRole('button', { name: 'Configure Patrol' }));
+ const patrolControlAnchor = document.getElementById(PATROL_CONTROL_ANCHOR);
+ expect(patrolControlAnchor).not.toBeNull();
+ const patrolControl = within(patrolControlAnchor!);
+ expect(patrolControl.queryByRole('group', { name: 'Patrol mode' })).not.toBeInTheDocument();
+ expect(patrolControl.getByText('Patrol mode')).toBeInTheDocument();
+ expect(patrolControl.getAllByText('Watch only').length).toBeGreaterThan(0);
+ expect(patrolControl.queryByRole('button', { name: 'Limits' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Ask first, requires Pulse Pro' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Safe auto-fix, requires Pulse Pro' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Autopilot, requires Pulse Pro' })).toBeNull();
+ expect(patrolControl.queryByText('Pro')).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Ask first Pro' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Safe auto-fix Pro' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Autopilot Pro' })).toBeNull();
+ expect(screen.queryByRole('link', { name: 'Plans & Billing' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'View plans' })).not.toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Open Patrol settings' })).toHaveAttribute(
+ 'href',
+ '/settings/pulse-intelligence/patrol',
+ );
+ expect(screen.queryByRole('dialog', { name: 'Patrol schedule & model' })).toBeNull();
+ expect(screen.queryByText('This install can only watch')).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol is in watch-only mode')).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Upgrade to Pro' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Upgrade' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /start free trial/i })).not.toBeInTheDocument();
+ });
+
+ it('hides paid patrol badges when commercial surfaces are hidden', async () => {
+ presentationPolicyHidesCommercialSurfacesMock.mockReturnValue(true);
+ getPatrolStatusMock.mockResolvedValue(
+ defaultPatrolStatus({
+ license_required: true,
+ }),
+ );
- await screen.findByRole('button', { name: 'Investigate' });
+ render(() => <AIIntelligence />);
- expect(screen.getByRole('button', { name: 'Investigate' })).toBeDisabled();
- expect(screen.getByRole('button', { name: 'Remediate' })).toBeDisabled();
+ await waitFor(() => {
+ expect(loadLicenseStatusMock).toHaveBeenCalled();
+ expect(getPatrolStatusMock).toHaveBeenCalled();
+ });
+
+ const patrolControlAnchor = document.getElementById(PATROL_CONTROL_ANCHOR);
+ expect(patrolControlAnchor).not.toBeNull();
+ const patrolControl = within(patrolControlAnchor!);
+ expect(patrolControl.getAllByText('Watch only').length).toBeGreaterThan(0);
+ expect(patrolControl.queryByText('Pro')).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'View plans' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Upgrade to Pro' })).not.toBeInTheDocument();
- expect(screen.queryByRole('link', { name: 'Upgrade' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /start free trial/i })).not.toBeInTheDocument();
});
- it('keeps a saved direct-provider Patrol model selected after the catalog loads', async () => {
+ it('keeps the Patrol model catalog out of the operator page', async () => {
apiFetchJSONMock.mockImplementation(async (path: string) => {
if (path === '/api/ai/models') {
return {
@@ -777,13 +1171,13 @@ describe('AIIntelligence entitlement gating', () => {
expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/models');
});
- fireEvent.click(screen.getByRole('button', { name: 'Configure Patrol' }));
-
- const select = screen.getByLabelText('Provider model') as HTMLSelectElement;
- await waitFor(() => {
- expect(select.value).toBe('deepseek:deepseek-v4-flash');
- });
- expect(select.selectedOptions[0]?.textContent).toContain('DeepSeek V4 Flash');
+ expect(screen.getByRole('link', { name: 'Open Patrol settings' })).toHaveAttribute(
+ 'href',
+ '/settings/pulse-intelligence/patrol',
+ );
+ expect(screen.queryByRole('dialog', { name: 'Patrol schedule & model' })).toBeNull();
+ expect(screen.queryByText('DeepSeek V4 Flash')).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Change model' })).toBeNull();
});
it('unlocks paid patrol controls when the entitlement grants the features', async () => {
@@ -798,72 +1192,100 @@ describe('AIIntelligence entitlement gating', () => {
expect(getPatrolStatusMock).toHaveBeenCalled();
});
- fireEvent.click(screen.getByRole('button', { name: 'Configure Patrol' }));
+ expect(screen.getByRole('button', { name: 'Ask first' })).not.toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Safe auto-fix' })).not.toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Autopilot' })).not.toBeDisabled();
+ expect(screen.getByText('Patrol reports issues without making changes.')).toBeInTheDocument();
+ expect(screen.queryByText('Patrol handles')).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Limits' })).not.toBeInTheDocument();
+ expect(screen.queryByText('Hard limits')).not.toBeInTheDocument();
- await screen.findByRole('button', { name: 'Investigate' });
+ fireEvent.click(screen.getByRole('button', { name: 'Autopilot' }));
- expect(screen.getByRole('button', { name: 'Investigate' })).not.toBeDisabled();
- expect(screen.getByRole('button', { name: 'Remediate' })).not.toBeDisabled();
- expect(screen.getByRole('checkbox', { name: 'Container Update Risk' })).toBeInTheDocument();
- expect(screen.getByRole('checkbox', { name: 'Alert-Triggered Patrols' })).toBeInTheDocument();
- expect(screen.getByRole('checkbox', { name: 'Anomaly-Triggered Patrols' })).toBeInTheDocument();
- expect(
- screen.getByRole('checkbox', { name: 'Autonomous critical remediation' }),
- ).toBeInTheDocument();
+ await waitFor(() => {
+ expect(
+ screen.getByText(
+ 'Patrol handles policy-approved issues automatically. It asks only when policy requires approval.',
+ ),
+ ).toBeInTheDocument();
+ });
+
+ expect(screen.getByRole('link', { name: 'Open Patrol settings' })).toHaveAttribute(
+ 'href',
+ '/settings/pulse-intelligence/patrol',
+ );
+ expect(screen.queryByRole('dialog', { name: 'Patrol schedule & model' })).toBeNull();
+ expect(screen.queryByRole('checkbox', { name: 'Container Update Risk' })).toBeNull();
+ expect(screen.queryByRole('checkbox', { name: 'Alert-Triggered Patrols' })).toBeNull();
+ expect(screen.queryByRole('checkbox', { name: 'Anomaly-Triggered Patrols' })).toBeNull();
expect(screen.queryByRole('link', { name: 'Upgrade to Pro' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Upgrade' })).not.toBeInTheDocument();
});
- it('persists the alert-trigger severity floor from the Patrol configuration panel', async () => {
+ it('records direct Patrol mode changes after successful paid control saves', async () => {
hasFeatureMock.mockReturnValue(true);
licenseStatusMock.mockReturnValue({ subscription_state: 'active' });
getPatrolStatusMock.mockResolvedValue(defaultPatrolStatus({ license_required: false }));
apiFetchJSONMock.mockImplementation(async (path: string) => {
+ if (path === '/api/ai/models') {
+ return { models: [] };
+ }
if (path === '/api/settings/ai') {
- return {
- ...defaultAISettings,
- patrol_alert_triggers_enabled: true,
- patrol_alert_trigger_min_severity: 'critical',
- };
+ return defaultAISettings;
}
if (path === '/api/settings/ai/update') {
- return {
- ...defaultAISettings,
- patrol_alert_triggers_enabled: true,
- patrol_alert_trigger_min_severity: 'warning',
- };
+ return defaultAISettings;
+ }
+ if (path === '/api/agent/capabilities') {
+ return defaultAgentCapabilitiesManifest();
+ }
+ if (path === AGENT_PATROL_CONTROL_STATUS_PATH) {
+ return defaultOperationsLoopStatus();
}
return {};
});
+ updatePatrolAutonomySettingsMock.mockResolvedValue({
+ settings: {
+ autonomy_level: 'approval',
+ full_mode_unlocked: false,
+ },
+ });
render(() => <AIIntelligence />);
await waitFor(() => {
- expect(screen.getByRole('heading', { name: 'Patrol' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Ask first' })).not.toBeDisabled();
});
+ const statusCallsBeforeModeChange = getPatrolStatusMock.mock.calls.length;
+ const runHistoryCallsBeforeModeChange = getPatrolRunHistoryMock.mock.calls.length;
- fireEvent.click(screen.getByRole('button', { name: 'Configure Patrol' }));
-
- const select = (await screen.findByLabelText(
- 'Investigate alerts at or above',
- )) as HTMLSelectElement;
- expect(select.value).toBe('critical');
- expect(Array.from(select.options).map((option) => option.value)).toEqual([
- 'critical',
- 'warning',
- ]);
-
- fireEvent.change(select, { target: { value: 'warning' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Ask first' }));
await waitFor(() => {
- expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/settings/ai/update', {
- patrol_alert_trigger_min_severity: 'warning',
+ expect(updatePatrolAutonomySettingsMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ autonomy_level: 'approval',
+ full_mode_unlocked: false,
+ }),
+ );
+ });
+ await waitFor(() => {
+ expect(recordWorkflowPromptActivityMock).toHaveBeenCalledWith({
+ name: 'pulse_operations_loop',
+ surface: 'patrol_control',
});
});
await waitFor(() => {
- expect(
- (screen.getByLabelText('Investigate alerts at or above') as HTMLSelectElement).value,
- ).toBe('warning');
+ expect(getPatrolStatusMock.mock.calls.length).toBeGreaterThan(statusCallsBeforeModeChange);
+ expect(getPatrolRunHistoryMock.mock.calls.length).toBeGreaterThan(
+ runHistoryCallsBeforeModeChange,
+ );
+ expect(screen.getByRole('heading', { name: 'Current work' })).toBeInTheDocument();
+ expect(screen.queryByTestId('patrol-current-work')).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol ready')).not.toBeInTheDocument();
+ expect(screen.queryByText(/Run Patrol now to look for issues/)).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol mode ready')).not.toBeInTheDocument();
+ expect(screen.queryByText(/Patrol mode is set/)).not.toBeInTheDocument();
});
});
@@ -934,20 +1356,21 @@ describe('AIIntelligence entitlement gating', () => {
await waitFor(() => {
expect(getPatrolStatusMock).toHaveBeenCalled();
- expect(screen.getByText('Patrol assessment')).toBeInTheDocument();
- expect(screen.getByText(/No issues found · 91\/100/)).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Patrol' })).toBeInTheDocument();
});
+ expect(screen.queryByText('Patrol status')).not.toBeInTheDocument();
+ expect(screen.queryByText(/No active issues · health score 91\/100/)).not.toBeInTheDocument();
expect(screen.queryByText('No active issues detected')).not.toBeInTheDocument();
expect(screen.queryByText(/Health A · 91\/100/)).not.toBeInTheDocument();
expect(screen.queryByText('Supporting context')).not.toBeInTheDocument();
expect(
- screen.queryByText('1 recent change · 4 policy-covered resources'),
+ screen.queryByText('1 recent change · 4 resources covered by policy'),
).not.toBeInTheDocument();
expect(screen.queryByText('Policy posture')).not.toBeInTheDocument();
});
- it('renders a stable patrol summary loading shell before the first assessment payload arrives', async () => {
+ it('keeps the Patrol page visible without a separate summary loading strip', async () => {
getPatrolStatusMock.mockImplementation(() => new Promise(() => {}));
intelligenceState.summary = null;
@@ -958,11 +1381,33 @@ describe('AIIntelligence entitlement gating', () => {
));
await waitFor(() => {
- expect(screen.getByTestId('patrol-summary-loading')).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Patrol' })).toBeInTheDocument();
+ expect(screen.getByText('Current work')).toBeInTheDocument();
+ });
+
+ expect(screen.queryByText('Loading view...')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('patrol-summary-loading')).not.toBeInTheDocument();
+ expect(screen.queryByText('Loading Patrol')).not.toBeInTheDocument();
+ });
+
+ it('keeps the Patrol page visible when first-load refreshes fail', async () => {
+ loadLicenseStatusMock.mockRejectedValue(new TypeError('Failed to fetch'));
+
+ render(() => (
+ <Suspense fallback={<div>Loading view...</div>}>
+ <AIIntelligence />
+ </Suspense>
+ ));
+
+ await waitFor(() => {
+ expect(screen.getByRole('heading', { name: 'Patrol' })).toBeInTheDocument();
+ expect(screen.getByText('Patrol could not refresh')).toBeInTheDocument();
+ expect(screen.getByText('Current work')).toBeInTheDocument();
});
expect(screen.queryByText('Loading view...')).not.toBeInTheDocument();
- expect(screen.queryByText('Patrol assessment')).not.toBeInTheDocument();
+ expect(screen.queryByText('Failed to fetch')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();
});
it('does not present a healthy patrol summary when a retired hosted block reason is normalized', async () => {
@@ -1009,7 +1454,7 @@ describe('AIIntelligence entitlement gating', () => {
await waitFor(() => {
expect(getPatrolStatusMock).toHaveBeenCalled();
- expect(screen.getAllByText('Patrol Paused')).toHaveLength(2);
+ expect(screen.getAllByText('Patrol paused').length).toBeGreaterThan(0);
});
expect(screen.getAllByText('Patrol paused').length).toBeGreaterThan(0);
@@ -1066,7 +1511,8 @@ describe('AIIntelligence entitlement gating', () => {
});
expect(screen.queryByText('Patrol quickstart exhausted')).not.toBeInTheDocument();
- expect(screen.getByText(/No issues found · 100\/100/)).toBeInTheDocument();
+ expect(screen.queryByText(/No active issues · health score 100\/100/)).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol status')).not.toBeInTheDocument();
});
it('normalizes retired hosted availability copy on unactivated installs', async () => {
@@ -1196,12 +1642,12 @@ describe('AIIntelligence entitlement gating', () => {
name: 'Patrol coverage incomplete',
impact: -0.35,
description:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
category: 'coverage',
},
],
prediction:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
},
findings_count: {
critical: 0,
@@ -1225,17 +1671,19 @@ describe('AIIntelligence entitlement gating', () => {
render(() => <AIIntelligence />);
await waitFor(() => {
- expect(screen.getByText(/Coverage incomplete · 70\/100/)).toBeInTheDocument();
+ expect(screen.getByText('Current work')).toBeInTheDocument();
expect(screen.queryByText('Next:')).not.toBeInTheDocument();
expect(screen.queryByText('Verify full coverage')).not.toBeInTheDocument();
expect(screen.queryByTestId('patrol-recommended-next-step-action')).not.toBeInTheDocument();
expect(findingsPanelState.latestProps).not.toBeNull();
});
+ expect(screen.queryByText('Coverage incomplete')).not.toBeInTheDocument();
+ expect(screen.queryByText(/health score 70\/100/)).not.toBeInTheDocument();
expect(screen.queryByTestId('patrol-summary-details-toggle')).not.toBeInTheDocument();
expect(screen.queryByTestId('patrol-summary-details')).not.toBeInTheDocument();
expect(screen.queryByText('No recent full patrol')).not.toBeInTheDocument();
- expect(screen.queryByText('No issues found')).not.toBeInTheDocument();
+ expect(screen.queryByText('No active issues')).not.toBeInTheDocument();
expect(screen.queryByText(/Last patrol/i)).not.toBeInTheDocument();
expect(screen.queryByText(/^Last:/i)).not.toBeInTheDocument();
expect(screen.queryByText('Partial verification')).not.toBeInTheDocument();
@@ -1244,7 +1692,7 @@ describe('AIIntelligence entitlement gating', () => {
expect(screen.queryByText('Critical')).not.toBeInTheDocument();
expect(
screen.queryByText(
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
),
).not.toBeInTheDocument();
expect(findingsPanelState.latestProps?.nextPatrolAt).toBeUndefined();
@@ -1364,12 +1812,12 @@ describe('AIIntelligence entitlement gating', () => {
name: 'Patrol coverage incomplete',
impact: -0.35,
description:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
category: 'coverage',
},
],
prediction:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
},
findings_count: {
critical: 0,
@@ -1393,19 +1841,51 @@ describe('AIIntelligence entitlement gating', () => {
render(() => <AIIntelligence />);
await waitFor(() => {
- expect(screen.getByText(/1 runtime issue · 60\/100/)).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Fix provider' })).toBeInTheDocument();
});
- expect(screen.getByText(/1 runtime issue · 60\/100/)).toBeInTheDocument();
expect(
- screen.queryByRole('link', { name: 'Open Patrol provider settings' }),
+ screen.queryByText(/1 Patrol runtime issue · health score 60\/100/),
).not.toBeInTheDocument();
- const assessmentShell = screen.getByText('Patrol assessment').closest('section');
- expect(assessmentShell).not.toBeNull();
- expect(assessmentShell!.className).toContain('border-y');
- expect(assessmentShell!.className).not.toContain('rounded-md');
- expect(assessmentShell!.className).not.toContain('shadow-sm');
- expect(assessmentShell!.className).not.toContain('bg-amber-50');
+ expect(
+ screen.getByText('Open Provider & Models, then run Patrol from this page.'),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('heading', { name: 'Provider needs attention' }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText('Fix the provider connection, then Patrol can check infrastructure.'),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText('Issue: Provider billing or quota issue')).toBeInTheDocument();
+ expect(screen.queryByText('Patrol setup issue')).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol readiness issue')).not.toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Open Provider & Models' })).toHaveAttribute(
+ 'href',
+ '/settings/pulse-intelligence/provider',
+ );
+ expect(screen.queryByText('Runtime issue')).not.toBeInTheDocument();
+ expect(screen.queryByText(/regressed \d+×/)).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Runtime issue/i })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Run Patrol' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Open Patrol settings' })).not.toBeInTheDocument();
+ expect(screen.queryByText(/Automation:/)).not.toBeInTheDocument();
+ const patrolControlAnchor = document.getElementById(PATROL_CONTROL_ANCHOR);
+ expect(patrolControlAnchor).not.toBeNull();
+ expect(patrolControlAnchor).toContainElement(
+ screen.getByRole('group', { name: 'Patrol mode' }),
+ );
+ const patrolControl = within(patrolControlAnchor!);
+ expect(patrolControl.getByText('Patrol mode')).toBeInTheDocument();
+ expect(patrolControl.getAllByText('Watch only').length).toBeGreaterThan(0);
+ expect(
+ patrolControl.getByText('Patrol reports issues without making changes.'),
+ ).toBeInTheDocument();
+ expect(patrolControl.getByRole('button', { name: 'Ask first' })).not.toBeDisabled();
+ expect(patrolControl.getByRole('button', { name: 'Safe auto-fix' })).not.toBeDisabled();
+ expect(patrolControl.getByRole('button', { name: 'Autopilot' })).not.toBeDisabled();
+ expect(patrolControl.queryByRole('button', { name: 'Limits' })).not.toBeInTheDocument();
+ expect(screen.queryByText(/Current mode:/)).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol status')).not.toBeInTheDocument();
expect(screen.queryByTestId('patrol-summary-details-toggle')).not.toBeInTheDocument();
expect(screen.queryByTestId('patrol-summary-details')).not.toBeInTheDocument();
expect(screen.queryByText('Infrastructure findings')).not.toBeInTheDocument();
@@ -1413,15 +1893,62 @@ describe('AIIntelligence entitlement gating', () => {
expect(screen.queryByText('Latest activity')).not.toBeInTheDocument();
expect(screen.queryByTestId('patrol-status-bar')).not.toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Findings' }).textContent).toBe('Findings 1');
+ expect(screen.queryByRole('heading', { name: 'Current work' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Active' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'All' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Resolved' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Details' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'History' })).not.toBeInTheDocument();
expect(
screen.queryByText(
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
),
).not.toBeInTheDocument();
});
+ it('keeps provider-blocked open issues to one provider action', async () => {
+ hasFeatureMock.mockReturnValue(true);
+ licenseStatusMock.mockReturnValue({ subscription_state: 'active' });
+ getPatrolStatusMock.mockResolvedValue(
+ defaultPatrolStatus({
+ license_required: false,
+ readiness: {
+ status: 'not_ready',
+ ready: false,
+ summary: 'Provider billing or quota issue.',
+ provider: 'openrouter',
+ model: 'openrouter:z-ai/glm-5.2',
+ },
+ }),
+ );
+ intelligenceState.findings = [
+ {
+ id: 'finding-storage-risk',
+ source: 'ai-patrol',
+ isThreshold: false,
+ status: 'active',
+ severity: 'critical',
+ resourceId: 'storage:tower-array',
+ resourceName: 'Tower Array',
+ resourceType: 'storage',
+ title: 'Unraid array running without parity protection',
+ detectedAt: '2026-03-12T09:57:00Z',
+ },
+ ];
+
+ render(() => <AIIntelligence />);
+
+ await waitFor(() => {
+ expect(screen.getByText('Provider issue')).toBeInTheDocument();
+ });
+ expect(screen.getByRole('heading', { name: 'Current work' })).toBeInTheDocument();
+ const providerActions = screen.getAllByRole('link', { name: /Fix Patrol provider/i });
+ expect(providerActions.length).toBeGreaterThan(0);
+ expect(providerActions[0]).toHaveAttribute('href', '/settings/pulse-intelligence/provider');
+ expect(screen.queryByRole('link', { name: 'Open Provider & Models' })).not.toBeInTheDocument();
+ });
+
it('does not repeat stale coverage caveats after a successful full patrol verified resources', async () => {
hasFeatureMock.mockReturnValue(true);
licenseStatusMock.mockReturnValue({ subscription_state: 'active' });
@@ -1502,7 +2029,7 @@ describe('AIIntelligence entitlement gating', () => {
name: 'Patrol coverage incomplete',
impact: -0.35,
description:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
category: 'coverage',
},
],
@@ -1532,8 +2059,11 @@ describe('AIIntelligence entitlement gating', () => {
await waitFor(() => {
expect(screen.getByText(/verified 58 resources/i)).toBeInTheDocument();
- expect(screen.getByText(/1 warning · 2 regressed · 85\/100/)).toBeInTheDocument();
});
+ expect(
+ screen.queryByText(/1 warning issue · 2 past regressions · health score 85\/100/),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol status')).not.toBeInTheDocument();
expect(screen.queryByLabelText('Patrol trust summary header')).not.toBeInTheDocument();
expect(screen.queryByLabelText('Patrol trust summary')).not.toBeInTheDocument();
expect(screen.queryByTestId('patrol-summary-details-toggle')).not.toBeInTheDocument();
@@ -1547,7 +2077,7 @@ describe('AIIntelligence entitlement gating', () => {
expect(screen.queryByText(/Recent coverage is also incomplete/i)).not.toBeInTheDocument();
});
- it('keeps recent activity mix out of the default Patrol assessment chrome', async () => {
+ it('keeps recent activity mix out of the default Patrol status chrome', async () => {
hasFeatureMock.mockReturnValue(true);
licenseStatusMock.mockReturnValue({ subscription_state: 'active' });
getPatrolStatusMock.mockResolvedValue(defaultPatrolStatus({ license_required: false }));
@@ -1680,27 +2210,22 @@ describe('AIIntelligence entitlement gating', () => {
render(() => <AIIntelligence />);
await waitFor(() => {
- expect(screen.getByText(/No issues found · 100\/100/)).toBeInTheDocument();
+ expect(getPatrolRunHistoryMock).toHaveBeenCalled();
+ expect(screen.getByRole('heading', { name: 'Patrol' })).toBeInTheDocument();
});
+ expect(screen.queryByText(/No active issues · health score 100\/100/)).not.toBeInTheDocument();
+ expect(screen.queryByText('Patrol status')).not.toBeInTheDocument();
expect(screen.queryByTestId('patrol-summary-details-toggle')).not.toBeInTheDocument();
expect(screen.queryByText(/Recent activity mix:/)).not.toBeInTheDocument();
+ expect(screen.queryByText(/Trigger mode:/)).not.toBeInTheDocument();
});
it('treats a selected zero-finding run as an empty snapshot and uses effective scope ids', async () => {
hasFeatureMock.mockReturnValue(true);
licenseStatusMock.mockReturnValue({ subscription_state: 'active' });
getPatrolStatusMock.mockResolvedValue(defaultPatrolStatus({ license_required: false }));
- intelligenceState.findings = [
- {
- id: 'finding-runtime',
- status: 'active',
- severity: 'warning',
- resourceId: 'ai-service',
- resourceName: 'Pulse Patrol Service',
- title: 'Pulse Patrol: Provider billing or quota issue',
- },
- ];
+ intelligenceState.findings = [];
runHistoryState.selection = {
id: 'run-empty',
started_at: '2026-03-12T10:00:00Z',
@@ -1740,16 +2265,14 @@ describe('AIIntelligence entitlement gating', () => {
expect(findingsPanelState.latestProps).not.toBeNull();
});
- fireEvent.click(screen.getByRole('button', { name: 'Runs' }));
+ fireEvent.click(screen.getByRole('button', { name: 'History' }));
fireEvent.click(screen.getByRole('button', { name: 'Select mocked run' }));
- fireEvent.click(screen.getByRole('button', { name: 'Findings' }));
await waitFor(() => {
- expect(screen.getByText(/Filtered to run/i)).toBeInTheDocument();
+ expect(screen.getAllByText(/Patrol run/i).length).toBeGreaterThan(0);
});
- expect(screen.queryByText('Findings snapshot unavailable')).not.toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Findings' }).textContent).toBe('Findings');
+ expect(screen.queryByText('Finding record unavailable')).not.toBeInTheDocument();
expect(findingsPanelState.latestProps).toMatchObject({
filterOverride: 'all',
@@ -1761,6 +2284,79 @@ describe('AIIntelligence entitlement gating', () => {
});
});
+ it('shows the selected Patrol run outcome before the finding list', async () => {
+ hasFeatureMock.mockReturnValue(true);
+ licenseStatusMock.mockReturnValue({ subscription_state: 'active' });
+ getPatrolStatusMock.mockResolvedValue(defaultPatrolStatus({ license_required: false }));
+ intelligenceState.findings = [];
+ runHistoryState.selection = {
+ id: 'run-provider-error',
+ started_at: '2026-03-12T10:00:00Z',
+ completed_at: '2026-03-12T10:58:00Z',
+ duration_ms: 3_480_000,
+ type: 'full',
+ trigger_reason: 'manual',
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ scope_resource_types: [],
+ resources_checked: 72,
+ nodes_checked: 0,
+ guests_checked: 72,
+ 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,
+ auto_fix_count: 0,
+ findings_summary: 'Provider failed during analysis',
+ finding_ids: ['runtime-provider'],
+ error_count: 1,
+ error_summary: 'Selected model does not support Patrol tools',
+ error_detail:
+ "agentic patrol failed: API error (404): No endpoints found that support the provided 'tool_choice' value.",
+ status: 'error',
+ tool_call_count: 0,
+ };
+
+ render(() => <AIIntelligence />);
+
+ await waitFor(() => {
+ expect(getPatrolStatusMock).toHaveBeenCalled();
+ expect(findingsPanelState.latestProps).not.toBeNull();
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'History' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Select mocked run' }));
+
+ await waitFor(() => {
+ expect(screen.getAllByText(/Patrol run/i).length).toBeGreaterThan(0);
+ });
+
+ expect(screen.getByText('Manual')).toBeInTheDocument();
+ expect(screen.getByText('error')).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ /Checked 72 resources in 58m\. Patrol ended with a runtime issue: Selected model does not support Patrol tools/i,
+ ),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Open Provider & Models' })).toHaveAttribute(
+ 'href',
+ '/settings/pulse-intelligence/provider',
+ );
+ expect(findingsPanelState.latestProps).toMatchObject({
+ filterOverride: 'all',
+ filterFindingIds: ['runtime-provider'],
+ scopeResourceIds: [],
+ runSnapshotId: 'run-provider-error',
+ });
+ });
+
it('keeps an explicit empty effective scope instead of falling back to seed scope ids', async () => {
hasFeatureMock.mockReturnValue(true);
licenseStatusMock.mockReturnValue({ subscription_state: 'active' });
@@ -1804,15 +2400,14 @@ describe('AIIntelligence entitlement gating', () => {
expect(findingsPanelState.latestProps).not.toBeNull();
});
- fireEvent.click(screen.getByRole('button', { name: 'Runs' }));
+ fireEvent.click(screen.getByRole('button', { name: 'History' }));
fireEvent.click(screen.getByRole('button', { name: 'Select mocked run' }));
- fireEvent.click(screen.getByRole('button', { name: 'Findings' }));
await waitFor(() => {
- expect(screen.getByText(/Filtered to run/i)).toBeInTheDocument();
+ expect(screen.getAllByText(/Patrol run/i).length).toBeGreaterThan(0);
});
- expect(screen.queryByText('Findings snapshot unavailable')).not.toBeInTheDocument();
+ expect(screen.queryByText('Finding record unavailable')).not.toBeInTheDocument();
expect(findingsPanelState.latestProps).toMatchObject({
filterOverride: 'all',
filterFindingIds: [],
@@ -1827,16 +2422,7 @@ describe('AIIntelligence entitlement gating', () => {
hasFeatureMock.mockReturnValue(true);
licenseStatusMock.mockReturnValue({ subscription_state: 'active' });
getPatrolStatusMock.mockResolvedValue(defaultPatrolStatus({ license_required: false }));
- intelligenceState.findings = [
- {
- id: 'finding-runtime',
- status: 'active',
- severity: 'warning',
- resourceId: 'ai-service',
- resourceName: 'Pulse Patrol Service',
- title: 'Pulse Patrol: Provider billing or quota issue',
- },
- ];
+ intelligenceState.findings = [];
runHistoryState.selection = {
id: 'run-missing-snapshot',
started_at: '2026-03-12T10:10:00Z',
@@ -1875,16 +2461,14 @@ describe('AIIntelligence entitlement gating', () => {
expect(findingsPanelState.latestProps).not.toBeNull();
});
- fireEvent.click(screen.getByRole('button', { name: 'Runs' }));
+ fireEvent.click(screen.getByRole('button', { name: 'History' }));
fireEvent.click(screen.getByRole('button', { name: 'Select mocked run' }));
- fireEvent.click(screen.getByRole('button', { name: 'Findings' }));
await waitFor(() => {
- expect(screen.getByText(/Filtered to run/i)).toBeInTheDocument();
+ expect(screen.getAllByText(/Patrol run/i).length).toBeGreaterThan(0);
});
- expect(screen.getByText(/Findings snapshot unavailable/)).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Findings' }).textContent).toBe('Findings');
+ expect(screen.getByText(/Finding record unavailable/)).toBeInTheDocument();
expect(findingsPanelState.latestProps).toMatchObject({
filterOverride: 'all',
diff --git a/frontend-modern/src/pages/__tests__/PricingHandoff.test.tsx b/frontend-modern/src/pages/__tests__/PricingHandoff.test.tsx
index 4be8fa1b50..a726628a23 100644
--- a/frontend-modern/src/pages/__tests__/PricingHandoff.test.tsx
+++ b/frontend-modern/src/pages/__tests__/PricingHandoff.test.tsx
@@ -3,7 +3,10 @@ import { cleanup, render, screen, waitFor } from '@solidjs/testing-library';
import { Route, Router } from '@solidjs/router';
import PricingHandoff from '@/pages/PricingHandoff';
import pricingHandoffSource from '@/pages/PricingHandoff.tsx?raw';
-import { getSelfHostedPurchaseStartUrl } from '@/utils/pricingHandoff';
+import {
+ getSelfHostedPurchaseStartUrl,
+ SELF_HOSTED_PRO_BILLING_PLAN_ROUTE,
+} from '@/utils/pricingHandoff';
const handoffToExternalPricingMock = vi.fn();
@@ -77,7 +80,7 @@ describe('PricingHandoff', () => {
<Router>
<Route path="/pricing" component={PricingHandoff} />
<Route
- path="/settings/system/billing/plan"
+ path={SELF_HOSTED_PRO_BILLING_PLAN_ROUTE}
component={() => <div>Plans destination</div>}
/>
</Router>
diff --git a/frontend-modern/src/routing/__tests__/resourceLinks.test.ts b/frontend-modern/src/routing/__tests__/resourceLinks.test.ts
index a6f402935e..0e85fd30fc 100644
--- a/frontend-modern/src/routing/__tests__/resourceLinks.test.ts
+++ b/frontend-modern/src/routing/__tests__/resourceLinks.test.ts
@@ -1,17 +1,46 @@
import { describe, expect, it } from 'vitest';
import {
+ API_TOKEN_CREATE_ANCHOR,
+ API_TOKEN_PRESET_QUERY_PARAM,
DOCKER_PATH,
DOCKER_QUERY_PARAMS,
+ EXTERNAL_AGENT_SETUP_ANCHOR,
+ EXTERNAL_AGENT_SETUP_PATH,
KUBERNETES_PATH,
PMG_THRESHOLDS_PATH,
+ PATROL_AUTONOMY_OPERATIONS_LOOP_PATH,
+ PATROL_CONTROL_ANCHOR,
+ PATROL_CONTROL_PATH,
+ PATROL_CONTROL_PATH_WITH_STARTER,
+ PATROL_CONTROL_STARTER,
+ PATROL_CONTROL_STARTER_QUERY_PARAM,
+ PATROL_CONTROL_OPERATIONS_LOOP_PATH,
+ PATROL_OPERATIONS_LOOP_ANCHOR,
+ PATROL_OPERATIONS_LOOP_PATROL_AUTONOMY_STARTER,
+ PATROL_OPERATIONS_LOOP_PATROL_CONTROL_STARTER,
+ PATROL_OPERATIONS_LOOP_PRO_ACTIVATION_STARTER,
+ PATROL_OPERATIONS_LOOP_PATH,
+ PATROL_OPERATIONS_LOOP_STARTER_QUERY_PARAM,
+ PATROL_PRO_ACTIVATION_OPERATIONS_LOOP_PATH,
PATROL_PATH,
+ PULSE_MCP_SETUP_ANCHOR,
+ PULSE_MCP_LEGACY_SETUP_PATH,
+ PULSE_MCP_SETUP_PATH,
+ PULSE_MCP_TOKEN_SETUP_PATH,
+ PULSE_INTELLIGENCE_AGENT_TOKEN_PRESET,
+ SETTINGS_PULSE_INTELLIGENCE_ASSISTANT_PATH,
+ SETTINGS_PULSE_INTELLIGENCE_PATH,
+ isExternalAgentSetupHash,
PROXMOX_DEFAULT_TAB,
PROXMOX_PATH,
RECOVERY_QUERY_PARAMS,
+ SETTINGS_API_ACCESS_PATH,
STANDALONE_DEFAULT_TAB,
STANDALONE_PATH,
TRUENAS_PATH,
VMWARE_PATH,
+ buildPatrolControlPath,
+ buildPatrolOperationsLoopPath,
buildDockerPath,
buildDockerRouteSearch,
buildKubernetesPath,
@@ -23,6 +52,8 @@ import {
buildVmwarePath,
buildWorkloadsRouteSearch,
parseRecoveryLinkSearch,
+ parsePatrolControlStarter,
+ parsePatrolOperationsLoopStarter,
parseStorageLinkSearch,
parseWorkloadsLinkSearch,
STORAGE_QUERY_PARAMS,
@@ -32,6 +63,91 @@ import {
describe('resource link routing contract', () => {
it('keeps Patrol links on the canonical Patrol route', () => {
expect(PATROL_PATH).toBe('/patrol');
+ expect(PATROL_CONTROL_ANCHOR).toBe('patrol-control');
+ expect(PATROL_CONTROL_STARTER_QUERY_PARAM).toBe('patrolControlStarter');
+ expect(PATROL_CONTROL_STARTER).toBe('patrol_control');
+ expect(PATROL_CONTROL_PATH).toBe('/patrol#patrol-control');
+ expect(PATROL_CONTROL_PATH_WITH_STARTER).toBe(
+ '/patrol?patrolControlStarter=patrol_control#patrol-control',
+ );
+ expect(PATROL_OPERATIONS_LOOP_ANCHOR).toBe('operations-loop');
+ expect(PATROL_OPERATIONS_LOOP_STARTER_QUERY_PARAM).toBe('operationsLoopStarter');
+ expect(PATROL_OPERATIONS_LOOP_PATROL_CONTROL_STARTER).toBe('patrol_control');
+ expect(PATROL_OPERATIONS_LOOP_PATROL_AUTONOMY_STARTER).toBe('patrol_autonomy');
+ expect(PATROL_OPERATIONS_LOOP_PRO_ACTIVATION_STARTER).toBe('pulse_pro_activation');
+ expect(PATROL_OPERATIONS_LOOP_PATH).toBe(PATROL_CONTROL_PATH);
+ expect(PATROL_CONTROL_OPERATIONS_LOOP_PATH).toBe(PATROL_CONTROL_PATH_WITH_STARTER);
+ expect(PATROL_AUTONOMY_OPERATIONS_LOOP_PATH).toBe(
+ '/patrol?patrolControlStarter=patrol_control#patrol-control',
+ );
+ expect(PATROL_PRO_ACTIVATION_OPERATIONS_LOOP_PATH).toBe(
+ '/patrol?patrolControlStarter=patrol_control#patrol-control',
+ );
+ expect(
+ buildPatrolControlPath({
+ starter: PATROL_CONTROL_STARTER,
+ }),
+ ).toBe(PATROL_CONTROL_PATH_WITH_STARTER);
+ expect(
+ buildPatrolControlPath({
+ starter: PATROL_OPERATIONS_LOOP_PRO_ACTIVATION_STARTER,
+ }),
+ ).toBe(PATROL_CONTROL_PATH_WITH_STARTER);
+ expect(
+ buildPatrolControlPath({
+ starter: null,
+ }),
+ ).toBe(PATROL_CONTROL_PATH);
+ expect(parsePatrolControlStarter('?patrolControlStarter=patrol_control')).toBe(
+ PATROL_CONTROL_STARTER,
+ );
+ expect(
+ buildPatrolOperationsLoopPath({
+ starter: PATROL_OPERATIONS_LOOP_PATROL_CONTROL_STARTER,
+ }),
+ ).toBe(PATROL_CONTROL_OPERATIONS_LOOP_PATH);
+ expect(
+ buildPatrolOperationsLoopPath({
+ starter: PATROL_OPERATIONS_LOOP_PRO_ACTIVATION_STARTER,
+ }),
+ ).toBe(PATROL_PRO_ACTIVATION_OPERATIONS_LOOP_PATH);
+ expect(parsePatrolOperationsLoopStarter('?operationsLoopStarter=patrol_control')).toBe(
+ PATROL_OPERATIONS_LOOP_PATROL_CONTROL_STARTER,
+ );
+ expect(parsePatrolOperationsLoopStarter('?operationsLoopStarter=patrol_autonomy')).toBe(
+ PATROL_OPERATIONS_LOOP_PATROL_CONTROL_STARTER,
+ );
+ expect(parsePatrolOperationsLoopStarter('?operationsLoopStarter=pulse_pro_activation')).toBe(
+ PATROL_OPERATIONS_LOOP_PATROL_CONTROL_STARTER,
+ );
+ expect(parsePatrolOperationsLoopStarter('?patrolControlStarter=patrol_control')).toBe(
+ PATROL_OPERATIONS_LOOP_PATROL_CONTROL_STARTER,
+ );
+ expect(parsePatrolOperationsLoopStarter('?operationsLoopStarter=pulse_patrol')).toBe('');
+ });
+
+ it('keeps external agent setup in Pulse Intelligence while token creation stays in API Access', () => {
+ expect(SETTINGS_API_ACCESS_PATH).toBe('/settings/security/api');
+ expect(SETTINGS_PULSE_INTELLIGENCE_PATH).toBe('/settings/pulse-intelligence');
+ expect(SETTINGS_PULSE_INTELLIGENCE_ASSISTANT_PATH).toBe(
+ '/settings/pulse-intelligence/assistant',
+ );
+ expect(EXTERNAL_AGENT_SETUP_ANCHOR).toBe('external-agent-setup');
+ expect(EXTERNAL_AGENT_SETUP_PATH).toBe(
+ '/settings/pulse-intelligence/assistant#external-agent-setup',
+ );
+ expect(PULSE_MCP_SETUP_ANCHOR).toBe('pulse-mcp-setup');
+ expect(PULSE_MCP_SETUP_PATH).toBe(EXTERNAL_AGENT_SETUP_PATH);
+ expect(PULSE_MCP_LEGACY_SETUP_PATH).toBe('/settings/security/api#pulse-mcp-setup');
+ expect(isExternalAgentSetupHash('#external-agent-setup')).toBe(true);
+ expect(isExternalAgentSetupHash('#pulse-mcp-setup')).toBe(true);
+ expect(isExternalAgentSetupHash('#api-token-create')).toBe(false);
+ expect(API_TOKEN_CREATE_ANCHOR).toBe('api-token-create');
+ expect(API_TOKEN_PRESET_QUERY_PARAM).toBe('tokenPreset');
+ expect(PULSE_INTELLIGENCE_AGENT_TOKEN_PRESET).toBe('pulse-intelligence-agent');
+ expect(PULSE_MCP_TOKEN_SETUP_PATH).toBe(
+ '/settings/security/api?tokenPreset=pulse-intelligence-agent#api-token-create',
+ );
});
it('builds canonical Proxmox platform tab paths', () => {
@@ -56,9 +172,7 @@ describe('resource link routing contract', () => {
expect(buildDockerRouteSearch({ host: 'frigate.mist-stork.ts.net' })).toBe(
'?host=frigate.mist-stork.ts.net',
);
- expect(buildDockerRouteSearch({ host: ' host with spaces ' })).toBe(
- '?host=host+with+spaces',
- );
+ expect(buildDockerRouteSearch({ host: ' host with spaces ' })).toBe('?host=host+with+spaces');
expect(buildDockerRouteSearch({ host: '' })).toBe('');
expect(KUBERNETES_PATH).toBe('/kubernetes');
diff --git a/frontend-modern/src/routing/resourceLinks.ts b/frontend-modern/src/routing/resourceLinks.ts
index b8d39b959c..f97b3d3a64 100644
--- a/frontend-modern/src/routing/resourceLinks.ts
+++ b/frontend-modern/src/routing/resourceLinks.ts
@@ -30,6 +30,31 @@ export const VMWARE_PATH = '/vmware';
export const VMWARE_DEFAULT_TAB = 'overview';
export const PMG_THRESHOLDS_PATH = '/alerts/thresholds/mail-gateway';
export const PATROL_PATH = '/patrol';
+export const PATROL_CONTROL_ANCHOR = 'patrol-control';
+export const PATROL_CONTROL_STARTER_QUERY_PARAM = 'patrolControlStarter';
+export const PATROL_CONTROL_STARTER = 'patrol_control';
+export const PATROL_CONTROL_PATH = `${PATROL_PATH}#${PATROL_CONTROL_ANCHOR}`;
+export const PATROL_OPERATIONS_LOOP_ANCHOR = 'operations-loop';
+export const PATROL_OPERATIONS_LOOP_STARTER_QUERY_PARAM = 'operationsLoopStarter';
+export const PATROL_OPERATIONS_LOOP_PATROL_CONTROL_STARTER = PATROL_CONTROL_STARTER;
+export const PATROL_OPERATIONS_LOOP_PATROL_AUTONOMY_STARTER = 'patrol_autonomy';
+export const PATROL_OPERATIONS_LOOP_PRO_ACTIVATION_STARTER = 'pulse_pro_activation';
+export const PATROL_OPERATIONS_LOOP_PATH = PATROL_CONTROL_PATH;
+export const SETTINGS_API_ACCESS_PATH = '/settings/security/api';
+export const SETTINGS_PULSE_INTELLIGENCE_PATH = '/settings/pulse-intelligence';
+export const SETTINGS_PULSE_INTELLIGENCE_ASSISTANT_PATH = `${SETTINGS_PULSE_INTELLIGENCE_PATH}/assistant`;
+export const API_TOKEN_CREATE_ANCHOR = 'api-token-create';
+export const API_TOKEN_PRESET_QUERY_PARAM = 'tokenPreset';
+export const PULSE_INTELLIGENCE_AGENT_TOKEN_PRESET = 'pulse-intelligence-agent';
+export const EXTERNAL_AGENT_SETUP_ANCHOR = 'external-agent-setup';
+export const EXTERNAL_AGENT_SETUP_PATH = `${SETTINGS_PULSE_INTELLIGENCE_ASSISTANT_PATH}#${EXTERNAL_AGENT_SETUP_ANCHOR}`;
+export const PULSE_MCP_SETUP_ANCHOR = 'pulse-mcp-setup';
+export const PULSE_MCP_LEGACY_SETUP_PATH = `${SETTINGS_API_ACCESS_PATH}#${PULSE_MCP_SETUP_ANCHOR}`;
+export const PULSE_MCP_SETUP_PATH = EXTERNAL_AGENT_SETUP_PATH;
+export const PULSE_MCP_TOKEN_SETUP_PATH = `${SETTINGS_API_ACCESS_PATH}?${API_TOKEN_PRESET_QUERY_PARAM}=${PULSE_INTELLIGENCE_AGENT_TOKEN_PRESET}#${API_TOKEN_CREATE_ANCHOR}`;
+
+export const isExternalAgentSetupHash = (hash: string | null | undefined): boolean =>
+ hash === `#${EXTERNAL_AGENT_SETUP_ANCHOR}` || hash === `#${PULSE_MCP_SETUP_ANCHOR}`;
export const DOCKER_QUERY_PARAMS = {
host: 'host',
@@ -161,6 +186,63 @@ const serializedRouteSearch = (params: URLSearchParams): string => {
return query ? `?${query}` : '';
};
+export type PatrolOperationsLoopStarter =
+ | typeof PATROL_OPERATIONS_LOOP_PATROL_CONTROL_STARTER
+ | typeof PATROL_OPERATIONS_LOOP_PATROL_AUTONOMY_STARTER
+ | typeof PATROL_OPERATIONS_LOOP_PRO_ACTIVATION_STARTER;
+
+export type PatrolControlStarter = PatrolOperationsLoopStarter;
+
+const isPatrolControlStarter = (starter: string): starter is PatrolControlStarter =>
+ starter === PATROL_CONTROL_STARTER ||
+ starter === PATROL_OPERATIONS_LOOP_PATROL_AUTONOMY_STARTER ||
+ starter === PATROL_OPERATIONS_LOOP_PRO_ACTIVATION_STARTER;
+
+export const buildPatrolControlPath = (
+ options: {
+ starter?: PatrolControlStarter | null;
+ } = {},
+): string => {
+ const params = new URLSearchParams();
+ const starter = normalizeQueryValue(options.starter);
+ if (isPatrolControlStarter(starter)) {
+ params.set(PATROL_CONTROL_STARTER_QUERY_PARAM, PATROL_CONTROL_STARTER);
+ }
+ return `${PATROL_PATH}${serializedRouteSearch(params)}#${PATROL_CONTROL_ANCHOR}`;
+};
+
+export const buildPatrolOperationsLoopPath = buildPatrolControlPath;
+
+export const PATROL_CONTROL_PATH_WITH_STARTER = buildPatrolControlPath({
+ starter: PATROL_CONTROL_STARTER,
+});
+
+export const PATROL_CONTROL_OPERATIONS_LOOP_PATH = PATROL_CONTROL_PATH_WITH_STARTER;
+
+export const PATROL_AUTONOMY_OPERATIONS_LOOP_PATH = buildPatrolControlPath({
+ starter: PATROL_OPERATIONS_LOOP_PATROL_AUTONOMY_STARTER,
+});
+
+export const PATROL_PRO_ACTIVATION_OPERATIONS_LOOP_PATH = buildPatrolControlPath({
+ starter: PATROL_OPERATIONS_LOOP_PRO_ACTIVATION_STARTER,
+});
+
+export const parsePatrolControlStarter = (search: string): PatrolControlStarter | '' => {
+ const params = new URLSearchParams(search);
+ const starter = normalizeQueryValue(
+ firstNonEmpty([
+ params.get(PATROL_CONTROL_STARTER_QUERY_PARAM),
+ params.get(PATROL_OPERATIONS_LOOP_STARTER_QUERY_PARAM),
+ ]),
+ ).toLowerCase();
+ if (isPatrolControlStarter(starter)) {
+ return PATROL_CONTROL_STARTER;
+ }
+ return '';
+};
+
+export const parsePatrolOperationsLoopStarter = parsePatrolControlStarter;
+
export const buildWorkloadsRouteSearch = (options: WorkloadsLinkOptions = {}): string => {
const params = new URLSearchParams();
const type = normalizeWorkloadsType(options.type);
diff --git a/frontend-modern/src/stores/__tests__/aiChat.test.ts b/frontend-modern/src/stores/__tests__/aiChat.test.ts
index 3701735fa9..be2a9ba318 100644
--- a/frontend-modern/src/stores/__tests__/aiChat.test.ts
+++ b/frontend-modern/src/stores/__tests__/aiChat.test.ts
@@ -8,6 +8,11 @@ const aiChatSource = readFileSync(
resolve(process.cwd(), 'src/components/AI/Chat/index.tsx'),
'utf8',
);
+const aiChatStoreSource = readFileSync(resolve(process.cwd(), 'src/stores/aiChat.ts'), 'utf8');
+const useChatSource = readFileSync(
+ resolve(process.cwd(), 'src/components/AI/Chat/hooks/useChat.ts'),
+ 'utf8',
+);
describe('aiChatStore', () => {
beforeEach(() => {
@@ -64,6 +69,13 @@ describe('aiChatStore', () => {
expect(aiChatStore.commandRequest).toMatchObject({ action: 'providers' });
});
+ it('uses native Assistant terminology for browser-owned chat shell state', () => {
+ expect(aiChatStoreSource).not.toContain('Pulse AI');
+ expect(useChatSource).not.toContain('Pulse AI');
+ expect(aiChatStoreSource).toContain('Pulse Assistant');
+ expect(useChatSource).toContain('Send answer to Pulse Assistant via API');
+ });
+
it('sets legacy context and clears it', () => {
aiChatStore.setContext({ targetType: 'vm', targetId: 'vm-101', context: { name: 'vm-101' } });
expect(aiChatStore.context.targetType).toBe('vm');
@@ -139,8 +151,8 @@ describe('aiChatStore', () => {
briefing: {
sourceLabel: 'Pulse Patrol',
title: 'Investigation record attached',
- actionLabel: 'Open Patrol provider settings',
- actionHref: '/settings/system-ai',
+ actionLabel: 'Open Provider & Models',
+ actionHref: '/settings/pulse-intelligence/provider',
},
handoffMetadata: {
kind: 'patrol_finding',
@@ -149,8 +161,8 @@ describe('aiChatStore', () => {
expect(aiChatStore.isOpen).toBe(true);
expect(aiChatStore.context.targetId).toBe('vm-101');
expect(aiChatStore.context.briefing?.title).toBe('Investigation record attached');
- expect(aiChatStore.context.briefing?.actionLabel).toBe('Open Patrol provider settings');
- expect(aiChatStore.context.briefing?.actionHref).toBe('/settings/system-ai');
+ expect(aiChatStore.context.briefing?.actionLabel).toBe('Open Provider & Models');
+ expect(aiChatStore.context.briefing?.actionHref).toBe('/settings/pulse-intelligence/provider');
expect(aiChatStore.context.handoffMetadata).toMatchObject({
kind: 'patrol_finding',
});
@@ -208,6 +220,7 @@ describe('aiChatStore', () => {
runStatus: 'error',
runtimeFailure: true,
},
+ preferredWorkflowPromptName: 'pulse_operations_loop',
});
aiChatStore.clearRequestHandoffPayload();
@@ -216,6 +229,7 @@ describe('aiChatStore', () => {
expect(aiChatStore.context.handoffResources).toBeUndefined();
expect(aiChatStore.context.handoffActions).toBeUndefined();
expect(aiChatStore.context.handoffMetadata).toBeUndefined();
+ expect(aiChatStore.context.preferredWorkflowPromptName).toBeUndefined();
expect(aiChatStore.context.targetId).toBe('storage-1');
expect(aiChatStore.context.findingId).toBe('finding-1');
expect(aiChatStore.context.autonomousMode).toBe(false);
diff --git a/frontend-modern/src/stores/__tests__/systemSettings.test.ts b/frontend-modern/src/stores/__tests__/systemSettings.test.ts
index 6dd52a44b4..47d3f1a093 100644
--- a/frontend-modern/src/stores/__tests__/systemSettings.test.ts
+++ b/frontend-modern/src/stores/__tests__/systemSettings.test.ts
@@ -3,6 +3,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { beforeEach, describe, expect, it } from 'vitest';
import { PRIVACY_DOC_URL } from '@/utils/docsLinks';
+import { EN_MESSAGES } from '@/i18n/messages';
import {
areSystemSettingsLoaded,
markSystemSettingsLoadedWithDefaults,
@@ -58,6 +59,17 @@ describe('systemSettings store', () => {
expect(PRIVACY_DOC_URL).toBe('/docs/PRIVACY.md');
});
+ it('keeps the telemetry disclosure in user-facing product language', () => {
+ const telemetryDescription = EN_MESSAGES['settings.general.telemetry.description'];
+
+ expect(telemetryDescription).toContain(
+ 'coarse Patrol, Assistant, and external-agent usage counters',
+ );
+ expect(telemetryDescription).not.toContain('Pulse Intelligence loop adoption');
+ expect(telemetryDescription).not.toContain('activation loop');
+ expect(telemetryDescription).not.toContain('operations loop');
+ });
+
it('documents telemetry retention and field-level rationale in the privacy doc', () => {
const privacyDoc = readFileSync(path.join(repoRoot, 'docs', 'PRIVACY.md'), 'utf8');
@@ -71,6 +83,13 @@ describe('systemSettings store', () => {
expect(privacyDoc).toContain('rows older than **90 days** are purged automatically');
expect(privacyDoc).toContain('uses client IP addresses transiently for abuse/rate limiting');
expect(privacyDoc).toContain('Reset ID');
+ expect(privacyDoc).toContain('Pulse Intelligence Patrol mode decision 30d');
+ expect(privacyDoc).toContain('Pulse Intelligence paid Patrol mode resolved issue 30d');
+ expect(privacyDoc).not.toContain('operations loop');
+ expect(privacyDoc).not.toContain('Pro activation');
+ expect(privacyDoc).not.toContain('completed-work proof');
+ expect(privacyDoc).not.toContain('resolved-work proof');
+ expect(privacyDoc).not.toContain('governed-operation proof');
});
it('keeps internal commercial compatibility switches out of public configuration docs', () => {
diff --git a/frontend-modern/src/stores/aiChat.ts b/frontend-modern/src/stores/aiChat.ts
index 60587b32a3..28d523f3be 100644
--- a/frontend-modern/src/stores/aiChat.ts
+++ b/frontend-modern/src/stores/aiChat.ts
@@ -1,7 +1,7 @@
import { createSignal } from 'solid-js';
import { logger } from '@/utils/logger';
import { eventBus } from '@/stores/events';
-// NOTE: AIAPI import removed - session management is handled by Pulse AI's embedded UI
+// NOTE: AIAPI import removed - session management is handled by Pulse Assistant's embedded UI
import type { AIChatSessionSummary } from '@/types/ai';
export interface AIChatContextBriefing {
@@ -74,6 +74,7 @@ export interface AIChatContext {
handoffResources?: AIChatHandoffResource[];
handoffActions?: AIChatHandoffAction[];
handoffMetadata?: AIChatHandoffMetadata;
+ preferredWorkflowPromptName?: string;
// Per-request execution mode override; false keeps scoped handoffs approval-required.
autonomousMode?: boolean;
}
@@ -196,9 +197,9 @@ let nextAIChatCommandRequestId = 1;
let aiInputRef: HTMLTextAreaElement | null = null;
// Sync current session to server (debounced)
-// NOTE: Session sync is disabled - Pulse AI handles session management internally
+// NOTE: Session sync is disabled - Pulse Assistant handles session management internally
const syncToServer = async () => {
- // Disabled: Pulse AI manages sessions through its embedded UI
+ // Disabled: Pulse Assistant manages sessions through its embedded UI
return;
};
@@ -211,9 +212,9 @@ const debouncedSync = () => {
};
// Load session from server
-// NOTE: Session sync is disabled - Pulse AI handles session management internally
+// NOTE: Session sync is disabled - Pulse Assistant handles session management internally
const loadSessionFromServer = async (_sessionId: string): Promise<boolean> => {
- // Disabled: Pulse AI manages sessions through its embedded UI
+ // Disabled: Pulse Assistant manages sessions through its embedded UI
return false;
};
@@ -320,9 +321,9 @@ export const aiChatStore = {
},
// Refresh session list from server
- // NOTE: Session sync is disabled - Pulse AI handles session management internally
+ // NOTE: Session sync is disabled - Pulse Assistant handles session management internally
async refreshSessions() {
- // Disabled: Pulse AI manages sessions through its embedded UI
+ // Disabled: Pulse Assistant manages sessions through its embedded UI
return;
},
@@ -375,9 +376,9 @@ export const aiChatStore = {
},
// Delete a session
- // NOTE: Session management is handled by Pulse AI's embedded UI
+ // NOTE: Session management is handled by Pulse Assistant's embedded UI
async deleteSession(_sessionId: string) {
- // Disabled: Pulse AI manages sessions through its embedded UI
+ // Disabled: Pulse Assistant manages sessions through its embedded UI
return;
},
@@ -512,7 +513,8 @@ export const aiChatStore = {
!prev.handoffContext &&
!prev.handoffResources?.length &&
!prev.handoffActions?.length &&
- !prev.handoffMetadata
+ !prev.handoffMetadata &&
+ !prev.preferredWorkflowPromptName
) {
return prev;
}
@@ -521,6 +523,7 @@ export const aiChatStore = {
handoffResources: _handoffResources,
handoffActions: _handoffActions,
handoffMetadata: _handoffMetadata,
+ preferredWorkflowPromptName: _preferredWorkflowPromptName,
...rest
} = prev;
return rest;
diff --git a/frontend-modern/src/stores/aiIntelligence.ts b/frontend-modern/src/stores/aiIntelligence.ts
index 0a67903446..8a02f1af79 100644
--- a/frontend-modern/src/stores/aiIntelligence.ts
+++ b/frontend-modern/src/stores/aiIntelligence.ts
@@ -57,6 +57,7 @@ const VALID_INVESTIGATION_OUTCOMES = new Set<string>([
'fix_queued',
'fix_executed',
'fix_failed',
+ 'fix_rejected',
'needs_attention',
'cannot_fix',
'timed_out',
@@ -163,7 +164,7 @@ export interface UnifiedFinding {
status: 'active' | 'resolved' | 'dismissed' | 'snoozed';
correlatedFindingIds?: string[];
remediationPlanId?: string;
- // Investigation fields (Patrol Autonomy)
+ // Investigation fields (Patrol mode)
investigationSessionId?: string;
investigationStatus?: 'pending' | 'running' | 'completed' | 'failed' | 'needs_attention';
investigationOutcome?:
@@ -171,6 +172,7 @@ export interface UnifiedFinding {
| 'fix_queued'
| 'fix_executed'
| 'fix_failed'
+ | 'fix_rejected'
| 'needs_attention'
| 'cannot_fix'
| 'timed_out'
diff --git a/frontend-modern/src/types/ai.ts b/frontend-modern/src/types/ai.ts
index 2840c32259..2ac608885f 100644
--- a/frontend-modern/src/types/ai.ts
+++ b/frontend-modern/src/types/ai.ts
@@ -40,12 +40,12 @@ export interface AISettings {
chat_model?: string; // Model for interactive chat (empty = use default)
patrol_model?: string; // Model for background patrol (empty = use default)
discovery_model?: string; // Model for infrastructure discovery (empty = use default)
- auto_fix_model?: string; // Model for safe remediation workflows (empty = use patrol model)
+ auto_fix_model?: string; // Model for Patrol fix actions (empty = use patrol model)
configured: boolean; // true if AI is ready to use
custom_context: string; // user-provided infrastructure context
- // OAuth fields for Claude Pro/Max subscription authentication
- auth_method: AuthMethod; // "api_key" or "oauth"
- oauth_connected: boolean; // true if OAuth tokens are configured
+ // Legacy OAuth fields are retained for cleanup/migration only.
+ auth_method: AuthMethod; // "api_key" or legacy "oauth"
+ oauth_connected: boolean; // true if legacy OAuth tokens are stored
// Patrol settings for token efficiency
patrol_interval_minutes?: number; // Patrol interval in minutes (0 = disabled, minimum 10)
patrol_enabled?: boolean; // Legacy/server-authored patrol runtime toggle still surfaced by the API
@@ -57,7 +57,7 @@ export interface AISettings {
patrol_alert_trigger_types?: string[]; // optional allowlist of alert types (empty = all types)
patrol_auto_fix?: boolean; // true if Patrol can remediate without approval
// Multi-provider configuration
- anthropic_configured: boolean; // true if Anthropic API key or OAuth is set
+ anthropic_configured: boolean; // true if Anthropic API key is set
openai_configured: boolean; // true if OpenAI API key is set
openrouter_configured: boolean; // true if OpenRouter API key is set
deepseek_configured: boolean; // true if DeepSeek API key is set
@@ -109,12 +109,12 @@ export interface AISettingsUpdateRequest {
enabled?: boolean;
model?: string;
custom_context?: string; // user-provided infrastructure context
- auth_method?: AuthMethod; // "api_key" or "oauth"
+ auth_method?: AuthMethod; // "api_key" or legacy "oauth"
// Model overrides for different use cases
chat_model?: string; // Model for interactive chat
patrol_model?: string; // Model for background patrol
discovery_model?: string; // Model for infrastructure discovery
- auto_fix_model?: string; // Model for safe remediation workflows
+ auto_fix_model?: string; // Model for Patrol fix actions
// Patrol settings for token efficiency
patrol_interval_minutes?: number; // Custom interval in minutes (0 = disabled, minimum 10)
patrol_enabled?: boolean; // Legacy/server-authored patrol runtime toggle still accepted by the API
diff --git a/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts b/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts
index 33e22f2f10..222eca1d50 100644
--- a/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/aiChatPresentation.test.ts
@@ -65,7 +65,7 @@ describe('aiChatPresentation', () => {
expect(AI_CHAT_DRAWER_SUBTITLE).toBe(
'Observed context, provider-backed reasoning, and governed actions.',
);
- expect(AI_CHAT_DISCOVERY_HINT_TITLE).toBe('Workload Discovery is off.');
+ expect(AI_CHAT_DISCOVERY_HINT_TITLE).toBe('Discovery is off.');
expect(AI_CHAT_DISCOVERY_HINT_BODY).toBe(
'Enable it in Settings so Pulse Assistant can reference real services, versions, and commands instead of generic guidance.',
);
@@ -94,11 +94,13 @@ describe('aiChatPresentation', () => {
expect(AI_CHAT_LAUNCHER_ARIA_LABEL).toBe('Expand Pulse Assistant');
expect(AI_CHAT_CLOSE_LABEL).toBe('Close Pulse Assistant');
expect(AI_CHAT_SESSION_MENU_TITLE).toBe('Pulse Assistant sessions');
- expect(AI_CHAT_AUTONOMOUS_WARNING_DISMISS_LABEL).toBe('Dismiss autonomous control warning');
+ expect(AI_CHAT_AUTONOMOUS_WARNING_DISMISS_LABEL).toBe('Dismiss chat actions warning');
expect(AI_CHAT_DISCOVERY_HINT_DISMISS_LABEL).toBe('Dismiss discovery context warning');
- expect(AI_CHAT_CONTROL_MODE_LABEL).toBe('Assistant control mode');
- expect(AI_CHAT_CONTROL_MODE_MENU_LABEL).toBe('Assistant control mode options');
- expect(AI_CHAT_SWITCH_TO_APPROVAL_LABEL).toBe('Switch Assistant control mode to Approval');
+ expect(AI_CHAT_CONTROL_MODE_LABEL).toBe('Assistant chat action mode');
+ expect(AI_CHAT_CONTROL_MODE_MENU_LABEL).toBe('Assistant chat action options');
+ expect(AI_CHAT_SWITCH_TO_APPROVAL_LABEL).toBe(
+ 'Switch Assistant chat actions to Ask first',
+ );
expect(AI_CHAT_COMMAND_HELP_TITLE).toBe('Assistant commands');
expect(AI_CHAT_COMMAND_HELP_BUTTON_LABEL).toBe('Open Assistant commands');
expect(AI_CHAT_COMMAND_HELP_CLOSE_LABEL).toBe('Close Assistant commands');
@@ -117,7 +119,7 @@ describe('aiChatPresentation', () => {
expect(AI_CHAT_ASSISTANT_MESSAGE_LABEL).toBe('Pulse Assistant');
expect(AI_CHAT_CONTEXT_USED_LABEL).toBe('Context used');
expect(AI_CHAT_LAST_TURN_SUMMARY_LABEL).toBe('Last assistant turn summary');
- expect(AI_CHAT_PROVIDER_READINESS_SETTINGS_HREF).toBe('/settings/system-ai');
+ expect(AI_CHAT_PROVIDER_READINESS_SETTINGS_HREF).toBe('/settings/pulse-intelligence/provider');
expect(AI_CHAT_PROVIDER_READINESS_SETTINGS_LABEL).toBe('Open settings');
expect(AI_CHAT_PROVIDER_READINESS_RETRY_LABEL).toBe('Retry');
});
diff --git a/frontend-modern/src/utils/__tests__/aiControlLevelPresentation.test.ts b/frontend-modern/src/utils/__tests__/aiControlLevelPresentation.test.ts
index 616f78d3b2..598981863b 100644
--- a/frontend-modern/src/utils/__tests__/aiControlLevelPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/aiControlLevelPresentation.test.ts
@@ -22,25 +22,30 @@ describe('aiControlLevelPresentation', () => {
expect(getAIControlLevelPanelClass('autonomous')).toContain('border-amber-200');
expect(getAIControlLevelBadgeClass('controlled')).toContain('bg-amber-100');
expect(getAIControlLevelBadgeClass('autonomous')).toContain('bg-red-100');
- expect(getAIControlLevelDescription('read_only')).toContain('query and observe only');
- expect(getAIControlLevelDescription('controlled')).toContain('after you approve');
- expect(getAIControlLevelDescription('autonomous')).toContain('without per-command approval');
+ expect(getAIControlLevelDescription('read_only')).toContain('Assistant can query and explain');
+ expect(getAIControlLevelDescription('controlled')).toContain(
+ 'asks before chat-only actions',
+ );
+ expect(getAIControlLevelDescription('autonomous')).toContain('eligible chat-only actions');
+ expect(getAIControlLevelDescription('autonomous')).toContain(
+ 'Infrastructure work stays with Patrol mode',
+ );
});
it('returns canonical chat control-level presentation', () => {
expect(getAIChatControlLevelPresentation('read_only')).toMatchObject({
label: 'Read-only',
- description: 'No commands or control actions',
+ description: 'Observes only',
dotClassName: 'bg-slate-400',
});
expect(getAIChatControlLevelPresentation('controlled')).toMatchObject({
- label: 'Approval',
- description: 'Ask before running commands',
+ label: 'Ask first',
+ description: 'Asks before chat-only actions',
dotClassName: 'bg-amber-500',
});
expect(getAIChatControlLevelPresentation('autonomous')).toMatchObject({
- label: 'Autonomous',
- description: 'Executes without approval',
+ label: 'Chat actions',
+ description: 'Eligible chat-only actions',
dotClassName: 'bg-red-500',
});
});
diff --git a/frontend-modern/src/utils/__tests__/aiCostPresentation.test.ts b/frontend-modern/src/utils/__tests__/aiCostPresentation.test.ts
index 61448e3600..d9b38dbd91 100644
--- a/frontend-modern/src/utils/__tests__/aiCostPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/aiCostPresentation.test.ts
@@ -10,6 +10,7 @@ import {
AI_COST_PATROL_USE_CASE_LABEL,
AI_COST_PROVIDER_MODEL_PAIR_LABEL,
AI_COST_RESET_HISTORY_LABEL,
+ AI_COST_TARGET_TABLE_LABEL,
buildAICostExportFilename,
getAICostBudgetNote,
getAICostExportHistoryErrorMessage,
@@ -19,6 +20,7 @@ import {
getAICostResetHistoryConfirmationMessage,
getAICostResetHistoryErrorMessage,
getAICostResetHistorySuccessMessage,
+ getAICostTargetPresentation,
} from '@/utils/aiCostPresentation';
describe('aiCostPresentation', () => {
@@ -38,6 +40,7 @@ describe('aiCostPresentation', () => {
expect(AI_COST_PATROL_USE_CASE_LABEL).toBe('Patrol');
expect(AI_COST_BUDGET_LABEL).toBe('30-day budget (USD)');
expect(AI_COST_RESET_HISTORY_LABEL).toBe('Reset usage history');
+ expect(AI_COST_TARGET_TABLE_LABEL).toBe('Usage by task');
expect(AI_COST_EMPTY_STATE).toBe(
'Provider usage data will appear here once Pulse Assistant or Patrol activity is recorded.',
);
@@ -52,7 +55,7 @@ describe('aiCostPresentation', () => {
});
expect(getAICostRefreshErrorMessage()).toBe('Failed to refresh provider usage summary');
expect(getAICostBudgetNote(7)).toBe(
- 'Configured in Assistant & Patrol settings. Pro-rated for 7d:',
+ 'Configured in Provider & Models settings. Pro-rated for 7d:',
);
expect(getAICostResetHistoryConfirmationMessage()).toBe(
'Reset provider usage history? A backup will be created in the Pulse config directory.',
@@ -63,8 +66,40 @@ describe('aiCostPresentation', () => {
expect(getAICostResetHistorySuccessMessage()).toBe('Provider usage history reset');
expect(getAICostResetHistoryErrorMessage()).toBe('Failed to reset provider usage history');
expect(getAICostExportHistoryErrorMessage()).toBe('Failed to export provider usage history');
+ expect(buildAICostExportFilename(30, 'csv', new Date('2026-03-01T12:00:00Z'))).toBe(
+ 'pulse-provider-usage-2026-03-01-30d.csv',
+ );
+ });
+
+ it('presents usage targets as product concepts instead of raw internal IDs', () => {
+ expect(
+ getAICostTargetPresentation({
+ target_type: 'assistant_session_title',
+ target_id: '7f5941d9-a503-416d-b84e-5a46c9e1e11f',
+ }),
+ ).toEqual({
+ label: 'Assistant sessions',
+ rawLabel: 'assistant_session_title:7f5941d9-a503-416d-b84e-5a46c9e1e11f',
+ });
+
expect(
- buildAICostExportFilename(30, 'csv', new Date('2026-03-01T12:00:00Z')),
- ).toBe('pulse-provider-usage-2026-03-01-30d.csv');
+ getAICostTargetPresentation({
+ target_type: 'patrol_run',
+ target_id: 'ed21e8612df6450fab4ebd4ae2502259',
+ }),
+ ).toEqual({
+ label: 'Patrol runs',
+ rawLabel: 'patrol_run:ed21e8612df6450fab4ebd4ae2502259',
+ });
+
+ expect(
+ getAICostTargetPresentation({
+ target_type: 'vm',
+ target_id: '100',
+ }),
+ ).toEqual({
+ label: 'VM 100',
+ rawLabel: 'vm:100',
+ });
});
});
diff --git a/frontend-modern/src/utils/__tests__/aiPatrolSchedulePresentation.test.ts b/frontend-modern/src/utils/__tests__/aiPatrolSchedulePresentation.test.ts
index 06c1da6600..3b9cc1632d 100644
--- a/frontend-modern/src/utils/__tests__/aiPatrolSchedulePresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/aiPatrolSchedulePresentation.test.ts
@@ -4,6 +4,7 @@ import {
getPatrolScheduleLabel,
PATROL_SCHEDULE_PRESETS,
} from '@/utils/aiPatrolSchedulePresentation';
+import { getPatrolRuntimePresentation } from '@/utils/patrolRuntimePresentation';
describe('aiPatrolSchedulePresentation', () => {
it('returns canonical patrol schedule presets', () => {
@@ -20,4 +21,12 @@ describe('aiPatrolSchedulePresentation', () => {
expect(buildPatrolScheduleOptions(360)).toEqual([...PATROL_SCHEDULE_PRESETS]);
expect(buildPatrolScheduleOptions(17)).toContainEqual({ value: 17, label: '17 min' });
});
+
+ it('keeps header runtime copy in check language', () => {
+ expect(getPatrolRuntimePresentation('running')).toMatchObject({
+ label: 'Patrol enabled',
+ title: 'Patrol running',
+ description: 'Patrol is checking your infrastructure now.',
+ });
+ });
});
diff --git a/frontend-modern/src/utils/__tests__/aiSettingsPresentation.test.ts b/frontend-modern/src/utils/__tests__/aiSettingsPresentation.test.ts
index 57aeaab50a..fe6e53899f 100644
--- a/frontend-modern/src/utils/__tests__/aiSettingsPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/aiSettingsPresentation.test.ts
@@ -25,27 +25,27 @@ import {
} from '@/utils/aiSettingsPresentation';
describe('aiSettingsPresentation', () => {
- it('returns the canonical assistant and patrol shell framing copy', () => {
- expect(AI_SETTINGS_PANEL_TITLE).toBe('Assistant & Patrol');
+ it('returns the canonical provider and models shell framing copy', () => {
+ expect(AI_SETTINGS_PANEL_TITLE).toBe('Provider & Models');
expect(AI_SETTINGS_PANEL_DESCRIPTION).toBe(
- 'Configure providers and models for Pulse Assistant and Patrol.',
+ 'Configure providers, default models, provider health, budget, and usage for Pulse Intelligence.',
);
expect(AI_SETTINGS_MODEL_OVERRIDES_TITLE).toBe('Model Overrides');
expect(AI_SETTINGS_ASSISTANT_SESSIONS_TITLE).toBe('Pulse Assistant Sessions');
- expect(AI_SETTINGS_ASSISTANT_PERMISSIONS_TITLE).toBe('Pulse Assistant Permissions');
+ expect(AI_SETTINGS_ASSISTANT_PERMISSIONS_TITLE).toBe('Assistant chat actions');
expect(getAISettingsWorkloadDiscoveryHelpContent()).toEqual({
- title: 'What is workload discovery?',
+ title: 'What is service context?',
description:
- 'Workload discovery scans your VMs, containers, and container runtimes to identify running services, versions, and access details. Pulse stores that context so Assistant can use it in chat and Patrol can use it during verification.',
+ 'Service context scans your VMs, containers, and container runtimes to identify running services, versions, and access details. Pulse stores those facts so Assistant can use them in chat and Patrol can use them during verification.',
});
expect(getAISettingsWorkloadDiscoverySummary()).toEqual({
- text: 'Workload discovery stores concrete service context for Assistant chat and Patrol verification, so responses and findings can reference real services and commands instead of generic advice.',
+ text: 'Service context records service names, versions, and commands so Assistant and Patrol can use real context instead of generic advice.',
});
expect(getAISettingsSetupDialogPresentation()).toEqual({
- ariaLabel: 'Set up Assistant and Patrol',
- title: 'Set Up Assistant & Patrol',
- description: 'Connect a provider to power Pulse Assistant and Patrol.',
- submitLabel: 'Enable Assistant & Patrol',
+ ariaLabel: 'Set up Pulse Intelligence',
+ title: 'Set Up Pulse Intelligence',
+ description: 'Connect a provider to power Patrol, Assistant, and service context.',
+ submitLabel: 'Enable Pulse Intelligence',
});
});
@@ -93,15 +93,18 @@ describe('aiSettingsPresentation', () => {
'Unable to complete authentication with Claude.',
);
expect(getAIOAuthErrorMessage('save_failed')).toBe('Unable to save OAuth credentials.');
+ expect(getAIOAuthErrorMessage('unsupported')).toBe(
+ 'Anthropic subscription OAuth is not supported. Configure an Anthropic API key instead.',
+ );
expect(getAIOAuthErrorMessage('other')).toBe('Authentication error: other');
});
it('returns canonical ai settings loading and chat-session copy', () => {
expect(getAISettingsLoadingState()).toEqual({
- text: 'Loading Assistant & Patrol settings...',
+ text: 'Loading Provider & Models settings...',
});
expect(getAISettingsLoadErrorMessage()).toBe(
- 'Unable to load Assistant & Patrol settings. Your configuration could not be retrieved.',
+ 'Unable to load Provider & Models settings. Your configuration could not be retrieved.',
);
expect(getAISettingsRetryLabel()).toBe('Retry');
expect(getAIChatSessionsLoadingState()).toEqual({
@@ -119,11 +122,14 @@ describe('aiSettingsPresentation', () => {
it('returns canonical ai settings operational failure copy', () => {
expect(getAISessionSummarizeErrorMessage()).toBe('Unable to summarize the session.');
expect(getAISessionSummarizeErrorMessage('provider offline')).toBe('provider offline');
- expect(getAISettingsSaveErrorMessage()).toBe('Unable to save Assistant & Patrol settings.');
+ expect(getAISettingsSaveErrorMessage()).toBe('Unable to save Provider & Models settings.');
+ expect(getAISettingsSaveErrorMessage(undefined, 'Unable to save Patrol settings.')).toBe(
+ 'Unable to save Patrol settings.',
+ );
expect(getAISettingsSaveErrorMessage('bad request')).toBe('bad request');
expect(getAICredentialsClearErrorMessage()).toBe('Unable to clear credentials.');
expect(getAICredentialsClearErrorMessage('permission denied')).toBe('permission denied');
- expect(getAISettingsToggleErrorMessage()).toBe('Unable to update Assistant & Patrol settings.');
+ expect(getAISettingsToggleErrorMessage()).toBe('Unable to update Pulse Intelligence settings.');
expect(getAISettingsToggleErrorMessage('rate limited')).toBe('rate limited');
});
});
diff --git a/frontend-modern/src/utils/__tests__/commercialBillingModel.test.ts b/frontend-modern/src/utils/__tests__/commercialBillingModel.test.ts
index e971be5573..eb1bb32ff8 100644
--- a/frontend-modern/src/utils/__tests__/commercialBillingModel.test.ts
+++ b/frontend-modern/src/utils/__tests__/commercialBillingModel.test.ts
@@ -22,7 +22,7 @@ describe('commercialBillingModel', () => {
expect(model.summary).toEqual([
{ label: 'Core Monitoring', value: 'Included' },
{ label: 'Metric History', value: '90 days' },
- { label: 'Included Extras', value: 'Analysis, remediation, and admin controls' },
+ { label: 'Included Extras', value: 'Patrol modes, history, and admin controls' },
]);
expect(model.details.map((item) => item.label)).toEqual([
'Tier',
@@ -48,5 +48,4 @@ describe('commercialBillingModel', () => {
expect(model.summary.map((item) => item.label)).not.toContain('Guest Capacity');
expect(JSON.stringify(model)).not.toContain('Unlimited');
});
-
});
diff --git a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
index 6f4e61692d..99084071e4 100644
--- a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
+++ b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts
@@ -189,7 +189,6 @@ import toolPresentationSource from '@/components/AI/Chat/toolPresentation.ts?raw
import toolExecutionBlockSource from '@/components/AI/Chat/ToolExecutionBlock.tsx?raw';
import aiChatSource from '@/components/AI/Chat/index.tsx?raw';
import useChatSource from '@/components/AI/Chat/hooks/useChat.ts?raw';
-import patrolStatusBarSource from '@/components/patrol/PatrolStatusBar.tsx?raw';
import patrolFormatSource from '@/utils/patrolFormat.ts?raw';
import aiFindingPresentationSource from '@/utils/aiFindingPresentation.ts?raw';
import chatIdentifiersSource from '@/utils/chatIdentifiers.ts?raw';
@@ -470,7 +469,6 @@ import aiIntelligenceStoreSource from '@/stores/aiIntelligence.ts?raw';
import aiIntelligenceSummaryModelSource from '@/stores/aiIntelligenceSummaryModel.ts?raw';
import patrolIntelligenceBannersSource from '@/features/patrol/PatrolIntelligenceBanners.tsx?raw';
import patrolIntelligenceHeaderSource from '@/features/patrol/PatrolIntelligenceHeader.tsx?raw';
-import patrolIntelligenceSummarySource from '@/features/patrol/PatrolIntelligenceSummary.tsx?raw';
import patrolIntelligenceSurfaceSource from '@/features/patrol/PatrolIntelligenceSurface.tsx?raw';
import patrolInvestigationContextModelSource from '@/features/patrol/patrolInvestigationContextModel.ts?raw';
import patrolIntelligenceStateSource from '@/features/patrol/usePatrolIntelligenceState.ts?raw';
@@ -2174,7 +2172,6 @@ describe('frontend resource type boundaries', () => {
expect(activeTurnStatusSource).toContain('formatIdentifierLabel');
expect(toolPresentationSource).toContain('formatIdentifierLabel');
expect(aiChatSource).toContain('formatIdentifierLabel');
- expect(patrolStatusBarSource).toContain('formatTriggerReason');
expect(findingsPanelSource).toContain('formatIdentifierLabel');
expect(patrolFormatSource).toContain('formatIdentifierLabel');
expect(aiFindingPresentationSource).toContain('formatIdentifierLabel');
@@ -2182,7 +2179,6 @@ describe('frontend resource type boundaries', () => {
expect(toolExecutionBlockSource).not.toContain("replace(/^pulse_/, '').replace(/_/g, ' ')");
expect(aiChatSource).not.toContain("replace(/^pulse_/, '').replace(/_/g, ' ')");
expect(findingsPanelSource).not.toContain("replace(/_/g, ' ')");
- expect(patrolStatusBarSource).not.toContain("replace(/_/g, ' ') : ''");
expect(patrolFormatSource).not.toContain("replace(/_/g, ' ') : 'Unknown'");
expect(aiFindingPresentationSource).not.toContain("replace(/_/g, ' ')");
expect(patrolRunPresentationSource).toContain('formatIdentifierLabel');
@@ -3483,6 +3479,9 @@ describe('frontend resource type boundaries', () => {
expect(updateInstallGuideSource).toContain('buildUpdateInstallGuide');
expect(copyCommandBlockSource).toContain('export function CopyCommandBlock');
expect(copyCommandBlockSource).toContain('CommandCopyButton');
+ expect(copyCommandBlockSource).toContain('@/utils/clipboard');
+ expect(copyCommandBlockSource).toContain('copyToClipboard(props.command)');
+ expect(copyCommandBlockSource).not.toContain('navigator.clipboard.writeText');
expect(copyCommandBlockSource).toContain('label="Copy to clipboard"');
expect(updatesSettingsModelSource).toContain('export function getUpdateChannelCardOptions');
expect(updatesSettingsModelSource).toContain('export function buildUpdateInstallGuide');
@@ -3562,32 +3561,27 @@ describe('frontend resource type boundaries', () => {
expect(patrolIntelligenceSurfaceSource).toContain('./usePatrolIntelligenceState');
expect(patrolIntelligenceSurfaceSource).toContain('./PatrolIntelligenceHeader');
expect(patrolIntelligenceSurfaceSource).toContain('./PatrolIntelligenceBanners');
- expect(patrolIntelligenceSurfaceSource).toContain('./PatrolIntelligenceSummary');
+ expect(patrolIntelligenceSurfaceSource).not.toContain('./PatrolIntelligenceSummary');
expect(patrolIntelligenceSurfaceSource).toContain('./PatrolIntelligenceWorkspace');
expect(patrolIntelligenceBannersSource).toContain('presentationPolicyHidesUpgradePrompts');
expect(patrolIntelligenceBannersSource).toContain('!presentationPolicyHidesUpgradePrompts()');
expect(patrolIntelligenceBannersSource).toContain('state.licenseRequired()');
expect(patrolIntelligenceHeaderSource).toContain('presentationPolicyHidesUpgradePrompts');
- expect(patrolIntelligenceHeaderSource).toContain(
- '!presentationPolicyHidesUpgradePrompts() && state.autoFixLocked()',
- );
- expect(patrolIntelligenceHeaderSource).toContain(
- '!presentationPolicyHidesUpgradePrompts() && state.alertAnalysisLocked()',
- );
+ expect(patrolIntelligenceHeaderSource).toContain('presentationPolicyHidesCommercialSurfaces');
+ expect(patrolIntelligenceHeaderSource).toContain('!presentationPolicyHidesUpgradePrompts()');
+ expect(patrolIntelligenceHeaderSource).toContain('!commercialSurfacesHidden()');
expect(patrolIntelligenceHeaderSource).toContain(
"from '@/components/shared/FilterButtonGroup'",
);
- expect(patrolIntelligenceHeaderSource).toContain('variant="segmented"');
+ expect(patrolIntelligenceHeaderSource).toContain("options.variant ?? 'segmented'");
expect(patrolIntelligenceHeaderSource).not.toContain(
'flex items-center bg-base rounded-md p-1 border shadow-inner',
);
expect(patrolIntelligenceHeaderSource).not.toContain(
'flex-1 py-1.5 px-2 text-xs font-semibold rounded-md transition-all duration-200',
);
- expect(patrolIntelligenceSummarySource).toContain('StatusIndicatorBadge');
- expect(patrolIntelligenceSummarySource).toContain('runtimeShellPresentation().badgeVariant');
- expect(patrolIntelligenceSummarySource).not.toContain('runtimeShellPresentation().badgeClass');
- expect(patrolIntelligenceSummarySource).not.toContain(
+ expect(patrolIntelligenceSurfaceSource).not.toContain('runtimeShellPresentation()');
+ expect(patrolIntelligenceSurfaceSource).not.toContain(
'inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em]',
);
expect(patrolSummaryPresentationSource).toContain('badgeVariant:');
@@ -3628,7 +3622,10 @@ describe('frontend resource type boundaries', () => {
// Verify the symbol is imported from the model without prescribing a
// specific single- vs multi-line import shape; usePatrolIntelligenceState
// groups several patrolInvestigationContextModel imports together.
- expect(patrolIntelligenceStateSource).toContain('buildPatrolInvestigationContextSummary');
+ expect(patrolIntelligenceStateSource).toContain(
+ 'buildPatrolAssistantFindingHandoffFromUnifiedFinding',
+ );
+ expect(patrolIntelligenceStateSource).toContain('buildPatrolSettingsReadinessFailure');
expect(patrolIntelligenceStateSource).toContain("from './patrolInvestigationContextModel'");
expect(patrolIntelligenceStateSource).not.toContain('recent_changes?.length');
expect(patrolIntelligenceStateSource).not.toContain('governed resource${');
@@ -3653,13 +3650,18 @@ describe('frontend resource type boundaries', () => {
'record.proposed_fix.commands.join',
);
expect(patrolInvestigationContextModelSource).toContain('policy-covered resource');
- expect(patrolIntelligenceHeaderSource).toContain('buildPatrolScheduleOptions');
+ expect(patrolIntelligenceHeaderSource).not.toContain('buildPatrolScheduleOptions');
expect(patrolIntelligenceHeaderSource).not.toContain('getAIQuickstartCreditsPresentation');
expect(patrolIntelligenceHeaderSource).not.toContain('quickstart_credits');
expect(patrolIntelligenceHeaderSource).not.toContain('using_quickstart');
- expect(patrolIntelligenceSummarySource).toContain('getPatrolAssessmentPresentation');
+ expect(patrolIntelligenceSurfaceSource).not.toContain('getPatrolAssessmentPresentation');
expect(patrolIntelligenceWorkspaceSource).toContain('ApprovalBanner');
expect(patrolIntelligenceWorkspaceSource).toContain('FindingsPanel');
+ expect(patrolIntelligenceStateSource).toContain('const historicalRegressionCount = createMemo');
+ expect(patrolIntelligenceStateSource).toContain('historicalRegressionCount,');
+ expect(patrolIntelligenceWorkspaceSource).toContain(
+ 'historicalRegressionCount={state.historicalRegressionCount()}',
+ );
expect(patrolIntelligenceBannersSource).not.toContain('trackUpgradeClicked');
expect(patrolIntelligenceSurfaceSource).not.toContain(
"summaryStats().criticalFindings > 0\n ? 'bg-red-50 dark:bg-red-900 border-red-200 dark:border-red-800'",
@@ -3682,7 +3684,7 @@ describe('frontend resource type boundaries', () => {
expect(investigationSectionSource).toContain('getInvestigationSectionState');
expect(investigationSectionSource).not.toContain('Loading investigation...');
expect(investigationSectionSource).not.toContain(
- 'No investigation data available. Enable patrol autonomy to investigate findings.',
+ 'No investigation yet. Patrol adds notes after it runs in a mode that investigates.',
);
expect(runHistoryPanelSource).toContain('getRunHistoryEmptyState');
expect(runHistoryPanelSource).toContain('getRunHistoryLoadingState');
@@ -3707,6 +3709,10 @@ describe('frontend resource type boundaries', () => {
expect(patrolEmptyStatePresentationSource).toContain(
'export function getPatrolFindingsEmptyState',
);
+ expect(patrolEmptyStatePresentationSource).toContain('historicalRegressionCount?: number');
+ expect(patrolEmptyStatePresentationSource).toContain(
+ 'HISTORICAL_REGRESSION_EMPTY_STATE_BODY',
+ );
expect(patrolRunPresentationSource).toContain('export function getRunHistoryLoadingState');
expect(patrolRunPresentationSource).toContain('export function getToolCallsLoadingState');
expect(patrolRunPresentationSource).toContain('export function getToolCallsUnavailableState');
diff --git a/frontend-modern/src/utils/__tests__/licensePresentation.test.ts b/frontend-modern/src/utils/__tests__/licensePresentation.test.ts
index 8f88010135..2750550c65 100644
--- a/frontend-modern/src/utils/__tests__/licensePresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/licensePresentation.test.ts
@@ -8,7 +8,7 @@ import {
getCommercialMigrationNotice,
getFeatureMinTierLabel,
getGrandfatheredPriceContinuityNotice,
- getSelfHostedActivationProofPresentation,
+ getSelfHostedPlanStatusPresentation,
getSelfHostedActivationSuccessPresentation,
getSelfHostedPlanComparisonPresentation,
getSelfHostedCurrentPlanPresentation,
@@ -24,12 +24,20 @@ import {
getPurchaseActivationNotice,
isDisplayableLicenseFeature,
isGrandfatheredRecurringV5PlanVersion,
+ PATROL_CONTROL_STARTER_URL,
SELF_HOSTED_RECOVERY_PRESENTATION,
} from '@/utils/licensePresentation';
import { SELF_HOSTED_PRO_BILLING_PRESENTATION } from '@/components/Settings/selfHostedBillingPresentation';
import { getSelfHostedPlanEntitlementSummary } from '@/utils/selfHostedPlans';
+import { PATROL_CONTROL_PATH } from '@/routing/resourceLinks';
describe('licensePresentation', () => {
+ it('routes the Patrol mode CTA to the owned Patrol journey', () => {
+ expect(PATROL_CONTROL_STARTER_URL).toBe(
+ '/patrol?patrolControlStarter=patrol_control#patrol-control',
+ );
+ });
+
it('returns canonical tier labels', () => {
expect(getLicenseTierLabel('free')).toBe('Community');
expect(getLicenseTierLabel('pro_plus')).toBe('Legacy Pro+');
@@ -49,10 +57,10 @@ describe('licensePresentation', () => {
text: 'Community is ready to use on this instance.',
});
expect(SELF_HOSTED_RECOVERY_PRESENTATION).toMatchObject({
- disclosureLabel: 'Use existing key',
- fieldLabel: 'License or Activation Key',
- activateIdleLabel: 'Activate Key',
- clearIdleLabel: 'Clear Key',
+ disclosureLabel: 'Manual key recovery',
+ fieldLabel: 'License key',
+ activateIdleLabel: 'Apply key',
+ clearIdleLabel: 'Clear key',
privateRuntimeNotice: {
title: 'Paid Docker and Linux installs use a private runtime',
actionLabel: 'Open Pulse Pro downloads',
@@ -63,22 +71,20 @@ describe('licensePresentation', () => {
},
});
expect(SELF_HOSTED_PRO_BILLING_PRESENTATION).toEqual({
- navLabel: 'Plans',
- shellTitle: 'Self-hosted plan',
- shellDescription:
- 'Review the plan this instance is using and the optional capabilities connected to it.',
- infrastructureRouteReferral: 'Billing and self-hosted plan changes live in Plans.',
+ navLabel: 'Plans & Billing',
+ shellTitle: 'Plans & Billing',
+ shellDescription: 'Plan, license, and Patrol mode for this instance.',
+ infrastructureRouteReferral: 'Billing and self-hosted plan changes live in Plans & Billing.',
infrastructureWorkspaceReferral:
- 'Self-hosted plan status, optional activation, and available capabilities live in Plans, not here.',
- sectionSelectorAriaLabel: 'Self-hosted plans section',
+ 'Self-hosted plan status, Patrol mode, and available capabilities live in Plans & Billing, not here.',
+ sectionSelectorAriaLabel: 'Plans and billing section',
refreshLabel: 'Refresh',
planTabLabel: 'Plan',
usageTabLabel: 'Usage',
planSectionTitle: 'Current plan',
- planSectionDescription:
- 'See which self-hosted tier this instance is using and which capabilities are available on this install.',
- planComparisonSectionTitle: 'Optional extras',
- planComparisonActionLabel: 'See all plans',
+ planSectionDescription: 'Current tier and enabled capabilities.',
+ planComparisonSectionTitle: 'Available plans',
+ planComparisonActionLabel: 'View plans',
usageSectionTitle: 'Usage',
hiddenShellTitle: 'Demo mode',
hiddenShellDescription: 'Commercial settings are hidden for this session.',
@@ -88,18 +94,16 @@ describe('licensePresentation', () => {
policyLoadingTitle: 'Loading settings access',
policyLoadingBody:
'Pulse waits for the session presentation policy before showing license, billing, or usage details.',
- planSelectionPromptTitle: 'Compare self-hosted plans',
- planSelectionPromptBody:
- 'Community includes core monitoring at no cost. Relay is optional for secure access from anywhere, and Pulse Pro adds root-cause analysis, safe remediation workflows, and 90-day history.',
- planSelectionPromptActionLabel: 'Compare plans',
+ planSelectionPromptTitle: 'Select a plan',
+ planSelectionPromptBody: 'Choose the plan for this install.',
+ planSelectionPromptActionLabel: 'View plans',
purchaseActivatedPlanActionLabel: 'Review plan',
- purchaseCancelledActionLabel: 'Compare plans',
- purchaseExpiredActionLabel: 'Compare plans',
+ purchaseCancelledActionLabel: 'View plans',
+ purchaseExpiredActionLabel: 'View plans',
purchaseFailedActionLabel: 'Open recovery',
purchaseUnavailableActionLabel: 'Try again',
- recoverySectionTitle: 'Existing purchases',
- recoverySectionDescription:
- 'Add an activation key you already have, recover a previous self-hosted purchase, or clear a local key from this instance.',
+ recoverySectionTitle: 'License recovery',
+ recoverySectionDescription: 'Paste a license key or clear the license on this install.',
});
});
@@ -257,12 +261,12 @@ describe('licensePresentation', () => {
}),
).toEqual({
title: 'Current plan: Community',
- body: 'Community is active on this instance. It includes self-hosted monitoring, 7-day metric history, Pulse Patrol (BYOK), update alerts, and SSO.',
+ body: 'Community is active on this instance. It includes self-hosted monitoring, 7-day metric history, watch-only Patrol, update alerts, and SSO.',
unlockedFeaturesLabel: 'Included on this instance',
unlockedFeatures: [
'Real-time monitoring',
'7-day metric history',
- 'Pulse Patrol (BYOK)',
+ 'Watch-only Patrol',
'Update alerts',
],
includedExtras: [],
@@ -281,11 +285,11 @@ describe('licensePresentation', () => {
upgrade_reasons: [],
runtime: { build: 'pro', label: 'Pulse Pro runtime' },
},
- displayableCapabilities: ['Pulse Relay (Remote Access)', 'Safe Remediation Workflows'],
+ displayableCapabilities: ['Pulse Relay (Remote Access)', 'Patrol Handles Safe Fixes'],
}),
).toMatchObject({
title: 'Current plan: Pulse Pro',
- body: 'Pulse Pro is active on this instance. Root-cause analysis, safe remediation workflows, 90-day history, and admin/reporting extras are available right now.',
+ body: 'Pulse Pro is active on this instance. It includes Patrol modes, 90-day metric history, RBAC, audit logs, reports, and agent profiles.',
supplementalBadges: [],
supplementalSummary: '',
});
@@ -303,16 +307,16 @@ describe('licensePresentation', () => {
displayableCapabilities: [
'Pulse Relay (Remote Access)',
'Pulse Mobile Pairing',
- 'Safe Remediation Workflows',
+ 'Patrol Handles Safe Fixes',
],
}),
).toEqual({
title: 'Current plan: Pulse Pro',
- body: 'Pulse Pro is active on this instance. Root-cause analysis, safe remediation workflows, 90-day history, and admin/reporting extras are available right now.',
+ body: 'Pulse Pro is active on this instance. It includes Patrol modes, 90-day metric history, RBAC, audit logs, reports, and agent profiles.',
unlockedFeaturesLabel: 'Primary capabilities',
unlockedFeatures: [
- 'Alert Root-Cause Analysis',
- 'Safe Remediation Workflows',
+ 'Patrol Investigates Issues',
+ 'Patrol Handles Safe Fixes',
'90-day metric history',
],
includedExtrasLabel: 'Included extras',
@@ -324,6 +328,245 @@ describe('licensePresentation', () => {
],
supplementalBadges: [],
supplementalSummary: '',
+ patrolControlAction: {
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ },
+ });
+
+ expect(
+ getSelfHostedCurrentPlanPresentation({
+ entitlements: {
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: ['relay', 'mobile_app', 'ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ },
+ displayableCapabilities: [
+ 'Pulse Relay (Remote Access)',
+ 'Pulse Mobile Pairing',
+ 'Patrol Handles Safe Fixes',
+ ],
+ patrolOperatorStatus: {
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 0,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ externalAgentReady: false,
+ },
+ }),
+ ).toMatchObject({
+ body: 'Pulse Pro is active on this instance. Open Patrol to continue current work.',
+ patrolControlAction: {
+ actionLabel: 'Open Patrol',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ },
+ });
+
+ expect(
+ getSelfHostedCurrentPlanPresentation({
+ entitlements: {
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: ['relay', 'mobile_app', 'ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ },
+ displayableCapabilities: [
+ 'Pulse Relay (Remote Access)',
+ 'Pulse Mobile Pairing',
+ 'Patrol Handles Safe Fixes',
+ ],
+ patrolOperatorStatus: {
+ proActivationOperationsLoopStarterCount: 1,
+ proActivationCompletedOperationsLoopCount: 0,
+ proActivationResolvedOperationsLoopCount: 0,
+ proActivationValueProofState: 'in_progress',
+ externalAgentReady: false,
+ },
+ }).patrolControlAction,
+ ).toMatchObject({
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ });
+
+ expect(
+ getSelfHostedCurrentPlanPresentation({
+ entitlements: {
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: ['relay', 'mobile_app', 'ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ },
+ displayableCapabilities: [
+ 'Pulse Relay (Remote Access)',
+ 'Pulse Mobile Pairing',
+ 'Patrol Handles Safe Fixes',
+ ],
+ patrolOperatorStatus: {
+ patrolControlOperationsLoopStarterCount: 1,
+ proActivationOperationsLoopStarterCount: 1,
+ externalAgentReady: false,
+ },
+ }).patrolControlAction,
+ ).toMatchObject({
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ });
+
+ expect(
+ getSelfHostedCurrentPlanPresentation({
+ entitlements: {
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: ['relay', 'mobile_app', 'ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ },
+ displayableCapabilities: [
+ 'Pulse Relay (Remote Access)',
+ 'Pulse Mobile Pairing',
+ 'Patrol Handles Safe Fixes',
+ ],
+ patrolOperatorStatus: {
+ patrolControlOperationsLoopStarterCount: 2,
+ proActivationOperationsLoopStarterCount: 1,
+ externalAgentReady: false,
+ },
+ }).patrolControlAction,
+ ).toMatchObject({
+ actionLabel: 'Open Patrol',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ });
+
+ expect(
+ getSelfHostedCurrentPlanPresentation({
+ entitlements: {
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: ['relay', 'mobile_app', 'ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ },
+ displayableCapabilities: [
+ 'Pulse Relay (Remote Access)',
+ 'Pulse Mobile Pairing',
+ 'Patrol Handles Safe Fixes',
+ ],
+ patrolOperatorStatus: {
+ patrolControlOperationsLoopStarterCount: 1,
+ patrolControlCompletedOperationsLoopCount: 1,
+ patrolControlResolvedOperationsLoopCount: 1,
+ patrolControlValueState: 'verified',
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 1,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ patrolAutonomyValueState: 'governed_decision_recorded',
+ externalAgentReady: true,
+ },
+ }).patrolControlAction,
+ ).toMatchObject({
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ });
+ expect(
+ getSelfHostedCurrentPlanPresentation({
+ entitlements: {
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: ['relay', 'mobile_app', 'ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ },
+ displayableCapabilities: [
+ 'Pulse Relay (Remote Access)',
+ 'Pulse Mobile Pairing',
+ 'Patrol Handles Safe Fixes',
+ ],
+ patrolOperatorStatus: {
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 1,
+ patrolAutonomyResolvedOperationsLoopCount: 1,
+ patrolAutonomyValueState: 'verified',
+ externalAgentReady: true,
+ },
+ }).patrolControlAction,
+ ).toMatchObject({
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ });
+
+ expect(
+ getSelfHostedCurrentPlanPresentation({
+ entitlements: {
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: ['relay', 'mobile_app', 'ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ },
+ displayableCapabilities: [
+ 'Pulse Relay (Remote Access)',
+ 'Pulse Mobile Pairing',
+ 'Patrol Handles Safe Fixes',
+ ],
+ patrolOperatorStatus: {
+ nextAction: 'complete',
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 1,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ patrolAutonomyValueState: 'governed_decision_recorded',
+ externalAgentReady: true,
+ },
+ }).patrolControlAction,
+ ).toMatchObject({
+ actionLabel: 'Review Patrol decision',
+ actionUrl: PATROL_CONTROL_PATH,
+ actionIntent: 'patrol_control',
+ });
+ expect(
+ getSelfHostedCurrentPlanPresentation({
+ entitlements: {
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: ['relay', 'mobile_app', 'ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ },
+ displayableCapabilities: [
+ 'Pulse Relay (Remote Access)',
+ 'Pulse Mobile Pairing',
+ 'Patrol Handles Safe Fixes',
+ ],
+ patrolOperatorStatus: {
+ nextAction: 'open_mcp',
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 1,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ patrolAutonomyValueState: 'verified_needs_mcp',
+ externalAgentReady: false,
+ },
+ }).patrolControlAction,
+ ).toMatchObject({
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
});
expect(
@@ -336,15 +579,15 @@ describe('licensePresentation', () => {
upgrade_reasons: [],
runtime: { build: 'pro', label: 'Pulse Pro runtime' },
},
- displayableCapabilities: ['Pulse Relay (Remote Access)', 'Safe Remediation Workflows'],
+ displayableCapabilities: ['Pulse Relay (Remote Access)', 'Patrol Handles Safe Fixes'],
}),
).toMatchObject({
title: 'Current plan: Legacy Pulse Pro+',
- body: 'Legacy Pulse Pro+ is active on this instance. Root-cause analysis, safe remediation workflows, 90-day history, and admin/reporting extras are available right now.',
+ body: 'Legacy Pulse Pro+ is active on this instance. It includes Patrol modes, 90-day metric history, RBAC, audit logs, reports, and agent profiles.',
unlockedFeaturesLabel: 'Primary capabilities',
unlockedFeatures: [
- 'Alert Root-Cause Analysis',
- 'Safe Remediation Workflows',
+ 'Patrol Investigates Issues',
+ 'Patrol Handles Safe Fixes',
'90-day metric history',
],
});
@@ -364,11 +607,11 @@ describe('licensePresentation', () => {
}),
).toEqual({
title: 'Current plan: Pulse Pro',
- body: 'Pulse Pro is active on this instance. Root-cause analysis, safe remediation workflows, 90-day history, and admin/reporting extras are available right now.',
+ body: 'Pulse Pro is active on this instance. It includes Patrol modes, 90-day metric history, RBAC, audit logs, reports, and agent profiles.',
unlockedFeaturesLabel: 'Primary capabilities',
unlockedFeatures: [
- 'Alert Root-Cause Analysis',
- 'Safe Remediation Workflows',
+ 'Patrol Investigates Issues',
+ 'Patrol Handles Safe Fixes',
'90-day metric history',
],
includedExtrasLabel: 'Included extras',
@@ -413,7 +656,7 @@ describe('licensePresentation', () => {
actionUrl: 'https://pulserelay.pro/download.html',
},
});
- expect(getSelfHostedActivationProofPresentation(entitlements)?.items[0]).toMatchObject({
+ expect(getSelfHostedPlanStatusPresentation(entitlements)?.items[0]).toMatchObject({
label: 'Pulse Pro runtime',
statusLabel: 'Needs attention',
state: 'missing',
@@ -460,7 +703,7 @@ describe('licensePresentation', () => {
actionUrl: 'https://pulserelay.pro/download.html',
},
});
- expect(getSelfHostedActivationProofPresentation(entitlements)?.items[0]).toMatchObject({
+ expect(getSelfHostedPlanStatusPresentation(entitlements)?.items[0]).toMatchObject({
label: 'Pulse Pro runtime',
statusLabel: 'Needs attention',
state: 'missing',
@@ -510,11 +753,79 @@ describe('licensePresentation', () => {
upgrade_reasons: [],
runtime: { build: 'pro', label: 'Pulse Pro runtime' },
},
- displayableCapabilities: ['Pulse Relay (Remote Access)', 'Safe Remediation Workflows'],
+ displayableCapabilities: ['Pulse Relay (Remote Access)', 'Patrol Handles Safe Fixes'],
}).body,
).toBe(getSelfHostedPlanEntitlementSummary('pro', 'Legacy Pulse Pro+'));
});
+ it('keeps the Patrol mode entry point on active Pro current-plan summaries', () => {
+ const patrolControlAction = {
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ };
+
+ expect(
+ getSelfHostedCurrentPlanPresentation({
+ entitlements: {
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: ['relay', 'ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ },
+ displayableCapabilities: ['Pulse Relay (Remote Access)', 'Patrol Handles Safe Fixes'],
+ }).patrolControlAction,
+ ).toEqual(patrolControlAction);
+
+ expect(
+ getSelfHostedCurrentPlanPresentation({
+ entitlements: {
+ tier: 'pro',
+ subscription_state: 'trial',
+ capabilities: ['ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ },
+ displayableCapabilities: ['Patrol Handles Safe Fixes'],
+ }).patrolControlAction,
+ ).toEqual(patrolControlAction);
+
+ expect(
+ getSelfHostedCurrentPlanPresentation({
+ entitlements: {
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: ['ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ runtime: { build: 'community', label: 'Pulse Community runtime' },
+ },
+ displayableCapabilities: ['Patrol Handles Safe Fixes'],
+ }).patrolControlAction,
+ ).toBeUndefined();
+
+ expect(
+ getSelfHostedCurrentPlanPresentation({
+ entitlements: {
+ tier: 'relay',
+ subscription_state: 'active',
+ capabilities: ['relay', 'mobile_app', 'push_notifications', 'ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ },
+ displayableCapabilities: [
+ 'Pulse Relay (Remote Access)',
+ 'Pulse Mobile Pairing',
+ 'Push Notifications',
+ 'Patrol Handles Safe Fixes',
+ ],
+ }).patrolControlAction,
+ ).toBeUndefined();
+ });
+
it('builds restrained higher-tier comparison cards for Community and Relay only', () => {
expect(
getSelfHostedPlanComparisonPresentation({
@@ -529,26 +840,28 @@ describe('licensePresentation', () => {
).toEqual({
cards: [
{
- title: 'What Relay adds',
- body: 'Reach your Pulse web UI securely from anywhere, pair supported Pulse Mobile clients for handoff and push notifications, and keep 14 days of history.',
+ title: 'Relay plan',
+ body: 'Remote web access, Pulse Mobile pairing, push notifications, and 14-day metric history.',
highlights: [
- 'Pulse Relay (Remote Access)',
- 'Pulse Mobile Pairing',
- 'Push Notifications',
+ 'Everything in Community',
+ 'Remote web access via Relay',
+ 'Pulse Mobile pairing',
+ 'Push notifications',
+ 'No inbound ports required',
'14-day metric history',
],
},
{
- title: 'What Pulse Pro adds',
- body: 'Add operations features on top of free monitoring: root-cause analysis, safe remediation workflows, 90-day history, RBAC, audit logging, reporting, and agent profiles.',
+ title: 'Pulse Pro plan',
+ body: 'Patrol modes, 90-day metric history, RBAC, audit logs, reports, and agent profiles.',
highlights: [
- 'Alert Root-Cause Analysis',
- 'Safe Remediation Workflows',
+ 'Everything in Relay',
+ 'Choose Patrol mode',
+ 'Patrol investigates issues',
+ 'Patrol handles safe fixes',
'90-day metric history',
- 'Role-Based Access Control (RBAC)',
- 'Audit Logging',
- 'PDF/CSV Reporting',
- 'Centralized Agent Profiles',
+ 'RBAC and audit logging',
+ 'Agent profiles · PDF/CSV reports',
],
},
],
@@ -567,16 +880,16 @@ describe('licensePresentation', () => {
).toEqual({
cards: [
{
- title: 'What Pulse Pro adds',
- body: 'Add operations features on top of free monitoring: root-cause analysis, safe remediation workflows, 90-day history, RBAC, audit logging, reporting, and agent profiles.',
+ title: 'Pulse Pro plan',
+ body: 'Patrol modes, 90-day metric history, RBAC, audit logs, reports, and agent profiles.',
highlights: [
- 'Alert Root-Cause Analysis',
- 'Safe Remediation Workflows',
+ 'Everything in Relay',
+ 'Choose Patrol mode',
+ 'Patrol investigates issues',
+ 'Patrol handles safe fixes',
'90-day metric history',
- 'Role-Based Access Control (RBAC)',
- 'Audit Logging',
- 'PDF/CSV Reporting',
- 'Centralized Agent Profiles',
+ 'RBAC and audit logging',
+ 'Agent profiles · PDF/CSV reports',
],
},
],
@@ -595,9 +908,9 @@ describe('licensePresentation', () => {
).toEqual({ cards: [] });
});
- it('builds entitlement-derived value proof for active Relay and Pro installs', () => {
+ it('builds entitlement-derived status for active Relay and Pro installs', () => {
expect(
- getSelfHostedActivationProofPresentation({
+ getSelfHostedPlanStatusPresentation({
tier: 'relay',
subscription_state: 'active',
capabilities: ['relay', 'mobile_app', 'push_notifications', 'long_term_metrics'],
@@ -606,27 +919,27 @@ describe('licensePresentation', () => {
max_history_days: 14,
}),
).toEqual({
- title: 'Relay value proof',
- body: "These checks come from this instance's entitlement and runtime payloads, not from public pricing copy.",
+ title: 'Relay status',
+ body: 'These checks show the capabilities this instance can use right now, based on its entitlement and runtime payloads.',
items: [
{
label: 'Remote access, pairing, and push',
statusLabel: 'Active',
state: 'active',
detail:
- 'Relay, Pulse Mobile pairing, and push notification capabilities are present in this entitlement payload.',
+ 'Relay, Pulse Mobile pairing, and push notifications are available on this instance.',
},
{
label: '14-day metric history',
statusLabel: 'Active',
state: 'active',
- detail: 'This instance reports 14 days of metric history in its entitlement payload.',
+ detail: 'This instance has 14 days of metric history available.',
},
],
});
expect(
- getSelfHostedActivationProofPresentation({
+ getSelfHostedPlanStatusPresentation({
tier: 'pro',
subscription_state: 'active',
capabilities: [
@@ -648,36 +961,53 @@ describe('licensePresentation', () => {
runtime: { build: 'pro', label: 'Pulse Pro runtime' },
}),
).toMatchObject({
- title: 'Pulse Pro value proof',
+ title: 'Capability details',
+ body: 'Open this only when a Pro capability looks unavailable. Normal setup is choosing Patrol mode.',
items: [
{ label: 'Pulse Pro runtime', statusLabel: 'Active' },
{ label: 'Remote access, pairing, and push', statusLabel: 'Active' },
{ label: '90-day metric history', statusLabel: 'Active' },
- { label: 'Root-cause analysis and remediation', statusLabel: 'Active' },
+ { label: 'Patrol investigation and remediation', statusLabel: 'Active' },
{ label: 'Team and admin controls', statusLabel: 'Active' },
],
});
- expect(
- getSelfHostedActivationProofPresentation({
- tier: 'pro',
- subscription_state: 'active',
- capabilities: ['relay', 'ai_autofix'],
- limits: [],
- upgrade_reasons: [],
- max_history_days: 14,
- runtime: { build: 'pro', label: 'Pulse Pro runtime' },
- })?.items.map((item) => [item.label, item.statusLabel]),
- ).toEqual([
+ const partialProStatus = getSelfHostedPlanStatusPresentation({
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: ['relay', 'ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ max_history_days: 14,
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ });
+ expect(partialProStatus?.items.map((item) => [item.label, item.statusLabel])).toEqual([
['Pulse Pro runtime', 'Active'],
['Remote access, pairing, and push', 'Partial'],
['90-day metric history', 'Partial'],
- ['Root-cause analysis and remediation', 'Partial'],
+ ['Patrol investigation and remediation', 'Partial'],
['Team and admin controls', 'Needs attention'],
]);
+ expect(partialProStatus?.items).toContainEqual({
+ label: 'Patrol investigation and remediation',
+ state: 'partial',
+ statusLabel: 'Partial',
+ detail:
+ 'Some Patrol capability is available, but investigation or remediation may not be fully enabled yet.',
+ });
+ expect(partialProStatus?.items).toContainEqual({
+ label: 'Team and admin controls',
+ state: 'missing',
+ statusLabel: 'Needs attention',
+ detail:
+ 'Team/admin controls are not available yet. Refresh the plan or open recovery before relying on this Pro install.',
+ });
+ expect(partialProStatus?.items.map((item) => item.detail).join(' ')).not.toContain(
+ 'admin tools',
+ );
expect(
- getSelfHostedActivationProofPresentation({
+ getSelfHostedPlanStatusPresentation({
tier: 'free',
subscription_state: 'expired',
capabilities: [],
@@ -687,6 +1017,160 @@ describe('licensePresentation', () => {
).toBeNull();
});
+ it('keeps Patrol work state out of plan capability details', () => {
+ const proEntitlements = {
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: [
+ 'relay',
+ 'mobile_app',
+ 'push_notifications',
+ 'ai_alerts',
+ 'ai_autofix',
+ 'rbac',
+ 'audit_logging',
+ 'advanced_reporting',
+ 'agent_profiles',
+ ],
+ limits: [],
+ upgrade_reasons: [],
+ max_history_days: 90,
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ };
+
+ const expectedCapabilityItems = [
+ ['Pulse Pro runtime', 'Active'],
+ ['Remote access, pairing, and push', 'Active'],
+ ['90-day metric history', 'Active'],
+ ['Patrol investigation and remediation', 'Active'],
+ ['Team and admin controls', 'Active'],
+ ];
+ const expectOnlyCapabilityItems = (
+ status?: ReturnType<typeof getSelfHostedPlanStatusPresentation>,
+ ) => {
+ expect(status?.title).toBe('Capability details');
+ expect(status?.items.map((item) => [item.label, item.statusLabel])).toEqual(
+ expectedCapabilityItems,
+ );
+ expect(status?.items.some((item) => item.label === 'Patrol work')).toBe(false);
+ };
+
+ expect(
+ getSelfHostedPlanStatusPresentation(proEntitlements)?.items.some(
+ (item) => item.label === 'Patrol work',
+ ),
+ ).toBe(false);
+
+ expectOnlyCapabilityItems(getSelfHostedPlanStatusPresentation(proEntitlements));
+
+ expectOnlyCapabilityItems(
+ getSelfHostedPlanStatusPresentation(proEntitlements, {
+ patrolControlOperationsLoopStarterCount: 1,
+ patrolControlCompletedOperationsLoopCount: 1,
+ patrolControlResolvedOperationsLoopCount: 1,
+ patrolControlValueState: 'verified',
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 1,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ patrolAutonomyValueState: 'governed_decision_recorded',
+ externalAgentReady: true,
+ }),
+ );
+
+ expectOnlyCapabilityItems(
+ getSelfHostedPlanStatusPresentation(proEntitlements, {
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 1,
+ patrolAutonomyResolvedOperationsLoopCount: 1,
+ patrolAutonomyValueState: 'verified',
+ externalAgentReady: true,
+ }),
+ );
+
+ expectOnlyCapabilityItems(
+ getSelfHostedPlanStatusPresentation(proEntitlements, {
+ nextAction: 'complete',
+ progressLabel:
+ 'Patrol recorded a rejected change decision. Nothing was changed; approve a safer fix before marking the issue resolved.',
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 1,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ patrolAutonomyValueState: 'governed_decision_recorded',
+ externalAgentReady: true,
+ }),
+ );
+
+ expectOnlyCapabilityItems(
+ getSelfHostedPlanStatusPresentation(proEntitlements, {
+ nextAction: 'complete',
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 1,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ patrolAutonomyValueState: 'governed_decision_recorded',
+ externalAgentReady: false,
+ }),
+ );
+
+ expectOnlyCapabilityItems(
+ getSelfHostedPlanStatusPresentation(proEntitlements, {
+ nextAction: 'open_mcp',
+ progressLabel: 'Legacy status asked for MCP readiness after the outcome was verified.',
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 0,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ patrolAutonomyValueState: 'verified_needs_mcp',
+ externalAgentReady: false,
+ }),
+ );
+
+ expectOnlyCapabilityItems(
+ getSelfHostedPlanStatusPresentation(proEntitlements, {
+ patrolAutonomyOperationsLoopStarterCount: 2,
+ patrolAutonomyCompletedOperationsLoopCount: 0,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ progressLabel: 'Investigation ready',
+ externalAgentReady: false,
+ }),
+ );
+
+ expectOnlyCapabilityItems(
+ getSelfHostedPlanStatusPresentation(proEntitlements, {
+ proActivationOperationsLoopStarterCount: 1,
+ proActivationCompletedOperationsLoopCount: 0,
+ proActivationResolvedOperationsLoopCount: 0,
+ proActivationValueProofState: 'in_progress',
+ externalAgentReady: false,
+ }),
+ );
+
+ expectOnlyCapabilityItems(
+ getSelfHostedPlanStatusPresentation(proEntitlements, {
+ patrolControlOperationsLoopStarterCount: 1,
+ proActivationOperationsLoopStarterCount: 1,
+ progressLabel: 'Legacy activation entry recorded',
+ externalAgentReady: false,
+ }),
+ );
+
+ expectOnlyCapabilityItems(
+ getSelfHostedPlanStatusPresentation(proEntitlements, {
+ patrolControlOperationsLoopStarterCount: 2,
+ proActivationOperationsLoopStarterCount: 1,
+ progressLabel: 'Patrol mode started',
+ externalAgentReady: false,
+ }),
+ );
+
+ expectOnlyCapabilityItems(
+ getSelfHostedPlanStatusPresentation(proEntitlements, {
+ patrolAutonomyOperationsLoopStarterCount: 0,
+ patrolAutonomyCompletedOperationsLoopCount: 0,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ externalAgentReady: false,
+ }),
+ );
+ });
+
it('builds activation-success summaries for purchase and pasted-key paths', () => {
expect(
getSelfHostedActivationSuccessPresentation({
@@ -702,24 +1186,27 @@ describe('licensePresentation', () => {
'Pulse Relay (Remote Access)',
'Pulse Mobile Pairing',
'Push Notifications',
- 'Safe Remediation Workflows',
+ 'Patrol Handles Safe Fixes',
],
source: 'purchase',
}),
).toEqual({
tone: 'border-green-200 dark:border-green-900 bg-green-50 dark:bg-green-900 text-green-900 dark:text-green-100',
title: 'Pulse Pro is now active',
- body: 'Checkout completed and this instance is now running Pulse Pro.',
+ body: 'Checkout completed and Pulse Pro is active. Choose Patrol mode.',
highlightsLabel: 'Available now on this instance',
highlights: [
- 'Alert Root-Cause Analysis',
- 'Safe Remediation Workflows',
+ 'Patrol Investigates Issues',
+ 'Patrol Handles Safe Fixes',
'90-day metric history',
'Role-Based Access Control (RBAC)',
'Audit Logging',
'PDF/CSV Reporting',
'Centralized Agent Profiles',
],
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
});
expect(
@@ -741,7 +1228,7 @@ describe('licensePresentation', () => {
).toEqual({
tone: 'border-green-200 dark:border-green-900 bg-green-50 dark:bg-green-900 text-green-900 dark:text-green-100',
title: 'Relay is now active',
- body: 'The activation key was accepted and this instance is now running Relay.',
+ body: 'The license key was accepted and this instance is now running Relay.',
highlightsLabel: 'Available now on this instance',
highlights: [
'Pulse Relay (Remote Access)',
@@ -760,7 +1247,7 @@ describe('licensePresentation', () => {
limits: [],
upgrade_reasons: [],
},
- displayableCapabilities: ['Pulse Patrol', 'Safe Remediation Workflows'],
+ displayableCapabilities: ['Pulse Patrol', 'Patrol Handles Safe Fixes'],
source: 'purchase',
}),
).toBeNull();
@@ -780,6 +1267,130 @@ describe('licensePresentation', () => {
).toBeNull();
});
+ it('keeps activation-success actions aligned with actionable Patrol states', () => {
+ const proEntitlements = {
+ tier: 'pro',
+ subscription_state: 'active',
+ capabilities: ['relay', 'mobile_app', 'push_notifications', 'ai_autofix'],
+ limits: [],
+ upgrade_reasons: [],
+ runtime: { build: 'pro', label: 'Pulse Pro runtime' },
+ };
+
+ expect(
+ getSelfHostedActivationSuccessPresentation({
+ entitlements: proEntitlements,
+ displayableCapabilities: ['Patrol Handles Safe Fixes'],
+ patrolOperatorStatus: {
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 0,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ externalAgentReady: false,
+ },
+ source: 'manual',
+ }),
+ ).toMatchObject({
+ actionLabel: 'Open Patrol',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ });
+
+ expect(
+ getSelfHostedActivationSuccessPresentation({
+ entitlements: proEntitlements,
+ displayableCapabilities: ['Patrol Handles Safe Fixes'],
+ patrolOperatorStatus: {
+ proActivationOperationsLoopStarterCount: 1,
+ proActivationCompletedOperationsLoopCount: 0,
+ proActivationResolvedOperationsLoopCount: 0,
+ proActivationValueProofState: 'in_progress',
+ externalAgentReady: false,
+ },
+ source: 'manual',
+ }),
+ ).toMatchObject({
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ });
+
+ expect(
+ getSelfHostedActivationSuccessPresentation({
+ entitlements: proEntitlements,
+ displayableCapabilities: ['Patrol Handles Safe Fixes'],
+ patrolOperatorStatus: {
+ patrolControlOperationsLoopStarterCount: 1,
+ proActivationOperationsLoopStarterCount: 1,
+ externalAgentReady: false,
+ },
+ source: 'manual',
+ }),
+ ).toMatchObject({
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ });
+
+ expect(
+ getSelfHostedActivationSuccessPresentation({
+ entitlements: proEntitlements,
+ displayableCapabilities: ['Patrol Handles Safe Fixes'],
+ patrolOperatorStatus: {
+ nextAction: 'open_mcp',
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 0,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ patrolAutonomyValueState: 'verified_needs_mcp',
+ externalAgentReady: false,
+ },
+ source: 'manual',
+ }),
+ ).toMatchObject({
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ });
+
+ expect(
+ getSelfHostedActivationSuccessPresentation({
+ entitlements: proEntitlements,
+ displayableCapabilities: ['Patrol Handles Safe Fixes'],
+ patrolOperatorStatus: {
+ nextAction: 'complete',
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 1,
+ patrolAutonomyResolvedOperationsLoopCount: 0,
+ patrolAutonomyValueState: 'governed_decision_recorded',
+ externalAgentReady: true,
+ },
+ source: 'manual',
+ }),
+ ).toMatchObject({
+ actionLabel: 'Review Patrol decision',
+ actionUrl: PATROL_CONTROL_PATH,
+ actionIntent: 'patrol_control',
+ });
+
+ expect(
+ getSelfHostedActivationSuccessPresentation({
+ entitlements: proEntitlements,
+ displayableCapabilities: ['Patrol Handles Safe Fixes'],
+ patrolOperatorStatus: {
+ patrolAutonomyOperationsLoopStarterCount: 1,
+ patrolAutonomyCompletedOperationsLoopCount: 1,
+ patrolAutonomyResolvedOperationsLoopCount: 1,
+ patrolAutonomyValueState: 'verified',
+ externalAgentReady: true,
+ },
+ source: 'manual',
+ }),
+ ).toMatchObject({
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+ });
+ });
+
it('returns canonical purchase activation notices', () => {
expect(getPurchaseActivationNotice('activated')).toMatchObject({
title: 'Plan activated',
@@ -795,7 +1406,7 @@ describe('licensePresentation', () => {
body: expect.stringContaining('Start the upgrade again'),
});
expect(getPurchaseActivationNotice('failed')).toMatchObject({
- title: 'Activation needs attention',
+ title: 'Plan needs attention',
body: expect.stringContaining('open recovery'),
tone: expect.stringContaining('red'),
});
diff --git a/frontend-modern/src/utils/__tests__/patrolEmptyStatePresentation.test.ts b/frontend-modern/src/utils/__tests__/patrolEmptyStatePresentation.test.ts
index 69db702b98..21ad1cf9ad 100644
--- a/frontend-modern/src/utils/__tests__/patrolEmptyStatePresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/patrolEmptyStatePresentation.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it } from 'vitest';
import runHistoryPanelSource from '@/components/patrol/RunHistoryPanel.tsx?raw';
+import patrolEmptyStatePresentationSource from '@/utils/patrolEmptyStatePresentation.ts?raw';
+import type { PatrolRunRecord } from '@/api/patrol';
import {
getInvestigationMessagesState,
getInvestigationSectionState,
@@ -34,11 +36,16 @@ describe('patrolEmptyStatePresentation', () => {
empty: false,
});
expect(getInvestigationSectionState(false, false)).toEqual({
- text: 'No investigation data available. Enable patrol autonomy to investigate findings.',
+ text: 'No investigation yet. Patrol adds notes after it runs in a mode that investigates.',
empty: true,
});
});
+ it('keeps the active Patrol empty queue out of all-clear wording', () => {
+ expect(patrolEmptyStatePresentationSource).not.toContain('Nothing needs attention');
+ expect(patrolEmptyStatePresentationSource).not.toContain('all clear');
+ });
+
it('suppresses the healthy findings empty state when patrol health is not fully verified', () => {
expect(
getPatrolFindingsEmptyState({
@@ -52,18 +59,42 @@ describe('patrolEmptyStatePresentation', () => {
name: 'Patrol coverage incomplete',
impact: -0.35,
description:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
category: 'coverage',
},
],
prediction:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
},
runtimeState: 'active',
}),
).toEqual({
- title: 'No active findings',
- body: 'Patrol has not surfaced active findings, but coverage is incomplete, so this is not a full all-clear.',
+ title: 'Check needed',
+ body: 'Run Patrol to check everything and update open issues.',
+ tone: 'warning',
+ });
+ });
+
+ it('uses run history to keep incomplete coverage visible when health summary is unavailable', () => {
+ expect(
+ getPatrolFindingsEmptyState({
+ filter: 'active',
+ runtimeState: 'active',
+ runs: [
+ {
+ id: 'run-errored-full',
+ started_at: '2026-05-06T12:00:00Z',
+ completed_at: '2026-05-06T12:01:00Z',
+ type: 'full',
+ status: 'error',
+ error_count: 1,
+ resources_checked: 72,
+ } as PatrolRunRecord,
+ ],
+ }),
+ ).toEqual({
+ title: 'Check needed',
+ body: 'Run Patrol to check everything and update open issues.',
tone: 'warning',
});
});
@@ -89,8 +120,8 @@ describe('patrolEmptyStatePresentation', () => {
runtimeState: 'active',
}),
).toEqual({
- title: 'No active findings',
- body: 'Patrol has not surfaced active findings, but the overall Patrol assessment still needs attention.',
+ title: 'Patrol needs review',
+ body: 'No active findings are listed, but Patrol health is degraded.',
tone: 'error',
});
});
@@ -110,6 +141,26 @@ describe('patrolEmptyStatePresentation', () => {
});
});
+ it('treats a running Patrol as active work instead of an empty state', () => {
+ expect(
+ getPatrolFindingsEmptyState({
+ filter: 'active',
+ runtimeState: 'running',
+ overallHealth: {
+ score: 100,
+ grade: 'A',
+ trend: 'stable',
+ factors: [],
+ prediction: 'Infrastructure is healthy with no significant issues detected.',
+ },
+ }),
+ ).toEqual({
+ title: 'Patrol is checking now',
+ body: 'The current run will add work here if Patrol finds issues or needs approval.',
+ tone: 'info',
+ });
+ });
+
it('keeps the healthy findings empty state when patrol health is fully healthy', () => {
expect(
getPatrolFindingsEmptyState({
@@ -124,12 +175,33 @@ describe('patrolEmptyStatePresentation', () => {
runtimeState: 'active',
}),
).toEqual({
- title: 'No active findings',
- body: 'Your infrastructure looks healthy!',
+ title: 'No current issues',
+ body: 'Run Patrol any time to check again.',
tone: 'success',
});
});
+ it('keeps past regressions informational when there are no current issues', () => {
+ expect(
+ getPatrolFindingsEmptyState({
+ filter: 'active',
+ overallHealth: {
+ score: 100,
+ grade: 'A',
+ trend: 'stable',
+ factors: [],
+ prediction: 'Infrastructure is healthy with no significant issues detected.',
+ },
+ historicalRegressionCount: 1,
+ runtimeState: 'active',
+ }),
+ ).toEqual({
+ title: 'No current issues',
+ body: 'Past issues are in History.',
+ tone: 'info',
+ });
+ });
+
it('describes a selected run snapshot with no recorded findings using coverage-aware copy', () => {
expect(
getPatrolFindingsEmptyState({
@@ -145,7 +217,7 @@ describe('patrolEmptyStatePresentation', () => {
}),
).toEqual({
title: 'No findings recorded for this run',
- body: 'Checked 1 of 2 scoped resources. This run recorded no snapshot findings, but it ended with issues requiring review.',
+ body: 'Checked 1 of 2 scoped resources. This run recorded no Patrol findings, but it ended with issues requiring review.',
tone: 'warning',
});
});
@@ -164,8 +236,8 @@ describe('patrolEmptyStatePresentation', () => {
},
}),
).toEqual({
- title: 'Findings snapshot unavailable for this run',
- body: 'This Patrol run predates findings snapshots, so run-specific findings cannot be verified.',
+ title: 'Finding record unavailable for this run',
+ body: 'This older Patrol run has no finding record, so Patrol cannot show its issue list.',
tone: 'warning',
});
});
diff --git a/frontend-modern/src/utils/__tests__/patrolFormat.test.ts b/frontend-modern/src/utils/__tests__/patrolFormat.test.ts
index 05764abd66..434ec9bf1b 100644
--- a/frontend-modern/src/utils/__tests__/patrolFormat.test.ts
+++ b/frontend-modern/src/utils/__tests__/patrolFormat.test.ts
@@ -209,6 +209,18 @@ describe('patrolFormat', () => {
expect(summary).not.toContain('No endpoints found');
});
+ it('drops generic provider connection prefixes when the detail is already actionable', () => {
+ const summary = formatPatrolRuntimeFailureSummary({
+ errorSummary: 'Provider connection issue',
+ errorDetail: 'context deadline exceeded while reaching provider',
+ errorCount: 1,
+ });
+
+ expect(summary).toBe(
+ 'Provider connection failed. Check provider reachability before retrying Patrol.',
+ );
+ });
+
it('redacts unknown provider details defensively', () => {
const detail = formatPatrolRuntimeFailureDetail(
'provider returned Authorization: Bearer sk-live-secret and url https://example.invalid/path?token=abc for user_abc123',
diff --git a/frontend-modern/src/utils/__tests__/patrolPagePresentation.test.ts b/frontend-modern/src/utils/__tests__/patrolPagePresentation.test.ts
index 6731b8dc43..f5eb6650ef 100644
--- a/frontend-modern/src/utils/__tests__/patrolPagePresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/patrolPagePresentation.test.ts
@@ -1,30 +1,61 @@
import { describe, expect, it } from 'vitest';
import {
PATROL_PAGE_DESCRIPTION,
+ PATROL_PAGE_MONITOR_DESCRIPTION,
PATROL_PAGE_TITLE,
PATROL_PAGE_TITLE_TOOLTIP,
+ PATROL_PAGE_WATCH_ONLY_DESCRIPTION,
getPatrolPageHeaderMeta,
} from '@/utils/patrolPagePresentation';
describe('patrolPagePresentation', () => {
- it('returns canonical Patrol page header metadata that names the proactive trust loop', () => {
+ it('returns canonical Patrol page header metadata in simple operator language', () => {
// The page header is the most visible piece of operator-facing copy on
- // the Patrol surface. It must keep the product boundary clear: Pulse
- // probes and assembles evidence, the configured model reasons over it,
- // and action stays approval-bound.
+ // the Patrol surface. It must name the product boundary without making
+ // users learn the full operations-loop model.
expect(PATROL_PAGE_TITLE).toBe('Patrol');
expect(PATROL_PAGE_DESCRIPTION).toBe(
- 'Pulse checks your infrastructure on a schedule, gives your configured model the right evidence, and keeps fixes behind your approval policy.',
+ 'Patrol watches, investigates, acts within your chosen mode, verifies outcomes, and records what happened.',
);
- // Tooltip must share the same framing so hover and inline don't tell
- // different stories about what Patrol does.
expect(PATROL_PAGE_TITLE_TOOLTIP).toBe(PATROL_PAGE_DESCRIPTION);
expect(getPatrolPageHeaderMeta()).toEqual({
title: 'Patrol',
description:
- 'Pulse checks your infrastructure on a schedule, gives your configured model the right evidence, and keeps fixes behind your approval policy.',
+ 'Patrol watches, investigates, acts within your chosen mode, verifies outcomes, and records what happened.',
titleTooltip:
- 'Pulse checks your infrastructure on a schedule, gives your configured model the right evidence, and keeps fixes behind your approval policy.',
+ 'Patrol watches, investigates, acts within your chosen mode, verifies outcomes, and records what happened.',
+ });
+ });
+
+ it('separates locked watch-only capability from Pro Watch only mode', () => {
+ expect(PATROL_PAGE_WATCH_ONLY_DESCRIPTION).toBe(
+ 'Patrol watches infrastructure and shows current issues.',
+ );
+ expect(PATROL_PAGE_MONITOR_DESCRIPTION).toBe(
+ 'Watch only: Patrol reports issues without making changes.',
+ );
+ expect(getPatrolPageHeaderMeta({ autonomyLocked: true })).toEqual({
+ title: 'Patrol',
+ description: PATROL_PAGE_WATCH_ONLY_DESCRIPTION,
+ titleTooltip: PATROL_PAGE_WATCH_ONLY_DESCRIPTION,
+ });
+ expect(getPatrolPageHeaderMeta({ autonomyLevel: 'monitor' })).toEqual({
+ title: 'Patrol',
+ description: PATROL_PAGE_MONITOR_DESCRIPTION,
+ titleTooltip: PATROL_PAGE_MONITOR_DESCRIPTION,
+ });
+ });
+
+ it('describes each governed Patrol mode level by what it can actually do', () => {
+ expect(getPatrolPageHeaderMeta({ autonomyLevel: 'approval' })).toMatchObject({
+ description: 'Patrol investigates issues and asks before every change.',
+ });
+ expect(getPatrolPageHeaderMeta({ autonomyLevel: 'assisted' })).toMatchObject({
+ description: 'Patrol handles safe policy-allowed fixes and asks before anything riskier.',
+ });
+ expect(getPatrolPageHeaderMeta({ autonomyLevel: 'full' })).toMatchObject({
+ description:
+ 'Patrol handles policy-approved work automatically and asks only when approval is required.',
});
});
});
diff --git a/frontend-modern/src/utils/__tests__/patrolRunPresentation.test.ts b/frontend-modern/src/utils/__tests__/patrolRunPresentation.test.ts
index c9814c733e..b7f3c6b203 100644
--- a/frontend-modern/src/utils/__tests__/patrolRunPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/patrolRunPresentation.test.ts
@@ -4,6 +4,8 @@ import {
formatPatrolActivityBreakdown,
getPatrolActivityBreakdown,
getPatrolLatestRunPresentation,
+ getPatrolRunOperatorRecordPresentation,
+ getPatrolRunRecordSummaryPresentation,
getPatrolRunKindLabel,
getPatrolRunCoverageSummary,
getPatrolRunPrimaryActionPresentation,
@@ -56,7 +58,7 @@ describe('patrolRunPresentation', () => {
expect(getPatrolRunStatusPresentation('healthy').variant).toBe('success');
});
- it('downgrades legacy healthy runs without findings snapshots to a neutral completed state', () => {
+ it('downgrades legacy healthy runs without finding records to a neutral completed state', () => {
expect(getPatrolRunStatusPresentation('healthy', 0, false)).toEqual({
badgeClass: 'bg-surface-alt text-base-content',
variant: 'muted',
@@ -86,8 +88,8 @@ describe('patrolRunPresentation', () => {
error_detail: 'Provider rejected tool_choice',
}),
).toEqual({
- label: 'Open Patrol provider settings',
- href: '/settings/system-ai',
+ label: 'Open Provider & Models',
+ href: '/settings/pulse-intelligence/provider',
});
expect(
getPatrolRunPrimaryActionPresentation({
@@ -105,6 +107,121 @@ describe('patrolRunPresentation', () => {
).toBeUndefined();
});
+ it('summarizes selected Patrol run records without requiring users to expand history internals', () => {
+ expect(
+ getPatrolRunRecordSummaryPresentation({
+ auto_fix_count: 0,
+ duration_ms: 3_480_000,
+ effective_scope_resource_ids: [],
+ error_count: 1,
+ error_detail:
+ "agentic patrol failed: API error (404): No endpoints found that support the provided 'tool_choice' value.",
+ error_summary: 'Selected model does not support Patrol tools',
+ existing_findings: 0,
+ finding_ids: ['runtime-provider'],
+ new_findings: 0,
+ resources_checked: 72,
+ scope_resource_ids: [],
+ status: 'error',
+ }),
+ ).toEqual({
+ action: {
+ label: 'Open Provider & Models',
+ href: '/settings/pulse-intelligence/provider',
+ },
+ summary: 'Checked 72 resources in 58m.',
+ outcome:
+ 'Patrol ended with a runtime issue: Selected model does not support Patrol tools: Provider rejected Patrol tool calls. Choose a Patrol model and endpoint with tool-call support.',
+ });
+
+ expect(
+ getPatrolRunRecordSummaryPresentation({
+ auto_fix_count: 0,
+ duration_ms: 60_000,
+ effective_scope_resource_ids: ['expanded-a', 'expanded-b'],
+ error_count: 0,
+ error_detail: '',
+ error_summary: '',
+ existing_findings: 0,
+ finding_ids: [],
+ new_findings: 0,
+ resources_checked: 2,
+ scope_resource_ids: ['seed-resource'],
+ status: 'healthy',
+ }),
+ ).toEqual({
+ summary: 'Checked 2 scoped resources in 1m.',
+ outcome: 'No issues recorded for this run.',
+ });
+ });
+
+ it('summarizes run history as operator actions before telemetry details', () => {
+ expect(
+ getPatrolRunOperatorRecordPresentation({
+ auto_fix_count: 1,
+ duration_ms: 60_000,
+ effective_scope_resource_ids: [],
+ error_count: 0,
+ error_detail: '',
+ error_summary: '',
+ existing_findings: 0,
+ finding_ids: ['finding-1', 'finding-2'],
+ new_findings: 2,
+ resources_checked: 72,
+ resolved_findings: 0,
+ scope_resource_ids: [],
+ status: 'healthy',
+ }),
+ ).toEqual({
+ headline: 'Fixed 1 issue',
+ detail: 'Checked 72 resources in 1m. Found 2 new issues and fixed 1 issue.',
+ });
+
+ expect(
+ getPatrolRunOperatorRecordPresentation({
+ auto_fix_count: 0,
+ duration_ms: 453,
+ effective_scope_resource_ids: ['vm-1', 'vm-2'],
+ error_count: 1,
+ error_detail:
+ "agentic patrol failed: API error (404): No endpoints found that support the provided 'tool_choice' value.",
+ error_summary: 'Selected model does not support Patrol tools',
+ existing_findings: 0,
+ finding_ids: ['runtime-provider'],
+ new_findings: 0,
+ resources_checked: 1,
+ resolved_findings: 0,
+ scope_resource_ids: ['vm-1'],
+ status: 'error',
+ }),
+ ).toEqual({
+ headline: 'Patrol needs attention',
+ detail:
+ 'Checked 1 of 2 scoped resources in 453ms. Runtime issue: Selected model does not support Patrol tools: Provider rejected Patrol tool calls. Choose a Patrol model and endpoint with tool-call support.',
+ });
+
+ expect(
+ getPatrolRunOperatorRecordPresentation({
+ auto_fix_count: 0,
+ duration_ms: 60_000,
+ effective_scope_resource_ids: [],
+ error_count: 0,
+ error_detail: '',
+ error_summary: '',
+ existing_findings: 0,
+ finding_ids: [],
+ new_findings: 0,
+ resources_checked: 72,
+ resolved_findings: 0,
+ scope_resource_ids: [],
+ status: 'healthy',
+ }),
+ ).toEqual({
+ headline: 'All clear',
+ detail: 'Checked 72 resources in 1m. No issues recorded.',
+ });
+ });
+
it('normalizes unknown status labels safely', () => {
const presentation = getPatrolRunStatusPresentation(' Needs Review ');
expect(presentation.label).toBe('needs review');
@@ -120,10 +237,10 @@ describe('patrolRunPresentation', () => {
});
it('returns canonical patrol run kind labels', () => {
- expect(getPatrolRunKindLabel('scoped')).toBe('Scoped run');
- expect(getPatrolRunKindLabel('verification')).toBe('Verification check');
- expect(getPatrolRunKindLabel('patrol')).toBe('Full patrol');
- expect(getPatrolRunKindLabel('')).toBe('Full patrol');
+ expect(getPatrolRunKindLabel('scoped')).toBe('Targeted check');
+ expect(getPatrolRunKindLabel('verification')).toBe('Follow-up check');
+ expect(getPatrolRunKindLabel('patrol')).toBe('Patrol check');
+ expect(getPatrolRunKindLabel('')).toBe('Patrol check');
expect(getPatrolRunKindLabel('unexpected')).toBe('Patrol run');
});
@@ -165,7 +282,7 @@ describe('patrolRunPresentation', () => {
).toEqual({
coverageSummary: 'Checked 1 of 2 scoped resources',
findingsSnapshotAvailable: false,
- kindLabel: 'Scoped run',
+ kindLabel: 'Targeted check',
status: {
badgeClass: 'bg-red-100 text-red-700 dark:bg-red-900 dark:text-red-300',
variant: 'danger',
@@ -189,7 +306,7 @@ describe('patrolRunPresentation', () => {
).toBe('4 queued · busy mode · anomalies off');
});
- it('surfaces runtime-blocked event triggers before compact trigger details', () => {
+ it('hides non-actionable runtime-blocked event triggers unless Patrol is already running', () => {
expect(
getPatrolTriggerStatusSummary({
running: true,
@@ -204,8 +321,52 @@ describe('patrolRunPresentation', () => {
event_triggers_blocked_message:
'Automatic Patrol checks from alerts and anomalies are paused by the local development safety guard. Manual Patrol still works.',
}),
+ ).toBeUndefined();
+
+ expect(
+ getPatrolTriggerStatusSummary(
+ {
+ running: true,
+ pending_triggers: 4,
+ current_interval_ms: 300000,
+ recent_events: 6,
+ is_busy_mode: true,
+ alert_triggers_enabled: true,
+ anomaly_triggers_enabled: true,
+ 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.',
+ },
+ {
+ manualRunAvailable: false,
+ manualRunBlockedReason: 'Provider connection issue (last preflight 49m ago).',
+ },
+ ),
+ ).toBeUndefined();
+
+ expect(
+ getPatrolTriggerStatusSummary(
+ {
+ running: true,
+ pending_triggers: 0,
+ current_interval_ms: 300000,
+ recent_events: 0,
+ is_busy_mode: false,
+ alert_triggers_enabled: true,
+ anomaly_triggers_enabled: true,
+ 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.',
+ },
+ {
+ manualRunAvailable: false,
+ manualRunBlockedReason: 'Patrol is already running',
+ },
+ ),
).toBe(
- 'Automatic Patrol checks from alerts and anomalies are paused by the local development safety guard. Manual Patrol still works.',
+ 'A Patrol run is already in progress. New automatic and manual runs are paused until it finishes.',
);
});
@@ -332,25 +493,25 @@ describe('patrolRunPresentation', () => {
newFindings: 3,
});
expect(formatPatrolActivityBreakdown(summary)).toBe(
- '1 full, 1 alert-triggered, 1 anomaly-triggered',
+ '1 full check, 1 alert-triggered check, 1 anomaly-triggered check',
);
});
it('returns canonical patrol run loading and unavailable copy', () => {
- expect(getRunHistoryLoadingState()).toBe('Loading run history…');
+ expect(getRunHistoryLoadingState()).toBe('Loading history...');
expect(getToolCallsLoadingState()).toBe('Loading tool calls...');
expect(getToolCallsUnavailableState()).toBe('Tool call details not available for this run.');
});
- it('warns when visible runs include legacy findings snapshots', () => {
+ it('warns when visible runs include legacy finding records', () => {
expect(getRunHistorySelectionHint([{ finding_ids: [] }, { finding_ids: undefined }])).toBe(
- 'Select a run to filter findings when available. Some older runs do not include findings snapshots.',
+ 'Open a check to review what Patrol found. Older checks may not have issue lists.',
);
});
it('explains selected legacy runs in the run-history shell', () => {
expect(getRunHistorySelectionHint([{ finding_ids: [] }], { finding_ids: undefined })).toBe(
- 'Selected run predates findings snapshots; run-scoped findings cannot be fully verified.',
+ 'This older check has no issue list.',
);
});
});
diff --git a/frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.ts b/frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.ts
index 88a1e65746..269aefbd13 100644
--- a/frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.ts
+++ b/frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.ts
@@ -7,8 +7,8 @@ import {
describe('patrolRuntimeActions', () => {
it('centralizes the Patrol provider settings action', () => {
expect(PATROL_PROVIDER_SETTINGS_ACTION).toEqual({
- label: 'Open Patrol provider settings',
- href: '/settings/system-ai',
+ label: 'Open Provider & Models',
+ href: '/settings/pulse-intelligence/provider',
});
const action = getPatrolProviderSettingsAction();
diff --git a/frontend-modern/src/utils/__tests__/patrolRuntimePresentation.test.ts b/frontend-modern/src/utils/__tests__/patrolRuntimePresentation.test.ts
new file mode 100644
index 0000000000..ff991a7650
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/patrolRuntimePresentation.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from 'vitest';
+
+import { getPatrolRuntimePresentation } from '@/utils/patrolRuntimePresentation';
+
+describe('patrolRuntimePresentation', () => {
+ it('keeps enabled state separate from a run-in-progress label', () => {
+ expect(getPatrolRuntimePresentation('running')).toMatchObject({
+ label: 'Patrol enabled',
+ title: 'Patrol running',
+ description: 'Patrol is checking your infrastructure now.',
+ tone: 'info',
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/patrolSummaryPresentation.test.ts b/frontend-modern/src/utils/__tests__/patrolSummaryPresentation.test.ts
index f5d0f1942b..7e7f1bf77d 100644
--- a/frontend-modern/src/utils/__tests__/patrolSummaryPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/patrolSummaryPresentation.test.ts
@@ -3,6 +3,7 @@ import {
getPatrolAssessmentPresentation,
getPatrolAssessmentAction,
getPatrolAssessmentShellPresentation,
+ getPatrolCompactAssessmentLabel,
getPatrolRecencyPresentation,
getPatrolScoreChipLabel,
getPatrolSummaryMetricState,
@@ -30,7 +31,7 @@ describe('getPatrolSummaryPresentation', () => {
});
it('exports canonical patrol empty-state copy', () => {
- expect(PATROL_NO_ISSUES_LABEL).toBe('No issues found');
+ expect(PATROL_NO_ISSUES_LABEL).toBe('No active issues');
});
it('promotes coverage gaps into the primary patrol assessment state', () => {
@@ -54,7 +55,7 @@ describe('getPatrolSummaryPresentation', () => {
).toEqual({
title: 'Coverage incomplete',
description: 'Patrol coverage is incomplete.',
- eyebrow: 'Patrol assessment',
+ eyebrow: 'Status',
compactLabel: 'Coverage incomplete',
tone: 'warning',
});
@@ -75,12 +76,33 @@ describe('getPatrolSummaryPresentation', () => {
).toEqual({
title: 'Issues detected',
description: 'Warnings require review.',
- eyebrow: 'Patrol assessment',
+ eyebrow: 'Status',
compactLabel: 'Issues detected',
tone: 'warning',
});
});
+ it('surfaces an active running Patrol instead of a stale all-clear summary', () => {
+ expect(
+ getPatrolAssessmentPresentation({
+ runtimeState: 'running',
+ overallHealth: {
+ score: 100,
+ grade: 'A',
+ trend: 'stable',
+ factors: [],
+ prediction: 'Infrastructure is healthy with no significant issues detected.',
+ },
+ }),
+ ).toEqual({
+ title: 'Patrol running',
+ description: 'Patrol is checking your infrastructure now.',
+ eyebrow: 'Status',
+ compactLabel: 'Patrol is checking now',
+ tone: 'info',
+ });
+ });
+
it('does not reuse an all-clear health prediction while active infrastructure findings exist', () => {
expect(
getPatrolAssessmentPresentation({
@@ -106,7 +128,7 @@ describe('getPatrolSummaryPresentation', () => {
title: 'Issues detected',
description:
'Patrol surfaced 1 active warning finding in your infrastructure. Review the active findings for more detail.',
- eyebrow: 'Patrol assessment',
+ eyebrow: 'Status',
compactLabel: 'Issues detected',
tone: 'warning',
});
@@ -137,7 +159,7 @@ describe('getPatrolSummaryPresentation', () => {
title: 'Patrol runtime issue',
description:
'Patrol has an active runtime issue: Provider billing or quota issue. Review the Patrol runtime issue for more detail.',
- eyebrow: 'Patrol assessment',
+ eyebrow: 'Status',
compactLabel: 'Patrol runtime issue',
tone: 'warning',
});
@@ -166,8 +188,8 @@ describe('getPatrolSummaryPresentation', () => {
).toEqual({
title: 'Issues detected',
description:
- 'Patrol surfaced 1 active warning finding. Recent coverage is also incomplete, so the rest of your infrastructure is not fully verified.',
- eyebrow: 'Patrol assessment',
+ 'Patrol surfaced 1 active warning finding. Recent coverage is incomplete. Run Patrol to check everything.',
+ eyebrow: 'Status',
compactLabel: 'Issues detected',
tone: 'warning',
});
@@ -189,7 +211,7 @@ describe('getPatrolSummaryPresentation', () => {
},
],
prediction:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
},
warningFindings: 1,
activeFindings: [
@@ -215,7 +237,7 @@ describe('getPatrolSummaryPresentation', () => {
title: 'Issues detected',
description:
'Patrol surfaced 1 active warning finding in your infrastructure. Review the active findings for more detail.',
- eyebrow: 'Patrol assessment',
+ eyebrow: 'Status',
compactLabel: 'Issues detected',
tone: 'warning',
});
@@ -237,7 +259,7 @@ describe('getPatrolSummaryPresentation', () => {
},
],
prediction:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
},
warningFindings: 2,
activeFindings: [
@@ -260,8 +282,8 @@ describe('getPatrolSummaryPresentation', () => {
).toEqual({
title: 'Issues detected',
description:
- 'Patrol surfaced 1 active warning finding in your infrastructure and 1 active Patrol runtime issue. Recent coverage is also incomplete, so the rest of your infrastructure is not fully verified.',
- eyebrow: 'Patrol assessment',
+ 'Patrol surfaced 1 active warning finding in your infrastructure and 1 active Patrol runtime issue. Recent coverage is incomplete. Run Patrol to check everything.',
+ eyebrow: 'Status',
compactLabel: 'Issues detected',
tone: 'warning',
});
@@ -283,7 +305,7 @@ describe('getPatrolSummaryPresentation', () => {
},
],
prediction:
- 'Patrol coverage is incomplete: recent activity was limited to scoped runs and ended with errors, so overall health is not fully verified.',
+ 'Recent Patrol activity only covered targeted checks and ended with errors. Run Patrol to check everything.',
},
warningFindings: 1,
activeFindings: [
@@ -299,8 +321,8 @@ describe('getPatrolSummaryPresentation', () => {
).toEqual({
title: 'Patrol runtime issue',
description:
- 'Patrol has an active runtime issue: Provider billing or quota issue. Recent coverage is also incomplete, so the rest of your infrastructure is not fully verified.',
- eyebrow: 'Patrol assessment',
+ 'Patrol has an active runtime issue: Provider billing or quota issue. Recent coverage is incomplete. Run Patrol to check everything.',
+ eyebrow: 'Status',
compactLabel: 'Patrol runtime issue',
tone: 'warning',
});
@@ -350,8 +372,8 @@ describe('getPatrolSummaryPresentation', () => {
] as never,
}),
).toEqual({
- label: 'Open Patrol provider settings',
- href: '/settings/system-ai',
+ label: 'Open Provider & Models',
+ href: '/settings/pulse-intelligence/provider',
});
});
@@ -460,6 +482,70 @@ describe('getPatrolSummaryPresentation', () => {
).toBe('Health');
});
+ it('names compact assessment evidence instead of exposing bare counters', () => {
+ expect(
+ getPatrolCompactAssessmentLabel({
+ assessmentLabel: 'No active issues',
+ overallHealth: {
+ score: 95,
+ grade: 'A',
+ trend: 'stable',
+ factors: [],
+ prediction: 'Infrastructure is healthy with no significant issues detected.',
+ },
+ activeFindings: [],
+ historicalRegressionCount: 1,
+ }),
+ ).toBe('No active issues · 1 past regression · health score 95/100');
+ });
+
+ it('uses issue nouns for compact active finding summaries', () => {
+ expect(
+ getPatrolCompactAssessmentLabel({
+ assessmentLabel: 'Issues detected',
+ overallHealth: {
+ score: 84,
+ grade: 'B',
+ trend: 'stable',
+ factors: [],
+ prediction: 'Warnings require review.',
+ },
+ activeFindings: [
+ {
+ status: 'active',
+ severity: 'critical',
+ resourceId: 'vm-100',
+ resourceName: 'web-1',
+ title: 'High CPU usage',
+ },
+ {
+ status: 'active',
+ severity: 'warning',
+ resourceId: 'ai-service',
+ resourceName: 'Pulse Patrol Service',
+ title: 'Pulse Patrol: Provider connection issue',
+ },
+ ] as never,
+ }),
+ ).toBe('1 critical issue · 1 Patrol runtime issue · health score 84/100');
+ });
+
+ it('can suppress stale health scores while Patrol is still running', () => {
+ expect(
+ getPatrolCompactAssessmentLabel({
+ assessmentLabel: 'Patrol is checking now',
+ overallHealth: {
+ score: 65,
+ grade: 'C',
+ trend: 'stable',
+ factors: [],
+ prediction: 'Previous assessment needs attention.',
+ },
+ includeHealthScore: false,
+ }),
+ ).toBe('Patrol is checking now');
+ });
+
it('keeps no-issues copy only for fully healthy patrol states', () => {
expect(
getPatrolNoIssuesPresentation({
@@ -472,12 +558,12 @@ describe('getPatrolSummaryPresentation', () => {
},
}),
).toEqual({
- label: 'No issues found',
+ label: 'No active issues',
tone: 'success',
});
});
- it('reports recent successful full patrol verification', () => {
+ it('reports a recent successful Patrol check', () => {
expect(
getPatrolVerificationPresentation({
runs: [
@@ -512,15 +598,15 @@ describe('getPatrolSummaryPresentation', () => {
] as never,
}),
).toEqual({
- title: 'Recently verified',
- description: 'The most recent full patrol completed successfully and checked 58 resources.',
- compactLabel: 'Recently verified',
+ title: 'Recently checked',
+ description: 'The most recent Patrol check completed successfully and covered 58 resources.',
+ compactLabel: 'Recently checked',
tone: 'success',
lastFullRunAt: '2026-03-12T09:57:00Z',
});
});
- it('adds an activity mix when scoped runs make recent verification look busy', () => {
+ it('adds a check mix when targeted runs make recent activity look busy', () => {
expect(
getPatrolVerificationPresentation({
runs: [
@@ -613,16 +699,16 @@ describe('getPatrolSummaryPresentation', () => {
] as never,
}),
).toEqual({
- title: 'Recently verified',
- description: 'The most recent full patrol completed successfully and checked 58 resources.',
- compactLabel: 'Recently verified',
+ title: 'Recently checked',
+ description: 'The most recent Patrol check completed successfully and covered 58 resources.',
+ compactLabel: 'Recently checked',
tone: 'success',
lastFullRunAt: '2026-03-12T09:57:00Z',
- activityMixLabel: '1 full, 1 alert-triggered, 1 anomaly-triggered',
+ activityMixLabel: '1 full check, 1 alert-triggered check, 1 anomaly-triggered check',
});
});
- it('reports partial verification when only scoped runs are recent', () => {
+ it('reports a partial check when only targeted runs are recent', () => {
expect(
getPatrolVerificationPresentation({
runs: [
@@ -658,15 +744,15 @@ describe('getPatrolSummaryPresentation', () => {
] as never,
}),
).toEqual({
- title: 'No recent full patrol',
+ title: 'Needs full check',
description:
- 'Recent activity was limited to scoped alert fired runs over 1 resource, so Patrol has not recently re-verified your full infrastructure.',
- compactLabel: 'Partial verification',
+ 'Recent targeted checks covered 1 resource. Run Patrol to check everything.',
+ compactLabel: 'Partial check',
tone: 'warning',
});
});
- it('reports limited verification when only verification checks are recent', () => {
+ it('reports a partial check when only follow-up checks are recent', () => {
expect(
getPatrolVerificationPresentation({
runs: [
@@ -702,15 +788,15 @@ describe('getPatrolSummaryPresentation', () => {
] as never,
}),
).toEqual({
- title: 'No recent full patrol',
+ title: 'Needs full check',
description:
- 'Recent activity was limited to verification checks over 1 resource, so Patrol has not recently re-verified your full infrastructure.',
- compactLabel: 'Partial verification',
+ 'Recent follow-up checks covered 1 resource. Run Patrol to check everything.',
+ compactLabel: 'Partial check',
tone: 'warning',
});
});
- it('labels scoped recency as activity rather than patrol', () => {
+ it('labels targeted recency as the last check', () => {
expect(
getPatrolRecencyPresentation({
runs: [
@@ -746,14 +832,14 @@ describe('getPatrolSummaryPresentation', () => {
] as never,
}),
).toEqual({
- label: 'Last activity',
+ label: 'Last check',
timestamp: '2026-03-12T09:59:00Z',
resourcesChecked: 1,
resourcesCheckedLabel: 'checked 1 resource',
});
});
- it('labels full patrol recency explicitly when the latest completed run is full', () => {
+ it('labels completed Patrol recency as the last check', () => {
expect(
getPatrolRecencyPresentation({
runs: [
@@ -788,7 +874,7 @@ describe('getPatrolSummaryPresentation', () => {
] as never,
}),
).toEqual({
- label: 'Last full patrol',
+ label: 'Last check',
timestamp: '2026-03-12T09:57:00Z',
resourcesChecked: 58,
resourcesCheckedLabel: 'verified 58 resources',
@@ -830,7 +916,7 @@ describe('getPatrolSummaryPresentation', () => {
] as never,
}),
).toEqual({
- label: 'Last full patrol',
+ label: 'Last check',
timestamp: '2026-03-12T09:57:00Z',
resourcesChecked: 58,
resourcesCheckedLabel: 'checked 58 resources',
@@ -890,7 +976,7 @@ describe('getPatrolSummaryPresentation', () => {
] as never,
}),
).toEqual({
- label: 'Last full patrol',
+ label: 'Last check',
timestamp: '2026-03-12T09:51:00Z',
});
});
diff --git a/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts b/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts
index c23207e966..fac637a37f 100644
--- a/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts
+++ b/frontend-modern/src/utils/__tests__/pricingHandoff.test.ts
@@ -15,6 +15,7 @@ import {
isExternalPricingDestination,
isRetiredPricingFeature,
isSelfHostedPurchaseStartDestination,
+ LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE,
resolveCanonicalSelfHostedBillingHref,
resolveSelfHostedBillingSection,
resolveSelfHostedPurchaseStartDestination,
@@ -52,6 +53,9 @@ describe('pricingHandoff', () => {
SELF_HOSTED_PRO_BILLING_PLAN_HREF,
);
expect(getUpgradeFallbackDestination('ai_alerts')).toBe(SELF_HOSTED_PRO_BILLING_PLAN_HREF);
+ expect(getUpgradeFallbackDestination('ai_autofix')).toBe(
+ SELF_HOSTED_PRO_BILLING_PLAN_SELECTION_HREF,
+ );
expect(getUpgradeFallbackDestination('rbac')).toBe(SELF_HOSTED_PRO_BILLING_PLAN_HREF);
expect(getUpgradeFallbackDestination('advanced_reporting')).toBe(
SELF_HOSTED_PRO_BILLING_PLAN_HREF,
@@ -79,7 +83,11 @@ describe('pricingHandoff', () => {
'agent_profiles',
]);
for (const key of paidCatalogFeatureKeys) {
- expect(getUpgradeFallbackDestination(key)).toBe(SELF_HOSTED_PRO_BILLING_PLAN_HREF);
+ expect(getUpgradeFallbackDestination(key)).toBe(
+ key === 'ai_autofix'
+ ? SELF_HOSTED_PRO_BILLING_PLAN_SELECTION_HREF
+ : SELF_HOSTED_PRO_BILLING_PLAN_HREF,
+ );
}
});
@@ -108,6 +116,9 @@ describe('pricingHandoff', () => {
});
it('preserves extra query parameters when handing off the legacy pricing route', () => {
+ expect(getPricingRouteDestination('?feature=ai_autofix')).toBe(
+ SELF_HOSTED_PRO_BILLING_PLAN_SELECTION_HREF,
+ );
expect(
getPricingRouteDestination('?feature=unknown_pro_feature&utm_content=legacy-bookmark'),
).toBe(
@@ -148,16 +159,20 @@ describe('pricingHandoff', () => {
it('canonicalizes legacy self-hosted billing aliases to route-owned states', () => {
expect(
- resolveCanonicalSelfHostedBillingHref(SELF_HOSTED_PRO_BILLING_ROUTE, '', '#pulse-pro-usage'),
+ resolveCanonicalSelfHostedBillingHref(
+ LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE,
+ '',
+ '#pulse-pro-usage',
+ ),
).toBe(SELF_HOSTED_PRO_BILLING_USAGE_HREF);
expect(
resolveCanonicalSelfHostedBillingHref(
- SELF_HOSTED_PRO_BILLING_ROUTE,
+ LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE,
'',
'#pulse-pro-recovery',
),
).toBe(SELF_HOSTED_PRO_BILLING_PLAN_RECOVERY_HREF);
- expect(resolveCanonicalSelfHostedBillingHref(SELF_HOSTED_PRO_BILLING_ROUTE)).toBe(
+ expect(resolveCanonicalSelfHostedBillingHref(LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE)).toBe(
SELF_HOSTED_PRO_BILLING_PLAN_HREF,
);
expect(
@@ -166,9 +181,9 @@ describe('pricingHandoff', () => {
'?intent=max_monitored_systems',
),
).toBe(SELF_HOSTED_PRO_BILLING_PLAN_HREF);
- expect(resolveCanonicalSelfHostedBillingHref(`${SELF_HOSTED_PRO_BILLING_ROUTE}/history`)).toBe(
- SELF_HOSTED_PRO_BILLING_PLAN_HREF,
- );
+ expect(
+ resolveCanonicalSelfHostedBillingHref(`${LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE}/history`),
+ ).toBe(SELF_HOSTED_PRO_BILLING_PLAN_HREF);
});
it('derives billing focus and arrival intent from canonical routes', () => {
diff --git a/frontend-modern/src/utils/__tests__/resourceChangePresentation.test.ts b/frontend-modern/src/utils/__tests__/resourceChangePresentation.test.ts
index dbab68e7a6..d18ccd2703 100644
--- a/frontend-modern/src/utils/__tests__/resourceChangePresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/resourceChangePresentation.test.ts
@@ -41,6 +41,16 @@ describe('resourceChangePresentation utils', () => {
observedAt: '2026-03-18T12:00:00Z',
} as never),
).toBe('Config update: Updated canonical config');
+
+ expect(
+ formatResourceChangeHeadline({
+ id: 'change-3',
+ resourceId: 'storage:pool:data',
+ kind: 'alert_resolved',
+ reason: "Alert resolved: ZFS pool 'data' has errors",
+ observedAt: '2026-03-18T12:00:00Z',
+ } as never),
+ ).toBe("Alert resolved: ZFS pool 'data' has errors");
});
it('exposes canonical kind, source type, and adapter presentations', () => {
diff --git a/frontend-modern/src/utils/__tests__/resourceCorrelationPresentation.test.ts b/frontend-modern/src/utils/__tests__/resourceCorrelationPresentation.test.ts
index edabf5ee78..580d21b068 100644
--- a/frontend-modern/src/utils/__tests__/resourceCorrelationPresentation.test.ts
+++ b/frontend-modern/src/utils/__tests__/resourceCorrelationPresentation.test.ts
@@ -48,6 +48,18 @@ describe('resourceCorrelationPresentation utils', () => {
it('formats correlation patterns and summaries', () => {
expect(formatResourceCorrelationPattern(correlation)).toBe('Disk Full → Restart');
+ expect(
+ formatResourceCorrelationPattern({
+ ...correlation,
+ event_pattern: 'ALERT -> ALERT',
+ }),
+ ).toBe('Alert → Alert');
+ expect(
+ formatResourceCorrelationPattern({
+ ...correlation,
+ event_pattern: 'ALERT → ALERT',
+ }),
+ ).toBe('Alert → Alert');
expect(formatResourceCorrelationSummary(correlation)).toBe(
'2 occurrences · avg delay 5s · 88% confidence',
);
diff --git a/frontend-modern/src/utils/__tests__/selfHostedPlans.test.ts b/frontend-modern/src/utils/__tests__/selfHostedPlans.test.ts
index 7dfb4c47b5..f901ac876f 100644
--- a/frontend-modern/src/utils/__tests__/selfHostedPlans.test.ts
+++ b/frontend-modern/src/utils/__tests__/selfHostedPlans.test.ts
@@ -63,8 +63,7 @@ describe('selfHostedPlans', () => {
it('keeps shared self-hosted commercial copy in the common contract', () => {
expect(SELF_HOSTED_COMMERCIAL_PRESENTATION).toEqual({
pageTitle: 'Pricing',
- pageDescription:
- 'Self-hosted Pulse includes core monitoring for free. Relay adds secure remote access to the Pulse web UI, Pulse Mobile pairing, and push notifications, while Pro adds root-cause analysis, safe remediation workflows, 90-day history, and admin/reporting extras.',
+ pageDescription: 'Self-hosted plans and included capabilities.',
mostPopularBadge: 'Most Popular',
currentPlanLabel: 'Current Plan',
includedLabel: 'Included',
@@ -90,18 +89,18 @@ describe('selfHostedPlans', () => {
it('keeps Community copy free-first and Pro copy focused on operational extras', () => {
expect(SELF_HOSTED_PLAN_BY_TIER.community.subline).toBe('Core monitoring included');
expect(SELF_HOSTED_PLAN_BY_TIER.community.billingExtrasSummary).toBe(
- 'Patrol, alerts, and SSO',
+ 'Watch-only Patrol, alerts, and SSO',
);
expect(SELF_HOSTED_PLAN_BY_TIER.community.entitlementSummary).toContain(
'Community is active on this instance.',
);
expect(SELF_HOSTED_PLAN_BY_TIER.community.comparisonSummary).toBe(
- 'Community covers self-hosted monitoring and core operations on this instance.',
+ 'Community covers self-hosted monitoring and watch-only Patrol on this instance.',
);
expect(SELF_HOSTED_PLAN_BY_TIER.community.entitlementHighlights).toEqual([
'Real-time monitoring',
'7-day metric history',
- 'Pulse Patrol (BYOK)',
+ 'Watch-only Patrol',
'Update alerts',
]);
expect(SELF_HOSTED_PLAN_BY_TIER.community.includedExtras).toEqual([]);
@@ -109,10 +108,10 @@ describe('selfHostedPlans', () => {
'Remote web access, pairing, and push',
);
expect(SELF_HOSTED_PLAN_BY_TIER.relay.entitlementSummary).toContain(
- 'Remote web access, Pulse Mobile pairing, push notifications, and longer history are available right now.',
+ 'remote web access, Pulse Mobile pairing, push notifications, and 14-day metric history.',
);
- expect(SELF_HOSTED_PLAN_BY_TIER.relay.comparisonSummary).toContain(
- 'Reach your Pulse web UI securely from anywhere',
+ expect(SELF_HOSTED_PLAN_BY_TIER.relay.comparisonSummary).toBe(
+ 'Remote web access, Pulse Mobile pairing, push notifications, and 14-day metric history.',
);
expect(SELF_HOSTED_PLAN_BY_TIER.relay.entitlementHighlights).toEqual([
'Pulse Relay (Remote Access)',
@@ -127,17 +126,18 @@ describe('selfHostedPlans', () => {
/yourlab\.pulserelay\.pro|custom\s+(?:url|subdomain|domain)/i,
);
expect(SELF_HOSTED_PLAN_BY_TIER.pro.billingExtrasSummary).toBe(
- 'Analysis, remediation, and admin controls',
+ 'Patrol modes, history, and admin controls',
);
expect(SELF_HOSTED_PLAN_BY_TIER.pro.entitlementSummary).toContain(
- 'Root-cause analysis, safe remediation workflows, 90-day history, and admin/reporting extras are available right now.',
+ 'Patrol modes, 90-day metric history, RBAC, audit logs, reports, and agent profiles.',
);
- expect(SELF_HOSTED_PLAN_BY_TIER.pro.comparisonSummary).toContain(
- 'safe remediation workflows, 90-day history',
+ expect(SELF_HOSTED_PLAN_BY_TIER.pro.comparisonSummary).toBe(
+ 'Patrol modes, 90-day metric history, RBAC, audit logs, reports, and agent profiles.',
);
+ expect(SELF_HOSTED_PLAN_BY_TIER.pro.comparisonSummary).not.toContain('how much control');
expect(SELF_HOSTED_PLAN_BY_TIER.pro.entitlementHighlights).toEqual([
- 'Alert Root-Cause Analysis',
- 'Safe Remediation Workflows',
+ 'Patrol Investigates Issues',
+ 'Patrol Handles Safe Fixes',
'90-day metric history',
]);
expect(SELF_HOSTED_PLAN_BY_TIER.pro.includedExtras).toEqual([
@@ -147,7 +147,7 @@ describe('selfHostedPlans', () => {
'Centralized Agent Profiles',
]);
expect(SELF_HOSTED_PLAN_BY_TIER.community.highlights).toEqual(
- expect.arrayContaining(['Real-time monitoring', 'Pulse Patrol (BYOK)']),
+ expect.arrayContaining(['Real-time monitoring', 'Watch-only Patrol']),
);
expect(SELF_HOSTED_PLAN_BY_TIER.community.highlights).not.toContain(
'Hosted Patrol quickstart with activated entitlement: 25 runs, no API key',
@@ -172,7 +172,7 @@ describe('selfHostedPlans', () => {
getSelfHostedPlanEntitlementSummary('pro'),
);
expect(getSelfHostedPlanEntitlementSummary('pro', 'Legacy Pulse Pro+')).toBe(
- 'Legacy Pulse Pro+ is active on this instance. Root-cause analysis, safe remediation workflows, 90-day history, and admin/reporting extras are available right now.',
+ 'Legacy Pulse Pro+ is active on this instance. It includes Patrol modes, 90-day metric history, RBAC, audit logs, reports, and agent profiles.',
);
expect(SELF_HOSTED_PLAN_BY_TIER.relay.entitlementHighlights).toEqual(
@@ -210,13 +210,13 @@ describe('selfHostedPlans', () => {
extras: plan.billingExtrasSummary,
})),
).toEqual([
- { tier: 'community', historyDays: 7, extras: 'Patrol, alerts, and SSO' },
+ { tier: 'community', historyDays: 7, extras: 'Watch-only Patrol, alerts, and SSO' },
{
tier: 'relay',
historyDays: 14,
extras: 'Remote web access, pairing, and push',
},
- { tier: 'pro', historyDays: 90, extras: 'Analysis, remediation, and admin controls' },
+ { tier: 'pro', historyDays: 90, extras: 'Patrol modes, history, and admin controls' },
]);
expect(SELF_HOSTED_FEATURE_ROWS.find((row) => row.key === 'history')).toEqual({
key: 'history',
diff --git a/frontend-modern/src/utils/aiChatPresentation.ts b/frontend-modern/src/utils/aiChatPresentation.ts
index 798766d2cc..ecca94b42e 100644
--- a/frontend-modern/src/utils/aiChatPresentation.ts
+++ b/frontend-modern/src/utils/aiChatPresentation.ts
@@ -1,3 +1,5 @@
+import { SETTINGS_PROVIDER_MODELS_PATH } from '@/components/Settings/settingsNavigationModel';
+
export const AI_CHAT_DRAWER_TITLE = 'Pulse Assistant';
export const AI_CHAT_DRAWER_SUBTITLE =
'Observed context, provider-backed reasoning, and governed actions.';
@@ -40,11 +42,11 @@ export const AI_CHAT_TRANSCRIPT_FALLBACK_CLOSE_LABEL = 'Close Assistant transcri
export const AI_CHAT_TRANSCRIPT_FALLBACK_DOWNLOAD_LABEL = 'Download Assistant transcript';
export const AI_CHAT_TRANSCRIPT_FALLBACK_TEXTAREA_LABEL = 'Assistant transcript';
export const AI_CHAT_TRANSCRIPT_FALLBACK_TITLE = 'Transcript ready';
-export const AI_CHAT_AUTONOMOUS_WARNING_DISMISS_LABEL = 'Dismiss autonomous control warning';
+export const AI_CHAT_AUTONOMOUS_WARNING_DISMISS_LABEL = 'Dismiss chat actions warning';
export const AI_CHAT_DISCOVERY_HINT_DISMISS_LABEL = 'Dismiss discovery context warning';
-export const AI_CHAT_CONTROL_MODE_LABEL = 'Assistant control mode';
-export const AI_CHAT_CONTROL_MODE_MENU_LABEL = 'Assistant control mode options';
-export const AI_CHAT_SWITCH_TO_APPROVAL_LABEL = 'Switch Assistant control mode to Approval';
+export const AI_CHAT_CONTROL_MODE_LABEL = 'Assistant chat action mode';
+export const AI_CHAT_CONTROL_MODE_MENU_LABEL = 'Assistant chat action options';
+export const AI_CHAT_SWITCH_TO_APPROVAL_LABEL = 'Switch Assistant chat actions to Ask first';
export const AI_CHAT_COMMAND_HELP_TITLE = 'Assistant commands';
export const AI_CHAT_COMMAND_HELP_BUTTON_LABEL = 'Open Assistant commands';
export const AI_CHAT_COMMAND_HELP_CLOSE_LABEL = 'Close Assistant commands';
@@ -59,7 +61,7 @@ export const AI_CHAT_SESSION_SEARCH_EMPTY_STATE = 'No sessions match your search
export const AI_CHAT_SESSION_SEARCH_LOADING_STATE = 'Searching assistant sessions...';
export const AI_CHAT_SESSION_SEARCH_ERROR_STATE = 'Failed to search assistant sessions';
export const AI_CHAT_MODEL_SELECTOR_EMPTY_STATE = 'No matching models.';
-export const AI_CHAT_DISCOVERY_HINT_TITLE = 'Workload Discovery is off.';
+export const AI_CHAT_DISCOVERY_HINT_TITLE = 'Discovery is off.';
export const AI_CHAT_DISCOVERY_HINT_BODY =
'Enable it in Settings so Pulse Assistant can reference real services, versions, and commands instead of generic guidance.';
export const AI_CHAT_INPUT_PLACEHOLDER = 'Ask about your infrastructure...';
@@ -68,7 +70,7 @@ export const AI_CHAT_QUESTION_CARD_PLACEHOLDER = 'Type your answer...';
export const AI_CHAT_ASSISTANT_MESSAGE_LABEL = 'Pulse Assistant';
export const AI_CHAT_CONTEXT_USED_LABEL = 'Context used';
export const AI_CHAT_LAST_TURN_SUMMARY_LABEL = 'Last assistant turn summary';
-export const AI_CHAT_PROVIDER_READINESS_SETTINGS_HREF = '/settings/system-ai';
+export const AI_CHAT_PROVIDER_READINESS_SETTINGS_HREF = SETTINGS_PROVIDER_MODELS_PATH;
export const AI_CHAT_PROVIDER_READINESS_SETTINGS_LABEL = 'Open settings';
export const AI_CHAT_PROVIDER_READINESS_RETRY_LABEL = 'Retry';
diff --git a/frontend-modern/src/utils/aiControlLevelPresentation.ts b/frontend-modern/src/utils/aiControlLevelPresentation.ts
index 8601b5fce6..24c313a5ef 100644
--- a/frontend-modern/src/utils/aiControlLevelPresentation.ts
+++ b/frontend-modern/src/utils/aiControlLevelPresentation.ts
@@ -38,11 +38,11 @@ export function getAIControlLevelBadgeClass(level: AIControlLevel): string {
export function getAIControlLevelDescription(level: AIControlLevel): string {
switch (level) {
case 'controlled':
- return 'Controlled mode: Pulse Assistant can run interactive actions only after you approve each one.';
+ return 'Assistant asks before chat-only actions. Infrastructure work stays with Patrol mode.';
case 'autonomous':
- return 'Autonomous mode: Pulse Assistant can run eligible actions without per-command approval.';
+ return 'Assistant may take eligible chat-only actions allowed by policy. Infrastructure work stays with Patrol mode.';
default:
- return 'Read-only mode: Pulse Assistant can query and observe only.';
+ return 'Assistant can query and explain only. Infrastructure work stays with Patrol mode.';
}
}
@@ -52,8 +52,8 @@ export function getAIChatControlLevelPresentation(
switch (level) {
case 'autonomous':
return {
- label: 'Autonomous',
- description: 'Executes without approval',
+ label: 'Chat actions',
+ description: 'Eligible chat-only actions',
pillClassName:
'border-red-200 text-red-700 bg-red-50 dark:border-red-800 dark:text-red-200 dark:bg-red-900',
dotClassName: 'bg-red-500',
@@ -61,8 +61,8 @@ export function getAIChatControlLevelPresentation(
};
case 'controlled':
return {
- label: 'Approval',
- description: 'Ask before running commands',
+ label: 'Ask first',
+ description: 'Asks before chat-only actions',
pillClassName:
'border-amber-200 text-amber-700 bg-amber-50 dark:border-amber-800 dark:text-amber-200 dark:bg-amber-900',
dotClassName: 'bg-amber-500',
@@ -71,7 +71,7 @@ export function getAIChatControlLevelPresentation(
default:
return {
label: 'Read-only',
- description: 'No commands or control actions',
+ description: 'Observes only',
pillClassName: 'border-border text-muted bg-surface',
dotClassName: 'bg-slate-400',
selectedClassName: 'bg-surface-alt',
diff --git a/frontend-modern/src/utils/aiCostPresentation.ts b/frontend-modern/src/utils/aiCostPresentation.ts
index 704472eb2e..918018336a 100644
--- a/frontend-modern/src/utils/aiCostPresentation.ts
+++ b/frontend-modern/src/utils/aiCostPresentation.ts
@@ -4,6 +4,7 @@ export const AI_COST_PANEL_TITLE = 'Provider Usage & Spend';
export const AI_COST_PANEL_DESCRIPTION =
'Token usage and estimated spend across providers backing Pulse Assistant and Patrol.';
export const AI_COST_PROVIDER_MODEL_PAIR_LABEL = 'Provider/model pairs';
+export const AI_COST_TARGET_TABLE_LABEL = 'Usage by task';
export const AI_COST_ASSISTANT_USE_CASE_LABEL = 'Pulse Assistant';
export const AI_COST_PATROL_USE_CASE_LABEL = 'Patrol';
export const AI_COST_BUDGET_LABEL = '30-day budget (USD)';
@@ -26,7 +27,7 @@ export function getAICostRefreshErrorMessage() {
}
export function getAICostBudgetNote(rangeDays: number) {
- return `Configured in Assistant & Patrol settings. Pro-rated for ${rangeDays}d:`;
+ return `Configured in Provider & Models settings. Pro-rated for ${rangeDays}d:`;
}
export function getAICostResetHistoryConfirmationMessage() {
@@ -58,3 +59,85 @@ export function buildAICostExportFilename(
export function getAICostRangeButtonClass(selected: boolean, disabled = false): string {
return `min-h-10 sm:min-h-9 min-w-10 border px-2.5 py-2 text-sm ${segmentedButtonClass(selected, disabled)}`;
}
+
+export interface AICostTargetPresentationInput {
+ target_type?: string | null;
+ target_id?: string | null;
+}
+
+export interface AICostTargetPresentation {
+ label: string;
+ detail?: string;
+ rawLabel: string;
+}
+
+const TARGET_TYPE_LABELS: Record<string, string> = {
+ assistant_session: 'Assistant sessions',
+ assistant_session_title: 'Assistant sessions',
+ chat: 'Assistant sessions',
+ discovery: 'Discovery runs',
+ discovery_run: 'Discovery runs',
+ patrol: 'Patrol runs',
+ patrol_run: 'Patrol runs',
+ patrol_session: 'Patrol runs',
+ resource: 'Resource checks',
+ resource_context: 'Resource checks',
+};
+
+const RESOURCE_TYPE_PREFIXES: Record<string, string> = {
+ container: 'Container',
+ lxc: 'Container',
+ vm: 'VM',
+};
+
+function humanizeIdentifier(value: string): string {
+ return value
+ .replace(/[_-]+/g, ' ')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .replace(/\b\w/g, (letter) => letter.toUpperCase());
+}
+
+function isOpaqueTargetId(value: string): boolean {
+ const trimmed = value.trim();
+ if (!trimmed) return false;
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed)) {
+ return true;
+ }
+ if (/^[0-9a-f]{20,}$/i.test(trimmed)) return true;
+ return trimmed.length > 32 && /^[a-z0-9:_-]+$/i.test(trimmed);
+}
+
+function readableTargetType(targetType: string): string {
+ const normalized = targetType.trim().toLowerCase();
+ return TARGET_TYPE_LABELS[normalized] || humanizeIdentifier(normalized || 'usage');
+}
+
+export function getAICostTargetPresentation(
+ target: AICostTargetPresentationInput,
+): AICostTargetPresentation {
+ const targetType = target.target_type?.trim() || 'usage';
+ const targetId = target.target_id?.trim() || '';
+ const normalizedType = targetType.toLowerCase();
+ const rawLabel = targetId ? `${targetType}:${targetId}` : targetType;
+ const resourcePrefix = RESOURCE_TYPE_PREFIXES[normalizedType];
+
+ if (resourcePrefix) {
+ return {
+ label:
+ targetId && !isOpaqueTargetId(targetId)
+ ? `${resourcePrefix} ${targetId}`
+ : `${resourcePrefix}s`,
+ rawLabel,
+ };
+ }
+
+ const label = readableTargetType(targetType);
+ const detail = targetId && !isOpaqueTargetId(targetId) ? targetId : undefined;
+
+ return {
+ label,
+ detail,
+ rawLabel,
+ };
+}
diff --git a/frontend-modern/src/utils/aiFindingPresentation.ts b/frontend-modern/src/utils/aiFindingPresentation.ts
index 5a785e5cae..a98c32158f 100644
--- a/frontend-modern/src/utils/aiFindingPresentation.ts
+++ b/frontend-modern/src/utils/aiFindingPresentation.ts
@@ -177,6 +177,7 @@ const INVESTIGATION_OUTCOME_LABELS: Record<InvestigationOutcome, string> = {
fix_queued: 'Fix queued',
fix_executed: 'Fix applied',
fix_failed: 'Fix failed',
+ fix_rejected: 'Fix rejected',
needs_attention: 'Needs attention',
cannot_fix: 'Cannot remediate',
timed_out: 'Timed out',
@@ -194,6 +195,8 @@ const INVESTIGATION_OUTCOME_CLASSES: Record<InvestigationOutcome, string> = {
'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-900 dark:text-emerald-300',
fix_failed:
'border-red-200 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-900 dark:text-red-300',
+ fix_rejected:
+ 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900 dark:text-amber-300',
needs_attention:
'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900 dark:text-amber-300',
cannot_fix: 'border-border bg-surface-alt text-muted',
@@ -211,6 +214,7 @@ const INVESTIGATION_OUTCOME_TONES: Record<InvestigationOutcome, MetadataBadgeTon
fix_queued: 'info',
fix_executed: 'success',
fix_failed: 'danger',
+ fix_rejected: 'warning',
needs_attention: 'warning',
cannot_fix: 'muted',
timed_out: 'neutral',
@@ -237,6 +241,7 @@ const INVESTIGATION_OUTCOME_SORT_ORDER: Record<string, number> = {
fix_verification_failed: 0,
fix_failed: 0,
fix_verification_unknown: 1,
+ fix_rejected: 1,
timed_out: 1,
needs_attention: 1,
cannot_fix: 1,
@@ -291,6 +296,15 @@ export interface PatrolFindingsBadgePresentation {
tone: 'danger' | 'warning' | 'info' | 'muted';
}
+export interface PatrolFindingDisplayGroup<TFinding> {
+ id: string;
+ resourceKey: string;
+ resourceLabel: string;
+ primaryFinding: TFinding;
+ relatedFindings: TFinding[];
+ findings: TFinding[];
+}
+
export interface FindingSeverityPresentation {
label: string;
badgeClasses: string;
@@ -303,6 +317,21 @@ export interface FindingCompactBadgePresentation {
badgeClasses: string;
}
+export type FindingPatrolWorkflowStage =
+ | 'investigating'
+ | 'approval'
+ | 'verification'
+ | 'attention'
+ | 'recorded'
+ | 'paused';
+
+export interface FindingPatrolWorkflowPresentation {
+ stage: FindingPatrolWorkflowStage;
+ label: string;
+ detail: string;
+ tone: MetadataBadgeTone;
+}
+
export const getFindingSourceLabel = (source: UnifiedFinding['source'] | string): string =>
FINDING_SOURCE_LABELS[source] || source;
@@ -480,6 +509,64 @@ export const getFindingSubjectPresentation = (
};
};
+export const getPatrolFindingResourceGroupKey = (
+ finding: Pick<UnifiedFinding, 'id' | 'resourceId' | 'resourceName' | 'resourceType' | 'title'>,
+): string => {
+ const resourceName = String(finding.resourceName || '').trim();
+ const resourceType = String(finding.resourceType || '').trim();
+ if (resourceName || resourceType) {
+ return `subject:${getFindingSubjectPresentation(finding).label.toLowerCase()}`;
+ }
+
+ const resourceId = String(finding.resourceId || '').trim();
+ if (resourceId) {
+ return `id:${resourceId}`;
+ }
+
+ return `finding:${finding.id}`;
+};
+
+export function buildPatrolFindingDisplayGroups<
+ TFinding extends Pick<
+ UnifiedFinding,
+ 'id' | 'resourceId' | 'resourceName' | 'resourceType' | 'title'
+ >,
+>(findings: readonly TFinding[]): PatrolFindingDisplayGroup<TFinding>[] {
+ const groups: PatrolFindingDisplayGroup<TFinding>[] = [];
+ const groupsByResourceKey = new Map<string, PatrolFindingDisplayGroup<TFinding>>();
+
+ for (const finding of findings) {
+ const resourceKey = getPatrolFindingResourceGroupKey(finding);
+ const existing = groupsByResourceKey.get(resourceKey);
+ if (existing) {
+ existing.findings.push(finding);
+ existing.relatedFindings.push(finding);
+ continue;
+ }
+
+ const group: PatrolFindingDisplayGroup<TFinding> = {
+ id: resourceKey,
+ resourceKey,
+ resourceLabel: getFindingSubjectPresentation(finding).label,
+ primaryFinding: finding,
+ relatedFindings: [],
+ findings: [finding],
+ };
+ groupsByResourceKey.set(resourceKey, group);
+ groups.push(group);
+ }
+
+ return groups;
+}
+
+export const getPatrolFindingIssueCountLabel = (count: number): string => {
+ const normalized = Number.isFinite(count) ? Math.max(0, Math.trunc(count)) : 0;
+ if (normalized === 1) {
+ return '1 issue';
+ }
+ return `${normalized} issues`;
+};
+
export const getFindingTitlePresentation = (
finding: Pick<UnifiedFinding, 'resourceId' | 'resourceName' | 'title'>,
): FindingTitlePresentation => {
@@ -649,6 +736,7 @@ const ATTENTION_OUTCOMES = new Set([
'fix_verification_failed',
'fix_verification_unknown',
'fix_failed',
+ 'fix_rejected',
'timed_out',
'needs_attention',
'cannot_fix',
@@ -688,6 +776,142 @@ export const doesFindingNeedAttention = (
);
};
+export const getFindingPatrolWorkflowPresentation = (
+ finding: Pick<
+ UnifiedFinding,
+ | 'id'
+ | 'source'
+ | 'status'
+ | 'resourceId'
+ | 'resourceName'
+ | 'title'
+ | 'investigationStatus'
+ | 'investigationOutcome'
+ | 'loopState'
+ >,
+ approvals: Pick<ApprovalRequest, 'status' | 'toolId' | 'targetId' | 'expiresAt'>[] = [],
+ now = Date.now(),
+): FindingPatrolWorkflowPresentation | undefined => {
+ if (finding.source !== 'ai-patrol') {
+ return undefined;
+ }
+
+ if (finding.status === 'resolved') {
+ return {
+ stage: 'recorded',
+ label: 'Outcome recorded',
+ detail: 'Patrol has a verified or cleared outcome for this finding.',
+ tone: 'success',
+ };
+ }
+
+ if (finding.status === 'snoozed') {
+ return {
+ stage: 'paused',
+ label: 'Paused until reminder',
+ detail: 'Patrol will surface this again when the snooze expires.',
+ tone: 'info',
+ };
+ }
+
+ if (finding.status !== 'active') {
+ return undefined;
+ }
+
+ if (isPatrolRuntimeFinding(finding)) {
+ return {
+ stage: 'attention',
+ label: 'Fix Patrol setup',
+ detail: 'Patrol needs runtime or provider setup before it can check infrastructure reliably.',
+ tone: 'info',
+ };
+ }
+
+ const hasLiveApproval = hasPendingInvestigationFixApproval(finding.id, approvals, now);
+ if (hasLiveApproval) {
+ return {
+ stage: 'approval',
+ label: 'Approve or reject',
+ detail: 'A governed fix is waiting for an approve or reject decision.',
+ tone: 'warning',
+ };
+ }
+
+ if (
+ finding.investigationStatus === 'running' ||
+ finding.investigationStatus === 'pending' ||
+ finding.loopState === 'investigating'
+ ) {
+ return {
+ stage: 'investigating',
+ label: 'Patrol investigating',
+ detail: 'Patrol is gathering context before asking for a decision.',
+ tone: 'indigo',
+ };
+ }
+
+ switch (finding.investigationOutcome) {
+ case 'resolved':
+ case 'fix_verified':
+ return {
+ stage: 'recorded',
+ label: 'Outcome recorded',
+ detail: 'Patrol verified or cleared this finding.',
+ tone: 'success',
+ };
+ case 'fix_queued':
+ return {
+ stage: 'approval',
+ label: 'Review fix',
+ detail:
+ 'A fix was queued, but no live approval is available. Expand the finding to recover it.',
+ tone: 'warning',
+ };
+ case 'fix_executed':
+ return {
+ stage: 'verification',
+ label: 'Verify outcome',
+ detail: 'Patrol executed a governed fix and is waiting for verification.',
+ tone: 'info',
+ };
+ case 'fix_failed':
+ case 'fix_verification_failed':
+ return {
+ stage: 'attention',
+ label: 'Fix failed',
+ detail:
+ 'The governed action did not resolve the finding. Reopen context before trying another change.',
+ tone: 'danger',
+ };
+ case 'fix_rejected':
+ return {
+ stage: 'attention',
+ label: 'Decide follow-up',
+ detail:
+ 'The last governed fix was rejected. Review the finding for another option or mark it resolved after manual work.',
+ tone: 'warning',
+ };
+ case 'fix_verification_unknown':
+ return {
+ stage: 'verification',
+ label: 'Check outcome',
+ detail: 'Patrol could not verify the fix. Inspect the resource or gather more evidence.',
+ tone: 'warning',
+ };
+ case 'needs_attention':
+ case 'cannot_fix':
+ case 'timed_out':
+ return {
+ stage: 'attention',
+ label: 'Needs input',
+ detail: 'Patrol needs operator context before continuing.',
+ tone: 'warning',
+ };
+ default:
+ return undefined;
+ }
+};
+
export const getFindingLoopStateBadgeClasses = (loopState: string): string =>
FINDING_LOOP_STATE_CLASSES[loopState] || DEFAULT_LOOP_STATE_CLASSES;
@@ -750,6 +974,8 @@ export const getFindingResolutionReason = (
return `Resolved by Patrol ${resolvedTime}`;
case 'fix_failed':
return `Resolved after fix failed ${resolvedTime}`;
+ case 'fix_rejected':
+ return `Resolved after rejected fix ${resolvedTime}`;
case 'fix_queued':
return `Resolved while fix was pending ${resolvedTime}`;
case 'fix_verification_failed':
diff --git a/frontend-modern/src/utils/aiSettingsPresentation.ts b/frontend-modern/src/utils/aiSettingsPresentation.ts
index 4f01d64a97..6b71affd5c 100644
--- a/frontend-modern/src/utils/aiSettingsPresentation.ts
+++ b/frontend-modern/src/utils/aiSettingsPresentation.ts
@@ -15,18 +15,20 @@ const AI_OAUTH_ERROR_MESSAGES: Record<string, string> = {
invalid_state: 'The authentication session is no longer valid. Try again.',
token_exchange_failed: 'Unable to complete authentication with Claude.',
save_failed: 'Unable to save OAuth credentials.',
+ unsupported:
+ 'Anthropic subscription OAuth is not supported. Configure an Anthropic API key instead.',
};
-export const AI_SETTINGS_PANEL_TITLE = 'Assistant & Patrol';
+export const AI_SETTINGS_PANEL_TITLE = 'Provider & Models';
export const AI_SETTINGS_PANEL_DESCRIPTION =
- 'Configure providers and models for Pulse Assistant and Patrol.';
+ 'Configure providers, default models, provider health, budget, and usage for Pulse Intelligence.';
export const AI_SETTINGS_MODEL_OVERRIDES_TITLE = 'Model Overrides';
export const AI_SETTINGS_ASSISTANT_SESSIONS_TITLE = 'Pulse Assistant Sessions';
-export const AI_SETTINGS_ASSISTANT_PERMISSIONS_TITLE = 'Pulse Assistant Permissions';
+export const AI_SETTINGS_ASSISTANT_PERMISSIONS_TITLE = 'Assistant chat actions';
export const AI_SETTINGS_LOAD_MODELS_ERROR = 'Unable to load models.';
export const AI_SETTINGS_LOAD_CHAT_SESSIONS_ERROR = 'Unable to load chat sessions.';
export const AI_SETTINGS_LOAD_FAILURE_MESSAGE =
- 'Unable to load Assistant & Patrol settings. Your configuration could not be retrieved.';
+ 'Unable to load Provider & Models settings. Your configuration could not be retrieved.';
export const AI_SETTINGS_LOAD_RETRY_LABEL = 'Retry';
export interface AISettingsSetupDialogPresentation {
@@ -42,24 +44,24 @@ export function getAIProviderTestResultTextClass(success: boolean): string {
export function getAISettingsWorkloadDiscoveryHelpContent() {
return {
- title: 'What is workload discovery?',
+ title: 'What is service context?',
description:
- 'Workload discovery scans your VMs, containers, and container runtimes to identify running services, versions, and access details. Pulse stores that context so Assistant can use it in chat and Patrol can use it during verification.',
+ 'Service context scans your VMs, containers, and container runtimes to identify running services, versions, and access details. Pulse stores those facts so Assistant can use them in chat and Patrol can use them during verification.',
} as const;
}
export function getAISettingsWorkloadDiscoverySummary() {
return {
- text: 'Workload discovery stores concrete service context for Assistant chat and Patrol verification, so responses and findings can reference real services and commands instead of generic advice.',
+ text: 'Service context records service names, versions, and commands so Assistant and Patrol can use real context instead of generic advice.',
} as const;
}
export function getAISettingsSetupDialogPresentation(): AISettingsSetupDialogPresentation {
return {
- ariaLabel: 'Set up Assistant and Patrol',
- title: 'Set Up Assistant & Patrol',
- description: 'Connect a provider to power Pulse Assistant and Patrol.',
- submitLabel: 'Enable Assistant & Patrol',
+ ariaLabel: 'Set up Pulse Intelligence',
+ title: 'Set Up Pulse Intelligence',
+ description: 'Connect a provider to power Patrol, Assistant, and service context.',
+ submitLabel: 'Enable Pulse Intelligence',
};
}
@@ -89,7 +91,7 @@ export function getAIOAuthErrorMessage(errorCode: string): string {
export function getAISettingsLoadingState() {
return {
- text: 'Loading Assistant & Patrol settings...',
+ text: 'Loading Provider & Models settings...',
} as const;
}
@@ -128,9 +130,12 @@ export function getAISessionSummarizeErrorMessage(message?: string | null) {
return detail || 'Unable to summarize the session.';
}
-export function getAISettingsSaveErrorMessage(message?: string | null) {
+export function getAISettingsSaveErrorMessage(
+ message?: string | null,
+ fallback = 'Unable to save Provider & Models settings.',
+) {
const detail = (message || '').trim();
- return detail || 'Unable to save Assistant & Patrol settings.';
+ return detail || fallback;
}
export function getAICredentialsClearErrorMessage(message?: string | null) {
@@ -140,5 +145,5 @@ export function getAICredentialsClearErrorMessage(message?: string | null) {
export function getAISettingsToggleErrorMessage(message?: string | null) {
const detail = (message || '').trim();
- return detail || 'Unable to update Assistant & Patrol settings.';
+ return detail || 'Unable to update Pulse Intelligence settings.';
}
diff --git a/frontend-modern/src/utils/infrastructureOnboardingPresentation.ts b/frontend-modern/src/utils/infrastructureOnboardingPresentation.ts
index f906777bd1..72955e1320 100644
--- a/frontend-modern/src/utils/infrastructureOnboardingPresentation.ts
+++ b/frontend-modern/src/utils/infrastructureOnboardingPresentation.ts
@@ -552,7 +552,7 @@ export const getInfrastructureEmptyStateSummary = (): string =>
'Choose an infrastructure source to start monitoring your environment.';
export const getInfrastructureEmptyStateDetail = (): string =>
- 'Supported source types include TrueNAS SCALE, Proxmox VE, Proxmox Backup Server, Proxmox Mail Gateway, and Pulse Agent hosts. VMware vCenter is available as a preview platform pending live support proof. Docker and Kubernetes are discovered from supported agent hosts.';
+ 'Supported source types include TrueNAS SCALE, Proxmox VE, Proxmox Backup Server, Proxmox Mail Gateway, and Pulse Agent hosts. VMware vCenter is available as a preview platform while live support is validated. Docker and Kubernetes are discovered from supported agent hosts.';
export const getInfrastructureCoverageCompleteActionPresentation =
(): InfrastructureCoverageCompleteActionPresentation => ({
diff --git a/frontend-modern/src/utils/licensePresentation.ts b/frontend-modern/src/utils/licensePresentation.ts
index 241b561e90..1d4b215263 100644
--- a/frontend-modern/src/utils/licensePresentation.ts
+++ b/frontend-modern/src/utils/licensePresentation.ts
@@ -9,6 +9,7 @@ import {
getSelfHostedPlanDefinitionForBillingTier,
getSelfHostedPlanEntitlementSummary,
} from '@/utils/selfHostedPlans';
+import { PATROL_CONTROL_PATH, PATROL_CONTROL_PATH_WITH_STARTER } from '@/routing/resourceLinks';
import {
getSelfHostedFeatureCatalogEntry,
isDisplayableSelfHostedFeatureKey,
@@ -75,6 +76,12 @@ export interface LicenseExternalActionCopy {
actionUrl: string;
}
+export type SelfHostedPatrolControlActionIntent = 'patrol_control';
+
+export interface SelfHostedPatrolControlAction extends LicenseExternalActionCopy {
+ actionIntent: SelfHostedPatrolControlActionIntent;
+}
+
export interface SelfHostedRecoveryPresentation {
disclosureLabel: string;
disclosureDescription: string;
@@ -101,19 +108,53 @@ export interface SelfHostedCurrentPlanPresentation {
supplementalBadges: string[];
supplementalSummary?: string;
privateRuntimeAction?: LicenseExternalActionCopy;
+ patrolControlAction?: SelfHostedPatrolControlAction;
}
-export interface SelfHostedActivationProofItem {
+export interface SelfHostedPlanStatusItem {
label: string;
statusLabel: string;
state: 'active' | 'partial' | 'missing';
detail: string;
}
-export interface SelfHostedActivationProofPresentation {
+export interface SelfHostedPlanStatusPresentation {
title: string;
body: string;
- items: SelfHostedActivationProofItem[];
+ items: SelfHostedPlanStatusItem[];
+}
+
+export interface SelfHostedPatrolOperatorStatus {
+ nextAction?: string;
+ progressLabel?: string;
+ patrolControlOperationsLoopStarterCount?: number;
+ patrolControlCompletedOperationsLoopCount?: number;
+ patrolControlResolvedOperationsLoopCount?: number;
+ patrolControlValueState?:
+ | 'not_started'
+ | 'in_progress'
+ | 'governed_decision_recorded'
+ | 'verified_needs_mcp'
+ | 'verified';
+ patrolAutonomyOperationsLoopStarterCount?: number;
+ patrolAutonomyCompletedOperationsLoopCount?: number;
+ patrolAutonomyResolvedOperationsLoopCount?: number;
+ patrolAutonomyValueState?:
+ | 'not_started'
+ | 'in_progress'
+ | 'governed_decision_recorded'
+ | 'verified_needs_mcp'
+ | 'verified';
+ proActivationOperationsLoopStarterCount?: number;
+ proActivationCompletedOperationsLoopCount?: number;
+ proActivationResolvedOperationsLoopCount?: number;
+ proActivationValueProofState?:
+ | 'not_started'
+ | 'in_progress'
+ | 'governed_decision_recorded'
+ | 'verified_needs_mcp'
+ | 'verified';
+ externalAgentReady: boolean;
}
export interface SelfHostedActivationSuccessPresentation extends LicenseInlineNotice {
@@ -121,6 +162,7 @@ export interface SelfHostedActivationSuccessPresentation extends LicenseInlineNo
highlights: string[];
actionLabel?: string;
actionUrl?: string;
+ actionIntent?: SelfHostedPatrolControlActionIntent;
}
export type SelfHostedActivationSuccessSource = 'manual' | 'purchase';
@@ -162,6 +204,134 @@ const PRO_RUNTIME_REQUIRED_TIERS = new Set([
]);
export const PULSE_PRO_DOWNLOAD_URL = 'https://pulserelay.pro/download.html';
+export const PATROL_CONTROL_STARTER_URL = PATROL_CONTROL_PATH_WITH_STARTER;
+
+const PATROL_CONTROL_CAPABILITIES = new Set(['ai_autofix']);
+
+const hasPatrolControlCapability = (entitlements?: LicenseCommercialEntitlements | null): boolean =>
+ Boolean(
+ entitlements?.capabilities?.some((capability) =>
+ PATROL_CONTROL_CAPABILITIES.has(capability.trim().toLowerCase()),
+ ),
+ );
+
+const normalizeStatusCount = (value?: number | null): number => {
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
+ return 0;
+ }
+ return Math.max(0, Math.trunc(value));
+};
+
+const getFirstPartyPatrolControlCount = (
+ patrolControlCount?: number | null,
+ patrolAutonomyCompatibilityCount?: number | null,
+ proActivationAliasCount?: number | null,
+): number => {
+ const aggregatePatrolControlCount = normalizeStatusCount(
+ patrolControlCount ?? patrolAutonomyCompatibilityCount,
+ );
+ return Math.max(0, aggregatePatrolControlCount - normalizeStatusCount(proActivationAliasCount));
+};
+
+const getPatrolControlStarterCount = (status?: SelfHostedPatrolOperatorStatus | null): number =>
+ getFirstPartyPatrolControlCount(
+ status?.patrolControlOperationsLoopStarterCount,
+ status?.patrolAutonomyOperationsLoopStarterCount,
+ status?.proActivationOperationsLoopStarterCount,
+ );
+
+const getPatrolControlCompletedCount = (status?: SelfHostedPatrolOperatorStatus | null): number =>
+ getFirstPartyPatrolControlCount(
+ status?.patrolControlCompletedOperationsLoopCount,
+ status?.patrolAutonomyCompletedOperationsLoopCount,
+ status?.proActivationCompletedOperationsLoopCount,
+ );
+
+const getPatrolControlResolvedCount = (status?: SelfHostedPatrolOperatorStatus | null): number =>
+ getFirstPartyPatrolControlCount(
+ status?.patrolControlResolvedOperationsLoopCount,
+ status?.patrolAutonomyResolvedOperationsLoopCount,
+ status?.proActivationResolvedOperationsLoopCount,
+ );
+
+const getPatrolControlValueState = (
+ status?: SelfHostedPatrolOperatorStatus | null,
+): SelfHostedPatrolOperatorStatus['patrolControlValueState'] =>
+ getPatrolControlStarterCount(status) > 0 ||
+ getPatrolControlCompletedCount(status) > 0 ||
+ getPatrolControlResolvedCount(status) > 0
+ ? (status?.patrolControlValueState ?? status?.patrolAutonomyValueState)
+ : undefined;
+
+const hasVerifiedPatrolOperatorOutcome = (
+ status?: SelfHostedPatrolOperatorStatus | null,
+): boolean => {
+ const resolvedCount = getPatrolControlResolvedCount(status);
+ const valueProofState = getPatrolControlValueState(status);
+ return (
+ valueProofState === 'verified' ||
+ valueProofState === 'verified_needs_mcp' ||
+ (!valueProofState && resolvedCount > 0)
+ );
+};
+
+const hasGovernedDecisionOnlyPatrolOperatorOutcome = (
+ status?: SelfHostedPatrolOperatorStatus | null,
+): boolean => {
+ const completedCount = getPatrolControlCompletedCount(status);
+ const resolvedCount = getPatrolControlResolvedCount(status);
+ const valueProofState = getPatrolControlValueState(status);
+ return (
+ valueProofState === 'governed_decision_recorded' ||
+ (!valueProofState && completedCount > 0 && resolvedCount === 0)
+ );
+};
+
+type PatrolControlActionStage = 'set' | 'continue' | 'decision';
+
+const getPatrolControlActionStage = (
+ status?: SelfHostedPatrolOperatorStatus | null,
+): PatrolControlActionStage => {
+ if (hasGovernedDecisionOnlyPatrolOperatorOutcome(status)) {
+ return 'decision';
+ }
+ const completedCount = getPatrolControlCompletedCount(status);
+ const resolvedCount = getPatrolControlResolvedCount(status);
+ const starterCount = getPatrolControlStarterCount(status);
+ if (
+ !hasVerifiedPatrolOperatorOutcome(status) &&
+ (starterCount > 0 || completedCount > 0 || resolvedCount > 0)
+ ) {
+ return 'continue';
+ }
+
+ return 'set';
+};
+
+const getPatrolControlActionLabel = (status?: SelfHostedPatrolOperatorStatus | null): string => {
+ switch (getPatrolControlActionStage(status)) {
+ case 'decision':
+ return 'Review Patrol decision';
+ case 'continue':
+ return 'Open Patrol';
+ case 'set':
+ return PATROL_CONTROL_ACTION.actionLabel;
+ }
+};
+
+const getPatrolControlActionUrl = (status?: SelfHostedPatrolOperatorStatus | null): string => {
+ const stage = getPatrolControlActionStage(status);
+ if (stage === 'decision') {
+ return PATROL_CONTROL_PATH;
+ }
+ return PATROL_CONTROL_STARTER_URL;
+};
+
+const PATROL_CONTROL_ACTION: SelfHostedPatrolControlAction = {
+ actionLabel: 'Choose Patrol mode',
+ actionUrl: PATROL_CONTROL_STARTER_URL,
+ actionIntent: 'patrol_control',
+};
const isActivePaidRuntimeState = (subscriptionState?: string | null): boolean => {
const normalized = (subscriptionState || '').trim().toLowerCase();
@@ -212,8 +382,39 @@ const getPulseProRuntimeMismatchDetail = (
entitlements?: Pick<LicenseCommercialEntitlements, 'runtime'> | null,
): string =>
getPulseProRuntimeBuild(entitlements) === 'community'
- ? `This install reports the community runtime. Open ${PULSE_PRO_DOWNLOAD_URL} with your activation key and install the private Pulse Pro runtime; public GitHub releases and the public Docker image do not include Pro-only runtime hooks.`
- : `This install is not reporting a Pulse Pro runtime identity. Open ${PULSE_PRO_DOWNLOAD_URL} with your activation key and install the private Pulse Pro runtime; public GitHub releases and the public Docker image do not include Pro-only runtime hooks.`;
+ ? `This install reports the community runtime. Open ${PULSE_PRO_DOWNLOAD_URL} with your license key and install the private Pulse Pro runtime; public GitHub releases and the public Docker image do not include Pro-only runtime hooks.`
+ : `This install is not reporting a Pulse Pro runtime identity. Open ${PULSE_PRO_DOWNLOAD_URL} with your license key and install the private Pulse Pro runtime; public GitHub releases and the public Docker image do not include Pro-only runtime hooks.`;
+
+const getPatrolControlAction = ({
+ entitlements,
+ patrolOperatorStatus,
+ planDefinition,
+ subscriptionState,
+}: {
+ entitlements?: LicenseCommercialEntitlements | null;
+ patrolOperatorStatus?: SelfHostedPatrolOperatorStatus | null;
+ planDefinition: ReturnType<typeof getSelfHostedPlanDefinitionForBillingTier>;
+ subscriptionState?: string | null;
+}): SelfHostedPatrolControlAction | undefined => {
+ const normalizedState = (subscriptionState || '').trim().toLowerCase();
+ if (normalizedState !== 'active' && normalizedState !== 'grace' && normalizedState !== 'trial') {
+ return undefined;
+ }
+ if (planDefinition?.tier !== 'pro') {
+ return undefined;
+ }
+ if (!hasPatrolControlCapability(entitlements)) {
+ return undefined;
+ }
+ if (hasPulseProRuntimeMismatch(entitlements)) {
+ return undefined;
+ }
+ return {
+ ...PATROL_CONTROL_ACTION,
+ actionLabel: getPatrolControlActionLabel(patrolOperatorStatus),
+ actionUrl: getPatrolControlActionUrl(patrolOperatorStatus),
+ };
+};
export const getLicenseTierLabel = (tier?: string | null): string => {
const normalized = (tier || '').trim().toLowerCase();
@@ -349,10 +550,7 @@ const getSelfHostedPlanComparisonHighlights = (
return [];
}
const highlights: string[] = [];
- for (const feature of [
- ...planDefinition.entitlementHighlights,
- ...planDefinition.includedExtras,
- ]) {
+ for (const feature of planDefinition.highlights) {
if (!feature || highlights.includes(feature)) {
continue;
}
@@ -367,13 +565,48 @@ const getSelfHostedPlanComparisonHighlights = (
const getSelfHostedActivePlanSummary = (
planLabel: string,
planDefinition: ReturnType<typeof getSelfHostedPlanDefinitionForBillingTier>,
+ patrolOperatorStatus?: SelfHostedPatrolOperatorStatus | null,
): string | null => {
if (!planDefinition) {
return null;
}
+ if (planDefinition.tier === 'pro') {
+ switch (getPatrolControlActionStage(patrolOperatorStatus)) {
+ case 'decision':
+ return `${planLabel} is active on this instance. Review the current Patrol decision.`;
+ case 'continue':
+ return `${planLabel} is active on this instance. Open Patrol to continue current work.`;
+ case 'set':
+ break;
+ }
+ }
return getSelfHostedPlanEntitlementSummary(planDefinition.tier, planLabel);
};
+const getSelfHostedActivationPatrolControlBody = ({
+ actionStage,
+ planLabel,
+ source,
+}: {
+ actionStage: PatrolControlActionStage;
+ planLabel: string;
+ source: SelfHostedActivationSuccessSource;
+}): string => {
+ const prefix =
+ source === 'purchase'
+ ? `Checkout completed and ${planLabel} is active.`
+ : `The license key was accepted and ${planLabel} is active.`;
+
+ switch (actionStage) {
+ case 'decision':
+ return `${prefix} Review the current Patrol decision.`;
+ case 'continue':
+ return `${prefix} Open Patrol to continue current work.`;
+ case 'set':
+ return `${prefix} Choose Patrol mode.`;
+ }
+};
+
export const getSelfHostedPlanComparisonPresentation = ({
entitlements,
}: {
@@ -395,7 +628,7 @@ export const getSelfHostedPlanComparisonPresentation = ({
return null;
}
return {
- title: `What ${getSelfHostedPlanLabel(tier)} adds`,
+ title: `${getSelfHostedPlanLabel(tier)} plan`,
body: definition.comparisonSummary,
highlights: getSelfHostedPlanComparisonHighlights(definition),
};
@@ -407,9 +640,11 @@ export const getSelfHostedPlanComparisonPresentation = ({
export const getSelfHostedCurrentPlanPresentation = ({
entitlements,
displayableCapabilities,
+ patrolOperatorStatus,
}: {
entitlements?: LicenseCommercialEntitlements | null;
displayableCapabilities: string[];
+ patrolOperatorStatus?: SelfHostedPatrolOperatorStatus | null;
}): SelfHostedCurrentPlanPresentation => {
const current = entitlements;
if (!current) {
@@ -437,6 +672,12 @@ export const getSelfHostedCurrentPlanPresentation = ({
const runtimeMismatch = hasPulseProRuntimeMismatch(current);
const unlockedFeaturesLabel =
normalizedTier === 'free' ? 'Included on this instance' : 'Primary capabilities';
+ const patrolControlAction = getPatrolControlAction({
+ entitlements: current,
+ patrolOperatorStatus,
+ planDefinition,
+ subscriptionState: current.subscription_state,
+ });
const supplementalBadges: string[] = [];
const supplementalDetails: string[] = [];
@@ -460,13 +701,13 @@ export const getSelfHostedCurrentPlanPresentation = ({
if (runtimeMismatch) {
supplementalBadges.push('Pro runtime missing');
supplementalDetails.unshift(
- 'Public GitHub releases and the public Docker image are community builds. Open Pulse Pro downloads with your activation key to install the private Pulse Pro runtime and test Pro-only runtime hooks during the trial.',
+ 'Public GitHub releases and the public Docker image are community builds. Open Pulse Pro downloads with your license key to install the private Pulse Pro runtime and test Pro-only runtime hooks during the trial.',
);
}
return {
title: `Current plan: ${planLabel} Trial`,
body: runtimeMismatch
- ? `${planLabel} trial entitlement is active, but this install is ${getPulseProRuntimeMismatchSummary(current)}. Open Pulse Pro downloads with your activation key and install the private Pulse Pro runtime to use Pro-only features.`
+ ? `${planLabel} trial entitlement is active, but this install is ${getPulseProRuntimeMismatchSummary(current)}. Open Pulse Pro downloads with your license key and install the private Pulse Pro runtime to use Pro-only features.`
: unlockedFeatures.length > 0
? `${planLabel} trial capabilities are active on this instance right now.`
: `${planLabel} trial entitlement is being confirmed for this instance.`,
@@ -476,6 +717,7 @@ export const getSelfHostedCurrentPlanPresentation = ({
includedExtras,
supplementalBadges,
supplementalSummary: supplementalDetails.join(' '),
+ ...(patrolControlAction ? { patrolControlAction } : {}),
...(runtimeMismatch
? {
privateRuntimeAction: {
@@ -492,7 +734,7 @@ export const getSelfHostedCurrentPlanPresentation = ({
title: 'Current plan: Community',
body:
getSelfHostedActivePlanSummary('Community', planDefinition) ||
- 'Community is active on this instance. Self-hosted monitoring, 7-day metric history, Pulse Patrol (BYOK), and update alerts are included here.',
+ 'Community is active on this instance. Self-hosted monitoring, 7-day metric history, watch-only Patrol, and update alerts are included here.',
unlockedFeaturesLabel,
unlockedFeatures,
includedExtras,
@@ -509,7 +751,7 @@ export const getSelfHostedCurrentPlanPresentation = ({
);
return {
title: `Current plan: ${planLabel}`,
- body: `${planLabel} is active, but this install is ${getPulseProRuntimeMismatchSummary(current)}. Open Pulse Pro downloads with your activation key and install the private Pulse Pro runtime to use Pro-only features such as Audit Log, Audit Webhooks, RBAC, and governed remediation.`,
+ body: `${planLabel} is active, but this install is ${getPulseProRuntimeMismatchSummary(current)}. Open Pulse Pro downloads with your license key and install the private Pulse Pro runtime to use Pro-only features such as Patrol mode, Audit Log, Audit Webhooks, and RBAC.`,
unlockedFeaturesLabel,
unlockedFeatures,
includedExtrasLabel: includedExtras.length > 0 ? 'Included extras' : undefined,
@@ -526,7 +768,7 @@ export const getSelfHostedCurrentPlanPresentation = ({
return {
title: `Current plan: ${planLabel}`,
body:
- getSelfHostedActivePlanSummary(planLabel, planDefinition) ||
+ getSelfHostedActivePlanSummary(planLabel, planDefinition, patrolOperatorStatus) ||
`${planLabel} is active on this instance. These capabilities are available right now.`,
unlockedFeaturesLabel,
unlockedFeatures,
@@ -534,6 +776,7 @@ export const getSelfHostedCurrentPlanPresentation = ({
includedExtras,
supplementalBadges,
supplementalSummary: supplementalDetails.join(' '),
+ ...(patrolControlAction ? { patrolControlAction } : {}),
};
}
@@ -548,10 +791,10 @@ export const getSelfHostedCurrentPlanPresentation = ({
};
};
-const getCapabilityProofState = (
+const getCapabilityStatusState = (
capabilities: Set<string>,
requiredCapabilities: readonly string[],
-): SelfHostedActivationProofItem['state'] => {
+): SelfHostedPlanStatusItem['state'] => {
const presentCount = requiredCapabilities.filter((capability) =>
capabilities.has(capability),
).length;
@@ -561,7 +804,7 @@ const getCapabilityProofState = (
return presentCount > 0 ? 'partial' : 'missing';
};
-const getProofStatusLabel = (state: SelfHostedActivationProofItem['state']): string => {
+const getStatusStateLabel = (state: SelfHostedPlanStatusItem['state']): string => {
switch (state) {
case 'active':
return 'Active';
@@ -572,7 +815,7 @@ const getProofStatusLabel = (state: SelfHostedActivationProofItem['state']): str
}
};
-const buildCapabilityProofItem = ({
+const buildCapabilityStatusItem = ({
capabilities,
label,
requiredCapabilities,
@@ -586,19 +829,20 @@ const buildCapabilityProofItem = ({
activeDetail: string;
partialDetail: string;
missingDetail: string;
-}): SelfHostedActivationProofItem => {
- const state = getCapabilityProofState(capabilities, requiredCapabilities);
+}): SelfHostedPlanStatusItem => {
+ const state = getCapabilityStatusState(capabilities, requiredCapabilities);
return {
label,
state,
- statusLabel: getProofStatusLabel(state),
+ statusLabel: getStatusStateLabel(state),
detail: state === 'active' ? activeDetail : state === 'partial' ? partialDetail : missingDetail,
};
};
-export const getSelfHostedActivationProofPresentation = (
+export const getSelfHostedPlanStatusPresentation = (
entitlements?: LicenseCommercialEntitlements | null,
-): SelfHostedActivationProofPresentation | null => {
+ _patrolOperatorStatus?: SelfHostedPatrolOperatorStatus | null,
+): SelfHostedPlanStatusPresentation | null => {
const planDefinition = getSelfHostedPlanDefinitionForBillingTier(entitlements?.tier);
if (!entitlements || !planDefinition || planDefinition.tier === 'community') {
return null;
@@ -615,7 +859,8 @@ export const getSelfHostedActivationProofPresentation = (
const capabilities = new Set(
(entitlements.capabilities || []).map((capability) => capability.trim().toLowerCase()),
);
- const items: SelfHostedActivationProofItem[] = [];
+ const isProPlan = planDefinition.tier === 'pro';
+ const items: SelfHostedPlanStatusItem[] = [];
if (requiresPulseProRuntime(entitlements)) {
const hasProRuntime = hasPulseProRuntime(entitlements);
items.push({
@@ -623,21 +868,21 @@ export const getSelfHostedActivationProofPresentation = (
state: hasProRuntime ? 'active' : 'missing',
statusLabel: hasProRuntime ? 'Active' : 'Needs attention',
detail: hasProRuntime
- ? 'This install reports the private Pulse Pro runtime.'
+ ? 'This install is running the private Pulse Pro runtime required for Patrol mode and Pro-only actions.'
: getPulseProRuntimeMismatchDetail(entitlements),
});
}
items.push(
- buildCapabilityProofItem({
+ buildCapabilityStatusItem({
capabilities,
label: 'Remote access, pairing, and push',
requiredCapabilities: ['relay', 'mobile_app', 'push_notifications'],
activeDetail:
- 'Relay, Pulse Mobile pairing, and push notification capabilities are present in this entitlement payload.',
+ 'Relay, Pulse Mobile pairing, and push notifications are available on this instance.',
partialDetail:
- 'Some Relay convenience capabilities are present. Refresh or recover activation if remote access, Pulse Mobile pairing, or push stays unavailable.',
+ 'Some remote-access capabilities are available. Refresh the plan or open recovery if remote access, Pulse Mobile pairing, or push stays unavailable.',
missingDetail:
- 'Expected Relay convenience capabilities are not present. Refresh or recover activation before treating this plan as fully active.',
+ 'Remote access, Pulse Mobile pairing, or push notifications are not available yet. Refresh the plan or open recovery before relying on Relay.',
}),
);
@@ -652,45 +897,50 @@ export const getSelfHostedActivationProofPresentation = (
items.push({
label: `${requiredHistoryDays}-day metric history`,
state: historyState,
- statusLabel: getProofStatusLabel(historyState),
+ statusLabel: getStatusStateLabel(historyState),
detail:
historyState === 'active'
- ? `This instance reports ${actualHistoryDays} days of metric history in its entitlement payload.`
+ ? isProPlan
+ ? `Patrol has ${actualHistoryDays} days of metric history available for investigation context.`
+ : `This instance has ${actualHistoryDays} days of metric history available.`
: historyState === 'partial'
? `This instance reports ${actualHistoryDays} days of metric history, below the expected ${requiredHistoryDays} days.`
- : `This instance has not reported a metric-history entitlement yet; expected ${requiredHistoryDays} days.`,
+ : `This instance does not have metric-history access yet; expected ${requiredHistoryDays} days.`,
});
if (planDefinition.tier === 'pro') {
items.push(
- buildCapabilityProofItem({
+ buildCapabilityStatusItem({
capabilities,
- label: 'Root-cause analysis and remediation',
+ label: 'Patrol investigation and remediation',
requiredCapabilities: ['ai_alerts', 'ai_autofix'],
activeDetail:
- 'Alert-triggered root-cause analysis and safe remediation workflow capabilities are present.',
+ 'Patrol can investigate alert-triggered issues and handle governed actions within the selected Patrol mode.',
partialDetail:
- 'Some Pro operations capabilities are present. Refresh or recover activation if alert analysis or remediation stays unavailable.',
+ 'Some Patrol capability is available, but investigation or remediation may not be fully enabled yet.',
missingDetail:
- 'Expected Pro operations capabilities are not present. Refresh or recover activation before treating this Pro install as complete.',
+ 'Patrol investigation or remediation capability is missing. Refresh the plan or open recovery before relying on Patrol to handle issues.',
}),
- buildCapabilityProofItem({
+ buildCapabilityStatusItem({
capabilities,
label: 'Team and admin controls',
requiredCapabilities: ['rbac', 'audit_logging', 'advanced_reporting', 'agent_profiles'],
- activeDetail: 'RBAC, audit logging, reporting, and agent-profile capabilities are present.',
+ activeDetail:
+ 'RBAC, audit logging, reporting, and agent profiles are available for governed operations.',
partialDetail:
- 'Some team/admin capabilities are present. Refresh or recover activation if any admin tools stay unavailable.',
+ 'Some team/admin capabilities are available. Refresh the plan or open recovery if any admin controls stay unavailable.',
missingDetail:
- 'Expected team/admin capabilities are not present. Refresh or recover activation before relying on this Pro install.',
+ 'Team/admin controls are not available yet. Refresh the plan or open recovery before relying on this Pro install.',
}),
);
}
const planLabel = getSelfHostedPlanLabel(entitlements.tier);
return {
- title: `${planLabel} value proof`,
- body: "These checks come from this instance's entitlement and runtime payloads, not from public pricing copy.",
+ title: isProPlan ? 'Capability details' : `${planLabel} status`,
+ body: isProPlan
+ ? 'Open this only when a Pro capability looks unavailable. Normal setup is choosing Patrol mode.'
+ : 'These checks show the capabilities this instance can use right now, based on its entitlement and runtime payloads.',
items,
};
};
@@ -698,10 +948,12 @@ export const getSelfHostedActivationProofPresentation = (
export const getSelfHostedActivationSuccessPresentation = ({
entitlements,
displayableCapabilities,
+ patrolOperatorStatus,
source,
}: {
entitlements?: LicenseCommercialEntitlements | null;
displayableCapabilities: string[];
+ patrolOperatorStatus?: SelfHostedPatrolOperatorStatus | null;
source: SelfHostedActivationSuccessSource | null;
}): SelfHostedActivationSuccessPresentation | null => {
const current = entitlements;
@@ -725,6 +977,13 @@ export const getSelfHostedActivationSuccessPresentation = ({
displayableCapabilities,
});
const runtimeMismatch = hasPulseProRuntimeMismatch(current);
+ const patrolControlAction = getPatrolControlAction({
+ entitlements: current,
+ patrolOperatorStatus,
+ planDefinition: getSelfHostedPlanDefinitionForBillingTier(current.tier),
+ subscriptionState: current.subscription_state,
+ });
+ const patrolControlActionStage = getPatrolControlActionStage(patrolOperatorStatus);
return {
tone: runtimeMismatch
@@ -734,11 +993,23 @@ export const getSelfHostedActivationSuccessPresentation = ({
body:
source === 'purchase'
? runtimeMismatch
- ? `Checkout completed and the license is active. This install is ${getPulseProRuntimeMismatchSummary(current)}, so open Pulse Pro downloads with your activation key and install the private Pulse Pro runtime before using Pro-only features.`
- : `Checkout completed and this instance is now running ${planLabel}.`
+ ? `Checkout completed and the license is active. This install is ${getPulseProRuntimeMismatchSummary(current)}, so open Pulse Pro downloads with your license key and install the private Pulse Pro runtime before using Pro-only features.`
+ : patrolControlAction
+ ? getSelfHostedActivationPatrolControlBody({
+ actionStage: patrolControlActionStage,
+ planLabel,
+ source,
+ })
+ : `Checkout completed and this instance is now running ${planLabel}.`
: runtimeMismatch
- ? `The activation key was accepted. This install is ${getPulseProRuntimeMismatchSummary(current)}, so open Pulse Pro downloads with your activation key and install the private Pulse Pro runtime before using Pro-only features.`
- : `The activation key was accepted and this instance is now running ${planLabel}.`,
+ ? `The license key was accepted. This install is ${getPulseProRuntimeMismatchSummary(current)}, so open Pulse Pro downloads with your license key and install the private Pulse Pro runtime before using Pro-only features.`
+ : patrolControlAction
+ ? getSelfHostedActivationPatrolControlBody({
+ actionStage: patrolControlActionStage,
+ planLabel,
+ source,
+ })
+ : `The license key was accepted and this instance is now running ${planLabel}.`,
highlightsLabel: runtimeMismatch ? 'Licensed capabilities' : 'Available now on this instance',
highlights,
...(runtimeMismatch
@@ -746,22 +1017,28 @@ export const getSelfHostedActivationSuccessPresentation = ({
actionLabel: 'Open Pulse Pro downloads',
actionUrl: PULSE_PRO_DOWNLOAD_URL,
}
- : {}),
+ : patrolControlAction
+ ? {
+ actionLabel: patrolControlAction.actionLabel,
+ actionUrl: patrolControlAction.actionUrl,
+ actionIntent: patrolControlAction.actionIntent,
+ }
+ : {}),
};
};
export const getCommercialMigrationActionText = (action?: string): string => {
switch (action) {
case 'retry_activation':
- return 'Retry activation from this instance.';
+ return 'Retry from this instance.';
case 'use_v6_activation_key':
- return 'Use the current v6 activation key for this purchase.';
+ return 'Use the current v6 key for this purchase.';
case 'enter_supported_v5_key':
return 'Retry with the original v5 Pro/Lifetime key from this instance.';
case 'free_installation_slot':
return 'Contact [email protected] to release an installation you no longer use or to raise the limit.';
default:
- return 'Review the activation state from this instance before trying again.';
+ return 'Review the plan state from this instance before trying again.';
}
};
@@ -781,7 +1058,7 @@ export const getCommercialMigrationNotice = (
break;
case 'exchange_conflict':
body =
- 'Pulse detected a paid v5 license, but another v6 activation handoff is still settling.';
+ 'Pulse detected a paid v5 license, but another v6 license handoff is still settling.';
break;
case 'exchange_unavailable':
default:
@@ -855,8 +1132,8 @@ export const getPurchaseActivationNotice = (result?: string | null): LicenseInli
case 'failed':
return {
tone: 'border-red-200 dark:border-red-900 bg-red-50 dark:bg-red-900 text-red-900 dark:text-red-100',
- title: 'Activation needs attention',
- body: 'Checkout completed, but Pulse could not finish local activation automatically. Review the plan state below, then open recovery if you already have a key from this purchase.',
+ title: 'Plan needs attention',
+ body: 'Checkout completed, but this instance could not apply the plan automatically. Review the current plan below, then open recovery if you already have a key from this purchase.',
};
case 'unavailable':
return {
@@ -929,28 +1206,28 @@ export const getNoActiveSelfHostedActivationState = (): LicenseLoadingStateCopy
});
export const SELF_HOSTED_RECOVERY_PRESENTATION: SelfHostedRecoveryPresentation = {
- disclosureLabel: 'Use existing key',
+ disclosureLabel: 'Manual key recovery',
disclosureDescription:
- 'Use this only if you already have an activation key or need to recover a legacy self-hosted purchase.',
- fieldLabel: 'License or Activation Key',
- fieldPlaceholder: 'Paste your license key or activation key',
+ 'Normal checkout handles this automatically. Open this only if you already have a key or need to recover an older purchase.',
+ fieldLabel: 'License key',
+ fieldPlaceholder: 'Paste your license key',
helpTextBeforeTerms:
- 'Paste the Pulse v6 activation key shown on the hosted checkout success page. A backup copy is also sent by email, but the hosted success page is the primary handoff. You can also paste a legacy Pulse v5 Pro/Lifetime license key and Pulse will exchange it automatically during activation when migration is available. By activating a license, you agree to the',
+ 'Paste the key from the hosted checkout success page or email. Legacy Pulse v5 Pro/Lifetime keys can be migrated when supported. By applying a license, you agree to the',
helpTextAfterTerms: '.',
termsLabel: 'Terms of Service',
privateRuntimeNotice: {
title: 'Paid Docker and Linux installs use a private runtime',
- body: 'Public GitHub releases and the public Docker image are community builds. They can accept an activation key, but Pro-only runtime hooks require the private Pulse Pro Docker image or Linux archive.',
+ body: 'Public GitHub releases and the public Docker image are community builds. Pro-only runtime hooks require the private Pulse Pro Docker image or Linux archive.',
actionLabel: 'Open Pulse Pro downloads',
actionUrl: PULSE_PRO_DOWNLOAD_URL,
},
- activateIdleLabel: 'Activate Key',
- activatePendingLabel: 'Activating...',
- clearIdleLabel: 'Clear Key',
+ activateIdleLabel: 'Apply key',
+ activatePendingLabel: 'Applying...',
+ clearIdleLabel: 'Clear key',
clearPendingLabel: 'Clearing...',
legacyNotice: {
title: 'Legacy v5 license detected',
- body: 'Pulse will try to exchange this key into the v6 activation model automatically. If the exchange cannot complete immediately, retry from this panel or use the self-serve retrieval flow to get the current v6 activation key.',
+ body: 'Pulse will try to migrate this key automatically. If migration is still pending, retry here or use self-serve retrieval to get the current v6 key.',
},
};
diff --git a/frontend-modern/src/utils/patrolEmptyStatePresentation.ts b/frontend-modern/src/utils/patrolEmptyStatePresentation.ts
index 7921b8aa62..59af8ae849 100644
--- a/frontend-modern/src/utils/patrolEmptyStatePresentation.ts
+++ b/frontend-modern/src/utils/patrolEmptyStatePresentation.ts
@@ -5,6 +5,7 @@ import { getPatrolRuntimePresentation } from '@/utils/patrolRuntimePresentation'
import type { SemanticTone } from '@/utils/semanticTonePresentation';
import type { IntelligenceHealthScore } from '@/types/aiIntelligence';
import { getPatrolRunCoverageSummary, isPatrolRunHealthy } from '@/utils/patrolRunPresentation';
+import { getPatrolVerificationPresentation } from '@/utils/patrolSummaryPresentation';
export function getInvestigationMessagesState(loading: boolean, hasMessages: boolean) {
if (loading) {
@@ -43,7 +44,7 @@ export function getInvestigationSectionState(loading: boolean, hasInvestigation:
if (!hasInvestigation) {
return {
- text: 'No investigation data available. Enable patrol autonomy to investigate findings.',
+ text: 'No investigation yet. Patrol adds notes after it runs in a mode that investigates.',
empty: true,
} as const;
}
@@ -60,47 +61,86 @@ export interface PatrolFindingsEmptyStateCopy {
tone: SemanticTone;
}
-interface PatrolRunSnapshotEmptyStateArgs
- extends Pick<
- PatrolRunRecord,
- | 'resources_checked'
- | 'scope_resource_ids'
- | 'effective_scope_resource_ids'
- | 'finding_ids'
- | 'status'
- | 'error_count'
- > {}
-
-const HEALTHY_PATROL_EMPTY_STATE_BODY = 'Your infrastructure looks healthy!';
+type PatrolRunSnapshotEmptyStateArgs = Pick<
+ PatrolRunRecord,
+ | 'resources_checked'
+ | 'scope_resource_ids'
+ | 'effective_scope_resource_ids'
+ | 'finding_ids'
+ | 'status'
+ | 'error_count'
+>;
+
+const HEALTHY_PATROL_EMPTY_STATE_BODY = 'Run Patrol any time to check again.';
const DEGRADED_COVERAGE_EMPTY_STATE_BODY =
- 'Patrol has not surfaced active findings, but coverage is incomplete, so this is not a full all-clear.';
+ 'Run Patrol to check everything and update open issues.';
const DEGRADED_HEALTH_EMPTY_STATE_BODY =
- 'Patrol has not surfaced active findings, but the overall Patrol assessment still needs attention.';
+ 'No active findings are listed, but Patrol health is degraded.';
+const HISTORICAL_REGRESSION_EMPTY_STATE_BODY = 'Past issues are in History.';
+const PATROL_QUEUE_CLEAR_TITLE = 'No current issues';
+const PATROL_QUEUE_RECHECK_TITLE = 'Check needed';
+const PATROL_QUEUE_REVIEW_TITLE = 'Patrol needs review';
+const PATROL_QUEUE_RUNNING_TITLE = 'Patrol is checking now';
+const PATROL_QUEUE_RUNNING_BODY =
+ 'The current run will add work here if Patrol finds issues or needs approval.';
function getHealthDegradedTone(overallHealth: IntelligenceHealthScore): SemanticTone {
return overallHealth.grade === 'D' || overallHealth.grade === 'F' ? 'error' : 'warning';
}
-function shouldSuppressHealthyEmptyState(overallHealth: IntelligenceHealthScore | undefined): boolean {
- if (!overallHealth) {
- return false;
+function hasIncompleteCoverageEvidence(
+ overallHealth: IntelligenceHealthScore | undefined,
+ runs: PatrolRunRecord[] | undefined,
+): boolean {
+ if (overallHealth?.factors.some((factor) => factor.category === 'coverage')) {
+ return true;
}
- if (overallHealth.factors.some((factor) => factor.category === 'coverage')) {
+ const verification = getPatrolVerificationPresentation({ runs });
+ return verification.tone === 'warning';
+}
+
+function shouldSuppressHealthyEmptyState(
+ overallHealth: IntelligenceHealthScore | undefined,
+ runs: PatrolRunRecord[] | undefined,
+): boolean {
+ if (hasIncompleteCoverageEvidence(overallHealth, runs)) {
return true;
}
+ if (!overallHealth) {
+ return false;
+ }
+
return overallHealth.grade !== 'A';
}
-function getDegradedPatrolEmptyStateBody(overallHealth: IntelligenceHealthScore): string {
- if (overallHealth.factors.some((factor) => factor.category === 'coverage')) {
+function getDegradedPatrolEmptyStateBody(
+ overallHealth: IntelligenceHealthScore | undefined,
+ runs: PatrolRunRecord[] | undefined,
+): string {
+ if (hasIncompleteCoverageEvidence(overallHealth, runs)) {
return DEGRADED_COVERAGE_EMPTY_STATE_BODY;
}
return DEGRADED_HEALTH_EMPTY_STATE_BODY;
}
+function getDegradedPatrolEmptyStateTitle(
+ overallHealth: IntelligenceHealthScore | undefined,
+ runs: PatrolRunRecord[] | undefined,
+): string {
+ if (hasIncompleteCoverageEvidence(overallHealth, runs)) {
+ return PATROL_QUEUE_RECHECK_TITLE;
+ }
+
+ return PATROL_QUEUE_REVIEW_TITLE;
+}
+
+function hasHistoricalRegressions(count: number | undefined): boolean {
+ return typeof count === 'number' && Number.isFinite(count) && count > 0;
+}
+
function getPatrolRunSnapshotEmptyState(
run: PatrolRunSnapshotEmptyStateArgs,
): PatrolFindingsEmptyStateCopy {
@@ -110,7 +150,7 @@ function getPatrolRunSnapshotEmptyState(
if (!isPatrolRunHealthy(run.status, run.error_count)) {
return {
title: 'No findings recorded for this run',
- body: `${coveragePrefix}This run recorded no snapshot findings, but it ended with issues requiring review.`,
+ body: `${coveragePrefix}This run recorded no Patrol findings, but it ended with issues requiring review.`,
tone: 'warning',
};
}
@@ -124,8 +164,8 @@ function getPatrolRunSnapshotEmptyState(
function getPatrolRunSnapshotUnavailableEmptyState(): PatrolFindingsEmptyStateCopy {
return {
- title: 'Findings snapshot unavailable for this run',
- body: 'This Patrol run predates findings snapshots, so run-specific findings cannot be verified.',
+ title: 'Finding record unavailable for this run',
+ body: 'This older Patrol run has no finding record, so Patrol cannot show its issue list.',
tone: 'warning',
};
}
@@ -135,6 +175,8 @@ export function getPatrolFindingsEmptyState(args: {
overallHealth?: IntelligenceHealthScore;
runtimeState?: PatrolRuntimeState;
blockedReason?: string;
+ historicalRegressionCount?: number;
+ runs?: PatrolRunRecord[];
runSnapshot?: PatrolRunSnapshotEmptyStateArgs;
}): PatrolFindingsEmptyStateCopy {
if (
@@ -146,11 +188,7 @@ export function getPatrolFindingsEmptyState(args: {
return getPatrolRunSnapshotEmptyState(args.runSnapshot);
}
- if (
- args.filter === 'all' &&
- args.runSnapshot &&
- args.runSnapshot.finding_ids === undefined
- ) {
+ if (args.filter === 'all' && args.runSnapshot && args.runSnapshot.finding_ids === undefined) {
return getPatrolRunSnapshotUnavailableEmptyState();
}
@@ -174,16 +212,32 @@ export function getPatrolFindingsEmptyState(args: {
};
}
- if (shouldSuppressHealthyEmptyState(args.overallHealth)) {
+ if (args.runtimeState === 'running') {
+ return {
+ title: PATROL_QUEUE_RUNNING_TITLE,
+ body: PATROL_QUEUE_RUNNING_BODY,
+ tone: 'info',
+ };
+ }
+
+ if (shouldSuppressHealthyEmptyState(args.overallHealth, args.runs)) {
return {
- title: 'No active findings',
- body: getDegradedPatrolEmptyStateBody(args.overallHealth!),
- tone: getHealthDegradedTone(args.overallHealth!),
+ title: getDegradedPatrolEmptyStateTitle(args.overallHealth, args.runs),
+ body: getDegradedPatrolEmptyStateBody(args.overallHealth, args.runs),
+ tone: args.overallHealth ? getHealthDegradedTone(args.overallHealth) : 'warning',
+ };
+ }
+
+ if (hasHistoricalRegressions(args.historicalRegressionCount)) {
+ return {
+ title: PATROL_QUEUE_CLEAR_TITLE,
+ body: HISTORICAL_REGRESSION_EMPTY_STATE_BODY,
+ tone: 'info',
};
}
return {
- title: 'No active findings',
+ title: PATROL_QUEUE_CLEAR_TITLE,
body: HEALTHY_PATROL_EMPTY_STATE_BODY,
tone: 'success',
};
diff --git a/frontend-modern/src/utils/patrolFormat.ts b/frontend-modern/src/utils/patrolFormat.ts
index 5da4dff6eb..cf65cafdbf 100644
--- a/frontend-modern/src/utils/patrolFormat.ts
+++ b/frontend-modern/src/utils/patrolFormat.ts
@@ -162,6 +162,12 @@ export function formatPatrolRuntimeFailureSummary(input: {
const summary = formatPatrolRuntimeFailureDetail(input.errorSummary);
const detail = formatPatrolRuntimeFailureDetail(input.errorDetail);
if (summary && detail && summary !== detail) {
+ if (
+ summary.toLowerCase() === 'provider connection issue' &&
+ detail.toLowerCase().startsWith('provider connection failed')
+ ) {
+ return detail;
+ }
return `${summary}: ${detail}`;
}
if (summary || detail) return summary || detail;
diff --git a/frontend-modern/src/utils/patrolPagePresentation.ts b/frontend-modern/src/utils/patrolPagePresentation.ts
index a03a93c0df..1152e7e80b 100644
--- a/frontend-modern/src/utils/patrolPagePresentation.ts
+++ b/frontend-modern/src/utils/patrolPagePresentation.ts
@@ -1,16 +1,45 @@
+import type { PatrolAutonomyLevel } from '@/api/patrol';
+
export const PATROL_PAGE_TITLE = 'Patrol';
-// Page description names the Patrol ownership boundary: scheduled probing,
-// context assembly, model-assisted investigation, and governed action.
+
+export const PATROL_PAGE_WATCH_ONLY_DESCRIPTION =
+ 'Patrol watches infrastructure and shows current issues.';
+
+export const PATROL_PAGE_MONITOR_DESCRIPTION =
+ 'Watch only: Patrol reports issues without making changes.';
+
export const PATROL_PAGE_DESCRIPTION =
- 'Pulse checks your infrastructure on a schedule, gives your configured model the right evidence, and keeps fixes behind your approval policy.';
-// Tooltip on the page title; shares the same framing as the description so
-// hover and inline copy don't tell different stories about what Patrol does.
+ 'Patrol watches, investigates, acts within your chosen mode, verifies outcomes, and records what happened.';
export const PATROL_PAGE_TITLE_TOOLTIP = PATROL_PAGE_DESCRIPTION;
-export function getPatrolPageHeaderMeta() {
+export interface PatrolPageHeaderMetaInput {
+ autonomyLevel?: PatrolAutonomyLevel;
+ autonomyLocked?: boolean;
+}
+
+function getPatrolPageDescription(input: PatrolPageHeaderMetaInput): string {
+ if (input.autonomyLocked) {
+ return PATROL_PAGE_WATCH_ONLY_DESCRIPTION;
+ }
+ if (input.autonomyLevel === 'monitor') return PATROL_PAGE_MONITOR_DESCRIPTION;
+
+ switch (input.autonomyLevel) {
+ case 'approval':
+ return 'Patrol investigates issues and asks before every change.';
+ case 'assisted':
+ return 'Patrol handles safe policy-allowed fixes and asks before anything riskier.';
+ case 'full':
+ return 'Patrol handles policy-approved work automatically and asks only when approval is required.';
+ default:
+ return PATROL_PAGE_DESCRIPTION;
+ }
+}
+
+export function getPatrolPageHeaderMeta(input: PatrolPageHeaderMetaInput = {}) {
+ const description = getPatrolPageDescription(input);
return {
title: PATROL_PAGE_TITLE,
- description: PATROL_PAGE_DESCRIPTION,
- titleTooltip: PATROL_PAGE_TITLE_TOOLTIP,
+ description,
+ titleTooltip: description,
} as const;
}
diff --git a/frontend-modern/src/utils/patrolRunPresentation.ts b/frontend-modern/src/utils/patrolRunPresentation.ts
index 11b6bef048..23bc1c1c75 100644
--- a/frontend-modern/src/utils/patrolRunPresentation.ts
+++ b/frontend-modern/src/utils/patrolRunPresentation.ts
@@ -1,7 +1,11 @@
import type { PatrolRunRecord, PatrolRunStatus, PatrolTriggerStatus } from '@/api/patrol';
import type { MetadataBadgeTone } from '@/components/shared/MetadataBadge';
import { formatIdentifierLabel } from '@/utils/textPresentation';
-import { getCanonicalScopeResourceIds } from '@/utils/patrolFormat';
+import {
+ formatDurationMs,
+ formatPatrolRuntimeFailureSummary,
+ getCanonicalScopeResourceIds,
+} from '@/utils/patrolFormat';
import {
getPatrolProviderSettingsAction,
type PatrolRuntimeActionPresentation,
@@ -22,6 +26,17 @@ export interface PatrolLatestRunPresentation {
timestamp?: string;
}
+export interface PatrolRunRecordSummaryPresentation {
+ action?: PatrolRunPrimaryActionPresentation;
+ outcome: string;
+ summary: string;
+}
+
+export interface PatrolRunOperatorRecordPresentation {
+ detail: string;
+ headline: string;
+}
+
export interface PatrolActivityBreakdown {
totalRuns: number;
fullPatrols: number;
@@ -35,6 +50,13 @@ export interface PatrolActivityBreakdown {
export type PatrolRunPrimaryActionPresentation = PatrolRuntimeActionPresentation;
+export const PATROL_FINDING_RECORD_UNAVAILABLE_LABEL = 'Finding record unavailable';
+
+export interface PatrolTriggerStatusSummaryOptions {
+ manualRunAvailable?: boolean;
+ manualRunBlockedReason?: string;
+}
+
function formatResourceCount(count: number, qualifier?: string): string {
const normalized = Math.max(0, count || 0);
const qualifierPrefix = qualifier ? `${qualifier} ` : '';
@@ -84,6 +106,130 @@ export function isPatrolRunHealthy(
return getEffectivePatrolRunStatus(status, errorCount) === 'healthy';
}
+function punctuateSentence(value: string): string {
+ const normalized = value.trim();
+ if (!normalized) return '';
+ return /[.!?]$/.test(normalized) ? normalized : `${normalized}.`;
+}
+
+function formatRunActionContext(
+ run: Pick<
+ PatrolRunRecord,
+ 'duration_ms' | 'effective_scope_resource_ids' | 'resources_checked' | 'scope_resource_ids'
+ >,
+): string {
+ const coverageSummary = getPatrolRunCoverageSummary(run);
+ const duration = formatDurationMs(run.duration_ms);
+ if (coverageSummary && duration) {
+ return `${coverageSummary} in ${duration}`;
+ }
+ if (coverageSummary) {
+ return coverageSummary;
+ }
+ if (duration) {
+ return `Patrol ran in ${duration}`;
+ }
+ return 'Patrol ran';
+}
+
+function formatIssueCount(count: number, singular: string = 'issue'): string {
+ const normalized = Math.max(0, count || 0);
+ return `${normalized} ${singular}${normalized === 1 ? '' : 's'}`;
+}
+
+export function getPatrolRunOperatorRecordPresentation(
+ run: Pick<
+ PatrolRunRecord,
+ | 'auto_fix_count'
+ | 'duration_ms'
+ | 'effective_scope_resource_ids'
+ | 'error_count'
+ | 'error_detail'
+ | 'error_summary'
+ | 'existing_findings'
+ | 'finding_ids'
+ | 'new_findings'
+ | 'resources_checked'
+ | 'resolved_findings'
+ | 'scope_resource_ids'
+ | 'status'
+ >,
+): PatrolRunOperatorRecordPresentation {
+ const context = formatRunActionContext(run);
+ const runtimeFailure = formatPatrolRuntimeFailureSummary({
+ errorSummary: run.error_summary,
+ errorDetail: run.error_detail,
+ errorCount: run.error_count,
+ });
+
+ const runHadRuntimeIssue =
+ Math.max(0, run.error_count || 0) > 0 || normalizePatrolRunStatus(run.status) === 'error';
+
+ if (runHadRuntimeIssue) {
+ return {
+ headline: 'Patrol needs attention',
+ detail: runtimeFailure
+ ? punctuateSentence(`${context}. Runtime issue: ${runtimeFailure}`)
+ : `${context}. It ended with issues that need review.`,
+ };
+ }
+
+ if (run.finding_ids === undefined) {
+ return {
+ headline: 'Completed check',
+ detail: `${context}. This older run has no issue list.`,
+ };
+ }
+
+ const fixedCount = Math.max(0, run.auto_fix_count || 0);
+ const newFindings = Math.max(0, run.new_findings || 0);
+ const resolvedFindings = Math.max(0, run.resolved_findings || 0);
+ const existingFindings = Math.max(0, run.existing_findings || 0);
+
+ if (fixedCount > 0) {
+ return {
+ headline: `Fixed ${formatIssueCount(fixedCount)}`,
+ detail:
+ newFindings > 0
+ ? `${context}. Found ${formatIssueCount(newFindings, 'new issue')} and fixed ${formatIssueCount(fixedCount)}.`
+ : `${context}. Fixed ${formatIssueCount(fixedCount)}.`,
+ };
+ }
+
+ if (resolvedFindings > 0) {
+ return {
+ headline: `Confirmed ${formatIssueCount(resolvedFindings)} resolved`,
+ detail: `${context}. Confirmed ${formatIssueCount(resolvedFindings)} resolved.`,
+ };
+ }
+
+ if (newFindings > 0) {
+ return {
+ headline: `Found ${formatIssueCount(newFindings, 'new issue')}`,
+ detail: `${context}. Ready for review.`,
+ };
+ }
+
+ if (existingFindings > 0) {
+ return {
+ headline: `${formatIssueCount(existingFindings)} still open`,
+ detail: `${context}. No new issues.`,
+ };
+ }
+
+ if (!isPatrolRunHealthy(run.status, run.error_count)) {
+ return {
+ headline: 'Patrol needs attention',
+ detail: `${context}. It ended with issues that need review.`,
+ };
+ }
+
+ return {
+ headline: 'All clear',
+ detail: `${context}. No issues recorded.`,
+ };
+}
+
export function getPatrolRunPrimaryActionPresentation(
run: Pick<PatrolRunRecord, 'error_count' | 'error_summary' | 'error_detail'>,
): PatrolRunPrimaryActionPresentation | undefined {
@@ -100,6 +246,77 @@ export function getPatrolRunPrimaryActionPresentation(
return getPatrolProviderSettingsAction();
}
+export function getPatrolRunRecordSummaryPresentation(
+ run: Pick<
+ PatrolRunRecord,
+ | 'auto_fix_count'
+ | 'duration_ms'
+ | 'effective_scope_resource_ids'
+ | 'error_count'
+ | 'error_detail'
+ | 'error_summary'
+ | 'existing_findings'
+ | 'finding_ids'
+ | 'new_findings'
+ | 'resources_checked'
+ | 'scope_resource_ids'
+ | 'status'
+ >,
+): PatrolRunRecordSummaryPresentation {
+ const coverageSummary = getPatrolRunCoverageSummary(run);
+ const duration = formatDurationMs(run.duration_ms);
+ const summarySubject = coverageSummary || 'Patrol ran';
+ const summary = duration ? `${summarySubject} in ${duration}.` : `${summarySubject}.`;
+ const runtimeFailure = formatPatrolRuntimeFailureSummary({
+ errorSummary: run.error_summary,
+ errorDetail: run.error_detail,
+ errorCount: run.error_count,
+ });
+ const action = getPatrolRunPrimaryActionPresentation(run);
+
+ if (!isPatrolRunHealthy(run.status, run.error_count)) {
+ return {
+ action,
+ summary,
+ outcome: runtimeFailure
+ ? punctuateSentence(`Patrol ended with a runtime issue: ${runtimeFailure}`)
+ : 'Patrol ended with issues requiring review.',
+ };
+ }
+
+ if (run.finding_ids === undefined) {
+ return {
+ summary,
+ outcome: 'This older run has no finding record, so Patrol cannot show its issue list.',
+ };
+ }
+
+ const newFindings = Math.max(0, run.new_findings || 0);
+ const existingFindings = Math.max(0, run.existing_findings || 0);
+ const fixedCount = Math.max(0, run.auto_fix_count || 0);
+
+ if (newFindings > 0) {
+ const fixedPart =
+ fixedCount > 0 ? ` Patrol fixed ${fixedCount} issue${fixedCount === 1 ? '' : 's'}.` : '';
+ return {
+ summary,
+ outcome: `Patrol found ${newFindings} new issue${newFindings === 1 ? '' : 's'}.${fixedPart}`,
+ };
+ }
+
+ if (existingFindings > 0) {
+ return {
+ summary,
+ outcome: `No new issues. ${existingFindings} existing issue${existingFindings === 1 ? ' remains' : 's remain'}.`,
+ };
+ }
+
+ return {
+ summary,
+ outcome: 'No issues recorded for this run.',
+ };
+}
+
export function getPatrolRunStatusPresentation(
status: PatrolRunStatus | string,
errorCount: number = 0,
@@ -154,11 +371,11 @@ export function getToolCallResultTextClass(success: boolean): string {
export function getPatrolRunKindLabel(type: string | undefined): string {
switch (normalizePatrolRunType(type)) {
case 'scoped':
- return 'Scoped run';
+ return 'Targeted check';
case 'verification':
- return 'Verification check';
+ return 'Follow-up check';
default:
- return isFullPatrolRunType(type) ? 'Full patrol' : 'Patrol run';
+ return isFullPatrolRunType(type) ? 'Patrol check' : 'Patrol run';
}
}
@@ -185,16 +402,30 @@ export function getPatrolLatestRunPresentation(
};
}
+function isAlreadyRunningBlockedReason(reason?: string): boolean {
+ return /\balready running\b|\brun\b.*\bin progress\b/i.test(reason?.trim() || '');
+}
+
+function getManualRunBlockedTriggerSummary(reason?: string): string | undefined {
+ if (isAlreadyRunningBlockedReason(reason)) {
+ return 'A Patrol run is already in progress. New automatic and manual runs are paused until it finishes.';
+ }
+ return undefined;
+}
+
export function getPatrolTriggerStatusSummary(
status: PatrolTriggerStatus | undefined,
+ options: PatrolTriggerStatusSummaryOptions = {},
): string | undefined {
if (!status) {
return undefined;
}
if (status.event_triggers_blocked) {
- const blockMessage = status.event_triggers_blocked_message?.trim();
- return blockMessage || 'Automatic Patrol checks from alerts and anomalies are paused';
+ if (options.manualRunAvailable === false) {
+ return getManualRunBlockedTriggerSummary(options.manualRunBlockedReason);
+ }
+ return undefined;
}
const notes: string[] = [];
@@ -271,27 +502,45 @@ export function getPatrolActivityBreakdown(
);
}
-function formatCountLabel(count: number, label: string): string {
- return `${count} ${label}`;
+function formatCountLabel(count: number, singular: string, plural?: string): string {
+ return `${count} ${count === 1 ? singular : (plural ?? `${singular}s`)}`;
}
export function formatPatrolActivityBreakdown(summary: PatrolActivityBreakdown): string {
const segments: string[] = [];
- if (summary.fullPatrols > 0) segments.push(formatCountLabel(summary.fullPatrols, 'full'));
+ if (summary.fullPatrols > 0) {
+ segments.push(formatCountLabel(summary.fullPatrols, 'full check', 'full checks'));
+ }
if (summary.alertTriggeredRuns > 0) {
- segments.push(formatCountLabel(summary.alertTriggeredRuns, 'alert-triggered'));
+ segments.push(
+ formatCountLabel(
+ summary.alertTriggeredRuns,
+ 'alert-triggered check',
+ 'alert-triggered checks',
+ ),
+ );
}
if (summary.anomalyTriggeredRuns > 0) {
- segments.push(formatCountLabel(summary.anomalyTriggeredRuns, 'anomaly-triggered'));
+ segments.push(
+ formatCountLabel(
+ summary.anomalyTriggeredRuns,
+ 'anomaly-triggered check',
+ 'anomaly-triggered checks',
+ ),
+ );
}
if (summary.alertClearedRuns > 0) {
- segments.push(formatCountLabel(summary.alertClearedRuns, 'alert-cleared'));
+ segments.push(
+ formatCountLabel(summary.alertClearedRuns, 'alert-cleared check', 'alert-cleared checks'),
+ );
}
if (summary.verificationChecks > 0) {
- segments.push(formatCountLabel(summary.verificationChecks, 'verification'));
+ segments.push(
+ formatCountLabel(summary.verificationChecks, 'follow-up check', 'follow-up checks'),
+ );
}
if (summary.otherScopedRuns > 0) {
- segments.push(formatCountLabel(summary.otherScopedRuns, 'other scoped'));
+ segments.push(formatCountLabel(summary.otherScopedRuns, 'targeted check', 'targeted checks'));
}
return segments.join(', ');
}
@@ -338,7 +587,7 @@ export function getPatrolRunResourcesHeading(
}
export function getRunHistoryLoadingState(): string {
- return 'Loading run history…';
+ return 'Loading history...';
}
export function getRunHistorySelectionHint(
@@ -346,14 +595,14 @@ export function getRunHistorySelectionHint(
selectedRun?: Pick<PatrolRunRecord, 'finding_ids'> | null,
): string {
if (selectedRun && selectedRun.finding_ids === undefined) {
- return 'Selected run predates findings snapshots; run-scoped findings cannot be fully verified.';
+ return 'This older check has no issue list.';
}
if (runs.some((run) => run.finding_ids === undefined)) {
- return 'Select a run to filter findings when available. Some older runs do not include findings snapshots.';
+ return 'Open a check to review what Patrol found. Older checks may not have issue lists.';
}
- return 'Select a run to filter findings to that snapshot';
+ return 'Open a check to review what Patrol found.';
}
export function getToolCallsLoadingState(): string {
diff --git a/frontend-modern/src/utils/patrolRuntimeActions.ts b/frontend-modern/src/utils/patrolRuntimeActions.ts
index 550c001acd..5ce577da72 100644
--- a/frontend-modern/src/utils/patrolRuntimeActions.ts
+++ b/frontend-modern/src/utils/patrolRuntimeActions.ts
@@ -1,11 +1,13 @@
+import { SETTINGS_PROVIDER_MODELS_PATH } from '@/components/Settings/settingsNavigationModel';
+
export interface PatrolRuntimeActionPresentation {
label: string;
href: string;
}
export const PATROL_PROVIDER_SETTINGS_ACTION: PatrolRuntimeActionPresentation = {
- label: 'Open Patrol provider settings',
- href: '/settings/system-ai',
+ label: 'Open Provider & Models',
+ href: SETTINGS_PROVIDER_MODELS_PATH,
};
export const getPatrolProviderSettingsAction = (): PatrolRuntimeActionPresentation => ({
diff --git a/frontend-modern/src/utils/patrolRuntimePresentation.ts b/frontend-modern/src/utils/patrolRuntimePresentation.ts
index e87ed9b035..9a256b4a67 100644
--- a/frontend-modern/src/utils/patrolRuntimePresentation.ts
+++ b/frontend-modern/src/utils/patrolRuntimePresentation.ts
@@ -33,32 +33,32 @@ export function getPatrolRuntimePresentation(
switch (runtimeState) {
case 'blocked':
return {
- label: 'Patrol Paused',
+ label: 'Patrol paused',
title: 'Patrol paused',
description:
normalizedBlockedReason ||
- 'Pulse Patrol cannot start new verification until the blocking condition is cleared.',
+ 'Patrol cannot check infrastructure until the blocking condition is cleared.',
tone: 'warning',
};
case 'disabled':
return {
- label: 'Patrol Disabled',
+ label: 'Patrol disabled',
title: 'Patrol disabled',
- description: 'Enable Patrol to resume continuous verification.',
+ description: 'Enable Patrol to resume checks.',
tone: 'info',
};
case 'running':
return {
- label: 'Patrol Running',
+ label: 'Patrol enabled',
title: 'Patrol running',
- description: 'Pulse Patrol is actively verifying your infrastructure.',
+ description: 'Patrol is checking your infrastructure now.',
tone: 'info',
};
case 'unavailable':
return {
- label: 'Patrol Unavailable',
+ label: 'Patrol unavailable',
title: 'Patrol unavailable',
- description: 'Pulse Patrol is not ready yet. Check Patrol provider settings and runtime availability.',
+ description: 'Patrol is not ready yet. Check Provider & Models and runtime availability.',
tone: 'error',
};
case 'active':
@@ -66,7 +66,7 @@ export function getPatrolRuntimePresentation(
return {
label: 'Patrol enabled',
title: 'Patrol enabled',
- description: 'Pulse Patrol is ready to continuously verify your infrastructure.',
+ description: 'Patrol is ready to check your infrastructure.',
tone: 'info',
};
}
diff --git a/frontend-modern/src/utils/patrolSummaryPresentation.ts b/frontend-modern/src/utils/patrolSummaryPresentation.ts
index 2cb842ea3f..3deb13c724 100644
--- a/frontend-modern/src/utils/patrolSummaryPresentation.ts
+++ b/frontend-modern/src/utils/patrolSummaryPresentation.ts
@@ -74,7 +74,7 @@ export interface PatrolRecencyPresentation {
timestamp?: string;
// resourcesChecked is the raw coverage signal for the most recent
// completed run. resourcesCheckedLabel is the operator-facing phrase; it
- // says "verified" only for successful full patrols and uses "checked" for
+ // says "verified" only for successful full checks and uses "checked" for
// limited or errored activity.
resourcesChecked?: number;
resourcesCheckedLabel?: string;
@@ -85,7 +85,17 @@ type PatrolAssessmentFinding = Pick<
'resourceId' | 'resourceName' | 'title' | 'severity' | 'status'
>;
-export const PATROL_NO_ISSUES_LABEL = 'No issues found';
+export interface PatrolCompactAssessmentLabelInput {
+ assessmentLabel: string;
+ overallHealth?: IntelligenceHealthScore;
+ activeFindings?: PatrolAssessmentFinding[];
+ totalActive?: number;
+ historicalRegressionCount?: number;
+ includeHealthScore?: boolean;
+}
+
+export const PATROL_NO_ISSUES_LABEL = 'No active issues';
+const PATROL_STATUS_EYEBROW = 'Status';
const QUIET_ICON_CONTAINER = 'bg-surface border-border';
const QUIET_ICON = 'text-muted';
@@ -161,10 +171,7 @@ function getHealthSummaryTone(overallHealth: IntelligenceHealthScore): SemanticT
}
function getCoverageDescription(overallHealth: IntelligenceHealthScore | undefined): string {
- return (
- overallHealth?.prediction?.trim() ||
- 'Patrol coverage is incomplete, so overall infrastructure health is not fully verified.'
- );
+ return overallHealth?.prediction?.trim() || 'Patrol has not finished a current check.';
}
function formatFindingCount(count: number, severity: 'critical' | 'warning'): string {
@@ -258,6 +265,50 @@ export function getPatrolScoreChipLabel(args: {
return 'Health';
}
+function formatIssueLabel(count: number, label: string): string {
+ return `${count} ${label} issue${count === 1 ? '' : 's'}`;
+}
+
+export function getPatrolCompactAssessmentLabel(input: PatrolCompactAssessmentLabelInput): string {
+ const classified = classifyActiveFindings(input.activeFindings);
+ const parts: string[] = [];
+
+ if (classified.infrastructureCritical > 0) {
+ parts.push(formatIssueLabel(classified.infrastructureCritical, 'critical'));
+ }
+
+ if (classified.infrastructureWarning > 0) {
+ parts.push(formatIssueLabel(classified.infrastructureWarning, 'warning'));
+ }
+
+ if (classified.runtimeTotal > 0) {
+ parts.push(
+ `${classified.runtimeTotal} Patrol runtime issue${classified.runtimeTotal === 1 ? '' : 's'}`,
+ );
+ }
+
+ if (parts.length === 0 && (input.totalActive ?? 0) > 0) {
+ parts.push(formatIssueLabel(input.totalActive ?? 0, 'active'));
+ }
+
+ if (parts.length === 0) {
+ parts.push(input.assessmentLabel);
+ }
+
+ const historicalRegressionCount = input.historicalRegressionCount ?? 0;
+ if (historicalRegressionCount > 0) {
+ parts.push(
+ `${historicalRegressionCount} past regression${historicalRegressionCount === 1 ? '' : 's'}`,
+ );
+ }
+
+ if (input.includeHealthScore !== false && input.overallHealth) {
+ parts.push(`health score ${Math.round(input.overallHealth.score)}/100`);
+ }
+
+ return parts.join(' · ');
+}
+
export function getPatrolAssessmentAction(args: {
activeFindings?: PatrolAssessmentFinding[];
}): PatrolAssessmentAction | undefined {
@@ -304,6 +355,9 @@ function predictionReadsAsCoverageGap(prediction: string | undefined): boolean {
normalized.includes('limited to targeted') ||
normalized.includes('runs encountered errors') ||
normalized.includes('ended with errors') ||
+ normalized.includes('current issue list') ||
+ normalized.includes('current full issue list') ||
+ normalized.includes('current health may be incomplete') ||
normalized.includes('summary may be incomplete')
);
}
@@ -350,7 +404,7 @@ function getFindingAssessmentDescription(args: {
: `Patrol has an active runtime issue: ${runtimeLabel}.`;
if (hasCoverageGap) {
- return `${runtimeSummary} Recent coverage is also incomplete, so the rest of your infrastructure is not fully verified.`;
+ return `${runtimeSummary} Recent coverage is incomplete. Run Patrol to check everything.`;
}
const prediction = args.overallHealth?.prediction?.trim();
@@ -388,7 +442,7 @@ function getFindingAssessmentDescription(args: {
: `Patrol surfaced ${formatFindingCount(warningFindings, 'warning')}.`;
if (hasCoverageGap) {
- return `${findingSummary} Recent coverage is also incomplete, so the rest of your infrastructure is not fully verified.`;
+ return `${findingSummary} Recent coverage is incomplete. Run Patrol to check everything.`;
}
const prediction = args.overallHealth?.prediction?.trim();
@@ -476,6 +530,16 @@ export function getPatrolAssessmentPresentation(args: {
const classified = classifyActiveFindings(args.activeFindings);
const hasVerifiedFullCoverage = hasSuccessfulFullCoverageRun(args.runs);
+ if (args.runtimeState === 'running') {
+ return {
+ title: 'Patrol running',
+ description: 'Patrol is checking your infrastructure now.',
+ eyebrow: PATROL_STATUS_EYEBROW,
+ compactLabel: 'Patrol is checking now',
+ tone: 'info',
+ };
+ }
+
if (
args.runtimeState === 'blocked' ||
args.runtimeState === 'disabled' ||
@@ -496,7 +560,7 @@ export function getPatrolAssessmentPresentation(args: {
return {
title: 'Critical Patrol runtime issue',
description: getFindingAssessmentDescription(args),
- eyebrow: 'Patrol assessment',
+ eyebrow: PATROL_STATUS_EYEBROW,
compactLabel: 'Patrol runtime issue',
tone: 'error',
};
@@ -505,7 +569,7 @@ export function getPatrolAssessmentPresentation(args: {
return {
title: 'Critical issues detected',
description: getFindingAssessmentDescription(args),
- eyebrow: 'Patrol assessment',
+ eyebrow: PATROL_STATUS_EYEBROW,
compactLabel: 'Issues detected',
tone: 'error',
};
@@ -516,7 +580,7 @@ export function getPatrolAssessmentPresentation(args: {
return {
title: 'Patrol runtime issue',
description: getFindingAssessmentDescription(args),
- eyebrow: 'Patrol assessment',
+ eyebrow: PATROL_STATUS_EYEBROW,
compactLabel: 'Patrol runtime issue',
tone: 'warning',
};
@@ -525,7 +589,7 @@ export function getPatrolAssessmentPresentation(args: {
return {
title: 'Issues detected',
description: getFindingAssessmentDescription(args),
- eyebrow: 'Patrol assessment',
+ eyebrow: PATROL_STATUS_EYEBROW,
compactLabel: 'Issues detected',
tone: 'warning',
};
@@ -538,7 +602,7 @@ export function getPatrolAssessmentPresentation(args: {
return {
title: 'Coverage incomplete',
description: getCoverageDescription(args.overallHealth),
- eyebrow: 'Patrol assessment',
+ eyebrow: PATROL_STATUS_EYEBROW,
compactLabel: 'Coverage incomplete',
tone: getHealthSummaryTone(args.overallHealth),
};
@@ -551,8 +615,8 @@ export function getPatrolAssessmentPresentation(args: {
description:
prediction && !(hasVerifiedFullCoverage && predictionReadsAsCoverageGap(prediction))
? prediction
- : 'Patrol assessment still needs attention.',
- eyebrow: 'Patrol assessment',
+ : 'Patrol still needs attention.',
+ eyebrow: PATROL_STATUS_EYEBROW,
compactLabel: 'Health requires attention',
tone: getHealthSummaryTone(args.overallHealth),
};
@@ -563,7 +627,7 @@ export function getPatrolAssessmentPresentation(args: {
description:
args.overallHealth?.prediction?.trim() ||
'Infrastructure is healthy with no significant issues detected.',
- eyebrow: 'Patrol assessment',
+ eyebrow: PATROL_STATUS_EYEBROW,
compactLabel: PATROL_NO_ISSUES_LABEL,
tone: 'success',
};
@@ -596,12 +660,12 @@ export function getPatrolVerificationPresentation(args: {
const resourcesChecked = recentFullRun.resources_checked || 0;
if (hasRunErrors(recentFullRun)) {
return {
- title: 'Full patrol needs review',
+ title: 'Patrol check needs review',
description:
resourcesChecked > 0
- ? `The most recent full patrol checked ${resourcesChecked} resource${resourcesChecked === 1 ? '' : 's'} but ended with ${recentFullRun.error_count} error${recentFullRun.error_count === 1 ? '' : 's'}.`
- : 'The most recent full patrol ended with errors, so Patrol has not fully re-verified your infrastructure.',
- compactLabel: 'Verification limited',
+ ? `The most recent Patrol check covered ${resourcesChecked} resource${resourcesChecked === 1 ? '' : 's'} but ended with ${recentFullRun.error_count} error${recentFullRun.error_count === 1 ? '' : 's'}.`
+ : 'The most recent Patrol check ended with errors.',
+ compactLabel: 'Check needs review',
tone: 'warning',
lastFullRunAt: recentFullRun.completed_at,
activityMixLabel,
@@ -609,12 +673,12 @@ export function getPatrolVerificationPresentation(args: {
}
return {
- title: 'Recently verified',
+ title: 'Recently checked',
description:
resourcesChecked > 0
- ? `The most recent full patrol completed successfully and checked ${resourcesChecked} resource${resourcesChecked === 1 ? '' : 's'}.`
- : 'The most recent full patrol completed successfully.',
- compactLabel: 'Recently verified',
+ ? `The most recent Patrol check completed successfully and covered ${resourcesChecked} resource${resourcesChecked === 1 ? '' : 's'}.`
+ : 'The most recent Patrol check completed successfully.',
+ compactLabel: 'Recently checked',
tone: 'success',
lastFullRunAt: recentFullRun.completed_at,
activityMixLabel,
@@ -625,35 +689,35 @@ export function getPatrolVerificationPresentation(args: {
if (recentLimitedRun) {
const resourcesChecked = recentLimitedRun.resources_checked || 0;
let description =
- 'Recent activity was limited to targeted Patrol checks, so Patrol has not recently re-verified your full infrastructure.';
+ 'Recent activity only checked part of your infrastructure. Run Patrol to check everything.';
if (isVerificationPatrolRun(recentLimitedRun)) {
description =
resourcesChecked > 0
- ? `Recent activity was limited to verification checks over ${resourcesChecked} resource${resourcesChecked === 1 ? '' : 's'}, so Patrol has not recently re-verified your full infrastructure.`
- : 'Recent activity was limited to verification checks, so Patrol has not recently re-verified your full infrastructure.';
+ ? `Recent follow-up checks covered ${resourcesChecked} resource${resourcesChecked === 1 ? '' : 's'}. Run Patrol to check everything.`
+ : 'Recent follow-up checks did not cover your full infrastructure. Run Patrol to check everything.';
} else if (isScopedPatrolRun(recentLimitedRun)) {
description =
resourcesChecked > 0
- ? `Recent activity was limited to scoped ${recentLimitedRun.trigger_reason ? String(recentLimitedRun.trigger_reason).replace(/_/g, ' ') : 'patrol'} runs over ${resourcesChecked} resource${resourcesChecked === 1 ? '' : 's'}, so Patrol has not recently re-verified your full infrastructure.`
- : 'Recent activity was limited to scoped patrol runs, so Patrol has not recently re-verified your full infrastructure.';
+ ? `Recent targeted checks covered ${resourcesChecked} resource${resourcesChecked === 1 ? '' : 's'}. Run Patrol to check everything.`
+ : 'Recent targeted checks did not cover your full infrastructure. Run Patrol to check everything.';
} else if (resourcesChecked > 0) {
- description = `Recent activity was limited to targeted Patrol checks over ${resourcesChecked} resource${resourcesChecked === 1 ? '' : 's'}, so Patrol has not recently re-verified your full infrastructure.`;
+ description = `Recent targeted checks covered ${resourcesChecked} resource${resourcesChecked === 1 ? '' : 's'}. Run Patrol to check everything.`;
}
return {
- title: 'No recent full patrol',
+ title: 'Needs full check',
description,
- compactLabel: 'Partial verification',
+ compactLabel: 'Partial check',
tone: 'warning',
activityMixLabel,
};
}
return {
- title: 'Verification pending',
- description: 'Patrol has not completed a recent full verification run yet.',
- compactLabel: 'Verification pending',
+ title: 'Run Patrol to check',
+ description: 'Patrol has not completed a check yet.',
+ compactLabel: 'Check pending',
tone: 'info',
};
}
@@ -668,7 +732,7 @@ export function getPatrolRecencyPresentation(args: {
const resourcesChecked = latestCompletedRun.resources_checked || 0;
const resourcesCheckedLabel = formatRecencyResourcesCheckedLabel(latestCompletedRun);
return {
- label: isFullPatrolRun(latestCompletedRun) ? 'Last full patrol' : 'Last activity',
+ label: 'Last check',
timestamp: latestCompletedRun.completed_at,
resourcesChecked: resourcesChecked > 0 ? resourcesChecked : undefined,
resourcesCheckedLabel,
@@ -683,13 +747,13 @@ export function getPatrolRecencyPresentation(args: {
const patrolMs = Date.parse(lastPatrolAt);
if (Number.isNaN(activityMs) && !Number.isNaN(patrolMs)) {
return {
- label: 'Last full patrol',
+ label: 'Last check',
timestamp: lastPatrolAt,
};
}
if (!Number.isNaN(activityMs) && !Number.isNaN(patrolMs) && patrolMs >= activityMs) {
return {
- label: 'Last full patrol',
+ label: 'Last check',
timestamp: lastPatrolAt,
};
}
@@ -708,7 +772,7 @@ export function getPatrolRecencyPresentation(args: {
if (lastPatrolAt) {
return {
- label: 'Last full patrol',
+ label: 'Last check',
timestamp: lastPatrolAt,
};
}
diff --git a/frontend-modern/src/utils/pricingHandoff.ts b/frontend-modern/src/utils/pricingHandoff.ts
index 339fac4117..96efd4e4df 100644
--- a/frontend-modern/src/utils/pricingHandoff.ts
+++ b/frontend-modern/src/utils/pricingHandoff.ts
@@ -10,7 +10,10 @@ const DEFAULT_MANAGED_HOSTING_REQUEST_URL =
'mailto:[email protected]?subject=Pulse%20Managed%20Hosting';
export const SELF_HOSTED_PURCHASE_START_PATH = '/auth/license-purchase-start';
-export const SELF_HOSTED_PRO_BILLING_ROUTE = '/settings/system/billing';
+export const LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE = '/settings/system/billing';
+export const LEGACY_SELF_HOSTED_PRO_BILLING_PLAN_ROUTE = `${LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE}/plan`;
+export const LEGACY_SELF_HOSTED_PRO_BILLING_USAGE_ROUTE = `${LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE}/usage`;
+export const SELF_HOSTED_PRO_BILLING_ROUTE = '/settings/pulse-intelligence/billing';
export const SELF_HOSTED_PRO_BILLING_PLAN_ROUTE = `${SELF_HOSTED_PRO_BILLING_ROUTE}/plan`;
export const SELF_HOSTED_PRO_BILLING_USAGE_ROUTE = `${SELF_HOSTED_PRO_BILLING_ROUTE}/usage`;
export const SELF_HOSTED_PRO_BILLING_PLAN_SECTION_ID = 'pulse-pro-plan';
@@ -58,7 +61,7 @@ const IN_PRODUCT_PRICING_DESTINATIONS: Record<string, string> = {
mobile_app: SELF_HOSTED_PRO_BILLING_PLAN_HREF,
push_notifications: SELF_HOSTED_PRO_BILLING_PLAN_HREF,
ai_alerts: SELF_HOSTED_PRO_BILLING_PLAN_HREF,
- ai_autofix: SELF_HOSTED_PRO_BILLING_PLAN_HREF,
+ ai_autofix: SELF_HOSTED_PRO_BILLING_PLAN_SELECTION_HREF,
relay: SELF_HOSTED_PRO_BILLING_PLAN_HREF,
rbac: SELF_HOSTED_PRO_BILLING_PLAN_HREF,
audit_logging: SELF_HOSTED_PRO_BILLING_PLAN_HREF,
@@ -99,7 +102,11 @@ function isSelfHostedBillingPath(pathname: string): boolean {
normalized === SELF_HOSTED_PRO_BILLING_ROUTE ||
normalized === SELF_HOSTED_PRO_BILLING_PLAN_ROUTE ||
normalized === SELF_HOSTED_PRO_BILLING_USAGE_ROUTE ||
- normalized.startsWith(`${SELF_HOSTED_PRO_BILLING_ROUTE}/`)
+ normalized.startsWith(`${SELF_HOSTED_PRO_BILLING_ROUTE}/`) ||
+ normalized === LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE ||
+ normalized === LEGACY_SELF_HOSTED_PRO_BILLING_PLAN_ROUTE ||
+ normalized === LEGACY_SELF_HOSTED_PRO_BILLING_USAGE_ROUTE ||
+ normalized.startsWith(`${LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE}/`)
);
}
@@ -262,13 +269,22 @@ export function resolveSelfHostedBillingSection(
): SelfHostedBillingSection {
const normalizedPath = normalizeSettingsLikePath(pathname);
- if (normalizedPath === SELF_HOSTED_PRO_BILLING_USAGE_ROUTE) {
+ if (
+ normalizedPath === SELF_HOSTED_PRO_BILLING_USAGE_ROUTE ||
+ normalizedPath === LEGACY_SELF_HOSTED_PRO_BILLING_USAGE_ROUTE
+ ) {
return 'usage';
}
- if (normalizedPath === SELF_HOSTED_PRO_BILLING_PLAN_ROUTE) {
+ if (
+ normalizedPath === SELF_HOSTED_PRO_BILLING_PLAN_ROUTE ||
+ normalizedPath === LEGACY_SELF_HOSTED_PRO_BILLING_PLAN_ROUTE
+ ) {
return 'plan';
}
- if (normalizedPath !== SELF_HOSTED_PRO_BILLING_ROUTE) {
+ if (
+ normalizedPath !== SELF_HOSTED_PRO_BILLING_ROUTE &&
+ normalizedPath !== LEGACY_SELF_HOSTED_PRO_BILLING_ROUTE
+ ) {
return 'plan';
}
diff --git a/frontend-modern/src/utils/resourceChangePresentation.ts b/frontend-modern/src/utils/resourceChangePresentation.ts
index 755faa5a68..dd2dc03057 100644
--- a/frontend-modern/src/utils/resourceChangePresentation.ts
+++ b/frontend-modern/src/utils/resourceChangePresentation.ts
@@ -261,7 +261,12 @@ export function formatResourceChangeHeadline(change: ResourceChange): string {
return `${formatResourceChangeKind(change.kind)}: ${change.from} → ${change.to}`;
}
if (change.reason) {
- return `${formatResourceChangeKind(change.kind)}: ${change.reason}`;
+ const kindLabel = formatResourceChangeKind(change.kind);
+ const normalizedReason = change.reason.trim();
+ if (normalizedReason.toLowerCase().startsWith(`${kindLabel.toLowerCase()}:`)) {
+ return normalizedReason;
+ }
+ return `${kindLabel}: ${normalizedReason}`;
}
return `${formatResourceChangeKind(change.kind)}: ${change.resourceId}`;
}
diff --git a/frontend-modern/src/utils/resourceCorrelationPresentation.ts b/frontend-modern/src/utils/resourceCorrelationPresentation.ts
index feba4c2f79..e53d7de96d 100644
--- a/frontend-modern/src/utils/resourceCorrelationPresentation.ts
+++ b/frontend-modern/src/utils/resourceCorrelationPresentation.ts
@@ -30,7 +30,12 @@ const parseGoDurationMs = (value: string): number | null => {
};
const humanizeCorrelationToken = (value?: string): string => {
- return humanizeArrowDelimitedLabel(value, { fallback: 'Correlation' });
+ const normalized = value?.trim() ?? '';
+ const readable =
+ normalized && normalized === normalized.toUpperCase() && /[A-Z]/.test(normalized)
+ ? normalized.toLowerCase()
+ : normalized;
+ return humanizeArrowDelimitedLabel(readable, { fallback: 'Correlation' });
};
export function formatResourceCorrelationEndpoint(
diff --git a/frontend-modern/src/utils/selfHostedFeatureCatalog.generated.ts b/frontend-modern/src/utils/selfHostedFeatureCatalog.generated.ts
index 0f35257bcc..c0f380f616 100644
--- a/frontend-modern/src/utils/selfHostedFeatureCatalog.generated.ts
+++ b/frontend-modern/src/utils/selfHostedFeatureCatalog.generated.ts
@@ -131,8 +131,8 @@ export const SELF_HOSTED_FEATURE_CATALOG: readonly GeneratedSelfHostedFeatureCat
},
{
"key": "ai_alerts",
- "displayName": "Alert Analysis",
- "comparisonName": "Alert Root-Cause Analysis",
+ "displayName": "Patrol Investigates Issues",
+ "comparisonName": "Patrol Investigates Issues",
"showInComparisonTable": true,
"displayableInSelfHostedPlan": true,
"roles": {
@@ -148,8 +148,8 @@ export const SELF_HOSTED_FEATURE_CATALOG: readonly GeneratedSelfHostedFeatureCat
},
{
"key": "ai_autofix",
- "displayName": "Safe Remediation Workflows",
- "comparisonName": "Safe Remediation Workflows",
+ "displayName": "Patrol Handles Safe Fixes",
+ "comparisonName": "Patrol Handles Safe Fixes",
"showInComparisonTable": true,
"displayableInSelfHostedPlan": true,
"roles": {
diff --git a/frontend-modern/src/utils/selfHostedPlans.ts b/frontend-modern/src/utils/selfHostedPlans.ts
index 73d9efb3e8..ab7870d311 100644
--- a/frontend-modern/src/utils/selfHostedPlans.ts
+++ b/frontend-modern/src/utils/selfHostedPlans.ts
@@ -80,11 +80,11 @@ export function getSelfHostedPlanEntitlementSummary(
): string {
switch (tier) {
case 'community':
- return `${planLabel} is active on this instance. It includes self-hosted monitoring, 7-day metric history, Pulse Patrol (BYOK), update alerts, and SSO.`;
+ return `${planLabel} is active on this instance. It includes self-hosted monitoring, 7-day metric history, watch-only Patrol, update alerts, and SSO.`;
case 'relay':
- return `${planLabel} is active on this instance. Remote web access, Pulse Mobile pairing, push notifications, and longer history are available right now.`;
+ return `${planLabel} is active on this instance. It includes remote web access, Pulse Mobile pairing, push notifications, and 14-day metric history.`;
case 'pro':
- return `${planLabel} is active on this instance. Root-cause analysis, safe remediation workflows, 90-day history, and admin/reporting extras are available right now.`;
+ return `${planLabel} is active on this instance. It includes Patrol modes, 90-day metric history, RBAC, audit logs, reports, and agent profiles.`;
}
}
@@ -104,21 +104,21 @@ export const SELF_HOSTED_PLAN_DEFINITIONS: readonly SelfHostedPlanDefinition[] =
price: 'Free forever',
subline: 'Core monitoring included',
metricHistoryDays: 7,
- billingExtrasSummary: 'Patrol, alerts, and SSO',
+ billingExtrasSummary: 'Watch-only Patrol, alerts, and SSO',
entitlementSummary: getSelfHostedPlanEntitlementSummary('community'),
entitlementHighlights: [
'Real-time monitoring',
'7-day metric history',
- 'Pulse Patrol (BYOK)',
+ 'Watch-only Patrol',
'Update alerts',
],
includedExtras: [],
comparisonSummary:
- 'Community covers self-hosted monitoring and core operations on this instance.',
+ 'Community covers self-hosted monitoring and watch-only Patrol on this instance.',
highlights: [
'Real-time monitoring',
'7-day metric history',
- 'Pulse Patrol (BYOK)',
+ 'Watch-only Patrol',
'Update alerts',
'SSO (OIDC/SAML)',
'Community support',
@@ -134,8 +134,7 @@ export const SELF_HOSTED_PLAN_DEFINITIONS: readonly SelfHostedPlanDefinition[] =
entitlementSummary: getSelfHostedPlanEntitlementSummary('relay'),
entitlementHighlights: getTierEntitlementHighlights('relay', 14),
includedExtras: [],
- comparisonSummary:
- 'Reach your Pulse web UI securely from anywhere, pair supported Pulse Mobile clients for handoff and push notifications, and keep 14 days of history.',
+ comparisonSummary: 'Remote web access, Pulse Mobile pairing, push notifications, and 14-day metric history.',
highlights: [
'Everything in Community',
'Remote web access via Relay',
@@ -151,16 +150,17 @@ export const SELF_HOSTED_PLAN_DEFINITIONS: readonly SelfHostedPlanDefinition[] =
price: '$79/year',
subline: 'or $8.99/month',
metricHistoryDays: 90,
- billingExtrasSummary: 'Analysis, remediation, and admin controls',
+ billingExtrasSummary: 'Patrol modes, history, and admin controls',
entitlementSummary: getSelfHostedPlanEntitlementSummary('pro'),
entitlementHighlights: getTierEntitlementHighlights('pro', 90),
includedExtras: getTierIncludedExtras('pro'),
comparisonSummary:
- 'Add operations features on top of free monitoring: root-cause analysis, safe remediation workflows, 90-day history, RBAC, audit logging, reporting, and agent profiles.',
+ 'Patrol modes, 90-day metric history, RBAC, audit logs, reports, and agent profiles.',
highlights: [
'Everything in Relay',
- 'Alert root-cause analysis',
- 'Safe remediation workflows',
+ 'Choose Patrol mode',
+ 'Patrol investigates issues',
+ 'Patrol handles safe fixes',
'90-day metric history',
'RBAC and audit logging',
'Agent profiles · PDF/CSV reports',
@@ -195,8 +195,7 @@ export function getSelfHostedPlanDefinitionForBillingTier(
export const SELF_HOSTED_COMMERCIAL_PRESENTATION: SelfHostedCommercialPresentation = {
pageTitle: 'Pricing',
- pageDescription:
- 'Self-hosted Pulse includes core monitoring for free. Relay adds secure remote access to the Pulse web UI, Pulse Mobile pairing, and push notifications, while Pro adds root-cause analysis, safe remediation workflows, 90-day history, and admin/reporting extras.',
+ pageDescription: 'Self-hosted plans and included capabilities.',
mostPopularBadge: 'Most Popular',
currentPlanLabel: 'Current Plan',
includedLabel: 'Included',