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.

fix(hosted): align tenant AI runtime with hosted lease bootstrap

rcourtman6a0f564a101c
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index e0c0019990..1c8186f5e3 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -144,6 +144,11 @@ This subsystem now sits under the dedicated agent lifecycle and fleet
operations lane so install, registration, update continuity, profile
management, and fleet safety stop hiding inside architecture, migration, or
monitoring work.
+That shared `internal/api/` dependency now also assumes hosted tenant AI and
+relay bootstrap reads use one effective hosted billing lease before
+lifecycle-adjacent flows inspect runtime readiness, so install and setup
+surfaces do not observe a tenant-org Pulse Assistant state that disagrees
+with the machine-owned hosted entitlement already backing the same instance.
Agent lifecycle owns the install/register/update continuity surfaces, but it
does not own unified-resource history or control-plane timeline persistence.
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index ee8e77576f..3e9af7538f 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -125,7 +125,11 @@ canonical hosted billing state instead of falling back to a synthetic
must persist one machine-owned quickstart-backed AI config with the canonical
`quickstart:minimax-2.5m` runtime models so Chat and Patrol can start before
the operator visits AI Settings, while any explicitly written AI config
-remains authoritative and must not be overwritten by hosted bootstrap.
+remains authoritative and must not be overwritten by hosted bootstrap. When
+the request runs under a hosted tenant org with no org-local billing lease,
+the same AI runtime path must inherit the default hosted lease for bootstrap
+and quickstart-credit reads so tenant-scoped Chat, Patrol, and AI Settings
+stay aligned with the machine-owned hosted entitlement state.
The same ownership includes the Pulse query tool schema under
`internal/ai/tools/`: topology-query input names must stay canonical inside
the AI runtime itself, so new tool arguments such as `max_proxmox_nodes`
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index f0c4e18827..3126df49d3 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -187,6 +187,13 @@ Own canonical runtime payload shapes between backend and frontend.
The API layer already uses contract tests in many places, but every major live
contract should continue moving toward canonical-only runtime shapes.
+Hosted Pulse Cloud tenant-org AI reads now also follow that same canonical
+rule: `internal/api/ai_hosted_runtime.go`, `internal/api/ai_handlers.go`,
+`internal/api/ai_handler.go`, and `internal/api/hosted_billing_state.go`
+must derive bootstrap and runtime readiness from the effective hosted billing
+lease, falling back to the machine-owned `default` lease when a tenant org
+has no org-local billing state, so `/api/settings/ai`, `/api/ai/status`, and
+`/api/ai/sessions` cannot drift across separate entitlement interpretations.
The shared API-token management surface now also preserves canonical local
operator identity when explaining where a token is currently in use. Runtime
and infrastructure usage labels in the revoke flow keep the local instance
@@ -1641,5 +1648,13 @@ hosted billing lease grants AI capability and carries hosted entitlement
proof, those read surfaces must persist a canonical quickstart-backed AI
config with the governed hosted default model instead of returning a synthetic
`enabled=false` payload that leaves Chat and Patrol unavailable until the
-operator manually saves settings. Once a real AI config exists, that explicit
+operator manually saves settings. Hosted tenant-org reads must also inherit
+the default hosted billing lease whenever no org-local billing state exists,
+so AI bootstrap and quickstart-credit surfaces stay aligned with the same
+machine-owned entitlement source. Once a real AI config exists, that explicit
operator-owned state must remain authoritative over hosted bootstrap.
+The same hosted contract now also requires tenant Pulse Assistant runtime
+startup to consume that hosted-aware config path and to refuse caching a
+failed tenant chat service, so tenant-org `/api/ai/status` and
+`/api/ai/sessions` cannot stay wedged behind a stale pre-bootstrap service
+after the lease-backed AI config has been persisted.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index e440478741..6e774dc04a 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -115,6 +115,12 @@ The recovery backend is a real product boundary, not just a helper package:
`internal/recovery/` owns per-tenant SQLite persistence, rollup derivation,
query filtering, and recovery-point indexing for the `/api/recovery/*`
surfaces.
+That shared `internal/api/` dependency now also assumes hosted tenant AI
+bootstrap and chat-runtime reads resolve through one effective hosted billing
+lease before storage- or recovery-adjacent runtime consumers inspect
+assistant availability, so recovery points, restore guidance, and related
+operator surfaces do not read a tenant-org AI readiness state that diverges
+from the machine-owned hosted entitlement already governing the instance.
The recovery frontend now also separates that ownership more explicitly:
`frontend-modern/src/features/recovery/useRecoverySurfaceState.ts` owns
canonical route parsing, filter/query state, transport hook inputs, and URL
diff --git a/internal/ai/quickstart.go b/internal/ai/quickstart.go
index 7ecb092812..69cf0e9e26 100644
--- a/internal/ai/quickstart.go
+++ b/internal/ai/quickstart.go
@@ -34,6 +34,7 @@ type FileQuickstartCreditManager struct {
mu sync.Mutex
billingStore *config.FileBillingStore
orgID string
+ orgResolver func() string
aiConfig func() *config.AIConfig // Getter for current AI config (for BYOK check)
licenseID string // Workspace identifier for the proxy
}
@@ -44,20 +45,45 @@ func NewFileQuickstartCreditManager(
orgID string,
aiConfigGetter func() *config.AIConfig,
licenseID string,
+) *FileQuickstartCreditManager {
+ return NewFileQuickstartCreditManagerWithOrgResolver(billingStore, orgID, nil, aiConfigGetter, licenseID)
+}
+
+// NewFileQuickstartCreditManagerWithOrgResolver creates a credit manager that
+// can resolve the effective billing org dynamically for each read/write.
+func NewFileQuickstartCreditManagerWithOrgResolver(
+ billingStore *config.FileBillingStore,
+ orgID string,
+ orgResolver func() string,
+ aiConfigGetter func() *config.AIConfig,
+ licenseID string,
) *FileQuickstartCreditManager {
return &FileQuickstartCreditManager{
billingStore: billingStore,
orgID: orgID,
+ orgResolver: orgResolver,
aiConfig: aiConfigGetter,
licenseID: licenseID,
}
}
+func (m *FileQuickstartCreditManager) effectiveOrgID() string {
+ if m == nil {
+ return ""
+ }
+ if m.orgResolver != nil {
+ if resolved := m.orgResolver(); resolved != "" {
+ return resolved
+ }
+ }
+ return m.orgID
+}
+
func (m *FileQuickstartCreditManager) getBillingState() *pkglicensing.BillingState {
if m.billingStore == nil {
return nil
}
- state, err := m.billingStore.GetBillingState(m.orgID)
+ state, err := m.billingStore.GetBillingState(m.effectiveOrgID())
if err != nil {
log.Warn().Err(err).Msg("Quickstart: failed to read billing state")
return nil
@@ -85,7 +111,8 @@ func (m *FileQuickstartCreditManager) ConsumeCredit() error {
m.mu.Lock()
defer m.mu.Unlock()
- state, err := m.billingStore.GetBillingState(m.orgID)
+ effectiveOrgID := m.effectiveOrgID()
+ state, err := m.billingStore.GetBillingState(effectiveOrgID)
if err != nil {
return fmt.Errorf("quickstart: read billing state: %w", err)
}
@@ -97,7 +124,7 @@ func (m *FileQuickstartCreditManager) ConsumeCredit() error {
return fmt.Errorf("quickstart: no credits remaining")
}
- if err := m.billingStore.SaveBillingState(m.orgID, state); err != nil {
+ if err := m.billingStore.SaveBillingState(effectiveOrgID, state); err != nil {
return fmt.Errorf("quickstart: save billing state: %w", err)
}
@@ -129,7 +156,8 @@ func (m *FileQuickstartCreditManager) GrantCredits() error {
m.mu.Lock()
defer m.mu.Unlock()
- state, err := m.billingStore.GetBillingState(m.orgID)
+ effectiveOrgID := m.effectiveOrgID()
+ state, err := m.billingStore.GetBillingState(effectiveOrgID)
if err != nil {
return fmt.Errorf("quickstart: read billing state: %w", err)
}
@@ -142,7 +170,7 @@ func (m *FileQuickstartCreditManager) GrantCredits() error {
return nil
}
- if err := m.billingStore.SaveBillingState(m.orgID, state); err != nil {
+ if err := m.billingStore.SaveBillingState(effectiveOrgID, state); err != nil {
return fmt.Errorf("quickstart: save billing state: %w", err)
}
diff --git a/internal/ai/quickstart_test.go b/internal/ai/quickstart_test.go
new file mode 100644
index 0000000000..c0c9f065e8
--- /dev/null
+++ b/internal/ai/quickstart_test.go
@@ -0,0 +1,52 @@
+package ai
+
+import (
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
+)
+
+func TestFileQuickstartCreditManager_OrgResolverUsesEffectiveBillingOrg(t *testing.T) {
+ baseDir := t.TempDir()
+ billingStore := config.NewFileBillingStore(baseDir)
+
+ state := pkglicensing.DefaultBillingState()
+ state.GrantQuickstartCredits()
+ if err := billingStore.SaveBillingState("default", state); err != nil {
+ t.Fatalf("SaveBillingState(default): %v", err)
+ }
+
+ mgr := NewFileQuickstartCreditManagerWithOrgResolver(
+ billingStore,
+ "t-tenant",
+ func() string { return "default" },
+ func() *config.AIConfig { return &config.AIConfig{Enabled: true} },
+ "t-tenant",
+ )
+
+ if !mgr.HasCredits() {
+ t.Fatal("expected quickstart credits through resolved billing org")
+ }
+ if got := mgr.CreditsRemaining(); got != pkglicensing.QuickstartCreditsTotal {
+ t.Fatalf("CreditsRemaining() = %d, want %d", got, pkglicensing.QuickstartCreditsTotal)
+ }
+ if err := mgr.ConsumeCredit(); err != nil {
+ t.Fatalf("ConsumeCredit(): %v", err)
+ }
+
+ defaultState, err := billingStore.GetBillingState("default")
+ if err != nil {
+ t.Fatalf("GetBillingState(default): %v", err)
+ }
+ if defaultState == nil || defaultState.QuickstartCreditsUsed != 1 {
+ t.Fatalf("expected resolved default billing state to consume one credit, got %#v", defaultState)
+ }
+ tenantState, err := billingStore.GetBillingState("t-tenant")
+ if err != nil {
+ t.Fatalf("GetBillingState(t-tenant): %v", err)
+ }
+ if tenantState != nil {
+ t.Fatalf("expected no tenant shadow billing state, got %#v", tenantState)
+ }
+}
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
index 0cc0e25b09..e64fd19d47 100644
--- a/internal/api/ai_handler.go
+++ b/internal/api/ai_handler.go
@@ -351,16 +351,23 @@ func (h *AIHandler) initTenantService(ctx context.Context, orgID string) AIServi
return nil
}
+ tenantCtx := context.WithValue(backgroundContext(ctx), OrgIDContextKey, orgID)
persistence, err := mtPersistence.GetPersistence(orgID)
if err != nil {
log.Warn().Str("orgID", orgID).Err(err).Msg("Failed to get persistence for AI service")
return nil
}
- // We need the config to get the data directory
- aiCfg, err := persistence.LoadAIConfig()
- if err != nil {
- log.Warn().Str("orgID", orgID).Err(err).Msg("Failed to load AI config for tenant service initialization")
+ // 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)
+ if aiCfg == nil {
+ log.Info().Str("orgID", orgID).Msg("AI config is nil for tenant service initialization")
+ return nil
+ }
+ if !aiCfg.Enabled {
+ log.Info().Str("orgID", orgID).Bool("enabled", aiCfg.Enabled).Msg("AI is disabled in tenant config")
+ return nil
}
dataDir := h.getDataDir(aiCfg, persistence.DataDir())
@@ -387,6 +394,7 @@ func (h *AIHandler) initTenantService(ctx context.Context, orgID string) AIServi
svc := newChatService(chatCfg)
if err := svc.Start(ctx); err != nil {
log.Error().Str("orgID", orgID).Err(err).Msg("Failed to start AI service for tenant")
+ return nil
}
return svc
diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.go
index 5e47a2a14c..61768e59c4 100644
--- a/internal/api/ai_handler_test.go
+++ b/internal/api/ai_handler_test.go
@@ -952,6 +952,11 @@ func TestGetService_MultiTenantInitAndCache(t *testing.T) {
tempDir := t.TempDir()
mtp := config.NewMultiTenantPersistence(tempDir)
+ persistence, err := mtp.GetPersistence("acme")
+ if err != nil {
+ t.Fatalf("GetPersistence(acme): %v", err)
+ }
+ saveEnabledTestAIConfig(t, persistence)
h := NewAIHandler(mtp, nil, nil)
mockSvc := new(MockAIService)
@@ -984,6 +989,11 @@ func TestGetService_MultiTenantUsesTenantReadState(t *testing.T) {
tempDir := t.TempDir()
mtp := config.NewMultiTenantPersistence(tempDir)
+ persistence, err := mtp.GetPersistence("acme")
+ if err != nil {
+ t.Fatalf("GetPersistence(acme): %v", err)
+ }
+ saveEnabledTestAIConfig(t, persistence)
mtm := monitoring.NewMultiTenantMonitor(&config.Config{}, mtp, nil)
t.Cleanup(mtm.Stop)
@@ -1019,6 +1029,92 @@ func TestGetService_MultiTenantUsesTenantReadState(t *testing.T) {
mockSvc.AssertExpectations(t)
}
+func TestGetService_HostedTenantAutoBootstrapsAndStartsService(t *testing.T) {
+ oldNewService := newChatService
+ defer func() { newChatService = oldNewService }()
+
+ tempDir := t.TempDir()
+ mtp := config.NewMultiTenantPersistence(tempDir)
+ _, err := mtp.GetPersistence("t-tenant")
+ if err != nil {
+ t.Fatalf("GetPersistence(t-tenant): %v", err)
+ }
+ seedHostedAIBillingState(t, mtp, "default")
+
+ h := NewAIHandler(mtp, nil, nil)
+ h.hostedMode = true
+
+ mockSvc := new(MockAIService)
+ mockSvc.On("Start", mock.Anything).Return(nil).Once()
+
+ var gotCfg chat.Config
+ newChatService = func(cfg chat.Config) AIService {
+ gotCfg = cfg
+ return mockSvc
+ }
+
+ ctx := context.WithValue(context.Background(), OrgIDContextKey, "t-tenant")
+ svc := h.GetService(ctx)
+ assert.Same(t, mockSvc, svc)
+
+ if gotCfg.AIConfig == nil {
+ t.Fatal("expected tenant chat service to receive hosted-aware AI config")
+ }
+ assert.True(t, gotCfg.AIConfig.Enabled)
+ assert.Equal(t, config.DefaultModelForProvider(config.AIProviderQuickstart), gotCfg.AIConfig.GetChatModel())
+
+ persistence, err := mtp.GetPersistence("t-tenant")
+ if err != nil {
+ t.Fatalf("GetPersistence(t-tenant): %v", err)
+ }
+ assert.True(t, persistence.HasAIConfig())
+
+ mockSvc.AssertExpectations(t)
+}
+
+func TestGetService_MultiTenantStartFailureDoesNotCacheDeadService(t *testing.T) {
+ oldNewService := newChatService
+ defer func() { newChatService = oldNewService }()
+
+ tempDir := t.TempDir()
+ mtp := config.NewMultiTenantPersistence(tempDir)
+ persistence, err := mtp.GetPersistence("acme")
+ if err != nil {
+ t.Fatalf("GetPersistence(acme): %v", err)
+ }
+ saveEnabledTestAIConfig(t, persistence)
+
+ h := NewAIHandler(mtp, nil, nil)
+
+ failedSvc := new(MockAIService)
+ failedSvc.On("Start", mock.Anything).Return(assert.AnError).Once()
+
+ runningSvc := new(MockAIService)
+ runningSvc.On("Start", mock.Anything).Return(nil).Once()
+
+ created := 0
+ newChatService = func(cfg chat.Config) AIService {
+ created++
+ if created == 1 {
+ return failedSvc
+ }
+ return runningSvc
+ }
+
+ ctx := context.WithValue(context.Background(), OrgIDContextKey, "acme")
+ svc := h.GetService(ctx)
+ assert.Nil(t, svc)
+ _, cached := h.services["acme"]
+ assert.False(t, cached, "failed tenant start should not be cached")
+
+ svc = h.GetService(ctx)
+ assert.Same(t, runningSvc, svc)
+ assert.Equal(t, 2, created)
+
+ failedSvc.AssertExpectations(t)
+ runningSvc.AssertExpectations(t)
+}
+
func TestSetServiceInitializer_AppliesToExistingServices(t *testing.T) {
h := NewAIHandler(nil, nil, nil)
legacySvc := new(MockAIService)
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index 9cf44668dd..4cf674871f 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -328,9 +328,20 @@ func (h *AISettingsHandler) GetAIService(ctx context.Context) *ai.Service {
// internally resolves org paths: base/orgs/<org>/billing.json.
billingBaseDir := mtPersistence.BaseDataDir()
billingStore := config.NewFileBillingStore(billingBaseDir)
- qsMgr := ai.NewFileQuickstartCreditManager(
+ qsMgr := ai.NewFileQuickstartCreditManagerWithOrgResolver(
billingStore,
orgID,
+ func() string {
+ if !h.hostedMode {
+ return orgID
+ }
+ _, effectiveOrgID, err := loadHostedEffectiveBillingState(billingStore, orgID)
+ if err != nil {
+ log.Warn().Str("orgID", orgID).Err(err).Msg("Failed to resolve hosted quickstart billing org fallback")
+ return orgID
+ }
+ return effectiveOrgID
+ },
func() *config.AIConfig {
cfg, _ := h.loadAIConfigForPersistence(context.Background(), orgID, persistence)
return cfg
diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.go
index 1826491ce8..97feb20cfd 100644
--- a/internal/api/ai_handlers_test.go
+++ b/internal/api/ai_handlers_test.go
@@ -221,6 +221,37 @@ func TestAISettingsHandler_GetHostedSettings_AutoBootstrapsQuickstart(t *testing
assert.True(t, persistence.HasAIConfig())
}
+func TestAISettingsHandler_GetHostedTenantSettings_InheritsDefaultHostedBillingState(t *testing.T) {
+ t.Setenv("PULSE_HOSTED_MODE", "true")
+
+ tmp := t.TempDir()
+ mtp := config.NewMultiTenantPersistence(tmp)
+ persistence, err := mtp.GetPersistence("t-tenant")
+ require.NoError(t, err)
+
+ seedHostedAIBillingState(t, mtp, "default")
+
+ handler := NewAISettingsHandler(mtp, nil, nil)
+ handler.defaultConfig = &config.Config{DataPath: tmp}
+
+ req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)
+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "t-tenant"))
+ rec := httptest.NewRecorder()
+ handler.HandleGetAISettings(rec, req)
+
+ require.Equal(t, http.StatusOK, rec.Code, "body=%s", rec.Body.String())
+
+ var resp AISettingsResponse
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp))
+ assert.True(t, resp.Enabled)
+ assert.True(t, resp.Configured)
+ assert.Equal(t, config.DefaultModelForProvider(config.AIProviderQuickstart), resp.Model)
+ assert.Equal(t, 25, resp.QuickstartCreditsTotal)
+ assert.Equal(t, 25, resp.QuickstartCreditsRemaining)
+ assert.True(t, resp.QuickstartCreditsAvailable)
+ assert.True(t, persistence.HasAIConfig())
+}
+
func TestAISettingsHandler_UpdateSettings_OpenRouterKeySetAndClear(t *testing.T) {
t.Parallel()
diff --git a/internal/api/ai_hosted_runtime.go b/internal/api/ai_hosted_runtime.go
index d4a1c93e5e..0ac8bc9da7 100644
--- a/internal/api/ai_hosted_runtime.go
+++ b/internal/api/ai_hosted_runtime.go
@@ -51,10 +51,9 @@ func ensureHostedAIQuickstartBillingState(billingBaseDir, orgID string) (*billin
if billingBaseDir == "" {
return nil, nil
}
- orgID = normalizeHostedEntitlementOrgID(orgID)
billingStore := config.NewFileBillingStore(billingBaseDir)
- state, err := billingStore.GetBillingState(orgID)
+ state, effectiveOrgID, err := loadHostedEffectiveBillingState(billingStore, orgID)
if err != nil || state == nil {
return state, err
}
@@ -64,7 +63,7 @@ func ensureHostedAIQuickstartBillingState(billingBaseDir, orgID string) (*billin
updated := normalizeBillingStateFromLicensing(state)
updated.GrantQuickstartCredits()
- if err := billingStore.SaveBillingState(orgID, updated); err != nil {
+ if err := billingStore.SaveBillingState(effectiveOrgID, updated); err != nil {
return nil, fmt.Errorf("save hosted Pulse Assistant quickstart billing state: %w", err)
}
return updated, nil
diff --git a/internal/api/ai_hosted_runtime_test.go b/internal/api/ai_hosted_runtime_test.go
index 7e53541674..6d169738e1 100644
--- a/internal/api/ai_hosted_runtime_test.go
+++ b/internal/api/ai_hosted_runtime_test.go
@@ -82,6 +82,44 @@ func TestLoadHostedAwareAIConfig_DoesNotOverrideExplicitAIConfig(t *testing.T) {
}
}
+func TestLoadHostedAwareAIConfig_HostedTenantFallsBackToDefaultBillingState(t *testing.T) {
+ baseDir := t.TempDir()
+ mtp := config.NewMultiTenantPersistence(baseDir)
+ persistence, err := mtp.GetPersistence("t-tenant")
+ if err != nil {
+ t.Fatalf("GetPersistence(t-tenant): %v", err)
+ }
+
+ seedHostedAIBillingState(t, mtp, "default")
+
+ loaded, err := loadHostedAwareAIConfig(true, mtp.BaseDataDir(), "t-tenant", persistence)
+ if err != nil {
+ t.Fatalf("loadHostedAwareAIConfig(): %v", err)
+ }
+ if loaded == nil || !loaded.Enabled {
+ t.Fatalf("expected hosted tenant AI config to auto-bootstrap, got %#v", loaded)
+ }
+ if !persistence.HasAIConfig() {
+ t.Fatal("expected hosted tenant AI bootstrap to persist tenant ai config")
+ }
+
+ billingStore := config.NewFileBillingStore(mtp.BaseDataDir())
+ defaultState, err := billingStore.GetBillingState("default")
+ if err != nil {
+ t.Fatalf("GetBillingState(default): %v", err)
+ }
+ if defaultState == nil || !defaultState.QuickstartCreditsGranted {
+ t.Fatal("expected hosted tenant AI bootstrap to reuse default hosted billing state")
+ }
+ tenantState, err := billingStore.GetBillingState("t-tenant")
+ if err != nil {
+ t.Fatalf("GetBillingState(t-tenant): %v", err)
+ }
+ if tenantState != nil && tenantState.SubscriptionState != "" {
+ t.Fatalf("expected tenant org to avoid shadow billing state, got %#v", tenantState)
+ }
+}
+
func TestAIHandlerStart_HostedAutoBootstrapStartsService(t *testing.T) {
oldNewService := newChatService
defer func() { newChatService = oldNewService }()
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 4e0857853d..ac0a8e1311 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -306,6 +306,70 @@ func TestContract_HostedAISettingsAutoBootstrapJSONSnapshot(t *testing.T) {
assertJSONSnapshot(t, rec.Body.Bytes(), want)
}
+func TestContract_HostedTenantAISettingsFallbackJSONSnapshot(t *testing.T) {
+ t.Setenv("PULSE_HOSTED_MODE", "true")
+
+ baseDir := t.TempDir()
+ mtp := config.NewMultiTenantPersistence(baseDir)
+ persistence, err := mtp.GetPersistence("t-tenant")
+ if err != nil {
+ t.Fatalf("GetPersistence(t-tenant): %v", err)
+ }
+
+ seedHostedAIBillingState(t, mtp, "default")
+
+ handler := NewAISettingsHandler(mtp, nil, nil)
+ handler.defaultConfig = &config.Config{DataPath: baseDir}
+
+ req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)
+ req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "t-tenant"))
+ 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())
+ }
+ if !persistence.HasAIConfig() {
+ t.Fatal("expected hosted tenant AI settings contract to persist tenant ai.enc bootstrap")
+ }
+
+ const want = `{
+ "enabled":true,
+ "model":"quickstart:minimax-2.5m",
+ "chat_model":"quickstart:minimax-2.5m",
+ "patrol_model":"quickstart:minimax-2.5m",
+ "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,
+ "use_proactive_thresholds":false,
+ "available_models":[],
+ "anthropic_configured":false,
+ "openai_configured":false,
+ "openrouter_configured":false,
+ "deepseek_configured":false,
+ "gemini_configured":false,
+ "ollama_configured":false,
+ "ollama_base_url":"http://localhost:11434",
+ "configured_providers":[],
+ "control_level":"read_only",
+ "protected_guests":[],
+ "discovery_enabled":false,
+ "quickstart_credits_total":25,
+ "quickstart_credits_used":0,
+ "quickstart_credits_remaining":25,
+ "quickstart_credits_available":true,
+ "using_quickstart":true
+ }`
+
+ assertJSONSnapshot(t, rec.Body.Bytes(), want)
+}
+
func TestContract_StripeWebhookHandlersUseCanonicalRuntimeDataDir(t *testing.T) {
envDir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", envDir)
diff --git a/internal/api/hosted_billing_state.go b/internal/api/hosted_billing_state.go
new file mode 100644
index 0000000000..e1bceb727e
--- /dev/null
+++ b/internal/api/hosted_billing_state.go
@@ -0,0 +1,36 @@
+package api
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+func loadHostedEffectiveBillingState(billingStore *config.FileBillingStore, orgID string) (*billingState, string, error) {
+ if billingStore == nil {
+ return nil, "", nil
+ }
+
+ effectiveOrgID := normalizeHostedEntitlementOrgID(orgID)
+ state, err := billingStore.GetBillingState(effectiveOrgID)
+ if err != nil {
+ return nil, "", fmt.Errorf("load hosted billing state for org %q: %w", effectiveOrgID, err)
+ }
+ if effectiveOrgID == hostedRelayBootstrapOrgID || hostedBillingStateHasSubscription(state) {
+ return state, effectiveOrgID, nil
+ }
+
+ defaultState, err := billingStore.GetBillingState(hostedRelayBootstrapOrgID)
+ if err != nil {
+ return nil, "", fmt.Errorf("load hosted default billing state fallback: %w", err)
+ }
+ if hostedBillingStateHasSubscription(defaultState) {
+ return defaultState, hostedRelayBootstrapOrgID, nil
+ }
+ return state, effectiveOrgID, nil
+}
+
+func hostedBillingStateHasSubscription(state *billingState) bool {
+ return state != nil && strings.TrimSpace(string(state.SubscriptionState)) != ""
+}