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(#903): Remote agent configuration for AI command execution

rcourtman55f63d5e9659
diff --git a/frontend-modern/src/api/monitoring.ts b/frontend-modern/src/api/monitoring.ts
index 6a9eaf4db8..225197ad2f 100644
--- a/frontend-modern/src/api/monitoring.ts
+++ b/frontend-modern/src/api/monitoring.ts
@@ -441,6 +441,45 @@ export class MonitoringAPI {
}
}
+ static async updateHostAgentConfig(hostId: string, config: { commandsEnabled?: boolean }): Promise<void> {
+ if (!hostId) {
+ throw new Error('Host ID is required to update agent config.');
+ }
+
+ const url = `${this.baseUrl}/agents/host/${encodeURIComponent(hostId)}/config`;
+ const response = await apiFetch(url, {
+ method: 'PATCH',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(config),
+ });
+
+ if (!response.ok) {
+ let message = `Failed with status ${response.status}`;
+ try {
+ const text = await response.text();
+ if (text?.trim()) {
+ message = text.trim();
+ try {
+ const parsed = JSON.parse(text);
+ if (typeof parsed?.error === 'string' && parsed.error.trim()) {
+ message = parsed.error.trim();
+ } else if (typeof parsed?.message === 'string' && parsed.message.trim()) {
+ message = parsed.message.trim();
+ }
+ } catch (_err) {
+ // Ignore JSON parse errors.
+ }
+ }
+ } catch (_err) {
+ // Ignore body read errors.
+ }
+
+ throw new Error(message);
+ }
+ }
+
static async lookupHost(params: { id?: string; hostname?: string }): Promise<HostLookupResponse | null> {
const search = new URLSearchParams();
if (params.id) search.set('id', params.id);
diff --git a/frontend-modern/src/components/Settings/UnifiedAgents.tsx b/frontend-modern/src/components/Settings/UnifiedAgents.tsx
index 5e2d85fe77..0b28ca5443 100644
--- a/frontend-modern/src/components/Settings/UnifiedAgents.tsx
+++ b/frontend-modern/src/components/Settings/UnifiedAgents.tsx
@@ -109,6 +109,7 @@ export const UnifiedAgents: Component = () => {
const [lookupError, setLookupError] = createSignal<string | null>(null);
const [lookupLoading, setLookupLoading] = createSignal(false);
const [insecureMode, setInsecureMode] = createSignal(false); // For self-signed certificates (issue #806)
+ const [enableCommands, setEnableCommands] = createSignal(false); // Enable AI command execution (issue #903)
const [customAgentUrl, setCustomAgentUrl] = createSignal('');
createEffect(() => {
@@ -239,6 +240,7 @@ export const UnifiedAgents: Component = () => {
};
const getInsecureFlag = () => insecureMode() ? ' --insecure' : '';
+ const getEnableCommandsFlag = () => enableCommands() ? ' --enable-commands' : '';
const getCurlInsecureFlag = () => insecureMode() ? '-k' : '';
const getUninstallCommand = () => {
@@ -265,6 +267,7 @@ export const UnifiedAgents: Component = () => {
lastSeen?: number;
isLegacy?: boolean;
linkedNodeId?: string;
+ commandsEnabled?: boolean;
}>();
// Process Host Agents (skip those linked to PVE nodes - they're shown merged with the node)
@@ -284,7 +287,8 @@ export const UnifiedAgents: Component = () => {
status: h.status || 'unknown',
version: h.agentVersion,
lastSeen: h.lastSeen,
- isLegacy: h.isLegacy
+ isLegacy: h.isLegacy,
+ commandsEnabled: h.commandsEnabled
});
});
@@ -420,6 +424,16 @@ export const UnifiedAgents: Component = () => {
}
};
+ const handleToggleCommands = async (hostId: string, enabled: boolean) => {
+ try {
+ await MonitoringAPI.updateHostAgentConfig(hostId, { commandsEnabled: enabled });
+ notificationStore.success(`AI command execution ${enabled ? 'enabled' : 'disabled'}. Agent will apply change on next report.`);
+ } catch (err) {
+ logger.error('Failed to toggle AI commands', err);
+ notificationStore.error('Failed to update agent configuration');
+ }
+ };
+
return (
<div class="space-y-6">
<Card padding="lg" class="space-y-5">
@@ -569,6 +583,20 @@ export const UnifiedAgents: Component = () => {
/>
Skip TLS certificate verification (self-signed certs)
</label>
+ <label class="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer" title="Allow AI Patrol to execute diagnostic and fix commands on this agent (requires Pulse Pro)">
+ <input
+ type="checkbox"
+ checked={enableCommands()}
+ onChange={(e) => setEnableCommands(e.currentTarget.checked)}
+ class="rounded border-gray-300 text-blue-600 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700"
+ />
+ Enable AI command execution (for AI auto-fix)
+ </label>
+ <Show when={enableCommands()}>
+ <div class="rounded-lg border border-blue-200 bg-blue-50 px-4 py-2 text-sm text-blue-800 dark:border-blue-700 dark:bg-blue-900/20 dark:text-blue-200">
+ <span class="font-medium">AI commands enabled</span> — The agent will accept diagnostic and fix commands from Pulse AI features.
+ </div>
+ </Show>
</div>
<div class="space-y-4">
@@ -593,6 +621,10 @@ export const UnifiedAgents: Component = () => {
if (insecureMode() && isBashScript) {
cmd += getInsecureFlag();
}
+ // Add --enable-commands flag if enabled (issue #903)
+ if (enableCommands() && isBashScript) {
+ cmd += getEnableCommandsFlag();
+ }
return cmd;
};
@@ -826,6 +858,7 @@ export const UnifiedAgents: Component = () => {
<th scope="col" class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">Type</th>
<th scope="col" class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">Status</th>
<th scope="col" class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">Version</th>
+ <th scope="col" class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">AI Commands</th>
<th scope="col" class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">Last Seen</th>
<th scope="col" class="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">Actions</th>
</tr>
@@ -833,7 +866,7 @@ export const UnifiedAgents: Component = () => {
<tbody class="divide-y divide-gray-200 bg-white dark:divide-gray-700 dark:bg-gray-900">
<For each={allHosts()} fallback={
<tr>
- <td colspan="6" class="px-4 py-8 text-center text-sm text-gray-500 dark:text-gray-400">
+ <td colspan="7" class="px-4 py-8 text-center text-sm text-gray-500 dark:text-gray-400">
No agents installed yet.
</td>
</tr>
@@ -876,6 +909,27 @@ export const UnifiedAgents: Component = () => {
</span>
</Show>
</td>
+ <td class="whitespace-nowrap px-4 py-3 text-sm">
+ <Show when={agent.types.includes('host')}
+ fallback={
+ <span class="text-gray-400 dark:text-gray-500">—</span>
+ }
+ >
+ <button
+ onClick={() => handleToggleCommands(agent.id, !agent.commandsEnabled)}
+ class={`relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 ${agent.commandsEnabled
+ ? 'bg-blue-600'
+ : 'bg-gray-200 dark:bg-gray-700'
+ }`}
+ title={agent.commandsEnabled ? 'AI command execution enabled' : 'AI command execution disabled'}
+ >
+ <span
+ class={`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${agent.commandsEnabled ? 'translate-x-4' : 'translate-x-0'
+ }`}
+ />
+ </button>
+ </Show>
+ </td>
<td class="whitespace-nowrap px-4 py-3 text-sm text-gray-500 dark:text-gray-400">
{agent.lastSeen ? formatRelativeTime(agent.lastSeen) : '—'}
</td>
diff --git a/internal/api/host_agents.go b/internal/api/host_agents.go
index 2fdad40f84..d5fedd3cf2 100644
--- a/internal/api/host_agents.go
+++ b/internal/api/host_agents.go
@@ -67,6 +67,9 @@ func (h *HostAgentHandlers) HandleReport(w http.ResponseWriter, r *http.Request)
go h.wsHub.BroadcastState(h.monitor.GetState().ToFrontend())
+ // Include any server-side config overrides in the response
+ serverConfig := h.monitor.GetHostAgentConfig(host.ID)
+
resp := map[string]any{
"success": true,
"hostId": host.ID,
@@ -76,6 +79,13 @@ func (h *HostAgentHandlers) HandleReport(w http.ResponseWriter, r *http.Request)
"osVersion": host.OSVersion,
}
+ // Only include config if there are actual overrides
+ if serverConfig.CommandsEnabled != nil {
+ resp["config"] = map[string]any{
+ "commandsEnabled": serverConfig.CommandsEnabled,
+ }
+ }
+
if err := utils.WriteJSONResponse(w, resp); err != nil {
log.Error().Err(err).Msg("Failed to serialize host agent response")
}
@@ -210,3 +220,81 @@ func (h *HostAgentHandlers) HandleDeleteHost(w http.ResponseWriter, r *http.Requ
log.Error().Err(err).Msg("Failed to serialize host removal response")
}
}
+
+// HandleConfig handles GET (fetch config) and PATCH (update config) for host agents.
+// GET /api/agents/host/{hostId}/config - Agent fetches its server-side config
+// PATCH /api/agents/host/{hostId}/config - UI updates host config (e.g., commandsEnabled)
+func (h *HostAgentHandlers) HandleConfig(w http.ResponseWriter, r *http.Request) {
+ // Extract host ID from URL path
+ // Expected format: /api/agents/host/{hostId}/config
+ trimmedPath := strings.TrimPrefix(r.URL.Path, "/api/agents/host/")
+ trimmedPath = strings.TrimSuffix(trimmedPath, "/config")
+ hostID := strings.TrimSpace(trimmedPath)
+ if hostID == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "missing_host_id", "Host ID is required", nil)
+ return
+ }
+
+ switch r.Method {
+ case http.MethodGet:
+ h.handleGetConfig(w, r, hostID)
+ case http.MethodPatch:
+ h.handlePatchConfig(w, r, hostID)
+ default:
+ writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only GET and PATCH are allowed", nil)
+ }
+}
+
+// handleGetConfig returns the server-side config for an agent to apply.
+func (h *HostAgentHandlers) handleGetConfig(w http.ResponseWriter, r *http.Request, hostID string) {
+ config := h.monitor.GetHostAgentConfig(hostID)
+
+ resp := map[string]any{
+ "success": true,
+ "hostId": hostID,
+ "config": config,
+ }
+
+ if err := utils.WriteJSONResponse(w, resp); err != nil {
+ log.Error().Err(err).Msg("Failed to serialize host config response")
+ }
+}
+
+// handlePatchConfig updates the server-side config for a host agent.
+func (h *HostAgentHandlers) handlePatchConfig(w http.ResponseWriter, r *http.Request, hostID string) {
+ r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
+ defer r.Body.Close()
+
+ var req struct {
+ CommandsEnabled *bool `json:"commandsEnabled"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Failed to decode request body", map[string]string{"error": err.Error()})
+ return
+ }
+
+ if err := h.monitor.UpdateHostAgentConfig(hostID, req.CommandsEnabled); err != nil {
+ writeErrorResponse(w, http.StatusInternalServerError, "update_failed", err.Error(), nil)
+ return
+ }
+
+ go h.wsHub.BroadcastState(h.monitor.GetState().ToFrontend())
+
+ log.Info().
+ Str("hostId", hostID).
+ Interface("commandsEnabled", req.CommandsEnabled).
+ Msg("Host agent config updated")
+
+ resp := map[string]any{
+ "success": true,
+ "hostId": hostID,
+ "config": map[string]any{
+ "commandsEnabled": req.CommandsEnabled,
+ },
+ }
+
+ if err := utils.WriteJSONResponse(w, resp); err != nil {
+ log.Error().Err(err).Msg("Failed to serialize host config update response")
+ }
+}
+
diff --git a/internal/api/router.go b/internal/api/router.go
index 30b2a721f2..7775028ceb 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -205,7 +205,34 @@ func (r *Router) setupRoutes() {
r.mux.HandleFunc("/api/agents/kubernetes/report", RequireAuth(r.config, RequireScope(config.ScopeKubernetesReport, r.kubernetesAgentHandlers.HandleReport)))
r.mux.HandleFunc("/api/agents/host/report", RequireAuth(r.config, RequireScope(config.ScopeHostReport, r.hostAgentHandlers.HandleReport)))
r.mux.HandleFunc("/api/agents/host/lookup", RequireAuth(r.config, RequireScope(config.ScopeHostReport, r.hostAgentHandlers.HandleLookup)))
- r.mux.HandleFunc("/api/agents/host/", RequireAdmin(r.config, RequireScope(config.ScopeHostManage, r.hostAgentHandlers.HandleDeleteHost)))
+ // Host agent management routes - config endpoint is accessible by agents (GET) and admins (PATCH)
+ r.mux.HandleFunc("/api/agents/host/", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {
+ // Route /api/agents/host/{id}/config to HandleConfig
+ if strings.HasSuffix(req.URL.Path, "/config") {
+ // GET is for agents to fetch config (host_report scope)
+ // PATCH is for UI to update config (host_manage scope, admin only)
+ if req.Method == http.MethodGet {
+ if !ensureScope(w, req, config.ScopeHostReport) {
+ return
+ }
+ } else if req.Method == http.MethodPatch {
+ if !ensureScope(w, req, config.ScopeHostManage) {
+ return
+ }
+ }
+ r.hostAgentHandlers.HandleConfig(w, req)
+ return
+ }
+ // Route DELETE /api/agents/host/{id} to HandleDeleteHost (host_manage scope)
+ if req.Method == http.MethodDelete {
+ if !ensureScope(w, req, config.ScopeHostManage) {
+ return
+ }
+ r.hostAgentHandlers.HandleDeleteHost(w, req)
+ return
+ }
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ }))
r.mux.HandleFunc("/api/temperature-proxy/register", r.requireSensorProxyEnabled(r.temperatureProxyHandlers.HandleRegister))
r.mux.HandleFunc("/api/temperature-proxy/authorized-nodes", r.requireSensorProxyEnabled(r.temperatureProxyHandlers.HandleAuthorizedNodes))
r.mux.HandleFunc("/api/temperature-proxy/unregister", r.requireSensorProxyEnabled(RequireAdmin(r.config, r.temperatureProxyHandlers.HandleUnregister)))
diff --git a/internal/config/host_metadata.go b/internal/config/host_metadata.go
index 01bc0c8299..278e1582f0 100644
--- a/internal/config/host_metadata.go
+++ b/internal/config/host_metadata.go
@@ -12,11 +12,12 @@ import (
// HostMetadata holds additional metadata for a host
type HostMetadata struct {
- ID string `json:"id"` // Host ID
- CustomURL string `json:"customUrl"` // Custom URL for the host
- Description string `json:"description"` // Optional description
- Tags []string `json:"tags"` // Optional tags for categorization
- Notes []string `json:"notes"` // User annotations for AI context
+ ID string `json:"id"` // Host ID
+ CustomURL string `json:"customUrl"` // Custom URL for the host
+ Description string `json:"description"` // Optional description
+ Tags []string `json:"tags"` // Optional tags for categorization
+ Notes []string `json:"notes"` // User annotations for AI context
+ CommandsEnabled *bool `json:"commandsEnabled"` // Remote override for AI command execution (nil = use agent default)
}
// HostMetadataStore manages host metadata
diff --git a/internal/hostagent/agent.go b/internal/hostagent/agent.go
index 1a2373fab4..8f63e95619 100644
--- a/internal/hostagent/agent.go
+++ b/internal/hostagent/agent.go
@@ -421,9 +421,52 @@ func (a *Agent) sendReport(ctx context.Context, report agentshost.Report) error
return fmt.Errorf("pulse responded with status %s", resp.Status)
}
+ // Parse response to check for server-side config overrides
+ var reportResp struct {
+ Success bool `json:"success"`
+ HostID string `json:"hostId"`
+ Config *struct {
+ CommandsEnabled *bool `json:"commandsEnabled"`
+ } `json:"config,omitempty"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&reportResp); err != nil {
+ // Non-fatal: just log and continue
+ a.logger.Debug().Err(err).Msg("Failed to parse report response, ignoring config")
+ return nil
+ }
+
+ // Apply server config overrides
+ if reportResp.Config != nil && reportResp.Config.CommandsEnabled != nil {
+ a.applyRemoteConfig(*reportResp.Config.CommandsEnabled)
+ }
+
return nil
}
+// applyRemoteConfig applies server-side configuration overrides.
+// Currently handles enabling/disabling the command execution feature dynamically.
+func (a *Agent) applyRemoteConfig(commandsEnabled bool) {
+ // Check if state would change
+ currentlyEnabled := a.commandClient != nil
+
+ if commandsEnabled && !currentlyEnabled {
+ // Server enabled commands, but we don't have a command client
+ // Start the command client
+ a.logger.Info().Msg("Server enabled command execution - starting command client")
+ a.commandClient = NewCommandClient(a.cfg, a.agentID, a.hostname, a.platform, a.agentVersion)
+ go func() {
+ if err := a.commandClient.Run(context.Background()); err != nil && !errors.Is(err, context.Canceled) {
+ a.logger.Error().Err(err).Msg("Command client stopped with error")
+ }
+ }()
+ } else if !commandsEnabled && currentlyEnabled {
+ // Server disabled commands, but we have a command client running
+ a.logger.Info().Msg("Server disabled command execution - stopping command client")
+ // Signal stop (the command client will exit on next iteration)
+ a.commandClient = nil
+ }
+}
+
func normalisePlatform(platform string) string {
platform = strings.ToLower(strings.TrimSpace(platform))
switch platform {
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index de403f8d5d..1af148635e 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -599,6 +599,7 @@ type Monitor struct {
tempCollector *TemperatureCollector // SSH-based temperature collector
guestMetadataStore *config.GuestMetadataStore
dockerMetadataStore *config.DockerMetadataStore
+ hostMetadataStore *config.HostMetadataStore
mu sync.RWMutex
startTime time.Time
rateTracker *RateTracker
@@ -1222,6 +1223,61 @@ func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
return host, nil
}
+// HostAgentConfig represents server-side configuration for a host agent.
+type HostAgentConfig struct {
+ CommandsEnabled *bool `json:"commandsEnabled,omitempty"` // nil = use agent default
+}
+
+// GetHostAgentConfig returns the server-side configuration for a host agent.
+// The agent can poll this to apply remote config overrides.
+func (m *Monitor) GetHostAgentConfig(hostID string) HostAgentConfig {
+ hostID = strings.TrimSpace(hostID)
+ if hostID == "" || m.hostMetadataStore == nil {
+ return HostAgentConfig{}
+ }
+
+ meta := m.hostMetadataStore.Get(hostID)
+ if meta == nil {
+ return HostAgentConfig{}
+ }
+
+ return HostAgentConfig{
+ CommandsEnabled: meta.CommandsEnabled,
+ }
+}
+
+// UpdateHostAgentConfig updates the server-side configuration for a host agent.
+// This allows the UI to remotely enable/disable features on agents.
+func (m *Monitor) UpdateHostAgentConfig(hostID string, commandsEnabled *bool) error {
+ hostID = strings.TrimSpace(hostID)
+ if hostID == "" {
+ return fmt.Errorf("host id is required")
+ }
+
+ if m.hostMetadataStore == nil {
+ return fmt.Errorf("host metadata store not initialized")
+ }
+
+ // Get existing metadata or create new
+ meta := m.hostMetadataStore.Get(hostID)
+ if meta == nil {
+ meta = &config.HostMetadata{ID: hostID}
+ }
+
+ meta.CommandsEnabled = commandsEnabled
+
+ if err := m.hostMetadataStore.Set(hostID, meta); err != nil {
+ return fmt.Errorf("failed to save host config: %w", err)
+ }
+
+ log.Info().
+ Str("hostId", hostID).
+ Interface("commandsEnabled", commandsEnabled).
+ Msg("Host agent config updated")
+
+ return nil
+}
+
// HideDockerHost marks a docker host as hidden without removing it from state.
// Hidden hosts will not be shown in the frontend but will continue to accept updates.
func (m *Monitor) HideDockerHost(hostID string) (models.DockerHost, error) {
@@ -3078,6 +3134,7 @@ func New(cfg *config.Config) (*Monitor, error) {
tempCollector: tempCollector,
guestMetadataStore: config.NewGuestMetadataStore(cfg.DataPath),
dockerMetadataStore: config.NewDockerMetadataStore(cfg.DataPath),
+ hostMetadataStore: config.NewHostMetadataStore(cfg.DataPath),
startTime: time.Now(),
rateTracker: NewRateTracker(),
metricsHistory: NewMetricsHistory(1000, 24*time.Hour), // Keep up to 1000 points or 24 hours