Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Add settings discovery refresh action
rcourtman976e7c6b4280
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex ddc7383b0a..d5c1033106 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -553,7 +553,7 @@ profile and assignment columns, but embedded table framing must route throughmismatched, and signature-invalid grants through agent metrics.9. Add or change profile management, the extracted agent profiles runtime owner, the agent profile settings catalog, the infrastructure source-manager landing, the pure unified-agent inventory/install model, the connections-ledger workspace shell, the unified ConnectionEditor and its per-type credential slots, route model, shared install section owner, the shared direct-node/discovery infrastructure settings owners plus their model, shared frontend install-command assembly, Proxmox setup/install API transport, TrueNAS platform-connection management, VMware platform-connection management, the shared monitored-system impact preview shell for those platform connections, setup-completion install handoff transport, deploy-fallback manual install transport, and fleet-control presentation through `frontend-modern/src/api/agentProfiles.ts`, `frontend-modern/src/api/nodes.ts`, `frontend-modern/src/components/Settings/AgentProfilesPanel.tsx`, `frontend-modern/src/components/Settings/agentProfileSettings.ts`, `frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts`, `frontend-modern/src/components/Settings/ConnectionsTable.tsx`, `frontend-modern/src/components/Settings/connectionsTableModel.ts`, `frontend-modern/src/components/Settings/useConnectionsLedger.ts`, `frontend-modern/src/components/Settings/useConnectionRowActions.ts`, `frontend-modern/src/components/Settings/ConnectionEditor/ConnectionEditor.tsx`, `frontend-modern/src/components/Settings/ConnectionEditor/AddressProbeStep.tsx`, `frontend-modern/src/components/Settings/ConnectionEditor/useConnectionEditor.ts`, `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCredentialSlot.tsx`, `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/TrueNASCredentialSlot.tsx`, `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/VMwareCredentialSlot.tsx`, `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx`, `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx`, `frontend-modern/src/components/Settings/InfrastructureSourceManager.tsx`, `frontend-modern/src/components/Settings/infrastructureWorkspaceModel.ts`, `frontend-modern/src/components/Settings/MonitoredSystemImpactPreview.tsx`, `frontend-modern/src/components/Settings/platformConnectionsModel.ts`, `frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts`, `frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts`, `frontend-modern/src/components/Settings/proxmoxSettingsModel.ts`, `frontend-modern/src/components/Settings/ConfiguredNodeTables.tsx`, `frontend-modern/src/components/Settings/SettingsSectionNav.tsx`, `frontend-modern/src/components/Settings/infrastructureSettingsModel.ts`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts`, `frontend-modern/src/components/Settings/nodeModalModel.ts`, `frontend-modern/src/components/Settings/useNodeModalState.ts`, `frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx`, and `frontend-modern/src/utils/agentInstallCommand.ts`. Phase 9 retired the legacy reporting/inventory surface (InfrastructureOperationsController, InfrastructureInventorySection, InfrastructureActiveRowDetails, InfrastructureIgnoredRowDetails, InfrastructureStopMonitoringDialog, useInfrastructureReportingState) and the per-type shells (PlatformConnectionsWorkspace, ProxmoxSettingsPanel, ProxmoxDirectWorkspace, ProxmoxConfiguredNodesTable, ProxmoxDirectConnectionsCard, ProxmoxDiscoveryResultsCard, ProxmoxDeleteNodeDialog, ProxmoxNodeModalStack, NodeModal shell, TrueNASSettingsPanel, VMwareSettingsPanel, useProxmoxDirectWorkspaceState); lifecycle extensions must route through the unified aggregator ledger, source-manager cards, and ConnectionEditor credential slots rather than reintroducing those retired surfaces.Those lifecycle-owned settings hooks may consume websocket state only through `frontend-modern/src/contexts/appRuntime.ts`; they must not import `frontend-modern/src/App.tsx` or recreate root-shell providers.- Discovery configuration is part of that same lifecycle-owned workspace boundary. `InfrastructureSourceManager.tsx` must open one canonical discovery editor through `InfrastructureDiscoverySettingsDialog.tsx`, `DiscoverySettingsForm.tsx`, and `discoverySettingsModel.ts`, while the System/Network shell stays limited to network-boundary controls instead of reintroducing a second editable discovery surface. That same workspace boundary now owns the infrastructure source-management toolbar too: the landing page exposes `Add infrastructure`, `Run discovery`, and `Discovery settings` as first-viewport toolbar actions inside the source manager, while governed source rows expose per-source add actions such as `Install Pulse Agent` from the shared catalog. `Run discovery` must remain a visible text command for manual scans rather than an icon-only affordance. `Detect address` remains inside the single add-flow source picker/probe path rather than a duplicate toolbar action. The same landing boundary may surface setup confidence from the unified rows and discovered candidates, including connected-system count, API coverage, agent coverage, sources that still need an agent, and discovery review state, without creating a second inventory model or provider-specific summary fetch. Source groups must stay in the governed source catalog order instead of re-sorting by current row count, row-level lifecycle entry points must use `Manage` language, and locked agent-install states must show a compact command inventory without raw token placeholders or disabled copy commands until a token exists. Network discovery settings remain safety-critical: automatic scanning must surface the shared-network/subnet warning before operators save scan mode changes. Agent command-execution handoff copy belongs to that same install surface: `InfrastructureInstallerSection.tsx` may expose the Pulse command-execution toggle for Patrol, but the label must describe Patrol remediation rather than reviving `Patrol auto-fix` or implying a paid monitoring-volume gate.+ Discovery configuration is part of that same lifecycle-owned workspace boundary. `InfrastructureSourceManager.tsx` must open one canonical discovery editor through `InfrastructureDiscoverySettingsDialog.tsx`, `DiscoverySettingsForm.tsx`, and `discoverySettingsModel.ts`, while the System/Network shell stays limited to network-boundary controls instead of reintroducing a second editable discovery surface. That same workspace boundary now owns the infrastructure source-management toolbar too: the landing page exposes `Add infrastructure`, `Run discovery`, and `Discovery settings` as first-viewport toolbar actions inside the source manager, while governed source rows expose per-source add actions such as `Install Pulse Agent` from the shared catalog. `Run discovery` must remain a visible text command for manual scans rather than an icon-only affordance. `Detect address` remains inside the single add-flow source picker/probe path rather than a duplicate toolbar action. The same landing boundary may surface setup confidence from the unified rows and discovered candidates, including connected-system count, API coverage, agent coverage, sources that still need an agent, and discovery review state, without creating a second inventory model or provider-specific summary fetch. Source groups must stay in the governed source catalog order instead of re-sorting by current row count, row-level lifecycle entry points must use `Manage` language, and locked agent-install states must show a compact command inventory without raw token placeholders or disabled copy commands until a token exists. Network discovery settings remain safety-critical: automatic scanning must surface the shared-network/subnet warning before operators save scan mode changes. The AI settings manual workload refresh at `/api/discovery/run` is a discovery/API refresh sweep, not an enrollment or source-admission path; lifecycle surfaces may observe the refreshed candidates but must not reinterpret it as agent install authority. Agent command-execution handoff copy belongs to that same install surface: `InfrastructureInstallerSection.tsx` may expose the Pulse command-execution toggle for Patrol, but the label must describe Patrol remediation rather than reviving `Patrol auto-fix` or implying a paid monitoring-volume gate.Setup-completion handoff belongs to that same single add-flow boundary. The first-run completion screen must keep credentials as the first surfaced object, then present one compact next-step surface that sends operators to Add infrastructure or directly to the Agent handoff; source-choice explanation may live inside that surface, but lifecycle work must not reintroduce a separate setup-wizard tour, duplicate CTA section, or inline install-command owner before the canonical infrastructure workspace.The same lifecycle-owned workspace boundary now also owns attached-agent composition. When a unified Pulse Agent augments a first-class platform source such as Proxmox VE, the source manager and edit dialog must present one primary platform row with explicit `API` plus `Pulse Agent` composition rather than duplicating that same machine as a second peer row under a generic Pulse Agent platform bucket. Standalone hosts with no owning platform source remain grouped under a standalone-host owner bucket, with `Pulse Agent` shown as the collection method rather than as the pseudo-platform label.When that primary Proxmox source is cluster-backed, the same workspace boundary must render the row under the canonical cluster moniker carried by the backend grouping contract rather than under one sibling node's hostname. That same backend grouping contract must also carry the explicit member-node list for the cluster so the source manager can render child node composition such as `delly` and `minipc` beneath the owning cluster row with per-node coverage/status. Cluster-member node agents belong as augmentations on that owning Proxmox row and its child nodes, not as separate standalone-host peers.diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 17c8e9cd14..0e858d8719 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -170,7 +170,7 @@ runtime cost control, and shared AI transport surfaces.divergence must be sourced from canonical `ReadState.DockerHosts()` views,with model-shaped data limited to the watcher adapter input rather thandirect `StateSnapshot.DockerHosts` reads in the Patrol run loop.-4. Keep discovery scheduling authoritative through `internal/config/ai.go`: `discovery_enabled` and `discovery_interval_hours` must govern both lightweight infrastructure discovery and deep service-discovery background loops. `internal/api/ai_handlers.go` must preserve an explicitly supplied `discovery_interval_hours: 0` as the manual-only setting and may only apply the 24-hour default when discovery is enabled without an explicit interval payload. Discovery analysis remains a Pulse tool-led model workflow: Pulse supplies agent/API/metrics evidence and cache orchestration, while the selected model provides the intelligence. Background or drawer-triggered discovery progress must describe that discovery analysis directly and must not imply a live Pulse Assistant chat transcript unless the run is actually executing inside the chat surface. Assistant and Patrol access to discovery must stay behind the governed `pulse_discovery` tool, including an explicit forced refresh action for known resources.+4. Keep discovery scheduling authoritative through `internal/config/ai.go`: `discovery_enabled` and `discovery_interval_hours` must govern both lightweight infrastructure discovery and deep service-discovery background loops. `internal/api/ai_handlers.go` must preserve an explicitly supplied `discovery_interval_hours: 0` as the manual-only setting and may only apply the 24-hour default when discovery is enabled without an explicit interval payload. Discovery analysis remains a Pulse tool-led model workflow: Pulse supplies agent/API/metrics evidence and cache orchestration, while the selected model provides the intelligence. Background, settings-triggered, or drawer-triggered discovery progress must describe that discovery analysis directly and must not imply a live Pulse Assistant chat transcript unless the run is actually executing inside the chat surface. Assistant and Patrol access to discovery must stay behind the governed `pulse_discovery` tool, including an explicit forced refresh action for known resources, while settings-level manual runs must use the canonical `/api/discovery/run` new/changed/stale sweep rather than a frontend-only shortcut.5. Preserve auditability for outbound model-bound context exports and keep the export record aligned with the prompt boundary that actually reaches the providerExternal provider-bound unified-resource context must enforce the samedata-handling policy the export audit records: `local-only` resources arediff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 064d8a54f9..4296d7a830 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -1368,10 +1368,11 @@ the canonical monitored-system blocked payload.explicit form truth, and the backend must persist a provided`discovery_interval_hours: 0` as manual-only rather than replacing it withthe automatic-scan default. Manual discovery can be triggered directly- through the discovery API for a known resource and through the governed- `pulse_discovery` tool; the API progress payload must describe discovery- evidence analysis rather than presenting background work as a visible- Pulse Assistant chat session.+ through the discovery API for a known resource, through the settings-level+ `/api/discovery/run` sweep for new/changed/stale workload refresh, and+ through the governed `pulse_discovery` tool; the API progress payload must+ describe discovery evidence analysis rather than presenting background work+ as a visible Pulse Assistant chat session.25. Keep shared AI runtime reads centralized on that same governed contract:`frontend-modern/src/stores/aiRuntimeState.ts` is the canonical frontendread owner for `/api/settings/ai` and `/api/ai/models`. AI-owned consumersdiff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 3b97ac78b2..625194ad39 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -894,6 +894,9 @@ AI runtime.must save workload discovery enablement and interval as one explicitsettings pair so selecting "Every 6 hours" or "Manual only" round-tripsthrough `/api/settings/ai` without depending on stale read-side diffing.+ The same workload-discovery settings section must expose a manual+ "Run discovery now" action wired through `/api/discovery/run`, while+ resource-drawer discovery remains the forced single-resource refresh path.Assistant-only controls inside the shared shell, suchas execution permissions and session maintenance, must stay explicitlylabeled as Pulse Assistant controls, while Patrol schedule and autonomydiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex fca13fdf82..b2f84ba69d 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -446,6 +446,11 @@ bypass the API fail-closed execution gate.observe the same node by hostname and IP, so storage- andrecovery-adjacent consumers inherit one canonical represented-host identityinstead of inventing local merge heuristics.+ The settings-level manual discovery refresh at `/api/discovery/run` belongs+ to that adjacent discovery/API boundary. Storage and recovery surfaces may+ consume refreshed workload discovery records, but they must not reinterpret+ the sweep as a recovery scan, protected-system admission, or storage-local+ ownership signal.That same adjacent `internal/api/` boundary also keeps public hosted signupcommercial-only: storage and recovery surfaces must not infer tenantexistence, email issuance, or readiness from `/api/public/signup` responsediff --git a/frontend-modern/src/api/__tests__/discovery.test.ts b/frontend-modern/src/api/__tests__/discovery.test.tsindex 81b669849d..b9d530f9dd 100644--- a/frontend-modern/src/api/__tests__/discovery.test.ts+++ b/frontend-modern/src/api/__tests__/discovery.test.ts@@ -8,6 +8,7 @@ import {getDiscovery,getDiscoveryInfo,listDiscoveriesByType,+ runDiscoveryRefresh,triggerDiscovery,} from '@/api/discovery';import { apiFetch } from '@/utils/apiClient';@@ -408,6 +409,29 @@ describe('discovery api', () => {});});+ it('runs the manual discovery refresh endpoint', async () => {+ apiFetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ mode: 'manual',+ fingerprint_count: 1,+ changed_count: 1,+ stale_count: 0,+ candidate_count: 1,+ discovered_count: 1,+ failed_count: 0,+ last_run: '2026-05-15T12:00:00Z',+ }),+ { status: 200 },+ ),+ );++ const result = await runDiscoveryRefresh();++ expect(result.discovered_count).toBe(1);+ expect(apiFetchMock).toHaveBeenCalledWith('/api/discovery/run', { method: 'POST' });+ });+it('maps canonical pod discovery type queries onto the backend k8s endpoint', async () => {apiFetchMock.mockResolvedValueOnce(new Response(diff --git a/frontend-modern/src/api/discovery.ts b/frontend-modern/src/api/discovery.tsindex 274fe6c608..025920a676 100644--- a/frontend-modern/src/api/discovery.ts+++ b/frontend-modern/src/api/discovery.ts@@ -9,6 +9,7 @@ import type {ResourceDiscovery,DiscoveryListResponse,DiscoveryProgress,+ DiscoveryRunResponse,DiscoveryStatus,TriggerDiscoveryRequest,UpdateNotesRequest,@@ -235,6 +236,20 @@ export async function getDiscoveryStatus(): Promise<DiscoveryStatus> {);}+/**+ * Run the scheduler-equivalent discovery refresh now.+ */+export async function runDiscoveryRefresh(): Promise<DiscoveryRunResponse> {+ const response = await apiFetch(`${API_BASE}/run`, {+ method: 'POST',+ });+ return parseRequiredAPIResponse(+ response,+ 'Failed to run discovery refresh',+ 'Failed to parse discovery refresh response',+ );+}+/*** Get discovery info for a resource type (AI provider info, commands that will run)*/diff --git a/frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx b/frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsxindex 8bfad5aea5..edd42ce391 100644--- a/frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx+++ b/frontend-modern/src/components/Settings/AIRuntimeControlsSection.tsx@@ -1,4 +1,5 @@import { Component, Show } from 'solid-js';+import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';import type { AIControlLevel } from '@/utils/aiControlLevelPresentation';import type { AISettingsState } from '@/components/Settings/useAISettingsState';import { HelpIcon } from '@/components/shared/HelpIcon';@@ -117,10 +118,29 @@ export const AIRuntimeControlsSection: Component<AIRuntimeControlsSectionProps></FormSelect><p class="text-[10px] text-muted ml-32 pl-3">{state.form.discoveryIntervalHours === 0- ? 'Workload discovery runs only when you click "Update Discovery" on a resource'+ ? 'Workload discovery runs only when you click "Run discovery now" here or "Run Discovery" on a resource': 'Workload discovery will automatically re-scan resources at this interval'}</p></div>+ <div class="flex items-center justify-between gap-3 rounded border border-border bg-surface-alt px-3 py-2">+ <p class="text-[10px] text-muted">+ Runs the new, changed, and stale workload sweep used by the schedule.+ </p>+ <button+ type="button"+ class="inline-flex min-h-10 sm:min-h-9 items-center gap-1.5 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"+ 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 discovery now'}+ </button>+ </div></Show><p class="text-[10px] text-muted">{getAISettingsWorkloadDiscoverySummary().text}</p>diff --git a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsxindex 528ea3a48c..cfb45cc01b 100644--- a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx@@ -11,6 +11,7 @@ const updateSettingsMock = vi.fn();const getModelsMock = vi.fn();const testProviderMock = vi.fn();const testConnectionMock = vi.fn();+const runDiscoveryRefreshMock = vi.fn();const listSessionsMock = vi.fn();const summarizeSessionMock = vi.fn();const getSessionDiffMock = vi.fn();@@ -47,6 +48,10 @@ vi.mock('@/api/aiChat', () => ({},}));+vi.mock('@/api/discovery', () => ({+ runDiscoveryRefresh: (...args: unknown[]) => runDiscoveryRefreshMock(...args),+}));+vi.mock('@/stores/notifications', () => ({notificationStore: {success: (...args: unknown[]) => notificationSuccessMock(...args),@@ -111,6 +116,7 @@ const resetAllMocks = () => {getModelsMock.mockReset();testProviderMock.mockReset();testConnectionMock.mockReset();+ runDiscoveryRefreshMock.mockReset();listSessionsMock.mockReset();summarizeSessionMock.mockReset();getSessionDiffMock.mockReset();@@ -142,6 +148,16 @@ const setupDefaultMocks = () => {message: 'OpenRouter reachable',provider: 'openrouter',});+ runDiscoveryRefreshMock.mockResolvedValue({+ mode: 'manual',+ fingerprint_count: 1,+ changed_count: 1,+ stale_count: 0,+ candidate_count: 1,+ discovered_count: 1,+ failed_count: 0,+ last_run: '2026-05-15T12:00:00Z',+ });listSessionsMock.mockResolvedValue([]);summarizeSessionMock.mockResolvedValue(undefined);getSessionDiffMock.mockResolvedValue({ files: [], summary: '' });@@ -464,6 +480,65 @@ describe('AISettings workload discovery persistence', () => {);});});++ it('runs a manual discovery refresh from workload discovery settings', async () => {+ getSettingsMock.mockResolvedValue({+ ...baseSettings(),+ discovery_enabled: true,+ discovery_interval_hours: 0,+ });++ renderComponent();++ await waitFor(() => {+ expect(+ screen.getByRole('button', { name: /Workload Discovery Manual/i }),+ ).toBeInTheDocument();+ });+ fireEvent.click(screen.getByRole('button', { name: /Workload Discovery Manual/i }));+ fireEvent.click(screen.getByRole('button', { name: /Run discovery now/i }));++ await waitFor(() => {+ expect(runDiscoveryRefreshMock).toHaveBeenCalledTimes(1);+ expect(notificationSuccessMock).toHaveBeenCalledWith(+ 'Discovery refresh finished: 1 workload refreshed.',+ );+ });+ });++ it('reports when a manual discovery refresh has no pending work', async () => {+ getSettingsMock.mockResolvedValue({+ ...baseSettings(),+ discovery_enabled: true,+ discovery_interval_hours: 0,+ });+ runDiscoveryRefreshMock.mockResolvedValue({+ mode: 'manual',+ fingerprint_count: 1,+ changed_count: 0,+ stale_count: 0,+ candidate_count: 0,+ discovered_count: 0,+ failed_count: 0,+ last_run: '2026-05-15T12:00:00Z',+ });++ renderComponent();++ await waitFor(() => {+ expect(+ screen.getByRole('button', { name: /Workload Discovery Manual/i }),+ ).toBeInTheDocument();+ });+ fireEvent.click(screen.getByRole('button', { name: /Workload Discovery Manual/i }));+ fireEvent.click(screen.getByRole('button', { name: /Run discovery now/i }));++ await waitFor(() => {+ expect(notificationInfoMock).toHaveBeenCalledWith(+ 'Discovery refresh finished: no new, changed, or stale workloads.',+ );+ });+ });});describe('AISettings OpenRouter flow', () => {diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.tsindex 0d2587874f..40476d1668 100644--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts@@ -259,6 +259,18 @@ describe('settings architecture guardrails', () => {expect(aiModelSelectionSectionSource).not.toContain("fetch('/api/ai/patrol/preflight");});+ it('keeps workload discovery manual refresh on the canonical settings state', () => {+ expect(aiSettingsStateSource).toContain(+ "import { runDiscoveryRefresh } from '@/api/discovery';",+ );+ expect(aiSettingsStateSource).toContain('const handleRunDiscoveryRefresh = async () => {');+ expect(aiSettingsStateSource).toContain('const result = await runDiscoveryRefresh();');+ expect(aiSettingsStateSource).toContain('discoveryRunRunning');+ expect(aiRuntimeControlsSectionSource).toContain('state.handleRunDiscoveryRefresh()');+ expect(aiRuntimeControlsSectionSource).toContain('Run discovery now');+ expect(aiRuntimeControlsSectionSource).not.toContain("fetch('/api/discovery/run");+ });+it('hydrates the Patrol preflight panel from the cached settings snapshot', () => {// The cached preflight outcome arrives on /api/settings/ai as// patrol_preflight; loadSettings and updateSettings must project it@@ -541,7 +553,7 @@ describe('settings architecture guardrails', () => {// Discovery actions are now icon-only ghost buttons; the human copy// still lives in their title and aria-label attributes.expect(infrastructureSourceManagerSource).toContain('Run discovery');- expect(infrastructureSourceManagerSource).toContain('discovery settings');+ expect(infrastructureSourceManagerSource).toContain('Discovery settings');expect(monitoredSystemImpactPreviewSource).toContain('getMonitoredSystemImpactPreviewTitle');expect(monitoredSystemImpactPreviewSource).toContain('formatMonitoredSystemImpactPreviewSummary',diff --git a/frontend-modern/src/components/Settings/useAISettingsState.ts b/frontend-modern/src/components/Settings/useAISettingsState.tsindex 872a9cb659..4b0f8dfb23 100644--- a/frontend-modern/src/components/Settings/useAISettingsState.ts+++ b/frontend-modern/src/components/Settings/useAISettingsState.ts@@ -2,6 +2,7 @@ import { createMemo, createSignal, onMount } from 'solid-js';import { createStore } from 'solid-js/store';import { AIAPI } from '@/api/ai';import { AIChatAPI, type ChatSession, type FileChange } from '@/api/aiChat';+import { runDiscoveryRefresh } from '@/api/discovery';import { runPatrolPreflight, type PatrolPreflightResponse } from '@/api/patrol';import {AI_PROVIDERS,@@ -246,6 +247,7 @@ export const useAISettingsState = () => {const [patrolPreflightRunning, setPatrolPreflightRunning] = createSignal(false);const [patrolPreflightResult, setPatrolPreflightResult] =createSignal<PatrolPreflightResponse | null>(null);+ const [discoveryRunRunning, setDiscoveryRunRunning] = createSignal(false);// hydratePatrolPreflightFromSettings projects the cached preflight// snapshot from /api/settings/ai into the same response shape the@@ -977,6 +979,31 @@ export const useAISettingsState = () => {}};+ const handleRunDiscoveryRefresh = async () => {+ setDiscoveryRunRunning(true);+ try {+ const result = await runDiscoveryRefresh();+ if (result.failed_count > 0) {+ notificationStore.warning(+ `Discovery refresh finished: ${result.discovered_count} refreshed, ${result.failed_count} failed.`,+ );+ } else if (result.candidate_count === 0) {+ notificationStore.info('Discovery refresh finished: no new, changed, or stale workloads.');+ } else {+ notificationStore.success(+ `Discovery refresh finished: ${result.discovered_count} workload${result.discovered_count === 1 ? '' : 's'} refreshed.`,+ );+ }+ } catch (error) {+ logger.error('[AISettings] Discovery refresh failed:', error);+ notificationStore.error(+ error instanceof Error ? error.message : 'Unable to run discovery refresh.',+ );+ } finally {+ setDiscoveryRunRunning(false);+ }+ };+const handleTestProvider = async (provider: AIProvider) => {setTestingProvider(provider);setProviderTestResult(null);@@ -1114,6 +1141,7 @@ export const useAISettingsState = () => {diffFiles,diffSessionLabel,diffSummary,+ discoveryRunRunning,expandedProviders,form,formatDiffStats,@@ -1122,6 +1150,7 @@ export const useAISettingsState = () => {handleCloseSetupModal,handleEnableRequest,handleEnabledToggle,+ handleRunDiscoveryRefresh,handleSave,handleSessionDiff,handleSessionRevert,diff --git a/frontend-modern/src/types/discovery.ts b/frontend-modern/src/types/discovery.tsindex 31725560df..9baef26e29 100644--- a/frontend-modern/src/types/discovery.ts+++ b/frontend-modern/src/types/discovery.ts@@ -141,6 +141,17 @@ export interface DiscoveryStatus {stale_count?: number; // Discoveries > 30 days old}+export interface DiscoveryRunResponse {+ mode: 'manual' | 'automatic' | string;+ fingerprint_count: number;+ changed_count: number;+ stale_count: number;+ candidate_count: number;+ discovered_count: number;+ failed_count: number;+ last_run: string;+}+export interface TriggerDiscoveryRequest {force?: boolean;hostname?: string;diff --git a/internal/api/discovery_handlers.go b/internal/api/discovery_handlers.goindex 2bf8f45d04..5f1ba03231 100644--- a/internal/api/discovery_handlers.go+++ b/internal/api/discovery_handlers.go@@ -545,6 +545,23 @@ func (h *DiscoveryHandlers) HandleGetStatus(w http.ResponseWriter, r *http.RequewriteDiscoveryJSON(w, status)}+// HandleRunDiscovery handles POST /api/discovery/run.+func (h *DiscoveryHandlers) HandleRunDiscovery(w http.ResponseWriter, r *http.Request) {+ if h.service == nil {+ writeDiscoveryError(w, http.StatusServiceUnavailable, "discovery service not configured")+ return+ }++ summary, err := h.service.RunManualDiscoveryRefresh(r.Context())+ if err != nil {+ log.Error().Err(err).Msg("Failed to run manual discovery refresh")+ writeDiscoveryError(w, http.StatusInternalServerError, "Discovery refresh failed: "+err.Error())+ return+ }++ writeDiscoveryJSON(w, summary)+}+// HandleUpdateSettings handles PUT /api/discovery/settings// Allows updating discovery settings like the staleness threshold.func (h *DiscoveryHandlers) HandleUpdateSettings(w http.ResponseWriter, r *http.Request) {diff --git a/internal/api/discovery_handlers_test.go b/internal/api/discovery_handlers_test.goindex cea46c56b6..7fb73fe34e 100644--- a/internal/api/discovery_handlers_test.go+++ b/internal/api/discovery_handlers_test.go@@ -22,6 +22,12 @@ type MockCommandExecutor struct {mock.Mock}+type discoveryHandlerTestAnalyzer struct{}++func (discoveryHandlerTestAnalyzer) AnalyzeForDiscovery(ctx context.Context, prompt string) (string, error) {+ return `{"service_type":"unknown","service_name":"Unknown","service_version":"","category":"unknown","cli_access":"","facts":[],"config_paths":[],"data_paths":[],"log_paths":[],"ports":[],"confidence":0.1,"reasoning":"test"}`, nil+}+func (m *MockCommandExecutor) ExecuteCommand(ctx context.Context, agentID string, cmd servicediscovery.ExecuteCommandPayload) (*servicediscovery.CommandResultPayload, error) {args := m.Called(ctx, agentID, cmd)if args.Get(0) == nil {@@ -350,6 +356,22 @@ func TestHandleGetStatus(t *testing.T) {assert.Contains(t, status, "running")}+func TestHandleRunDiscovery(t *testing.T) {+ h, svc, _ := setupDiscoveryHandlers(t)+ svc.SetAIAnalyzer(discoveryHandlerTestAnalyzer{})++ req := httptest.NewRequest("POST", "/api/discovery/run", nil)+ w := httptest.NewRecorder()++ h.HandleRunDiscovery(w, req)++ assert.Equal(t, http.StatusOK, w.Code)+ var summary servicediscovery.DiscoveryRefreshSummary+ require.NoError(t, json.NewDecoder(w.Body).Decode(&summary))+ assert.Equal(t, "manual", summary.Mode)+ assert.Equal(t, 0, summary.CandidateCount)+}+func TestHandleUpdateSettings(t *testing.T) {h, _, _ := setupDiscoveryHandlers(t)diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex 939dcb4469..ec9c6f0008 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -650,6 +650,7 @@ var allRouteAllowlist = []string{"/api/ai/question/","/api/discovery","/api/discovery/status",+ "/api/discovery/run","/api/discovery/settings","/api/discovery/info/","/api/discovery/type/",diff --git a/internal/api/router_routes_monitoring.go b/internal/api/router_routes_monitoring.goindex 1293502e47..6e6cc8a411 100644--- a/internal/api/router_routes_monitoring.go+++ b/internal/api/router_routes_monitoring.go@@ -259,6 +259,13 @@ func (r *Router) registerMonitoringResourceRoutes(// AI-powered infrastructure discovery endpointsr.mux.HandleFunc("/api/discovery", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.discoveryHandlers.HandleListDiscoveries)))r.mux.HandleFunc("/api/discovery/status", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.discoveryHandlers.HandleGetStatus)))+ r.mux.HandleFunc("/api/discovery/run", RequireAuth(r.config, RequireScope(config.ScopeMonitoringWrite, func(w http.ResponseWriter, req *http.Request) {+ if req.Method == http.MethodPost {+ r.discoveryHandlers.HandleRunDiscovery(w, req)+ } else {+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)+ }+ })))r.mux.HandleFunc("/api/discovery/settings", RequireAuth(r.config, RequireScope(config.ScopeSettingsWrite, r.discoveryHandlers.HandleUpdateSettings)))r.mux.HandleFunc("/api/discovery/info/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.discoveryHandlers.HandleGetInfo)))r.mux.HandleFunc("/api/discovery/type/", RequireAuth(r.config, RequireScope(config.ScopeMonitoringRead, r.discoveryHandlers.HandleListByType)))diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.goindex 3b185a53ff..41b8a478e4 100644--- a/internal/api/security_regression_test.go+++ b/internal/api/security_regression_test.go@@ -2348,6 +2348,7 @@ func TestDiscoveryMutationEndpointsRequireMonitoringWriteScope(t *testing.T) {path stringbody string}{+ {method: http.MethodPost, path: "/api/discovery/run", body: `{}`},{method: http.MethodPost, path: "/api/discovery/agent/host-1/resource-1", body: `{}`},{method: http.MethodPut, path: "/api/discovery/agent/host-1/resource-1/notes", body: `{}`},{method: http.MethodDelete, path: "/api/discovery/agent/host-1/resource-1", body: ""},diff --git a/internal/servicediscovery/service.go b/internal/servicediscovery/service.goindex 46a025743d..0952d2c450 100644--- a/internal/servicediscovery/service.go+++ b/internal/servicediscovery/service.go@@ -625,8 +625,25 @@ func (s *Service) finishDiscoveryLoop(stopCh <-chan struct{}) {}func (s *Service) runAutomaticDiscoveryRefresh(ctx context.Context) {+ if _, err := s.runDiscoveryRefresh(ctx, "automatic"); err != nil {+ log.Debug().Err(err).Msg("skipping automatic discovery refresh")+ }+}++// RunManualDiscoveryRefresh runs the scheduler-equivalent discovery refresh on demand.+func (s *Service) RunManualDiscoveryRefresh(ctx context.Context) (DiscoveryRefreshSummary, error) {if ctx == nil || ctx.Err() != nil || s.store == nil {- return+ return DiscoveryRefreshSummary{Mode: "manual"}, fmt.Errorf("discovery service is not ready")+ }++ s.collectFingerprints(ctx)+ return s.runDiscoveryRefresh(ctx, "manual")+}++func (s *Service) runDiscoveryRefresh(ctx context.Context, mode string) (DiscoveryRefreshSummary, error) {+ summary := DiscoveryRefreshSummary{Mode: mode}+ if ctx == nil || ctx.Err() != nil || s.store == nil {+ return summary, fmt.Errorf("discovery service is not ready")}s.mu.RLock()@@ -634,19 +651,16 @@ func (s *Service) runAutomaticDiscoveryRefresh(ctx context.Context) {maxDiscoveryAge := s.maxDiscoveryAges.mu.RUnlock()if !analyzerConfigured {- log.Debug().Msg("skipping automatic discovery refresh - AI analyzer not configured")- return+ return summary, fmt.Errorf("AI analyzer not configured")}changedResources, err := s.store.GetChangedResources()if err != nil {- log.Warn().Err(err).Msg("failed to fetch changed resources for automatic discovery refresh")- return+ return summary, fmt.Errorf("fetch changed resources: %w", err)}staleResources, err := s.store.GetStaleResources(maxDiscoveryAge)if err != nil {- log.Warn().Err(err).Msg("failed to fetch stale resources for automatic discovery refresh")- return+ return summary, fmt.Errorf("fetch stale resources: %w", err)}candidates := make(map[string]struct{}, len(changedResources)+len(staleResources))@@ -660,8 +674,15 @@ func (s *Service) runAutomaticDiscoveryRefresh(ctx context.Context) {candidates[id] = struct{}{}}}++ summary.ChangedCount = len(changedResources)+ summary.StaleCount = len(staleResources)+ summary.CandidateCount = len(candidates)+ summary.FingerprintCount = s.store.GetFingerprintCount()+ summary.LastRun = time.Now()+if len(candidates) == 0 {- return+ return summary, nil}resourceIDs := make([]string, 0, len(candidates))@@ -671,13 +692,11 @@ func (s *Service) runAutomaticDiscoveryRefresh(ctx context.Context) {sort.Strings(resourceIDs)log.Info().+ Str("mode", mode).Int("changed", len(changedResources)).Int("stale", len(staleResources)).Int("total", len(resourceIDs)).- Msg("Running automatic discovery refresh for changed/stale resources")-- discoveredCount := 0- failedCount := 0+ Msg("Running discovery refresh for changed/stale resources")for _, id := range resourceIDs {if ctx.Err() != nil {@@ -686,7 +705,7 @@ func (s *Service) runAutomaticDiscoveryRefresh(ctx context.Context) {resourceType, targetID, resourceID, err := ParseResourceID(id)if err != nil {- failedCount+++ summary.FailedCount++log.Warn().Err(err).Str("resource_id", id).@@ -701,21 +720,24 @@ func (s *Service) runAutomaticDiscoveryRefresh(ctx context.Context) {Hostname: targetID,})if err != nil {- failedCount+++ summary.FailedCount++log.Warn().Err(err).Str("resource_id", id).Str("resource_type", string(resourceType)).- Msg("Automatic discovery refresh failed for resource")+ Msg("Discovery refresh failed for resource")continue}- discoveredCount+++ summary.DiscoveredCount++}log.Info().- Int("discovered", discoveredCount).- Int("failed", failedCount).- Msg("Automatic discovery refresh completed")+ Str("mode", mode).+ Int("discovered", summary.DiscoveredCount).+ Int("failed", summary.FailedCount).+ Msg("Discovery refresh completed")++ return summary, nil}// getSnapshot returns the current infrastructure state from ReadState.diff --git a/internal/servicediscovery/service_test.go b/internal/servicediscovery/service_test.goindex 1d740a57f6..fbd2b6efb5 100644--- a/internal/servicediscovery/service_test.go+++ b/internal/servicediscovery/service_test.go@@ -919,6 +919,49 @@ func TestService_FingerprintCollectionAndDiscoveryWrappers(t *testing.T) {service.collectFingerprints(context.Background())}+func TestService_RunManualDiscoveryRefreshDiscoversNewFingerprints(t *testing.T) {+ store, err := NewStore(t.TempDir())+ if err != nil {+ t.Fatalf("NewStore error: %v", err)+ }+ store.crypto = nil++ state := StateSnapshot{+ DockerHosts: []DockerHost{+ {+ AgentID: "host1",+ Hostname: "host1",+ Containers: []DockerContainer{+ {Name: "web", Image: "nginx:latest", Status: "running"},+ },+ },+ },+ }+ analyzer := &stubAnalyzer{+ response: `{"service_type":"nginx","service_name":"Nginx","service_version":"1.2","category":"web_server","cli_access":"docker exec {container} nginx -v","facts":[],"config_paths":["/etc/nginx"],"data_paths":[],"log_paths":[],"ports":[{"port":80,"protocol":"tcp","process":"nginx","address":"0.0.0.0"}],"confidence":0.9,"reasoning":"image"}`,+ }+ service := NewService(store, nil, DefaultConfig())+ service.SetReadState(readStateFromSnapshot(state))+ service.SetAIAnalyzer(analyzer)++ summary, err := service.RunManualDiscoveryRefresh(context.Background())+ if err != nil {+ t.Fatalf("RunManualDiscoveryRefresh error: %v", err)+ }+ if summary.Mode != "manual" || summary.CandidateCount != 1 || summary.DiscoveredCount != 1 || summary.FailedCount != 0 {+ t.Fatalf("unexpected summary: %+v", summary)+ }+ if summary.FingerprintCount != 1 || summary.ChangedCount != 1 {+ t.Fatalf("expected one new changed fingerprint, got %+v", summary)+ }+ if analyzer.calls != 1 {+ t.Fatalf("expected one analyzer call, got %d", analyzer.calls)+ }+ if got, err := service.GetDiscovery("docker:host1:web"); err != nil || got == nil || got.ServiceName != "Nginx" {+ t.Fatalf("expected stored Nginx discovery, got %#v err=%v", got, err)+ }+}+// Regression: collectFingerprints used to panic-and-recover for every LXC/VM// because processFingerprint went through reflect.Value.Interface(), losing// addressability so reflect.Call hit a Container-vs-*Container type mismatch.diff --git a/internal/servicediscovery/types.go b/internal/servicediscovery/types.goindex 0d8ee9d94c..ec1fee028e 100644--- a/internal/servicediscovery/types.go+++ b/internal/servicediscovery/types.go@@ -346,6 +346,18 @@ type ServiceStatus struct {LastFingerprintScan time.Time}+// DiscoveryRefreshSummary describes one scheduler-equivalent discovery refresh.+type DiscoveryRefreshSummary struct {+ Mode string `json:"mode"`+ FingerprintCount int `json:"fingerprint_count"`+ ChangedCount int `json:"changed_count"`+ StaleCount int `json:"stale_count"`+ CandidateCount int `json:"candidate_count"`+ DiscoveredCount int `json:"discovered_count"`+ FailedCount int `json:"failed_count"`+ LastRun time.Time `json:"last_run"`+}+// ToMap converts the status snapshot to a legacy map representation.func (s ServiceStatus) ToMap() map[string]any {return map[string]any{