From 16b9e079a692425e13cbc56ca7b01f49e83cd234 Mon Sep 17 00:00:00 2001 From: rcourtman Date: Mon, 30 Mar 2026 22:44:34 +0100 Subject: [PATCH] Implement VMware assistant mention floor --- .../v6/internal/subsystems/ai-runtime.md | 7 + .../v6/internal/subsystems/api-contracts.md | 8 + .../internal/subsystems/unified-resources.md | 7 + .../src/api/__tests__/aiChatMentions.test.ts | 78 ++++ frontend-modern/src/api/aiChat.ts | 2 +- .../AI/Chat/MentionAutocomplete.tsx | 13 +- .../AI/Chat/__tests__/AIChat.test.tsx | 121 +++++- .../__tests__/MentionAutocomplete.test.tsx | 14 + .../src/components/AI/Chat/index.tsx | 84 +++- .../monitoredSystemModelGuardrails.test.ts | 2 +- internal/ai/chat/context_prefetch.go | 384 +++++++++++++----- .../chat/context_prefetch_additional_test.go | 110 ++++- internal/ai/chat/service.go | 28 +- .../chat/service_execute_additional_test.go | 84 +++- internal/unifiedresources/resolve.go | 72 ++++ internal/unifiedresources/resolve_context.go | 10 + internal/unifiedresources/resolve_test.go | 42 ++ .../tests/38-vmware-ai-chat-mentions.spec.ts | 244 +++++++++++ 18 files changed, 1168 insertions(+), 142 deletions(-) create mode 100644 frontend-modern/src/api/__tests__/aiChatMentions.test.ts create mode 100644 tests/integration/tests/38-vmware-ai-chat-mentions.spec.ts diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md index 63e41c393e..f7cef10c5e 100644 --- a/docs/release-control/v6/internal/subsystems/ai-runtime.md +++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md @@ -210,6 +210,13 @@ event, task, metrics-history, and snapshot-tree context for VMware-backed resources must stay reachable through those same shared read/query surfaces and canonical resource links rather than through a VMware-only AI tool or provider-local incident adapter. +That same VMware AI rule also now includes mention resolution. Frontend +Assistant mention payloads for VMware-backed `agent`, `vm`, `storage`, and +canonical `app-container` resources must preserve the shared unified resource +ID coming from `/api/resources`, and backend prefetch/runtime code must +resolve those mentions through canonical read-state lookups rather than +reconstructing provider-local IDs in the UI or adding VMware-only read routes +under `/api/vmware/*` for Assistant context. That same AI tool ownership also applies to recovery-backed storage reads. When `internal/ai/tools/adapters.go` returns recovery points with malformed persisted metadata omitted at the shared recovery-store boundary, the storage diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md index 371556590c..a905493f48 100644 --- a/docs/release-control/v6/internal/subsystems/api-contracts.md +++ b/docs/release-control/v6/internal/subsystems/api-contracts.md @@ -724,6 +724,14 @@ provider-local routes. Phase 1 must not add public `/api/vmware/resources`, `/api/vmware/history`, `/api/vmware/alerts`, or VMware-specific recovery transport just because the internal poller now projects VMware-backed resources into the shared canonical inventory. +That same shared API contract now also owns Assistant mention transport for +those canonical resources. `frontend-modern/src/api/aiChat.ts`, +`internal/api/ai_handler.go`, and `internal/api/ai_handlers.go` must preserve +structured mention payloads for canonical `agent`, `vm`, `storage`, and +`app-container` resources as shared unified-resource IDs plus shared mention +types, so VMware-backed reads stay on `/api/ai/*` and `/api/resources*` +instead of introducing VMware-only mention payloads or provider-local +inventory reads under `/api/vmware/*`. That same backend API boundary now also owns the negative space around assistant control. Wiring native TrueNAS app actions into `internal/api/router.go`, `internal/api/ai_handler.go`, or adjacent backend diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md index 09fa7e122a..a34b4420b4 100644 --- a/docs/release-control/v6/internal/subsystems/unified-resources.md +++ b/docs/release-control/v6/internal/subsystems/unified-resources.md @@ -868,6 +868,13 @@ policy requires governed handling, the shared label helper now prefers the canonical AI-safe summary for every redacted or local-only resource and only falls back to the canonical redacted label if that governed summary is missing, so path-only and IP-only redactions do not regress to raw identity +tokens in chat context. That same unified-resource contract now also owns the +canonical mention identity path for shared Assistant reads: chat surfaces must +carry the backend-issued unified resource ID for canonical `agent`, `vm`, +`storage`, and `app-container` records, and backend mention resolution must be +able to recover those resources by canonical ID and canonical name through the +shared read-state instead of relying on provider-local route families or +frontend reconstruction of VMware- or TrueNAS-specific coordinates. leakage or over-redaction. The frontend unified-resource hook now trusts backend canonical `policy` and `aiSafeSummary` values directly, so the canonical summary value stays diff --git a/frontend-modern/src/api/__tests__/aiChatMentions.test.ts b/frontend-modern/src/api/__tests__/aiChatMentions.test.ts new file mode 100644 index 0000000000..4d3679814c --- /dev/null +++ b/frontend-modern/src/api/__tests__/aiChatMentions.test.ts @@ -0,0 +1,78 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('@/utils/apiClient', () => ({ + apiFetchJSON: vi.fn(), + apiFetch: vi.fn(), +})); + +vi.mock('@/utils/logger', () => ({ + logger: { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, +})); + +import { AIChatAPI } from '@/api/aiChat'; +import { apiFetch } from '@/utils/apiClient'; + +describe('AIChatAPI mention payloads', () => { + const apiFetchMock = vi.mocked(apiFetch); + + beforeEach(() => { + apiFetchMock.mockReset(); + }); + + it('preserves canonical storage mention ids in the shared chat request body', async () => { + apiFetchMock.mockResolvedValueOnce({ + ok: true, + body: { + getReader: () => ({ + read: vi.fn().mockResolvedValueOnce({ done: true, value: undefined }), + releaseLock: vi.fn(), + }), + }, + } as unknown as Response); + + await AIChatAPI.chat( + 'check @NVMe Primary', + undefined, + undefined, + vi.fn(), + undefined, + [ + { + id: 'storage-vmware-1', + name: 'NVMe Primary', + type: 'storage', + node: 'Lab VC', + }, + ], + ); + + expect(apiFetchMock).toHaveBeenCalledWith( + '/api/ai/chat', + expect.objectContaining({ + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Accept: 'text/event-stream', + }, + body: JSON.stringify({ + prompt: 'check @NVMe Primary', + session_id: undefined, + model: undefined, + mentions: [ + { + id: 'storage-vmware-1', + name: 'NVMe Primary', + type: 'storage', + node: 'Lab VC', + }, + ], + }), + }), + ); + }); +}); diff --git a/frontend-modern/src/api/aiChat.ts b/frontend-modern/src/api/aiChat.ts index c3916b129d..61507a3bae 100644 --- a/frontend-modern/src/api/aiChat.ts +++ b/frontend-modern/src/api/aiChat.ts @@ -14,7 +14,7 @@ export interface ChatSession { message_count: number; } -export type ChatMentionType = 'vm' | 'system-container' | 'app-container' | 'agent'; +export type ChatMentionType = 'vm' | 'system-container' | 'app-container' | 'agent' | 'storage'; export interface ChatMention { id: string; diff --git a/frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx b/frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx index c764dc3f48..aac95dd0c7 100644 --- a/frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx +++ b/frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx @@ -5,7 +5,7 @@ import { getSimpleStatusIndicator } from '@/utils/status'; export interface MentionResource { id: string; label: string; - type: 'vm' | 'system-container' | 'app-container' | 'agent'; + type: 'vm' | 'system-container' | 'app-container' | 'agent' | 'storage'; status?: string; node?: string; } @@ -117,6 +117,17 @@ export function MentionAutocomplete(props: MentionAutocompleteProps) { /> ); + case 'storage': + return ( + + + + ); default: return ( 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 c45ce81f52..47f061c50f 100644 --- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx +++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx @@ -149,6 +149,16 @@ vi.mock('../MentionAutocomplete', () => ({ > select-first + {props.resources.map((resource) => ( + + ))} ), })); @@ -593,7 +603,7 @@ describe('AIChat', () => { ); }); - fireEvent.click(screen.getByTestId('mention-select-first')); + fireEvent.click(screen.getByTestId('mention-select-app-container:truenas-main:nextcloud')); fireEvent.keyDown(textarea, { key: 'Enter' }); expect(mockChat.sendMessage).toHaveBeenCalledWith( @@ -610,6 +620,115 @@ describe('AIChat', () => { ); }); + it('preserves canonical VMware vm and storage mention IDs in the shared payload', async () => { + const vmwareResources = [ + { + id: 'vmware-vm-1', + type: 'vm' as const, + name: 'app-01', + displayName: 'App 01', + status: 'running', + parentId: 'vmware-host-1', + parentName: 'esxi-01.lab.local', + platformType: 'vmware-vsphere', + sourceType: 'api', + vmware: { + managedObjectId: 'vm-201', + runtimeHostName: 'esxi-01.lab.local', + connectionName: 'Lab VC', + }, + }, + { + id: 'vmware-datastore-1', + type: 'storage' as const, + name: 'nvme-primary', + displayName: 'NVMe Primary', + status: 'online', + parentName: 'Lab VC', + platformType: 'vmware-vsphere', + sourceType: 'api', + vmware: { + managedObjectId: 'datastore-11', + connectionName: 'Lab VC', + }, + }, + ]; + mockByType.mockImplementation((type: string) => { + switch (type) { + case 'vm': + return [vmwareResources[0]]; + case 'storage': + return [vmwareResources[1]]; + default: + return []; + } + }); + mockResources.mockReturnValue(vmwareResources); + + renderChat(); + const textarea = screen.getByPlaceholderText( + 'Ask about your infrastructure...', + ) as HTMLTextAreaElement; + + Object.defineProperty(textarea, 'selectionStart', { value: 4, writable: true }); + fireEvent.input(textarea, { target: { value: '@app' } }); + + await waitFor(() => { + expect(screen.getByTestId('mention-autocomplete').getAttribute('data-resource-ids')).toContain( + 'vmware-vm-1', + ); + }); + + fireEvent.click(screen.getByTestId('mention-select-vmware-vm-1')); + fireEvent.keyDown(textarea, { key: 'Enter' }); + + await waitFor(() => { + expect(mockChat.sendMessage).toHaveBeenCalledWith( + '@App 01', + [ + expect.objectContaining({ + id: 'vmware-vm-1', + name: 'App 01', + type: 'vm', + node: 'esxi-01.lab.local', + }), + ], + undefined, + ); + }); + + mockChat.sendMessage.mockClear(); + await waitFor(() => { + expect(textarea.value).toBe(''); + }); + Object.defineProperty(textarea, 'selectionStart', { value: 5, writable: true }); + fireEvent.input(textarea, { target: { value: '@nvme' } }); + + await waitFor(() => { + expect(screen.getByTestId('mention-autocomplete').getAttribute('data-resource-ids')).toContain( + 'vmware-datastore-1', + ); + }); + + fireEvent.click(screen.getByTestId('mention-select-vmware-datastore-1')); + fireEvent.keyDown(textarea, { key: 'Enter' }); + + await waitFor(() => { + expect(mockChat.sendMessage).toHaveBeenCalledWith( + '@NVMe Primary', + [ + expect.objectContaining({ + id: 'vmware-datastore-1', + name: 'NVMe Primary', + type: 'storage', + node: 'Lab VC', + }), + ], + undefined, + ); + }); + }); + it('inserts the governed display label into the prompt when a mention is selected', async () => { const governedPolicy = { sensitivity: 'restricted' as const, diff --git a/frontend-modern/src/components/AI/Chat/__tests__/MentionAutocomplete.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/MentionAutocomplete.test.tsx index 014c09033c..d12a815ce2 100644 --- a/frontend-modern/src/components/AI/Chat/__tests__/MentionAutocomplete.test.tsx +++ b/frontend-modern/src/components/AI/Chat/__tests__/MentionAutocomplete.test.tsx @@ -46,6 +46,13 @@ const defaultResources: MentionResource[] = [ status: 'stopped', node: undefined, }), + makeResource({ + id: 'storage-1', + label: 'nvme-primary', + type: 'storage', + status: 'online', + node: 'Lab VC', + }), ]; const defaultPosition = { top: 100, left: 200 }; @@ -136,6 +143,13 @@ describe('MentionAutocomplete', () => { expect(screen.getByText('pve1', { exact: false })).toBeInTheDocument(); }); + it('shows the storage type label for storage resources', () => { + renderAutocomplete({ query: 'nvme' }); + const resourceBtn = screen.getByText('nvme-primary').closest('button')!; + expect(resourceBtn.textContent).toContain('storage'); + expect(resourceBtn.textContent).toContain('Lab VC'); + }); + it('does not show node separator when node is absent', () => { renderAutocomplete({ query: 'bare-metal' }); const resourceBtn = screen.getByText('bare-metal-01').closest('button')!; diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx index a94195d769..fb81b28ca8 100644 --- a/frontend-modern/src/components/AI/Chat/index.tsx +++ b/frontend-modern/src/components/AI/Chat/index.tsx @@ -437,16 +437,64 @@ export const AIChat: Component = (props) => { const parseLegacyVmid = ( resource: Resource, platformData: Record | undefined, - ): number => { + ): number | undefined => { const vmidRaw = platformData?.vmid; - if (typeof vmidRaw === 'number' && Number.isFinite(vmidRaw)) return vmidRaw; + if (typeof vmidRaw === 'number' && Number.isFinite(vmidRaw) && vmidRaw > 0) return vmidRaw; if (typeof vmidRaw === 'string') { const parsed = parseInt(vmidRaw, 10); - if (Number.isFinite(parsed)) return parsed; + if (Number.isFinite(parsed) && parsed > 0) return parsed; } - const idTail = resource.id.split('-').pop() ?? '0'; - const parsed = parseInt(idTail, 10); - return Number.isFinite(parsed) ? parsed : 0; + return undefined; + }; + + const getVMMentionNode = (resource: Resource): string => { + const platformData = readPlatformData(resource); + return ( + asString(platformData?.node) || + asString(resource.vmware?.runtimeHostName) || + asString(resource.vmware?.runtimeHostId) || + resource.parentName || + '' + ); + }; + + const getVMMentionId = (resource: Resource): string => { + if (resource.id.startsWith('vm:')) { + return resource.id; + } + + const platformData = readPlatformData(resource); + const node = getVMMentionNode(resource); + const vmid = parseLegacyVmid(resource, platformData); + if (node && vmid !== undefined) { + return `vm:${node}:${vmid}`; + } + + return resource.id; + }; + + const getSystemContainerMentionId = (resource: Resource): string => { + if (resource.id.startsWith('system-container:')) { + return resource.id; + } + + const platformData = readPlatformData(resource); + const node = asString(platformData?.node) || resource.parentName || ''; + const vmid = parseLegacyVmid(resource, platformData); + if (node && vmid !== undefined) { + return `system-container:${node}:${vmid}`; + } + + return resource.id; + }; + + const getStorageMentionNode = (resource: Resource): string => { + return ( + resource.parentName || + asString(resource.vmware?.connectionName) || + asString(resource.vmware?.runtimeHostName) || + '' + ); }; const nodes = byType('agent'); @@ -454,6 +502,7 @@ export const AIChat: Component = (props) => { const containers = [...byType('system-container'), ...byType('oci-container')]; const dockerHosts = byType('docker-host'); const appContainers = byType('app-container'); + const storageResources = byType('storage'); const agentResources = allResources().filter((resource) => isAgentFacetInfrastructureResource(resource), ); @@ -461,12 +510,9 @@ export const AIChat: Component = (props) => { // Add VMs for (const vm of vms) { - const platformData = readPlatformData(vm); - const nodeRaw = platformData?.node; - const node = typeof nodeRaw === 'string' ? nodeRaw : ''; - const vmid = parseLegacyVmid(vm, platformData); + const node = getVMMentionNode(vm); mentionCandidates.push({ - id: `vm:${node}:${vmid}`, + id: getVMMentionId(vm), label: getPreferredResourceDisplayName(vm), type: 'vm', status: vm.status === 'running' ? 'running' : 'stopped', @@ -477,11 +523,9 @@ export const AIChat: Component = (props) => { // Add LXC/system containers (includes OCI containers). for (const container of containers) { const platformData = readPlatformData(container); - const nodeRaw = platformData?.node; - const node = typeof nodeRaw === 'string' ? nodeRaw : ''; - const vmid = parseLegacyVmid(container, platformData); + const node = asString(platformData?.node) || container.parentName || ''; mentionCandidates.push({ - id: `system-container:${node}:${vmid}`, + id: getSystemContainerMentionId(container), label: getPreferredResourceDisplayName(container), type: 'system-container', status: container.status === 'running' ? 'running' : 'stopped', @@ -519,6 +563,16 @@ export const AIChat: Component = (props) => { }); } + for (const storage of storageResources) { + mentionCandidates.push({ + id: storage.id, + label: getPreferredResourceDisplayName(storage), + type: 'storage', + status: storage.status, + node: getStorageMentionNode(storage), + }); + } + // Add nodes for (const node of nodes) { mentionCandidates.push({ diff --git a/frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.ts b/frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.ts index cea4ea745b..f9d0d9a0b4 100644 --- a/frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.ts +++ b/frontend-modern/src/components/Settings/__tests__/monitoredSystemModelGuardrails.test.ts @@ -1020,7 +1020,7 @@ describe('monitored-system model guardrails', () => { expect(mentionAutocompleteSource).not.toContain('const getStatusColor ='); expect(mentionAutocompleteSource).toContain("| 'system-container'"); expect(mentionAutocompleteSource).not.toContain("| 'container'"); - expect(mentionAutocompleteSource).not.toContain("| 'storage'"); + expect(mentionAutocompleteSource).toContain("| 'storage'"); expect(mentionAutocompleteSource).not.toContain("| 'host'"); }); diff --git a/internal/ai/chat/context_prefetch.go b/internal/ai/chat/context_prefetch.go index fd5fa135b6..bb42bcee45 100644 --- a/internal/ai/chat/context_prefetch.go +++ b/internal/ai/chat/context_prefetch.go @@ -3,6 +3,7 @@ package chat import ( "context" "fmt" + "strconv" "strings" "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools" @@ -12,13 +13,14 @@ import ( // ResourceMention represents a detected resource mention in a user message type ResourceMention struct { - Name string - ResourceType string // "vm", "system-container", "app-container", "agent", "node" - ResourceID string - TargetID string - MatchedText string // The actual text that matched - Policy *unifiedresources.ResourcePolicy - AISafeSummary string + Name string + ResourceType string // "vm", "system-container", "app-container", "agent", "node" + ResourceID string + TargetID string + MatchedText string // The actual text that matched + Policy *unifiedresources.ResourcePolicy + AISafeSummary string + UnifiedResourceID string // Docker-specific: bind mounts (source -> destination) BindMounts []MountInfo // Full routing chain (for Docker containers) @@ -191,14 +193,22 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMe seen[nameLower] = true resolved := unifiedresources.ResolveResourceContext(rs, name) policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource) + resourceID := "" + if vmid := vm.VMID(); vmid > 0 { + resourceID = strconv.Itoa(vmid) + } + targetID := strings.TrimSpace(vm.Node()) + resourceID = firstNonEmptyTrimmed(resourceID, mentionResourceIDFromResolved("vm", resolved.Resource)) + targetID = firstNonEmptyTrimmed(targetID, mentionTargetIDFromResolved("vm", resolved.Resource)) mentions = append(mentions, ResourceMention{ - Name: name, - ResourceType: "vm", - ResourceID: fmt.Sprintf("%d", vm.VMID()), - TargetID: vm.Node(), - MatchedText: name, - Policy: policy, - AISafeSummary: aiSafeSummary, + Name: name, + ResourceType: "vm", + ResourceID: resourceID, + TargetID: targetID, + MatchedText: name, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedUnifiedResourceID(resolved.Resource), }) } } @@ -218,14 +228,22 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMe seen[nameLower] = true resolved := unifiedresources.ResolveResourceContext(rs, name) policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource) + resourceID := "" + if vmid := ct.VMID(); vmid > 0 { + resourceID = strconv.Itoa(vmid) + } + targetID := strings.TrimSpace(ct.Node()) + resourceID = firstNonEmptyTrimmed(resourceID, mentionResourceIDFromResolved("system-container", resolved.Resource)) + targetID = firstNonEmptyTrimmed(targetID, mentionTargetIDFromResolved("system-container", resolved.Resource)) mentions = append(mentions, ResourceMention{ - Name: name, - ResourceType: "system-container", - ResourceID: fmt.Sprintf("%d", ct.VMID()), - TargetID: ct.Node(), - MatchedText: name, - Policy: policy, - AISafeSummary: aiSafeSummary, + Name: name, + ResourceType: "system-container", + ResourceID: resourceID, + TargetID: targetID, + MatchedText: name, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedUnifiedResourceID(resolved.Resource), }) } } @@ -278,19 +296,48 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMe loc := resolved.Location mentions = append(mentions, ResourceMention{ - Name: name, - ResourceType: "app-container", - ResourceID: container.ContainerID(), - TargetID: hostID, - MatchedText: name, - Policy: policy, - AISafeSummary: aiSafeSummary, - BindMounts: mounts, - DockerHostName: loc.DockerHostName, - DockerHostType: loc.DockerHostType, - DockerHostVMID: loc.DockerHostVMID, - NodeName: loc.Node, - TargetHost: loc.TargetHost, + Name: name, + ResourceType: "app-container", + ResourceID: container.ContainerID(), + TargetID: hostID, + MatchedText: name, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedUnifiedResourceID(resolved.Resource), + BindMounts: mounts, + DockerHostName: loc.DockerHostName, + DockerHostType: loc.DockerHostType, + DockerHostVMID: loc.DockerHostVMID, + NodeName: loc.Node, + TargetHost: loc.TargetHost, + }) + } + } + } + } + + // Check canonical storage resources (including VMware datastores) via ReadState. + if rs != nil { + for _, storage := range rs.StoragePools() { + if storage == nil { + continue + } + name := storage.Name() + nameLower := strings.ToLower(name) + if nameLower != "" && len(nameLower) >= 3 && matchesResource(messageLower, messageWords, nameLower) { + if !seen[nameLower] { + seen[nameLower] = true + resolved := unifiedresources.ResolveResourceContext(rs, name) + policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource) + mentions = append(mentions, ResourceMention{ + Name: name, + ResourceType: "storage", + ResourceID: firstNonEmptyTrimmed(strings.TrimSpace(storage.SourceID()), mentionResourceIDFromResolved("storage", resolved.Resource)), + TargetID: firstNonEmptyTrimmed(strings.TrimSpace(storage.Node()), strings.TrimSpace(storage.Instance()), mentionTargetIDFromResolved("storage", resolved.Resource)), + MatchedText: name, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedUnifiedResourceID(resolved.Resource), }) } } @@ -312,14 +359,15 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMe policy, aiSafeSummary := resourceMentionGovernance(resolved.Resource) loc := resolved.Location mentions = append(mentions, ResourceMention{ - Name: name, - ResourceType: "node", - ResourceID: name, - TargetID: name, - MatchedText: name, - Policy: policy, - AISafeSummary: aiSafeSummary, - TargetHost: loc.TargetHost, + Name: name, + ResourceType: "node", + ResourceID: name, + TargetID: name, + MatchedText: name, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedUnifiedResourceID(resolved.Resource), + TargetHost: loc.TargetHost, }) } } @@ -343,14 +391,15 @@ func (p *ContextPrefetcher) extractResourceMentions(message string) []ResourceMe // Use AgentID which maps to the original models.Host.ID hostID := host.AgentID() mentions = append(mentions, ResourceMention{ - Name: hostname, - ResourceType: "agent", - ResourceID: hostID, - TargetID: hostID, - MatchedText: hostname, - Policy: policy, - AISafeSummary: aiSafeSummary, - TargetHost: loc.TargetHost, + Name: hostname, + ResourceType: "agent", + ResourceID: hostID, + TargetID: hostID, + MatchedText: hostname, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedUnifiedResourceID(resolved.Resource), + TargetHost: loc.TargetHost, }) } } @@ -492,17 +541,20 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMen node := sm.Node if len(parts) >= 3 { node = parts[1] - vmID = parts[2] + vmID = strings.Join(parts[2:], ":") } + vmID = firstNonEmptyTrimmed(vmID, mentionResourceIDFromResolved("vm", resolved.Resource)) + node = firstNonEmptyTrimmed(node, mentionTargetIDFromResolved("vm", resolved.Resource)) mentions = append(mentions, ResourceMention{ - Name: sm.Name, - ResourceType: "vm", - ResourceID: vmID, - TargetID: node, - MatchedText: sm.Name, - Policy: policy, - AISafeSummary: aiSafeSummary, - TargetHost: loc.TargetHost, + Name: sm.Name, + ResourceType: "vm", + ResourceID: vmID, + TargetID: node, + MatchedText: sm.Name, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource), + TargetHost: loc.TargetHost, }) case "system-container": @@ -510,21 +562,29 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMen node := sm.Node if len(parts) >= 3 { node = parts[1] - vmID = parts[2] + vmID = strings.Join(parts[2:], ":") } + vmID = firstNonEmptyTrimmed(vmID, mentionResourceIDFromResolved("system-container", resolved.Resource)) + node = firstNonEmptyTrimmed(node, mentionTargetIDFromResolved("system-container", resolved.Resource)) mentions = append(mentions, ResourceMention{ - Name: sm.Name, - ResourceType: "system-container", - ResourceID: vmID, - TargetID: node, - MatchedText: sm.Name, - Policy: policy, - AISafeSummary: aiSafeSummary, - TargetHost: loc.TargetHost, + Name: sm.Name, + ResourceType: "system-container", + ResourceID: vmID, + TargetID: node, + MatchedText: sm.Name, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource), + TargetHost: loc.TargetHost, }) case "app-container": hostID, containerID := parseStructuredAppContainerMentionID(sm.ID, rs) + if resolved.Resource != nil { + resolvedHost, resolvedContainerID := resolvedAppContainerMentionCoordinates(resolved.Resource) + hostID = firstNonEmptyTrimmed(hostID, resolvedHost) + containerID = firstNonEmptyTrimmed(containerID, resolvedContainerID) + } // Gather bind mounts via ReadState var mounts []MountInfo @@ -548,31 +608,48 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMen } mentions = append(mentions, ResourceMention{ - Name: sm.Name, - ResourceType: "app-container", - ResourceID: containerID, - TargetID: hostID, - MatchedText: sm.Name, - Policy: policy, - AISafeSummary: aiSafeSummary, - BindMounts: mounts, - DockerHostName: loc.DockerHostName, - DockerHostType: loc.DockerHostType, - DockerHostVMID: loc.DockerHostVMID, - NodeName: loc.Node, - TargetHost: loc.TargetHost, + Name: sm.Name, + ResourceType: "app-container", + ResourceID: containerID, + TargetID: hostID, + MatchedText: sm.Name, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource), + BindMounts: mounts, + DockerHostName: loc.DockerHostName, + DockerHostType: loc.DockerHostType, + DockerHostVMID: loc.DockerHostVMID, + NodeName: loc.Node, + TargetHost: loc.TargetHost, + }) + + case "storage": + resourceID := firstNonEmptyTrimmed(sm.ID, resolvedUnifiedResourceID(resolved.Resource), mentionResourceIDFromResolved("storage", resolved.Resource)) + targetID := firstNonEmptyTrimmed(sm.Node, mentionTargetIDFromResolved("storage", resolved.Resource), loc.TargetHost) + mentions = append(mentions, ResourceMention{ + Name: sm.Name, + ResourceType: "storage", + ResourceID: resourceID, + TargetID: targetID, + MatchedText: sm.Name, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource), + TargetHost: firstNonEmptyTrimmed(loc.TargetHost, targetID), }) case "node": mentions = append(mentions, ResourceMention{ - Name: sm.Name, - ResourceType: "node", - ResourceID: sm.Name, - TargetID: sm.Name, - MatchedText: sm.Name, - Policy: policy, - AISafeSummary: aiSafeSummary, - TargetHost: loc.TargetHost, + Name: sm.Name, + ResourceType: "node", + ResourceID: sm.Name, + TargetID: sm.Name, + MatchedText: sm.Name, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource), + TargetHost: loc.TargetHost, }) case "agent": @@ -581,14 +658,15 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMen hostID = strings.Join(parts[1:], ":") } mentions = append(mentions, ResourceMention{ - Name: sm.Name, - ResourceType: "agent", - ResourceID: hostID, - TargetID: hostID, - MatchedText: sm.Name, - Policy: policy, - AISafeSummary: aiSafeSummary, - TargetHost: loc.TargetHost, + Name: sm.Name, + ResourceType: "agent", + ResourceID: hostID, + TargetID: hostID, + MatchedText: sm.Name, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource), + TargetHost: loc.TargetHost, }) default: @@ -604,14 +682,15 @@ func (p *ContextPrefetcher) resolveStructuredMentions(structured []StructuredMen Str("type", sm.Type). Msg("[ContextPrefetch] Unknown structured mention type, falling back to ResolveResource") mentions = append(mentions, ResourceMention{ - Name: sm.Name, - ResourceType: resourceType, - ResourceID: sm.ID, - TargetID: sm.Node, - MatchedText: sm.Name, - Policy: policy, - AISafeSummary: aiSafeSummary, - TargetHost: loc.TargetHost, + Name: sm.Name, + ResourceType: resourceType, + ResourceID: firstNonEmptyTrimmed(sm.ID, mentionResourceIDFromResolved(resourceType, resolved.Resource)), + TargetID: firstNonEmptyTrimmed(sm.Node, mentionTargetIDFromResolved(resourceType, resolved.Resource)), + MatchedText: sm.Name, + Policy: policy, + AISafeSummary: aiSafeSummary, + UnifiedResourceID: resolvedStructuredUnifiedResourceID(sm.ID, resolved.Resource), + TargetHost: loc.TargetHost, }) } } @@ -714,6 +793,101 @@ func appContainerProviderUID(resource unifiedresources.Resource, host string) st return "" } +func resolvedAppContainerMentionCoordinates(resource *unifiedresources.Resource) (hostID string, containerID string) { + if resource == nil { + return "", "" + } + hostID = appContainerResourceHost(*resource) + containerID = appContainerProviderUID(*resource, hostID) + return strings.TrimSpace(hostID), strings.TrimSpace(containerID) +} + +func resolvedUnifiedResourceID(resource *unifiedresources.Resource) string { + if resource == nil { + return "" + } + return strings.TrimSpace(resource.ID) +} + +func resolvedStructuredUnifiedResourceID(structuredID string, resource *unifiedresources.Resource) string { + return firstNonEmptyTrimmed(resolvedUnifiedResourceID(resource), structuredID) +} + +func mentionResourceIDFromResolved(resourceType string, resource *unifiedresources.Resource) string { + if resource == nil { + return "" + } + + switch tools.CanonicalDiscoveryResourceType(resourceType) { + case "vm", "system-container": + if resource.Proxmox != nil && resource.Proxmox.VMID > 0 { + return strconv.Itoa(resource.Proxmox.VMID) + } + if resource.VMware != nil { + return strings.TrimSpace(resource.VMware.ManagedObjectID) + } + case "storage": + if resource.Proxmox != nil { + return strings.TrimSpace(resource.Proxmox.SourceID) + } + if resource.VMware != nil { + return strings.TrimSpace(resource.VMware.ManagedObjectID) + } + case "agent": + if resource.Agent != nil { + return strings.TrimSpace(resource.Agent.AgentID) + } + } + + return "" +} + +func mentionTargetIDFromResolved(resourceType string, resource *unifiedresources.Resource) string { + if resource == nil { + return "" + } + + switch tools.CanonicalDiscoveryResourceType(resourceType) { + case "vm", "system-container": + if resource.Proxmox != nil { + return strings.TrimSpace(resource.Proxmox.NodeName) + } + if resource.VMware != nil { + return firstNonEmptyTrimmed( + resource.VMware.RuntimeHostName, + resource.VMware.RuntimeHostID, + resource.ParentName, + ) + } + case "storage": + if resource.Proxmox != nil { + return firstNonEmptyTrimmed(resource.Proxmox.NodeName, resource.Proxmox.Instance) + } + if resource.VMware != nil { + return firstNonEmptyTrimmed( + resource.ParentName, + resource.VMware.ConnectionName, + resource.VMware.RuntimeHostName, + ) + } + case "agent": + if resource.Agent != nil { + return strings.TrimSpace(resource.Agent.AgentID) + } + } + + return "" +} + +func firstNonEmptyTrimmed(values ...string) string { + for _, value := range values { + if trimmed := strings.TrimSpace(value); trimmed != "" { + return trimmed + } + } + return "" +} + func parseStructuredDockerMentionID(mentionID string, rs unifiedresources.ReadState) (hostID string, containerID string) { const prefix = "docker:" if !strings.HasPrefix(mentionID, prefix) { diff --git a/internal/ai/chat/context_prefetch_additional_test.go b/internal/ai/chat/context_prefetch_additional_test.go index e543a7b1cb..b50a412a9d 100644 --- a/internal/ai/chat/context_prefetch_additional_test.go +++ b/internal/ai/chat/context_prefetch_additional_test.go @@ -268,9 +268,15 @@ func TestContextPrefetcher_ResolveStructuredMentions_TrueNASCanonicalAppContaine }, }) + appContainers := rr.ListByType(unifiedresources.ResourceTypeAppContainer) + if len(appContainers) != 1 { + t.Fatalf("expected one TrueNAS app resource, got %d", len(appContainers)) + } + appResourceID := appContainers[0].ID + prefetcher := NewContextPrefetcher(rr, nil) mentions := prefetcher.resolveStructuredMentions([]StructuredMention{{ - ID: "app-container:truenas-main:nextcloud", + ID: appResourceID, Name: "Nextcloud", Type: "app-container", }}) @@ -283,8 +289,106 @@ func TestContextPrefetcher_ResolveStructuredMentions_TrueNASCanonicalAppContaine if mentions[0].TargetID != "truenas-main" || mentions[0].TargetHost != "truenas-main" { t.Fatalf("expected TrueNAS host routing, got %+v", mentions[0]) } - if mentions[0].ResourceID != "nextcloud" { - t.Fatalf("expected canonical provider uid, got %+v", mentions[0]) + if mentions[0].ResourceID != appResourceID { + t.Fatalf("expected canonical app mention id to be preserved, got %+v", mentions[0]) + } + if mentions[0].UnifiedResourceID != appResourceID { + t.Fatalf("expected unified resource id to be preserved, got %+v", mentions[0]) + } +} + +func TestContextPrefetcher_ResolveStructuredMentions_VMwareCanonicalIDs(t *testing.T) { + now := time.Now().UTC() + rr := unifiedresources.NewRegistry(nil) + rr.IngestRecords(unifiedresources.SourceVMware, []unifiedresources.IngestRecord{ + { + SourceID: "vc-1:host:host-101", + Resource: unifiedresources.Resource{ + Type: unifiedresources.ResourceTypeAgent, + Name: "esxi-01.lab.local", + Status: unifiedresources.StatusOnline, + LastSeen: now, + UpdatedAt: now, + VMware: &unifiedresources.VMwareData{ + ConnectionID: "vc-1", + ConnectionName: "Lab VC", + ManagedObjectID: "host-101", + EntityType: "host", + }, + }, + Identity: unifiedresources.ResourceIdentity{Hostnames: []string{"esxi-01.lab.local"}}, + }, + { + SourceID: "vc-1:vm:vm-201", + Resource: unifiedresources.Resource{ + ID: "vmware-vm-1", + Type: unifiedresources.ResourceTypeVM, + Name: "app-01", + Status: unifiedresources.StatusOnline, + LastSeen: now, + UpdatedAt: now, + ParentName: "esxi-01.lab.local", + VMware: &unifiedresources.VMwareData{ + ConnectionID: "vc-1", + ConnectionName: "Lab VC", + ManagedObjectID: "vm-201", + EntityType: "vm", + RuntimeHostName: "esxi-01.lab.local", + }, + }, + Identity: unifiedresources.ResourceIdentity{Hostnames: []string{"app-01"}}, + }, + { + SourceID: "vc-1:datastore:datastore-11", + Resource: unifiedresources.Resource{ + ID: "vmware-datastore-1", + Type: unifiedresources.ResourceTypeStorage, + Name: "nvme-primary", + Status: unifiedresources.StatusOnline, + LastSeen: now, + UpdatedAt: now, + ParentName: "Lab VC", + VMware: &unifiedresources.VMwareData{ + ConnectionID: "vc-1", + ConnectionName: "Lab VC", + ManagedObjectID: "datastore-11", + EntityType: "datastore", + }, + Storage: &unifiedresources.StorageMeta{Type: "vmfs"}, + }, + }, + }) + + vmResources := rr.ListByType(unifiedresources.ResourceTypeVM) + if len(vmResources) != 1 { + t.Fatalf("expected one VMware VM resource, got %d", len(vmResources)) + } + storageResources := rr.ListByType(unifiedresources.ResourceTypeStorage) + if len(storageResources) != 1 { + t.Fatalf("expected one VMware storage resource, got %d", len(storageResources)) + } + vmResourceID := vmResources[0].ID + storageResourceID := storageResources[0].ID + + prefetcher := NewContextPrefetcher(rr, nil) + mentions := prefetcher.resolveStructuredMentions([]StructuredMention{ + {ID: vmResourceID, Name: "app-01", Type: "vm"}, + {ID: storageResourceID, Name: "nvme-primary", Type: "storage"}, + }) + if len(mentions) != 2 { + t.Fatalf("expected two mentions, got %#v", mentions) + } + if mentions[0].ResourceType != "vm" || mentions[0].ResourceID != "vm-201" || mentions[0].TargetID != "esxi-01.lab.local" { + t.Fatalf("expected VMware VM routing coordinates, got %+v", mentions[0]) + } + if mentions[0].UnifiedResourceID != vmResourceID { + t.Fatalf("expected VMware VM unified resource id, got %+v", mentions[0]) + } + if mentions[1].ResourceType != "storage" || mentions[1].ResourceID != storageResourceID || mentions[1].TargetID != "Lab VC" { + t.Fatalf("expected VMware datastore shared coordinates, got %+v", mentions[1]) + } + if mentions[1].UnifiedResourceID != storageResourceID { + t.Fatalf("expected VMware datastore unified resource id, got %+v", mentions[1]) } } diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go index c37669842e..bbe63840d5 100644 --- a/internal/ai/chat/service.go +++ b/internal/ai/chat/service.go @@ -513,19 +513,21 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac resolvedCtx := sessions.GetResolvedContext(session.ID) for _, mention := range prefetchCtx.Mentions { // Build canonical resource ID: kind:scope:id - var resourceID string - switch mention.ResourceType { - case "system-container": - if mention.TargetID != "" { - resourceID = "system-container:" + mention.TargetID + ":" + mention.ResourceID - } - case "vm": - if mention.TargetID != "" { - resourceID = "vm:" + mention.TargetID + ":" + mention.ResourceID - } - case "app-container": - if mention.TargetHost != "" { - resourceID = "app-container:" + mention.TargetHost + ":" + mention.ResourceID + resourceID := strings.TrimSpace(mention.UnifiedResourceID) + if resourceID == "" { + switch mention.ResourceType { + case "system-container": + if mention.TargetID != "" { + resourceID = "system-container:" + mention.TargetID + ":" + mention.ResourceID + } + case "vm": + if mention.TargetID != "" { + resourceID = "vm:" + mention.TargetID + ":" + mention.ResourceID + } + case "app-container": + if mention.TargetHost != "" { + resourceID = "app-container:" + mention.TargetHost + ":" + mention.ResourceID + } } } if resourceID != "" { diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.go index 99a85b710d..8ee77e2d20 100644 --- a/internal/ai/chat/service_execute_additional_test.go +++ b/internal/ai/chat/service_execute_additional_test.go @@ -11,6 +11,7 @@ import ( "github.com/rcourtman/pulse-go-rewrite/internal/config" "github.com/rcourtman/pulse-go-rewrite/internal/models" "github.com/rcourtman/pulse-go-rewrite/internal/recovery" + "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources" ) type stubServiceProvider struct { @@ -109,6 +110,13 @@ func TestService_ExecuteStream_PrefetchMentionsAndOverrideModel(t *testing.T) { {ID: "vm:node1:101", VMID: 101, Name: "vm1", Node: "node1", Status: "running"}, }, } + readState := unifiedresources.NewRegistry(nil) + readState.IngestSnapshot(state) + vmResources := readState.ListByType(unifiedresources.ResourceTypeVM) + if len(vmResources) != 1 { + t.Fatalf("expected one canonical VM resource, got %d", len(vmResources)) + } + vmResourceID := vmResources[0].ID var capturedModel string svc := &Service{ @@ -116,7 +124,8 @@ func TestService_ExecuteStream_PrefetchMentionsAndOverrideModel(t *testing.T) { sessions: store, executor: executor, agenticLoop: loop, - contextPrefetcher: NewContextPrefetcher(newTestReadState(state), nil), + contextPrefetcher: NewContextPrefetcher(readState, nil), + provider: provider, started: true, providerFactory: func(modelStr string) (providers.StreamingProvider, error) { capturedModel = modelStr @@ -142,11 +151,82 @@ func TestService_ExecuteStream_PrefetchMentionsAndOverrideModel(t *testing.T) { } resolved := store.GetResolvedContext("sess-2") - if !resolved.WasRecentlyAccessed("vm:node1:101", time.Minute) { + if !resolved.WasRecentlyAccessed(vmResourceID, time.Minute) { t.Fatal("expected explicit access to be recorded for structured mention") } } +func TestService_ExecuteStream_PrefetchMentionsMarksVMwareUnifiedResourceAccess(t *testing.T) { + tmpDir := t.TempDir() + store, err := NewSessionStore(tmpDir) + if err != nil { + t.Fatalf("failed to create session store: %v", err) + } + + executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{}) + provider := &stubServiceProvider{} + loop := NewAgenticLoop(provider, executor, "system") + + now := time.Now().UTC() + rr := unifiedresources.NewRegistry(nil) + rr.IngestRecords(unifiedresources.SourceVMware, []unifiedresources.IngestRecord{{ + SourceID: "vc-1:vm:vm-201", + Resource: unifiedresources.Resource{ + ID: "vmware-vm-1", + Type: unifiedresources.ResourceTypeVM, + Name: "app-01", + Status: unifiedresources.StatusOnline, + LastSeen: now, + UpdatedAt: now, + ParentName: "esxi-01.lab.local", + VMware: &unifiedresources.VMwareData{ + ConnectionID: "vc-1", + ConnectionName: "Lab VC", + ManagedObjectID: "vm-201", + EntityType: "vm", + RuntimeHostName: "esxi-01.lab.local", + }, + }, + Identity: unifiedresources.ResourceIdentity{Hostnames: []string{"app-01"}}, + }}) + vmResources := rr.ListByType(unifiedresources.ResourceTypeVM) + if len(vmResources) != 1 { + t.Fatalf("expected one VMware VM resource, got %d", len(vmResources)) + } + vmResourceID := vmResources[0].ID + + svc := &Service{ + cfg: &config.AIConfig{ChatModel: "openai:primary"}, + sessions: store, + executor: executor, + agenticLoop: loop, + contextPrefetcher: NewContextPrefetcher(rr, nil), + provider: provider, + started: true, + providerFactory: func(modelStr string) (providers.StreamingProvider, error) { + return provider, nil + }, + } + + autonomous := true + req := ExecuteRequest{ + SessionID: "sess-vmware-mentions", + Prompt: "check @app-01", + Mentions: []StructuredMention{{ID: vmResourceID, Name: "app-01", Type: "vm"}}, + MaxTurns: 1, + AutonomousMode: &autonomous, + } + + if err := svc.ExecuteStream(context.Background(), req, func(StreamEvent) {}); err != nil { + t.Fatalf("ExecuteStream failed: %v", err) + } + + resolved := store.GetResolvedContext("sess-vmware-mentions") + if !resolved.WasRecentlyAccessed(vmResourceID, time.Minute) { + t.Fatal("expected explicit access to be recorded for VMware structured mention") + } +} + func TestService_ExecuteStream_AgenticPulseStorageSnapshotsToleratesMalformedRecoveryMetadata(t *testing.T) { tmpDir := t.TempDir() store, err := NewSessionStore(tmpDir) diff --git a/internal/unifiedresources/resolve.go b/internal/unifiedresources/resolve.go index 61110544ea..1daa8d67c4 100644 --- a/internal/unifiedresources/resolve.go +++ b/internal/unifiedresources/resolve.go @@ -106,6 +106,24 @@ func ResolveResource(rs ReadState, name string) models.ResourceLocation { return loc } + // Check storage pools, including VMware datastores and shared platform storage. + for _, pool := range rs.StoragePools() { + if pool == nil { + continue + } + if !storagePoolMatches(pool, name) { + continue + } + targetID := storagePoolTarget(pool) + return models.ResourceLocation{ + Found: true, + Name: pool.Name(), + ResourceType: "storage", + TargetID: targetID, + TargetHost: targetID, + } + } + // Check generic Hosts (Windows/Linux via Pulse Unified Agent). // Match on Hostname() or AgentID() for parity with state.Hosts[].Hostname/ID. // Use AgentID() as canonical target ID for host resources. @@ -311,6 +329,60 @@ func appContainerResourceMatches(resource Resource, name string) bool { return false } +func storagePoolMatches(pool *StoragePoolView, name string) bool { + name = strings.TrimSpace(name) + if pool == nil || name == "" { + return false + } + if strings.EqualFold(strings.TrimSpace(pool.Name()), name) || + strings.EqualFold(strings.TrimSpace(pool.ID()), name) || + strings.EqualFold(strings.TrimSpace(pool.SourceID()), name) { + return true + } + if pool.r != nil && pool.r.Canonical != nil { + for _, alias := range pool.r.Canonical.Aliases { + if strings.EqualFold(strings.TrimSpace(alias), name) { + return true + } + } + } + return false +} + +func storagePoolTarget(pool *StoragePoolView) string { + if pool == nil { + return "" + } + vmwareConnectionName := "" + vmwareRuntimeHost := "" + parentName := "" + if pool.r != nil { + parentName = strings.TrimSpace(pool.r.ParentName) + if pool.r.VMware != nil { + vmwareConnectionName = strings.TrimSpace(pool.r.VMware.ConnectionName) + vmwareRuntimeHost = strings.TrimSpace(pool.r.VMware.RuntimeHostName) + } + } + return firstNonEmptyResolvedString( + pool.Node(), + pool.Instance(), + parentName, + vmwareConnectionName, + vmwareRuntimeHost, + pool.ParentName(), + pool.Name(), + ) +} + +func firstNonEmptyResolvedString(values ...string) string { + for _, value := range values { + if trimmed := strings.TrimSpace(value); trimmed != "" { + return trimmed + } + } + return "" +} + func appContainerResourceHost(resource Resource) string { if host := strings.TrimSpace(resource.ParentName); host != "" { return host diff --git a/internal/unifiedresources/resolve_context.go b/internal/unifiedresources/resolve_context.go index 630578997d..61e1b8a1cb 100644 --- a/internal/unifiedresources/resolve_context.go +++ b/internal/unifiedresources/resolve_context.go @@ -82,6 +82,16 @@ func lookupResolvedResource(rs ReadState, loc models.ResourceLocation) *Resource } } + case "storage": + for _, pool := range rs.StoragePools() { + if pool == nil { + continue + } + if storagePoolMatches(pool, name) { + return cloneResourcePtr(pool.r) + } + } + case "agent": for _, host := range rs.Hosts() { if host == nil { diff --git a/internal/unifiedresources/resolve_test.go b/internal/unifiedresources/resolve_test.go index 78b668eab2..d45bbc7e3a 100644 --- a/internal/unifiedresources/resolve_test.go +++ b/internal/unifiedresources/resolve_test.go @@ -187,6 +187,48 @@ func TestResolveResource_TrueNASAppDoesNotUseDockerRouting(t *testing.T) { } } +func TestResolveResource_VMwareStorage(t *testing.T) { + rr := NewRegistry(nil) + now := time.Now().UTC() + rr.IngestRecords(SourceVMware, []IngestRecord{{ + SourceID: "vc-1:datastore:datastore-11", + Resource: Resource{ + Type: ResourceTypeStorage, + Name: "nvme-primary", + Status: StatusOnline, + LastSeen: now, + UpdatedAt: now, + ParentName: "Lab VC", + Storage: &StorageMeta{Type: "vmfs"}, + VMware: &VMwareData{ + ConnectionID: "vc-1", + ConnectionName: "Lab VC", + ManagedObjectID: "datastore-11", + EntityType: "datastore", + }, + }, + }}) + + loc := ResolveResource(rr, "nvme-primary") + if !loc.Found || loc.ResourceType != "storage" { + t.Fatalf("expected storage resource, got found=%v type=%q", loc.Found, loc.ResourceType) + } + if loc.TargetID != "Lab VC" || loc.TargetHost != "Lab VC" { + t.Fatalf("expected VMware storage target to route through Lab VC, got %+v", loc) + } + + resolved := ResolveResourceContext(rr, "nvme-primary") + if resolved.Resource == nil { + t.Fatal("expected resolved VMware storage resource") + } + if resolved.Resource.Type != ResourceTypeStorage { + t.Fatalf("expected storage resource payload, got %q", resolved.Resource.Type) + } + if resolved.Resource.VMware == nil || resolved.Resource.VMware.ManagedObjectID != "datastore-11" { + t.Fatalf("expected VMware datastore metadata, got %+v", resolved.Resource.VMware) + } +} + func TestLookupResolvedResource_TrueNASAppUsesCanonicalAppContainerSet(t *testing.T) { rr := newTrueNASAppRegistryFixture() diff --git a/tests/integration/tests/38-vmware-ai-chat-mentions.spec.ts b/tests/integration/tests/38-vmware-ai-chat-mentions.spec.ts new file mode 100644 index 0000000000..9cc889610b --- /dev/null +++ b/tests/integration/tests/38-vmware-ai-chat-mentions.spec.ts @@ -0,0 +1,244 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { expect, test as base } from '@playwright/test'; + +import { createAuthenticatedStorageState } from './helpers'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const SCREENSHOT_PATH = '/tmp/vmware-ai-chat-mentions.png'; + +type WorkerFixtures = { + authStorageStatePath: string; +}; + +const test = base.extend<{}, WorkerFixtures>({ + storageState: async ({ authStorageStatePath }, use) => { + await use(authStorageStatePath); + }, + authStorageStatePath: [async ({ browser }, use, workerInfo) => { + const storageStatePath = path.resolve( + __dirname, + '..', + '..', + 'tmp', + 'playwright-auth', + `vmware-ai-chat-mentions-${workerInfo.project.name}.json`, + ); + fs.mkdirSync(path.dirname(storageStatePath), { recursive: true }); + await createAuthenticatedStorageState(browser, storageStatePath); + try { + await use(storageStatePath); + } finally { + fs.rmSync(storageStatePath, { force: true }); + } + }, { scope: 'worker' }], +}); + +test.describe('VMware AI chat mentions', () => { + test.setTimeout(180_000); + + test('surfaces VMware resources through shared assistant mention paths only', async ({ + page, + }) => { + const unexpectedVMwareRequests: string[] = []; + + await page.route('**/api/vmware/**', async (route) => { + const url = new URL(route.request().url()); + const method = route.request().method(); + if (method === 'GET' && url.pathname === '/api/vmware/connections') { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify([]), + }); + return; + } + + unexpectedVMwareRequests.push(`${method} ${url.pathname}`); + await route.abort(); + }); + + await page.route('**/api/ai/status', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ running: true, engine: 'test' }), + }); + }); + + await page.route('**/api/ai/sessions', async (route) => { + if (route.request().method() !== 'GET') { + await route.continue(); + return; + } + + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify([]), + }); + }); + + await page.route('**/api/ai/settings', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + model: 'openai:gpt-4o-mini', + chat_model: '', + control_level: 'read_only', + discovery_enabled: true, + }), + }); + }); + + await page.route('**/api/ai/models', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + models: [{ id: 'openai:gpt-4o-mini', name: 'GPT-4o mini' }], + }), + }); + }); + + await page.route('**/api/resources**', async (route) => { + const requestUrl = new URL(route.request().url()); + if (requestUrl.pathname !== '/api/resources') { + await route.continue(); + return; + } + + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + data: [ + { + id: 'agent-vmware-host-1', + type: 'agent', + name: 'esxi-01.lab.local', + status: 'online', + lastSeen: '2026-03-30T09:00:00Z', + platformType: 'vmware-vsphere', + sourceType: 'api', + sources: ['vmware-vsphere'], + canonicalIdentity: { + displayName: 'ESXi 01', + hostname: 'esxi-01.lab.local', + primaryId: 'vmware:vc-1:host:host-101', + }, + agent: { + agentId: 'vc-1:host:host-101', + hostname: 'esxi-01.lab.local', + platform: 'VMware ESXi', + }, + vmware: { + connectionId: 'vc-1', + connectionName: 'Lab VC', + managedObjectId: 'host-101', + entityType: 'host', + }, + }, + { + id: 'vm-vmware-1', + type: 'vm', + name: 'app-01', + status: 'running', + lastSeen: '2026-03-30T09:00:00Z', + parentId: 'agent-vmware-host-1', + parentName: 'esxi-01.lab.local', + platformType: 'vmware-vsphere', + sourceType: 'api', + sources: ['vmware-vsphere'], + canonicalIdentity: { + displayName: 'App 01', + hostname: 'app-01.internal', + primaryId: 'vmware:vc-1:vm:vm-201', + }, + vmware: { + connectionId: 'vc-1', + connectionName: 'Lab VC', + managedObjectId: 'vm-201', + entityType: 'vm', + runtimeHostName: 'esxi-01.lab.local', + }, + }, + { + id: 'storage-vmware-1', + type: 'storage', + name: 'nvme-primary', + status: 'online', + lastSeen: '2026-03-30T09:00:00Z', + parentName: 'Lab VC', + platformType: 'vmware-vsphere', + sourceType: 'api', + sources: ['vmware-vsphere'], + canonicalIdentity: { + displayName: 'NVMe Primary', + primaryId: 'vmware:vc-1:datastore:datastore-11', + }, + storage: { + type: 'vmfs', + platform: 'vmware-vsphere', + }, + vmware: { + connectionId: 'vc-1', + connectionName: 'Lab VC', + managedObjectId: 'datastore-11', + entityType: 'datastore', + }, + }, + ], + meta: { + page: 1, + limit: 100, + total: 3, + totalPages: 1, + }, + }), + }); + }); + + const resourcesLoaded = page.waitForResponse((response) => { + const url = new URL(response.url()); + return url.pathname === '/api/resources' && response.request().method() === 'GET'; + }); + + await page.goto('/infrastructure?source=vmware-vsphere', { + waitUntil: 'domcontentloaded', + }); + await page.waitForURL(/\/infrastructure\?source=vmware-vsphere/, { + timeout: 15_000, + }); + await expect(page.getByTestId('infrastructure-page')).toBeVisible(); + await resourcesLoaded; + + await page.getByRole('button', { name: 'Expand Pulse Assistant' }).click(); + await expect(page.getByRole('heading', { name: 'Pulse Assistant', exact: true })).toBeVisible(); + + const textarea = page.getByPlaceholder('Ask about your infrastructure...'); + await textarea.click(); + await textarea.pressSequentially('@app'); + + const mentionSurface = page.locator('[data-mention-autocomplete]'); + await expect(mentionSurface.getByText('Resources')).toBeVisible(); + await expect(mentionSurface.getByRole('button', { name: /App 01/ })).toBeVisible(); + await expect(mentionSurface).toContainText('vm'); + await expect(mentionSurface).toContainText('esxi-01.lab.local'); + await mentionSurface.getByRole('button', { name: /App 01/ }).click(); + await expect(textarea).toHaveValue('@App 01 '); + + await textarea.fill(''); + await textarea.pressSequentially('@nvme'); + await expect(mentionSurface.getByRole('button', { name: /NVMe Primary/ })).toBeVisible(); + await expect(mentionSurface).toContainText('storage'); + await expect(mentionSurface).toContainText('Lab VC'); + await mentionSurface.getByRole('button', { name: /NVMe Primary/ }).click(); + await expect(textarea).toHaveValue('@NVMe Primary '); + + expect(unexpectedVMwareRequests).toEqual([]); + await page.screenshot({ path: SCREENSHOT_PATH, fullPage: true }); + }); +});