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.

feat(ai): add canonical truenas app control

rcourtmanb0ba88d54117
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index da0f489c42..ee707c80d6 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -428,6 +428,11 @@ and `frontend-modern/src/utils/proxmoxSettingsPresentation.ts`, so endpoint
reachability state, discovery-prefill defaults, and variant copy stay on the
same governed lifecycle surface instead of drifting into card-local strings or
prefill assembly.
+That same platform-connections boundary also defines the agent-optional rule
+for API-backed platforms. TrueNAS may surface Assistant control and runtime
+insight through the backend-owned platform connection and polling path, but
+adjacent lifecycle flows must not start treating a unified-agent install as
+the required bootstrap for provider-backed TrueNAS operations.
That same infrastructure workspace boundary now also owns the first-run
handoff copy for new operators. `InfrastructureWorkspace.tsx` must tell a new
Pulse user to start with `Install on a host` to add the first monitored
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 1126d1fb31..9f19a03264 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -151,6 +151,13 @@ The same ownership includes the Pulse query tool schema under
the AI runtime itself, so new tool arguments such as `max_proxmox_nodes`
cannot reintroduce parallel legacy aliases once the backend query contract is
renamed.
+That same AI tool ownership now also includes canonical resource-native
+control. `internal/ai/tools/executor.go`,
+`internal/ai/tools/tools_control.go`, and `internal/api/router.go` must keep
+API-backed control actions such as TrueNAS app start/stop/restart on the
+shared `pulse_control` tool with `type="resource"` and native audited
+execution, instead of adding provider-local control tools or bypassing the
+shared approval and policy model.
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 ce0996c576..70942d4989 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -580,6 +580,13 @@ must stay the canonical API-backed platform boundary for listing, creating,
updating, deleting, and testing TrueNAS integrations, and `PUT` updates must
preserve masked secrets (`********`) instead of clearing stored API keys or
passwords when operators edit non-secret fields from the settings surface.
+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
+helpers must not introduce a parallel public `/api/truenas/apps/...` control
+surface; provider-backed app control for Pulse Assistant stays behind the
+shared AI runtime tool contract unless this API contract changes in the same
+slice.
The monitored-system ledger contract now also carries a canonical grouping
explanation payload. `/api/license/monitored-system-ledger` must expose the
shared monitored-system explanation summary, sanitized grouping reasons, and
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 1a084e93d2..8c7887fe1f 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -245,6 +245,12 @@ canonical `app-container` metrics contract, and sync them into the existing
guest metrics-history/store path. Pulse must not add a TrueNAS-only charts
path or treat API-backed app workloads as second-class compared with native
Docker reports.
+That same monitoring boundary now also owns canonical TrueNAS app control
+refresh semantics. `internal/truenas/provider.go` and
+`internal/monitoring/truenas_poller.go` must execute native app start/stop
+actions through the owned TrueNAS runtime and refresh cached records and
+recovery ingest immediately afterward, so assistant-driven app control does
+not rely on stale provider state or ad hoc config-local action paths.
That same monitoring boundary now also owns API-backed TrueNAS system
telemetry for the top-level NAS host. `internal/truenas/client.go` must ingest
`reporting.realtime` through the official `/api/current` JSON-RPC websocket
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 78ee2c448f..b0da47fe70 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -80,6 +80,7 @@ querying, and the operator-facing storage health presentation layer.
19. Preserve shipped local security-doc guidance in shared `internal/api/` config/setup helpers so storage- and recovery-adjacent transport surfaces do not reintroduce GitHub `main` security links when the running build already serves its own local security documentation route.
20. Keep shared `internal/api/` Patrol transport and alert-trigger edits feature-isolated: Patrol-specific recency fields, callback fan-out, or alert-bridge wiring changes must not leak into recovery queries, storage links, or recovery-adjacent install/setup flows unless this contract changes in the same slice.
21. Keep provider-backed recovery onboarding on the adjacent platform-connections contract. When `internal/api/` grows or changes TrueNAS connection CRUD, masked-secret preservation, or similar provider setup flows, storage and recovery may consume the resulting recovery points but must not absorb that connection-management ownership into storage/recovery-local handlers or page flows.
+22. Keep backend-native platform actions on the adjacent AI/runtime and platform contracts. When `internal/api/` wires native TrueNAS app control for Assistant, storage and recovery may consume the refreshed recovery points afterward, but they must not grow a parallel recovery-local action transport or action-specific payload shape.
## Forbidden Paths
@@ -1517,3 +1518,9 @@ onboarding. Storage and recovery may consume resulting TrueNAS snapshots and
replication points, but connection CRUD, masked-secret preservation on update,
and platform polling setup must stay on the adjacent platform-connections
contract instead of being rebuilt as storage/recovery-local connection flows.
+That same shared boundary also owns the line between recovery data and
+assistant control. Backend-native TrueNAS app actions may refresh the poller
+and recovery ingest after a control event, but storage and recovery surfaces
+must continue to consume the resulting canonical recovery points instead of
+growing a second recovery-local control transport or action-specific payload
+contract.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index e40670672e..ffcc45379c 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -1072,6 +1072,14 @@ The same governed lookup boundary now also owns policy-aware resolved context:
downstream consumers that need routing plus canonical policy metadata must use
the unified-resource resolution context instead of rescanning typed views or
re-deriving AI redaction rules locally.
+That same resolved-context boundary now also owns cross-platform app-container
+routing. `internal/unifiedresources/resolve.go`,
+`internal/unifiedresources/resolve_context.go`, and
+`internal/ai/tools/tools_query.go` must register TrueNAS-backed canonical
+`app-container` resources into the same resolved-context model as Docker app
+containers while preserving adapter-specific routing. Reusing shared
+`DockerData` for workload metadata must not misclassify a TrueNAS app as a
+Docker-routed control target.
Typed view accessors for linked topology IDs must also return canonical
trimmed values. Callers must not observe `" node-99 "` or `" agent-123 "`
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 0b3bb12761..a0061c8800 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -37,23 +37,24 @@ type AgentServer interface {
// MCP provider type aliases for external use
type (
- MCPAlertProvider = tools.AlertProvider
- MCPFindingsProvider = tools.FindingsProvider
- MCPBaselineProvider = tools.BaselineProvider
- MCPPatternProvider = tools.PatternProvider
- MCPMetricsHistoryProvider = tools.MetricsHistoryProvider
- MCPBackupProvider = tools.BackupProvider
- MCPGuestConfigProvider = tools.GuestConfigProvider
- MCPDiskHealthProvider = tools.DiskHealthProvider
- MCPUpdatesProvider = tools.UpdatesProvider
- AgentProfileManager = tools.AgentProfileManager
- FindingsManager = tools.FindingsManager
- MetadataUpdater = tools.MetadataUpdater
- IncidentRecorderProvider = tools.IncidentRecorderProvider
- EventCorrelatorProvider = tools.EventCorrelatorProvider
- KnowledgeStoreProvider = tools.KnowledgeStoreProvider
- MCPDiscoveryProvider = tools.DiscoveryProvider
- MCPUnifiedResourceProvider = tools.UnifiedResourceProvider
+ MCPAlertProvider = tools.AlertProvider
+ MCPFindingsProvider = tools.FindingsProvider
+ MCPBaselineProvider = tools.BaselineProvider
+ MCPPatternProvider = tools.PatternProvider
+ MCPMetricsHistoryProvider = tools.MetricsHistoryProvider
+ MCPBackupProvider = tools.BackupProvider
+ MCPGuestConfigProvider = tools.GuestConfigProvider
+ MCPDiskHealthProvider = tools.DiskHealthProvider
+ MCPUpdatesProvider = tools.UpdatesProvider
+ MCPAppContainerActionProvider = tools.AppContainerActionProvider
+ AgentProfileManager = tools.AgentProfileManager
+ FindingsManager = tools.FindingsManager
+ MetadataUpdater = tools.MetadataUpdater
+ IncidentRecorderProvider = tools.IncidentRecorderProvider
+ EventCorrelatorProvider = tools.EventCorrelatorProvider
+ KnowledgeStoreProvider = tools.KnowledgeStoreProvider
+ MCPDiscoveryProvider = tools.DiscoveryProvider
+ MCPUnifiedResourceProvider = tools.UnifiedResourceProvider
)
// Config holds service configuration
@@ -1233,6 +1234,14 @@ func (s *Service) SetUnifiedResourceProvider(provider tools.UnifiedResourceProvi
}
}
+func (s *Service) SetAppContainerActionProvider(provider MCPAppContainerActionProvider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.executor != nil {
+ s.executor.SetAppContainerActionProvider(provider)
+ }
+}
+
func (s *Service) SetDiscoveryProvider(provider MCPDiscoveryProvider) {
s.mu.Lock()
defer s.mu.Unlock()
diff --git a/internal/ai/tools/action_audit.go b/internal/ai/tools/action_audit.go
index 8e08a2131b..430ace8c37 100644
--- a/internal/ai/tools/action_audit.go
+++ b/internal/ai/tools/action_audit.go
@@ -4,6 +4,7 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
+ "encoding/json"
"fmt"
"strings"
"time"
@@ -136,6 +137,94 @@ func (e *PulseToolExecutor) executeCommandWithAudit(
return result, err
}
+func (e *PulseToolExecutor) executeNativeActionWithAudit(
+ ctx context.Context,
+ capabilityName string,
+ resourceID string,
+ approvalID string,
+ requiresApproval bool,
+ params map[string]any,
+ requestedBy string,
+ reason string,
+ execute func(context.Context) (*unifiedresources.ExecutionResult, error),
+) (*unifiedresources.ExecutionResult, error) {
+ actionID := uuid.NewString()
+ requestCorrelationID := strings.TrimSpace(approvalID)
+ if requestCorrelationID == "" {
+ requestCorrelationID = actionID
+ }
+
+ now := time.Now().UTC()
+ plan := unifiedresources.ActionPlan{
+ ActionID: actionID,
+ RequestID: requestCorrelationID,
+ Allowed: true,
+ RequiresApproval: requiresApproval,
+ ApprovalPolicy: func() unifiedresources.ActionApprovalLevel {
+ if requiresApproval {
+ return unifiedresources.ApprovalAdmin
+ }
+ return unifiedresources.ApprovalNone
+ }(),
+ PlannedAt: now,
+ ExpiresAt: now.Add(5 * time.Minute),
+ ResourceVersion: "",
+ PolicyVersion: "",
+ PlanHash: actionPlanHashForParams(actionID, requestCorrelationID, capabilityName, resourceID, params, reason),
+ Message: reason,
+ }
+
+ record := unifiedresources.ActionAuditRecord{
+ ID: actionID,
+ CreatedAt: now,
+ UpdatedAt: now,
+ State: unifiedresources.ActionStateExecuting,
+ Request: unifiedresources.ActionRequest{
+ RequestID: requestCorrelationID,
+ ResourceID: strings.TrimSpace(resourceID),
+ CapabilityName: capabilityName,
+ Params: cloneActionParams(params),
+ Reason: reason,
+ RequestedBy: requestedBy,
+ },
+ Plan: plan,
+ }
+ record.Approvals = approvalRecordsForID(approvalID)
+
+ e.recordActionLifecycle(actionID, unifiedresources.ActionStatePlanned, requestedBy, reason)
+ e.recordActionLifecycle(actionID, unifiedresources.ActionStateExecuting, requestedBy, "dispatching native resource action")
+ e.recordActionAudit(record)
+
+ result, err := execute(ctx)
+ finalState := unifiedresources.ActionStateCompleted
+ finalMessage := "native resource action completed"
+ executionResult := &unifiedresources.ExecutionResult{Success: true}
+
+ if err != nil {
+ finalState = unifiedresources.ActionStateFailed
+ finalMessage = err.Error()
+ executionResult.Success = false
+ executionResult.ErrorMessage = err.Error()
+ } else if result != nil {
+ executionResult = result
+ if !result.Success {
+ finalState = unifiedresources.ActionStateFailed
+ finalMessage = strings.TrimSpace(result.ErrorMessage)
+ if finalMessage == "" {
+ finalMessage = "native resource action failed"
+ }
+ }
+ }
+
+ record.State = finalState
+ record.UpdatedAt = time.Now().UTC()
+ record.Result = executionResult
+ e.recordActionAudit(record)
+ e.recordActionLifecycle(actionID, finalState, requestedBy, finalMessage)
+
+ return executionResult, err
+}
+
func (e *PulseToolExecutor) recordActionAudit(record unifiedresources.ActionAuditRecord) {
if e == nil || e.actionAuditStore == nil {
return
@@ -183,6 +272,57 @@ func actionPlanHash(actionID, requestID, capabilityName, resourceID string, payl
return hex.EncodeToString(sum[:])
}
+func actionPlanHashForParams(actionID, requestID, capabilityName, resourceID string, params map[string]any, reason string) string {
+ encoded, _ := json.Marshal(cloneActionParams(params))
+ sum := sha256.Sum256([]byte(strings.Join([]string{
+ actionID,
+ requestID,
+ capabilityName,
+ strings.TrimSpace(resourceID),
+ string(encoded),
+ reason,
+ }, "|")))
+ return hex.EncodeToString(sum[:])
+}
+
+func cloneActionParams(params map[string]any) map[string]any {
+ if len(params) == 0 {
+ return nil
+ }
+ cloned := make(map[string]any, len(params))
+ for key, value := range params {
+ cloned[key] = value
+ }
+ return cloned
+}
+
+func approvalRecordsForID(approvalID string) []unifiedresources.ActionApprovalRecord {
+ approvalID = strings.TrimSpace(approvalID)
+ if approvalID == "" {
+ return nil
+ }
+ store := approval.GetStore()
+ if store == nil {
+ return nil
+ }
+ req, ok := store.GetApproval(approvalID)
+ if !ok || req == nil {
+ return nil
+ }
+
+ record := unifiedresources.ActionApprovalRecord{
+ Actor: strings.TrimSpace(req.DecidedBy),
+ Method: unifiedresources.MethodAPI,
+ Timestamp: approvalTimestamp(req),
+ Outcome: unifiedresources.OutcomeApproved,
+ Reason: strings.TrimSpace(req.Context),
+ }
+ if req.Status == approval.StatusDenied {
+ record.Outcome = unifiedresources.OutcomeRejected
+ }
+ return []unifiedresources.ActionApprovalRecord{record}
+}
+
func approvalTimestamp(req *approval.ApprovalRequest) time.Time {
if req == nil || req.DecidedAt == nil {
return time.Now().UTC()
diff --git a/internal/ai/tools/control_helpers_test.go b/internal/ai/tools/control_helpers_test.go
index 28346a4743..d409d39c23 100644
--- a/internal/ai/tools/control_helpers_test.go
+++ b/internal/ai/tools/control_helpers_test.go
@@ -166,6 +166,17 @@ func TestFormattingHelpers(t *testing.T) {
assert.Equal(t, "docker restart web", payload["command"])
assert.Equal(t, "id-3", payload["approval_id"])
})
+
+ t.Run("formatAppContainerApprovalNeeded", func(t *testing.T) {
+ payload := decodePayload(t, formatAppContainerApprovalNeeded("Nextcloud", "truenas-main", "restart", "truenas app restart Nextcloud on truenas-main", "id-4"), "APPROVAL_REQUIRED: ")
+ assert.Equal(t, "approval_required", payload["type"])
+ assert.Equal(t, "Nextcloud", payload["resource_name"])
+ assert.Equal(t, "truenas-main", payload["resource_host"])
+ assert.Equal(t, "app-container", payload["resource_type"])
+ assert.Equal(t, "restart", payload["action"])
+ assert.Equal(t, "truenas app restart Nextcloud on truenas-main", payload["command"])
+ assert.Equal(t, "id-4", payload["approval_id"])
+ })
}
func decodePayload(t *testing.T, value, prefix string) map[string]interface{} {
diff --git a/internal/ai/tools/control_resource_test.go b/internal/ai/tools/control_resource_test.go
new file mode 100644
index 0000000000..b687d4e5eb
--- /dev/null
+++ b/internal/ai/tools/control_resource_test.go
@@ -0,0 +1,142 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+type stubAppContainerActionProvider struct {
+ calls []AppContainerActionRequest
+ result *AppContainerActionResult
+ err error
+}
+
+func (s *stubAppContainerActionProvider) ExecuteAction(_ context.Context, req AppContainerActionRequest) (*AppContainerActionResult, error) {
+ s.calls = append(s.calls, req)
+ if s.err != nil {
+ return nil, s.err
+ }
+ if s.result == nil {
+ return &AppContainerActionResult{
+ ResourceID: req.ResourceID,
+ ProviderUID: req.ProviderUID,
+ Name: req.Name,
+ Host: req.Host,
+ Platform: req.Platform,
+ Action: req.Action,
+ Status: "running",
+ Output: "ok",
+ }, nil
+ }
+ result := *s.result
+ return &result, nil
+}
+
+func TestPulseToolExecutor_ListTools_IncludesPulseControlForNativeAppProvider(t *testing.T) {
+ provider := newTrueNASUnifiedQueryProvider(t)
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ UnifiedResourceProvider: provider,
+ ReadState: provider.ResourceRegistry,
+ AppContainerActionProvider: &stubAppContainerActionProvider{},
+ ControlLevel: ControlLevelControlled,
+ })
+
+ tools := executor.ListTools()
+ found := false
+ for _, tool := range tools {
+ if tool.Name == "pulse_control" {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatalf("expected pulse_control to be available with native app action provider, got %+v", tools)
+ }
+}
+
+func TestExecuteControlResource_TrueNASAppUsesNativeActionProvider(t *testing.T) {
+ provider := newTrueNASUnifiedQueryProvider(t)
+ resolved := &mockResolvedContext{
+ resources: make(map[string]ResolvedResourceInfo),
+ aliases: make(map[string]ResolvedResourceInfo),
+ }
+ actionProvider := &stubAppContainerActionProvider{
+ result: &AppContainerActionResult{
+ ResourceID: "app-container:truenas-main:nextcloud",
+ ProviderUID: "nextcloud",
+ Name: "Nextcloud",
+ Host: "truenas-main",
+ Platform: "truenas",
+ Action: "restart",
+ Status: "running",
+ Output: "restart app Nextcloud on truenas-main; current state=running",
+ },
+ }
+ store := unifiedresources.NewMemoryStore()
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ UnifiedResourceProvider: provider,
+ ReadState: provider.ResourceRegistry,
+ AppContainerActionProvider: actionProvider,
+ ActionAuditStore: store,
+ })
+ executor.SetResolvedContext(resolved)
+
+ if _, err := executor.executeGetResource(context.Background(), map[string]interface{}{
+ "resource_type": "app-container",
+ "resource_id": "nextcloud",
+ }); err != nil {
+ t.Fatalf("seed resolved context: unexpected error: %v", err)
+ }
+
+ result, err := executor.executeControl(context.Background(), map[string]interface{}{
+ "type": "resource",
+ "resource_id": "Nextcloud",
+ "action": "restart",
+ })
+ if err != nil {
+ t.Fatalf("executeControl(type=resource): unexpected error: %v", err)
+ }
+ if result.IsError {
+ t.Fatalf("expected success result, got %+v", result)
+ }
+
+ var payload map[string]any
+ if err := json.Unmarshal([]byte(result.Content[0].Text), &payload); err != nil {
+ t.Fatalf("decode result payload: %v", err)
+ }
+ if payload["platform"] != "truenas" {
+ t.Fatalf("expected truenas platform, got %+v", payload)
+ }
+ if payload["action"] != "restart" || payload["status"] != "running" {
+ t.Fatalf("unexpected action payload: %+v", payload)
+ }
+
+ if len(actionProvider.calls) != 1 {
+ t.Fatalf("expected one native app action call, got %+v", actionProvider.calls)
+ }
+ call := actionProvider.calls[0]
+ if call.OrgID != "default" || call.ProviderUID != "nextcloud" || call.Host != "truenas-main" || call.Action != "restart" {
+ t.Fatalf("unexpected native app action request: %+v", call)
+ }
+
+ audits, err := store.GetActionAudits("", time.Time{}, 10)
+ if err != nil {
+ t.Fatalf("GetActionAudits() error = %v", err)
+ }
+ if len(audits) != 1 {
+ t.Fatalf("expected one action audit, got %+v", audits)
+ }
+ if audits[0].Request.CapabilityName != "pulse_control" {
+ t.Fatalf("unexpected capability name: %+v", audits[0].Request)
+ }
+ if got := audits[0].Request.Params["action"]; got != "restart" {
+ t.Fatalf("expected audited action restart, got %+v", audits[0].Request.Params)
+ }
+ if got := audits[0].Request.Params["platform"]; got != "truenas" {
+ t.Fatalf("expected audited platform truenas, got %+v", audits[0].Request.Params)
+ }
+}
diff --git a/internal/ai/tools/executor.go b/internal/ai/tools/executor.go
index 0bef4030bc..d7217b5a8d 100644
--- a/internal/ai/tools/executor.go
+++ b/internal/ai/tools/executor.go
@@ -165,6 +165,37 @@ type UpdatesProvider interface {
IsUpdateActionsEnabled() bool
}
+// AppContainerActionRequest describes a canonical control action against an
+// API-backed app-container resource.
+type AppContainerActionRequest struct {
+ OrgID string
+ ResourceID string
+ ProviderUID string
+ Name string
+ Host string
+ Platform string
+ Action string
+}
+
+// AppContainerActionResult captures the post-action view of an app-container
+// after a native provider operation completes.
+type AppContainerActionResult struct {
+ ResourceID string
+ ProviderUID string
+ Name string
+ Host string
+ Platform string
+ Action string
+ Status string
+ Output string
+}
+
+// AppContainerActionProvider executes canonical actions for API-backed
+// app-container resources such as TrueNAS-managed applications.
+type AppContainerActionProvider interface {
+ ExecuteAction(ctx context.Context, req AppContainerActionRequest) (*AppContainerActionResult, error)
+}
+
// DiscoveryProvider provides AI-powered infrastructure discovery
type DiscoveryProvider interface {
GetDiscovery(id string) (*ResourceDiscoveryInfo, error)
@@ -368,8 +399,9 @@ type ExecutorConfig struct {
DiscoveryProvider DiscoveryProvider
// Optional providers - unified resources
- UnifiedResourceProvider UnifiedResourceProvider
- ActionAuditStore unifiedresources.ResourceStore
+ UnifiedResourceProvider UnifiedResourceProvider
+ AppContainerActionProvider AppContainerActionProvider
+ ActionAuditStore unifiedresources.ResourceStore
// Optional typed read access to current infrastructure state.
// When provided, tool handlers should prefer this over models.StateSnapshot iteration.
ReadState unifiedresources.ReadState
@@ -419,8 +451,9 @@ type PulseToolExecutor struct {
discoveryProvider DiscoveryProvider
// Unified resources provider
- unifiedResourceProvider UnifiedResourceProvider
- actionAuditStore unifiedresources.ResourceStore
+ unifiedResourceProvider UnifiedResourceProvider
+ appContainerActionProvider AppContainerActionProvider
+ actionAuditStore unifiedresources.ResourceStore
// Typed state reader. Nil means "legacy-only": tools must fall back to StateSnapshot access.
readState unifiedresources.ReadState
@@ -483,23 +516,24 @@ func NewPulseToolExecutor(cfg ExecutorConfig) *PulseToolExecutor {
connectionHealth: cfg.ConnectionHealth,
recoveryPointsProvider: cfg.RecoveryPointsProvider,
- guestConfigProvider: cfg.GuestConfigProvider,
- diskHealthProvider: cfg.DiskHealthProvider,
- updatesProvider: cfg.UpdatesProvider,
- metadataUpdater: cfg.MetadataUpdater,
- findingsManager: cfg.FindingsManager,
- agentProfileManager: cfg.AgentProfileManager,
- incidentRecorderProvider: cfg.IncidentRecorderProvider,
- eventCorrelatorProvider: cfg.EventCorrelatorProvider,
- knowledgeStoreProvider: cfg.KnowledgeStoreProvider,
- discoveryProvider: cfg.DiscoveryProvider,
- unifiedResourceProvider: cfg.UnifiedResourceProvider,
- actionAuditStore: cfg.ActionAuditStore,
- readState: cfg.ReadState,
- controlLevel: cfg.ControlLevel,
- protectedGuests: cfg.ProtectedGuests,
- orgID: normalizeExecutorOrgID(cfg.OrgID),
- registry: NewToolRegistry(),
+ guestConfigProvider: cfg.GuestConfigProvider,
+ diskHealthProvider: cfg.DiskHealthProvider,
+ updatesProvider: cfg.UpdatesProvider,
+ metadataUpdater: cfg.MetadataUpdater,
+ findingsManager: cfg.FindingsManager,
+ agentProfileManager: cfg.AgentProfileManager,
+ incidentRecorderProvider: cfg.IncidentRecorderProvider,
+ eventCorrelatorProvider: cfg.EventCorrelatorProvider,
+ knowledgeStoreProvider: cfg.KnowledgeStoreProvider,
+ discoveryProvider: cfg.DiscoveryProvider,
+ unifiedResourceProvider: cfg.UnifiedResourceProvider,
+ appContainerActionProvider: cfg.AppContainerActionProvider,
+ actionAuditStore: cfg.ActionAuditStore,
+ readState: cfg.ReadState,
+ controlLevel: cfg.ControlLevel,
+ protectedGuests: cfg.ProtectedGuests,
+ orgID: normalizeExecutorOrgID(cfg.OrgID),
+ registry: NewToolRegistry(),
}
// Auto-wire backup, replication, and connection health adapters from
@@ -696,6 +730,12 @@ func (e *PulseToolExecutor) SetUnifiedResourceProvider(provider UnifiedResourceP
e.unifiedResourceProvider = provider
}
+// SetAppContainerActionProvider sets the provider used for canonical native
+// app-container control actions.
+func (e *PulseToolExecutor) SetAppContainerActionProvider(provider AppContainerActionProvider) {
+ e.appContainerActionProvider = provider
+}
+
// SetActionAuditStore sets the durable store used to persist action audit and lifecycle events.
func (e *PulseToolExecutor) SetActionAuditStore(store unifiedresources.ResourceStore) {
e.actionAuditStore = store
@@ -771,7 +811,7 @@ func (e *PulseToolExecutor) isToolAvailable(name string) bool {
case "pulse_read":
return e.agentServer != nil
case "pulse_control":
- return e.agentServer != nil && e.hasReadState()
+ return (e.agentServer != nil || e.appContainerActionProvider != nil) && e.hasReadState()
case "pulse_file_edit":
return e.agentServer != nil
case "pulse_discovery":
diff --git a/internal/ai/tools/strict_resolution_test.go b/internal/ai/tools/strict_resolution_test.go
index 1cd36d72b2..7a45b81218 100644
--- a/internal/ai/tools/strict_resolution_test.go
+++ b/internal/ai/tools/strict_resolution_test.go
@@ -308,7 +308,45 @@ type mockResolvedContext struct {
}
func (m *mockResolvedContext) AddResolvedResource(reg ResourceRegistration) {
- // Not implemented for mock
+ if m.resources == nil {
+ m.resources = make(map[string]ResolvedResourceInfo)
+ }
+ if m.aliases == nil {
+ m.aliases = make(map[string]ResolvedResourceInfo)
+ }
+
+ resourceID := strings.TrimSpace(reg.Kind)
+ if providerUID := strings.TrimSpace(reg.ProviderUID); providerUID != "" {
+ resourceID = resourceID + ":" + providerUID
+ }
+ if resourceID == "" {
+ resourceID = strings.TrimSpace(reg.Name)
+ }
+
+ resource := &mockResource{
+ resourceID: resourceID,
+ resourceType: reg.Kind,
+ targetHost: strings.TrimSpace(reg.HostName),
+ agentID: strings.TrimSpace(reg.HostUID),
+ providerUID: strings.TrimSpace(reg.ProviderUID),
+ kind: reg.Kind,
+ aliases: append([]string(nil), reg.Aliases...),
+ allowedActions: nil,
+ }
+ if len(reg.Executors) > 0 {
+ resource.adapter = strings.TrimSpace(reg.Executors[0].Adapter)
+ resource.allowedActions = append([]string(nil), reg.Executors[0].Actions...)
+ resource.node = strings.TrimSpace(reg.Executors[0].ExecutorID)
+ }
+
+ m.resources[resourceID] = resource
+ for _, alias := range append([]string{reg.Name, resourceID}, reg.Aliases...) {
+ alias = strings.TrimSpace(alias)
+ if alias == "" {
+ continue
+ }
+ m.aliases[alias] = resource
+ }
}
func (m *mockResolvedContext) GetResolvedResourceByID(resourceID string) (ResolvedResourceInfo, bool) {
diff --git a/internal/ai/tools/tools_control.go b/internal/ai/tools/tools_control.go
index 50f25b8d68..60294e8f7a 100644
--- a/internal/ai/tools/tools_control.go
+++ b/internal/ai/tools/tools_control.go
@@ -3,6 +3,7 @@ package tools
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"strconv"
"strings"
@@ -20,22 +21,26 @@ func (e *PulseToolExecutor) registerControlTools() {
e.registry.Register(RegisteredTool{
Definition: Tool{
Name: "pulse_control",
- Description: `WRITE operations: control VMs/containers (start/stop/restart/delete) or execute state-modifying commands. For read-only operations use pulse_read. For Docker use pulse_docker.`,
+ Description: `WRITE operations: control canonical resources (VMs, system containers, supported app-containers) or execute state-modifying commands. For read-only operations use pulse_read. For Docker-only workflows use pulse_docker.`,
InputSchema: InputSchema{
Type: "object",
Properties: map[string]PropertySchema{
"type": {
Type: "string",
- Description: "Control type: guest or command",
- Enum: []string{"guest", "command"},
+ Description: "Control type: guest, resource, or command",
+ Enum: []string{"guest", "resource", "command"},
},
"guest_id": {
Type: "string",
Description: "For guest: VMID or name",
},
+ "resource_id": {
+ Type: "string",
+ Description: "For resource: discovered resource name or canonical resource ID from pulse_query",
+ },
"action": {
Type: "string",
- Description: "For guest: start, stop, shutdown, restart, delete",
+ Description: "For guest/resource: start, stop, shutdown, restart, delete (availability depends on resource type)",
Enum: []string{"start", "stop", "shutdown", "restart", "delete"},
},
"command": {
@@ -71,11 +76,239 @@ func (e *PulseToolExecutor) executeControl(ctx context.Context, args map[string]
switch controlType {
case "guest":
return e.executeControlGuest(ctx, args)
+ case "resource":
+ return e.executeControlResource(ctx, args)
case "command":
return e.executeRunCommand(ctx, args)
default:
- return NewErrorResult(fmt.Errorf("unknown type: %s. Use: guest, command", controlType)), nil
+ return NewErrorResult(fmt.Errorf("unknown type: %s. Use: guest, resource, command", controlType)), nil
+ }
+}
+
+func (e *PulseToolExecutor) executeControlResource(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {
+ resourceRef, _ := args["resource_id"].(string)
+ resourceRef = strings.TrimSpace(resourceRef)
+ action, _ := args["action"].(string)
+ action = strings.TrimSpace(action)
+ approvalID, _ := args["_approval_id"].(string)
+ approvalID = strings.TrimSpace(approvalID)
+
+ if resourceRef == "" {
+ return NewErrorResult(fmt.Errorf("resource_id is required")), nil
+ }
+ if action == "" {
+ return NewErrorResult(fmt.Errorf("action is required")), nil
+ }
+
+ validation := e.validateResolvedResource(resourceRef, action, true)
+ if validation.IsBlocked() {
+ return NewToolResponseResult(validation.StrictError.ToToolResponse()), nil
+ }
+ if validation.Resource == nil {
+ if validation.ErrorMsg != "" {
+ return NewErrorResult(errors.New(validation.ErrorMsg)), nil
+ }
+ return NewErrorResult(fmt.Errorf("resource '%s' has not been discovered in this session. Use pulse_query to find it first", resourceRef)), nil
+ }
+ if validation.ErrorMsg != "" {
+ log.Warn().
+ Str("resource", resourceRef).
+ Str("action", action).
+ Str("validation_error", validation.ErrorMsg).
+ Msg("[ControlResource] Continuing with discovered resource despite validation warning")
+ }
+
+ resolved := validation.Resource
+ switch resolved.GetKind() {
+ case "vm", "system-container":
+ guestArgs := map[string]interface{}{
+ "guest_id": resolvedResourceControlIdentity(resolved, resourceRef),
+ "action": action,
+ }
+ if force, ok := args["force"].(bool); ok {
+ guestArgs["force"] = force
+ }
+ if approvalID != "" {
+ guestArgs["_approval_id"] = approvalID
+ }
+ return e.executeControlGuest(ctx, guestArgs)
+
+ case "app-container":
+ switch strings.ToLower(strings.TrimSpace(resolved.GetAdapter())) {
+ case "docker":
+ dockerArgs := map[string]interface{}{
+ "container": resolvedResourceControlIdentity(resolved, resourceRef),
+ "host": strings.TrimSpace(resolved.GetTargetHost()),
+ "operation": action,
+ }
+ if approvalID != "" {
+ dockerArgs["_approval_id"] = approvalID
+ }
+ return e.executeDockerControl(ctx, dockerArgs)
+ case "truenas":
+ return e.executeNativeAppContainerControl(ctx, resolved, action, approvalID)
+ default:
+ return NewErrorResult(fmt.Errorf("resource '%s' uses unsupported control adapter %q", resourceRef, resolved.GetAdapter())), nil
+ }
}
+
+ return NewErrorResult(fmt.Errorf("resource '%s' of kind %q is not controllable through pulse_control type=resource", resourceRef, resolved.GetKind())), nil
+}
+
+func (e *PulseToolExecutor) executeNativeAppContainerControl(ctx context.Context, resource ResolvedResourceInfo, action string, approvalID string) (CallToolResult, error) {
+ if resource == nil {
+ return NewErrorResult(fmt.Errorf("resolved resource is nil")), nil
+ }
+ if e.appContainerActionProvider == nil {
+ return NewErrorResult(fmt.Errorf("native app-container control provider is not available")), nil
+ }
+
+ validActions := map[string]bool{"start": true, "stop": true, "restart": true}
+ if !validActions[action] {
+ return NewErrorResult(fmt.Errorf("invalid app-container action: %s. Use start, stop, or restart", action)), nil
+ }
+ if e.controlLevel == ControlLevelReadOnly {
+ return NewTextResult("Resource control actions are not available in read-only mode."), nil
+ }
+
+ resourceName := resolvedResourceDisplayName(resource)
+ resourceHost := strings.TrimSpace(resource.GetTargetHost())
+ command := fmt.Sprintf("truenas app %s %s", action, resourceName)
+ if resourceHost != "" {
+ command = fmt.Sprintf("%s on %s", command, resourceHost)
+ }
+ approvalTargetType := "app-container"
+ approvalTargetID := strings.TrimSpace(resource.GetResourceID())
+ if approvalTargetID == "" {
+ approvalTargetID = strings.TrimSpace(resource.GetProviderUID())
+ }
+
+ preApproved := consumeApprovalWithValidation(map[string]interface{}{"_approval_id": approvalID}, e.orgID, command, approvalTargetType, approvalTargetID)
+ decision := agentexec.PolicyAllow
+ if e.policy != nil {
+ decision = e.policy.Evaluate(command)
+ if decision == agentexec.PolicyBlock {
+ return NewTextResult(formatPolicyBlocked(command, "This action is blocked by security policy")), nil
+ }
+ }
+ requiresApproval := !e.isAutonomous && (e.controlLevel == ControlLevelControlled || decision == agentexec.PolicyRequireApproval)
+
+ if !preApproved && decision == agentexec.PolicyRequireApproval && !e.isAutonomous {
+ approvalID = createApprovalRecordForOrg(e.orgID, command, approvalTargetType, approvalTargetID, resourceName, fmt.Sprintf("%s app-container %s", action, resourceName))
+ return NewTextResult(formatAppContainerApprovalNeeded(resourceName, resourceHost, action, command, approvalID)), nil
+ }
+ if !preApproved && e.controlLevel == ControlLevelControlled {
+ approvalID = createApprovalRecordForOrg(e.orgID, command, approvalTargetType, approvalTargetID, resourceName, fmt.Sprintf("%s app-container %s", action, resourceName))
+ return NewTextResult(formatAppContainerApprovalNeeded(resourceName, resourceHost, action, command, approvalID)), nil
+ }
+
+ var actionResult *AppContainerActionResult
+ executionResult, err := e.executeNativeActionWithAudit(
+ ctx,
+ "pulse_control",
+ strings.TrimSpace(resource.GetResourceID()),
+ approvalID,
+ requiresApproval,
+ map[string]any{
+ "action": action,
+ "kind": resource.GetKind(),
+ "providerUid": resource.GetProviderUID(),
+ "host": resourceHost,
+ "platform": "truenas",
+ "approvalId": approvalID,
+ "requestedBy": "pulse_control",
+ },
+ "pulse_control",
+ fmt.Sprintf("%s app-container %s", action, resourceName),
+ func(ctx context.Context) (*unifiedresources.ExecutionResult, error) {
+ result, err := e.appContainerActionProvider.ExecuteAction(ctx, AppContainerActionRequest{
+ OrgID: e.orgID,
+ ResourceID: strings.TrimSpace(resource.GetResourceID()),
+ ProviderUID: strings.TrimSpace(resource.GetProviderUID()),
+ Name: resourceName,
+ Host: resourceHost,
+ Platform: "truenas",
+ Action: action,
+ })
+ if err != nil {
+ return nil, err
+ }
+ actionResult = result
+ return &unifiedresources.ExecutionResult{
+ Success: true,
+ Output: strings.TrimSpace(result.Output),
+ }, nil
+ },
+ )
+ if err != nil {
+ return NewErrorResult(err), nil
+ }
+ if actionResult == nil {
+ actionResult = &AppContainerActionResult{
+ ResourceID: strings.TrimSpace(resource.GetResourceID()),
+ ProviderUID: strings.TrimSpace(resource.GetProviderUID()),
+ Name: resourceName,
+ Host: resourceHost,
+ Platform: "truenas",
+ Action: action,
+ Output: strings.TrimSpace(executionResult.Output),
+ }
+ }
+ if strings.TrimSpace(actionResult.Output) == "" {
+ actionResult.Output = strings.TrimSpace(executionResult.Output)
+ }
+
+ response := map[string]interface{}{
+ "success": executionResult.Success,
+ "type": "resource",
+ "resource_id": actionResult.ResourceID,
+ "resource": actionResult.Name,
+ "resource_type": resource.GetKind(),
+ "provider_uid": actionResult.ProviderUID,
+ "platform": actionResult.Platform,
+ "host": actionResult.Host,
+ "action": actionResult.Action,
+ "status": actionResult.Status,
+ "output": actionResult.Output,
+ "verification": map[string]interface{}{
+ "ok": executionResult.Success,
+ "method": "provider_refresh",
+ "observed_status": actionResult.Status,
+ },
+ }
+ return NewJSONResultWithIsError(response, !executionResult.Success), nil
+}
+
+func resolvedResourceControlIdentity(resource ResolvedResourceInfo, fallback string) string {
+ if resource == nil {
+ return strings.TrimSpace(fallback)
+ }
+ if providerUID := strings.TrimSpace(resource.GetProviderUID()); providerUID != "" {
+ return providerUID
+ }
+ for _, alias := range resource.GetAliases() {
+ alias = strings.TrimSpace(alias)
+ if alias != "" {
+ return alias
+ }
+ }
+ return strings.TrimSpace(fallback)
+}
+
+func resolvedResourceDisplayName(resource ResolvedResourceInfo) string {
+ if resource == nil {
+ return ""
+ }
+ aliases := resource.GetAliases()
+ if len(aliases) > 0 {
+ if name := strings.TrimSpace(aliases[0]); name != "" {
+ return name
+ }
+ }
+ if providerUID := strings.TrimSpace(resource.GetProviderUID()); providerUID != "" {
+ return providerUID
+ }
+ return strings.TrimSpace(resource.GetResourceID())
}
func (e *PulseToolExecutor) executeRunCommand(ctx context.Context, args map[string]interface{}) (CallToolResult, error) {
@@ -1307,3 +1540,19 @@ func formatDockerApprovalNeeded(name, host, action, command, approvalID string)
b, _ := json.Marshal(payload)
return "APPROVAL_REQUIRED: " + string(b)
}
+
+func formatAppContainerApprovalNeeded(name, host, action, command, approvalID string) string {
+ payload := map[string]interface{}{
+ "type": "approval_required",
+ "approval_id": approvalID,
+ "resource_name": name,
+ "resource_host": host,
+ "resource_type": "app-container",
+ "action": action,
+ "command": command,
+ "how_to_approve": "Click the approval button in the chat to execute this action.",
+ "do_not_retry": true,
+ }
+ b, _ := json.Marshal(payload)
+ return "APPROVAL_REQUIRED: " + string(b)
+}
diff --git a/internal/ai/tools/tools_query.go b/internal/ai/tools/tools_query.go
index 0a3225d07c..7bc5ffc7fa 100644
--- a/internal/ai/tools/tools_query.go
+++ b/internal/ai/tools/tools_query.go
@@ -2330,6 +2330,113 @@ func canonicalAppContainerHost(resource unifiedresources.Resource) string {
return ""
}
+func guestExecutorActions() []string {
+ return []string{"query", "get", "logs", "console", "exec", "start", "stop", "shutdown", "restart", "delete"}
+}
+
+func canonicalAppContainerAdapter(resource unifiedresources.Resource) string {
+ switch canonicalResourcePlatform(resource) {
+ case "docker":
+ return "docker"
+ case "truenas":
+ return "truenas"
+ default:
+ return strings.TrimSpace(canonicalResourcePlatform(resource))
+ }
+}
+
+func canonicalCapabilityActions(resource unifiedresources.Resource) []string {
+ seen := make(map[string]struct{})
+ actions := make([]string, 0, len(resource.Capabilities))
+ for _, capability := range resource.Capabilities {
+ name := strings.ToLower(strings.TrimSpace(capability.Name))
+ if name == "" {
+ continue
+ }
+ if _, ok := seen[name]; ok {
+ continue
+ }
+ seen[name] = struct{}{}
+ actions = append(actions, name)
+ }
+ return actions
+}
+
+func appendUniqueStrings(base []string, values ...string) []string {
+ seen := make(map[string]struct{}, len(base))
+ for _, value := range base {
+ key := strings.TrimSpace(value)
+ if key == "" {
+ continue
+ }
+ seen[key] = struct{}{}
+ }
+ for _, value := range values {
+ key := strings.TrimSpace(value)
+ if key == "" {
+ continue
+ }
+ if _, ok := seen[key]; ok {
+ continue
+ }
+ seen[key] = struct{}{}
+ base = append(base, key)
+ }
+ return base
+}
+
+func canonicalAppContainerActions(resource unifiedresources.Resource) []string {
+ actions := []string{"query", "get"}
+ switch canonicalResourcePlatform(resource) {
+ case "docker":
+ actions = append(actions, "logs", "exec", "restart", "stop", "start")
+ case "truenas":
+ actions = append(actions, "restart", "stop", "start")
+ }
+ return appendUniqueStrings(actions, canonicalCapabilityActions(resource)...)
+}
+
+func resolvedAppContainerRegistration(resource unifiedresources.Resource) (ResourceRegistration, bool) {
+ containerID := strings.TrimSpace(canonicalAppContainerID(resource))
+ name := strings.TrimSpace(resourceDisplayName(resource))
+ host := strings.TrimSpace(canonicalAppContainerHost(resource))
+ adapter := strings.TrimSpace(canonicalAppContainerAdapter(resource))
+ if containerID == "" || name == "" || host == "" || adapter == "" {
+ return ResourceRegistration{}, false
+ }
+
+ aliases := appendUniqueStrings(nil, name, containerID, strings.TrimSpace(resource.ID))
+ if adapter == "docker" && len(containerID) > 12 {
+ aliases = appendUniqueStrings(aliases, containerID[:12])
+ }
+
+ reg := ResourceRegistration{
+ Kind: "app-container",
+ ProviderUID: containerID,
+ Name: name,
+ Aliases: aliases,
+ HostUID: host,
+ HostName: host,
+ Executors: []ExecutorRegistration{{
+ ExecutorID: host,
+ Adapter: adapter,
+ Actions: canonicalAppContainerActions(resource),
+ Priority: 10,
+ }},
+ }
+
+ switch adapter {
+ case "docker":
+ reg.LocationChain = []string{"docker-host:" + host, "docker:" + name}
+ case "truenas":
+ reg.LocationChain = []string{"system:" + host, "app:" + name}
+ default:
+ reg.LocationChain = []string{"app-container:" + name}
+ }
+
+ return reg, true
+}
+
func canonicalSystemSummaryFromResource(resource unifiedresources.Resource, connected map[string]bool) SystemSummary {
return SystemSummary{
ID: strings.TrimSpace(resource.ID),
@@ -3681,7 +3788,7 @@ func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[strin
Executors: []ExecutorRegistration{{
ExecutorID: vm.Node(),
Adapter: "qm",
- Actions: []string{"query", "get", "logs", "console"},
+ Actions: guestExecutorActions(),
Priority: 10,
}},
})
@@ -3736,7 +3843,7 @@ func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[strin
Executors: []ExecutorRegistration{{
ExecutorID: ct.Node(),
Adapter: "pct",
- Actions: []string{"query", "get", "logs", "console", "exec"},
+ Actions: guestExecutorActions(),
Priority: 10,
}},
})
@@ -3823,44 +3930,8 @@ func (e *PulseToolExecutor) executeGetResource(_ context.Context, args map[strin
}
}
- if response.Platform == "docker" {
- hostUID := ""
- if resource.ParentID != nil {
- hostUID = strings.TrimSpace(*resource.ParentID)
- }
- hostName := response.Host
- if hostUID == "" {
- hostUID = hostName
- }
- if hostName == "" {
- hostName = hostUID
- }
- executorID := hostName
- if executorID == "" {
- executorID = hostUID
- }
- aliases := []string{response.Name, containerID, strings.TrimSpace(resource.ID)}
- if len(containerID) > 12 {
- aliases = append(aliases, containerID[:12])
- }
- e.registerResolvedResourceWithExplicitAccess(ResourceRegistration{
- Kind: "app-container",
- ProviderUID: containerID,
- Name: response.Name,
- Aliases: aliases,
- HostUID: hostUID,
- HostName: hostName,
- LocationChain: []string{
- "docker-host:" + hostName,
- "docker:" + response.Name,
- },
- Executors: []ExecutorRegistration{{
- ExecutorID: executorID,
- Adapter: "docker",
- Actions: []string{"query", "get", "logs", "exec", "restart", "stop", "start"},
- Priority: 10,
- }},
- })
+ if reg, ok := resolvedAppContainerRegistration(resource); ok {
+ e.registerResolvedResourceWithExplicitAccess(reg)
}
return NewJSONResult(response.NormalizeCollections()), nil
}
@@ -4746,7 +4817,7 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
Executors: []ExecutorRegistration{{
ExecutorID: match.Node,
Adapter: "qm",
- Actions: []string{"query", "get", "logs", "console"},
+ Actions: guestExecutorActions(),
Priority: 10,
}},
}
@@ -4764,7 +4835,7 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
Executors: []ExecutorRegistration{{
ExecutorID: match.Node,
Adapter: "pct",
- Actions: []string{"query", "get", "logs", "console", "exec"},
+ Actions: guestExecutorActions(),
Priority: 10,
}},
}
@@ -4801,6 +4872,14 @@ func (e *PulseToolExecutor) executeSearchResources(_ context.Context, args map[s
Actions: []string{"query", "get", "logs", "exec", "restart", "stop", "start"},
Priority: 10,
}}
+ } else if match.Platform == "truenas" {
+ reg.LocationChain = []string{"system:" + match.Host, "app:" + match.Name}
+ reg.Executors = []ExecutorRegistration{{
+ ExecutorID: match.Host,
+ Adapter: "truenas",
+ Actions: []string{"query", "get", "restart", "stop", "start"},
+ Priority: 10,
+ }}
}
case "storage-pool":
reg = ResourceRegistration{
diff --git a/internal/ai/tools/tools_query_test.go b/internal/ai/tools/tools_query_test.go
index ae3f31c76c..25379e51f1 100644
--- a/internal/ai/tools/tools_query_test.go
+++ b/internal/ai/tools/tools_query_test.go
@@ -902,6 +902,43 @@ func TestExecuteQuery_UsesCanonicalTrueNASUnifiedResources(t *testing.T) {
}
}
+func TestExecuteGetResource_RegistersTrueNASAppContainerForCanonicalControl(t *testing.T) {
+ provider := newTrueNASUnifiedQueryProvider(t)
+ resolved := &mockResolvedContext{
+ resources: make(map[string]ResolvedResourceInfo),
+ aliases: make(map[string]ResolvedResourceInfo),
+ }
+ executor := NewPulseToolExecutor(ExecutorConfig{
+ UnifiedResourceProvider: provider,
+ })
+ executor.SetResolvedContext(resolved)
+
+ _, err := executor.executeGetResource(context.Background(), map[string]interface{}{
+ "resource_type": "app-container",
+ "resource_id": "nextcloud",
+ })
+ if err != nil {
+ t.Fatalf("get app-container: unexpected error: %v", err)
+ }
+
+ info, found := resolved.GetResolvedResourceByAlias("Nextcloud")
+ if !found {
+ t.Fatal("expected resolved context to include TrueNAS app by alias")
+ }
+ if info.GetAdapter() != "truenas" {
+ t.Fatalf("expected truenas adapter, got %q", info.GetAdapter())
+ }
+ if info.GetTargetHost() != "truenas-main" {
+ t.Fatalf("expected truenas-main target host, got %q", info.GetTargetHost())
+ }
+ allowed := strings.Join(info.GetAllowedActions(), ",")
+ for _, action := range []string{"query", "get", "start", "stop", "restart"} {
+ if !strings.Contains(allowed, action) {
+ t.Fatalf("expected allowed actions to include %q, got %v", action, info.GetAllowedActions())
+ }
+ }
+}
+
func TestExecuteQuerySurfacesIncludeGovernedMetadata(t *testing.T) {
state := models.StateSnapshot{
Nodes: []models.Node{
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
index e64fd19d47..858774ff34 100644
--- a/internal/api/ai_handler.go
+++ b/internal/api/ai_handler.go
@@ -66,6 +66,7 @@ type AIService interface {
SetEventCorrelatorProvider(provider chat.EventCorrelatorProvider)
SetDiscoveryProvider(provider chat.MCPDiscoveryProvider)
SetUnifiedResourceProvider(provider chat.MCPUnifiedResourceProvider)
+ SetAppContainerActionProvider(provider chat.MCPAppContainerActionProvider)
UpdateControlSettings(cfg *config.AIConfig)
GetBaseURL() string
}
diff --git a/internal/api/ai_handler_recovery_wiring_test.go b/internal/api/ai_handler_recovery_wiring_test.go
index 24d0afc964..2286529730 100644
--- a/internal/api/ai_handler_recovery_wiring_test.go
+++ b/internal/api/ai_handler_recovery_wiring_test.go
@@ -8,12 +8,14 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/ai/chat"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
"github.com/rcourtman/pulse-go-rewrite/internal/recovery"
recoverymanager "github.com/rcourtman/pulse-go-rewrite/internal/recovery/manager"
)
type capturingAIService struct {
- running bool
+ running bool
+ appContainerActionProvider chat.MCPAppContainerActionProvider
}
func (s *capturingAIService) Start(ctx context.Context) error { s.running = true; return nil }
@@ -75,8 +77,24 @@ func (s *capturingAIService) SetIncidentRecorderProvider(provider chat.IncidentR
func (s *capturingAIService) SetEventCorrelatorProvider(provider chat.EventCorrelatorProvider) {}
func (s *capturingAIService) SetDiscoveryProvider(provider chat.MCPDiscoveryProvider) {}
func (s *capturingAIService) SetUnifiedResourceProvider(provider chat.MCPUnifiedResourceProvider) {}
-func (s *capturingAIService) UpdateControlSettings(cfg *config.AIConfig) {}
-func (s *capturingAIService) GetBaseURL() string { return "" }
+func (s *capturingAIService) SetAppContainerActionProvider(provider chat.MCPAppContainerActionProvider) {
+ s.appContainerActionProvider = provider
+}
+func (s *capturingAIService) UpdateControlSettings(cfg *config.AIConfig) {}
+func (s *capturingAIService) GetBaseURL() string { return "" }
+
+func TestWireAIChatDependenciesForService_WiresTrueNASAppActionProvider(t *testing.T) {
+ router := &Router{
+ trueNASPoller: monitoring.NewTrueNASPoller(nil, 0, nil),
+ }
+ service := &capturingAIService{}
+
+ router.wireAIChatDependenciesForService(context.Background(), service)
+
+ if service.appContainerActionProvider == nil {
+ t.Fatal("expected TrueNAS app action provider to be wired into AI chat service")
+ }
+}
func TestAIHandlerStart_WiresRecoveryPointsProviderForDefaultChatService(t *testing.T) {
oldNewService := newChatService
diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.go
index 767c352044..17a40e4e9d 100644
--- a/internal/api/ai_handler_test.go
+++ b/internal/api/ai_handler_test.go
@@ -152,6 +152,9 @@ func (m *MockAIService) SetDiscoveryProvider(provider chat.MCPDiscoveryProvider)
func (m *MockAIService) SetUnifiedResourceProvider(provider chat.MCPUnifiedResourceProvider) {
m.Called(provider)
}
+func (m *MockAIService) SetAppContainerActionProvider(provider chat.MCPAppContainerActionProvider) {
+ m.Called(provider)
+}
func (m *MockAIService) UpdateControlSettings(cfg *config.AIConfig) { m.Called(cfg) }
func (m *MockAIService) GetBaseURL() string {
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index de2b227096..017b9eb08e 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -65,6 +65,19 @@ func TestContract_WebSocketTrustedProxyHostedOrigin(t *testing.T) {
conn.Close()
}
+func TestContract_WireAIChatDependencies_WiresTrueNASAppActionProvider(t *testing.T) {
+ router := &Router{
+ trueNASPoller: monitoring.NewTrueNASPoller(nil, 0, nil),
+ }
+ service := &capturingAIService{}
+
+ router.wireAIChatDependenciesForService(context.Background(), service)
+
+ if service.appContainerActionProvider == nil {
+ t.Fatal("expected TrueNAS app action provider to be wired into AI chat dependencies")
+ }
+}
+
func TestContract_SSOTestRejectsMetadataURLWithUserinfo(t *testing.T) {
called := make(chan struct{}, 1)
metadataServer := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/api/router.go b/internal/api/router.go
index f59c16c8a7..bc4a36a168 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -2415,6 +2415,10 @@ func (r *Router) wireAIChatDependenciesForService(ctx context.Context, service A
log.Debug().Msg("AI chat: Unified resource provider wired")
}
}
+ if provider := newTrueNASAppActionProvider(r.trueNASPoller); provider != nil {
+ service.SetAppContainerActionProvider(provider)
+ log.Debug().Msg("AI chat: App-container action provider wired")
+ }
log.Info().Str("org_id", orgID).Msg("AI chat MCP tool providers wired")
}
diff --git a/internal/api/truenas_app_action_provider.go b/internal/api/truenas_app_action_provider.go
new file mode 100644
index 0000000000..5a289b388d
--- /dev/null
+++ b/internal/api/truenas_app_action_provider.go
@@ -0,0 +1,70 @@
+package api
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
+)
+
+type trueNASAppActionProvider struct {
+ poller *monitoring.TrueNASPoller
+}
+
+func newTrueNASAppActionProvider(poller *monitoring.TrueNASPoller) tools.AppContainerActionProvider {
+ if poller == nil {
+ return nil
+ }
+ return &trueNASAppActionProvider{poller: poller}
+}
+
+func (p *trueNASAppActionProvider) ExecuteAction(ctx context.Context, req tools.AppContainerActionRequest) (*tools.AppContainerActionResult, error) {
+ if p == nil || p.poller == nil {
+ return nil, fmt.Errorf("truenas app action provider is unavailable")
+ }
+
+ appID := strings.TrimSpace(req.ProviderUID)
+ if appID == "" {
+ appID = strings.TrimSpace(req.Name)
+ }
+ app, err := p.poller.ControlApp(ctx, req.OrgID, req.Host, appID, req.Action)
+ if err != nil {
+ return nil, err
+ }
+
+ result := &tools.AppContainerActionResult{
+ ResourceID: strings.TrimSpace(req.ResourceID),
+ ProviderUID: strings.TrimSpace(req.ProviderUID),
+ Name: strings.TrimSpace(req.Name),
+ Host: strings.TrimSpace(req.Host),
+ Platform: strings.TrimSpace(req.Platform),
+ Action: strings.TrimSpace(req.Action),
+ }
+ if app != nil {
+ if id := strings.TrimSpace(app.ID); id != "" {
+ result.ProviderUID = id
+ }
+ if name := strings.TrimSpace(app.Name); name != "" {
+ result.Name = name
+ }
+ if state := strings.ToLower(strings.TrimSpace(app.State)); state != "" {
+ result.Status = state
+ }
+ }
+ if result.Platform == "" {
+ result.Platform = "truenas"
+ }
+ if result.Output == "" {
+ output := fmt.Sprintf("%s app %s", strings.TrimSpace(result.Action), strings.TrimSpace(result.Name))
+ if result.Host != "" {
+ output = fmt.Sprintf("%s on %s", output, result.Host)
+ }
+ if result.Status != "" {
+ output = fmt.Sprintf("%s; current state=%s", output, result.Status)
+ }
+ result.Output = output
+ }
+ return result, nil
+}
diff --git a/internal/monitoring/truenas_poller.go b/internal/monitoring/truenas_poller.go
index 1e968746bd..21b90b7443 100644
--- a/internal/monitoring/truenas_poller.go
+++ b/internal/monitoring/truenas_poller.go
@@ -3,6 +3,7 @@ package monitoring
import (
"context"
"errors"
+ "fmt"
"net"
"net/http"
"net/url"
@@ -493,6 +494,91 @@ func (p *TrueNASPoller) GetCurrentRecordsForOrg(orgID string) []unifiedresources
return records
}
+// ControlApp executes a canonical TrueNAS app action for one tenant-scoped
+// API-backed app-container resource and refreshes the cached records afterward.
+func (p *TrueNASPoller) ControlApp(ctx context.Context, orgID, host, appID, action string) (*truenas.App, error) {
+ if p == nil {
+ return nil, fmt.Errorf("truenas poller is nil")
+ }
+ if !truenas.IsFeatureEnabled() {
+ return nil, fmt.Errorf("truenas integration is disabled")
+ }
+
+ orgID = strings.TrimSpace(orgID)
+ if orgID == "" {
+ orgID = "default"
+ }
+ host = strings.TrimSpace(host)
+ appID = strings.TrimSpace(appID)
+ action = strings.ToLower(strings.TrimSpace(action))
+ if appID == "" {
+ return nil, fmt.Errorf("truenas app id is required")
+ }
+
+ type providerEntry struct {
+ connectionID string
+ provider *truenas.Provider
+ }
+
+ p.mu.Lock()
+ entries := make([]providerEntry, 0, len(p.providersByOrg[orgID]))
+ for connectionID, provider := range p.providersByOrg[orgID] {
+ if provider == nil {
+ continue
+ }
+ entries = append(entries, providerEntry{
+ connectionID: connectionID,
+ provider: provider,
+ })
+ }
+ p.mu.Unlock()
+
+ for _, entry := range entries {
+ currentSnapshot := entry.provider.Snapshot()
+ currentApp, ok := findTrueNASAppSnapshot(currentSnapshot, host, appID)
+ if !ok {
+ continue
+ }
+
+ var nextSnapshot *truenas.FixtureSnapshot
+ var err error
+ switch action {
+ case "start", "stop":
+ nextSnapshot, err = entry.provider.ControlApp(ctx, trueNASAppCanonicalID(*currentApp), action)
+ case "restart":
+ if trueNASAppRunning(currentApp) {
+ if _, err = entry.provider.ControlApp(ctx, trueNASAppCanonicalID(*currentApp), "stop"); err != nil {
+ return nil, err
+ }
+ }
+ nextSnapshot, err = entry.provider.ControlApp(ctx, trueNASAppCanonicalID(*currentApp), "start")
+ default:
+ return nil, fmt.Errorf("unsupported truenas app action %q", action)
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ records := entry.provider.Records()
+ p.mu.Lock()
+ if p.cachedRecordsByOrg[orgID] == nil {
+ p.cachedRecordsByOrg[orgID] = make(map[string][]unifiedresources.IngestRecord)
+ }
+ p.cachedRecordsByOrg[orgID][entry.connectionID] = cloneIngestRecords(records)
+ p.mu.Unlock()
+ p.ingestRecoveryPoints(ctx, orgID, entry.connectionID, entry.provider)
+
+ if updatedApp, ok := findTrueNASAppSnapshot(nextSnapshot, host, appID); ok {
+ appCopy := *updatedApp
+ return &appCopy, nil
+ }
+ appCopy := *currentApp
+ return &appCopy, nil
+ }
+
+ return nil, fmt.Errorf("truenas app %q was not found for org %q", appID, orgID)
+}
+
func cloneIngestRecords(records []unifiedresources.IngestRecord) []unifiedresources.IngestRecord {
if len(records) == 0 {
return nil
@@ -502,6 +588,44 @@ func cloneIngestRecords(records []unifiedresources.IngestRecord) []unifiedresour
return cloned
}
+func findTrueNASAppSnapshot(snapshot *truenas.FixtureSnapshot, host, appID string) (*truenas.App, bool) {
+ if snapshot == nil {
+ return nil, false
+ }
+ if host != "" && !strings.EqualFold(strings.TrimSpace(snapshot.System.Hostname), host) {
+ return nil, false
+ }
+ for i := range snapshot.Apps {
+ app := &snapshot.Apps[i]
+ if strings.EqualFold(trueNASAppCanonicalID(*app), appID) || strings.EqualFold(strings.TrimSpace(app.Name), appID) {
+ return app, true
+ }
+ }
+ return nil, false
+}
+
+func trueNASAppCanonicalID(app truenas.App) string {
+ if id := strings.TrimSpace(app.ID); id != "" {
+ return id
+ }
+ return strings.TrimSpace(app.Name)
+}
+
+func trueNASAppRunning(app *truenas.App) bool {
+ if app == nil {
+ return false
+ }
+ if strings.EqualFold(strings.TrimSpace(app.State), "RUNNING") {
+ return true
+ }
+ for _, container := range app.Containers {
+ if strings.EqualFold(strings.TrimSpace(container.State), "running") {
+ return true
+ }
+ }
+ return false
+}
+
func trueNASProviderConfigChanged(previous, next config.TrueNASInstance) bool {
return strings.TrimSpace(previous.Host) != strings.TrimSpace(next.Host) ||
previous.Port != next.Port ||
diff --git a/internal/monitoring/truenas_poller_test.go b/internal/monitoring/truenas_poller_test.go
index 0d3936078c..87eb9b95b4 100644
--- a/internal/monitoring/truenas_poller_test.go
+++ b/internal/monitoring/truenas_poller_test.go
@@ -249,6 +249,85 @@ func TestTrueNASPollerRecordsMetrics(t *testing.T) {
}
}
+type pollerControlFetcher struct {
+ snapshot *truenas.FixtureSnapshot
+ startCalls []string
+ stopCalls []string
+}
+
+func (f *pollerControlFetcher) Fetch(context.Context) (*truenas.FixtureSnapshot, error) {
+ if f == nil {
+ return nil, nil
+ }
+ return copyTrueNASSnapshot(f.snapshot), nil
+}
+
+func (f *pollerControlFetcher) StartApp(_ context.Context, appID string) error {
+ f.startCalls = append(f.startCalls, appID)
+ for i := range f.snapshot.Apps {
+ if f.snapshot.Apps[i].ID == appID {
+ f.snapshot.Apps[i].State = "RUNNING"
+ if len(f.snapshot.Apps[i].Containers) > 0 {
+ f.snapshot.Apps[i].Containers[0].State = "running"
+ }
+ }
+ }
+ return nil
+}
+
+func (f *pollerControlFetcher) StopApp(_ context.Context, appID string) error {
+ f.stopCalls = append(f.stopCalls, appID)
+ for i := range f.snapshot.Apps {
+ if f.snapshot.Apps[i].ID == appID {
+ f.snapshot.Apps[i].State = "STOPPED"
+ if len(f.snapshot.Apps[i].Containers) > 0 {
+ f.snapshot.Apps[i].Containers[0].State = "stopped"
+ }
+ }
+ }
+ return nil
+}
+
+func TestTrueNASPollerControlAppRefreshesCachedRecords(t *testing.T) {
+ previous := truenas.IsFeatureEnabled()
+ truenas.SetFeatureEnabled(true)
+ t.Cleanup(func() { truenas.SetFeatureEnabled(previous) })
+
+ fixtures := truenas.DefaultFixtures()
+ for i := range fixtures.Apps {
+ if fixtures.Apps[i].ID == "nextcloud" {
+ fixtures.Apps[i].State = "STOPPED"
+ if len(fixtures.Apps[i].Containers) > 0 {
+ fixtures.Apps[i].Containers[0].State = "stopped"
+ }
+ }
+ }
+
+ fetcher := &pollerControlFetcher{snapshot: &fixtures}
+ provider := truenas.NewLiveProvider(fetcher)
+ if err := provider.Refresh(context.Background()); err != nil {
+ t.Fatalf("Refresh() error = %v", err)
+ }
+
+ poller := NewTrueNASPoller(nil, 0, nil)
+ poller.providersByOrg["default"] = map[string]*truenas.Provider{"conn-1": provider}
+ poller.cachedRecordsByOrg["default"] = map[string][]unifiedresources.IngestRecord{"conn-1": provider.Records()}
+
+ app, err := poller.ControlApp(context.Background(), "default", "truenas-main", "nextcloud", "start")
+ if err != nil {
+ t.Fatalf("ControlApp() error = %v", err)
+ }
+ if app == nil || app.State != "RUNNING" {
+ t.Fatalf("expected RUNNING app after control, got %+v", app)
+ }
+ if len(fetcher.startCalls) != 1 || fetcher.startCalls[0] != "nextcloud" {
+ t.Fatalf("expected start call for nextcloud, got %+v", fetcher.startCalls)
+ }
+ if got := len(poller.cachedRecordsByOrg["default"]["conn-1"]); got == 0 {
+ t.Fatal("expected refreshed cached records after app control")
+ }
+}
+
func TestTrueNASPollerHandlesConnectionAddRemove(t *testing.T) {
previous := truenas.IsFeatureEnabled()
truenas.SetFeatureEnabled(true)
@@ -299,6 +378,44 @@ func TestTrueNASPollerHandlesConnectionAddRemove(t *testing.T) {
}
}
+func copyTrueNASSnapshot(snapshot *truenas.FixtureSnapshot) *truenas.FixtureSnapshot {
+ if snapshot == nil {
+ return nil
+ }
+ cloned := *snapshot
+ cloned.Pools = append([]truenas.Pool(nil), snapshot.Pools...)
+ cloned.Datasets = append([]truenas.Dataset(nil), snapshot.Datasets...)
+ cloned.Disks = append([]truenas.Disk(nil), snapshot.Disks...)
+ cloned.Alerts = append([]truenas.Alert(nil), snapshot.Alerts...)
+ cloned.ZFSSnapshots = append([]truenas.ZFSSnapshot(nil), snapshot.ZFSSnapshots...)
+ cloned.ReplicationTasks = append([]truenas.ReplicationTask(nil), snapshot.ReplicationTasks...)
+ if snapshot.System.TemperatureCelsius != nil {
+ cloned.System.TemperatureCelsius = make(map[string]float64, len(snapshot.System.TemperatureCelsius))
+ for key, value := range snapshot.System.TemperatureCelsius {
+ cloned.System.TemperatureCelsius[key] = value
+ }
+ }
+ if len(snapshot.Apps) > 0 {
+ cloned.Apps = make([]truenas.App, len(snapshot.Apps))
+ for i, app := range snapshot.Apps {
+ appCopy := app
+ appCopy.UsedHostIPs = append([]string(nil), app.UsedHostIPs...)
+ appCopy.UsedPorts = append([]truenas.AppPort(nil), app.UsedPorts...)
+ appCopy.Volumes = append([]truenas.AppVolume(nil), app.Volumes...)
+ appCopy.Images = append([]string(nil), app.Images...)
+ appCopy.Networks = append([]truenas.AppNetwork(nil), app.Networks...)
+ appCopy.Containers = append([]truenas.AppContainer(nil), app.Containers...)
+ if app.Stats != nil {
+ statsCopy := *app.Stats
+ statsCopy.Interfaces = append([]truenas.AppInterfaceStats(nil), app.Stats.Interfaces...)
+ appCopy.Stats = &statsCopy
+ }
+ cloned.Apps[i] = appCopy
+ }
+ }
+ return &cloned
+}
+
func TestTrueNASPollerAPITimeout(t *testing.T) {
previous := truenas.IsFeatureEnabled()
truenas.SetFeatureEnabled(true)
diff --git a/internal/truenas/client.go b/internal/truenas/client.go
index 77f0468519..c441947ddc 100644
--- a/internal/truenas/client.go
+++ b/internal/truenas/client.go
@@ -460,6 +460,43 @@ func (c *Client) GetAppStats(ctx context.Context) (map[string]AppStats, error) {
return rpc.readAppStatsEvent(ctx, defaultAppStatsIntervalSeconds)
}
+// StartApp requests that TrueNAS start the named app through the canonical
+// JSON-RPC control path.
+func (c *Client) StartApp(ctx context.Context, appID string) error {
+ return c.executeAppAction(ctx, "app.start", appID)
+}
+
+// StopApp requests that TrueNAS stop the named app through the canonical
+// JSON-RPC control path.
+func (c *Client) StopApp(ctx context.Context, appID string) error {
+ return c.executeAppAction(ctx, "app.stop", appID)
+}
+
+func (c *Client) executeAppAction(ctx context.Context, method, appID string) error {
+ appID = strings.TrimSpace(appID)
+ if appID == "" {
+ return fmt.Errorf("truenas app id is required")
+ }
+
+ conn, err := c.dialRPC(ctx)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = conn.Close() }()
+
+ rpc := trueNASRPCClient{
+ conn: conn,
+ nextID: 1,
+ }
+ if err := rpc.authenticate(ctx, c.config); err != nil {
+ return err
+ }
+ if err := rpc.call(ctx, method, []any{appID}, nil); err != nil {
+ return err
+ }
+ return nil
+}
+
// GetZFSSnapshots returns a best-effort list of ZFS snapshots.
//
// NOTE: TrueNAS exposes multiple snapshot APIs across versions. We intentionally parse the
diff --git a/internal/truenas/client_test.go b/internal/truenas/client_test.go
index a47d855ffa..debdec3c8a 100644
--- a/internal/truenas/client_test.go
+++ b/internal/truenas/client_test.go
@@ -280,6 +280,40 @@ func TestGetAppsEnrichesStatsFromRPC(t *testing.T) {
}
}
+func TestStartAndStopAppUseRPCMethods(t *testing.T) {
+ var rpcCalls int
+ server := newMockServerWithRPC(t, defaultAPIResponses(), nil, func(t *testing.T, conn *websocket.Conn) {
+ rpcCalls++
+ authReq := readRPCRequest(t, conn)
+ if authReq.Method != "auth.login_with_api_key" {
+ t.Fatalf("expected api-key auth method, got %q", authReq.Method)
+ }
+ writeRPCResult(t, conn, authReq.ID, true)
+
+ actionReq := readRPCRequest(t, conn)
+ expectedMethod := "app.start"
+ if rpcCalls == 2 {
+ expectedMethod = "app.stop"
+ }
+ if actionReq.Method != expectedMethod {
+ t.Fatalf("expected %s, got %q", expectedMethod, actionReq.Method)
+ }
+ writeRPCResult(t, conn, actionReq.ID, true)
+ })
+ t.Cleanup(server.Close)
+
+ client := mustClientForServer(t, server.URL, ClientConfig{APIKey: "api-key"})
+ if err := client.StartApp(context.Background(), "nextcloud"); err != nil {
+ t.Fatalf("StartApp() error = %v", err)
+ }
+ if err := client.StopApp(context.Background(), "nextcloud"); err != nil {
+ t.Fatalf("StopApp() error = %v", err)
+ }
+ if rpcCalls != 2 {
+ t.Fatalf("expected two RPC app-action sessions, got %d", rpcCalls)
+ }
+}
+
func TestGetSystemTelemetryFromRPC(t *testing.T) {
server := newMockServerWithRPC(t, defaultAPIResponses(), nil, func(t *testing.T, conn *websocket.Conn) {
authReq := readRPCRequest(t, conn)
diff --git a/internal/truenas/provider.go b/internal/truenas/provider.go
index dd463bbc21..f94fae9145 100644
--- a/internal/truenas/provider.go
+++ b/internal/truenas/provider.go
@@ -47,6 +47,11 @@ type fetcherCloser interface {
Close()
}
+type appActionFetcher interface {
+ StartApp(ctx context.Context, appID string) error
+ StopApp(ctx context.Context, appID string) error
+}
+
// APIFetcher loads snapshots from the live TrueNAS API client.
type APIFetcher struct {
Client *Client
@@ -68,6 +73,20 @@ func (f *APIFetcher) Close() {
f.Client.Close()
}
+func (f *APIFetcher) StartApp(ctx context.Context, appID string) error {
+ if f == nil || f.Client == nil {
+ return fmt.Errorf("truenas api fetcher client is nil")
+ }
+ return f.Client.StartApp(ctx, appID)
+}
+
+func (f *APIFetcher) StopApp(ctx context.Context, appID string) error {
+ if f == nil || f.Client == nil {
+ return fmt.Errorf("truenas api fetcher client is nil")
+ }
+ return f.Client.StopApp(ctx, appID)
+}
+
// FixtureFetcher loads snapshots from static fixture data.
type FixtureFetcher struct {
Snapshot FixtureSnapshot
@@ -138,6 +157,36 @@ func (p *Provider) Refresh(ctx context.Context) error {
return nil
}
+// ControlApp executes a native start/stop action against a TrueNAS app and
+// refreshes the cached snapshot so downstream readers observe canonical state.
+func (p *Provider) ControlApp(ctx context.Context, appID, action string) (*FixtureSnapshot, error) {
+ if p == nil {
+ return nil, fmt.Errorf("truenas provider is nil")
+ }
+ executor, ok := p.fetcher.(appActionFetcher)
+ if !ok {
+ return nil, fmt.Errorf("truenas provider fetcher does not support app control")
+ }
+
+ switch strings.ToLower(strings.TrimSpace(action)) {
+ case "start":
+ if err := executor.StartApp(ctx, appID); err != nil {
+ return nil, err
+ }
+ case "stop":
+ if err := executor.StopApp(ctx, appID); err != nil {
+ return nil, err
+ }
+ default:
+ return nil, fmt.Errorf("unsupported truenas app action %q", action)
+ }
+
+ if err := p.Refresh(ctx); err != nil {
+ return nil, err
+ }
+ return p.Snapshot(), nil
+}
+
// Close releases resources held by the active fetcher, if supported.
func (p *Provider) Close() {
if p == nil || p.fetcher == nil {
@@ -337,15 +386,16 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {
SourceID: appSourceID(app.ID),
ParentSourceID: systemSourceID,
Resource: unifiedresources.Resource{
- Type: unifiedresources.ResourceTypeAppContainer,
- Technology: "docker",
- Name: appDisplayName(app),
- Status: statusFromApp(app),
- LastSeen: collectedAt,
- UpdatedAt: collectedAt,
- Metrics: metrics,
- Docker: dockerMeta,
- Tags: appTags(app),
+ Type: unifiedresources.ResourceTypeAppContainer,
+ Technology: "docker",
+ Name: appDisplayName(app),
+ Status: statusFromApp(app),
+ LastSeen: collectedAt,
+ UpdatedAt: collectedAt,
+ Metrics: metrics,
+ Docker: dockerMeta,
+ Capabilities: truenasAppCapabilities(),
+ Tags: appTags(app),
},
Identity: unifiedresources.ResourceIdentity{
Hostnames: dedupeStrings([]string{appDisplayName(app)}),
@@ -971,6 +1021,35 @@ func statusFromApp(app App) unifiedresources.ResourceStatus {
}
}
+func truenasAppCapabilities() []unifiedresources.ResourceCapability {
+ return []unifiedresources.ResourceCapability{
+ {
+ Name: "start",
+ Type: unifiedresources.CapabilityTypeCommon,
+ Description: "Start the TrueNAS-managed application.",
+ MinimumApprovalLevel: unifiedresources.ApprovalAdmin,
+ Platform: "truenas",
+ InternalHandler: "app.start",
+ },
+ {
+ Name: "stop",
+ Type: unifiedresources.CapabilityTypeCommon,
+ Description: "Stop the TrueNAS-managed application.",
+ MinimumApprovalLevel: unifiedresources.ApprovalAdmin,
+ Platform: "truenas",
+ InternalHandler: "app.stop",
+ },
+ {
+ Name: "restart",
+ Type: unifiedresources.CapabilityTypeCommon,
+ Description: "Restart the TrueNAS-managed application using canonical stop/start semantics.",
+ MinimumApprovalLevel: unifiedresources.ApprovalAdmin,
+ Platform: "truenas",
+ InternalHandler: "app.restart",
+ },
+ }
+}
+
func appTags(app App) []string {
tags := []string{"truenas", "app"}
if state := strings.ToLower(strings.TrimSpace(app.State)); state != "" {
diff --git a/internal/truenas/provider_test.go b/internal/truenas/provider_test.go
index 63a2234291..421f448df2 100644
--- a/internal/truenas/provider_test.go
+++ b/internal/truenas/provider_test.go
@@ -37,6 +37,42 @@ func (s *closableStubFetcher) Close() {
s.closeCalls++
}
+type controllableStubFetcher struct {
+ snapshot *FixtureSnapshot
+ startCalls []string
+ stopCalls []string
+}
+
+func (s *controllableStubFetcher) Fetch(context.Context) (*FixtureSnapshot, error) {
+ return copyFixtureSnapshot(s.snapshot), nil
+}
+
+func (s *controllableStubFetcher) StartApp(_ context.Context, appID string) error {
+ s.startCalls = append(s.startCalls, appID)
+ for i := range s.snapshot.Apps {
+ if s.snapshot.Apps[i].ID == appID {
+ s.snapshot.Apps[i].State = "RUNNING"
+ if len(s.snapshot.Apps[i].Containers) > 0 {
+ s.snapshot.Apps[i].Containers[0].State = "running"
+ }
+ }
+ }
+ return nil
+}
+
+func (s *controllableStubFetcher) StopApp(_ context.Context, appID string) error {
+ s.stopCalls = append(s.stopCalls, appID)
+ for i := range s.snapshot.Apps {
+ if s.snapshot.Apps[i].ID == appID {
+ s.snapshot.Apps[i].State = "STOPPED"
+ if len(s.snapshot.Apps[i].Containers) > 0 {
+ s.snapshot.Apps[i].Containers[0].State = "stopped"
+ }
+ }
+ }
+ return nil
+}
+
func TestFixtureFetcherReturnsSnapshotCopy(t *testing.T) {
fixtures := DefaultFixtures()
fetcher := &FixtureFetcher{Snapshot: fixtures}
@@ -116,6 +152,41 @@ func TestProviderRefreshUpdatesLastSnapshot(t *testing.T) {
}
}
+func TestProviderControlAppUsesFetcherAndRefreshesSnapshot(t *testing.T) {
+ fixtures := DefaultFixtures()
+ for i := range fixtures.Apps {
+ if fixtures.Apps[i].ID == "nextcloud" {
+ fixtures.Apps[i].State = "STOPPED"
+ if len(fixtures.Apps[i].Containers) > 0 {
+ fixtures.Apps[i].Containers[0].State = "stopped"
+ }
+ }
+ }
+
+ fetcher := &controllableStubFetcher{snapshot: &fixtures}
+ provider := NewLiveProvider(fetcher)
+
+ snapshot, err := provider.ControlApp(context.Background(), "nextcloud", "start")
+ if err != nil {
+ t.Fatalf("ControlApp(start) error = %v", err)
+ }
+ if len(fetcher.startCalls) != 1 || fetcher.startCalls[0] != "nextcloud" {
+ t.Fatalf("expected start call for nextcloud, got %+v", fetcher.startCalls)
+ }
+ if snapshot == nil {
+ t.Fatal("expected refreshed snapshot after control")
+ }
+ foundRunning := false
+ for _, app := range snapshot.Apps {
+ if app.ID == "nextcloud" && app.State == "RUNNING" {
+ foundRunning = true
+ }
+ }
+ if !foundRunning {
+ t.Fatalf("expected nextcloud to be RUNNING after control, got %+v", snapshot.Apps)
+ }
+}
+
func TestProviderRefreshPreservesLastSnapshotOnError(t *testing.T) {
initial := DefaultFixtures()
provider := NewProvider(initial)
diff --git a/internal/unifiedresources/resolve.go b/internal/unifiedresources/resolve.go
index 94bb56a8bb..61110544ea 100644
--- a/internal/unifiedresources/resolve.go
+++ b/internal/unifiedresources/resolve.go
@@ -93,31 +93,17 @@ func ResolveResource(rs ReadState, name string) models.ResourceLocation {
// Check Docker containers — flat list, resolve parent host.
// Docker CONTAINER lookups DO rewrite TargetHost to the backing guest name.
- for _, container := range rs.DockerContainers() {
- if container == nil {
+ for _, resource := range appContainerResourcesFromReadState(rs) {
+ if !appContainerResourceMatches(resource, name) {
continue
}
- if container.Name() == name {
- loc := models.ResourceLocation{
- Found: true,
- Name: name,
- ResourceType: "app-container",
- }
- // Find the parent Docker host to populate the routing chain.
- parentID := container.ParentID()
- for _, dh := range rs.DockerHosts() {
- if dh == nil {
- continue
- }
- if dh.ID() == parentID {
- loc.DockerHostName = dh.Hostname()
- loc.TargetHost = dh.Hostname()
- resolveDockerHostParent(rs, dh.Hostname(), dh.HostSourceID(), true, &loc)
- break
- }
- }
- return loc
+ loc := models.ResourceLocation{
+ Found: true,
+ Name: name,
+ ResourceType: "app-container",
}
+ populateAppContainerLocation(rs, resource, &loc)
+ return loc
}
// Check generic Hosts (Windows/Linux via Pulse Unified Agent).
@@ -270,3 +256,123 @@ func resolveDockerHostParent(rs ReadState, hostname, sourceID string, rewriteTar
}
loc.DockerHostType = "standalone"
}
+
+type appContainerResourceGetter interface {
+ GetByType(ResourceType) []Resource
+}
+
+type appContainerResourceLister interface {
+ ListByType(ResourceType) []Resource
+}
+
+func appContainerResourcesFromReadState(rs ReadState) []Resource {
+ if rs == nil {
+ return nil
+ }
+ if getter, ok := any(rs).(appContainerResourceGetter); ok {
+ return getter.GetByType(ResourceTypeAppContainer)
+ }
+ if lister, ok := any(rs).(appContainerResourceLister); ok {
+ return lister.ListByType(ResourceTypeAppContainer)
+ }
+
+ containers := rs.DockerContainers()
+ if len(containers) == 0 {
+ return nil
+ }
+ resources := make([]Resource, 0, len(containers))
+ for _, container := range containers {
+ if container == nil || container.r == nil {
+ continue
+ }
+ resources = append(resources, cloneResource(container.r))
+ }
+ return resources
+}
+
+func appContainerResourceMatches(resource Resource, name string) bool {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return false
+ }
+ if strings.EqualFold(strings.TrimSpace(resource.Name), name) || strings.EqualFold(strings.TrimSpace(resource.ID), name) {
+ return true
+ }
+ if resource.Docker != nil && strings.EqualFold(strings.TrimSpace(resource.Docker.ContainerID), name) {
+ return true
+ }
+ if resource.Canonical != nil {
+ for _, alias := range resource.Canonical.Aliases {
+ if strings.EqualFold(strings.TrimSpace(alias), name) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func appContainerResourceHost(resource Resource) string {
+ if host := strings.TrimSpace(resource.ParentName); host != "" {
+ return host
+ }
+ if resource.Docker != nil {
+ if host := strings.TrimSpace(resource.Docker.Hostname); host != "" {
+ return host
+ }
+ }
+ if resource.TrueNAS != nil {
+ if host := strings.TrimSpace(resource.TrueNAS.Hostname); host != "" {
+ return host
+ }
+ }
+ for _, host := range resource.Identity.Hostnames {
+ host = strings.TrimSpace(host)
+ if host != "" {
+ return host
+ }
+ }
+ return ""
+}
+
+func populateAppContainerLocation(rs ReadState, resource Resource, loc *models.ResourceLocation) {
+ if loc == nil {
+ return
+ }
+ hostName := appContainerResourceHost(resource)
+ if hostName == "" {
+ return
+ }
+ loc.TargetHost = hostName
+
+ if !appContainerUsesDockerRouting(resource) {
+ return
+ }
+
+ loc.DockerHostName = hostName
+ hostSourceID := hostName
+ if resource.ParentID != nil {
+ if parentID := strings.TrimSpace(*resource.ParentID); parentID != "" {
+ hostSourceID = parentID
+ }
+ }
+ resolveDockerHostParent(rs, hostName, hostSourceID, true, loc)
+}
+
+func appContainerUsesDockerRouting(resource Resource) bool {
+ if resourceHasTagCaseInsensitive(resource, "truenas") {
+ return false
+ }
+ if resource.Docker != nil {
+ return true
+ }
+ return resourceHasTagCaseInsensitive(resource, "docker")
+}
+
+func resourceHasTagCaseInsensitive(resource Resource, needle string) bool {
+ for _, tag := range resource.Tags {
+ if strings.EqualFold(strings.TrimSpace(tag), needle) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/unifiedresources/resolve_context.go b/internal/unifiedresources/resolve_context.go
index 0628ec2513..630578997d 100644
--- a/internal/unifiedresources/resolve_context.go
+++ b/internal/unifiedresources/resolve_context.go
@@ -76,12 +76,9 @@ func lookupResolvedResource(rs ReadState, loc models.ResourceLocation) *Resource
}
case "app-container":
- for _, container := range rs.DockerContainers() {
- if container == nil {
- continue
- }
- if container.Name() == name {
- return cloneResourcePtr(container.r)
+ for _, resource := range appContainerResourcesFromReadState(rs) {
+ if appContainerResourceMatches(resource, name) {
+ return cloneResourcePtr(&resource)
}
}
diff --git a/internal/unifiedresources/resolve_test.go b/internal/unifiedresources/resolve_test.go
index d9db160edd..78b668eab2 100644
--- a/internal/unifiedresources/resolve_test.go
+++ b/internal/unifiedresources/resolve_test.go
@@ -2,6 +2,7 @@ package unifiedresources
import (
"testing"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
)
@@ -171,6 +172,98 @@ func TestResolveResource_DockerHost(t *testing.T) {
}
}
+func TestResolveResource_TrueNASAppDoesNotUseDockerRouting(t *testing.T) {
+ rr := newTrueNASAppRegistryFixture()
+
+ loc := ResolveResource(rr, "Nextcloud")
+ if !loc.Found || loc.ResourceType != "app-container" {
+ t.Fatalf("expected TrueNAS app-container, got found=%v type=%q", loc.Found, loc.ResourceType)
+ }
+ if loc.TargetHost != "truenas-main" {
+ t.Fatalf("expected target host truenas-main, got %q", loc.TargetHost)
+ }
+ if loc.DockerHostName != "" || loc.DockerHostType != "" {
+ t.Fatalf("expected TrueNAS app to avoid docker routing, got docker_host=%q type=%q", loc.DockerHostName, loc.DockerHostType)
+ }
+}
+
+func TestLookupResolvedResource_TrueNASAppUsesCanonicalAppContainerSet(t *testing.T) {
+ rr := newTrueNASAppRegistryFixture()
+
+ loc := ResolveResource(rr, "Nextcloud")
+ resource := lookupResolvedResource(rr, loc)
+ if resource == nil {
+ t.Fatal("expected resolved resource for TrueNAS app")
+ }
+ if resource.Type != ResourceTypeAppContainer {
+ t.Fatalf("expected app-container resource, got %q", resource.Type)
+ }
+ if resource.TrueNAS == nil {
+ t.Fatalf("expected TrueNAS metadata on resolved resource, got %+v", resource)
+ }
+ if resource.Name != "Nextcloud" {
+ t.Fatalf("expected canonical app name Nextcloud, got %q", resource.Name)
+ }
+}
+
+func newTrueNASAppRegistryFixture() *ResourceRegistry {
+ rr := NewRegistry(nil)
+ now := time.Now().UTC()
+ hostID := "agent:truenas-main"
+ hostSourceID := "truenas-system:truenas-main"
+ rr.IngestRecords(SourceTrueNAS, []IngestRecord{
+ {
+ SourceID: hostSourceID,
+ Resource: Resource{
+ ID: hostID,
+ Type: ResourceTypeAgent,
+ Name: "truenas-main",
+ Status: StatusOnline,
+ LastSeen: now,
+ UpdatedAt: now,
+ Agent: &AgentData{
+ Hostname: "truenas-main",
+ Platform: "truenas",
+ },
+ TrueNAS: &TrueNASData{Hostname: "truenas-main"},
+ },
+ Identity: ResourceIdentity{Hostnames: []string{"truenas-main"}},
+ },
+ {
+ SourceID: "app:nextcloud",
+ ParentSourceID: hostSourceID,
+ Resource: Resource{
+ ID: "app-container:truenas-main:nextcloud",
+ Type: ResourceTypeAppContainer,
+ Name: "Nextcloud",
+ Status: StatusOnline,
+ LastSeen: now,
+ UpdatedAt: now,
+ ParentID: stringPtr(hostID),
+ ParentName: "truenas-main",
+ Docker: &DockerData{
+ ContainerID: "nextcloud",
+ Hostname: "truenas-main",
+ },
+ TrueNAS: &TrueNASData{Hostname: "truenas-main"},
+ Canonical: &CanonicalIdentity{
+ DisplayName: "Nextcloud",
+ Hostname: "truenas-main",
+ PrimaryID: "nextcloud",
+ Aliases: []string{"Nextcloud", "nextcloud"},
+ },
+ Tags: []string{"truenas", "app"},
+ },
+ Identity: ResourceIdentity{Hostnames: []string{"truenas-main"}},
+ },
+ })
+ return rr
+}
+
+func stringPtr(value string) *string {
+ return &value
+}
+
func TestResolveResource_Host(t *testing.T) {
rr := NewRegistry(nil)
rr.IngestSnapshot(models.StateSnapshot{