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.

Extract discovery tab runtime owner

rcourtman9f8b61d0b0d2
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index d52b13d3e9..2126cbd647 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -2912,6 +2912,8 @@
"internal/unifiedresources/"
],
"owned_files": [
+ "frontend-modern/src/components/Discovery/DiscoveryTab.tsx",
+ "frontend-modern/src/components/Discovery/useDiscoveryTabState.ts",
"frontend-modern/src/components/Infrastructure/infrastructureSelectors.ts",
"frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx",
"frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts",
@@ -2984,6 +2986,8 @@
"label": "unified resource consumer proof",
"match_prefixes": [],
"match_files": [
+ "frontend-modern/src/components/Discovery/DiscoveryTab.tsx",
+ "frontend-modern/src/components/Discovery/useDiscoveryTabState.ts",
"frontend-modern/src/components/Infrastructure/infrastructureSelectors.ts",
"frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx",
"frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts",
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 28f3ee1684..f97cebe1c9 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -47,8 +47,10 @@ cross-source deduplication.
25. `frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx`
26. `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts`
27. `frontend-modern/src/components/Infrastructure/useUnifiedResourceTableState.ts`
-28. `frontend-modern/src/features/infrastructure/InfrastructurePageSurface.tsx`
-29. `frontend-modern/src/features/infrastructure/useInfrastructurePageState.ts`
+28. `frontend-modern/src/components/Discovery/DiscoveryTab.tsx`
+29. `frontend-modern/src/components/Discovery/useDiscoveryTabState.ts`
+30. `frontend-modern/src/features/infrastructure/InfrastructurePageSurface.tsx`
+31. `frontend-modern/src/features/infrastructure/useInfrastructurePageState.ts`
## Shared Boundaries
@@ -76,6 +78,7 @@ assembly branch.
5. Add platform registry, resolution, or host-dedup behavior through `internal/unifiedresources/registry.go`, `internal/unifiedresources/resolve.go`, `internal/unifiedresources/resolved_host_set.go`, `internal/unifiedresources/snapshot_source_filter.go`, `internal/unifiedresources/store.go`, `internal/unifiedresources/kubernetes_capabilities.go`, and `internal/unifiedresources/pbs_rollups.go`
6. Add canonical governed name-resolution or policy-aware resource lookup behavior through `internal/unifiedresources/resolve.go` and `internal/unifiedresources/resolve_context.go`
7. Add or change resource drawer timeline/facet presentation through `frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx`, `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts`, `frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx`, `frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts`, and the governed `internal/api/resources.go` facet/timeline contract together
+8. Add or change discovery-support runtime under the resource drawer through `frontend-modern/src/components/Discovery/DiscoveryTab.tsx` for shell/presentation ownership and `frontend-modern/src/components/Discovery/useDiscoveryTabState.ts` for fetch, websocket-progress, and notes-mutation ownership
## Forbidden Paths
@@ -318,6 +321,10 @@ second peer overview surface.
The discovery metadata panel now expands directly under the outer support
disclosure instead of nesting a second bordered card, so the support surface
reads as one flattened reveal instead of a card inside a card.
+That discovery support surface now also follows the same shell/runtime split
+as the rest of the drawer: `DiscoveryTab.tsx` owns presentation and
+disclosures, while `useDiscoveryTabState.ts` owns API fetches, websocket
+progress, and note/discovery mutations.
The overview keeps host, service, investigation, and discovery detail as
collapsed sibling disclosures under the primary summary, so the drawer keeps
the top-level shape to `Summary` plus `Change history` before any secondary
diff --git a/frontend-modern/src/components/Discovery/DiscoveryTab.tsx b/frontend-modern/src/components/Discovery/DiscoveryTab.tsx
index f89d124e5d..be83b84fa6 100644
--- a/frontend-modern/src/components/Discovery/DiscoveryTab.tsx
+++ b/frontend-modern/src/components/Discovery/DiscoveryTab.tsx
@@ -1,26 +1,10 @@
+import { Component, For, Show, createMemo } from 'solid-js';
+import type { ResourceType } from '../../types/discovery';
import {
- Component,
- Show,
- For,
- createSignal,
- createMemo,
- createResource,
- onCleanup,
- createEffect,
-} from 'solid-js';
-import type { ResourceType, DiscoveryProgress } from '../../types/discovery';
-import {
- getDiscovery,
- getDiscoveryInfo,
- triggerDiscovery,
- updateDiscoveryNotes,
formatDiscoveryAge,
getCategoryDisplayName,
getConfidenceLevel,
- getConnectedAgents,
} from '../../api/discovery';
-import { toDiscoveryAPIResourceType } from '@/utils/discoveryTarget';
-import { eventBus } from '../../stores/events';
import {
getDiscoveryInitialEmptyState,
getDiscoveryLoadingState,
@@ -30,6 +14,7 @@ import {
getDiscoverySuggestedURLFallback,
getDiscoveryURLSuggestionSourceLabel,
} from '@/utils/discoveryPresentation';
+import { useDiscoveryTabState } from './useDiscoveryTabState';
interface DiscoveryTabProps {
resourceType: ResourceType;
@@ -40,11 +25,6 @@ interface DiscoveryTabProps {
commandsEnabled?: boolean;
}
-// Construct the resource ID in the same format the backend uses
-const makeResourceId = (type: ResourceType, agentId: string, resourceId: string) => {
- return `${toDiscoveryAPIResourceType(type) || type}:${agentId}:${resourceId}`;
-};
-
const toSentence = (text?: string): string => {
const trimmed = (text || '').trim();
if (!trimmed) return '';
@@ -53,304 +33,63 @@ const toSentence = (text?: string): string => {
};
export const DiscoveryTab: Component<DiscoveryTabProps> = (props) => {
- const [isScanning, setIsScanning] = createSignal(false);
- const [editingNotes, setEditingNotes] = createSignal(false);
- // Live elapsed time counter (updates every second while scanning)
- const [liveElapsedSeconds, setLiveElapsedSeconds] = createSignal(0);
- const [scanStartTime, setScanStartTime] = createSignal<number | null>(null);
- // Delayed loading spinner - only show after 150ms to prevent flash
- const [showLoadingSpinner, setShowLoadingSpinner] = createSignal(false);
-
- // Reset ephemeral UI state when changing discovery context
- createEffect(() => {
- void discoverySourceKey();
- setIsScanning(false);
- setHttpScanInProgress(false);
- setScanProgress(null);
- setScanError(null);
- setScanSuccess(false);
- setScanStartTime(null);
- setLiveElapsedSeconds(0);
- setShowLoadingSpinner(false);
- setEditingNotes(false);
- setSaveError(null);
- });
- const [notesText, setNotesText] = createSignal('');
- const [saveError, setSaveError] = createSignal<string | null>(null);
- const [scanError, setScanError] = createSignal<string | null>(null);
- const [scanProgress, setScanProgress] = createSignal<DiscoveryProgress | null>(null);
- const [scanSuccess, setScanSuccess] = createSignal(false);
- const [showCommandsPreview, setShowCommandsPreview] = createSignal(false);
- const [showExplanation, setShowExplanation] = createSignal(true);
- // Track if we initiated scan via HTTP to prevent WebSocket race conditions
- const [httpScanInProgress, setHttpScanInProgress] = createSignal(false);
- const targetAgentId = createMemo(() => props.agentId || '');
-
- // Fetch discovery info (AI provider, commands) - used for pre-scan transparency
- const [discoveryInfo] = createResource(
- () => props.resourceType,
- async (type) => {
- try {
- return await getDiscoveryInfo(type);
- } catch {
- return null;
- }
- },
- );
-
- // Fetch connected agents (for WebSocket command execution)
- const [connectedAgents] = createResource(async () => {
- try {
- return await getConnectedAgents();
- } catch {
- return { count: 0, agents: [] };
- }
- });
-
- // Check if this resource has a connected agent for command execution
- // Matches backend logic in deep_scanner.go findAgentForHost()
- const hasConnectedAgent = () => {
- const agents = connectedAgents()?.agents || [];
- const agentId = targetAgentId();
- if (!agentId) return false;
-
- // First try exact match on agent ID
- if (agents.some((agent) => agent.agent_id === agentId)) {
- return true;
- }
+ const {
+ connectedAgents,
+ discovery,
+ discoveryInfo,
+ editingNotes,
+ handleSaveNotes,
+ handleTriggerDiscovery,
+ hasConnectedAgent,
+ hasValidDiscovery,
+ isScanning,
+ liveElapsedSeconds,
+ notesText,
+ saveError,
+ scanError,
+ scanProgress,
+ scanSuccess,
+ setEditingNotes,
+ setNotesText,
+ setScanError,
+ setShowCommandsPreview,
+ setShowExplanation,
+ showCommandsPreview,
+ showExplanation,
+ showLoadingSpinner,
+ startEditingNotes,
+ validDiscovery,
+ } = useDiscoveryTabState(props);
- // Then try hostname match
- if (agents.some((agent) => agent.hostname === props.hostname || agent.hostname === agentId)) {
- return true;
- }
-
- // If only one agent connected, backend will use it (fallback)
- if (agents.length === 1) {
- return true;
- }
-
- return false;
- };
-
- // Fetch discovery data
- // Use a stable string key so createResource doesn't refetch when the parent's guest
- // object reference changes (e.g. from <Index> data updates every 5 seconds)
- const discoverySourceKey = createMemo(
- () => `${props.resourceType}|${targetAgentId()}|${props.resourceId}`,
- );
- const [discovery, { refetch, mutate }] = createResource(discoverySourceKey, async () => {
- const agentId = targetAgentId();
- if (!agentId) return null;
- try {
- return await getDiscovery(props.resourceType, agentId, props.resourceId);
- } catch {
- return null;
- }
- });
const suggestedURLReasonText = createMemo(() => {
- const d = discovery();
- if (!d) return '';
- const detail = toSentence(d.suggested_url_source_detail);
+ const current = discovery();
+ if (!current) return '';
+ const detail = toSentence(current.suggested_url_source_detail);
if (detail) return detail;
- if (d.suggested_url_source_code)
- return getDiscoveryURLSuggestionSourceLabel(d.suggested_url_source_code);
- return '';
- });
- const suggestedURLReasonTitle = createMemo(() => {
- const d = discovery();
- if (!d) return '';
- const label = getDiscoveryURLSuggestionSourceLabel(d.suggested_url_source_code);
- if (d.suggested_url_source_detail) return `${label}: ${d.suggested_url_source_detail}`;
- return label;
- });
-
- // Delay showing loading spinner to prevent flash for fast API calls
- createEffect(() => {
- if (discovery.loading) {
- const timer = setTimeout(() => {
- if (discovery.loading) {
- setShowLoadingSpinner(true);
- }
- }, 150);
- onCleanup(() => clearTimeout(timer));
- } else {
- setShowLoadingSpinner(false);
+ if (current.suggested_url_source_code) {
+ return getDiscoveryURLSuggestionSourceLabel(current.suggested_url_source_code);
}
+ return '';
});
- // Live elapsed time timer - updates every second while scanning
- createEffect(() => {
- if (isScanning() && scanStartTime()) {
- const interval = setInterval(() => {
- const elapsed = Math.floor((Date.now() - scanStartTime()!) / 1000);
- setLiveElapsedSeconds(elapsed);
- }, 1000);
- onCleanup(() => clearInterval(interval));
+ const suggestedURLReasonTitle = createMemo(() => {
+ const current = discovery();
+ if (!current) return '';
+ const label = getDiscoveryURLSuggestionSourceLabel(current.suggested_url_source_code);
+ if (current.suggested_url_source_detail) {
+ return `${label}: ${current.suggested_url_source_detail}`;
}
+ return label;
});
- // Handle triggering a new discovery
- const handleTriggerDiscovery = async (force = false) => {
- setIsScanning(true);
- setHttpScanInProgress(true); // Prevent WebSocket from resetting state
- setScanProgress(null);
- setScanError(null);
- setScanSuccess(false);
- setScanStartTime(Date.now()); // Start the live timer
- setLiveElapsedSeconds(0);
- try {
- // triggerDiscovery runs the discovery and returns the result directly
- const agentId = targetAgentId();
- if (!agentId) {
- setScanError('Agent identifier unavailable for discovery');
- return;
- }
- const result = await triggerDiscovery(props.resourceType, agentId, props.resourceId, {
- force,
- hostname: props.hostname,
- });
- // Use the result directly - no need for a separate refetch which can race
- if (result) {
- mutate(result);
- }
- // Now everything is ready - hide scanning state and show success
- setHttpScanInProgress(false);
- setIsScanning(false);
- setScanProgress(null);
- setScanStartTime(null); // Stop the live timer
- setScanSuccess(true);
- // Clear success after user has seen it
- setTimeout(() => setScanSuccess(false), 2000);
- } catch (err) {
- console.error('Discovery failed:', err);
- // Extract error message for display
- const message = err instanceof Error ? err.message : 'Discovery scan failed';
- // Provide helpful, specific message based on the error and current state
- if (message.includes('no connected agent')) {
- // Check if commands are enabled to provide more specific guidance
- if (props.commandsEnabled === false) {
- setScanError(
- 'Commands not enabled. Enable "Pulse Commands" in Settings → Unified Agents for this agent.',
- );
- } else if (props.commandsEnabled === true) {
- // Commands enabled but no WebSocket connection - likely token scope issue
- setScanError(
- 'Agent not connected for command execution. The API token may be missing the "agent:exec" scope. Check Settings → API Tokens.',
- );
- } else {
- // Unknown state - provide general guidance
- setScanError(
- 'No agent available for command execution. Ensure "Pulse Commands" is enabled in Settings → Unified Agents and the API token has "agent:exec" scope.',
- );
- }
- } else {
- setScanError(message);
- }
- setHttpScanInProgress(false);
- setIsScanning(false);
- setScanProgress(null);
- setScanStartTime(null); // Stop the live timer
- }
- };
-
- // Handle saving notes
- const handleSaveNotes = async () => {
- setSaveError(null);
- const agentId = targetAgentId();
- if (!agentId) {
- setSaveError('Agent identifier unavailable for discovery');
- return;
- }
- try {
- await updateDiscoveryNotes(props.resourceType, agentId, props.resourceId, {
- user_notes: notesText(),
- });
- setEditingNotes(false);
- await refetch();
- } catch (err) {
- setSaveError(err instanceof Error ? err.message : 'Failed to save notes');
+ const confidenceInfo = createMemo(() => {
+ const current = discovery();
+ if (discovery.loading || !current || current.confidence === undefined || current.confidence === null) {
+ return null;
}
- };
-
- // Start editing notes
- const startEditingNotes = () => {
- const currentNotes = discovery()?.user_notes || '';
- setNotesText(currentNotes);
- setEditingNotes(true);
- };
-
- // Subscribe to WebSocket progress updates
- const resourceId = () => makeResourceId(props.resourceType, targetAgentId(), props.resourceId);
-
- createEffect(() => {
- const unsubscribe = eventBus.on('ai_discovery_progress', (progress) => {
- // Only update if this progress is for our resource
- if (progress && progress.resource_id === resourceId()) {
- // Always update progress display (shows current step, percentage, etc.)
- setScanProgress(progress);
-
- // If scan completed or failed via WebSocket, handle state update
- // BUT only if we didn't initiate this scan via HTTP (which handles its own state)
- if (
- (progress.status === 'completed' || progress.status === 'failed') &&
- !httpScanInProgress()
- ) {
- setIsScanning(false);
- // Fetch the updated discovery data
- // Use a small delay to ensure the backend has persisted the data
- setTimeout(async () => {
- const agentId = targetAgentId();
- if (!agentId) return;
- try {
- const result = await getDiscovery(props.resourceType, agentId, props.resourceId);
- if (result) {
- mutate(result);
- }
- } catch (err) {
- console.error('Failed to fetch discovery after completion:', err);
- }
- setScanProgress(null);
- }, 500);
- }
- }
- });
-
- onCleanup(() => {
- unsubscribe();
- });
+ return getConfidenceLevel(current.confidence);
});
- const confidenceInfo = () => {
- if (discovery.loading) return null;
- const d = discovery();
- if (!d || d.confidence === undefined || d.confidence === null) return null;
- return getConfidenceLevel(d.confidence);
- };
-
- // Check if discovery has meaningful data (not empty/unknown results)
- const hasValidDiscovery = () => {
- const d = discovery();
- if (!d) return false;
- // Consider valid if:
- // - Has a service name that's not empty and not "unknown" (case-insensitive)
- // - OR has a confidence value above 0
- // - OR has any discovered ports, facts, paths, etc.
- const hasServiceName = d.service_name && d.service_name.toLowerCase() !== 'unknown';
- const hasConfidence = typeof d.confidence === 'number' && d.confidence > 0;
- const hasPorts = d.ports && d.ports.length > 0;
- const hasFacts = d.facts && d.facts.length > 0;
- const hasPaths =
- (d.config_paths && d.config_paths.length > 0) ||
- (d.data_paths && d.data_paths.length > 0) ||
- (d.log_paths && d.log_paths.length > 0);
- const hasCliAccess = !!d.cli_access;
-
- return hasServiceName || hasConfidence || hasPorts || hasFacts || hasPaths || hasCliAccess;
- };
-
- // Accessor that returns discovery only when valid (for use with Show component)
- const validDiscovery = () => (!discovery.loading && hasValidDiscovery() ? discovery() : null);
-
return (
<div class="space-y-4">
{/* AI Provider Badge - Always visible when AI is configured */}
diff --git a/frontend-modern/src/components/Discovery/useDiscoveryTabState.ts b/frontend-modern/src/components/Discovery/useDiscoveryTabState.ts
new file mode 100644
index 0000000000..d550f2cc09
--- /dev/null
+++ b/frontend-modern/src/components/Discovery/useDiscoveryTabState.ts
@@ -0,0 +1,295 @@
+import { createEffect, createMemo, createResource, createSignal, onCleanup } from 'solid-js';
+
+import {
+ getConnectedAgents,
+ getDiscovery,
+ getDiscoveryInfo,
+ triggerDiscovery,
+ updateDiscoveryNotes,
+} from '@/api/discovery';
+import { eventBus } from '@/stores/events';
+import type { DiscoveryProgress, ResourceType } from '@/types/discovery';
+import { toDiscoveryAPIResourceType } from '@/utils/discoveryTarget';
+
+export interface DiscoveryTabStateProps {
+ resourceType: ResourceType;
+ agentId?: string;
+ resourceId: string;
+ hostname: string;
+ commandsEnabled?: boolean;
+}
+
+const makeResourceId = (type: ResourceType, agentId: string, resourceId: string) =>
+ `${toDiscoveryAPIResourceType(type) || type}:${agentId}:${resourceId}`;
+
+export function useDiscoveryTabState(props: DiscoveryTabStateProps) {
+ const [isScanning, setIsScanning] = createSignal(false);
+ const [editingNotes, setEditingNotes] = createSignal(false);
+ const [liveElapsedSeconds, setLiveElapsedSeconds] = createSignal(0);
+ const [scanStartTime, setScanStartTime] = createSignal<number | null>(null);
+ const [showLoadingSpinner, setShowLoadingSpinner] = createSignal(false);
+ const [notesText, setNotesText] = createSignal('');
+ const [saveError, setSaveError] = createSignal<string | null>(null);
+ const [scanError, setScanError] = createSignal<string | null>(null);
+ const [scanProgress, setScanProgress] = createSignal<DiscoveryProgress | null>(null);
+ const [scanSuccess, setScanSuccess] = createSignal(false);
+ const [showCommandsPreview, setShowCommandsPreview] = createSignal(false);
+ const [showExplanation, setShowExplanation] = createSignal(true);
+ const [httpScanInProgress, setHttpScanInProgress] = createSignal(false);
+
+ const targetAgentId = createMemo(() => props.agentId || '');
+ const discoverySourceKey = createMemo(
+ () => `${props.resourceType}|${targetAgentId()}|${props.resourceId}`,
+ );
+ const resourceId = createMemo(() =>
+ makeResourceId(props.resourceType, targetAgentId(), props.resourceId),
+ );
+
+ const [discoveryInfo] = createResource(
+ () => props.resourceType,
+ async (type) => {
+ try {
+ return await getDiscoveryInfo(type);
+ } catch {
+ return null;
+ }
+ },
+ );
+
+ const [connectedAgents] = createResource(async () => {
+ try {
+ return await getConnectedAgents();
+ } catch {
+ return { count: 0, agents: [] };
+ }
+ });
+
+ const hasConnectedAgent = createMemo(() => {
+ const agentId = targetAgentId();
+ const agents = connectedAgents()?.agents || [];
+
+ if (!agentId) return false;
+ if (agents.some((agent) => agent.agent_id === agentId)) return true;
+ if (agents.some((agent) => agent.hostname === props.hostname || agent.hostname === agentId)) {
+ return true;
+ }
+
+ return agents.length === 1;
+ });
+
+ const [discovery, { refetch, mutate }] = createResource(discoverySourceKey, async () => {
+ const agentId = targetAgentId();
+ if (!agentId) return null;
+
+ try {
+ return await getDiscovery(props.resourceType, agentId, props.resourceId);
+ } catch {
+ return null;
+ }
+ });
+
+ createEffect(() => {
+ void discoverySourceKey();
+ setIsScanning(false);
+ setHttpScanInProgress(false);
+ setScanProgress(null);
+ setScanError(null);
+ setScanSuccess(false);
+ setScanStartTime(null);
+ setLiveElapsedSeconds(0);
+ setShowLoadingSpinner(false);
+ setEditingNotes(false);
+ setSaveError(null);
+ });
+
+ createEffect(() => {
+ if (discovery.loading) {
+ const timer = setTimeout(() => {
+ if (discovery.loading) {
+ setShowLoadingSpinner(true);
+ }
+ }, 150);
+ onCleanup(() => clearTimeout(timer));
+ return;
+ }
+
+ setShowLoadingSpinner(false);
+ });
+
+ createEffect(() => {
+ const startedAt = scanStartTime();
+ if (!isScanning() || !startedAt) return;
+
+ const interval = setInterval(() => {
+ setLiveElapsedSeconds(Math.floor((Date.now() - startedAt) / 1000));
+ }, 1000);
+
+ onCleanup(() => clearInterval(interval));
+ });
+
+ const handleTriggerDiscovery = async (force = false) => {
+ setIsScanning(true);
+ setHttpScanInProgress(true);
+ setScanProgress(null);
+ setScanError(null);
+ setScanSuccess(false);
+ setScanStartTime(Date.now());
+ setLiveElapsedSeconds(0);
+
+ try {
+ const agentId = targetAgentId();
+ if (!agentId) {
+ setScanError('Agent identifier unavailable for discovery');
+ return;
+ }
+
+ const result = await triggerDiscovery(props.resourceType, agentId, props.resourceId, {
+ force,
+ hostname: props.hostname,
+ });
+ if (result) {
+ mutate(result);
+ }
+
+ setHttpScanInProgress(false);
+ setIsScanning(false);
+ setScanProgress(null);
+ setScanStartTime(null);
+ setScanSuccess(true);
+ setTimeout(() => setScanSuccess(false), 2000);
+ } catch (err) {
+ console.error('Discovery failed:', err);
+ const message = err instanceof Error ? err.message : 'Discovery scan failed';
+
+ if (message.includes('no connected agent')) {
+ if (props.commandsEnabled === false) {
+ setScanError(
+ 'Commands not enabled. Enable "Pulse Commands" in Settings → Unified Agents for this agent.',
+ );
+ } else if (props.commandsEnabled === true) {
+ setScanError(
+ 'Agent not connected for command execution. The API token may be missing the "agent:exec" scope. Check Settings → API Tokens.',
+ );
+ } else {
+ setScanError(
+ 'No agent available for command execution. Ensure "Pulse Commands" is enabled in Settings → Unified Agents and the API token has "agent:exec" scope.',
+ );
+ }
+ } else {
+ setScanError(message);
+ }
+
+ setHttpScanInProgress(false);
+ setIsScanning(false);
+ setScanProgress(null);
+ setScanStartTime(null);
+ }
+ };
+
+ const handleSaveNotes = async () => {
+ setSaveError(null);
+ const agentId = targetAgentId();
+ if (!agentId) {
+ setSaveError('Agent identifier unavailable for discovery');
+ return;
+ }
+
+ try {
+ await updateDiscoveryNotes(props.resourceType, agentId, props.resourceId, {
+ user_notes: notesText(),
+ });
+ setEditingNotes(false);
+ await refetch();
+ } catch (err) {
+ setSaveError(err instanceof Error ? err.message : 'Failed to save notes');
+ }
+ };
+
+ const startEditingNotes = () => {
+ setNotesText(discovery()?.user_notes || '');
+ setEditingNotes(true);
+ };
+
+ createEffect(() => {
+ const unsubscribe = eventBus.on('ai_discovery_progress', (progress) => {
+ if (!progress || progress.resource_id !== resourceId()) return;
+
+ setScanProgress(progress);
+
+ if (
+ (progress.status === 'completed' || progress.status === 'failed') &&
+ !httpScanInProgress()
+ ) {
+ setIsScanning(false);
+ setTimeout(async () => {
+ const agentId = targetAgentId();
+ if (!agentId) return;
+
+ try {
+ const result = await getDiscovery(props.resourceType, agentId, props.resourceId);
+ if (result) {
+ mutate(result);
+ }
+ } catch (err) {
+ console.error('Failed to fetch discovery after completion:', err);
+ }
+
+ setScanProgress(null);
+ }, 500);
+ }
+ });
+
+ onCleanup(() => {
+ unsubscribe();
+ });
+ });
+
+ const hasValidDiscovery = createMemo(() => {
+ const current = discovery();
+ if (!current) return false;
+
+ const hasServiceName = current.service_name && current.service_name.toLowerCase() !== 'unknown';
+ const hasConfidence = typeof current.confidence === 'number' && current.confidence > 0;
+ const hasPorts = current.ports && current.ports.length > 0;
+ const hasFacts = current.facts && current.facts.length > 0;
+ const hasPaths =
+ (current.config_paths && current.config_paths.length > 0) ||
+ (current.data_paths && current.data_paths.length > 0) ||
+ (current.log_paths && current.log_paths.length > 0);
+ const hasCliAccess = Boolean(current.cli_access);
+
+ return Boolean(hasServiceName || hasConfidence || hasPorts || hasFacts || hasPaths || hasCliAccess);
+ });
+
+ const validDiscovery = createMemo(() =>
+ !discovery.loading && hasValidDiscovery() ? discovery() : null,
+ );
+
+ return {
+ connectedAgents,
+ discovery,
+ discoveryInfo,
+ editingNotes,
+ handleSaveNotes,
+ handleTriggerDiscovery,
+ hasConnectedAgent,
+ hasValidDiscovery,
+ isScanning,
+ liveElapsedSeconds,
+ notesText,
+ saveError,
+ scanError,
+ scanProgress,
+ scanSuccess,
+ setEditingNotes,
+ setNotesText,
+ setScanError,
+ setShowCommandsPreview,
+ setShowExplanation,
+ showCommandsPreview,
+ showExplanation,
+ showLoadingSpinner,
+ startEditingNotes,
+ validDiscovery,
+ };
+}
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx
index dd945f9b82..f29aa73737 100644
--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx
+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx
@@ -1,6 +1,8 @@
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, within } from '@solidjs/testing-library';
+import discoveryTabSource from '@/components/Discovery/DiscoveryTab.tsx?raw';
+import discoveryTabStateSource from '@/components/Discovery/useDiscoveryTabState.ts?raw';
import type { Resource } from '@/types/resource';
import { ResourceDetailDrawer } from '@/components/Infrastructure/ResourceDetailDrawer';
@@ -94,6 +96,20 @@ const baseResource = (overrides: Partial<Resource>): Resource => ({
});
describe('ResourceDetailDrawer change history section', () => {
+ it('keeps discovery context presentation separate from discovery runtime ownership', () => {
+ expect(discoveryTabSource).toContain('useDiscoveryTabState');
+ expect(discoveryTabStateSource).toContain('export function useDiscoveryTabState');
+ expect(discoveryTabStateSource).toContain('createResource');
+ expect(discoveryTabStateSource).toContain("eventBus.on('ai_discovery_progress'");
+ expect(discoveryTabStateSource).toContain('triggerDiscovery(');
+ expect(discoveryTabStateSource).toContain('updateDiscoveryNotes(');
+ expect(discoveryTabSource).not.toContain("eventBus.on('ai_discovery_progress'");
+ expect(discoveryTabSource).not.toContain('createResource(');
+ expect(discoveryTabSource).not.toContain('getConnectedAgents(');
+ expect(discoveryTabSource).not.toContain('triggerDiscovery(');
+ expect(discoveryTabSource).not.toContain('updateDiscoveryNotes(');
+ });
+
it('keeps compact timeline summary chips in overview while showing one embedded change history section', async () => {
facetBundleMock.getFacetBundle.mockResolvedValueOnce({
capabilities: [
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index ca42fe3dbc..2ba9ef8aa7 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -3116,6 +3116,58 @@ class SubsystemLookupTest(unittest.TestCase):
],
)
+ def test_lookup_paths_assigns_discovery_tab_to_unified_resources(self) -> None:
+ result = lookup_paths(["frontend-modern/src/components/Discovery/DiscoveryTab.tsx"])
+ self.assertEqual(result["unowned_runtime_files"], [])
+
+ file_entry = result["files"][0]
+ self.assertEqual(file_entry["classification"], "runtime")
+ self.assertEqual(len(file_entry["matches"]), 1)
+
+ match = file_entry["matches"][0]
+ self.assertEqual(match["subsystem"], "unified-resources")
+ self.assertEqual(
+ match["contract"],
+ "docs/release-control/v6/internal/subsystems/unified-resources.md",
+ )
+ self.assertEqual(match["lane_context"]["lane_id"], "L13")
+ self.assertEqual(match["verification_requirement"]["id"], "resource-consumers")
+ self.assertEqual(
+ match["verification_requirement"]["exact_files"],
+ [
+ "frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx",
+ "frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.performance.contract.test.tsx",
+ "frontend-modern/src/components/Infrastructure/__tests__/UnifiedResourceTable.workloads-link.test.tsx",
+ "frontend-modern/src/components/Infrastructure/__tests__/infrastructureSelectors.test.ts",
+ "frontend-modern/src/components/Infrastructure/__tests__/resourceDetailMappers.test.ts",
+ "frontend-modern/src/hooks/__tests__/useDashboardTrends.test.ts",
+ "frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts",
+ "frontend-modern/src/pages/__tests__/Infrastructure.empty-state.test.tsx",
+ "frontend-modern/src/pages/__tests__/Infrastructure.pbs-pmg.test.tsx",
+ "frontend-modern/src/routing/__tests__/resourceLinks.test.ts",
+ "frontend-modern/src/stores/__tests__/websocket-unified.test.ts",
+ "frontend-modern/src/types/__tests__/resource.test.ts",
+ "internal/unifiedresources/code_standards_test.go",
+ ],
+ )
+
+ def test_lookup_paths_assigns_discovery_tab_state_owner_to_unified_resources(self) -> None:
+ result = lookup_paths(["frontend-modern/src/components/Discovery/useDiscoveryTabState.ts"])
+ self.assertEqual(result["unowned_runtime_files"], [])
+
+ file_entry = result["files"][0]
+ self.assertEqual(file_entry["classification"], "runtime")
+ self.assertEqual(len(file_entry["matches"]), 1)
+
+ match = file_entry["matches"][0]
+ self.assertEqual(match["subsystem"], "unified-resources")
+ self.assertEqual(
+ match["contract"],
+ "docs/release-control/v6/internal/subsystems/unified-resources.md",
+ )
+ self.assertEqual(match["lane_context"]["lane_id"], "L13")
+ self.assertEqual(match["verification_requirement"]["id"], "resource-consumers")
+
def test_lookup_paths_reports_dependent_contract_updates_for_shared_canonical_file(self) -> None:
result = lookup_paths(["internal/unifiedresources/views.go"])
file_entry = result["files"][0]