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.

Forward-port Ollama runtime auth continuity

rcourtman73597f8b1adb
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index d7cb78a3ae..9940d2ab77 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -125,6 +125,7 @@ management, and fleet control surfaces.
2. Add or change update continuity and persisted-version handoff through `internal/agentupdate/`.
3. Add or change runtime-side Unified Agent startup, first-report assembly, and enroll/runtime continuity through `internal/hostagent/`.
4. Keep shared `internal/api/` helper edits isolated from agent lifecycle semantics: Patrol-specific status transport or alert-trigger wiring changes in shared handlers must not bleed into auto-register, installer, or fleet-control behavior unless this contract moves in the same slice.
+ The same isolation rule applies to AI settings payload work in `internal/api/ai_handlers.go`: provider auth fields, masked-secret echoes, and provider-test model selection remain AI/runtime plus API-contract ownership and must not be reinterpreted as lifecycle setup or registration semantics just because they share backend helper layers.
4. Keep legacy Unified Agent compatibility names explicitly secondary when touching shared `internal/api/` runtime helpers: the legacy host-route family and `host-agent:*` scope names may remain as ingress or migration aliases, but they must not retake primary ownership in router state, live runtime scope checks, handler commentary, or operator-facing guidance.
5. Add or change installer flags, persisted service arguments, or upgrade-safe re-entry behavior through `scripts/install.sh` and `scripts/install.ps1`.
6. Add or change profile management, the extracted agent profiles runtime owner, the pure unified-agent inventory/install model, the API-backed platform connections workspace shell, route model, reporting summary owner, shared install/inventory/dialog section owners, the split infrastructure install/reporting state owners, the split direct-node/discovery infrastructure settings owners plus their shared model, shared frontend install-command assembly, Proxmox setup/install API transport, TrueNAS platform-connection management, VMware platform-connection management, setup-completion install handoff transport, deploy-fallback manual install transport, and fleet-control presentation through `frontend-modern/src/api/agentProfiles.ts`, `frontend-modern/src/api/nodes.ts`, `frontend-modern/src/components/Settings/AgentProfilesPanel.tsx`, `frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts`, `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`, `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallPanel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx`, `frontend-modern/src/components/Settings/InfrastructureReportingPanel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInventorySection.tsx`, `frontend-modern/src/components/Settings/InfrastructureActiveRowDetails.tsx`, `frontend-modern/src/components/Settings/InfrastructureIgnoredRowDetails.tsx`, `frontend-modern/src/components/Settings/InfrastructureStopMonitoringDialog.tsx`, `frontend-modern/src/components/Settings/InfrastructurePlatformConnectionsSummaryCard.tsx`, `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx`, `frontend-modern/src/components/Settings/infrastructureWorkspaceModel.ts`, `frontend-modern/src/components/Settings/PlatformConnectionsWorkspace.tsx`, `frontend-modern/src/components/Settings/platformConnectionsModel.ts`, `frontend-modern/src/components/Settings/TrueNASSettingsPanel.tsx`, `frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts`, `frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx`, `frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts`, `frontend-modern/src/components/Settings/ProxmoxSettingsPanel.tsx`, `frontend-modern/src/components/Settings/proxmoxSettingsModel.ts`, `frontend-modern/src/components/Settings/ProxmoxDirectWorkspace.tsx`, `frontend-modern/src/components/Settings/ProxmoxConfiguredNodesTable.tsx`, `frontend-modern/src/components/Settings/ProxmoxDirectConnectionsCard.tsx`, `frontend-modern/src/components/Settings/ProxmoxDiscoveryResultsCard.tsx`, `frontend-modern/src/components/Settings/ProxmoxDeleteNodeDialog.tsx`, `frontend-modern/src/components/Settings/ProxmoxNodeModalStack.tsx`, `frontend-modern/src/components/Settings/ConfiguredNodeTables.tsx`, `frontend-modern/src/components/Settings/SettingsSectionNav.tsx`, `frontend-modern/src/components/Settings/infrastructureSettingsModel.ts`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts`, `frontend-modern/src/components/Settings/useProxmoxDirectWorkspaceState.ts`, `frontend-modern/src/components/Settings/NodeModal.tsx`, `frontend-modern/src/components/Settings/nodeModalModel.ts`, `frontend-modern/src/components/Settings/useNodeModalState.ts`, `frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx`, and `frontend-modern/src/utils/agentInstallCommand.ts`.
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index e3f9745b20..e7c1199fbe 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -21,22 +21,23 @@ runtime cost control, and shared AI transport surfaces.
## Canonical Files
1. `internal/ai/`
-2. `internal/api/ai_handler.go`
-3. `internal/api/ai_handlers.go`
-4. `internal/api/ai_hosted_runtime.go`
-5. `internal/api/ai_intelligence_handlers.go`
-6. `frontend-modern/src/api/ai.ts`
-7. `frontend-modern/src/api/patrol.ts`
-8. `frontend-modern/src/components/AI/AICostDashboard.tsx`
-9. `frontend-modern/src/components/AI/Chat/`
-10. `frontend-modern/src/utils/aiChatPresentation.ts`
-11. `frontend-modern/src/utils/aiControlLevelPresentation.ts`
-12. `frontend-modern/src/utils/aiCostPresentation.ts`
-13. `frontend-modern/src/utils/aiExplorePresentation.ts`
-14. `frontend-modern/src/utils/aiProviderHealthPresentation.ts`
-15. `frontend-modern/src/utils/aiProviderPresentation.ts`
-16. `frontend-modern/src/utils/aiSessionDiffPresentation.ts`
-17. `frontend-modern/src/utils/textPresentation.ts`
+2. `internal/config/ai.go`
+3. `internal/api/ai_handler.go`
+4. `internal/api/ai_handlers.go`
+5. `internal/api/ai_hosted_runtime.go`
+6. `internal/api/ai_intelligence_handlers.go`
+7. `frontend-modern/src/api/ai.ts`
+8. `frontend-modern/src/api/patrol.ts`
+9. `frontend-modern/src/components/AI/AICostDashboard.tsx`
+10. `frontend-modern/src/components/AI/Chat/`
+11. `frontend-modern/src/utils/aiChatPresentation.ts`
+12. `frontend-modern/src/utils/aiControlLevelPresentation.ts`
+13. `frontend-modern/src/utils/aiCostPresentation.ts`
+14. `frontend-modern/src/utils/aiExplorePresentation.ts`
+15. `frontend-modern/src/utils/aiProviderHealthPresentation.ts`
+16. `frontend-modern/src/utils/aiProviderPresentation.ts`
+17. `frontend-modern/src/utils/aiSessionDiffPresentation.ts`
+18. `frontend-modern/src/utils/textPresentation.ts`
## Shared Boundaries
@@ -49,11 +50,12 @@ runtime cost control, and shared AI transport surfaces.
## Extension Points
1. Add or change chat runtime, Patrol orchestration, findings generation, or remediation behavior through `internal/ai/`
-2. Add or change Pulse Assistant request flow through `internal/api/ai_handler.go` and `frontend-modern/src/api/ai.ts`
-3. Add or change Patrol, alert-analysis, or remediation transport through `internal/api/ai_handlers.go`, `internal/api/ai_intelligence_handlers.go`, and `frontend-modern/src/api/patrol.ts`
-4. Add or change AI usage/cost dashboard presentation through `frontend-modern/src/components/AI/AICostDashboard.tsx` and `frontend-modern/src/utils/aiCostPresentation.ts`
-5. Add or change AI provider, control-level, chat/session, or explore-state presentation through `frontend-modern/src/components/AI/Chat/`, `frontend-modern/src/utils/aiProviderPresentation.ts`, `frontend-modern/src/utils/aiProviderHealthPresentation.ts`, `frontend-modern/src/utils/aiControlLevelPresentation.ts`, `frontend-modern/src/utils/aiChatPresentation.ts`, `frontend-modern/src/utils/aiSessionDiffPresentation.ts`, and `frontend-modern/src/utils/aiExplorePresentation.ts`
-6. Keep AI chat presentation helpers aligned through `frontend-modern/src/components/AI/Chat/` and the shared `frontend-modern/src/utils/textPresentation.ts`
+2. Add or change canonical AI provider config, provider-scoped model selection, or runtime auth/base-URL defaults through `internal/config/ai.go`
+3. Add or change Pulse Assistant request flow through `internal/api/ai_handler.go` and `frontend-modern/src/api/ai.ts`
+4. Add or change Patrol, alert-analysis, or remediation transport through `internal/api/ai_handlers.go`, `internal/api/ai_intelligence_handlers.go`, and `frontend-modern/src/api/patrol.ts`
+5. Add or change AI usage/cost dashboard presentation through `frontend-modern/src/components/AI/AICostDashboard.tsx` and `frontend-modern/src/utils/aiCostPresentation.ts`
+6. Add or change AI provider, control-level, chat/session, or explore-state presentation through `frontend-modern/src/components/AI/Chat/`, `frontend-modern/src/utils/aiProviderPresentation.ts`, `frontend-modern/src/utils/aiProviderHealthPresentation.ts`, `frontend-modern/src/utils/aiControlLevelPresentation.ts`, `frontend-modern/src/utils/aiChatPresentation.ts`, `frontend-modern/src/utils/aiSessionDiffPresentation.ts`, and `frontend-modern/src/utils/aiExplorePresentation.ts`
+7. Keep AI chat presentation helpers aligned through `frontend-modern/src/components/AI/Chat/` and the shared `frontend-modern/src/utils/textPresentation.ts`
## Forbidden Paths
@@ -85,6 +87,10 @@ governed floor is ready.
`internal/ai/` is the live backend AI engine. It owns chat execution, Patrol
orchestration, findings generation, investigation support, quickstart and
provider selection, remediation flow, and cost persistence.
+That same backend runtime ownership includes `internal/config/ai.go`, because
+provider auth, base URLs, provider-scoped model defaults, and other persisted
+runtime AI selection rules must stay canonical in the shared AI config model
+instead of drifting into handler-local fallbacks or frontend-only assumptions.
That quickstart ownership includes the public proxy dependency under
`internal/ai/providers/quickstart.go`: the runtime must default to the owned
commercial API edge at `https://license.pulserelay.pro/v1/quickstart/patrol`
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index bce12e500a..37071b0df7 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -205,6 +205,7 @@ Own canonical runtime payload shapes between backend and frontend.
20. Backend config/settings handlers pointing operator guidance at GitHub `main` docs when the running build already ships that guidance locally under `/docs/`
21. Telemetry preview or reset endpoints drifting from the exact server-owned telemetry runtime contract instead of reusing the same source-of-truth snapshot and install-ID state the background sender uses
22. Shared SSO test or metadata-preview handlers open-coding outbound metadata/discovery URLs, allowing userinfo-bearing HTTP(S) inputs, or rebuilding `/.well-known/openid-configuration` with origin-root string concatenation instead of the shared validated URL helpers before any outbound request
+23. AI settings handlers echoing raw provider secrets or testing the wrong provider model: `/api/settings/ai` may expose masked provider-auth presence such as `ollama_password_set`, but backend payloads must never echo stored secrets back to clients, and provider-specific test routes must stay bound to the selected provider's own configured model instead of whichever other provider currently owns the default `model` field
## Completion Obligations
@@ -265,6 +266,13 @@ Own canonical runtime payload shapes between backend and frontend.
(`agent`, `docker`, `kubernetes`) and platform-connections-managed
surfaces (`proxmox`, `pbs`, `pmg`, `truenas`) instead of collapsing them
into one uninstall/stop-monitoring model.
+23. Keep AI settings payload continuity explicit on the shared `/api/settings/ai`
+ surface: `internal/api/ai_handlers.go` and `internal/api/contract_test.go`
+ must expose masked provider-auth state such as `ollama_username` and
+ `ollama_password_set` without echoing raw stored secrets, and the same
+ backend contract must keep provider test routes bound to the selected
+ provider's configured model instead of whichever other provider currently
+ owns the default `model` field.
23. Keep API-backed first-target onboarding canonical on that same shared
infrastructure-settings boundary:
`frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`,
@@ -2244,6 +2252,13 @@ on its empty-list payload once AI is enabled, even when the first enablement
happens after process startup. A post-boot settings save may not leave that
surface on `503 Approval store not initialized` just because the direct AI
runtime had not previously started.
+That same shared AI settings contract also owns provider-auth continuity and
+provider-scoped test selection. `internal/api/ai_handlers.go` and
+`internal/api/contract_test.go` must expose masked Ollama auth state through
+`ollama_username` and `ollama_password_set`, accept provider-auth updates
+without echoing raw secrets back into the payload, and keep provider test
+routes bound to the provider's own configured model instead of whichever
+other provider currently owns the default `model` selection.
That same shared infrastructure-settings API contract now also owns the
connected-infrastructure distinction between machine-managed and
platform-connections-managed reporting. `frontend-modern/src/types/api.ts`,
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 0164dd7748..f22d45fb47 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -969,7 +969,8 @@
"frontend-modern/src/utils/aiSessionDiffPresentation.ts",
"internal/api/ai_handler.go",
"internal/api/ai_handlers.go",
- "internal/api/ai_intelligence_handlers.go"
+ "internal/api/ai_intelligence_handlers.go",
+ "internal/config/ai.go"
],
"verification": {
"allow_same_subsystem_tests": false,
@@ -1051,6 +1052,19 @@
"internal/ai/"
],
"exact_files": []
+ },
+ {
+ "id": "ai-runtime-config",
+ "label": "AI runtime config proof",
+ "match_prefixes": [],
+ "match_files": [
+ "internal/config/ai.go"
+ ],
+ "allow_same_subsystem_tests": false,
+ "test_prefixes": [],
+ "exact_files": [
+ "internal/config/ai_config_test.go"
+ ]
}
]
}
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 5e4b05f5f8..71762d0f5a 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -89,6 +89,7 @@ querying, and the operator-facing storage health presentation layer.
18. Preserve the dedicated backend-owned `relay:mobile:access` capability and its governed backward-compatible route inventory plus the shared helper call sites around it, so storage- and recovery-adjacent transport surfaces do not treat the mobile relay credential as a general AI scope bundle.
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.
+ The same adjacency rule applies to AI settings transport in `internal/api/ai_handlers.go`: provider auth state, masked-secret payload fields, and provider-test model selection remain AI/runtime plus API-contract concerns and must not be absorbed into storage/recovery transport ownership just because those handlers live under the shared backend API tree.
21. Keep provider-backed recovery onboarding on the adjacent platform-connections contract. When `internal/api/` grows or changes TrueNAS connection CRUD, masked-secret preservation, saved-connection retest routes, edit-form saved-test payload overlays, 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.
23. Keep backend-native platform diagnostics on the adjacent AI/runtime and platform contracts. When `internal/api/` wires native TrueNAS app log reads for Assistant, storage and recovery may use those diagnostics during investigation, but they must not grow a parallel recovery-local log transport or diagnostic payload shape.
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index 48d2ce3aad..64680a85c3 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -930,11 +930,8 @@ func (s *Service) createProviderForModel(modelStr string) (providers.StreamingPr
}
return providers.NewGeminiClient(s.cfg.GeminiAPIKey, modelName, "", timeout), nil
case "ollama":
- baseURL := s.cfg.OllamaBaseURL
- if baseURL == "" {
- baseURL = "http://localhost:11434"
- }
- return providers.NewOllamaClient(modelName, baseURL, timeout), nil
+ baseURL := s.cfg.GetBaseURLForProvider(config.AIProviderOllama)
+ return providers.NewOllamaClient(modelName, baseURL, s.cfg.OllamaUsername, s.cfg.OllamaPassword, timeout), nil
case config.AIProviderQuickstart:
// Quickstart uses the hosted proxy — no API key needed.
// The licenseID is embedded in the client via orgID.
diff --git a/internal/ai/chat/service_explore.go b/internal/ai/chat/service_explore.go
index 1c098d194f..dbb50aa7da 100644
--- a/internal/ai/chat/service_explore.go
+++ b/internal/ai/chat/service_explore.go
@@ -246,11 +246,8 @@ func (s *Service) createProviderForExplore(modelStr string) (providers.Streaming
}
return providers.NewGeminiClient(s.cfg.GeminiAPIKey, modelName, "", exploreHTTPTimeout), nil
case "ollama":
- baseURL := s.cfg.OllamaBaseURL
- if baseURL == "" {
- baseURL = "http://localhost:11434"
- }
- return providers.NewOllamaClient(modelName, baseURL, exploreHTTPTimeout), nil
+ baseURL := s.cfg.GetBaseURLForProvider(config.AIProviderOllama)
+ return providers.NewOllamaClient(modelName, baseURL, s.cfg.OllamaUsername, s.cfg.OllamaPassword, exploreHTTPTimeout), nil
case config.AIProviderQuickstart:
// Quickstart uses the hosted proxy and does not require a BYOK key.
// The orgID carries the hosted workspace identity for credit accounting.
diff --git a/internal/ai/chat/service_patrol_additional_test.go b/internal/ai/chat/service_patrol_additional_test.go
index f094788974..d306facc55 100644
--- a/internal/ai/chat/service_patrol_additional_test.go
+++ b/internal/ai/chat/service_patrol_additional_test.go
@@ -2,6 +2,9 @@ package chat
import (
"context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
"strings"
"testing"
"time"
@@ -87,6 +90,48 @@ func TestService_CreateProviderForModel(t *testing.T) {
}
}
+func TestService_CreateProviderForModel_OllamaUsesConfiguredBasicAuth(t *testing.T) {
+ versionHits := 0
+ tagsHits := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ username, password, ok := r.BasicAuth()
+ if !ok || username != "unai" || password != "secret" {
+ t.Fatalf("unexpected basic auth: ok=%v user=%q pass=%q", ok, username, password)
+ }
+ switch r.URL.Path {
+ case "/api/version":
+ versionHits++
+ _ = json.NewEncoder(w).Encode(map[string]any{"version": "0.1.0"})
+ case "/api/tags":
+ tagsHits++
+ _ = json.NewEncoder(w).Encode(map[string]any{"models": []map[string]any{{"name": "llama3:latest"}}})
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer server.Close()
+
+ svc := &Service{
+ cfg: &config.AIConfig{
+ OllamaBaseURL: server.URL,
+ OllamaUsername: "unai",
+ OllamaPassword: "secret",
+ },
+ }
+
+ provider, err := svc.createProviderForModel("ollama:llama3")
+ if err != nil {
+ t.Fatalf("expected ollama provider to be created: %v", err)
+ }
+
+ if err := provider.TestConnection(context.Background()); err != nil {
+ t.Fatalf("expected ollama provider test connection to succeed: %v", err)
+ }
+ if versionHits != 1 || tagsHits != 1 {
+ t.Fatalf("expected version+tags check, got version=%d tags=%d", versionHits, tagsHits)
+ }
+}
+
func TestService_ExecutePatrolStream_Success(t *testing.T) {
store, err := NewSessionStore(t.TempDir())
if err != nil {
diff --git a/internal/ai/providers/factory.go b/internal/ai/providers/factory.go
index 7928fd9a6a..8a094a96c9 100644
--- a/internal/ai/providers/factory.go
+++ b/internal/ai/providers/factory.go
@@ -29,6 +29,10 @@ func NewForProvider(cfg *config.AIConfig, provider, model string) (Provider, err
return nil, fmt.Errorf("Pulse Assistant config is nil")
}
+ if normalizedProvider, normalizedModel := config.ParseModelString(model); normalizedProvider == provider && normalizedModel != "" {
+ model = normalizedModel
+ }
+
// Get the configured timeout
timeout := cfg.GetRequestTimeout()
@@ -77,7 +81,7 @@ func NewForProvider(cfg *config.AIConfig, provider, model string) (Provider, err
case config.AIProviderOllama:
baseURL := cfg.GetBaseURLForProvider(config.AIProviderOllama)
- return NewOllamaClient(model, baseURL, timeout), nil
+ return NewOllamaClient(model, baseURL, cfg.OllamaUsername, cfg.OllamaPassword, timeout), nil
case config.AIProviderGemini:
apiKey := cfg.GetAPIKeyForProvider(config.AIProviderGemini)
diff --git a/internal/ai/providers/integration_test.go b/internal/ai/providers/integration_test.go
index 93317fa27f..7c73afab6e 100644
--- a/internal/ai/providers/integration_test.go
+++ b/internal/ai/providers/integration_test.go
@@ -28,7 +28,7 @@ func getOllamaURL() string {
}
func TestIntegration_Ollama_TestConnection(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -41,7 +41,7 @@ func TestIntegration_Ollama_TestConnection(t *testing.T) {
}
func TestIntegration_Ollama_ListModels(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
@@ -62,7 +62,7 @@ func TestIntegration_Ollama_ListModels(t *testing.T) {
}
func TestIntegration_Ollama_SimpleChat(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
@@ -87,7 +87,7 @@ func TestIntegration_Ollama_SimpleChat(t *testing.T) {
}
func TestIntegration_Ollama_SystemPrompt(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
@@ -117,7 +117,7 @@ func TestIntegration_Ollama_SystemPrompt(t *testing.T) {
}
func TestIntegration_Ollama_MultiTurnConversation(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
defer cancel()
@@ -156,7 +156,7 @@ func TestIntegration_Ollama_MultiTurnConversation(t *testing.T) {
}
func TestIntegration_Ollama_TokenCounting(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
@@ -184,7 +184,7 @@ func TestIntegration_Ollama_TokenCounting(t *testing.T) {
}
func TestIntegration_Ollama_ErrorHandling_BadModel(t *testing.T) {
- client := providers.NewOllamaClient("nonexistent-model-12345", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("nonexistent-model-12345", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
@@ -203,7 +203,7 @@ func TestIntegration_Ollama_ErrorHandling_BadModel(t *testing.T) {
}
func TestIntegration_Ollama_Timeout(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
// Very short timeout - should fail
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
@@ -226,7 +226,7 @@ func TestIntegration_Ollama_Timeout(t *testing.T) {
// --- More useful tests below ---
func TestIntegration_Ollama_JSONOutput(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
@@ -268,7 +268,7 @@ func TestIntegration_Ollama_JSONOutput(t *testing.T) {
}
func TestIntegration_Ollama_LongResponse(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
defer cancel()
@@ -293,7 +293,7 @@ func TestIntegration_Ollama_LongResponse(t *testing.T) {
}
func TestIntegration_Ollama_EmptyMessage(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
@@ -314,7 +314,7 @@ func TestIntegration_Ollama_EmptyMessage(t *testing.T) {
}
func TestIntegration_Ollama_SpecialCharacters(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
@@ -337,7 +337,7 @@ func TestIntegration_Ollama_SpecialCharacters(t *testing.T) {
}
func TestIntegration_Ollama_ConcurrentRequests(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
const numRequests = 3
results := make(chan error, numRequests)
@@ -373,7 +373,7 @@ func TestIntegration_Ollama_ConcurrentRequests(t *testing.T) {
func TestIntegration_Ollama_InfrastructureAnalysis(t *testing.T) {
// This simulates what Pulse actually does - send infrastructure context
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
@@ -417,7 +417,7 @@ What should I investigate first?`
}
func TestIntegration_Ollama_ModelName_Preserved(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
@@ -442,7 +442,7 @@ func TestIntegration_Ollama_ModelName_Preserved(t *testing.T) {
}
func TestIntegration_Ollama_StopReason(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
@@ -462,7 +462,7 @@ func TestIntegration_Ollama_StopReason(t *testing.T) {
}
func TestIntegration_Ollama_VeryLongInput(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
defer cancel()
@@ -487,7 +487,7 @@ func TestIntegration_Ollama_VeryLongInput(t *testing.T) {
}
func TestIntegration_Ollama_RapidFireRequests(t *testing.T) {
- client := providers.NewOllamaClient("tinyllama", getOllamaURL(), 0)
+ client := providers.NewOllamaClient("tinyllama", getOllamaURL(), "", "", 0)
// Send 5 requests in rapid succession
for i := 0; i < 5; i++ {
diff --git a/internal/ai/providers/ollama.go b/internal/ai/providers/ollama.go
index 77c1fb1faa..07974fb3c5 100644
--- a/internal/ai/providers/ollama.go
+++ b/internal/ai/providers/ollama.go
@@ -15,13 +15,15 @@ import (
type OllamaClient struct {
model string
baseURL string
+ username string
+ password string
client *http.Client // For non-streaming requests (has overall timeout)
streamClient *http.Client // For streaming requests (no overall timeout — relies on context)
}
// NewOllamaClient creates a new Ollama API client
// timeout is optional - pass 0 to use the default 5 minute timeout
-func NewOllamaClient(model, baseURL string, timeout time.Duration) *OllamaClient {
+func NewOllamaClient(model, baseURL, username, password string, timeout time.Duration) *OllamaClient {
if baseURL == "" {
baseURL = "http://localhost:11434"
}
@@ -34,8 +36,10 @@ func NewOllamaClient(model, baseURL string, timeout time.Duration) *OllamaClient
timeout = 300 * time.Second // Default 5 minutes
}
return &OllamaClient{
- model: model,
- baseURL: baseURL,
+ model: model,
+ baseURL: baseURL,
+ username: username,
+ password: password,
client: &http.Client{
Timeout: timeout,
},
@@ -51,6 +55,12 @@ func NewOllamaClient(model, baseURL string, timeout time.Duration) *OllamaClient
}
}
+func (c *OllamaClient) applyAuth(req *http.Request) {
+ if c.username != "" || c.password != "" {
+ req.SetBasicAuth(c.username, c.password)
+ }
+}
+
// Name returns the provider name
func (c *OllamaClient) Name() string {
return "ollama"
@@ -223,6 +233,7 @@ func (c *OllamaClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse
}
httpReq.Header.Set("Content-Type", "application/json")
+ c.applyAuth(httpReq)
resp, err := c.client.Do(httpReq)
if err != nil {
@@ -388,6 +399,7 @@ func (c *OllamaClient) ChatStream(ctx context.Context, req ChatRequest, callback
}
httpReq.Header.Set("Content-Type", "application/json")
+ c.applyAuth(httpReq)
// Use streamClient which has no overall timeout — http.Client.Timeout
// includes response body reading time, which kills slow streaming responses.
@@ -477,12 +489,14 @@ func (c *OllamaClient) ChatStream(ctx context.Context, req ChatRequest, callback
}
// TestConnection validates connectivity by checking the Ollama version endpoint
+// and ensuring the configured model is available from the local model registry.
func (c *OllamaClient) TestConnection(ctx context.Context) error {
versionURL := c.baseURL + "/api/version"
httpReq, err := http.NewRequestWithContext(ctx, "GET", versionURL, nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
+ c.applyAuth(httpReq)
resp, err := c.client.Do(httpReq)
if err != nil {
@@ -494,9 +508,76 @@ func (c *OllamaClient) TestConnection(ctx context.Context) error {
return fmt.Errorf("Ollama returned status %d", resp.StatusCode)
}
+ models, err := c.ListModels(ctx)
+ if err != nil {
+ return fmt.Errorf("connected to Ollama version endpoint but failed to list models: %w", err)
+ }
+ if c.model != "" && !ollamaModelAvailable(c.model, models) {
+ available := make([]string, 0, len(models))
+ for _, model := range models {
+ label := strings.TrimSpace(model.ID)
+ if label == "" {
+ label = strings.TrimSpace(model.Name)
+ }
+ if label != "" {
+ available = append(available, label)
+ }
+ }
+ if len(available) > 0 {
+ return fmt.Errorf("connected to Ollama but model %q is not available; found: %s", normalizeOllamaModelRef(c.model), strings.Join(available, ", "))
+ }
+ return fmt.Errorf("connected to Ollama but model %q is not available", normalizeOllamaModelRef(c.model))
+ }
+
return nil
}
+func normalizeOllamaModelRef(model string) string {
+ model = strings.TrimSpace(model)
+ if strings.HasPrefix(model, "ollama:") {
+ model = strings.TrimPrefix(model, "ollama:")
+ }
+ return model
+}
+
+func splitOllamaModelRef(model string) (string, string) {
+ model = normalizeOllamaModelRef(model)
+ if model == "" {
+ return "", ""
+ }
+ idx := strings.LastIndex(model, ":")
+ if idx == -1 {
+ return model, ""
+ }
+ return model[:idx], model[idx+1:]
+}
+
+func ollamaModelAvailable(model string, available []ModelInfo) bool {
+ wantName, wantTag := splitOllamaModelRef(model)
+ if wantName == "" {
+ return len(available) > 0
+ }
+
+ for _, candidate := range available {
+ ref := strings.TrimSpace(candidate.ID)
+ if ref == "" {
+ ref = strings.TrimSpace(candidate.Name)
+ }
+ haveName, haveTag := splitOllamaModelRef(ref)
+ if haveName == "" {
+ continue
+ }
+ if wantName != haveName {
+ continue
+ }
+ if wantTag == "" || haveTag == "" || wantTag == haveTag {
+ return true
+ }
+ }
+
+ return false
+}
+
// ListModels fetches available models from the local Ollama instance
func (c *OllamaClient) ListModels(ctx context.Context) ([]ModelInfo, error) {
modelsURL := c.baseURL + "/api/tags"
@@ -504,6 +585,7 @@ func (c *OllamaClient) ListModels(ctx context.Context) ([]ModelInfo, error) {
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
+ c.applyAuth(httpReq)
resp, err := c.client.Do(httpReq)
if err != nil {
diff --git a/internal/ai/providers/ollama_test.go b/internal/ai/providers/ollama_test.go
index 2db5113dfe..9f48a88e09 100644
--- a/internal/ai/providers/ollama_test.go
+++ b/internal/ai/providers/ollama_test.go
@@ -35,7 +35,7 @@ func TestOllamaClient_ChatStream_Success(t *testing.T) {
}))
defer server.Close()
- client := NewOllamaClient("llama3", server.URL, 0)
+ client := NewOllamaClient("llama3", server.URL, "", "", 0)
var content string
var done bool
@@ -78,7 +78,7 @@ func TestOllamaClient_ChatStream_ToolCall(t *testing.T) {
}))
defer server.Close()
- client := NewOllamaClient("llama3", server.URL, 0)
+ client := NewOllamaClient("llama3", server.URL, "", "", 0)
var toolsFound []string
@@ -111,7 +111,7 @@ func TestOllamaClient_ChatStream_Errors(t *testing.T) {
}))
defer server.Close()
- client := NewOllamaClient("llama3", server.URL, 0)
+ client := NewOllamaClient("llama3", server.URL, "", "", 0)
err := client.ChatStream(context.Background(), ChatRequest{Messages: []Message{{Role: "user"}}}, func(e StreamEvent) {})
assert.Error(t, err)
@@ -132,7 +132,7 @@ func TestOllamaClient_ListModels(t *testing.T) {
}))
defer server.Close()
- client := NewOllamaClient("llama3", server.URL, 0)
+ client := NewOllamaClient("llama3", server.URL, "", "", 0)
models, err := client.ListModels(context.Background())
require.NoError(t, err)
@@ -153,7 +153,7 @@ func TestNewOllamaClient_Normalization(t *testing.T) {
}
for _, tt := range tests {
- client := NewOllamaClient("model", tt.input, 0)
+ client := NewOllamaClient("model", tt.input, "", "", 0)
assert.Equal(t, tt.expect, client.baseURL)
}
}
@@ -186,7 +186,7 @@ func TestOllamaClient_Chat_Success(t *testing.T) {
}))
defer server.Close()
- client := NewOllamaClient("llama3", server.URL, 0)
+ client := NewOllamaClient("llama3", server.URL, "", "", 0)
resp, err := client.Chat(context.Background(), ChatRequest{
Messages: []Message{{Role: "user", Content: "Hi"}},
Tools: []Tool{
@@ -211,20 +211,59 @@ func TestOllamaClient_Chat_Success(t *testing.T) {
}
func TestOllamaClient_TestConnection(t *testing.T) {
+ versionHits := 0
+ tagsHits := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- assert.Equal(t, "/api/version", r.URL.Path)
- w.WriteHeader(http.StatusOK)
+ username, password, ok := r.BasicAuth()
+ assert.True(t, ok)
+ assert.Equal(t, "unai", username)
+ assert.Equal(t, "secret", password)
+ switch r.URL.Path {
+ case "/api/version":
+ versionHits++
+ _ = json.NewEncoder(w).Encode(map[string]any{"version": "0.1.0"})
+ case "/api/tags":
+ tagsHits++
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "models": []map[string]any{{"name": "llama3:latest"}},
+ })
+ default:
+ http.NotFound(w, r)
+ }
}))
defer server.Close()
- client := NewOllamaClient("llama3", server.URL, 0)
+ client := NewOllamaClient("llama3", server.URL, "unai", "secret", 0)
err := client.TestConnection(context.Background())
require.NoError(t, err)
+ assert.Equal(t, 1, versionHits)
+ assert.Equal(t, 1, tagsHits)
}
func TestOllamaClient_SupportsThinking(t *testing.T) {
- client := NewOllamaClient("llama3", "http://localhost:11434", 0)
+ client := NewOllamaClient("llama3", "http://localhost:11434", "", "", 0)
if client.SupportsThinking("llama3") {
t.Fatal("expected SupportsThinking to be false")
}
}
+
+func TestOllamaClient_TestConnection_ModelUnavailable(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/version":
+ _ = json.NewEncoder(w).Encode(map[string]any{"version": "0.1.0"})
+ case "/api/tags":
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "models": []map[string]any{{"name": "mistral:latest"}},
+ })
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer server.Close()
+
+ client := NewOllamaClient("llama3", server.URL, "", "", 0)
+ err := client.TestConnection(context.Background())
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), `model "llama3" is not available`)
+}
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 7d39d8539b..d058c4628c 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -2,6 +2,8 @@ package ai
import (
"context"
+ "crypto/sha256"
+ "encoding/hex"
"encoding/json"
"fmt"
"io"
@@ -4422,6 +4424,11 @@ func buildModelsCacheKey(cfg *config.AIConfig) string {
b.WriteString(cfg.OpenAIBaseURL)
b.WriteString("|ollama_base=")
b.WriteString(cfg.OllamaBaseURL)
+ b.WriteString("|ollama_auth=")
+ if cfg.OllamaUsername != "" || cfg.OllamaPassword != "" {
+ sum := sha256.Sum256([]byte(cfg.OllamaUsername + "\n" + cfg.OllamaPassword))
+ b.WriteString(hex.EncodeToString(sum[:]))
+ }
return b.String()
}
diff --git a/internal/ai/service_extended_test.go b/internal/ai/service_extended_test.go
index 3bf918885a..63b518de3c 100644
--- a/internal/ai/service_extended_test.go
+++ b/internal/ai/service_extended_test.go
@@ -1295,6 +1295,31 @@ func TestService_ListModelsWithCache_CacheHit(t *testing.T) {
}
}
+func TestBuildModelsCacheKey_OllamaAuthFingerprint(t *testing.T) {
+ cfgA := &config.AIConfig{
+ Enabled: true,
+ OllamaBaseURL: "http://localhost:11434",
+ OllamaUsername: "unai",
+ OllamaPassword: "secret-a",
+ }
+ cfgB := &config.AIConfig{
+ Enabled: true,
+ OllamaBaseURL: "http://localhost:11434",
+ OllamaUsername: "unai",
+ OllamaPassword: "secret-b",
+ }
+
+ keyA := buildModelsCacheKey(cfgA)
+ keyB := buildModelsCacheKey(cfgB)
+
+ if keyA == keyB {
+ t.Fatal("expected different cache keys when Ollama credentials change")
+ }
+ if strings.Contains(keyA, "secret-a") || strings.Contains(keyB, "secret-b") {
+ t.Fatal("expected cache keys to avoid embedding raw Ollama passwords")
+ }
+}
+
// Note: ListModelsWithCache does not handle nil persistence gracefully (panics)
// This is acceptable as NewService should always be called with a valid persistence
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index 82bbd1db61..4c2b72c379 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -1665,6 +1665,32 @@ func (h *AISettingsHandler) SetOnModelChange(callback func()) {
h.onModelChange = callback
}
+func shouldRestartAIChat(req AISettingsUpdateRequest) bool {
+ return req.Enabled != nil ||
+ req.Model != nil ||
+ req.ChatModel != nil ||
+ req.PatrolModel != nil ||
+ req.AutoFixModel != nil ||
+ req.AuthMethod != nil ||
+ req.AnthropicAPIKey != nil ||
+ req.OpenAIAPIKey != nil ||
+ req.OpenRouterAPIKey != nil ||
+ req.DeepSeekAPIKey != nil ||
+ req.GeminiAPIKey != nil ||
+ req.OllamaBaseURL != nil ||
+ req.OllamaUsername != nil ||
+ req.OllamaPassword != nil ||
+ req.OpenAIBaseURL != nil ||
+ req.ClearAnthropicKey != nil ||
+ req.ClearOpenAIKey != nil ||
+ req.ClearOpenRouterKey != nil ||
+ req.ClearDeepSeekKey != nil ||
+ req.ClearGeminiKey != nil ||
+ req.ClearOllamaURL != nil ||
+ req.ClearOllamaUsername != nil ||
+ req.ClearOllamaPassword != nil
+}
+
// SetOnControlSettingsChange sets a callback to be invoked when control settings change
// Used by Router to update MCP tool visibility without restarting AI chat
func (h *AISettingsHandler) SetOnControlSettingsChange(callback func()) {
@@ -2178,6 +2204,8 @@ type AISettingsResponse struct {
GeminiConfigured bool `json:"gemini_configured"` // true if Gemini API key is set
OllamaConfigured bool `json:"ollama_configured"` // true (always available for attempt)
OllamaBaseURL string `json:"ollama_base_url"` // Ollama server URL
+ OllamaUsername string `json:"ollama_username,omitempty"` // Optional Basic Auth username for Ollama
+ OllamaPasswordSet bool `json:"ollama_password_set"` // true if an Ollama password is stored
OpenAIBaseURL string `json:"openai_base_url,omitempty"` // Custom OpenAI base URL
ConfiguredProviders []string `json:"configured_providers"` // List of provider names with credentials
// Cost controls
@@ -2240,14 +2268,18 @@ type AISettingsUpdateRequest struct {
DeepSeekAPIKey *string `json:"deepseek_api_key,omitempty"` // Set DeepSeek API key
GeminiAPIKey *string `json:"gemini_api_key,omitempty"` // Set Gemini API key
OllamaBaseURL *string `json:"ollama_base_url,omitempty"` // Set Ollama server URL
+ OllamaUsername *string `json:"ollama_username,omitempty"` // Set Ollama Basic Auth username
+ OllamaPassword *string `json:"ollama_password,omitempty"` // Set Ollama Basic Auth password
OpenAIBaseURL *string `json:"openai_base_url,omitempty"` // Set custom OpenAI base URL
// Clear flags for removing credentials
- ClearAnthropicKey *bool `json:"clear_anthropic_key,omitempty"` // Clear Anthropic API key
- ClearOpenAIKey *bool `json:"clear_openai_key,omitempty"` // Clear OpenAI API key
- ClearOpenRouterKey *bool `json:"clear_openrouter_key,omitempty"` // Clear OpenRouter API key
- ClearDeepSeekKey *bool `json:"clear_deepseek_key,omitempty"` // Clear DeepSeek API key
- ClearGeminiKey *bool `json:"clear_gemini_key,omitempty"` // Clear Gemini API key
- ClearOllamaURL *bool `json:"clear_ollama_url,omitempty"` // Clear Ollama URL
+ ClearAnthropicKey *bool `json:"clear_anthropic_key,omitempty"` // Clear Anthropic API key
+ ClearOpenAIKey *bool `json:"clear_openai_key,omitempty"` // Clear OpenAI API key
+ ClearOpenRouterKey *bool `json:"clear_openrouter_key,omitempty"` // Clear OpenRouter API key
+ ClearDeepSeekKey *bool `json:"clear_deepseek_key,omitempty"` // Clear DeepSeek API key
+ ClearGeminiKey *bool `json:"clear_gemini_key,omitempty"` // Clear Gemini API key
+ ClearOllamaURL *bool `json:"clear_ollama_url,omitempty"` // Clear Ollama URL
+ ClearOllamaUsername *bool `json:"clear_ollama_username,omitempty"` // Clear Ollama Basic Auth username
+ ClearOllamaPassword *bool `json:"clear_ollama_password,omitempty"` // Clear Ollama Basic Auth password
// Cost controls
CostBudgetUSD30d *float64 `json:"cost_budget_usd_30d,omitempty"`
// Request timeout (seconds) - for slow hardware running local models
@@ -2338,6 +2370,8 @@ func (h *AISettingsHandler) HandleGetAISettings(w http.ResponseWriter, r *http.R
GeminiConfigured: settings.HasProvider(config.AIProviderGemini),
OllamaConfigured: settings.HasProvider(config.AIProviderOllama),
OllamaBaseURL: settings.GetBaseURLForProvider(config.AIProviderOllama),
+ OllamaUsername: settings.OllamaUsername,
+ OllamaPasswordSet: settings.OllamaPassword != "",
OpenAIBaseURL: settings.OpenAIBaseURL,
ConfiguredProviders: settings.GetConfiguredProviders(),
CostBudgetUSD30d: settings.CostBudgetUSD30d,
@@ -2477,6 +2511,16 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt
} else if req.OllamaBaseURL != nil {
settings.OllamaBaseURL = strings.TrimSpace(*req.OllamaBaseURL)
}
+ if req.ClearOllamaUsername != nil && *req.ClearOllamaUsername {
+ settings.OllamaUsername = ""
+ } else if req.OllamaUsername != nil {
+ settings.OllamaUsername = strings.TrimSpace(*req.OllamaUsername)
+ }
+ if req.ClearOllamaPassword != nil && *req.ClearOllamaPassword {
+ settings.OllamaPassword = ""
+ } else if req.OllamaPassword != nil {
+ settings.OllamaPassword = *req.OllamaPassword
+ }
if req.OpenAIBaseURL != nil {
settings.OpenAIBaseURL = strings.TrimSpace(*req.OpenAIBaseURL)
}
@@ -2681,11 +2725,10 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt
analyzer.SetEnabled(settings.AlertTriggeredAnalysis)
}
- // Trigger AI chat service restart if model changed
- // This ensures the new model is picked up by the service
- // Trigger AI chat service restart if model changed or AI enabled
- // This ensures the new model is picked up by the service
- if h.onModelChange != nil && (req.Model != nil || req.ChatModel != nil || req.Enabled != nil) {
+ // Trigger AI chat service restart when provider-affecting settings change.
+ // The running service keeps provider configuration in memory, so credential,
+ // base URL, or model updates must restart the chat runtime to take effect.
+ if h.onModelChange != nil && shouldRestartAIChat(req) {
h.onModelChange()
}
@@ -2743,6 +2786,8 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt
GeminiConfigured: settings.HasProvider(config.AIProviderGemini),
OllamaConfigured: settings.HasProvider(config.AIProviderOllama),
OllamaBaseURL: settings.GetBaseURLForProvider(config.AIProviderOllama),
+ OllamaUsername: settings.OllamaUsername,
+ OllamaPasswordSet: settings.OllamaPassword != "",
OpenAIBaseURL: settings.OpenAIBaseURL,
ConfiguredProviders: settings.GetConfiguredProviders(),
RequestTimeoutSeconds: settings.RequestTimeoutSeconds,
@@ -2871,7 +2916,7 @@ func (h *AISettingsHandler) HandleTestProvider(w http.ResponseWriter, r *http.Re
}
// Create provider and test connection
- testProvider, err := providers.NewForProvider(cfg, provider, cfg.GetModel())
+ testProvider, err := providers.NewForProvider(cfg, provider, cfg.GetPreferredModelForProvider(provider))
if err != nil {
testResult.Success = false
testResult.Message = "Failed to create provider"
diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.go
index b99e5b2255..48c95ee40a 100644
--- a/internal/api/ai_handlers_test.go
+++ b/internal/api/ai_handlers_test.go
@@ -88,9 +88,11 @@ func TestAISettingsHandler_GetAndUpdateSettings_RoundTrip(t *testing.T) {
// Update settings to enable AI via Ollama.
{
body, _ := json.Marshal(AISettingsUpdateRequest{
- Enabled: ptr(true),
- Model: ptr("ollama:llama3"),
- OllamaBaseURL: ptr("http://localhost:11434"),
+ Enabled: ptr(true),
+ Model: ptr("ollama:llama3"),
+ OllamaBaseURL: ptr("http://localhost:11434"),
+ OllamaUsername: ptr("unai"),
+ OllamaPassword: ptr("secret"),
})
req := httptest.NewRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))
rec := httptest.NewRecorder()
@@ -110,6 +112,9 @@ func TestAISettingsHandler_GetAndUpdateSettings_RoundTrip(t *testing.T) {
if resp.OllamaBaseURL != "http://localhost:11434" {
t.Fatalf("unexpected ollama base url: %+v", resp)
}
+ if resp.OllamaUsername != "unai" || !resp.OllamaPasswordSet {
+ t.Fatalf("expected ollama auth state in response, got %+v", resp)
+ }
responseBody := rec.Body.String()
if !strings.Contains(responseBody, `"available_models":[]`) ||
!strings.Contains(responseBody, `"configured_providers":[`) ||
@@ -135,6 +140,9 @@ func TestAISettingsHandler_GetAndUpdateSettings_RoundTrip(t *testing.T) {
if !resp.Enabled || !resp.OllamaConfigured {
t.Fatalf("expected enabled + ollama configured, got %+v", resp)
}
+ if resp.OllamaUsername != "unai" || !resp.OllamaPasswordSet {
+ t.Fatalf("expected persisted ollama auth state, got %+v", resp)
+ }
responseBody := rec.Body.String()
if !strings.Contains(responseBody, `"available_models":[]`) ||
!strings.Contains(responseBody, `"configured_providers":[`) ||
@@ -573,12 +581,23 @@ func ptr[T any](v T) *T { return &v }
func TestAISettingsHandler_TestConnection_Ollama(t *testing.T) {
t.Parallel()
+ versionHits := 0
+ tagsHits := 0
ollama := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/api/version" {
+ username, password, ok := r.BasicAuth()
+ if !ok || username != "unai" || password != "secret" {
+ t.Fatalf("unexpected basic auth: ok=%v user=%q pass=%q", ok, username, password)
+ }
+ switch r.URL.Path {
+ case "/api/version":
+ versionHits++
+ _ = json.NewEncoder(w).Encode(map[string]any{"version": "0.1.0"})
+ case "/api/tags":
+ tagsHits++
+ _ = json.NewEncoder(w).Encode(map[string]any{"models": []map[string]any{{"name": "llama3:latest"}}})
+ default:
http.NotFound(w, r)
- return
}
- _ = json.NewEncoder(w).Encode(map[string]any{"version": "0.1.0"})
}))
defer ollama.Close()
@@ -590,6 +609,8 @@ func TestAISettingsHandler_TestConnection_Ollama(t *testing.T) {
aiCfg.Enabled = true
aiCfg.Model = "ollama:llama3"
aiCfg.OllamaBaseURL = ollama.URL
+ aiCfg.OllamaUsername = "unai"
+ aiCfg.OllamaPassword = "secret"
if err := persistence.SaveAIConfig(*aiCfg); err != nil {
t.Fatalf("SaveAIConfig: %v", err)
}
@@ -614,17 +635,31 @@ func TestAISettingsHandler_TestConnection_Ollama(t *testing.T) {
if !resp.Success {
t.Fatalf("expected success, got %+v", resp)
}
+ if versionHits != 1 || tagsHits != 1 {
+ t.Fatalf("expected version+tags check, got version=%d tags=%d", versionHits, tagsHits)
+ }
}
func TestAISettingsHandler_TestProvider_Ollama(t *testing.T) {
t.Parallel()
+ versionHits := 0
+ tagsHits := 0
ollama := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/api/version" {
+ username, password, ok := r.BasicAuth()
+ if !ok || username != "unai" || password != "secret" {
+ t.Fatalf("unexpected basic auth: ok=%v user=%q pass=%q", ok, username, password)
+ }
+ switch r.URL.Path {
+ case "/api/version":
+ versionHits++
+ _ = json.NewEncoder(w).Encode(map[string]any{"version": "0.1.0"})
+ case "/api/tags":
+ tagsHits++
+ _ = json.NewEncoder(w).Encode(map[string]any{"models": []map[string]any{{"name": "llama3:latest"}}})
+ default:
http.NotFound(w, r)
- return
}
- _ = json.NewEncoder(w).Encode(map[string]any{"version": "0.1.0"})
}))
defer ollama.Close()
@@ -634,8 +669,11 @@ func TestAISettingsHandler_TestProvider_Ollama(t *testing.T) {
aiCfg := config.NewDefaultAIConfig()
aiCfg.Enabled = true
- aiCfg.Model = "ollama:llama3"
+ aiCfg.Model = "openai:gpt-4o"
+ aiCfg.PatrolModel = "ollama:llama3"
aiCfg.OllamaBaseURL = ollama.URL
+ aiCfg.OllamaUsername = "unai"
+ aiCfg.OllamaPassword = "secret"
if err := persistence.SaveAIConfig(*aiCfg); err != nil {
t.Fatalf("SaveAIConfig: %v", err)
}
@@ -660,6 +698,9 @@ func TestAISettingsHandler_TestProvider_Ollama(t *testing.T) {
if !resp.Success || resp.Provider != "ollama" {
t.Fatalf("unexpected response: %+v", resp)
}
+ if versionHits != 1 || tagsHits != 1 {
+ t.Fatalf("expected version+tags check, got version=%d tags=%d", versionHits, tagsHits)
+ }
}
// ========================================
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 515078eabc..724010b669 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -1644,6 +1644,7 @@ func TestContract_HostedAISettingsAutoBootstrapJSONSnapshot(t *testing.T) {
"gemini_configured":false,
"ollama_configured":false,
"ollama_base_url":"http://localhost:11434",
+ "ollama_password_set":false,
"configured_providers":[],
"control_level":"read_only",
"protected_guests":[],
@@ -1658,6 +1659,72 @@ func TestContract_HostedAISettingsAutoBootstrapJSONSnapshot(t *testing.T) {
assertJSONSnapshot(t, rec.Body.Bytes(), want)
}
+func TestContract_AISettingsOllamaAuthJSONSnapshot(t *testing.T) {
+ tmp := t.TempDir()
+ cfg := &config.Config{DataPath: tmp}
+ persistence := config.NewConfigPersistence(tmp)
+
+ aiCfg := config.NewDefaultAIConfig()
+ aiCfg.Enabled = true
+ aiCfg.Model = "openai:gpt-4o"
+ aiCfg.PatrolModel = "ollama:llama3"
+ aiCfg.OllamaBaseURL = "http://ollama.example:11434"
+ aiCfg.OllamaUsername = "unai"
+ aiCfg.OllamaPassword = "secret"
+ if err := persistence.SaveAIConfig(*aiCfg); err != nil {
+ t.Fatalf("SaveAIConfig: %v", err)
+ }
+
+ handler := newTestAISettingsHandler(cfg, persistence, nil)
+
+ req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)
+ rec := httptest.NewRecorder()
+ handler.HandleGetAISettings(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status=%d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
+ }
+
+ const want = `{
+ "enabled":true,
+ "model":"openai:gpt-4o",
+ "patrol_model":"ollama:llama3",
+ "configured":true,
+ "custom_context":"",
+ "auth_method":"api_key",
+ "oauth_connected":false,
+ "patrol_interval_minutes":360,
+ "patrol_enabled":true,
+ "patrol_auto_fix":false,
+ "alert_triggered_analysis":true,
+ "patrol_event_triggers_enabled":true,
+ "patrol_alert_triggers_enabled":true,
+ "patrol_anomaly_triggers_enabled":true,
+ "use_proactive_thresholds":false,
+ "available_models":[],
+ "anthropic_configured":false,
+ "openai_configured":false,
+ "openrouter_configured":false,
+ "deepseek_configured":false,
+ "gemini_configured":false,
+ "ollama_configured":true,
+ "ollama_base_url":"http://ollama.example:11434",
+ "ollama_username":"unai",
+ "ollama_password_set":true,
+ "configured_providers":["ollama"],
+ "control_level":"read_only",
+ "protected_guests":[],
+ "discovery_enabled":false,
+ "quickstart_credits_total":0,
+ "quickstart_credits_used":0,
+ "quickstart_credits_remaining":0,
+ "quickstart_credits_available":false,
+ "using_quickstart":false
+ }`
+
+ assertJSONSnapshot(t, rec.Body.Bytes(), want)
+}
+
func TestContract_VMInventoryExportCSVHeaders(t *testing.T) {
handler := NewReportingHandlers(nil, nil)
req := httptest.NewRequest(http.MethodGet, "/api/admin/reports/inventory/vms/export?format=csv", nil)
@@ -2112,6 +2179,7 @@ func TestContract_HostedTenantAISettingsFallbackJSONSnapshot(t *testing.T) {
"gemini_configured":false,
"ollama_configured":false,
"ollama_base_url":"http://localhost:11434",
+ "ollama_password_set":false,
"configured_providers":[],
"control_level":"read_only",
"protected_guests":[],
diff --git a/internal/config/ai.go b/internal/config/ai.go
index ba809445df..8e7221b0ba 100644
--- a/internal/config/ai.go
+++ b/internal/config/ai.go
@@ -38,6 +38,8 @@ type AIConfig struct {
DeepSeekAPIKey string `json:"deepseek_api_key,omitempty"` // DeepSeek API key
GeminiAPIKey string `json:"gemini_api_key,omitempty"` // Google Gemini API key
OllamaBaseURL string `json:"ollama_base_url,omitempty"` // Ollama server URL (default: http://localhost:11434)
+ OllamaUsername string `json:"ollama_username,omitempty"` // Optional Basic Auth username for Ollama
+ OllamaPassword string `json:"ollama_password,omitempty"` // Optional Basic Auth password for Ollama
OpenAIBaseURL string `json:"openai_base_url,omitempty"` // Custom OpenAI-compatible base URL (optional)
// OAuth fields for Claude Pro/Max subscription authentication
@@ -369,6 +371,24 @@ func (c *AIConfig) GetModel() string {
return ""
}
+// GetPreferredModelForProvider returns the most relevant configured model for a provider.
+// It prefers explicitly selected models for that provider before falling back to the
+// provider default model string.
+func (c *AIConfig) GetPreferredModelForProvider(provider string) string {
+ for _, candidate := range []string{c.Model, c.ChatModel, c.PatrolModel, c.AutoFixModel, c.DiscoveryModel} {
+ candidate = strings.TrimSpace(candidate)
+ if candidate == "" {
+ continue
+ }
+ candidateProvider, _ := ParseModelString(candidate)
+ if candidateProvider == provider {
+ return candidate
+ }
+ }
+
+ return DefaultModelForProvider(provider)
+}
+
// GetChatModel returns the model for interactive chat conversations
// Falls back to the main Model if ChatModel is not set
func (c *AIConfig) GetChatModel() string {
diff --git a/internal/config/ai_config_test.go b/internal/config/ai_config_test.go
index 0f2cc8d38f..e492f9812d 100644
--- a/internal/config/ai_config_test.go
+++ b/internal/config/ai_config_test.go
@@ -492,6 +492,63 @@ func TestAIConfig_GetChatModel(t *testing.T) {
})
}
+func TestAIConfig_GetPreferredModelForProvider(t *testing.T) {
+ tests := []struct {
+ name string
+ config AIConfig
+ provider string
+ expected string
+ }{
+ {
+ name: "uses main model when provider matches",
+ config: AIConfig{
+ Model: "ollama:llama3.2",
+ },
+ provider: AIProviderOllama,
+ expected: "ollama:llama3.2",
+ },
+ {
+ name: "falls back to patrol override for provider",
+ config: AIConfig{
+ Model: "openai:gpt-4o",
+ PatrolModel: "ollama:qwen2.5",
+ },
+ provider: AIProviderOllama,
+ expected: "ollama:qwen2.5",
+ },
+ {
+ name: "detects unprefixed ollama model",
+ config: AIConfig{
+ PatrolModel: "llama3.1",
+ },
+ provider: AIProviderOllama,
+ expected: "llama3.1",
+ },
+ {
+ name: "falls back to provider default when no model matches",
+ config: AIConfig{
+ Model: "openai:gpt-4o",
+ },
+ provider: AIProviderGemini,
+ expected: FormatModelString(AIProviderGemini, DefaultAIModelGemini),
+ },
+ {
+ name: "unknown provider returns empty",
+ config: AIConfig{Model: "openai:gpt-4o"},
+ provider: "unknown",
+ expected: "",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := tt.config.GetPreferredModelForProvider(tt.provider); got != tt.expected {
+ t.Fatalf("GetPreferredModelForProvider(%q) = %q, want %q", tt.provider, got, tt.expected)
+ }
+ })
+ }
+}
+
func TestAIConfig_GetPatrolModel(t *testing.T) {
t.Run("explicit patrol model", func(t *testing.T) {
config := AIConfig{
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 2105e1c516..6a8e980f29 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -2018,6 +2018,25 @@ class SubsystemLookupTest(unittest.TestCase):
self.assertEqual(match["verification_requirement"]["id"], "ai-runtime-engine")
self.assertEqual(match["verification_requirement"]["test_prefixes"], ["internal/ai/"])
+ def test_lookup_paths_assigns_internal_ai_config_to_ai_runtime(self) -> None:
+ result = lookup_paths(["internal/config/ai.go"])
+ self.assertEqual(result["unowned_runtime_files"], [])
+ self.assertEqual(
+ {item["subsystem"] for item in result["impacted_subsystems"]},
+ {"ai-runtime"},
+ )
+ file_entry = result["files"][0]
+ self.assertEqual(file_entry["classification"], "runtime")
+ self.assertEqual(
+ {match["subsystem"] for match in file_entry["matches"]},
+ {"ai-runtime"},
+ )
+ match = file_entry["matches"][0]
+ self.assertEqual(match["contract"], "docs/release-control/v6/internal/subsystems/ai-runtime.md")
+ self.assertEqual(match["lane_context"]["lane_id"], "L6")
+ self.assertEqual(match["verification_requirement"]["id"], "ai-runtime-config")
+ self.assertEqual(match["verification_requirement"]["exact_files"], ["internal/config/ai_config_test.go"])
+
def test_lookup_paths_reports_notification_client_as_shared_boundary(self) -> None:
result = lookup_paths(["frontend-modern/src/api/notifications.ts"])
self.assertEqual(result["unowned_runtime_files"], [])
@@ -4676,7 +4695,7 @@ class SubsystemLookupTest(unittest.TestCase):
ai_runtime_expected = [
_contract_reference(
"docs/release-control/v6/internal/subsystems/ai-runtime.md",
- "2. `internal/api/ai_handler.go`",
+ "3. `internal/api/ai_handler.go`",
"internal/api/ai_handler.go",
),
_contract_reference(
@@ -4686,7 +4705,7 @@ class SubsystemLookupTest(unittest.TestCase):
),
_contract_reference(
"docs/release-control/v6/internal/subsystems/ai-runtime.md",
- "2. Add or change Pulse Assistant request flow through `internal/api/ai_handler.go`",
+ "3. Add or change Pulse Assistant request flow through `internal/api/ai_handler.go`",
"internal/api/ai_handler.go",
),
]
@@ -4764,8 +4783,8 @@ class SubsystemLookupTest(unittest.TestCase):
)
self.assertIn(
"contract focus: "
- f"{_contract_reference('docs/release-control/v6/internal/subsystems/ai-runtime.md', '2. `internal/api/ai_handler.go`', 'internal/api/ai_handler.go')['heading']} "
- f"@L{_contract_reference('docs/release-control/v6/internal/subsystems/ai-runtime.md', '2. `internal/api/ai_handler.go`', 'internal/api/ai_handler.go')['line']}: "
+ f"{_contract_reference('docs/release-control/v6/internal/subsystems/ai-runtime.md', '3. `internal/api/ai_handler.go`', 'internal/api/ai_handler.go')['heading']} "
+ f"@L{_contract_reference('docs/release-control/v6/internal/subsystems/ai-runtime.md', '3. `internal/api/ai_handler.go`', 'internal/api/ai_handler.go')['line']}: "
"internal/api/ai_handler.go",
rendered,
)