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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Remove OpenCode references
rcourtmanecc31730f641
diff --git a/frontend-modern/src/api/opencode.ts b/frontend-modern/src/api/aiChat.tssimilarity index 93%rename from frontend-modern/src/api/opencode.tsrename to frontend-modern/src/api/aiChat.tsindex bd54bff9b9..c9c6e2a75c 100644--- a/frontend-modern/src/api/opencode.ts+++ b/frontend-modern/src/api/aiChat.ts@@ -1,7 +1,7 @@import { apiFetchJSON, apiFetch } from '@/utils/apiClient';import { logger } from '@/utils/logger';-// OpenCode API - Simplified AI interface+// AI Chat API - Simplified AI interfaceexport interface ChatSession {id: string;@@ -37,7 +37,7 @@ export interface AIStatus {engine: string;}-// OpenCode Agent (build, code, etc.) with specific permissions and model+// AI Agent (build, code, etc.) with specific permissions and modelexport interface Agent {name: string;description?: string;@@ -65,7 +65,7 @@ export interface SessionDiff {summary?: string;}-export class OpenCodeAPI {+export class AIChatAPI {private static baseUrl = '/api/ai';// Get AI status@@ -119,7 +119,7 @@ export class OpenCodeAPI {}) as Promise<{ denied: boolean; message: string }>;}- // Answer a pending question from OpenCode+ // Answer a pending question from the AI chatstatic async answerQuestion(questionId: string, answers: Array<{ id: string; value: string }>): Promise<void> {await apiFetch(`${this.baseUrl}/question/${questionId}/answer`, {method: 'POST',@@ -128,7 +128,7 @@ export class OpenCodeAPI {}// ============================================- // OpenCode Extended Features+ // AI Chat Extended Features// ============================================// List available agents (build, code, etc.)@@ -177,7 +177,7 @@ export class OpenCodeAPI {onEvent: (event: StreamEvent) => void,signal?: AbortSignal): Promise<void> {- logger.debug('[OpenCode] Starting chat stream', { prompt: prompt.substring(0, 50) });+ logger.debug('[AI Chat] Starting chat stream', { prompt: prompt.substring(0, 50) });const response = await apiFetch(`${this.baseUrl}/chat`, {method: 'POST',@@ -211,7 +211,7 @@ export class OpenCodeAPI {try {for (; ;) {if (Date.now() - lastEventTime > STREAM_TIMEOUT_MS) {- logger.warn('[OpenCode] Stream timeout');+ logger.warn('[AI Chat] Stream timeout');break;}@@ -250,14 +250,14 @@ export class OpenCodeAPI {if (!jsonStr.trim()) continue;const event = JSON.parse(jsonStr) as StreamEvent;- logger.debug('[OpenCode] Event', { type: event.type });+ logger.debug('[AI Chat] Event', { type: event.type });onEvent(event);if (event.type === 'done' || event.type === 'error') {return;}} catch (e) {- logger.error('[OpenCode] Failed to parse event', { error: e, line });+ logger.error('[AI Chat] Failed to parse event', { error: e, line });}}}@@ -272,7 +272,7 @@ export class OpenCodeAPI {onEvent(event);}} catch {- logger.warn('[OpenCode] Could not parse remaining buffer');+ logger.warn('[AI Chat] Could not parse remaining buffer');}}diff --git a/frontend-modern/src/components/AI/Chat/ThinkingBlock.tsx b/frontend-modern/src/components/AI/Chat/ThinkingBlock.tsxindex 9a19a00065..aa4584f5d1 100644--- a/frontend-modern/src/components/AI/Chat/ThinkingBlock.tsx+++ b/frontend-modern/src/components/AI/Chat/ThinkingBlock.tsx@@ -9,7 +9,7 @@ interface ThinkingBlockProps {/*** ThinkingBlock - Displays AI's reasoning/thinking in a collapsed-by-default block.*- * Inspired by OpenCode's terminal TUI which shows thinking as a subtle,+ * Inspired by Pulse AI's terminal TUI which shows thinking as a subtle,* collapsible section that doesn't distract from the main response.*/export const ThinkingBlock: Component<ThinkingBlockProps> = (props) => {diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.tsindex 8865e7e70a..2cbae7dedb 100644--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts@@ -1,5 +1,5 @@import { createSignal, onCleanup } from 'solid-js';-import { OpenCodeAPI, type StreamEvent } from '@/api/opencode';+import { AIChatAPI, type StreamEvent } from '@/api/aiChat';import { notificationStore } from '@/stores/notifications';import { logger } from '@/utils/logger';import type {@@ -295,7 +295,7 @@ export function useChat(options: UseChatOptions = {}) {);};- // Send a message - allows sending mid-stream (aborts current response like OpenCode TUI)+ // Send a message - allows sending mid-stream (aborts current response like Pulse AI TUI)const sendMessage = async (prompt: string) => {if (!prompt.trim()) return;@@ -319,7 +319,7 @@ export function useChat(options: UseChatOptions = {}) {let currentSessionId = sessionId();if (!currentSessionId) {try {- const session = await OpenCodeAPI.createSession();+ const session = await AIChatAPI.createSession();currentSessionId = session.id;setSessionId(currentSessionId);logger.debug('[useChat] Created new session', { sessionId: currentSessionId });@@ -357,7 +357,7 @@ export function useChat(options: UseChatOptions = {}) {setMessages((prev) => [...prev, streamingMessage]);try {- await OpenCodeAPI.chat(+ await AIChatAPI.chat(prompt,currentSessionId,model() || undefined,@@ -397,7 +397,7 @@ export function useChat(options: UseChatOptions = {}) {// Load session messagesconst loadSession = async (id: string) => {try {- const msgs = await OpenCodeAPI.getMessages(id);+ const msgs = await AIChatAPI.getMessages(id);setMessages(msgs.map(m => ({id: m.id,role: m.role,@@ -415,7 +415,7 @@ export function useChat(options: UseChatOptions = {}) {// Create new sessionconst newSession = async () => {try {- const session = await OpenCodeAPI.createSession();+ const session = await AIChatAPI.createSession();setSessionId(session.id);setMessages([]);return session;@@ -494,8 +494,8 @@ export function useChat(options: UseChatOptions = {}) {updateQuestion(messageId, questionId, { isAnswering: true });try {- // Send answer to OpenCode via API- await OpenCodeAPI.answerQuestion(questionId, answers);+ // Send answer to Pulse AI via API+ await AIChatAPI.answerQuestion(questionId, answers);// Remove the question card - it's been handledupdateQuestion(messageId, questionId, { removed: true });@@ -518,7 +518,7 @@ export function useChat(options: UseChatOptions = {}) {prev.map((m) => (m.id === messageId ? { ...m, isStreaming: true } : m)));- OpenCodeAPI.chat(+ AIChatAPI.chat('', // Empty prompt - just resume listening for completioncurrentSessionId,model() || undefined,diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsxindex 1c59ffc94d..f58c817c2c 100644--- a/frontend-modern/src/components/AI/Chat/index.tsx+++ b/frontend-modern/src/components/AI/Chat/index.tsx@@ -1,6 +1,6 @@import { Component, Show, createSignal, onMount, onCleanup, For, createMemo, createEffect } from 'solid-js';import { AIAPI } from '@/api/ai';-import { OpenCodeAPI, type ChatSession } from '@/api/opencode';+import { AIChatAPI, type ChatSession } from '@/api/aiChat';import { notificationStore } from '@/stores/notifications';import { aiChatStore } from '@/stores/aiChat';import { logger } from '@/utils/logger';@@ -192,12 +192,12 @@ export const AIChat: Component<AIChatProps> = (props) => {// Load sessions on mountonMount(async () => {try {- const status = await OpenCodeAPI.getStatus();+ const status = await AIChatAPI.getStatus();if (!status.running) {notificationStore.warning('AI is not running');return;}- const sessionList = await OpenCodeAPI.listSessions();+ const sessionList = await AIChatAPI.listSessions();setSessions(sessionList);await loadSettings();await loadModels();@@ -253,7 +253,7 @@ export const AIChat: Component<AIChatProps> = (props) => {e.stopPropagation();if (!confirm('Delete this conversation?')) return;try {- await OpenCodeAPI.deleteSession(sessionId);+ await AIChatAPI.deleteSession(sessionId);setSessions(prev => prev.filter(s => s.id !== sessionId));updateStoredModel(sessionId, '');if (chat.sessionId() === sessionId) {@@ -278,7 +278,7 @@ export const AIChat: Component<AIChatProps> = (props) => {// Call the approve endpoint - this marks it as approved in the backend// The agentic loop will detect this and execute the command// Execution results will come via tool_end event in the stream- await OpenCodeAPI.approveCommand(approval.approvalId);+ await AIChatAPI.approveCommand(approval.approvalId);// Remove from pending approvals - the tool_end event will show the resultchat.updateApproval(messageId, approval.toolId, { removed: true });@@ -314,7 +314,7 @@ export const AIChat: Component<AIChatProps> = (props) => {}try {- await OpenCodeAPI.denyCommand(approval.approvalId, 'User skipped');+ await AIChatAPI.denyCommand(approval.approvalId, 'User skipped');chat.updateApproval(messageId, toolId, { removed: true });} catch (error) {logger.error('[AIChat] Skip/deny failed:', error);@@ -351,7 +351,7 @@ export const AIChat: Component<AIChatProps> = (props) => {<div><h2 class="text-sm font-semibold text-slate-900 dark:text-slate-100">AI Assistant</h2><p class="text-[11px] text-slate-500 dark:text-slate-400">- Powered by OpenCode+ Powered by Pulse</p></div></div>diff --git a/frontend-modern/src/components/AI/Chat/types.ts b/frontend-modern/src/components/AI/Chat/types.tsindex 3a56e9e5e7..1666df0ef0 100644--- a/frontend-modern/src/components/AI/Chat/types.ts+++ b/frontend-modern/src/components/AI/Chat/types.ts@@ -22,7 +22,7 @@ export interface PendingApproval {approvalId?: string; // ID of the approval record for API calls}-// Question from OpenCode+// Question from Pulse AIexport interface QuestionOption {label: string;value: string;diff --git a/frontend-modern/src/components/Settings/AISettings.tsx b/frontend-modern/src/components/Settings/AISettings.tsxindex 8ad7595aa3..889c9addbc 100644--- a/frontend-modern/src/components/Settings/AISettings.tsx+++ b/frontend-modern/src/components/Settings/AISettings.tsx@@ -8,7 +8,7 @@ import { formField, labelClass, controlClass } from '@/components/shared/Form';import { notificationStore } from '@/stores/notifications';import { logger } from '@/utils/logger';import { AIAPI } from '@/api/ai';-import { OpenCodeAPI, type ChatSession, type FileChange } from '@/api/opencode';+import { AIChatAPI, type ChatSession, type FileChange } from '@/api/aiChat';import { hasFeature, loadLicenseStatus } from '@/stores/license';import type { AISettings as AISettingsType, AIProvider, AuthMethod } from '@/types/ai';@@ -249,7 +249,7 @@ export const AISettings: Component = () => {setChatSessionsLoading(true);setChatSessionsError('');try {- const sessions = await OpenCodeAPI.listSessions();+ const sessions = await AIChatAPI.listSessions();setChatSessions(sessions);const current = selectedSessionId();if (!current || !sessions.some((session) => session.id === current)) {@@ -315,7 +315,7 @@ export const AISettings: Component = () => {setSessionActionLoading('summarize');try {- await OpenCodeAPI.summarizeSession(sessionId);+ await AIChatAPI.summarizeSession(sessionId);notificationStore.success('Session summarized.');} catch (error) {logger.error('[AISettings] Failed to summarize session:', error);@@ -335,7 +335,7 @@ export const AISettings: Component = () => {setSessionActionLoading('diff');try {- const diff = await OpenCodeAPI.getSessionDiff(sessionId);+ const diff = await AIChatAPI.getSessionDiff(sessionId);const files = diff.files || [];if (files.length === 0) {setDiffFiles([]);@@ -368,7 +368,7 @@ export const AISettings: Component = () => {setSessionActionLoading('revert');try {- await OpenCodeAPI.revertSession(sessionId);+ await AIChatAPI.revertSession(sessionId);notificationStore.success('Session changes reverted.');} catch (error) {logger.error('[AISettings] Failed to revert session:', error);diff --git a/frontend-modern/src/components/Settings/DiagnosticsPanel.tsx b/frontend-modern/src/components/Settings/DiagnosticsPanel.tsxindex 5fe4a7fd46..d2fd0df6f4 100644--- a/frontend-modern/src/components/Settings/DiagnosticsPanel.tsx+++ b/frontend-modern/src/components/Settings/DiagnosticsPanel.tsx@@ -112,7 +112,7 @@ interface AlertsDiagnostic {notes?: string[];}-interface OpenCodeDiagnostic {+interface AIChatDiagnostic {enabled: boolean;running: boolean;healthy: boolean;@@ -135,7 +135,7 @@ interface DiagnosticsData {apiTokens?: APITokenDiagnostic | null;dockerAgents?: DockerAgentDiagnostic | null;alerts?: AlertsDiagnostic | null;- openCode?: OpenCodeDiagnostic | null;+ aiChat?: AIChatDiagnostic | null;discovery?: DiscoveryDiagnostic | null;errors: string[];}@@ -665,8 +665,8 @@ export const DiagnosticsPanel: Component = () => {</Card></Show>- {/* OpenCode AI Status */}- <Show when={diagnosticsData()?.openCode}>+ {/* AI Chat Status */}+ <Show when={diagnosticsData()?.aiChat}><Card padding="md"><div class="flex items-center gap-3 mb-4 pb-3 border-b border-gray-200 dark:border-gray-700"><div class="p-2 rounded-lg bg-indigo-100 dark:bg-indigo-900/30">@@ -674,35 +674,35 @@ export const DiagnosticsPanel: Component = () => {</div><div><h4 class="text-sm font-semibold text-gray-900 dark:text-gray-100">AI Assistant</h4>- <p class="text-xs text-gray-500 dark:text-gray-400">OpenCode Sidecar</p>+ <p class="text-xs text-gray-500 dark:text-gray-400">Pulse AI Service</p></div><div class="ml-auto"><StatusBadge- status={diagnosticsData()?.openCode?.running ? 'online' : (diagnosticsData()?.openCode?.enabled ? 'offline' : 'unknown')}- label={diagnosticsData()?.openCode?.running ? 'Running' : (diagnosticsData()?.openCode?.enabled ? 'Stopped' : 'Disabled')}+ status={diagnosticsData()?.aiChat?.running ? 'online' : (diagnosticsData()?.aiChat?.enabled ? 'offline' : 'unknown')}+ label={diagnosticsData()?.aiChat?.running ? 'Running' : (diagnosticsData()?.aiChat?.enabled ? 'Stopped' : 'Disabled')}/></div></div><div class="space-y-2 text-xs">- <MetricRow label="Model" value={diagnosticsData()?.openCode?.model} />- <MetricRow label="Port" value={diagnosticsData()?.openCode?.port} mono />- <MetricRow label="Status" value={diagnosticsData()?.openCode?.healthy ? 'Healthy' : 'Unhealthy'} />+ <MetricRow label="Model" value={diagnosticsData()?.aiChat?.model} />+ <MetricRow label="Port" value={diagnosticsData()?.aiChat?.port} mono />+ <MetricRow label="Status" value={diagnosticsData()?.aiChat?.healthy ? 'Healthy' : 'Unhealthy'} /></div><div class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700/50 flex items-center justify-between text-xs"><span class="text-gray-500 dark:text-gray-400">MCP Connection</span><div class="flex items-center gap-1.5">- {diagnosticsData()?.openCode?.mcpConnected ?+ {diagnosticsData()?.aiChat?.mcpConnected ?<CheckCircle class="w-3.5 h-3.5 text-green-500" /> :<XCircle class="w-3.5 h-3.5 text-red-500" />}- <span class={diagnosticsData()?.openCode?.mcpConnected ? 'text-green-700 dark:text-green-300' : 'text-gray-500'}>- {diagnosticsData()?.openCode?.mcpConnected ? 'Connected' : 'Disconnected'}+ <span class={diagnosticsData()?.aiChat?.mcpConnected ? 'text-green-700 dark:text-green-300' : 'text-gray-500'}>+ {diagnosticsData()?.aiChat?.mcpConnected ? 'Connected' : 'Disconnected'}</span></div></div>- <Show when={(diagnosticsData()?.openCode?.notes?.length || 0) > 0}>+ <Show when={(diagnosticsData()?.aiChat?.notes?.length || 0) > 0}><ul class="mt-3 bg-amber-50 dark:bg-amber-900/10 p-2 rounded text-xs text-amber-700 dark:text-amber-400 list-disc pl-4">- <For each={diagnosticsData()?.openCode?.notes || []}>+ <For each={diagnosticsData()?.aiChat?.notes || []}>{(note) => <li>{note}</li>}</For></ul>diff --git a/frontend-modern/src/stores/aiChat.ts b/frontend-modern/src/stores/aiChat.tsindex 2b5a501a95..2199b79950 100644--- a/frontend-modern/src/stores/aiChat.ts+++ b/frontend-modern/src/stores/aiChat.ts@@ -1,6 +1,6 @@import { createSignal } from 'solid-js';import { logger } from '@/utils/logger';-// NOTE: AIAPI import removed - session management is handled by OpenCode's embedded UI+// NOTE: AIAPI import removed - session management is handled by Pulse AI's embedded UIimport type { AIChatSessionSummary } from '@/types/ai';interface AIChatContext {@@ -111,9 +111,9 @@ const SAVE_DEBOUNCE_MS = 2000; // Save 2 seconds after last changelet aiInputRef: HTMLTextAreaElement | null = null;// Sync current session to server (debounced)-// NOTE: Session sync is disabled - OpenCode handles session management internally+// NOTE: Session sync is disabled - Pulse AI handles session management internallyconst syncToServer = async () => {- // Disabled: OpenCode manages sessions through its embedded UI+ // Disabled: Pulse AI manages sessions through its embedded UIreturn;};@@ -126,9 +126,9 @@ const debouncedSync = () => {};// Load session from server-// NOTE: Session sync is disabled - OpenCode handles session management internally+// NOTE: Session sync is disabled - Pulse AI handles session management internallyconst loadSessionFromServer = async (_sessionId: string): Promise<boolean> => {- // Disabled: OpenCode manages sessions through its embedded UI+ // Disabled: Pulse AI manages sessions through its embedded UIreturn false;};@@ -229,9 +229,9 @@ export const aiChatStore = {},// Refresh session list from server- // NOTE: Session sync is disabled - OpenCode handles session management internally+ // NOTE: Session sync is disabled - Pulse AI handles session management internallyasync refreshSessions() {- // Disabled: OpenCode manages sessions through its embedded UI+ // Disabled: Pulse AI manages sessions through its embedded UIreturn;},@@ -284,9 +284,9 @@ export const aiChatStore = {},// Delete a session- // NOTE: Session management is handled by OpenCode's embedded UI+ // NOTE: Session management is handled by Pulse AI's embedded UIasync deleteSession(_sessionId: string) {- // Disabled: OpenCode manages sessions through its embedded UI+ // Disabled: Pulse AI manages sessions through its embedded UIreturn;},diff --git a/internal/ai/chat/patrol_test.go b/internal/ai/chat/patrol_test.goindex 6533bcf379..8894d34f0c 100644--- a/internal/ai/chat/patrol_test.go+++ b/internal/ai/chat/patrol_test.go@@ -145,12 +145,12 @@ func TestPatrolService_RunPatrol(t *testing.T) {// Create Service manuallycfg := Config{AIConfig: &config.AIConfig{- Enabled: true,- OpenAIAPIKey: "sk-test",- ChatModel: "openai:gpt-4",- OpenCodeDataDir: t.TempDir(),+ Enabled: true,+ OpenAIAPIKey: "sk-test",+ ChatModel: "openai:gpt-4",},StateProvider: &mockStateProvider{},+ DataDir: t.TempDir(),}// Use NewService to initialize internal structures (like executor)diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex c1561dbae1..3392446045 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -63,6 +63,7 @@ type Service struct {mu sync.RWMutexcfg *config.AIConfig+ dataDir stringstateProvider StateProvideragentServer AgentServerexecutor *tools.PulseToolExecutor@@ -104,6 +105,7 @@ func NewService(cfg Config) *Service {return &Service{cfg: cfg.AIConfig,+ dataDir: cfg.DataDir,stateProvider: cfg.StateProvider,agentServer: cfg.AgentServer,executor: executor,@@ -155,9 +157,10 @@ func (s *Service) Start(ctx context.Context) error {s.applyChatContextSettings()// Create session store- dataDir := s.cfg.OpenCodeDataDir+ dataDir := s.dataDirif dataDir == "" {dataDir = "/tmp/pulse-ai"+ s.dataDir = dataDir}store, err := NewSessionStore(dataDir)diff --git a/internal/ai/chat/service_test.go b/internal/ai/chat/service_test.goindex c2b2e0c1c1..6d07e0c6bb 100644--- a/internal/ai/chat/service_test.go+++ b/internal/ai/chat/service_test.go@@ -60,12 +60,12 @@ func TestService_StartStop(t *testing.T) {tmpDir := t.TempDir()cfg := Config{AIConfig: &config.AIConfig{- Enabled: true,- OpenAIAPIKey: "sk-test",- ChatModel: "openai:gpt-4",- OpenCodeDataDir: tmpDir,+ Enabled: true,+ OpenAIAPIKey: "sk-test",+ ChatModel: "openai:gpt-4",},StateProvider: &mockStateProvider{},+ DataDir: tmpDir,}service := NewService(cfg)@@ -92,12 +92,12 @@ func TestService_Restart(t *testing.T) {tmpDir := t.TempDir()cfg := Config{AIConfig: &config.AIConfig{- Enabled: true,- OpenAIAPIKey: "sk-test",- ChatModel: "openai:gpt-4",- OpenCodeDataDir: tmpDir,+ Enabled: true,+ OpenAIAPIKey: "sk-test",+ ChatModel: "openai:gpt-4",},StateProvider: &mockStateProvider{},+ DataDir: tmpDir,}service := NewService(cfg)@@ -108,7 +108,6 @@ func TestService_Restart(t *testing.T) {Enabled: true,AnthropicAPIKey: "chk-test",ChatModel: "anthropic:claude-3",- OpenCodeDataDir: tmpDir,}err := service.Restart(ctx, newCfg)@@ -224,12 +223,12 @@ func TestService_SessionWrappers(t *testing.T) {tmpDir := t.TempDir()cfg := Config{AIConfig: &config.AIConfig{- Enabled: true,- OpenAIAPIKey: "test-key",- ChatModel: "openai:gpt-4",- OpenCodeDataDir: tmpDir,+ Enabled: true,+ OpenAIAPIKey: "test-key",+ ChatModel: "openai:gpt-4",},StateProvider: &mockStateProvider{},+ DataDir: tmpDir,}service := NewService(cfg)diff --git a/internal/ai/patrol.go b/internal/ai/patrol.goindex b1e062acbf..cf03f228d6 100644--- a/internal/ai/patrol.go+++ b/internal/ai/patrol.go@@ -234,8 +234,8 @@ type PatrolRunRecord struct {// MaxPatrolRunHistory is the maximum number of patrol runs to keep in historyconst MaxPatrolRunHistory = 100-// OpenCodePatrolRunner interface allows delegating patrol to OpenCode-type OpenCodePatrolRunner interface {+// ChatPatrolRunner interface allows delegating patrol to the AI chat service+type ChatPatrolRunner interface {RunPatrol(ctx context.Context) errorIsRunning() bool}@@ -261,9 +261,9 @@ type PatrolService struct {// Unified intelligence facade - aggregates all subsystems for unified viewintelligence *Intelligence- // OpenCode integration - when set and UseOpenCode is true, delegate patrol to OpenCode- opencodePatrol OpenCodePatrolRunner- useOpenCode bool // Whether to use OpenCode for patrol+ // AI chat integration - when set and enabled, delegate patrol to the AI chat service+ chatPatrol ChatPatrolRunner+ useChatPatrol bool // Whether to use AI chat for patrol// Cached thresholds (recalculated when thresholdProvider changes)thresholds PatrolThresholds@@ -325,27 +325,14 @@ func (p *PatrolService) GetIncidentStore() *memory.IncidentStore {return p.incidentStore}-// SetOpenCodePatrol sets the OpenCode patrol runner for delegation-// When set and useOpenCode is true, patrol will be handled by OpenCode-func (p *PatrolService) SetOpenCodePatrol(runner OpenCodePatrolRunner, enabled bool) {+// SetChatPatrol sets the chat-based patrol runner for delegation.+// When enabled, patrol will be handled by the AI chat service.+func (p *PatrolService) SetChatPatrol(runner ChatPatrolRunner, enabled bool) {p.mu.Lock()defer p.mu.Unlock()- p.opencodePatrol = runner- p.useOpenCode = enabled- log.Info().Bool("enabled", enabled).Msg("OpenCode patrol integration configured")-}--// SetChatPatrol sets the chat-based patrol runner for delegation-// This is functionally equivalent to SetOpenCodePatrol-func (p *PatrolService) SetChatPatrol(runner OpenCodePatrolRunner, enabled bool) {- p.SetOpenCodePatrol(runner, enabled)-}--// UseOpenCode returns whether OpenCode is configured for patrol-func (p *PatrolService) UseOpenCode() bool {- p.mu.RLock()- defer p.mu.RUnlock()- return p.useOpenCode && p.opencodePatrol != nil+ p.chatPatrol = runner+ p.useChatPatrol = enabled+ log.Info().Bool("enabled", enabled).Msg("AI chat patrol integration configured")}// SetConfig updates the patrol configuration@@ -820,19 +807,19 @@ func (p *PatrolService) patrolLoop(ctx context.Context) {func (p *PatrolService) runPatrol(ctx context.Context) {p.mu.RLock()cfg := p.config- opencodePatrol := p.opencodePatrol- useOpenCode := p.useOpenCode+ chatPatrol := p.chatPatrol+ useChatPatrol := p.useChatPatrolp.mu.RUnlock()if !cfg.Enabled {return}- // Delegate to OpenCode patrol if configured- if useOpenCode && opencodePatrol != nil {- log.Info().Msg("AI Patrol: Delegating to OpenCode patrol")- if err := opencodePatrol.RunPatrol(ctx); err != nil {- log.Error().Err(err).Msg("AI Patrol: OpenCode patrol failed")+ // Delegate to AI chat patrol if configured+ if useChatPatrol && chatPatrol != nil {+ log.Info().Msg("AI Patrol: Delegating to AI chat patrol")+ if err := chatPatrol.RunPatrol(ctx); err != nil {+ log.Error().Err(err).Msg("AI Patrol: AI chat patrol failed")}return}diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.goindex 8a43620794..1e344ddd8f 100644--- a/internal/api/ai_handler.go+++ b/internal/api/ai_handler.go@@ -98,10 +98,7 @@ func (h *AIHandler) Start(ctx context.Context, stateProvider AIStateProvider) er}// Determine data directory- dataDir := aiCfg.OpenCodeDataDir- if dataDir == "" {- dataDir = "/tmp/pulse-ai"- }+ dataDir := "/tmp/pulse-ai"log.Info().Bool("enabled", aiCfg.Enabled).Str("model", aiCfg.Model).Msg("Starting AI chat service")h.service = newChatService(chat.Config{diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.goindex 09c2035da7..4be57f06e6 100644--- a/internal/api/ai_handlers.go+++ b/internal/api/ai_handlers.go@@ -35,7 +35,7 @@ type AISettingsHandler struct {persistence *config.ConfigPersistenceaiService *ai.ServiceagentServer *agentexec.Server- onModelChange func() // Called when model or other OpenCode-affecting settings change+ onModelChange func() // Called when model or other AI chat-affecting settings changeonControlSettingsChange func() // Called when control level or protected guests change}@@ -164,13 +164,13 @@ func (h *AISettingsHandler) SetLicenseChecker(checker ai.LicenseChecker) {}// SetOnModelChange sets a callback to be invoked when model settings change-// Used by Router to trigger OpenCode sidecar restart+// Used by Router to trigger AI chat service restartfunc (h *AISettingsHandler) SetOnModelChange(callback func()) {h.onModelChange = callback}// SetOnControlSettingsChange sets a callback to be invoked when control settings change-// Used by Router to update MCP tool visibility without restarting OpenCode+// Used by Router to update MCP tool visibility without restarting AI chatfunc (h *AISettingsHandler) SetOnControlSettingsChange(callback func()) {h.onControlSettingsChange = callback}@@ -663,14 +663,14 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *httanalyzer.SetEnabled(settings.AlertTriggeredAnalysis)}- // Trigger OpenCode sidecar restart if model changed- // This ensures the new model is picked up by the sidecar+ // Trigger AI chat service restart if model changed+ // This ensures the new model is picked up by the serviceif h.onModelChange != nil && (req.Model != nil || req.ChatModel != nil) {h.onModelChange()}// Update MCP control settings if control level or protected guests changed- // This updates tool visibility without restarting OpenCode+ // This updates tool visibility without restarting AI chat// Note: req.AutonomousMode also maps to control_level for backwards compatibilityif h.onControlSettingsChange != nil && (req.ControlLevel != nil || req.ProtectedGuests != nil || req.AutonomousMode != nil) {h.onControlSettingsChange()diff --git a/internal/api/diagnostics.go b/internal/api/diagnostics.goindex b1cc9777fc..f922137f60 100644--- a/internal/api/diagnostics.go+++ b/internal/api/diagnostics.go@@ -43,7 +43,7 @@ type DiagnosticsInfo struct {APITokens *APITokenDiagnostic `json:"apiTokens,omitempty"`DockerAgents *DockerAgentDiagnostic `json:"dockerAgents,omitempty"`Alerts *AlertsDiagnostic `json:"alerts,omitempty"`- OpenCode *OpenCodeDiagnostic `json:"openCode,omitempty"`+ AIChat *AIChatDiagnostic `json:"aiChat,omitempty"`Errors []string `json:"errors"`// NodeSnapshots captures the raw memory payload and derived usage Pulse last observed per node.NodeSnapshots []monitoring.NodeMemorySnapshot `json:"nodeSnapshots,omitempty"`@@ -356,8 +356,8 @@ type AlertsDiagnostic struct {Notes []string `json:"notes,omitempty"`}-// OpenCodeDiagnostic reports on the OpenCode AI sidecar status.-type OpenCodeDiagnostic struct {+// AIChatDiagnostic reports on the AI chat service status.+type AIChatDiagnostic struct {Enabled bool `json:"enabled"`Running bool `json:"running"`Healthy bool `json:"healthy"`@@ -569,7 +569,7 @@ func (r *Router) computeDiagnostics(ctx context.Context) DiagnosticsInfo {diag.DockerAgents = buildDockerAgentDiagnostic(r.monitor, diag.Version)diag.Alerts = buildAlertsDiagnostic(r.monitor)- diag.OpenCode = buildOpenCodeDiagnostic(r.config, r.aiHandler)+ diag.AIChat = buildAIChatDiagnostic(r.config, r.aiHandler)diag.Discovery = buildDiscoveryDiagnostic(r.config, r.monitor)@@ -1876,12 +1876,12 @@ func interfaceToStringSlice(value interface{}) []string {}}-func buildOpenCodeDiagnostic(cfg *config.Config, aiHandler *AIHandler) *OpenCodeDiagnostic {+func buildAIChatDiagnostic(cfg *config.Config, aiHandler *AIHandler) *AIChatDiagnostic {if cfg == nil {return nil}- diag := &OpenCodeDiagnostic{+ diag := &AIChatDiagnostic{Enabled: false,Notes: []string{},}@@ -1891,13 +1891,8 @@ func buildOpenCodeDiagnostic(cfg *config.Config, aiHandler *AIHandler) *OpenCodeif aiHandler != nil {aiCfg := aiHandler.GetAIConfig()if aiCfg != nil {- diag.Enabled = aiCfg.UseOpenCode+ diag.Enabled = aiCfg.Enableddiag.Model = aiCfg.GetChatModel()-- // Pulse legacy config check- if !diag.Enabled && aiCfg.Enabled {- diag.Notes = append(diag.Notes, "AI is enabled but UseOpenCode is false - using legacy implementation")- }}svc := aiHandler.GetService()@@ -1921,10 +1916,10 @@ func buildOpenCodeDiagnostic(cfg *config.Config, aiHandler *AIHandler) *OpenCodediag.MCPConnected = diag.Running // Assume connected if running for nowif !diag.Running && diag.Enabled {- diag.Notes = append(diag.Notes, "OpenCode service is enabled but not running")+ diag.Notes = append(diag.Notes, "AI chat service is enabled but not running")}} else if diag.Enabled {- diag.Notes = append(diag.Notes, "OpenCode service is nil")+ diag.Notes = append(diag.Notes, "AI chat service is nil")}} else {diag.Notes = append(diag.Notes, "AI Handler not initialized")diff --git a/internal/api/router.go b/internal/api/router.goindex 54885a6c64..1710297d94 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -59,7 +59,7 @@ type Router struct {temperatureProxyHandlers *TemperatureProxyHandlerssystemSettingsHandler *SystemSettingsHandleraiSettingsHandler *AISettingsHandler- aiHandler *AIHandler // OpenCode-based AI handler+ aiHandler *AIHandler // AI chat handlerresourceHandlers *ResourceHandlersreportingHandlers *ReportingHandlersconfigProfileHandler *ConfigProfileHandler@@ -1246,13 +1246,13 @@ func (r *Router) setupRoutes() {)r.aiSettingsHandler.SetMetadataProvider(metadataProvider)- // OpenCode-based AI handler (when UseOpenCode is enabled)+ // AI chat handlerr.aiHandler = NewAIHandler(r.config, r.persistence, r.agentExecServer)// Wire license checker for Pro feature gating (AI Patrol, Alert Analysis, Auto-Fix)r.aiSettingsHandler.SetLicenseChecker(r.licenseHandlers.Service())- // Wire model change callback to restart OpenCode sidecar when model is changed+ // Wire model change callback to restart AI chat service when model is changedr.aiSettingsHandler.SetOnModelChange(func() {- r.RestartOpenCodeAI(context.Background())+ r.RestartAIChat(context.Background())})// Wire control settings change callback to update MCP tool visibilityr.aiSettingsHandler.SetOnControlSettingsChange(func() {@@ -1396,7 +1396,7 @@ func (r *Router) setupRoutes() {}}))- // OpenCode AI endpoints - new AI backend powered by OpenCode+ // AI chat endpointsr.mux.HandleFunc("/api/ai/status", RequireAuth(r.config, r.aiHandler.HandleStatus))r.mux.HandleFunc("/api/ai/chat", RequireAuth(r.config, r.aiHandler.HandleChat))r.mux.HandleFunc("/api/ai/sessions", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {@@ -1409,13 +1409,13 @@ func (r *Router) setupRoutes() {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}}))- r.mux.HandleFunc("/api/ai/sessions/", RequireAuth(r.config, r.routeOpenCodeSessions))+ r.mux.HandleFunc("/api/ai/sessions/", RequireAuth(r.config, r.routeAISessions))// AI approval endpoints - for command approval workflowr.mux.HandleFunc("/api/ai/approvals", RequireAuth(r.config, r.aiSettingsHandler.HandleListApprovals))r.mux.HandleFunc("/api/ai/approvals/", RequireAuth(r.config, r.routeApprovals))- // AI question endpoints - for answering OpenCode questions+ // AI question endpointsr.mux.HandleFunc("/api/ai/question/", RequireAuth(r.config, r.routeQuestions))// Agent WebSocket for AI command execution@@ -1456,8 +1456,8 @@ func (r *Router) setupRoutes() {}-// routeOpenCodeSessions routes session-specific OpenCode AI requests-func (r *Router) routeOpenCodeSessions(w http.ResponseWriter, req *http.Request) {+// routeAISessions routes session-specific AI chat requests+func (r *Router) routeAISessions(w http.ResponseWriter, req *http.Request) {// Extract session ID from path: /api/ai/sessions/{id}[/messages|/abort|/summarize|/diff|/fork|/revert|/unrevert]path := strings.TrimPrefix(req.URL.Path, "/api/ai/sessions/")parts := strings.SplitN(path, "/", 2)@@ -1953,24 +1953,24 @@ func (r *Router) StopPatrol() {}}-// StartOpenCodeAI starts the OpenCode-based AI service-// This is the new AI backend that uses OpenCode for better tool calling and multi-model support-func (r *Router) StartOpenCodeAI(ctx context.Context) {+// StartAIChat starts the AI chat service+// This is the new AI backend that supports tool calling and multi-model support+func (r *Router) StartAIChat(ctx context.Context) {if r.aiHandler == nil {return}if r.monitor == nil {- log.Warn().Msg("Cannot start OpenCode AI: monitor not available")+ log.Warn().Msg("Cannot start AI chat: monitor not available")return}if err := r.aiHandler.Start(ctx, r.monitor); err != nil {- log.Error().Err(err).Msg("Failed to start OpenCode AI service")+ log.Error().Err(err).Msg("Failed to start AI chat service")return}// Wire up MCP tool providers so AI can access real data- r.wireOpenCodeProviders()+ r.wireAIChatProviders()// Wire up AI patrol if AI is runningaiCfg := r.aiHandler.GetAIConfig()@@ -1995,8 +1995,8 @@ func (r *Router) StartOpenCodeAI(ctx context.Context) {}}-// wireOpenCodeProviders wires up all MCP tool providers for OpenCode-func (r *Router) wireOpenCodeProviders() {+// wireAIChatProviders wires up all MCP tool providers for AI chat+func (r *Router) wireAIChatProviders() {if r.aiHandler == nil || !r.aiHandler.IsRunning() {return}@@ -2012,7 +2012,7 @@ func (r *Router) wireOpenCodeProviders() {alertAdapter := tools.NewAlertManagerMCPAdapter(alertManager)if alertAdapter != nil {service.SetAlertProvider(alertAdapter)- log.Debug().Msg("OpenCode: Alert provider wired")+ log.Debug().Msg("AI chat: Alert provider wired")}}}@@ -2024,7 +2024,7 @@ func (r *Router) wireOpenCodeProviders() {findingsAdapter := ai.NewFindingsMCPAdapter(findingsStore)if findingsAdapter != nil {service.SetFindingsProvider(findingsAdapter)- log.Debug().Msg("OpenCode: Findings provider wired")+ log.Debug().Msg("AI chat: Findings provider wired")}}}@@ -2033,7 +2033,7 @@ func (r *Router) wireOpenCodeProviders() {if r.persistence != nil {manager := NewMCPAgentProfileManager(r.persistence, r.licenseHandlers.Service())service.SetAgentProfileManager(manager)- log.Debug().Msg("OpenCode: Agent profile manager wired")+ log.Debug().Msg("AI chat: Agent profile manager wired")}// Wire storage provider@@ -2041,7 +2041,7 @@ func (r *Router) wireOpenCodeProviders() {storageAdapter := tools.NewStorageMCPAdapter(r.monitor)if storageAdapter != nil {service.SetStorageProvider(storageAdapter)- log.Debug().Msg("OpenCode: Storage provider wired")+ log.Debug().Msg("AI chat: Storage provider wired")}}@@ -2050,7 +2050,7 @@ func (r *Router) wireOpenCodeProviders() {backupAdapter := tools.NewBackupMCPAdapter(r.monitor)if backupAdapter != nil {service.SetBackupProvider(backupAdapter)- log.Debug().Msg("OpenCode: Backup provider wired")+ log.Debug().Msg("AI chat: Backup provider wired")}}@@ -2059,7 +2059,7 @@ func (r *Router) wireOpenCodeProviders() {diskHealthAdapter := tools.NewDiskHealthMCPAdapter(r.monitor)if diskHealthAdapter != nil {service.SetDiskHealthProvider(diskHealthAdapter)- log.Debug().Msg("OpenCode: Disk health provider wired")+ log.Debug().Msg("AI chat: Disk health provider wired")}}@@ -2068,7 +2068,7 @@ func (r *Router) wireOpenCodeProviders() {updatesAdapter := tools.NewUpdatesMCPAdapter(r.monitor, &updatesConfigWrapper{cfg: r.config})if updatesAdapter != nil {service.SetUpdatesProvider(updatesAdapter)- log.Debug().Msg("OpenCode: Updates provider wired")+ log.Debug().Msg("AI chat: Updates provider wired")}}@@ -2081,7 +2081,7 @@ func (r *Router) wireOpenCodeProviders() {)if metricsAdapter != nil {service.SetMetricsHistory(metricsAdapter)- log.Debug().Msg("OpenCode: Metrics history provider wired")+ log.Debug().Msg("AI chat: Metrics history provider wired")}}}@@ -2093,7 +2093,7 @@ func (r *Router) wireOpenCodeProviders() {baselineAdapter := tools.NewBaselineMCPAdapter(&baselineSourceWrapper{store: baselineStore})if baselineAdapter != nil {service.SetBaselineProvider(baselineAdapter)- log.Debug().Msg("OpenCode: Baseline provider wired")+ log.Debug().Msg("AI chat: Baseline provider wired")}}}@@ -2109,7 +2109,7 @@ func (r *Router) wireOpenCodeProviders() {)if patternAdapter != nil {service.SetPatternProvider(patternAdapter)- log.Debug().Msg("OpenCode: Pattern provider wired")+ log.Debug().Msg("AI chat: Pattern provider wired")}}}@@ -2121,7 +2121,7 @@ func (r *Router) wireOpenCodeProviders() {findingsManagerAdapter := tools.NewFindingsManagerMCPAdapter(patrolSvc)if findingsManagerAdapter != nil {service.SetFindingsManager(findingsManagerAdapter)- log.Debug().Msg("OpenCode: Findings manager wired")+ log.Debug().Msg("AI chat: Findings manager wired")}}}@@ -2131,11 +2131,11 @@ func (r *Router) wireOpenCodeProviders() {metadataAdapter := tools.NewMetadataUpdaterMCPAdapter(r.aiSettingsHandler.GetAIService())if metadataAdapter != nil {service.SetMetadataUpdater(metadataAdapter)- log.Debug().Msg("OpenCode: Metadata updater wired")+ log.Debug().Msg("AI chat: Metadata updater wired")}}- log.Info().Msg("OpenCode MCP tool providers wired")+ log.Info().Msg("AI chat MCP tool providers wired")}// metricsSourceWrapper wraps monitoring.MetricsHistory to implement tools.MetricsSource@@ -2285,23 +2285,23 @@ func (w *updatesConfigWrapper) IsDockerUpdateActionsEnabled() bool {return !w.cfg.DisableDockerUpdateActions}-// StopOpenCodeAI stops the OpenCode-based AI service-func (r *Router) StopOpenCodeAI(ctx context.Context) {+// StopAIChat stops the AI chat service+func (r *Router) StopAIChat(ctx context.Context) {if r.aiHandler != nil {if err := r.aiHandler.Stop(ctx); err != nil {- log.Error().Err(err).Msg("Failed to stop OpenCode AI service")+ log.Error().Err(err).Msg("Failed to stop AI chat service")}}}-// RestartOpenCodeAI restarts the OpenCode service with updated configuration-// Call this when AI settings change that affect the sidecar (e.g., model selection)-func (r *Router) RestartOpenCodeAI(ctx context.Context) {+// RestartAIChat restarts the AI chat service with updated configuration+// Call this when AI settings change that affect the service (e.g., model selection)+func (r *Router) RestartAIChat(ctx context.Context) {if r.aiHandler != nil {if err := r.aiHandler.Restart(ctx); err != nil {- log.Error().Err(err).Msg("Failed to restart OpenCode AI service")+ log.Error().Err(err).Msg("Failed to restart AI chat service")} else {- log.Info().Msg("OpenCode AI service restarted with new configuration")+ log.Info().Msg("AI chat service restarted with new configuration")}}}diff --git a/internal/config/ai.go b/internal/config/ai.goindex acbdb25afa..4f7f669da3 100644--- a/internal/config/ai.go+++ b/internal/config/ai.go@@ -62,12 +62,6 @@ type AIConfig struct {// Budget is expressed as an estimated USD amount over a 30-day window (pro-rated in UI for other ranges).CostBudgetUSD30d float64 `json:"cost_budget_usd_30d,omitempty"`- // OpenCode integration - use OpenCode as the AI backend instead of direct provider calls- // When enabled, chat and patrol use OpenCode for better tool calling and multi-model support- UseOpenCode bool `json:"use_opencode,omitempty"` // Enable OpenCode backend- OpenCodeDataDir string `json:"opencode_data_dir,omitempty"` // Data directory for OpenCode (default: /tmp/pulse-opencode)- OpenCodePort int `json:"opencode_port,omitempty"` // Port for OpenCode server (0 = auto-assign)-// AI Infrastructure Control settings// These control whether AI can take actions on infrastructure (start/stop VMs, containers, etc.)ControlLevel string `json:"control_level,omitempty"` // "read_only", "suggest", "controlled", "autonomous"diff --git a/internal/config/persistence.go b/internal/config/persistence.goindex be4a18bc75..a1551dad03 100644--- a/internal/config/persistence.go+++ b/internal/config/persistence.go@@ -1680,12 +1680,7 @@ func (c *ConfigPersistence) LoadAIConfig() (*AIConfig, error) {settings.PatrolIntervalMinutes = 15}- // Environment variable override for UseOpenCode- if os.Getenv("PULSE_USE_OPENCODE") == "true" || os.Getenv("PULSE_USE_OPENCODE") == "1" {- settings.UseOpenCode = true- }-- log.Info().Str("file", c.aiFile).Bool("enabled", settings.Enabled).Bool("patrol_enabled", settings.PatrolEnabled).Bool("alert_triggered_analysis", settings.AlertTriggeredAnalysis).Bool("use_opencode", settings.UseOpenCode).Msg("AI configuration loaded")+ log.Info().Str("file", c.aiFile).Bool("enabled", settings.Enabled).Bool("patrol_enabled", settings.PatrolEnabled).Bool("alert_triggered_analysis", settings.AlertTriggeredAnalysis).Msg("AI configuration loaded")return settings, nil}diff --git a/pkg/server/server.go b/pkg/server/server.goindex cca526cf2f..08466729d9 100644--- a/pkg/server/server.go+++ b/pkg/server/server.go@@ -195,8 +195,8 @@ func Run(ctx context.Context, version string) error {// Start AI patrol service for background infrastructure monitoringrouter.StartPatrol(ctx)- // Start OpenCode AI service (when UseOpenCode is enabled in config)- router.StartOpenCodeAI(ctx)+ // Start AI chat service+ router.StartAIChat(ctx)// Wire alert-triggered AI analysisrouter.WireAlertTriggeredAI()@@ -304,8 +304,8 @@ shutdown:log.Error().Err(err).Msg("Server shutdown error")}- // Stop OpenCode AI service (kills sidecar process group)- router.StopOpenCodeAI(shutdownCtx)+ // Stop AI chat service (kills sidecar process group)+ router.StopAIChat(shutdownCtx)cancel()reloadableMonitor.Stop()