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.

test(ai/chat): add tests for service utilities and knowledge extraction

rcourtman20f1a9ee7fcd
diff --git a/internal/ai/chat/knowledge_extractor_additional2_test.go b/internal/ai/chat/knowledge_extractor_additional2_test.go
new file mode 100644
index 0000000000..93ceeeaa28
--- /dev/null
+++ b/internal/ai/chat/knowledge_extractor_additional2_test.go
@@ -0,0 +1,65 @@
+package chat
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestExtractMetricsFacts_UnknownAction(t *testing.T) {
+ facts := ExtractFacts("pulse_metrics", map[string]interface{}{"action": "mystery"}, `{}`)
+ assert.Empty(t, facts)
+}
+
+func TestExtractMetricsFacts_TypeFallbackSummary(t *testing.T) {
+ input := map[string]interface{}{
+ "type": "performance",
+ "resource_id": "vm123",
+ }
+ result := `{"summary":{"other":{"avg_cpu":5,"max_cpu":10,"avg_memory":20,"max_memory":30,"trend":"up"}}}`
+
+ facts := ExtractFacts("pulse_metrics", input, result)
+ if assert.Len(t, facts, 1) {
+ assert.Equal(t, "metrics:vm123", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "avg_cpu=5.0%")
+ assert.Contains(t, facts[0].Value, "trend=up")
+ }
+}
+
+func TestExtractAlertsFacts_UnknownAction(t *testing.T) {
+ facts := ExtractFacts("pulse_alerts", map[string]interface{}{"type": "mystery"}, `{}`)
+ assert.Empty(t, facts)
+}
+
+func TestExtractAlertsListFacts_ResolvedFiltered(t *testing.T) {
+ input := map[string]interface{}{"action": "list"}
+ result := `{"alerts":[{"resource_name":"vm101","type":"cpu","severity":"critical","value":95.2,"threshold":80,"status":"resolved"},{"resource_name":"ct200","type":"memory","severity":"warning","value":82.0,"threshold":90,"status":"active"}]}`
+
+ facts := ExtractFacts("pulse_alerts", input, result)
+ if assert.Len(t, facts, 3) {
+ assert.Equal(t, "alerts:overview", facts[0].Key)
+ assert.Contains(t, facts[0].Value, "1 active alerts")
+ }
+}
+
+func TestExtractKubernetesFacts_UnknownAction(t *testing.T) {
+ facts := ExtractFacts("pulse_kubernetes", map[string]interface{}{"action": "mystery"}, `{}`)
+ assert.Empty(t, facts)
+}
+
+func TestExtractPMGFacts_UnknownAction(t *testing.T) {
+ facts := ExtractFacts("pulse_pmg", map[string]interface{}{"action": "mystery"}, `{}`)
+ assert.Empty(t, facts)
+}
+
+func TestStrFromMap_EdgeCases(t *testing.T) {
+ if got := strFromMap(nil, "key"); got != "" {
+ t.Fatalf("expected empty for nil map, got %q", got)
+ }
+ if got := strFromMap(map[string]interface{}{"key": 123}, "key"); got != "" {
+ t.Fatalf("expected empty for non-string value, got %q", got)
+ }
+ if got := strFromMap(map[string]interface{}{"other": "value"}, "key"); got != "" {
+ t.Fatalf("expected empty for missing key, got %q", got)
+ }
+}
diff --git a/internal/ai/chat/service_misc_test.go b/internal/ai/chat/service_misc_test.go
new file mode 100644
index 0000000000..b2f1c9aad8
--- /dev/null
+++ b/internal/ai/chat/service_misc_test.go
@@ -0,0 +1,72 @@
+package chat
+
+import (
+ "context"
+ "testing"
+ "time"
+)
+
+func TestAbortSession(t *testing.T) {
+ svc := &Service{}
+ if err := svc.AbortSession(context.Background(), "sess-1"); err == nil {
+ t.Fatalf("expected error when service not started")
+ }
+
+ loop := &AgenticLoop{aborted: make(map[string]bool)}
+ svc.agenticLoop = loop
+ if err := svc.AbortSession(context.Background(), "sess-2"); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !loop.aborted["sess-2"] {
+ t.Fatalf("expected session to be marked aborted")
+ }
+}
+
+func TestResolvedContext_GetResourceAliasAndMiss(t *testing.T) {
+ ctx := NewResolvedContext("session")
+ res := &ResolvedResource{
+ ResourceID: "node:alpha",
+ Name: "alpha",
+ Aliases: []string{"@alpha", "alpha-node"},
+ ResourceType: "node",
+ }
+ ctx.AddResource(res.Name, res)
+
+ if got, ok := ctx.GetResource("@alpha"); !ok || got == nil {
+ t.Fatalf("expected alias lookup to succeed")
+ }
+ if got, ok := ctx.GetResource("missing"); ok || got != nil {
+ t.Fatalf("expected missing resource to return false")
+ }
+}
+
+func TestResolvedContext_TouchInitializesMap(t *testing.T) {
+ ctx := &ResolvedContext{}
+ ctx.touch("node:1")
+ if ctx.lastAccessed == nil {
+ t.Fatalf("expected lastAccessed map to be initialized")
+ }
+ if _, ok := ctx.lastAccessed["node:1"]; !ok {
+ t.Fatalf("expected access time to be recorded")
+ }
+}
+
+func TestSessionFSM_CleanupExpiredRecoveries(t *testing.T) {
+ fsm := &SessionFSM{}
+ fsm.cleanupExpiredRecoveries()
+ if fsm.PendingRecoveries == nil {
+ t.Fatalf("expected pending recoveries to be initialized")
+ }
+
+ now := time.Now()
+ fsm.PendingRecoveries["old"] = &PendingRecovery{CreatedAt: now.Add(-2 * RecoveryTTL)}
+ fsm.PendingRecoveries["new"] = &PendingRecovery{CreatedAt: now.Add(-time.Minute)}
+
+ fsm.cleanupExpiredRecoveries()
+ if _, ok := fsm.PendingRecoveries["old"]; ok {
+ t.Fatalf("expected expired recovery to be removed")
+ }
+ if _, ok := fsm.PendingRecoveries["new"]; !ok {
+ t.Fatalf("expected recent recovery to remain")
+ }
+}
diff --git a/internal/ai/chat/service_recent_context_test.go b/internal/ai/chat/service_recent_context_test.go
new file mode 100644
index 0000000000..ae459c9580
--- /dev/null
+++ b/internal/ai/chat/service_recent_context_test.go
@@ -0,0 +1,133 @@
+package chat
+
+import (
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestShouldInjectRecentContext(t *testing.T) {
+ if !shouldInjectRecentContext("show me its status") {
+ t.Fatalf("expected pronoun prompt to trigger recent context")
+ }
+ if !shouldInjectRecentContext("restart the service") {
+ t.Fatalf("expected noun prompt to trigger recent context")
+ }
+ if shouldInjectRecentContext("what is the uptime") {
+ t.Fatalf("expected unrelated prompt to skip recent context")
+ }
+}
+
+func TestInjectRecentContextIfNeeded_InjectsSummaryAndInstruction(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+ session, err := store.Create()
+ if err != nil {
+ t.Fatalf("failed to create session: %v", err)
+ }
+
+ resolved := store.GetResolvedContext(session.ID)
+
+ secondary := &ResolvedResource{
+ ResourceID: "vm:node-2:201",
+ Name: "db",
+ ResourceType: "vm",
+ Scope: ResourceScope{HostName: "node-2"},
+ }
+ resolved.AddResourceWithExplicitAccess(secondary.Name, secondary)
+
+ time.Sleep(10 * time.Millisecond)
+
+ primary := &ResolvedResource{
+ ResourceID: "docker_container:minipc:abc",
+ Name: "api",
+ Kind: "docker_container",
+ Node: "minipc",
+ TargetHost: "host-1",
+ }
+ resolved.AddResourceWithExplicitAccess(primary.Name, primary)
+
+ messages := []Message{{Role: "user", Content: "show its logs"}}
+ service := &Service{}
+ service.injectRecentContextIfNeeded("show its logs", session.ID, messages, store)
+
+ content := messages[0].Content
+ if content == "show its logs" {
+ t.Fatalf("expected recent context to be injected")
+ }
+ if !strings.Contains(content, "Context: The most recently referenced resource is api (docker_container on minipc).") {
+ t.Fatalf("expected primary resource summary, got: %s", content)
+ }
+ if !strings.Contains(content, "Other recent resources:\n- db (vm on node-2)") {
+ t.Fatalf("expected secondary resource summary, got: %s", content)
+ }
+ if !strings.Contains(content, "Use target_host=\"host-1\".") {
+ t.Fatalf("expected target host hint, got: %s", content)
+ }
+ if !strings.Contains(content, "Instruction: Show logs for api (last 50 lines).") {
+ t.Fatalf("expected log instruction, got: %s", content)
+ }
+ if !strings.Contains(content, "Use pulse_read action=logs target_host=\"host-1\" lines=50.") {
+ t.Fatalf("expected log tool instruction, got: %s", content)
+ }
+ if !strings.Contains(content, "Explicit target: api") {
+ t.Fatalf("expected explicit target, got: %s", content)
+ }
+ if !strings.Contains(content, "User question (targeted): show its logs") {
+ t.Fatalf("expected targeted user question, got: %s", content)
+ }
+}
+
+func TestInjectRecentContextIfNeeded_NoRecentDoesNotModify(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+ session, err := store.Create()
+ if err != nil {
+ t.Fatalf("failed to create session: %v", err)
+ }
+
+ resolved := store.GetResolvedContext(session.ID)
+ resolved.AddResource("alpha", &ResolvedResource{ResourceID: "node:alpha", Name: "alpha"})
+
+ messages := []Message{{Role: "user", Content: "restart it"}}
+ service := &Service{}
+ service.injectRecentContextIfNeeded("restart it", session.ID, messages, store)
+
+ if messages[0].Content != "restart it" {
+ t.Fatalf("expected message to remain unchanged")
+ }
+}
+
+func TestInjectRecentContextIfNeeded_PrimaryNameFallback(t *testing.T) {
+ store, err := NewSessionStore(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create session store: %v", err)
+ }
+ session, err := store.Create()
+ if err != nil {
+ t.Fatalf("failed to create session: %v", err)
+ }
+
+ resolved := store.GetResolvedContext(session.ID)
+ resource := &ResolvedResource{ResourceID: "node:alpha"}
+ resolved.AddResourceWithExplicitAccess("alpha", resource)
+
+ messages := []Message{{Role: "user", Content: "show its logs"}}
+ service := &Service{}
+ service.injectRecentContextIfNeeded("show its logs", session.ID, messages, store)
+
+ content := messages[0].Content
+ if !strings.Contains(content, "Context: The most recently referenced resource is node:alpha.") {
+ t.Fatalf("expected resource ID label, got: %s", content)
+ }
+ if !strings.Contains(content, "Explicit target: node:alpha") {
+ t.Fatalf("expected fallback explicit target, got: %s", content)
+ }
+ if !strings.Contains(content, "Use pulse_read action=logs target_host=\"node:alpha\" lines=50.") {
+ t.Fatalf("expected log instruction to use primary name, got: %s", content)
+ }
+}
diff --git a/internal/ai/chat/service_tooling_test.go b/internal/ai/chat/service_tooling_test.go
new file mode 100644
index 0000000000..7a60dc5432
--- /dev/null
+++ b/internal/ai/chat/service_tooling_test.go
@@ -0,0 +1,173 @@
+package chat
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+type fakeStateProvider struct{}
+
+func (f fakeStateProvider) GetState() models.StateSnapshot {
+ return models.StateSnapshot{}
+}
+
+type fakeAgentServer struct{}
+
+func (f fakeAgentServer) GetConnectedAgents() []agentexec.ConnectedAgent {
+ return []agentexec.ConnectedAgent{{AgentID: "agent-1", Hostname: "node-1"}}
+}
+
+func (f fakeAgentServer) ExecuteCommand(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error) {
+ return &agentexec.CommandResultPayload{Stdout: "ok", ExitCode: 0}, nil
+}
+
+func toolNameSet(list []providers.Tool) map[string]bool {
+ set := make(map[string]bool, len(list))
+ for _, tool := range list {
+ set[tool.Name] = true
+ }
+ return set
+}
+
+func TestFilterToolsForPrompt_ReadOnlyAndSpecialty(t *testing.T) {
+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{
+ StateProvider: fakeStateProvider{},
+ AgentServer: fakeAgentServer{},
+ ControlLevel: tools.ControlLevelControlled,
+ })
+
+ svc := &Service{executor: exec}
+
+ readOnlyTools := svc.filterToolsForPrompt(context.Background(), "show node status")
+ readOnlySet := toolNameSet(readOnlyTools)
+ if readOnlySet["pulse_control"] || readOnlySet["pulse_file_edit"] || readOnlySet["pulse_docker"] {
+ t.Fatalf("expected write tools to be filtered for read-only prompt")
+ }
+ if !readOnlySet["pulse_storage"] || !readOnlySet["pulse_kubernetes"] || !readOnlySet["pulse_pmg"] {
+ t.Fatalf("expected specialty tools to remain when no specialty keyword detected")
+ }
+
+ k8sTools := svc.filterToolsForPrompt(context.Background(), "check kubernetes pods")
+ k8sSet := toolNameSet(k8sTools)
+ if !k8sSet["pulse_kubernetes"] {
+ t.Fatalf("expected kubernetes tool to be included")
+ }
+ if k8sSet["pulse_storage"] || k8sSet["pulse_pmg"] {
+ t.Fatalf("expected non-k8s specialty tools to be excluded")
+ }
+}
+
+func TestFilterToolsForPrompt_BroadInfraKeepsStorage(t *testing.T) {
+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{
+ StateProvider: fakeStateProvider{},
+ AgentServer: fakeAgentServer{},
+ ControlLevel: tools.ControlLevelControlled,
+ })
+
+ svc := &Service{executor: exec}
+ toolsList := svc.filterToolsForPrompt(context.Background(), "full status overview")
+ set := toolNameSet(toolsList)
+ if !set["pulse_storage"] {
+ t.Fatalf("expected storage tool to be kept for broad infrastructure prompt")
+ }
+ if set["pulse_control"] || set["pulse_file_edit"] || set["pulse_docker"] {
+ t.Fatalf("expected write tools to be filtered for read-only prompt")
+ }
+}
+
+func TestExecuteCommand_SuccessAndExitCode(t *testing.T) {
+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+ exec.RegisterTool(tools.RegisteredTool{
+ Definition: tools.Tool{Name: "pulse_run_command"},
+ Handler: func(ctx context.Context, exec *tools.PulseToolExecutor, args map[string]interface{}) (tools.CallToolResult, error) {
+ return tools.NewTextResult("Command failed (exit code 7): boom"), nil
+ },
+ })
+
+ svc := &Service{executor: exec}
+
+ output, code, err := svc.ExecuteCommand(context.Background(), "uptime", "")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if code != 7 {
+ t.Fatalf("expected exit code 7, got %d", code)
+ }
+ if !strings.Contains(output, "Command failed") {
+ t.Fatalf("expected command output, got: %s", output)
+ }
+}
+
+func TestExecuteCommand_ErrorAndApprovalPaths(t *testing.T) {
+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+ exec.RegisterTool(tools.RegisteredTool{
+ Definition: tools.Tool{Name: "pulse_run_command"},
+ Handler: func(ctx context.Context, exec *tools.PulseToolExecutor, args map[string]interface{}) (tools.CallToolResult, error) {
+ return tools.NewErrorResult(context.Canceled), nil
+ },
+ })
+
+ svc := &Service{executor: exec}
+
+ _, code, err := svc.ExecuteCommand(context.Background(), "uptime", "")
+ if err == nil || code != 1 {
+ t.Fatalf("expected error with exit code 1")
+ }
+
+ exec.RegisterTool(tools.RegisteredTool{
+ Definition: tools.Tool{Name: "pulse_run_command"},
+ Handler: func(ctx context.Context, exec *tools.PulseToolExecutor, args map[string]interface{}) (tools.CallToolResult, error) {
+ return tools.NewTextResult("APPROVAL_REQUIRED: requires approval"), nil
+ },
+ })
+
+ _, _, err = svc.ExecuteCommand(context.Background(), "uptime", "")
+ if err == nil {
+ t.Fatalf("expected approval error")
+ }
+}
+
+func TestExecuteMCPTool_ErrorsAndSuccess(t *testing.T) {
+ exec := tools.NewPulseToolExecutor(tools.ExecutorConfig{})
+ exec.RegisterTool(tools.RegisteredTool{
+ Definition: tools.Tool{Name: "test_tool"},
+ Handler: func(ctx context.Context, exec *tools.PulseToolExecutor, args map[string]interface{}) (tools.CallToolResult, error) {
+ return tools.NewErrorResult(context.DeadlineExceeded), nil
+ },
+ })
+
+ svc := &Service{executor: exec}
+
+ _, err := svc.ExecuteMCPTool(context.Background(), "test_tool", map[string]interface{}{})
+ if err == nil {
+ t.Fatalf("expected tool error")
+ }
+
+ exec.RegisterTool(tools.RegisteredTool{
+ Definition: tools.Tool{Name: "test_tool"},
+ Handler: func(ctx context.Context, exec *tools.PulseToolExecutor, args map[string]interface{}) (tools.CallToolResult, error) {
+ return tools.NewTextResult("POLICY_BLOCKED: nope"), nil
+ },
+ })
+ _, err = svc.ExecuteMCPTool(context.Background(), "test_tool", map[string]interface{}{})
+ if err == nil {
+ t.Fatalf("expected policy blocked error")
+ }
+
+ exec.RegisterTool(tools.RegisteredTool{
+ Definition: tools.Tool{Name: "test_tool"},
+ Handler: func(ctx context.Context, exec *tools.PulseToolExecutor, args map[string]interface{}) (tools.CallToolResult, error) {
+ return tools.NewTextResult("ok"), nil
+ },
+ })
+ output, err := svc.ExecuteMCPTool(context.Background(), "test_tool", map[string]interface{}{})
+ if err != nil || output != "ok" {
+ t.Fatalf("expected success, got output=%q err=%v", output, err)
+ }
+}