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
Start Assistant runtime in mock mode
rcourtman3c74fe2ca0d5
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex aa2482e6ef..a84d2a5661 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -1532,6 +1532,12 @@ prior chat session. Lifecycle-adjacent mobile pairing and setup flows dependon `/api/ai/approvals` becoming ready from the first governed settings save,not only after some earlier process-start or chat-start side effect hasalready initialized the approval store.+That same shared dependency now also assumes mock-mode Assistant runtime+startup is AI/runtime-only. When mock mode is active, `internal/api/ai_handler.go`+may enable the Assistant runtime in memory so `/api/ai/chat` can exercise the+typed mock stream without configured providers, but that effective config must+not become agent enrollment, install readiness, command approval authority, or+persisted lifecycle setup state.That same shared `internal/api/ai_handler.go` dependency now also assumesAssistant finding handoffs may include a model-only factual finding briefingfrom Patrol's unified finding and structured investigation record. Lifecycle-adjacentdiff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 9e48d769a6..be392a02e5 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -567,9 +567,26 @@ runtime cost control, and shared AI transport surfaces.persist a real assistant message with model route `pulse:mock-assistant` anda successful `pulse_query` tool call so session restore, transcript tooling,and stream-contract tests exercise the same backend-to-browser shape as a- live provider/tool turn. This fixture must not run as provider fallback in- non-mock mode and must not become Pulse-authored remediation or routing- behavior.+ live provider/tool turn. Mock mode is also an effective runtime-config+ overlay: `internal/api/ai_handler.go` startup, restart, config sync, and+ tenant service initialization must treat Assistant as enabled in memory when+ mock mode is active, without saving or mutating the persisted `AIConfig`, so+ `/api/ai/chat` and Assistant sessions are available with zero configured+ external providers or models. The live fixture must pace its status, tool,+ and content events enough for the browser to paint each state in sequence;+ unit tests may disable that pace, but the dev fixture must not collapse into+ a single final completed row. This fixture must not run as provider fallback+ in non-mock mode and must not become Pulse-authored remediation or routing+ behavior. The referenced OpenCode source at fetched `origin/dev` commit+ `4519a1da329c1a4fc384054e7203ba7d06928205` publishes tool-call and+ tool-result events incrementally in+ `packages/core/src/session/runner/publish-llm-event.ts`, mutates assistant+ tool parts through pending/running/completed states in+ `packages/core/src/session/message-updater.ts`, and renders the current tool+ part state in `packages/ui/src/components/message-part.tsx` through+ `packages/ui/src/components/basic-tool.tsx`. Pulse adapts that source model+ by making the mock fixture prove the same visible state sequence without+ copying OpenCode's editor-specific tool catalog.The referenced OpenCode source at fetched `origin/dev` commit`09d9cf01f93798939c1284fbe974b6e1f4d2759d` renders tool-specific inlinelabels such as `Read <path>`, `Grep "<pattern>"`, `WebFetch <url>`, and bashdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex eea639b03b..0d14f2ece3 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -527,8 +527,8 @@ payload shape change when the portal presents compact client rows.Assistant execution is still in flight. Hidden SSE comment heartbeats arenot sufficient user-visible progress. The handler must serialize commentheartbeats and JSON event writes through one writer lock, and the- `stream_idle` event must stop before terminal `done`/`error` rather than- becoming assistant-authored transcript content.+ `stream_idle` event must stop before terminal `done`/`error` rather than+ becoming assistant-authored transcript content.The generated frontend union, stream parsertests, and backend JSON snapshot proof must stay in lockstep with that payload;`done.session_id` and `question.session_id` remain compatibility payloads,@@ -536,6 +536,16 @@ payload shape change when the portal presents compact client rows.must also carry the effective `model` route that completed the stream soprovider fallback, transcript labels, retries, and model-route recovery staytied to the actual responding provider rather than the failed request route.+ Mock-mode Assistant chat is part of that same API contract: when mock mode+ is active, `internal/api/ai_handler.go` must start, restart, sync, and+ tenant-initialize the chat runtime from an in-memory effective config that+ enables Assistant without mutating the persisted `AIConfig`. `/api/ai/chat`+ must therefore accept cold Assistant requests in mock mode even when no real+ provider or model is configured, and it must return the normal typed SSE+ sequence rather than the service-not-running recovery error. The mock+ fixture must pace its browser-facing status/tool/content events enough to+ prove the visible stream contract, while tests may disable that pace to keep+ backend proof fast.34. `internal/api/ai_handlers.go` shared with `ai-runtime`: AI settings and remediation handlers are both an AI runtime control surface and a canonical API payload contract boundary.Provider test responses from `/api/ai/test` and provider-specific`/api/ai/test/{provider}` preflight responses must return one safediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 0b6b77c998..beb2788ba2 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -221,6 +221,12 @@ state only. A restored prompt or restored message count may help an operatorcontinue a protected-item investigation, but it must not become backup coverageevidence, recovery freshness, restore entitlement, storage-owner identity,approval policy, or a provider-local recovery command handoff.+Mock-mode Assistant chat startup through `internal/api/ai_handler.go` is also+only adjacent AI/runtime proof for storage/recovery consumers. The handler may+enable the Assistant runtime in memory during mock mode so the typed mock SSE+fixture works without real providers, but that effective config and paced mock+tool stream must not become backup visibility, recovery readiness, restore+authority, storage health evidence, or a recovery-local fixture path.Storage and recovery may also consume unified-resource TrueNAS app and VMmetadata, TrueNAS native service metadata, plus TrueNAS network-share metadata,as read-only workload, system, and storage-access context when explainingdiff --git a/internal/ai/chat/mock_stream.go b/internal/ai/chat/mock_stream.goindex c19696eb88..a64d5f06e2 100644--- a/internal/ai/chat/mock_stream.go+++ b/internal/ai/chat/mock_stream.go@@ -18,7 +18,23 @@ const (mockAssistantToolName = "pulse_query")-func streamMockAssistantTurnIfEnabled(sessions *SessionStore, sessionID, prompt string, streamCallback StreamCallback) bool {+var mockAssistantStreamPace = 220 * time.Millisecond++func pauseMockAssistantStream(ctx context.Context) bool {+ if mockAssistantStreamPace <= 0 {+ return true+ }+ timer := time.NewTimer(mockAssistantStreamPace)+ defer timer.Stop()+ select {+ case <-ctx.Done():+ return false+ case <-timer.C:+ return true+ }+}++func streamMockAssistantTurnIfEnabled(ctx context.Context, sessions *SessionStore, sessionID, prompt string, streamCallback StreamCallback) bool {if !mockmode.IsEnabled() {return false}@@ -42,10 +58,25 @@ func streamMockAssistantTurnIfEnabled(sessions *SessionStore, sessionID, prompttoolOutput := string(toolOutputBytes)emitWorkflowState(streamCallback, "mock_context", "Preparing mock Assistant fixture.", "mock", "")+ if !pauseMockAssistantStream(ctx) {+ return true+ }emitToolStartEvent(streamCallback, mockAssistantToolID, mockAssistantToolName, toolInput)+ if !pauseMockAssistantStream(ctx) {+ return true+ }emitToolProgressEvent(streamCallback, mockAssistantToolID, mockAssistantToolName, toolInput, "running", "Reading synthetic Pulse inventory.")+ if !pauseMockAssistantStream(ctx) {+ return true+ }emitToolProgressEvent(streamCallback, mockAssistantToolID, mockAssistantToolName, toolInput, "running", "Summarizing mock inventory result.")+ if !pauseMockAssistantStream(ctx) {+ return true+ }emitToolEndEvent(streamCallback, mockAssistantToolID, mockAssistantToolName, toolInput, toolOutput, true)+ if !pauseMockAssistantStream(ctx) {+ return true+ }emitWorkflowState(streamCallback, "mock_response", "Composing mock Assistant response.", "mock", mockAssistantToolName)chunks := mockAssistantResponseChunks(prompt)@@ -71,6 +102,9 @@ func streamMockAssistantTurnIfEnabled(sessions *SessionStore, sessionID, prompt}for _, chunk := range chunks {+ if !pauseMockAssistantStream(ctx) {+ return true+ }contentData, _ := json.Marshal(ContentData{Text: chunk})streamCallback(StreamEvent{Type: "content", Data: contentData})}diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex 8f4503507b..b0309f5e32 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -595,7 +595,7 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbacInt("message_count", len(messages)).Msg("[ChatService] Got messages, calling agentic loop")- if streamMockAssistantTurnIfEnabled(sessions, session.ID, req.Prompt, streamCallback) {+ if streamMockAssistantTurnIfEnabled(ctx, sessions, session.ID, req.Prompt, streamCallback) {return nil}diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.goindex 2758d5473b..17c18cb550 100644--- a/internal/ai/chat/service_execute_additional_test.go+++ b/internal/ai/chat/service_execute_additional_test.go@@ -412,6 +412,9 @@ func TestServiceExecuteStreamMockModeStreamsToolFixtureWithoutProviderCall(t *teoriginalMockMode := mockruntime.IsEnabled()t.Cleanup(func() { mockruntime.SetEnabled(originalMockMode) })mockruntime.SetEnabled(true)+ originalPace := mockAssistantStreamPace+ mockAssistantStreamPace = 0+ t.Cleanup(func() { mockAssistantStreamPace = originalPace })var providerFactoryCalls atomic.Int32var providerStreamCalls atomic.Int32diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.goindex 6547611123..343046590d 100644--- a/internal/api/ai_handler.go+++ b/internal/api/ai_handler.go@@ -22,6 +22,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/tools""github.com/rcourtman/pulse-go-rewrite/internal/ai/unified""github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/mockmode""github.com/rcourtman/pulse-go-rewrite/internal/monitoring"recoverymanager "github.com/rcourtman/pulse-go-rewrite/internal/recovery/manager""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"@@ -105,6 +106,18 @@ func aiChatRuntimeConfigChanged(current, latest *config.AIConfig) bool {return aiChatRuntimeConfigDigest(current) != aiChatRuntimeConfigDigest(latest)}+func aiChatRuntimeConfigForMockMode(cfg *config.AIConfig) *config.AIConfig {+ if !mockmode.IsEnabled() {+ return cfg+ }+ if cfg == nil {+ cfg = config.NewDefaultAIConfig()+ }+ next := *cfg+ next.Enabled = true+ return &next+}+type patrolRunHandoffProvider func(context.Context, string) (airuntime.PatrolRunRecord, bool)// AIHandler handles all AI endpoints using direct AI integration@@ -514,7 +527,7 @@ func (h *AIHandler) syncServiceConfig(ctx context.Context, svc AIService) {}currentCfg := reader.GetConfig()- latestCfg := h.loadAIConfig(ctx)+ latestCfg := aiChatRuntimeConfigForMockMode(h.loadAIConfig(ctx))if latestCfg == nil || !latestCfg.Enabled {if currentCfg != nil && currentCfg.Enabled {if err := svc.Stop(ctx); err != nil {@@ -582,7 +595,7 @@ func (h *AIHandler) initTenantService(ctx context.Context, orgID string) AIServi// Tenant chat startup must use the same hosted-aware config path as// /api/settings/ai so hosted orgs do not race into a synthetic disabled/default config.- aiCfg := h.loadAIConfig(tenantCtx)+ aiCfg := aiChatRuntimeConfigForMockMode(h.loadAIConfig(tenantCtx))if aiCfg == nil {log.Info().Str("orgID", orgID).Msg("AI config is nil for tenant service initialization")return nil@@ -818,6 +831,7 @@ func (h *AIHandler) Start(ctx context.Context, monitor *monitoring.Monitor) erro// startWithConfig starts the AI service with an already-loaded config so callers// such as Restart do not re-read (and risk racing) the config a second time.func (h *AIHandler) startWithConfig(ctx context.Context, monitor *monitoring.Monitor, aiCfg *config.AIConfig) error {+ aiCfg = aiChatRuntimeConfigForMockMode(aiCfg)if aiCfg == nil {log.Info().Msg("AI config is nil, AI is disabled")return nil@@ -891,7 +905,7 @@ func (h *AIHandler) Stop(ctx context.Context) error {// Call this when model or other settings changefunc (h *AIHandler) Restart(ctx context.Context) error {// Load fresh config from persistence to get latest settings- newCfg := h.loadAIConfig(ctx)+ newCfg := aiChatRuntimeConfigForMockMode(h.loadAIConfig(ctx))svc := h.getDefaultService()if newCfg == nil || !newCfg.Enabled {diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.goindex 16fc5a95e5..9d2c67ec21 100644--- a/internal/api/ai_handler_test.go+++ b/internal/api/ai_handler_test.go@@ -17,6 +17,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/ai/chat""github.com/rcourtman/pulse-go-rewrite/internal/ai/unified""github.com/rcourtman/pulse-go-rewrite/internal/config"+ mockfixtures "github.com/rcourtman/pulse-go-rewrite/internal/mock""github.com/rcourtman/pulse-go-rewrite/internal/monitoring""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rcourtman/pulse-go-rewrite/pkg/aicontracts"@@ -301,6 +302,74 @@ func TestStart(t *testing.T) {assert.Equal(t, mockSvc, h.defaultService)}+func TestStart_MockModeStartsChatServiceWhenPersistedConfigDisabled(t *testing.T) {+ previousMock := mockfixtures.IsMockEnabled()+ t.Cleanup(func() { _ = mockfixtures.SetEnabled(previousMock) })+ if err := mockfixtures.SetEnabled(true); err != nil {+ t.Fatalf("enable mock mode: %v", err)+ }++ oldNewService := newChatService+ defer func() { newChatService = oldNewService }()++ mockSvc := new(MockAIService)+ persistedCfg := &config.AIConfig{Enabled: false}+ var gotCfg chat.Config+ newChatService = func(cfg chat.Config) AIService {+ gotCfg = cfg+ return mockSvc+ }++ mockPersist := new(MockAIPersistence)+ mockPersist.On("LoadAIConfig").Return(persistedCfg, nil).Once()+ mockSvc.On("Start", mock.Anything).Return(nil).Once()+ h := newTestAIHandler(&config.Config{}, mockPersist, nil)++ err := h.Start(context.Background(), nil)+ assert.NoError(t, err)+ assert.Equal(t, mockSvc, h.defaultService)+ if assert.NotNil(t, gotCfg.AIConfig) {+ assert.True(t, gotCfg.AIConfig.Enabled)+ }+ assert.False(t, persistedCfg.Enabled, "mock-mode runtime enablement must not mutate persisted settings")+ mockSvc.AssertExpectations(t)+ mockPersist.AssertExpectations(t)+}++func TestRestart_MockModeStartsChatServiceWhenPersistedConfigDisabled(t *testing.T) {+ previousMock := mockfixtures.IsMockEnabled()+ t.Cleanup(func() { _ = mockfixtures.SetEnabled(previousMock) })+ if err := mockfixtures.SetEnabled(true); err != nil {+ t.Fatalf("enable mock mode: %v", err)+ }++ oldNewService := newChatService+ defer func() { newChatService = oldNewService }()++ mockSvc := new(MockAIService)+ persistedCfg := &config.AIConfig{Enabled: false}+ var gotCfg chat.Config+ newChatService = func(cfg chat.Config) AIService {+ gotCfg = cfg+ return mockSvc+ }++ mockPersist := new(MockAIPersistence)+ mockPersist.On("LoadAIConfig").Return(persistedCfg, nil).Once()+ mockSvc.On("Start", mock.Anything).Return(nil).Once()+ h := newTestAIHandler(&config.Config{}, mockPersist, nil)++ err := h.Restart(context.Background())+ assert.NoError(t, err)+ assert.Equal(t, mockSvc, h.defaultService)+ if assert.NotNil(t, gotCfg.AIConfig) {+ assert.True(t, gotCfg.AIConfig.Enabled)+ }+ assert.False(t, persistedCfg.Enabled, "mock-mode runtime enablement must not mutate persisted settings")+ mockSvc.AssertExpectations(t)+ mockPersist.AssertExpectations(t)+}+func TestStop(t *testing.T) {mockSvc := new(MockAIService)h := newTestAIHandler(nil, nil, nil)diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 50fa4084a0..8484908cc2 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -10821,6 +10821,47 @@ func TestContract_AssistantChatStreamUsesClientSafeProjection(t *testing.T) {}}+func TestContract_AssistantMockModeRuntimeUsesEffectiveConfig(t *testing.T) {+ handlerSource, err := os.ReadFile(filepath.Clean("ai_handler.go"))+ if err != nil {+ t.Fatalf("read ai_handler.go: %v", err)+ }+ mockStreamSource, err := os.ReadFile(filepath.Clean("../ai/chat/mock_stream.go"))+ if err != nil {+ t.Fatalf("read chat mock stream: %v", err)+ }++ handlerText := string(handlerSource)+ for _, required := range []string{+ "func aiChatRuntimeConfigForMockMode(cfg *config.AIConfig) *config.AIConfig",+ "mockmode.IsEnabled()",+ "next.Enabled = true",+ "latestCfg := aiChatRuntimeConfigForMockMode(h.loadAIConfig(ctx))",+ "aiCfg := aiChatRuntimeConfigForMockMode(h.loadAIConfig(tenantCtx))",+ "aiCfg = aiChatRuntimeConfigForMockMode(aiCfg)",+ "newCfg := aiChatRuntimeConfigForMockMode(h.loadAIConfig(ctx))",+ } {+ if !strings.Contains(handlerText, required) {+ t.Fatalf("Assistant mock-mode runtime config must stay effective-only and cover startup/sync paths: missing %q", required)+ }+ }++ mockStreamText := string(mockStreamSource)+ for _, required := range []string{+ "var mockAssistantStreamPace =",+ "func pauseMockAssistantStream(ctx context.Context) bool",+ "time.NewTimer(mockAssistantStreamPace)",+ "pauseMockAssistantStream(ctx)",+ "Reading synthetic Pulse inventory.",+ "Summarizing mock inventory result.",+ "Composing mock Assistant response.",+ } {+ if !strings.Contains(mockStreamText, required) {+ t.Fatalf("Assistant mock stream must pace browser-visible status/tool/content proof: missing %q", required)+ }+ }+}+func TestContract_PushNotificationJSONSnapshots(t *testing.T) {cases := []struct {name string