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.

fix(state): deduplicate PVE nodes and AI mention resources (#1217, #1214)

rcourtmanc92ccc122e11
diff --git a/frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx b/frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx
index a92df50db6..baa720f0de 100644
--- a/frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx
+++ b/frontend-modern/src/components/AI/Chat/MentionAutocomplete.tsx
@@ -1,12 +1,5 @@
import { createSignal, createEffect, For, Show, onCleanup } from 'solid-js';
-
-export interface MentionResource {
- id: string;
- name: string;
- type: 'vm' | 'container' | 'node' | 'storage' | 'docker' | 'host';
- status?: string;
- node?: string;
-}
+import type { MentionResource } from './mentionResources';
interface MentionAutocompleteProps {
query: string;
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/mentionResources.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/mentionResources.test.ts
new file mode 100644
index 0000000000..8f5074fd52
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/__tests__/mentionResources.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildMentionResources } from '@/components/AI/Chat/mentionResources';
+import type { State } from '@/types/api';
+
+describe('mentionResources', () => {
+ it('deduplicates host mentions when docker host and host agent represent the same machine', () => {
+ const state = {
+ nodes: [],
+ vms: [],
+ containers: [],
+ dockerHosts: [
+ {
+ id: 'host-1',
+ agentId: 'agent-1',
+ hostname: 'pve01.local',
+ displayName: 'pve01',
+ cpus: 4,
+ totalMemoryBytes: 16,
+ uptimeSeconds: 100,
+ status: 'online',
+ lastSeen: Date.now(),
+ intervalSeconds: 15,
+ containers: [],
+ },
+ ],
+ hosts: [
+ {
+ id: 'host-1',
+ hostname: 'pve01.local',
+ displayName: 'pve01',
+ status: 'offline',
+ lastSeen: Date.now(),
+ memory: { total: 16, used: 8, free: 8, usage: 50 },
+ },
+ ],
+ } as unknown as State;
+
+ const resources = buildMentionResources(state);
+ const hosts = resources.filter((resource) => resource.type === 'host');
+ expect(hosts).toHaveLength(1);
+ expect(hosts[0].status).toBe('online');
+ });
+
+ it('deduplicates cluster node mentions from multiple instances and keeps the healthiest status', () => {
+ const state = {
+ nodes: [
+ {
+ instance: 'cluster-entry-a',
+ name: 'pve01',
+ status: 'online',
+ clusterName: 'cluster-a',
+ },
+ {
+ instance: 'cluster-entry-b',
+ name: 'pve01',
+ status: 'offline',
+ clusterName: 'cluster-a',
+ },
+ ],
+ vms: [],
+ containers: [],
+ dockerHosts: [],
+ hosts: [],
+ } as unknown as State;
+
+ const resources = buildMentionResources(state);
+ const nodes = resources.filter((resource) => resource.type === 'node');
+ expect(nodes).toHaveLength(1);
+ expect(nodes[0].name).toBe('pve01');
+ expect(nodes[0].status).toBe('online');
+ });
+});
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
index c43e670c71..f86e357460 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -8,7 +8,8 @@ import { logger } from '@/utils/logger';
import { useChat } from './hooks/useChat';
import { ChatMessages } from './ChatMessages';
import { ModelSelector } from './ModelSelector';
-import { MentionAutocomplete, type MentionResource } from './MentionAutocomplete';
+import { MentionAutocomplete } from './MentionAutocomplete';
+import { buildMentionResources, type MentionResource } from './mentionResources';
import type { PendingApproval, PendingQuestion, ModelInfo } from './types';
const MODEL_LEGACY_STORAGE_KEY = 'pulse:ai_chat_model';
@@ -332,72 +333,9 @@ export const AIChat: Component<AIChatProps> = (props) => {
try {
const state = await MonitoringAPI.getState();
setIsCluster((state.nodes?.length || 0) > 1);
- const resources: MentionResource[] = [];
-
- // Add VMs
- for (const vm of state.vms || []) {
- resources.push({
- id: `vm:${vm.node}:${vm.vmid}`,
- name: vm.name,
- type: 'vm',
- status: vm.status,
- node: vm.node,
- });
- }
-
- // Add LXC containers
- for (const container of state.containers || []) {
- resources.push({
- id: `lxc:${container.node}:${container.vmid}`,
- name: container.name,
- type: 'container',
- status: container.status,
- node: container.node,
- });
- }
-
- // Add Docker hosts
- for (const host of state.dockerHosts || []) {
- resources.push({
- id: `host:${host.id}`,
- name: host.displayName || host.hostname || host.id,
- type: 'host',
- status: host.status || 'online',
- });
- // Add Docker containers
- for (const container of host.containers || []) {
- resources.push({
- id: `docker:${host.id}:${container.id}`,
- name: container.name,
- type: 'docker',
- status: container.state,
- node: host.hostname || host.id,
- });
- }
- }
-
- // Add nodes
- for (const node of state.nodes || []) {
- resources.push({
- id: `node:${node.instance}:${node.name}`,
- name: node.name,
- type: 'node',
- status: node.status,
- });
- }
-
- // Add standalone host agents
- for (const host of state.hosts || []) {
- resources.push({
- id: `host:${host.id}`,
- name: host.displayName || host.hostname,
- type: 'host',
- status: host.status,
- });
- }
-
+ const resources: MentionResource[] = buildMentionResources(state);
setMentionResources(resources);
- console.log('[AIChat] Loaded', resources.length, 'resources for @ mention autocomplete');
+ logger.debug('[AIChat] Loaded mention resources', { count: resources.length });
} catch (error) {
logger.error('[AIChat] Failed to fetch resources for autocomplete:', error);
console.error('[AIChat] Failed to fetch resources:', error);
diff --git a/frontend-modern/src/components/AI/Chat/mentionResources.ts b/frontend-modern/src/components/AI/Chat/mentionResources.ts
new file mode 100644
index 0000000000..cd6053c470
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/mentionResources.ts
@@ -0,0 +1,231 @@
+import type { State } from '@/types/api';
+
+export interface MentionResource {
+ id: string;
+ name: string;
+ type: 'vm' | 'container' | 'node' | 'storage' | 'docker' | 'host';
+ status?: string;
+ node?: string;
+}
+
+type MentionStateSubset = Pick<State, 'vms' | 'containers' | 'dockerHosts' | 'nodes' | 'hosts'>;
+
+function normalizeKeyPart(value: string | undefined | null): string {
+ return (value || '').trim().toLowerCase();
+}
+
+function mentionStatusRank(status?: string): number {
+ switch (normalizeKeyPart(status)) {
+ case 'online':
+ case 'running':
+ case 'healthy':
+ case 'up':
+ return 3
+ case 'degraded':
+ case 'warning':
+ case 'warn':
+ case 'paused':
+ return 2
+ case 'offline':
+ case 'stopped':
+ case 'error':
+ case 'failed':
+ return 1
+ default:
+ return 0
+ }
+}
+
+function preferMentionResource(existing: MentionResource, candidate: MentionResource): MentionResource {
+ const existingRank = mentionStatusRank(existing.status);
+ const candidateRank = mentionStatusRank(candidate.status);
+
+ if (candidateRank > existingRank) {
+ return {
+ ...candidate,
+ id: existing.id || candidate.id,
+ };
+ }
+ if (candidateRank < existingRank) {
+ return existing;
+ }
+
+ if (!existing.node && candidate.node) {
+ return {
+ ...existing,
+ node: candidate.node,
+ };
+ }
+ if (!existing.status && candidate.status) {
+ return {
+ ...existing,
+ status: candidate.status,
+ };
+ }
+
+ return existing;
+}
+
+function upsertMentionResource(
+ byKey: Map<string, MentionResource>,
+ aliasToKey: Map<string, string>,
+ resource: MentionResource,
+ aliases: string[] = [],
+): void {
+ const normalizedPrimary = normalizeKeyPart(resource.id);
+ let key = normalizedPrimary ? `id:${normalizedPrimary}` : '';
+
+ for (const rawAlias of aliases) {
+ const alias = normalizeKeyPart(rawAlias);
+ if (!alias) continue;
+ const existingKey = aliasToKey.get(alias);
+ if (existingKey) {
+ key = existingKey;
+ break;
+ }
+ if (!key) {
+ key = alias;
+ }
+ }
+
+ if (!key) {
+ key = `fallback:${normalizeKeyPart(resource.type)}:${normalizeKeyPart(resource.name)}`;
+ }
+
+ const existing = byKey.get(key);
+ if (existing) {
+ byKey.set(key, preferMentionResource(existing, resource));
+ } else {
+ byKey.set(key, resource);
+ }
+
+ const allAliases = [normalizedPrimary ? `id:${normalizedPrimary}` : '', ...aliases];
+ for (const rawAlias of allAliases) {
+ const alias = normalizeKeyPart(rawAlias);
+ if (!alias) continue;
+ aliasToKey.set(alias, key);
+ }
+}
+
+function nodeAlias(instance: string, clusterName: string | undefined, nodeName: string): string {
+ const normalizedName = normalizeKeyPart(nodeName);
+ if (!normalizedName) {
+ return '';
+ }
+ const normalizedCluster = normalizeKeyPart(clusterName);
+ if (normalizedCluster) {
+ return `node-cluster:${normalizedCluster}:${normalizedName}`;
+ }
+ const normalizedInstance = normalizeKeyPart(instance);
+ if (normalizedInstance) {
+ return `node-instance:${normalizedInstance}:${normalizedName}`;
+ }
+ return `node-name:${normalizedName}`;
+}
+
+export function buildMentionResources(state: MentionStateSubset): MentionResource[] {
+ const byKey = new Map<string, MentionResource>();
+ const aliasToKey = new Map<string, string>();
+
+ for (const vm of state.vms || []) {
+ upsertMentionResource(
+ byKey,
+ aliasToKey,
+ {
+ id: `vm:${vm.node}:${vm.vmid}`,
+ name: vm.name,
+ type: 'vm',
+ status: vm.status,
+ node: vm.node,
+ },
+ [`vm-id:${vm.node}:${vm.vmid}`],
+ );
+ }
+
+ for (const container of state.containers || []) {
+ upsertMentionResource(
+ byKey,
+ aliasToKey,
+ {
+ id: `lxc:${container.node}:${container.vmid}`,
+ name: container.name,
+ type: 'container',
+ status: container.status,
+ node: container.node,
+ },
+ [`lxc-id:${container.node}:${container.vmid}`],
+ );
+ }
+
+ for (const host of state.dockerHosts || []) {
+ const hostName = host.displayName || host.hostname || host.id;
+ upsertMentionResource(
+ byKey,
+ aliasToKey,
+ {
+ id: `host:${host.id}`,
+ name: hostName,
+ type: 'host',
+ status: host.status || 'online',
+ },
+ [
+ `docker-host-id:${host.id}`,
+ `host-name:${hostName}`,
+ `host-hostname:${host.hostname}`,
+ ],
+ );
+
+ for (const container of host.containers || []) {
+ upsertMentionResource(
+ byKey,
+ aliasToKey,
+ {
+ id: `docker:${host.id}:${container.id}`,
+ name: container.name,
+ type: 'docker',
+ status: container.state,
+ node: host.hostname || host.id,
+ },
+ [`docker-container-id:${host.id}:${container.id}`],
+ );
+ }
+ }
+
+ for (const node of state.nodes || []) {
+ upsertMentionResource(
+ byKey,
+ aliasToKey,
+ {
+ id: `node:${node.instance}:${node.name}`,
+ name: node.name,
+ type: 'node',
+ status: node.status,
+ },
+ [
+ `node-id:${node.instance}:${node.name}`,
+ nodeAlias(node.instance, node.clusterName, node.name),
+ ],
+ );
+ }
+
+ for (const host of state.hosts || []) {
+ const hostName = host.displayName || host.hostname || host.id;
+ upsertMentionResource(
+ byKey,
+ aliasToKey,
+ {
+ id: `host:${host.id}`,
+ name: hostName,
+ type: 'host',
+ status: host.status,
+ },
+ [
+ `agent-host-id:${host.id}`,
+ `host-name:${hostName}`,
+ `host-hostname:${host.hostname}`,
+ ],
+ );
+ }
+
+ return Array.from(byKey.values());
+}
diff --git a/internal/models/models.go b/internal/models/models.go
index 6cd03afa79..d359521670 100644
--- a/internal/models/models.go
+++ b/internal/models/models.go
@@ -1318,16 +1318,103 @@ func (s *State) UpdateNodes(nodes []Node) {
s.LastUpdate = time.Now()
}
+func normalizeNodeIdentityPart(value string) string {
+ return strings.ToLower(strings.TrimSpace(value))
+}
+
+func nodeLogicalKey(node Node) string {
+ name := normalizeNodeIdentityPart(node.Name)
+ if name == "" {
+ return ""
+ }
+
+ if cluster := normalizeNodeIdentityPart(node.ClusterName); cluster != "" {
+ return "cluster:" + cluster + ":" + name
+ }
+ if instance := normalizeNodeIdentityPart(node.Instance); instance != "" {
+ return "instance:" + instance + ":" + name
+ }
+ if host := normalizeNodeIdentityPart(node.Host); host != "" {
+ return "host:" + host + ":" + name
+ }
+
+ return "name:" + name
+}
+
+func nodeStatusRank(status string) int {
+ switch normalizeNodeIdentityPart(status) {
+ case "online":
+ return 3
+ case "degraded":
+ return 2
+ case "unknown":
+ return 1
+ default:
+ return 0
+ }
+}
+
+func nodeConnectionHealthRank(health string) int {
+ switch normalizeNodeIdentityPart(health) {
+ case "healthy":
+ return 3
+ case "degraded":
+ return 2
+ case "unknown":
+ return 1
+ default:
+ return 0
+ }
+}
+
+func preferNodeForMerge(existing Node, candidate Node) Node {
+ existingScore := nodeStatusRank(existing.Status)*100 + nodeConnectionHealthRank(existing.ConnectionHealth)*10
+ if existing.LinkedHostAgentID != "" {
+ existingScore += 2
+ }
+ if existing.IsClusterMember {
+ existingScore++
+ }
+
+ candidateScore := nodeStatusRank(candidate.Status)*100 + nodeConnectionHealthRank(candidate.ConnectionHealth)*10
+ if candidate.LinkedHostAgentID != "" {
+ candidateScore += 2
+ }
+ if candidate.IsClusterMember {
+ candidateScore++
+ }
+
+ if candidateScore > existingScore {
+ return candidate
+ }
+ if candidateScore < existingScore {
+ return existing
+ }
+
+ if candidate.LastSeen.After(existing.LastSeen) {
+ return candidate
+ }
+ if existing.LastSeen.After(candidate.LastSeen) {
+ return existing
+ }
+
+ return existing
+}
+
// UpdateNodesForInstance updates nodes for a specific instance, merging with existing nodes
func (s *State) UpdateNodesForInstance(instanceName string, nodes []Node) {
s.mu.Lock()
defer s.mu.Unlock()
// Preserve LinkedHostAgentID for nodes that are being updated
- existingNodeLinks := make(map[string]string) // nodeID -> linkedHostAgentID
+ existingNodeLinks := make(map[string]string) // nodeID -> linkedHostAgentID
+ existingNodeLinksByLogicalKey := make(map[string]string) // logical node key -> linkedHostAgentID
for _, node := range s.Nodes {
if node.LinkedHostAgentID != "" {
existingNodeLinks[node.ID] = node.LinkedHostAgentID
+ if key := nodeLogicalKey(node); key != "" {
+ existingNodeLinksByLogicalKey[key] = node.LinkedHostAgentID
+ }
}
}
@@ -1339,6 +1426,25 @@ func (s *State) UpdateNodesForInstance(instanceName string, nodes []Node) {
}
}
+ // Deduplicate incoming nodes by logical identity so a single node cannot appear
+ // multiple times in the same poll cycle with different IDs.
+ dedupedNodes := make(map[string]Node)
+ for _, node := range nodes {
+ key := nodeLogicalKey(node)
+ if key == "" {
+ key = "id:" + normalizeNodeIdentityPart(node.ID)
+ }
+ if key == "id:" {
+ key = "instance:" + normalizeNodeIdentityPart(instanceName) + ":" + normalizeNodeIdentityPart(node.Name)
+ }
+
+ if existing, ok := dedupedNodes[key]; ok {
+ dedupedNodes[key] = preferNodeForMerge(existing, node)
+ continue
+ }
+ dedupedNodes[key] = node
+ }
+
// Build hostname-to-hostAgentID map for linking new nodes to existing host agents
// Also build a set of valid host agent IDs to validate existing links
hostAgentByHostname := make(map[string]string) // lowercase hostname -> hostAgentID
@@ -1355,7 +1461,7 @@ func (s *State) UpdateNodesForInstance(instanceName string, nodes []Node) {
}
// Add or update nodes from this instance
- for _, node := range nodes {
+ for _, node := range dedupedNodes {
// Preserve existing link if we had one, but only if the host agent still exists
if existingLink, ok := existingNodeLinks[node.ID]; ok {
if validHostAgentIDs[existingLink] {
@@ -1363,6 +1469,14 @@ func (s *State) UpdateNodesForInstance(instanceName string, nodes []Node) {
}
// If host agent no longer exists, leave LinkedHostAgentID empty (stale reference cleared)
}
+ // Fallback: preserve link by logical identity when node IDs changed across polls.
+ if node.LinkedHostAgentID == "" {
+ if existingLink, ok := existingNodeLinksByLogicalKey[nodeLogicalKey(node)]; ok {
+ if validHostAgentIDs[existingLink] {
+ node.LinkedHostAgentID = existingLink
+ }
+ }
+ }
// If no existing link, try to match by hostname
if node.LinkedHostAgentID == "" {
nodeName := strings.ToLower(node.Name)
@@ -1374,7 +1488,20 @@ func (s *State) UpdateNodesForInstance(instanceName string, nodes []Node) {
}
}
}
- nodeMap[node.ID] = node
+
+ targetKey := strings.TrimSpace(node.ID)
+ if targetKey == "" {
+ targetKey = nodeLogicalKey(node)
+ }
+ if targetKey == "" {
+ targetKey = "instance:" + normalizeNodeIdentityPart(instanceName) + ":" + normalizeNodeIdentityPart(node.Name)
+ }
+
+ if existing, ok := nodeMap[targetKey]; ok {
+ nodeMap[targetKey] = preferNodeForMerge(existing, node)
+ } else {
+ nodeMap[targetKey] = node
+ }
}
// Convert map back to slice
diff --git a/internal/models/state_additional_test.go b/internal/models/state_additional_test.go
index abbd5b076b..997f846542 100644
--- a/internal/models/state_additional_test.go
+++ b/internal/models/state_additional_test.go
@@ -186,6 +186,115 @@ func TestStateLinkHostAgentToNode(t *testing.T) {
}
}
+func TestUpdateNodesForInstancePreservesLinkWhenNodeIDChanges(t *testing.T) {
+ state := &State{
+ Hosts: []Host{
+ {ID: "host-1", Hostname: "pve01"},
+ },
+ Nodes: []Node{
+ {
+ ID: "cluster-a-pve01-old",
+ Name: "pve01",
+ Instance: "cluster-entry-a",
+ ClusterName: "cluster-a",
+ LinkedHostAgentID: "host-1",
+ },
+ },
+ }
+
+ state.UpdateNodesForInstance("cluster-entry-a", []Node{
+ {
+ ID: "cluster-a-pve01-new",
+ Name: "pve01",
+ Instance: "cluster-entry-a",
+ ClusterName: "cluster-a",
+ Status: "online",
+ },
+ })
+
+ if len(state.Nodes) != 1 {
+ t.Fatalf("nodes = %#v, want exactly 1 node", state.Nodes)
+ }
+ if state.Nodes[0].ID != "cluster-a-pve01-new" {
+ t.Fatalf("node id = %q, want cluster-a-pve01-new", state.Nodes[0].ID)
+ }
+ if state.Nodes[0].LinkedHostAgentID != "host-1" {
+ t.Fatalf("linkedHostAgentID = %q, want host-1", state.Nodes[0].LinkedHostAgentID)
+ }
+}
+
+func TestUpdateNodesForInstanceDeduplicatesLogicalNode(t *testing.T) {
+ state := NewState()
+ older := time.Now().Add(-2 * time.Minute)
+ newer := time.Now()
+
+ state.UpdateNodesForInstance("instance-a", []Node{
+ {
+ ID: "node-old",
+ Name: "pve01",
+ Instance: "instance-a",
+ Status: "offline",
+ ConnectionHealth: "error",
+ LastSeen: older,
+ },
+ {
+ ID: "node-new",
+ Name: "pve01",
+ Instance: "instance-a",
+ Status: "online",
+ ConnectionHealth: "healthy",
+ LastSeen: newer,
+ },
+ })
+
+ if len(state.Nodes) != 1 {
+ t.Fatalf("expected one logical node after dedupe, got %d (%#v)", len(state.Nodes), state.Nodes)
+ }
+ if state.Nodes[0].ID != "node-new" {
+ t.Fatalf("node id = %q, want node-new", state.Nodes[0].ID)
+ }
+ if state.Nodes[0].Status != "online" {
+ t.Fatalf("status = %q, want online", state.Nodes[0].Status)
+ }
+}
+
+func TestUpdateNodesForInstancePrefersHealthyOnCrossInstanceCollision(t *testing.T) {
+ now := time.Now()
+ state := &State{
+ Nodes: []Node{
+ {
+ ID: "shared-node-id",
+ Name: "pve01",
+ Instance: "instance-b",
+ Status: "online",
+ ConnectionHealth: "healthy",
+ LastSeen: now,
+ },
+ },
+ }
+
+ state.UpdateNodesForInstance("instance-a", []Node{
+ {
+ ID: "shared-node-id",
+ Name: "pve01",
+ Instance: "instance-a",
+ Status: "offline",
+ ConnectionHealth: "error",
+ LastSeen: now.Add(-time.Minute),
+ },
+ })
+
+ if len(state.Nodes) != 1 {
+ t.Fatalf("nodes = %#v, want exactly one merged node", state.Nodes)
+ }
+ if state.Nodes[0].Instance != "instance-b" {
+ t.Fatalf("instance = %q, want instance-b", state.Nodes[0].Instance)
+ }
+ if state.Nodes[0].Status != "online" {
+ t.Fatalf("status = %q, want online", state.Nodes[0].Status)
+ }
+}
+
func TestStateUnlinkHostAgent(t *testing.T) {
state := &State{
Hosts: []Host{{ID: "h1", LinkedNodeID: "n1", LinkedVMID: "vm", LinkedContainerID: "ct"}},