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
Improve MSP workspace setup onboarding
rcourtmand425f0266141
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex f515c8cafd..18bec54849 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -176,13 +176,20 @@ Pulse Account workspace summaries carry setup state as a backend-owned payloadcontract. Browser bootstrap and `/api/portal/dashboard` workspace entries mayinclude `setup_status` with only `ready`, `setup_path`, `install_agents`,`configure_outputs`, or `review`, plus optional setup evidence counts such as-`agent_count`, `alert_route_count`, and `report_schedule_count` when the-control plane has a canonical source for them. Until those counts are owned by-a backend source, active healthy workspaces must report `setup_path` rather-than pretending onboarding is complete. The browser may present that state as a-setup checklist and deep-link into tenant install/reporting surfaces, but it-must not infer cross-client readiness from health alone or mint tenant-owned-agent, alert, or report configuration from Pulse Account.+`agent_count`, `last_agent_seen_at`, `alert_route_count`, and+`report_schedule_count` when the control plane has a canonical source for+them. The canonical source is a read-only tenant-local setup facts reader, not+browser inference or portal-local state. Health review still wins first:+active workspaces with a failed latest health check report `review`. Healthy+or unchecked workspaces with no used non-expired `agent:report` token report+`install_agents`; workspaces with an agent but no enabled alert route or no+enabled report schedule report `configure_outputs`; only workspaces with at+least one reporting agent, enabled alert route, and enabled report schedule may+report `ready`. `setup_path` remains the fallback when no canonical setup facts+source is available. The browser may present that state as a setup checklist+and deep-link into tenant install/reporting surfaces, but it must not infer+cross-client readiness from health alone or mint tenant-owned agent, alert, or+report configuration from Pulse Account.1. `frontend-modern/src/api/agentProfiles.ts` shared with `agent-lifecycle`: the agent profiles frontend client is both an agent lifecycle control surface and a canonical API payload contract boundary.2. `frontend-modern/src/api/ai.ts` shared with `ai-runtime`: the AI frontend client is both an AI runtime control surface and a canonical API payload contract boundary.diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex 55da7ff052..1e953398db 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -329,6 +329,19 @@ or other self-hosted uncapped continuity plans.runtime; Pulse Account may deep-link to those tenant surfaces but must notmint workspace agent credentials or render cross-client monitoring state inthe account portal.+ Pulse Account also owns the provider-facing setup progression for client+ workspaces: after workspace creation the portal should select the created+ workspace, reveal the setup job, and preserve workspace/target context in+ install or reporting handoffs so an MSP can continue the first-run flow+ without guessing where to go next. That setup progression is control-plane+ guidance, not a second monitoring plane. Workspace readiness must be derived+ from read-only tenant-local setup facts without creating tenant config,+ encryption keys, migrations, agent credentials, alert routes, or report+ schedules as a side effect. The provider shell may show an unfinished-setup+ queue and fact counts for active workspaces, but `Ready` requires at least+ one reporting agent, one enabled alert route, and one enabled report+ schedule; a failed latest health check remains `Review` ahead of setup+ counts.Portal workspace payloads are live-workspace surfaces, not registry historydumps: tenants in `deleting` or `deleted` state must stay hidden from thebrowser bootstrap, `/api/portal/dashboard`, and workspace-detail API sodiff --git a/internal/cloudcp/portal/bootstrap.go b/internal/cloudcp/portal/bootstrap.goindex 44737e94cc..7576e9083f 100644--- a/internal/cloudcp/portal/bootstrap.go+++ b/internal/cloudcp/portal/bootstrap.go@@ -7,14 +7,18 @@ import ()type BootstrapWorkspace struct {- ID string `json:"id"`- DisplayName string `json:"display_name"`- State string `json:"state"`- Healthy bool `json:"healthy"`- HealthStatus string `json:"health_status"`- SetupStatus string `json:"setup_status,omitempty"`- LastHealthCheck string `json:"last_health_check,omitempty"`- CreatedAt string `json:"created_at"`+ ID string `json:"id"`+ DisplayName string `json:"display_name"`+ State string `json:"state"`+ Healthy bool `json:"healthy"`+ HealthStatus string `json:"health_status"`+ SetupStatus string `json:"setup_status,omitempty"`+ AgentCount *int `json:"agent_count,omitempty"`+ LastAgentSeenAt string `json:"last_agent_seen_at,omitempty"`+ AlertRouteCount *int `json:"alert_route_count,omitempty"`+ ReportScheduleCount *int `json:"report_schedule_count,omitempty"`+ LastHealthCheck string `json:"last_health_check,omitempty"`+ CreatedAt string `json:"created_at"`}type BootstrapMember struct {@@ -73,15 +77,23 @@ func BuildBootstrapDataWithSignupPath(authenticated bool, email string, accountsif workspace.LastHealthCheck != nil {lastHealthCheck = workspace.LastHealthCheck.UTC().Format(time.RFC3339)}+ lastAgentSeenAt := ""+ if workspace.LastAgentSeenAt != nil {+ lastAgentSeenAt = workspace.LastAgentSeenAt.UTC().Format(time.RFC3339)+ }workspaces = append(workspaces, BootstrapWorkspace{- ID: workspace.ID,- DisplayName: workspace.DisplayName,- State: workspace.State,- Healthy: workspace.Healthy,- HealthStatus: workspace.HealthStatus,- SetupStatus: workspace.SetupStatus,- LastHealthCheck: lastHealthCheck,- CreatedAt: workspace.CreatedAt.UTC().Format(time.RFC3339),+ ID: workspace.ID,+ DisplayName: workspace.DisplayName,+ State: workspace.State,+ Healthy: workspace.Healthy,+ HealthStatus: workspace.HealthStatus,+ SetupStatus: workspace.SetupStatus,+ AgentCount: workspace.AgentCount,+ LastAgentSeenAt: lastAgentSeenAt,+ AlertRouteCount: workspace.AlertRouteCount,+ ReportScheduleCount: workspace.ReportScheduleCount,+ LastHealthCheck: lastHealthCheck,+ CreatedAt: workspace.CreatedAt.UTC().Format(time.RFC3339),})}members := make([]BootstrapMember, 0, len(account.Members))diff --git a/internal/cloudcp/portal/dist/build_manifest.json b/internal/cloudcp/portal/dist/build_manifest.jsonindex 182b520a7d..1918fe7d4d 100644--- a/internal/cloudcp/portal/dist/build_manifest.json+++ b/internal/cloudcp/portal/dist/build_manifest.json@@ -1,5 +1,5 @@{- "source_hash": "2c71703848e7ca663ac54560164ea200ed01d13f2755242372eb9bc310bf0f66",+ "source_hash": "9063274971f801824ef7f87270abb7a358e7e7ba941a294d1557f8a4c12ce1e2","build_inputs": ["package.json","tsconfig.json",diff --git a/internal/cloudcp/portal/dist/portal_app.css b/internal/cloudcp/portal/dist/portal_app.cssindex d84bdb1b83..b02bbc9fcd 100644--- a/internal/cloudcp/portal/dist/portal_app.css+++ b/internal/cloudcp/portal/dist/portal_app.css@@ -546,7 +546,7 @@ header .logout-btn:hover,}.workspace-management-facts {display: grid;- grid-template-columns: repeat(3, 1fr);+ grid-template-columns: repeat(auto-fit, minmax(112px, 1fr));gap: 8px;}.workspace-management-fact {@@ -1546,6 +1546,82 @@ header .logout-btn:hover,.workspace-summary-link:hover {text-decoration: none;}+.workspace-setup-queue {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding-bottom: 16px;+ border-bottom: 1px solid var(--border);+}+.workspace-setup-queue-header {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 12px;+}+.workspace-setup-queue-header h3 {+ margin: 0;+ font-size: 14px;+ color: var(--ink);+}+.workspace-setup-queue-header p {+ margin: 3px 0 0;+ color: var(--ink-secondary);+ font-size: 12px;+}+.workspace-setup-queue-header > span {+ flex: 0 0 auto;+ color: var(--ink-secondary);+ font-size: 12px;+}+.workspace-setup-queue-list {+ display: flex;+ flex-direction: column;+ border: 1px solid var(--border-muted);+ border-radius: var(--radius);+ overflow: hidden;+ background: var(--bg);+}+.workspace-setup-queue-row {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto;+ gap: 12px;+ align-items: center;+ padding: 10px 12px;+ border-top: 1px solid var(--border-muted);+}+.workspace-setup-queue-row:first-child {+ border-top: none;+}+.workspace-setup-queue-main {+ display: grid;+ grid-template-columns: auto minmax(0, 1fr);+ gap: 10px;+ align-items: flex-start;+ min-width: 0;+}+.workspace-setup-queue-main strong,+.workspace-setup-queue-main span,+.workspace-setup-queue-main small {+ display: block;+}+.workspace-setup-queue-main strong {+ color: var(--ink);+ font-size: 13px;+}+.workspace-setup-queue-main span,+.workspace-setup-queue-main small {+ margin-top: 2px;+ color: var(--ink-secondary);+ font-size: 12px;+ overflow-wrap: anywhere;+}+.workspace-setup-queue-actions {+ display: flex;+ flex-wrap: wrap;+ justify-content: flex-end;+ gap: 8px;+}.account-panel-kicker,.billing-card-kicker,.account-eyebrow {@@ -1756,6 +1832,16 @@ header .logout-btn:hover,.workspace-summary-actions {justify-content: flex-start;}+ .workspace-setup-queue-header,+ .workspace-setup-queue-row {+ grid-template-columns: 1fr;+ }+ .workspace-setup-queue-header {+ flex-direction: column;+ }+ .workspace-setup-queue-actions {+ justify-content: flex-start;+ }.workspace-list-head {display: none;}diff --git a/internal/cloudcp/portal/dist/portal_app.js b/internal/cloudcp/portal/dist/portal_app.jsindex a1e22a4b19..42275b105a 100644--- a/internal/cloudcp/portal/dist/portal_app.js+++ b/internal/cloudcp/portal/dist/portal_app.js@@ -90,8 +90,6 @@return "";}function workspaceSetupState(workspace) {- var explicit = explicitSetupStatus(workspace);- if (explicit) return explicit;var state = String(workspace.state || "");var health = workspaceHealthState(workspace);if (state === "suspended" || state === "failed" || health === "unhealthy") return "review";@@ -109,6 +107,8 @@if (hasAgents && (!knowsAlertCount || hasAlerts) && (!knowsReportCount || hasReports)) {return "ready";}+ var explicit = explicitSetupStatus(workspace);+ if (explicit) return explicit;return "setup_path";}function workspaceSetupLabel(workspace) {@@ -177,6 +177,17 @@if (Number.isNaN(date.getTime())) return "Unknown";return date.toLocaleDateString(void 0, { month: "short", day: "numeric", year: "numeric" });}+ function hasKnownCount(value) {+ return typeof value === "number" && Number.isFinite(value);+ }+ function hasPositiveCount(value) {+ return hasKnownCount(value) && Number(value) > 0;+ }+ function setupCountLabel(value, singular, plural) {+ if (!hasKnownCount(value)) return "Unknown";+ var count = Number(value);+ return String(count) + " " + (count === 1 ? singular : plural);+ }function workspaceMeta(workspace) {var parts = [workspace.state];if (workspace.health_status) parts.push(workspace.health_status);@@ -228,12 +239,15 @@var summary = getElement("workspace-management-summary-" + account.id);var health = getElement("workspace-management-health-" + account.id);var setup = getElement("workspace-management-setup-" + account.id);+ var agents = getElement("workspace-management-agents-" + account.id);+ var alerts = getElement("workspace-management-alerts-" + account.id);+ var reports = getElement("workspace-management-reports-" + account.id);var created = getElement("workspace-management-created-" + account.id);var guidance = getElement("workspace-management-guidance-" + account.id);var checkCreated = getElement("workspace-management-check-created-" + account.id);- var checkOpen = getElement("workspace-management-check-open-" + account.id);var checkInstall = getElement("workspace-management-check-install-" + account.id);- var checkOutputs = getElement("workspace-management-check-outputs-" + account.id);+ var checkAlerts = getElement("workspace-management-check-alerts-" + account.id);+ var checkReports = getElement("workspace-management-check-reports-" + account.id);var checkAccess = getElement("workspace-management-check-access-" + account.id);var actionButton = getElement("workspace-management-action-" + account.id);var closeButton = getElement("workspace-management-close-" + account.id);@@ -285,27 +299,41 @@summary.textContent = workspaceStatusCopy(workspace);health.textContent = workspaceHealthLabel(workspace);setup.textContent = workspaceSetupLabel(workspace);+ if (agents) agents.textContent = setupCountLabel(workspace.agent_count, "agent", "agents");+ if (alerts) alerts.textContent = setupCountLabel(workspace.alert_route_count, "route", "routes");+ if (reports) reports.textContent = setupCountLabel(workspace.report_schedule_count, "schedule", "schedules");created.textContent = workspaceCreatedLabel(workspace);guidance.textContent = workspaceGuidanceCopy(workspace);var setupState = workspaceSetupState(workspace);var isActive = workspace.state === "active";+ var hasAgents = hasPositiveCount(workspace.agent_count) || setupState === "configure_outputs" || setupState === "ready";+ var hasAlertRoutes = hasPositiveCount(workspace.alert_route_count);+ var hasReportSchedules = hasPositiveCount(workspace.report_schedule_count);setChecklistStatus(checkCreated, workspace.state ? "done" : "pending", workspace.state ? "Done" : "Pending");- setChecklistStatus(checkOpen, isActive ? "available" : "blocked", isActive ? "Available" : "Blocked");- if (setupState === "ready" || setupState === "configure_outputs") {+ if (hasAgents) {setChecklistStatus(checkInstall, "done", "Done");} else if (setupState === "install_agents" || setupState === "setup_path") {setChecklistStatus(checkInstall, isActive ? "next" : "blocked", isActive ? "Next" : "Blocked");} else {setChecklistStatus(checkInstall, "blocked", "Review");}- if (setupState === "ready") {- setChecklistStatus(checkOutputs, "done", "Done");- } else if (setupState === "configure_outputs") {- setChecklistStatus(checkOutputs, "next", "Next");+ if (hasAlertRoutes) {+ setChecklistStatus(checkAlerts, "done", "Done");} else if (setupState === "review") {- setChecklistStatus(checkOutputs, "blocked", "Review");+ setChecklistStatus(checkAlerts, "blocked", "Review");+ } else if (isActive && hasAgents) {+ setChecklistStatus(checkAlerts, "next", "Next");} else {- setChecklistStatus(checkOutputs, "pending", "Pending");+ setChecklistStatus(checkAlerts, "pending", "Pending");+ }+ if (hasReportSchedules) {+ setChecklistStatus(checkReports, "done", "Done");+ } else if (setupState === "review") {+ setChecklistStatus(checkReports, "blocked", "Review");+ } else if (isActive && hasAgents && hasAlertRoutes) {+ setChecklistStatus(checkReports, "next", "Next");+ } else {+ setChecklistStatus(checkReports, "pending", "Pending");}setChecklistStatus(checkAccess, "available", "Available");actionButton.textContent = workspaceActionLabel(workspace);@@ -1108,6 +1136,20 @@}return true;};+ var findWorkspaceIDByName = function(accountID, displayName) {+ var bootstrap = deps.store.getBootstrap();+ var accounts = Array.isArray(bootstrap.accounts) ? bootstrap.accounts : [];+ for (var i = 0; i < accounts.length; i += 1) {+ if (accounts[i].id !== accountID) continue;+ var workspaces = Array.isArray(accounts[i].workspaces) ? accounts[i].workspaces : [];+ for (var j = 0; j < workspaces.length; j += 1) {+ if (workspaces[j].display_name === displayName) {+ return workspaces[j].id;+ }+ }+ }+ return "";+ };var renderAccountRuntime = function() {var bootstrap = deps.store.getBootstrap();renderAccountUI(deps.store.getAccountState(), bootstrap.accounts || [], bootstrap.account_api_base_path || "");@@ -1201,7 +1243,7 @@beginMutationState(entry.createWorkspace);});try {- await deps.api.createWorkspace(accountID, { display_name: name });+ var created = await deps.api.createWorkspace(accountID, { display_name: name });if (!await refreshOrRedirect()) {deps.store.updateAccountState(function(accountState) {var entry = ensurePortalAccountUIEntry(accountState, accountID);@@ -1209,12 +1251,20 @@}, { notify: false });return;}+ var createdWorkspaceID = created && typeof created.id === "string" ? created.id : "";+ if (!createdWorkspaceID) {+ createdWorkspaceID = findWorkspaceIDByName(accountID, name);+ }deps.store.updateAccountState(function(accountState) {var entry = ensurePortalAccountUIEntry(accountState, accountID);entry.addWorkspaceOpen = false;+ entry.selectedWorkspaceID = createdWorkspaceID;+ entry.accessVisible = false;+ entry.activeAccessJob = "";succeedMutationState(entry.createWorkspace);});- deps.showToast("Workspace created!");+ revealElementWhenReady("workspace-management-" + accountID);+ deps.showToast("Workspace created. Finish setup next.");} catch (error) {var message = error instanceof Error ? error.message : "Failed to create workspace.";deps.store.updateAccountState(function(accountState) {@@ -2651,6 +2701,17 @@}return results;}+ function setupFactCountLabel(value, singular, plural) {+ if (typeof value !== "number" || !Number.isFinite(value)) return "Unknown " + plural;+ return String(value) + " " + (value === 1 ? singular : plural);+ }+ function workspaceSetupFactsLine(workspace) {+ return [+ setupFactCountLabel(workspace.agent_count, "agent", "agents"),+ setupFactCountLabel(workspace.alert_route_count, "alert route", "alert routes"),+ setupFactCountLabel(workspace.report_schedule_count, "report schedule", "report schedules")+ ].join(" \xB7 ");+ }function workspaceSummaryContext(entry, includeAccountName, note) {if (!includeAccountName) return note;return entry.account.name + " \xB7 " + note;@@ -2775,6 +2836,33 @@var decision = renderWorkspaceSummaryDecision(accounts, entries, accountAPIBasePath, showSelfHostedCommercial);return '<section class="workspace-summary-inline"><div class="workspace-summary-inline-copy"><p><strong>Next:</strong> ' + escapeHTML(decision.title) + "</p><p>" + escapeHTML(decision.description) + '</p></div><div class="workspace-summary-actions">' + decision.primaryAction + decision.secondaryAction + "</div></section>";}+ function renderWorkspaceSetupQueueAction(entry, accountAPIBasePath) {+ var setup = workspaceSetupState(entry.workspace);+ if (setup === "configure_outputs") {+ return renderWorkspaceReportingHandoffForm(+ entry.account.id,+ entry.workspace.id,+ accountAPIBasePath,+ "Configure outputs",+ "btn-primary btn-compact"+ );+ }+ return renderWorkspaceInstallHandoffForm(+ entry.account.id,+ entry.workspace.id,+ accountAPIBasePath,+ setup === "install_agents" ? "Install agents" : "Open setup",+ "btn-primary btn-compact"+ );+ }+ function renderWorkspaceSetupQueue(entries, accountAPIBasePath) {+ var setupNeeded = setupNeededWorkspaceEntries(entries);+ if (!setupNeeded.length) return "";+ var visible = setupNeeded.slice(0, 5);+ return '<section class="workspace-setup-queue" aria-label="Unfinished workspace setup"><div class="workspace-setup-queue-header"><div><h3>Unfinished setup</h3><p>Client workspaces stay here until agents, alert routing, and reports are in place.</p></div><span>' + escapeHTML(setupNeededWorkspaceChipLabel(setupNeeded.length)) + '</span></div><div class="workspace-setup-queue-list">' + visible.map(function(entry) {+ return '<article class="workspace-setup-queue-row"><div class="workspace-setup-queue-main">' + setupBadgeHTML(entry.workspace) + "<div><strong>" + escapeHTML(entry.workspace.display_name) + "</strong><span>" + escapeHTML(entry.account.name + " \xB7 " + workspaceSetupNextStep(entry.workspace)) + "</span><small>" + escapeHTML(workspaceSetupFactsLine(entry.workspace)) + '</small></div></div><div class="workspace-setup-queue-actions">' + renderWorkspaceSetupQueueAction(entry, accountAPIBasePath) + (entry.account.can_manage ? '<button type="button" class="btn-secondary btn-compact" data-action="select-workspace" data-account-id="' + escapeAttr(entry.account.id) + '" data-workspace-id="' + escapeAttr(entry.workspace.id) + '">Checklist</button>' : renderWorkspaceHandoffForm(entry.account.id, entry.workspace.id, accountAPIBasePath, "Open workspace")) + "</div></article>";+ }).join("") + "</div></section>";+ }function workspaceSectionHeaderCopy(accounts, entries) {var canManageAnyWorkspace = accounts.some(function(account) {return account.can_manage;@@ -2791,7 +2879,7 @@var accounts = Array.isArray(context.bootstrap.accounts) ? context.bootstrap.accounts : [];var entries = collectWorkspaceSummaryEntries(accounts);var showSelfHostedCommercial = hasSelfHostedCommercial(context.bootstrap);- return '<section class="workspace-summary-shell"><div class="portal-page-header"><h2>Workspaces</h2><p>' + escapeHTML(workspaceSectionHeaderCopy(accounts, entries)) + "</p></div>" + renderFactLine("workspace-summary-facts", renderWorkspaceSummaryFacts(accounts, entries)) + renderWorkspaceSummaryInline(accounts, entries, context.accountAPIBasePath, showSelfHostedCommercial) + "</section>";+ return '<section class="workspace-summary-shell"><div class="portal-page-header"><h2>Workspaces</h2><p>' + escapeHTML(workspaceSectionHeaderCopy(accounts, entries)) + "</p></div>" + renderFactLine("workspace-summary-facts", renderWorkspaceSummaryFacts(accounts, entries)) + renderWorkspaceSummaryInline(accounts, entries, context.accountAPIBasePath, showSelfHostedCommercial) + renderWorkspaceSetupQueue(entries, context.accountAPIBasePath) + "</section>";}function renderNoHostedWorkspacesSection() {return '<section class="account-content-panel account-content-panel-workspaces"><div class="empty-state"><p>No hosted workspaces are attached to this account. Use Billing for self-hosted subscriptions and licenses.</p></div></section>';@@ -2815,7 +2903,7 @@if (account.kind === "msp") {addWorkspaceForm = '<div class="add-workspace-form" id="add-ws-form-' + escapeAttr(account.id) + '"><label for="ws-name-' + escapeAttr(account.id) + '">Workspace name (for example, a client name)</label><input type="text" id="ws-name-' + escapeAttr(account.id) + '" placeholder="Acme Corp" maxlength="80" autocomplete="off"><div class="form-actions"><button type="button" class="btn-primary" data-action="create-workspace" data-account-id="' + escapeAttr(account.id) + '">Create workspace</button><button type="button" class="btn-secondary" data-action="toggle-add-workspace" data-account-id="' + escapeAttr(account.id) + '">Cancel</button><div class="spinner" id="ws-spinner-' + escapeAttr(account.id) + '" hidden></div></div></div>';}- workspaceManagement = '<section class="workspace-management-panel workspace-management-panel-idle" id="workspace-management-' + escapeAttr(account.id) + '" hidden><div class="workspace-management-header"><div><h3>Workspace setup checklist</h3><p>Finish the client setup steps without mixing client data across workspaces.</p></div><button type="button" class="btn-secondary btn-compact" id="workspace-management-close-' + escapeAttr(account.id) + '" data-action="clear-workspace-selection" data-account-id="' + escapeAttr(account.id) + '">Close panel</button></div><div class="workspace-management-empty" id="workspace-management-empty-' + escapeAttr(account.id) + '"><div class="workspace-management-empty-shell"><div class="workspace-management-empty-actions-card"><div class="workspace-management-empty-actions-copy"><h4>Create a workspace</h4><p>Add a new hosted workspace for a customer or operating boundary.</p></div>' + addWorkspaceForm + '</div><div class="workspace-management-empty-note">Access changes stay in Access. Billing changes stay in Billing.</div></div></div><div class="workspace-management-content" id="workspace-management-content-' + escapeAttr(account.id) + '" hidden><div class="workspace-management-meta" id="workspace-management-meta-' + escapeAttr(account.id) + '"></div><h4 id="workspace-management-title-' + escapeAttr(account.id) + '"></h4><p class="workspace-management-summary" id="workspace-management-summary-' + escapeAttr(account.id) + '"></p><div class="workspace-management-facts"><div class="workspace-management-fact"><span>Health</span><strong id="workspace-management-health-' + escapeAttr(account.id) + '"></strong></div><div class="workspace-management-fact"><span>Setup</span><strong id="workspace-management-setup-' + escapeAttr(account.id) + '"></strong></div><div class="workspace-management-fact"><span>Created</span><strong id="workspace-management-created-' + escapeAttr(account.id) + '"></strong></div></div><div class="workspace-management-guidance" id="workspace-management-guidance-' + escapeAttr(account.id) + '"></div><div class="workspace-setup-checklist" aria-label="Workspace setup checklist"><div class="workspace-setup-step workspace-setup-step-created"><span class="workspace-setup-status" id="workspace-management-check-created-' + escapeAttr(account.id) + '"></span><div><strong>Workspace created</strong><span>This client has a separate account boundary.</span></div></div><div class="workspace-setup-step"><span class="workspace-setup-status" id="workspace-management-check-open-' + escapeAttr(account.id) + '"></span><div><strong>Open the workspace</strong><span>Work inside the selected client boundary.</span></div></div><div class="workspace-setup-step"><span class="workspace-setup-status" id="workspace-management-check-install-' + escapeAttr(account.id) + '"></span><div><strong>Install the first agent</strong><span>Use the workspace-bound install path so data lands in this client.</span></div></div><div class="workspace-setup-step"><span class="workspace-setup-status" id="workspace-management-check-outputs-' + escapeAttr(account.id) + '"></span><div><strong>Configure alerts and reports</strong><span>Keep notifications and reports scoped to this client.</span></div></div><div class="workspace-setup-step"><span class="workspace-setup-status" id="workspace-management-check-access-' + escapeAttr(account.id) + '"></span><div><strong>Review access</strong><span>Invite provider staff or client users from Access.</span></div></div></div><div class="workspace-management-next-steps" id="workspace-management-next-steps-' + escapeAttr(account.id) + '"><div class="workspace-next-step"><div><strong>Open workspace</strong><span>Work inside this client boundary.</span></div><form method="POST" id="workspace-management-open-form-' + escapeAttr(account.id) + '"><button type="submit" class="btn-primary btn-compact" id="workspace-management-open-' + escapeAttr(account.id) + '">Open workspace</button></form></div><div class="workspace-next-step"><div><strong>Install agents</strong><span>Open the workspace-bound install commands.</span></div><form method="POST" id="workspace-management-install-form-' + escapeAttr(account.id) + '"><button type="submit" class="btn-secondary btn-compact" id="workspace-management-install-' + escapeAttr(account.id) + '">Install agents</button></form></div><div class="workspace-next-step workspace-next-step-readonly"><div><strong>Alerts and reports</strong><span>Alerts and performance reports stay inside the client workspace.</span></div><form method="POST" id="workspace-management-reporting-form-' + escapeAttr(account.id) + '"><button type="submit" class="btn-secondary btn-compact" id="workspace-management-reporting-' + escapeAttr(account.id) + '">Open reports</button></form></div><div class="workspace-next-step workspace-next-step-readonly"><div><strong>Access</strong><span>Invite people or adjust roles from the account access boundary.</span></div><button type="button" class="btn-secondary btn-compact" data-shell-action="activate-section" data-shell-section="access">Open Access</button></div></div><div class="workspace-management-actions"><button type="button" class="btn-danger" id="workspace-management-action-' + escapeAttr(account.id) + '" data-action="workspace-action" data-account-id="' + escapeAttr(account.id) + '">Manage workspace</button></div></div></section>';+ workspaceManagement = '<section class="workspace-management-panel workspace-management-panel-idle" id="workspace-management-' + escapeAttr(account.id) + '" hidden><div class="workspace-management-header"><div><h3>Workspace setup checklist</h3><p>Finish the client setup steps without mixing client data across workspaces.</p></div><button type="button" class="btn-secondary btn-compact" id="workspace-management-close-' + escapeAttr(account.id) + '" data-action="clear-workspace-selection" data-account-id="' + escapeAttr(account.id) + '">Close panel</button></div><div class="workspace-management-empty" id="workspace-management-empty-' + escapeAttr(account.id) + '"><div class="workspace-management-empty-shell"><div class="workspace-management-empty-actions-card"><div class="workspace-management-empty-actions-copy"><h4>Create a workspace</h4><p>Add a new hosted workspace for a customer or operating boundary.</p></div>' + addWorkspaceForm + '</div><div class="workspace-management-empty-note">Access changes stay in Access. Billing changes stay in Billing.</div></div></div><div class="workspace-management-content" id="workspace-management-content-' + escapeAttr(account.id) + '" hidden><div class="workspace-management-meta" id="workspace-management-meta-' + escapeAttr(account.id) + '"></div><h4 id="workspace-management-title-' + escapeAttr(account.id) + '"></h4><p class="workspace-management-summary" id="workspace-management-summary-' + escapeAttr(account.id) + '"></p><div class="workspace-management-facts"><div class="workspace-management-fact"><span>Health</span><strong id="workspace-management-health-' + escapeAttr(account.id) + '"></strong></div><div class="workspace-management-fact"><span>Setup</span><strong id="workspace-management-setup-' + escapeAttr(account.id) + '"></strong></div><div class="workspace-management-fact"><span>Agents</span><strong id="workspace-management-agents-' + escapeAttr(account.id) + '"></strong></div><div class="workspace-management-fact"><span>Alert routes</span><strong id="workspace-management-alerts-' + escapeAttr(account.id) + '"></strong></div><div class="workspace-management-fact"><span>Report schedules</span><strong id="workspace-management-reports-' + escapeAttr(account.id) + '"></strong></div><div class="workspace-management-fact"><span>Created</span><strong id="workspace-management-created-' + escapeAttr(account.id) + '"></strong></div></div><div class="workspace-management-guidance" id="workspace-management-guidance-' + escapeAttr(account.id) + '"></div><div class="workspace-setup-checklist" aria-label="Workspace setup checklist"><div class="workspace-setup-step workspace-setup-step-created"><span class="workspace-setup-status" id="workspace-management-check-created-' + escapeAttr(account.id) + '"></span><div><strong>Workspace created</strong><span>This client has a separate account boundary.</span></div></div><div class="workspace-setup-step"><span class="workspace-setup-status" id="workspace-management-check-install-' + escapeAttr(account.id) + '"></span><div><strong>Install the first agent</strong><span>Use the workspace-bound install path so data lands in this client.</span></div></div><div class="workspace-setup-step"><span class="workspace-setup-status" id="workspace-management-check-alerts-' + escapeAttr(account.id) + '"></span><div><strong>Configure alert routes</strong><span>Keep notifications scoped to this client.</span></div></div><div class="workspace-setup-step"><span class="workspace-setup-status" id="workspace-management-check-reports-' + escapeAttr(account.id) + '"></span><div><strong>Schedule reports</strong><span>Send client performance reports from this workspace.</span></div></div><div class="workspace-setup-step"><span class="workspace-setup-status" id="workspace-management-check-access-' + escapeAttr(account.id) + '"></span><div><strong>Review access</strong><span>Invite provider staff or client users from Access.</span></div></div></div><div class="workspace-management-next-steps" id="workspace-management-next-steps-' + escapeAttr(account.id) + '"><div class="workspace-next-step"><div><strong>Open workspace</strong><span>Work inside this client boundary.</span></div><form method="POST" id="workspace-management-open-form-' + escapeAttr(account.id) + '"><button type="submit" class="btn-primary btn-compact" id="workspace-management-open-' + escapeAttr(account.id) + '">Open workspace</button></form></div><div class="workspace-next-step"><div><strong>Install agents</strong><span>Open the workspace-bound install commands.</span></div><form method="POST" id="workspace-management-install-form-' + escapeAttr(account.id) + '"><button type="submit" class="btn-secondary btn-compact" id="workspace-management-install-' + escapeAttr(account.id) + '">Install agents</button></form></div><div class="workspace-next-step workspace-next-step-readonly"><div><strong>Alerts and reports</strong><span>Alerts and performance reports stay inside the client workspace.</span></div><form method="POST" id="workspace-management-reporting-form-' + escapeAttr(account.id) + '"><button type="submit" class="btn-secondary btn-compact" id="workspace-management-reporting-' + escapeAttr(account.id) + '">Open reports</button></form></div><div class="workspace-next-step workspace-next-step-readonly"><div><strong>Access</strong><span>Invite people or adjust roles from the account access boundary.</span></div><button type="button" class="btn-secondary btn-compact" data-shell-action="activate-section" data-shell-section="access">Open Access</button></div></div><div class="workspace-management-actions"><button type="button" class="btn-danger" id="workspace-management-action-' + escapeAttr(account.id) + '" data-action="workspace-action" data-account-id="' + escapeAttr(account.id) + '">Manage workspace</button></div></div></section>';}var workspaceHTML = workspaces.length ? '<div class="workspace-list-wrap" id="' + escapeAttr(workspaceListAnchorID(account.id)) + '">' + (workspaceHeaderActions ? '<div class="workspace-list-toolbar">' + workspaceHeaderActions + "</div>" : "") + '<div class="workspace-list-head"><span>Workspace</span><span>Setup</span><span>Health</span><span>Actions</span></div><div class="workspace-list">' + workspaces.map(function(workspace) {return renderWorkspaceCard(account, workspace, accountAPIBasePath);diff --git a/internal/cloudcp/portal/frontend/dev.mjs b/internal/cloudcp/portal/frontend/dev.mjsindex 4d252bdaae..aded564820 100644--- a/internal/cloudcp/portal/frontend/dev.mjs+++ b/internal/cloudcp/portal/frontend/dev.mjs@@ -145,6 +145,18 @@ function buildScenarioTemplate(name) {report_schedule_count: 0,created_at: iso('2026-03-21T10:00:00Z'),},+ {+ id: 'ws_gamma',+ display_name: 'MSP Test Workspace C',+ state: 'active',+ healthy: true,+ health_status: 'healthy',+ setup_status: 'install_agents',+ agent_count: 0,+ alert_route_count: 0,+ report_schedule_count: 0,+ created_at: iso('2026-03-22T10:00:00Z'),+ },],members: [{ email: '[email protected]', role: 'owner', user_id: 'u_owner' },@@ -313,6 +325,7 @@ function buildPreviewWorkspaceHTML(bootstrap, workspaceID, targetPath, scenario): targetPath === '/settings/support/reporting'? 'Configure scheduled reports and alert routing for this client workspace before treating onboarding as complete.': 'Use this workspace for client-specific monitoring work after the Pulse Account handoff.';+ const installCommand = 'pulse-agent install --workspace ' + workspaceID + ' --name <agent-name>';return '<!DOCTYPE html>' +'<html lang="en">' +'<head>' +@@ -334,7 +347,12 @@ function buildPreviewWorkspaceHTML(bootstrap, workspaceID, targetPath, scenario)'.fact strong{display:block;margin-top:2px;font-size:13px}' +'.task{border:1px solid #eaecf0;border-radius:6px;background:#f8fafc;padding:14px;margin:16px 0}' +'.task code{display:block;margin:8px 0 0;padding:10px;border:1px solid #d0d5dd;border-radius:6px;background:#fff;color:#101828;white-space:pre-wrap;overflow-wrap:anywhere;font-size:12px}' ++ '.steps{display:grid;gap:8px;margin:16px 0}' ++ '.step{display:grid;grid-template-columns:28px minmax(0,1fr);gap:10px;padding:10px;border:1px solid #eaecf0;border-radius:6px;background:#fff}' ++ '.step b{display:flex;align-items:center;justify-content:center;width:22px;height:22px;border-radius:999px;background:#eef4ff;color:#155eef;font-size:12px}' ++ '.step strong{display:block;font-size:13px}.step span{display:block;margin-top:2px;color:#667085;font-size:12px;line-height:1.45}' +'.button{display:inline-flex;align-items:center;min-height:34px;padding:0 12px;border-radius:6px;background:#155eef;color:#fff;text-decoration:none;font-size:14px;font-weight:600}' ++ '.copy-button{display:inline-flex;align-items:center;min-height:32px;margin-top:10px;padding:0 10px;border:1px solid #d0d5dd;border-radius:6px;background:#fff;color:#344054;font:inherit;font-size:13px;font-weight:600;cursor:pointer}' +'.secondary{background:#fff;color:#344054;border:1px solid #d0d5dd}' +'.actions{display:flex;gap:8px;flex-wrap:wrap}' +'@media(max-width:640px){.facts{grid-template-columns:1fr}}' +@@ -356,11 +374,17 @@ function buildPreviewWorkspaceHTML(bootstrap, workspaceID, targetPath, scenario)'<strong>' + escapeHTML(targetLabel) + '</strong>' +'<p>' + escapeHTML(taskCopy) + '</p>' +(targetPath === '/settings/infrastructure?add=linux-host'- ? '<code>pulse-agent install --workspace ' + escapeHTML(workspaceID) + ' --name <agent-name></code>'+ ? '<code id="preview-install-command">' + escapeHTML(installCommand) + '</code><button class="copy-button" type="button" onclick="navigator.clipboard&&navigator.clipboard.writeText(document.getElementById(\'preview-install-command\').textContent)">Copy command</button>': '') +'</div>' ++ '<div class="steps" aria-label="Workspace setup flow">' ++ '<div class="step"><b>1</b><div><strong>Install agents in this workspace</strong><span>The handoff keeps the agent command tied to this client boundary.</span></div></div>' ++ '<div class="step"><b>2</b><div><strong>Confirm data is arriving</strong><span>Pulse Account marks the workspace as installed only after an agent-scoped token is used.</span></div></div>' ++ '<div class="step"><b>3</b><div><strong>Add alert routes and reports</strong><span>Alerts and scheduled reports are part of the setup state, not optional polish.</span></div></div>' ++ '</div>' +'<div class="actions">' +'<a class="button" href="' + escapeHTML(portalWorkspaceURL) + '">Back to workspace row</a>' ++ '<a class="button secondary" href="' + escapeHTML(portalURL + '#workspace-management-' + accountID) + '">Refresh setup state</a>' +'<a class="button secondary" href="' + escapeHTML(portalURL) + '">Pulse Account home</a>' +'</div>' +'</section>' +@@ -581,7 +605,7 @@ function routeAccountAPI(request, response, url, bootstrap, scenario) {return;}account.workspaces = account.workspaces || [];- account.workspaces.push({+ const workspace = {id: 'ws_' + Math.random().toString(36).slice(2, 10),display_name: displayName,state: 'active',@@ -592,8 +616,9 @@ function routeAccountAPI(request, response, url, bootstrap, scenario) {alert_route_count: 0,report_schedule_count: 0,created_at: iso(new Date()),- });- sendJSON(response, 200, { ok: true });+ };+ account.workspaces.push(workspace);+ sendJSON(response, 201, workspace);}).catch(function() {sendJSON(response, 400, { error: 'Invalid JSON.' });});diff --git a/internal/cloudcp/portal/frontend/src/account_runtime.test.ts b/internal/cloudcp/portal/frontend/src/account_runtime.test.tsindex bb256dcf9f..9f17c3f8b9 100644--- a/internal/cloudcp/portal/frontend/src/account_runtime.test.ts+++ b/internal/cloudcp/portal/frontend/src/account_runtime.test.ts@@ -76,7 +76,7 @@ describe('account runtime', function() {});it('creates a workspace through the managed account action flow', async function() {- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ tenant_id: 't_123' })));+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ id: 'ws_new' })));document.body.innerHTML ='<div id="add-ws-form-acct_1" class="add-workspace-form">' +@@ -102,8 +102,9 @@ describe('account runtime', function() {}));expect(deps.refreshBootstrap).toHaveBeenCalled();- expect(deps.showToast).toHaveBeenCalledWith('Workspace created!');+ expect(deps.showToast).toHaveBeenCalledWith('Workspace created. Finish setup next.');expect(deps.store.getAccountState().byAccountID.acct_1.addWorkspaceOpen).toBe(false);+ expect(deps.store.getAccountState().byAccountID.acct_1.selectedWorkspaceID).toBe('ws_new');expect(deps.store.getAccountState().byAccountID.acct_1.createWorkspace.pending).toBe(false);expect((document.getElementById('ws-spinner-acct_1') as HTMLElement).hidden).toBe(true);});diff --git a/internal/cloudcp/portal/frontend/src/account_runtime.ts b/internal/cloudcp/portal/frontend/src/account_runtime.tsindex 7e1c5a3b42..751824d06d 100644--- a/internal/cloudcp/portal/frontend/src/account_runtime.ts+++ b/internal/cloudcp/portal/frontend/src/account_runtime.ts@@ -66,6 +66,21 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntimereturn true;};+ var findWorkspaceIDByName = function(accountID: string, displayName: string): string {+ var bootstrap = deps.store.getBootstrap();+ var accounts = Array.isArray(bootstrap.accounts) ? bootstrap.accounts : [];+ for (var i = 0; i < accounts.length; i += 1) {+ if (accounts[i].id !== accountID) continue;+ var workspaces = Array.isArray(accounts[i].workspaces) ? accounts[i].workspaces : [];+ for (var j = 0; j < workspaces.length; j += 1) {+ if (workspaces[j].display_name === displayName) {+ return workspaces[j].id;+ }+ }+ }+ return '';+ };+var renderAccountRuntime = function(): void {var bootstrap = deps.store.getBootstrap();renderAccountUIState(deps.store.getAccountState(), bootstrap.accounts || [], bootstrap.account_api_base_path || '');@@ -165,7 +180,7 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntimebeginMutationState(entry.createWorkspace);});try {- await deps.api.createWorkspace(accountID, { display_name: name });+ var created = await deps.api.createWorkspace(accountID, { display_name: name });if (!await refreshOrRedirect()) {deps.store.updateAccountState(function(accountState) {var entry = ensurePortalAccountUIEntry(accountState, accountID);@@ -173,12 +188,20 @@ export function installAccountRuntime(deps: AccountRuntimeDeps): AccountRuntime}, { notify: false });return;}+ var createdWorkspaceID = created && typeof created.id === 'string' ? created.id : '';+ if (!createdWorkspaceID) {+ createdWorkspaceID = findWorkspaceIDByName(accountID, name);+ }deps.store.updateAccountState(function(accountState) {var entry = ensurePortalAccountUIEntry(accountState, accountID);entry.addWorkspaceOpen = false;+ entry.selectedWorkspaceID = createdWorkspaceID;+ entry.accessVisible = false;+ entry.activeAccessJob = '';succeedMutationState(entry.createWorkspace);});- deps.showToast('Workspace created!');+ revealElementWhenReady('workspace-management-' + accountID);+ deps.showToast('Workspace created. Finish setup next.');} catch (error) {var message = error instanceof Error ? error.message : 'Failed to create workspace.';deps.store.updateAccountState(function(accountState) {diff --git a/internal/cloudcp/portal/frontend/src/account_view.test.ts b/internal/cloudcp/portal/frontend/src/account_view.test.tsindex af014f20b6..63f7084dbb 100644--- a/internal/cloudcp/portal/frontend/src/account_view.test.ts+++ b/internal/cloudcp/portal/frontend/src/account_view.test.ts@@ -75,12 +75,15 @@ describe('account view', function() {'<p id="workspace-management-summary-' + accountID + '"></p>' +'<div id="workspace-management-health-' + accountID + '"></div>' +'<div id="workspace-management-setup-' + accountID + '"></div>' ++ '<div id="workspace-management-agents-' + accountID + '"></div>' ++ '<div id="workspace-management-alerts-' + accountID + '"></div>' ++ '<div id="workspace-management-reports-' + accountID + '"></div>' +'<div id="workspace-management-created-' + accountID + '"></div>' +'<div id="workspace-management-guidance-' + accountID + '"></div>' +'<span id="workspace-management-check-created-' + accountID + '"></span>' +- '<span id="workspace-management-check-open-' + accountID + '"></span>' +'<span id="workspace-management-check-install-' + accountID + '"></span>' +- '<span id="workspace-management-check-outputs-' + accountID + '"></span>' ++ '<span id="workspace-management-check-alerts-' + accountID + '"></span>' ++ '<span id="workspace-management-check-reports-' + accountID + '"></span>' +'<span id="workspace-management-check-access-' + accountID + '"></span>' +'<form id="workspace-management-open-form-' + accountID + '"><button id="workspace-management-open-' + accountID + '"></button></form>' +'<form id="workspace-management-install-form-' + accountID + '"><button id="workspace-management-install-' + accountID + '"></button></form>' +@@ -304,8 +307,12 @@ describe('account view', function() {expect(document.getElementById('workspace-management-title-acct_1')?.textContent).toContain('Alpha Workspace');expect(document.getElementById('workspace-management-health-acct_1')?.textContent).toContain('Healthy');expect(document.getElementById('workspace-management-setup-acct_1')?.textContent).toContain('Setup path');+ expect(document.getElementById('workspace-management-agents-acct_1')?.textContent).toContain('Unknown');+ expect(document.getElementById('workspace-management-alerts-acct_1')?.textContent).toContain('Unknown');+ expect(document.getElementById('workspace-management-reports-acct_1')?.textContent).toContain('Unknown');expect(document.getElementById('workspace-management-check-install-acct_1')?.textContent).toContain('Next');- expect(document.getElementById('workspace-management-check-outputs-acct_1')?.textContent).toContain('Pending');+ expect(document.getElementById('workspace-management-check-alerts-acct_1')?.textContent).toContain('Pending');+ expect(document.getElementById('workspace-management-check-reports-acct_1')?.textContent).toContain('Pending');expect(document.getElementById('workspace-management-check-access-acct_1')?.textContent).toContain('Available');expect(document.getElementById('workspace-management-action-acct_1')?.textContent).toContain('Suspend workspace');expect((document.getElementById('workspace-management-open-form-acct_1') as HTMLFormElement).action).toContain('/api/accounts/acct_1/tenants/ws_1/handoff');diff --git a/internal/cloudcp/portal/frontend/src/account_view.ts b/internal/cloudcp/portal/frontend/src/account_view.tsindex c298802a02..bc1441b5c6 100644--- a/internal/cloudcp/portal/frontend/src/account_view.ts+++ b/internal/cloudcp/portal/frontend/src/account_view.ts@@ -41,6 +41,20 @@ function workspaceCreatedLabel(workspace: PortalWorkspaceSummary): string {return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });}+function hasKnownCount(value: unknown): boolean {+ return typeof value === 'number' && Number.isFinite(value);+}++function hasPositiveCount(value: unknown): boolean {+ return hasKnownCount(value) && Number(value) > 0;+}++function setupCountLabel(value: unknown, singular: string, plural: string): string {+ if (!hasKnownCount(value)) return 'Unknown';+ var count = Number(value);+ return String(count) + ' ' + (count === 1 ? singular : plural);+}+function workspaceMeta(workspace: PortalWorkspaceSummary): string {var parts = [workspace.state];if (workspace.health_status) parts.push(workspace.health_status);@@ -106,12 +120,15 @@ export function renderWorkspaceManagement(account: PortalAccountSummary, entry:var summary = getElement<HTMLElement>('workspace-management-summary-' + account.id);var health = getElement<HTMLElement>('workspace-management-health-' + account.id);var setup = getElement<HTMLElement>('workspace-management-setup-' + account.id);+ var agents = getElement<HTMLElement>('workspace-management-agents-' + account.id);+ var alerts = getElement<HTMLElement>('workspace-management-alerts-' + account.id);+ var reports = getElement<HTMLElement>('workspace-management-reports-' + account.id);var created = getElement<HTMLElement>('workspace-management-created-' + account.id);var guidance = getElement<HTMLElement>('workspace-management-guidance-' + account.id);var checkCreated = getElement<HTMLElement>('workspace-management-check-created-' + account.id);- var checkOpen = getElement<HTMLElement>('workspace-management-check-open-' + account.id);var checkInstall = getElement<HTMLElement>('workspace-management-check-install-' + account.id);- var checkOutputs = getElement<HTMLElement>('workspace-management-check-outputs-' + account.id);+ var checkAlerts = getElement<HTMLElement>('workspace-management-check-alerts-' + account.id);+ var checkReports = getElement<HTMLElement>('workspace-management-check-reports-' + account.id);var checkAccess = getElement<HTMLElement>('workspace-management-check-access-' + account.id);var actionButton = getElement<HTMLButtonElement>('workspace-management-action-' + account.id);var closeButton = getElement<HTMLButtonElement>('workspace-management-close-' + account.id);@@ -166,27 +183,41 @@ export function renderWorkspaceManagement(account: PortalAccountSummary, entry:summary.textContent = workspaceStatusCopy(workspace);health.textContent = workspaceHealthLabel(workspace);setup.textContent = workspaceSetupLabel(workspace);+ if (agents) agents.textContent = setupCountLabel(workspace.agent_count, 'agent', 'agents');+ if (alerts) alerts.textContent = setupCountLabel(workspace.alert_route_count, 'route', 'routes');+ if (reports) reports.textContent = setupCountLabel(workspace.report_schedule_count, 'schedule', 'schedules');created.textContent = workspaceCreatedLabel(workspace);guidance.textContent = workspaceGuidanceCopy(workspace);var setupState = workspaceSetupState(workspace);var isActive = workspace.state === 'active';+ var hasAgents = hasPositiveCount(workspace.agent_count) || setupState === 'configure_outputs' || setupState === 'ready';+ var hasAlertRoutes = hasPositiveCount(workspace.alert_route_count);+ var hasReportSchedules = hasPositiveCount(workspace.report_schedule_count);setChecklistStatus(checkCreated, workspace.state ? 'done' : 'pending', workspace.state ? 'Done' : 'Pending');- setChecklistStatus(checkOpen, isActive ? 'available' : 'blocked', isActive ? 'Available' : 'Blocked');- if (setupState === 'ready' || setupState === 'configure_outputs') {+ if (hasAgents) {setChecklistStatus(checkInstall, 'done', 'Done');} else if (setupState === 'install_agents' || setupState === 'setup_path') {setChecklistStatus(checkInstall, isActive ? 'next' : 'blocked', isActive ? 'Next' : 'Blocked');} else {setChecklistStatus(checkInstall, 'blocked', 'Review');}- if (setupState === 'ready') {- setChecklistStatus(checkOutputs, 'done', 'Done');- } else if (setupState === 'configure_outputs') {- setChecklistStatus(checkOutputs, 'next', 'Next');+ if (hasAlertRoutes) {+ setChecklistStatus(checkAlerts, 'done', 'Done');+ } else if (setupState === 'review') {+ setChecklistStatus(checkAlerts, 'blocked', 'Review');+ } else if (isActive && hasAgents) {+ setChecklistStatus(checkAlerts, 'next', 'Next');+ } else {+ setChecklistStatus(checkAlerts, 'pending', 'Pending');+ }+ if (hasReportSchedules) {+ setChecklistStatus(checkReports, 'done', 'Done');} else if (setupState === 'review') {- setChecklistStatus(checkOutputs, 'blocked', 'Review');+ setChecklistStatus(checkReports, 'blocked', 'Review');+ } else if (isActive && hasAgents && hasAlertRoutes) {+ setChecklistStatus(checkReports, 'next', 'Next');} else {- setChecklistStatus(checkOutputs, 'pending', 'Pending');+ setChecklistStatus(checkReports, 'pending', 'Pending');}setChecklistStatus(checkAccess, 'available', 'Available');actionButton.textContent = workspaceActionLabel(workspace);diff --git a/internal/cloudcp/portal/frontend/src/api.ts b/internal/cloudcp/portal/frontend/src/api.tsindex 5393c4da1c..078b41a668 100644--- a/internal/cloudcp/portal/frontend/src/api.ts+++ b/internal/cloudcp/portal/frontend/src/api.ts@@ -28,6 +28,12 @@ export interface PortalWorkspaceCreateRequest {display_name: string;}+export interface PortalWorkspaceCreateResponse {+ id?: string;+ display_name?: string;+ state?: string;+}+export interface PortalMemberInviteRequest {email: string;role: string;@@ -49,7 +55,7 @@ export interface PortalAPI {logout(): Promise<void>;getCommercialJSON<T>(path: string): Promise<T>;postCommercialJSON<T>(path: string, body: Record<string, unknown>): Promise<T>;- createWorkspace(accountID: string, body: PortalWorkspaceCreateRequest): Promise<void>;+ createWorkspace(accountID: string, body: PortalWorkspaceCreateRequest): Promise<PortalWorkspaceCreateResponse>;suspendWorkspace(accountID: string, tenantID: string): Promise<void>;deleteWorkspace(accountID: string, tenantID: string): Promise<void>;openBilling(accountID: string): Promise<PortalBillingResponse>;@@ -160,7 +166,7 @@ export function createPortalAPI(context: PortalAPIContext): PortalAPI {}, 'Commercial request failed.');},createWorkspace: function(accountID: string, body: PortalWorkspaceCreateRequest) {- return request<void>(accountURL(accountID, '/tenants'), {+ return request<PortalWorkspaceCreateResponse>(accountURL(accountID, '/tenants'), {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(body),diff --git a/internal/cloudcp/portal/frontend/src/shell_view.test.ts b/internal/cloudcp/portal/frontend/src/shell_view.test.tsindex 177d3afe8e..27a5aff81f 100644--- a/internal/cloudcp/portal/frontend/src/shell_view.test.ts+++ b/internal/cloudcp/portal/frontend/src/shell_view.test.ts@@ -125,6 +125,8 @@ describe('shell view', function() {expect(html).toContain('workspace-summary-shell');expect(html).toContain('workspace-summary-facts');expect(html).toContain('Next:</strong> Set up Summary Workspace');+ expect(html).toContain('Unfinished setup');+ expect(html).toContain('Unknown agents');expect(html).toContain('1 workspace in setup');expect(html).toContain('Summary Workspace');expect(html).not.toContain('overview-task-grid');@@ -192,6 +194,7 @@ describe('shell view', function() {expect(html).toContain('1 workspace in setup');expect(html).toContain('2 workspaces to review');expect(html).toContain('Next:</strong> Review Beta Workspace');+ expect(html).toContain('Unfinished setup');expect(html).toContain('Create workspace');expect(html).not.toContain('Manage billing');expect(html).not.toContain('Manage team');@@ -206,6 +209,8 @@ describe('shell view', function() {expect(html).toContain('/api/accounts/acct_1/tenants/ws_active/handoff?target_path=%2Fsettings%2Finfrastructure%3Fadd%3Dlinux-host');expect(html).toContain('Open workspace');expect(html).toContain('Install agents');+ expect(html).toContain('Configure alert routes');+ expect(html).toContain('Schedule reports');expect(html).toContain('Open the workspace-bound install commands.');expect(html).toContain('Alerts and performance reports stay inside the client workspace.');expect(html).toContain('data-action="select-workspace"');diff --git a/internal/cloudcp/portal/frontend/src/shell_view.ts b/internal/cloudcp/portal/frontend/src/shell_view.tsindex f232c01d36..8c7902a4ef 100644--- a/internal/cloudcp/portal/frontend/src/shell_view.ts+++ b/internal/cloudcp/portal/frontend/src/shell_view.ts@@ -592,6 +592,19 @@ function setupNeededWorkspaceEntries(entries: WorkspaceSummaryEntry[]): Workspacreturn results;}+function setupFactCountLabel(value: unknown, singular: string, plural: string): string {+ if (typeof value !== 'number' || !Number.isFinite(value)) return 'Unknown ' + plural;+ return String(value) + ' ' + (value === 1 ? singular : plural);+}++function workspaceSetupFactsLine(workspace: PortalWorkspaceSummary): string {+ return [+ setupFactCountLabel(workspace.agent_count, 'agent', 'agents'),+ setupFactCountLabel(workspace.alert_route_count, 'alert route', 'alert routes'),+ setupFactCountLabel(workspace.report_schedule_count, 'report schedule', 'report schedules'),+ ].join(' · ');+}+function workspaceSummaryContext(entry: WorkspaceSummaryEntry, includeAccountName: boolean, note: string): string {if (!includeAccountName) return note;return entry.account.name + ' · ' + note;@@ -789,6 +802,69 @@ function renderWorkspaceSummaryInline();}+function renderWorkspaceSetupQueueAction(entry: WorkspaceSummaryEntry, accountAPIBasePath: string): string {+ var setup = workspaceSetupState(entry.workspace);+ if (setup === 'configure_outputs') {+ return renderWorkspaceReportingHandoffForm(+ entry.account.id,+ entry.workspace.id,+ accountAPIBasePath,+ 'Configure outputs',+ 'btn-primary btn-compact',+ );+ }+ return renderWorkspaceInstallHandoffForm(+ entry.account.id,+ entry.workspace.id,+ accountAPIBasePath,+ setup === 'install_agents' ? 'Install agents' : 'Open setup',+ 'btn-primary btn-compact',+ );+}++function renderWorkspaceSetupQueue(entries: WorkspaceSummaryEntry[], accountAPIBasePath: string): string {+ var setupNeeded = setupNeededWorkspaceEntries(entries);+ if (!setupNeeded.length) return '';+ var visible = setupNeeded.slice(0, 5);+ return (+ '<section class="workspace-setup-queue" aria-label="Unfinished workspace setup">' ++ '<div class="workspace-setup-queue-header">' ++ '<div>' ++ '<h3>Unfinished setup</h3>' ++ '<p>Client workspaces stay here until agents, alert routing, and reports are in place.</p>' ++ '</div>' ++ '<span>' + escapeHTML(setupNeededWorkspaceChipLabel(setupNeeded.length)) + '</span>' ++ '</div>' ++ '<div class="workspace-setup-queue-list">' ++ visible.map(function(entry) {+ return (+ '<article class="workspace-setup-queue-row">' ++ '<div class="workspace-setup-queue-main">' ++ setupBadgeHTML(entry.workspace) ++ '<div>' ++ '<strong>' + escapeHTML(entry.workspace.display_name) + '</strong>' ++ '<span>' + escapeHTML(entry.account.name + ' · ' + workspaceSetupNextStep(entry.workspace)) + '</span>' ++ '<small>' + escapeHTML(workspaceSetupFactsLine(entry.workspace)) + '</small>' ++ '</div>' ++ '</div>' ++ '<div class="workspace-setup-queue-actions">' ++ renderWorkspaceSetupQueueAction(entry, accountAPIBasePath) ++ (entry.account.can_manage+ ? '<button type="button" class="btn-secondary btn-compact" data-action="select-workspace" data-account-id="' ++ escapeAttr(entry.account.id) ++ '" data-workspace-id="' ++ escapeAttr(entry.workspace.id) ++ '">Checklist</button>'+ : renderWorkspaceHandoffForm(entry.account.id, entry.workspace.id, accountAPIBasePath, 'Open workspace')) ++ '</div>' ++ '</article>'+ );+ }).join('') ++ '</div>' ++ '</section>'+ );+}+function workspaceSectionHeaderCopy(accounts: PortalAccountSummary[], entries: WorkspaceSummaryEntry[]): string {var canManageAnyWorkspace = accounts.some(function(account) { return account.can_manage; });if (!entries.length) {@@ -815,6 +891,7 @@ export function renderWorkspaceSummarySection(context: ShellViewContext): string'</div>' +renderFactLine('workspace-summary-facts', renderWorkspaceSummaryFacts(accounts, entries)) +renderWorkspaceSummaryInline(accounts, entries, context.accountAPIBasePath, showSelfHostedCommercial) ++ renderWorkspaceSetupQueue(entries, context.accountAPIBasePath) +'</section>');}@@ -943,6 +1020,18 @@ function renderAccountWorkspaceSection(account: PortalAccountSummary, accountAPI'<span>Setup</span>' +'<strong id="workspace-management-setup-' + escapeAttr(account.id) + '"></strong>' +'</div>' ++ '<div class="workspace-management-fact">' ++ '<span>Agents</span>' ++ '<strong id="workspace-management-agents-' + escapeAttr(account.id) + '"></strong>' ++ '</div>' ++ '<div class="workspace-management-fact">' ++ '<span>Alert routes</span>' ++ '<strong id="workspace-management-alerts-' + escapeAttr(account.id) + '"></strong>' ++ '</div>' ++ '<div class="workspace-management-fact">' ++ '<span>Report schedules</span>' ++ '<strong id="workspace-management-reports-' + escapeAttr(account.id) + '"></strong>' ++ '</div>' +'<div class="workspace-management-fact">' +'<span>Created</span>' +'<strong id="workspace-management-created-' + escapeAttr(account.id) + '"></strong>' +@@ -956,17 +1045,17 @@ function renderAccountWorkspaceSection(account: PortalAccountSummary, accountAPI'<span class="workspace-setup-status" id="workspace-management-check-created-' + escapeAttr(account.id) + '"></span>' +'<div><strong>Workspace created</strong><span>This client has a separate account boundary.</span></div>' +'</div>' +- '<div class="workspace-setup-step">' +- '<span class="workspace-setup-status" id="workspace-management-check-open-' + escapeAttr(account.id) + '"></span>' +- '<div><strong>Open the workspace</strong><span>Work inside the selected client boundary.</span></div>' +- '</div>' +'<div class="workspace-setup-step">' +'<span class="workspace-setup-status" id="workspace-management-check-install-' + escapeAttr(account.id) + '"></span>' +'<div><strong>Install the first agent</strong><span>Use the workspace-bound install path so data lands in this client.</span></div>' +'</div>' +'<div class="workspace-setup-step">' +- '<span class="workspace-setup-status" id="workspace-management-check-outputs-' + escapeAttr(account.id) + '"></span>' +- '<div><strong>Configure alerts and reports</strong><span>Keep notifications and reports scoped to this client.</span></div>' ++ '<span class="workspace-setup-status" id="workspace-management-check-alerts-' + escapeAttr(account.id) + '"></span>' ++ '<div><strong>Configure alert routes</strong><span>Keep notifications scoped to this client.</span></div>' ++ '</div>' ++ '<div class="workspace-setup-step">' ++ '<span class="workspace-setup-status" id="workspace-management-check-reports-' + escapeAttr(account.id) + '"></span>' ++ '<div><strong>Schedule reports</strong><span>Send client performance reports from this workspace.</span></div>' +'</div>' +'<div class="workspace-setup-step">' +'<span class="workspace-setup-status" id="workspace-management-check-access-' + escapeAttr(account.id) + '"></span>' +diff --git a/internal/cloudcp/portal/frontend/src/styles.css b/internal/cloudcp/portal/frontend/src/styles.cssindex e1917bfee7..30b4271290 100644--- a/internal/cloudcp/portal/frontend/src/styles.css+++ b/internal/cloudcp/portal/frontend/src/styles.css@@ -500,7 +500,7 @@ header .logout-btn:hover,.workspace-management-facts {display: grid;- grid-template-columns: repeat(3, 1fr);+ grid-template-columns: repeat(auto-fit, minmax(112px, 1fr));gap: 8px;}@@ -1360,6 +1360,95 @@ header .logout-btn:hover,text-decoration: none;}+.workspace-setup-queue {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding-bottom: 16px;+ border-bottom: 1px solid var(--border);+}++.workspace-setup-queue-header {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 12px;+}++.workspace-setup-queue-header h3 {+ margin: 0;+ font-size: 14px;+ color: var(--ink);+}++.workspace-setup-queue-header p {+ margin: 3px 0 0;+ color: var(--ink-secondary);+ font-size: 12px;+}++.workspace-setup-queue-header > span {+ flex: 0 0 auto;+ color: var(--ink-secondary);+ font-size: 12px;+}++.workspace-setup-queue-list {+ display: flex;+ flex-direction: column;+ border: 1px solid var(--border-muted);+ border-radius: var(--radius);+ overflow: hidden;+ background: var(--bg);+}++.workspace-setup-queue-row {+ display: grid;+ grid-template-columns: minmax(0, 1fr) auto;+ gap: 12px;+ align-items: center;+ padding: 10px 12px;+ border-top: 1px solid var(--border-muted);+}++.workspace-setup-queue-row:first-child {+ border-top: none;+}++.workspace-setup-queue-main {+ display: grid;+ grid-template-columns: auto minmax(0, 1fr);+ gap: 10px;+ align-items: flex-start;+ min-width: 0;+}++.workspace-setup-queue-main strong,+.workspace-setup-queue-main span,+.workspace-setup-queue-main small {+ display: block;+}++.workspace-setup-queue-main strong {+ color: var(--ink);+ font-size: 13px;+}++.workspace-setup-queue-main span,+.workspace-setup-queue-main small {+ margin-top: 2px;+ color: var(--ink-secondary);+ font-size: 12px;+ overflow-wrap: anywhere;+}++.workspace-setup-queue-actions {+ display: flex;+ flex-wrap: wrap;+ justify-content: flex-end;+ gap: 8px;+}+/* Remove kicker labels — they feel like a custom portal. Use section context instead. */.account-panel-kicker,.billing-card-kicker,@@ -1525,6 +1614,16 @@ header .logout-btn:hover,}.workspace-summary-actions { justify-content: flex-start; }+ .workspace-setup-queue-header,+ .workspace-setup-queue-row {+ grid-template-columns: 1fr;+ }+ .workspace-setup-queue-header {+ flex-direction: column;+ }+ .workspace-setup-queue-actions {+ justify-content: flex-start;+ }.workspace-list-head { display: none; }.workspace-row { grid-template-columns: 1fr; gap: 8px; }diff --git a/internal/cloudcp/portal/frontend/src/types.ts b/internal/cloudcp/portal/frontend/src/types.tsindex 7f9582a53b..1b826fbc2f 100644--- a/internal/cloudcp/portal/frontend/src/types.ts+++ b/internal/cloudcp/portal/frontend/src/types.ts@@ -6,6 +6,7 @@ export interface PortalWorkspaceSummary {health_status: 'healthy' | 'checking' | 'unhealthy';setup_status?: 'ready' | 'setup_path' | 'install_agents' | 'configure_outputs' | 'review';agent_count?: number;+ last_agent_seen_at?: string;alert_route_count?: number;report_schedule_count?: number;last_health_check?: string;diff --git a/internal/cloudcp/portal/frontend/src/workspace_presentation.test.ts b/internal/cloudcp/portal/frontend/src/workspace_presentation.test.tsindex dd3a4ad36c..50df13a1c6 100644--- a/internal/cloudcp/portal/frontend/src/workspace_presentation.test.ts+++ b/internal/cloudcp/portal/frontend/src/workspace_presentation.test.ts@@ -63,6 +63,7 @@ describe('workspace presentation', function() {expect(workspaceRowNote(createWorkspace())).toBe('Setup path ready');expect(workspaceSetupNextStep(createWorkspace({ setup_status: 'install_agents' }))).toBe('Install the first agent from this workspace so client data lands in the right boundary.');expect(workspaceSetupState(createWorkspace({ agent_count: 0 }))).toBe('install_agents');+ expect(workspaceSetupState(createWorkspace({ setup_status: 'setup_path', agent_count: 0 }))).toBe('install_agents');expect(workspaceSetupState(createWorkspace({ agent_count: 1, alert_route_count: 0, report_schedule_count: 0 }))).toBe('configure_outputs');expect(workspaceSetupState(createWorkspace({ agent_count: 1, alert_route_count: 1, report_schedule_count: 1 }))).toBe('ready');expect(workspaceSetupState(createWorkspace({ state: 'failed', healthy: false, health_status: 'unhealthy' }))).toBe('review');diff --git a/internal/cloudcp/portal/frontend/src/workspace_presentation.ts b/internal/cloudcp/portal/frontend/src/workspace_presentation.tsindex a1f6ffe093..f1da7b4eae 100644--- a/internal/cloudcp/portal/frontend/src/workspace_presentation.ts+++ b/internal/cloudcp/portal/frontend/src/workspace_presentation.ts@@ -67,9 +67,6 @@ function explicitSetupStatus(workspace: PortalWorkspaceSummary): WorkspaceSetupS}export function workspaceSetupState(workspace: PortalWorkspaceSummary): WorkspaceSetupState {- var explicit = explicitSetupStatus(workspace);- if (explicit) return explicit;-var state = String(workspace.state || '');var health = workspaceHealthState(workspace);if (state === 'suspended' || state === 'failed' || health === 'unhealthy') return 'review';@@ -89,6 +86,8 @@ export function workspaceSetupState(workspace: PortalWorkspaceSummary): Workspacif (hasAgents && (!knowsAlertCount || hasAlerts) && (!knowsReportCount || hasReports)) {return 'ready';}+ var explicit = explicitSetupStatus(workspace);+ if (explicit) return explicit;return 'setup_path';}diff --git a/internal/cloudcp/portal/handlers.go b/internal/cloudcp/portal/handlers.goindex ebba816798..972fe1d1ed 100644--- a/internal/cloudcp/portal/handlers.go+++ b/internal/cloudcp/portal/handlers.go@@ -21,13 +21,17 @@ type accountInfo struct {}type workspaceSummaryItem struct {- ID string `json:"id"`- DisplayName string `json:"display_name"`- State registry.TenantState `json:"state"`- HealthCheckOK bool `json:"health_check_ok"`- SetupStatus string `json:"setup_status,omitempty"`- LastHealthCheck *time.Time `json:"last_health_check"`- CreatedAt time.Time `json:"created_at"`+ ID string `json:"id"`+ DisplayName string `json:"display_name"`+ State registry.TenantState `json:"state"`+ HealthCheckOK bool `json:"health_check_ok"`+ SetupStatus string `json:"setup_status,omitempty"`+ AgentCount *int `json:"agent_count,omitempty"`+ LastAgentSeenAt *time.Time `json:"last_agent_seen_at,omitempty"`+ AlertRouteCount *int `json:"alert_route_count,omitempty"`+ ReportScheduleCount *int `json:"report_schedule_count,omitempty"`+ LastHealthCheck *time.Time `json:"last_health_check"`+ CreatedAt time.Time `json:"created_at"`}type dashboardSummary struct {@@ -71,6 +75,10 @@ func accountIDFromRequest(r *http.Request) string {//// Auth: control-plane session + account membership middleware.func HandlePortalDashboard(reg *registry.TenantRegistry) http.HandlerFunc {+ return HandlePortalDashboardWithSetupFacts(reg, nil)+}++func HandlePortalDashboardWithSetupFacts(reg *registry.TenantRegistry, setupFacts WorkspaceSetupFactReader) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)@@ -119,15 +127,20 @@ func HandlePortalDashboard(reg *registry.TenantRegistry) http.HandlerFunc {if !isPortalVisibleTenant(t) {continue}+ facts := workspaceSetupFactsForTenant(setupFacts, t.ID)resp.Workspaces = append(resp.Workspaces, workspaceSummaryItem{- ID: t.ID,- DisplayName: t.DisplayName,- State: t.State,- HealthCheckOK: t.HealthCheckOK,- SetupStatus: workspaceSetupStatus(t.State, t.HealthCheckOK, t.LastHealthCheck),- LastHealthCheck: t.LastHealthCheck,- CreatedAt: t.CreatedAt,+ ID: t.ID,+ DisplayName: t.DisplayName,+ State: t.State,+ HealthCheckOK: t.HealthCheckOK,+ SetupStatus: workspaceSetupStatus(t.State, t.HealthCheckOK, t.LastHealthCheck, facts),+ AgentCount: facts.AgentCount,+ LastAgentSeenAt: facts.LastAgentSeenAt,+ AlertRouteCount: facts.AlertRouteCount,+ ReportScheduleCount: facts.ReportScheduleCount,+ LastHealthCheck: t.LastHealthCheck,+ CreatedAt: t.CreatedAt,})resp.Summary.Total++@@ -228,6 +241,10 @@ func HandlePortalBootstrap(sessionSvc *cpauth.Service, reg *registry.TenantRegis}func HandlePortalBootstrapWithSignupPath(sessionSvc *cpauth.Service, reg *registry.TenantRegistry, commercialLookup CommercialIdentityLookup, signupPath string) http.HandlerFunc {+ return HandlePortalBootstrapWithSignupPathAndSetupFacts(sessionSvc, reg, commercialLookup, signupPath, nil)+}++func HandlePortalBootstrapWithSignupPathAndSetupFacts(sessionSvc *cpauth.Service, reg *registry.TenantRegistry, commercialLookup CommercialIdentityLookup, signupPath string, setupFacts WorkspaceSetupFactReader) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)@@ -249,7 +266,7 @@ func HandlePortalBootstrapWithSignupPath(sessionSvc *cpauth.Service, reg *registreturn}- accounts, err := loadPortalAccountsForUser(reg, claims.UserID)+ accounts, err := loadPortalAccountsForUserWithSetupFacts(reg, claims.UserID, setupFacts)if err != nil {log.Error().Err(err).Str("user_id", claims.UserID).Msg("cloudcp.portal.bootstrap: load accounts")http.Error(w, "internal error", http.StatusInternalServerError)diff --git a/internal/cloudcp/portal/handlers_test.go b/internal/cloudcp/portal/handlers_test.goindex a10157f007..d287006e8c 100644--- a/internal/cloudcp/portal/handlers_test.go+++ b/internal/cloudcp/portal/handlers_test.go@@ -35,6 +35,12 @@ func newTestMux(reg *registry.TenantRegistry) *http.ServeMux {return mux}+type staticSetupFactReader map[string]WorkspaceSetupFacts++func (r staticSetupFactReader) FactsForWorkspace(tenantID string) WorkspaceSetupFacts {+ return r[tenantID]+}+func doRequest(t *testing.T, h http.Handler, req *http.Request) *httptest.ResponseRecorder {t.Helper()req.Header.Set("X-Admin-Key", "secret-key")@@ -115,13 +121,17 @@ type dashboardResp struct {Kind registry.AccountKind `json:"kind"`} `json:"account"`Workspaces []struct {- ID string `json:"id"`- DisplayName string `json:"display_name"`- State registry.TenantState `json:"state"`- HealthCheckOK bool `json:"health_check_ok"`- SetupStatus string `json:"setup_status"`- LastHealthCheck *time.Time `json:"last_health_check"`- CreatedAt time.Time `json:"created_at"`+ ID string `json:"id"`+ DisplayName string `json:"display_name"`+ State registry.TenantState `json:"state"`+ HealthCheckOK bool `json:"health_check_ok"`+ SetupStatus string `json:"setup_status"`+ AgentCount *int `json:"agent_count"`+ LastAgentSeenAt *time.Time `json:"last_agent_seen_at"`+ AlertRouteCount *int `json:"alert_route_count"`+ ReportScheduleCount *int `json:"report_schedule_count"`+ LastHealthCheck *time.Time `json:"last_health_check"`+ CreatedAt time.Time `json:"created_at"`} `json:"workspaces"`Summary struct {Total int `json:"total"`@@ -237,13 +247,17 @@ func TestPortalDashboard(t *testing.T) {// local helper type for easier indexingfor _, ws := range resp.Workspaces {wsByID[ws.ID] = dashboardRespWorkspace{- ID: ws.ID,- DisplayName: ws.DisplayName,- State: ws.State,- HealthCheckOK: ws.HealthCheckOK,- SetupStatus: ws.SetupStatus,- LastHealthCheck: ws.LastHealthCheck,- CreatedAt: ws.CreatedAt,+ ID: ws.ID,+ DisplayName: ws.DisplayName,+ State: ws.State,+ HealthCheckOK: ws.HealthCheckOK,+ SetupStatus: ws.SetupStatus,+ AgentCount: ws.AgentCount,+ LastAgentSeenAt: ws.LastAgentSeenAt,+ AlertRouteCount: ws.AlertRouteCount,+ ReportScheduleCount: ws.ReportScheduleCount,+ LastHealthCheck: ws.LastHealthCheck,+ CreatedAt: ws.CreatedAt,}}@@ -298,14 +312,139 @@ func TestPortalDashboard(t *testing.T) {}}+func TestPortalDashboardUsesWorkspaceSetupFacts(t *testing.T) {+ reg := newTestRegistry(t)+ mux := http.NewServeMux()++ accountID, err := registry.GenerateAccountID()+ if err != nil {+ t.Fatal(err)+ }+ if err := reg.CreateAccount(®istry.Account{ID: accountID, Kind: registry.AccountKindMSP, DisplayName: "Example MSP"}); err != nil {+ t.Fatal(err)+ }++ tenantInstallID, err := registry.GenerateTenantID()+ if err != nil {+ t.Fatal(err)+ }+ tenantOutputsID, err := registry.GenerateTenantID()+ if err != nil {+ t.Fatal(err)+ }+ tenantReadyID, err := registry.GenerateTenantID()+ if err != nil {+ t.Fatal(err)+ }+ lastSeen := time.Date(2026, 4, 1, 10, 0, 0, 0, time.UTC)++ for _, tenant := range []*registry.Tenant{+ {+ ID: tenantInstallID,+ AccountID: accountID,+ DisplayName: "Install",+ State: registry.TenantStateActive,+ CreatedAt: lastSeen,+ HealthCheckOK: true,+ },+ {+ ID: tenantOutputsID,+ AccountID: accountID,+ DisplayName: "Outputs",+ State: registry.TenantStateActive,+ CreatedAt: lastSeen,+ HealthCheckOK: true,+ },+ {+ ID: tenantReadyID,+ AccountID: accountID,+ DisplayName: "Ready",+ State: registry.TenantStateActive,+ CreatedAt: lastSeen,+ HealthCheckOK: true,+ },+ } {+ if err := reg.Create(tenant); err != nil {+ t.Fatal(err)+ }+ }++ mux.Handle(PortalDashboardPath, admin.AdminKeyMiddleware("secret-key", HandlePortalDashboardWithSetupFacts(reg, staticSetupFactReader{+ tenantInstallID: {+ AgentCount: intPtr(0),+ AlertRouteCount: intPtr(0),+ ReportScheduleCount: intPtr(0),+ },+ tenantOutputsID: {+ AgentCount: intPtr(1),+ LastAgentSeenAt: &lastSeen,+ AlertRouteCount: intPtr(1),+ ReportScheduleCount: intPtr(0),+ },+ tenantReadyID: {+ AgentCount: intPtr(2),+ LastAgentSeenAt: &lastSeen,+ AlertRouteCount: intPtr(1),+ ReportScheduleCount: intPtr(1),+ },+ })))++ req := httptest.NewRequest(http.MethodGet, "/api/portal/dashboard?account_id="+accountID, nil)+ rec := doRequest(t, mux, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusOK, rec.Body.String())+ }++ var resp dashboardResp+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v (body=%q)", err, rec.Body.String())+ }++ got := map[string]dashboardRespWorkspace{}+ for _, ws := range resp.Workspaces {+ got[ws.ID] = dashboardRespWorkspace{+ ID: ws.ID,+ DisplayName: ws.DisplayName,+ State: ws.State,+ HealthCheckOK: ws.HealthCheckOK,+ SetupStatus: ws.SetupStatus,+ AgentCount: ws.AgentCount,+ LastAgentSeenAt: ws.LastAgentSeenAt,+ AlertRouteCount: ws.AlertRouteCount,+ ReportScheduleCount: ws.ReportScheduleCount,+ LastHealthCheck: ws.LastHealthCheck,+ CreatedAt: ws.CreatedAt,+ }+ }+ if got[tenantInstallID].SetupStatus != "install_agents" {+ t.Fatalf("install setup_status = %q, want install_agents", got[tenantInstallID].SetupStatus)+ }+ if got[tenantOutputsID].SetupStatus != "configure_outputs" {+ t.Fatalf("outputs setup_status = %q, want configure_outputs", got[tenantOutputsID].SetupStatus)+ }+ if got[tenantReadyID].SetupStatus != "ready" {+ t.Fatalf("ready setup_status = %q, want ready", got[tenantReadyID].SetupStatus)+ }+ if got[tenantReadyID].AgentCount == nil || *got[tenantReadyID].AgentCount != 2 {+ t.Fatalf("ready agent_count = %v, want 2", got[tenantReadyID].AgentCount)+ }+ if got[tenantReadyID].LastAgentSeenAt == nil || !got[tenantReadyID].LastAgentSeenAt.Equal(lastSeen) {+ t.Fatalf("ready last_agent_seen_at = %v, want %v", got[tenantReadyID].LastAgentSeenAt, lastSeen)+ }+}+type dashboardRespWorkspace struct {- ID string- DisplayName string- State registry.TenantState- HealthCheckOK bool- SetupStatus string- LastHealthCheck *time.Time- CreatedAt time.Time+ ID string+ DisplayName string+ State registry.TenantState+ HealthCheckOK bool+ SetupStatus string+ AgentCount *int+ LastAgentSeenAt *time.Time+ AlertRouteCount *int+ ReportScheduleCount *int+ LastHealthCheck *time.Time+ CreatedAt time.Time}func TestPortalDashboardEmpty(t *testing.T) {@@ -1110,6 +1249,62 @@ func TestHandlePortalBootstrap_Success(t *testing.T) {}}+func TestHandlePortalBootstrapIncludesWorkspaceSetupFacts(t *testing.T) {+ reg, sessionSvc, token, accountID, _ := newPortalSessionFixture(t)+ lastSeen := time.Date(2026, 4, 1, 10, 0, 0, 0, time.UTC)++ if err := reg.Create(®istry.Tenant{+ ID: "t_bootstrap_facts",+ AccountID: accountID,+ DisplayName: "Bootstrap Workspace",+ State: registry.TenantStateActive,+ CreatedAt: time.Date(2026, 3, 25, 10, 0, 0, 0, time.UTC),+ HealthCheckOK: true,+ }); err != nil {+ t.Fatal(err)+ }++ req := httptest.NewRequest(http.MethodGet, "/api/portal/bootstrap", nil)+ req.Header.Set("Authorization", "Bearer "+token)+ rec := httptest.NewRecorder()+ HandlePortalBootstrapWithSignupPathAndSetupFacts(sessionSvc, reg, nil, PortalSignupPath, staticSetupFactReader{+ "t_bootstrap_facts": {+ AgentCount: intPtr(1),+ LastAgentSeenAt: &lastSeen,+ AlertRouteCount: intPtr(1),+ ReportScheduleCount: intPtr(0),+ },+ }).ServeHTTP(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d (body=%q)", rec.Code, http.StatusOK, rec.Body.String())+ }++ var payload map[string]any+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {+ t.Fatalf("unmarshal bootstrap response: %v", err)+ }+ accounts := payload["accounts"].([]any)+ account := accounts[0].(map[string]any)+ workspaces := account["workspaces"].([]any)+ workspace := workspaces[0].(map[string]any)+ if got := workspace["setup_status"]; got != "configure_outputs" {+ t.Fatalf("workspace setup_status = %#v, want configure_outputs", got)+ }+ if got := workspace["agent_count"]; got != float64(1) {+ t.Fatalf("workspace agent_count = %#v, want 1", got)+ }+ if got := workspace["alert_route_count"]; got != float64(1) {+ t.Fatalf("workspace alert_route_count = %#v, want 1", got)+ }+ if got := workspace["report_schedule_count"]; got != float64(0) {+ t.Fatalf("workspace report_schedule_count = %#v, want 0", got)+ }+ if got := workspace["last_agent_seen_at"]; got != "2026-04-01T10:00:00Z" {+ t.Fatalf("workspace last_agent_seen_at = %#v, want 2026-04-01T10:00:00Z", got)+ }+}+func TestHandlePortalBootstrap_RequiresAuth(t *testing.T) {reg := newTestRegistry(t)sessionSvc, err := cpauth.NewService(t.TempDir())diff --git a/internal/cloudcp/portal/page.go b/internal/cloudcp/portal/page.goindex 5fe31032a6..094ea34075 100644--- a/internal/cloudcp/portal/page.go+++ b/internal/cloudcp/portal/page.go@@ -14,14 +14,18 @@ import (// portalPageWorkspace holds per-workspace display data for the portal template.type portalPageWorkspace struct {- ID string- DisplayName string- State string- Healthy bool- HealthStatus string- SetupStatus string- LastHealthCheck *time.Time- CreatedAt time.Time+ ID string+ DisplayName string+ State string+ Healthy bool+ HealthStatus string+ SetupStatus string+ AgentCount *int+ LastAgentSeenAt *time.Time+ AlertRouteCount *int+ ReportScheduleCount *int+ LastHealthCheck *time.Time+ CreatedAt time.Time}type portalPageMember struct {@@ -76,6 +80,10 @@ func HandlePortalPage(sessionSvc *cpauth.Service, reg *registry.TenantRegistry,}func HandlePortalPageWithSignupPath(sessionSvc *cpauth.Service, reg *registry.TenantRegistry, commercialLookup CommercialIdentityLookup, faviconHref string, signupPath string) http.HandlerFunc {+ return HandlePortalPageWithSignupPathAndSetupFacts(sessionSvc, reg, commercialLookup, faviconHref, signupPath, nil)+}++func HandlePortalPageWithSignupPathAndSetupFacts(sessionSvc *cpauth.Service, reg *registry.TenantRegistry, commercialLookup CommercialIdentityLookup, faviconHref string, signupPath string, setupFacts WorkspaceSetupFactReader) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)@@ -87,7 +95,7 @@ func HandlePortalPageWithSignupPath(sessionSvc *cpauth.Service, reg *registry.Teclaims, err := validatePortalSessionClaims(r, sessionSvc, reg)switch {case err == nil:- accounts, loadErr := loadPortalAccountsForUser(reg, claims.UserID)+ accounts, loadErr := loadPortalAccountsForUserWithSetupFacts(reg, claims.UserID, setupFacts)if loadErr != nil {log.Error().Err(loadErr).Str("user_id", claims.UserID).Msg("cloudcp.portal.page: load accounts")http.Error(w, "internal error", http.StatusInternalServerError)@@ -129,6 +137,10 @@ func validatePortalSessionClaims(r *http.Request, sessionSvc *cpauth.Service, re}func loadPortalAccountsForUser(reg *registry.TenantRegistry, userID string) ([]portalPageAccount, error) {+ return loadPortalAccountsForUserWithSetupFacts(reg, userID, nil)+}++func loadPortalAccountsForUserWithSetupFacts(reg *registry.TenantRegistry, userID string, setupFacts WorkspaceSetupFactReader) ([]portalPageAccount, error) {accountIDs, err := reg.ListAccountsByUser(userID)if err != nil {return nil, err@@ -170,16 +182,7 @@ func loadPortalAccountsForUser(reg *registry.TenantRegistry, userID string) ([]pif !isPortalVisibleTenant(t) {continue}- workspaces = append(workspaces, portalPageWorkspace{- ID: t.ID,- DisplayName: t.DisplayName,- State: string(t.State),- Healthy: t.HealthCheckOK,- HealthStatus: workspaceHealthStatus(t.HealthCheckOK, t.LastHealthCheck),- SetupStatus: workspaceSetupStatus(t.State, t.HealthCheckOK, t.LastHealthCheck),- LastHealthCheck: t.LastHealthCheck,- CreatedAt: t.CreatedAt,- })+ workspaces = append(workspaces, portalPageWorkspaceFromTenant(t, workspaceSetupFactsForTenant(setupFacts, t.ID)))}kindLabel := "Cloud"@@ -210,6 +213,33 @@ func loadPortalAccountsForUser(reg *registry.TenantRegistry, userID string) ([]preturn accounts, nil}+func workspaceSetupFactsForTenant(setupFacts WorkspaceSetupFactReader, tenantID string) WorkspaceSetupFacts {+ if setupFacts == nil {+ return WorkspaceSetupFacts{}+ }+ return setupFacts.FactsForWorkspace(tenantID)+}++func portalPageWorkspaceFromTenant(t *registry.Tenant, facts WorkspaceSetupFacts) portalPageWorkspace {+ if t == nil {+ return portalPageWorkspace{}+ }+ return portalPageWorkspace{+ ID: t.ID,+ DisplayName: t.DisplayName,+ State: string(t.State),+ Healthy: t.HealthCheckOK,+ HealthStatus: workspaceHealthStatus(t.HealthCheckOK, t.LastHealthCheck),+ SetupStatus: workspaceSetupStatus(t.State, t.HealthCheckOK, t.LastHealthCheck, facts),+ AgentCount: facts.AgentCount,+ LastAgentSeenAt: facts.LastAgentSeenAt,+ AlertRouteCount: facts.AlertRouteCount,+ ReportScheduleCount: facts.ReportScheduleCount,+ LastHealthCheck: t.LastHealthCheck,+ CreatedAt: t.CreatedAt,+ }+}+func loadPortalAccountMembers(reg *registry.TenantRegistry, accountID string, actorRole registry.MemberRole) ([]portalPageMember, error) {subjects, err := reg.ListAccessSubjectsByAccount(accountID)if err != nil {@@ -251,12 +281,23 @@ func workspaceHealthStatus(healthy bool, lastHealthCheck *time.Time) string {return "unhealthy"}-func workspaceSetupStatus(state registry.TenantState, healthy bool, lastHealthCheck *time.Time) string {+func workspaceSetupStatus(state registry.TenantState, healthy bool, lastHealthCheck *time.Time, facts WorkspaceSetupFacts) string {switch state {case registry.TenantStateActive:if !healthy && lastHealthCheck != nil {return "review"}+ if facts.AgentCount != nil {+ if *facts.AgentCount <= 0 {+ return "install_agents"+ }+ if factCountIsZero(facts.AlertRouteCount) || factCountIsZero(facts.ReportScheduleCount) {+ return "configure_outputs"+ }+ if factCountIsPositive(facts.AlertRouteCount) && factCountIsPositive(facts.ReportScheduleCount) {+ return "ready"+ }+ }return "setup_path"case registry.TenantStateProvisioning:return "setup_path"@@ -265,6 +306,14 @@ func workspaceSetupStatus(state registry.TenantState, healthy bool, lastHealthCh}}+func factCountIsZero(value *int) bool {+ return value != nil && *value <= 0+}++func factCountIsPositive(value *int) bool {+ return value != nil && *value > 0+}+func renderPortalPage(w http.ResponseWriter, nonce string, faviconHref string, bootstrapData BootstrapData) {w.Header().Set("Content-Type", "text/html; charset=utf-8")w.WriteHeader(http.StatusOK)diff --git a/internal/cloudcp/portal/setup_facts.go b/internal/cloudcp/portal/setup_facts.gonew file mode 100644index 0000000000..79b1528743--- /dev/null+++ b/internal/cloudcp/portal/setup_facts.go@@ -0,0 +1,255 @@+package portal++import (+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/crypto"+ "github.com/rcourtman/pulse-go-rewrite/internal/notifications"+ "github.com/rs/zerolog/log"+)++type WorkspaceSetupFacts struct {+ AgentCount *int+ LastAgentSeenAt *time.Time+ AlertRouteCount *int+ ReportScheduleCount *int+}++type WorkspaceSetupFactReader interface {+ FactsForWorkspace(tenantID string) WorkspaceSetupFacts+}++type tenantDirWorkspaceSetupFactReader struct {+ tenantsDir string+}++func NewTenantDirWorkspaceSetupFactReader(tenantsDir string) WorkspaceSetupFactReader {+ return tenantDirWorkspaceSetupFactReader{tenantsDir: strings.TrimSpace(tenantsDir)}+}++func (r tenantDirWorkspaceSetupFactReader) FactsForWorkspace(tenantID string) WorkspaceSetupFacts {+ orgDir, ok := r.orgConfigDir(tenantID)+ if !ok {+ return WorkspaceSetupFacts{}+ }+ return readWorkspaceSetupFacts(orgDir)+}++func (r tenantDirWorkspaceSetupFactReader) orgConfigDir(tenantID string) (string, bool) {+ tenantID = strings.TrimSpace(tenantID)+ if r.tenantsDir == "" || tenantID == "" || filepath.Base(tenantID) != tenantID {+ return "", false+ }+ return filepath.Join(r.tenantsDir, tenantID, "orgs", tenantID), true+}++func readWorkspaceSetupFacts(orgDir string) WorkspaceSetupFacts {+ facts := WorkspaceSetupFacts{}+ if orgDir == "" {+ return facts+ }++ facts.AgentCount, facts.LastAgentSeenAt = readAgentSetupFacts(orgDir)+ facts.AlertRouteCount = intPtr(readAlertRouteCount(orgDir))+ facts.ReportScheduleCount = intPtr(readReportScheduleCount(orgDir))+ return facts+}++func intPtr(value int) *int {+ return &value+}++func readAgentSetupFacts(orgDir string) (*int, *time.Time) {+ var tokens []config.APITokenRecord+ ok, err := readMaybeEncryptedJSON(orgDir, "api_tokens.json", &tokens)+ if err != nil {+ log.Warn().Err(err).Str("org_dir", orgDir).Msg("cloudcp.portal.setup_facts: read api tokens")+ return nil, nil+ }+ if !ok {+ return intPtr(0), nil+ }++ count := 0+ var lastSeen *time.Time+ for i := range tokens {+ if tokens[i].IsExpired() || !tokens[i].HasScope(config.ScopeAgentReport) || tokens[i].LastUsedAt == nil {+ continue+ }+ count+++ if lastSeen == nil || tokens[i].LastUsedAt.After(*lastSeen) {+ seenAt := tokens[i].LastUsedAt.UTC()+ lastSeen = &seenAt+ }+ }+ return intPtr(count), lastSeen+}++func readAlertRouteCount(orgDir string) int {+ count := 0++ var email notifications.EmailConfig+ if ok, err := readMaybeEncryptedJSON(orgDir, "email.enc", &email); err != nil {+ log.Warn().Err(err).Str("org_dir", orgDir).Msg("cloudcp.portal.setup_facts: read email config")+ } else if ok && email.Enabled {+ for _, recipient := range email.To {+ if strings.TrimSpace(recipient) != "" {+ count+++ }+ }+ }++ var apprise notifications.AppriseConfig+ if ok, err := readMaybeEncryptedJSON(orgDir, "apprise.enc", &apprise); err != nil {+ log.Warn().Err(err).Str("org_dir", orgDir).Msg("cloudcp.portal.setup_facts: read apprise config")+ } else if ok && apprise.Enabled {+ for _, target := range apprise.Targets {+ if strings.TrimSpace(target) != "" {+ count+++ }+ }+ }++ var webhooks []notifications.WebhookConfig+ if ok, err := readMaybeEncryptedJSON(orgDir, "webhooks.enc", &webhooks); err != nil {+ log.Warn().Err(err).Str("org_dir", orgDir).Msg("cloudcp.portal.setup_facts: read webhook config")+ } else if !ok {+ _, _ = readMaybeEncryptedJSON(orgDir, "webhooks.json", &webhooks)+ }+ for _, webhook := range webhooks {+ if webhook.Enabled && strings.TrimSpace(webhook.URL) != "" {+ count+++ }+ }++ return count+}++func readReportScheduleCount(orgDir string) int {+ for _, leaf := range []string{"report_schedules.json", filepath.Join("reports", "schedules.json")} {+ var raw json.RawMessage+ ok, err := readMaybeEncryptedJSON(orgDir, leaf, &raw)+ if err != nil {+ log.Warn().Err(err).Str("org_dir", orgDir).Str("file", leaf).Msg("cloudcp.portal.setup_facts: read report schedules")+ continue+ }+ if ok {+ return countReportSchedules(raw)+ }+ }+ return 0+}++func countReportSchedules(raw json.RawMessage) int {+ trimmed := strings.TrimSpace(string(raw))+ if trimmed == "" || trimmed == "null" {+ return 0+ }++ var items []json.RawMessage+ if err := json.Unmarshal(raw, &items); err == nil {+ return countEnabledScheduleItems(items)+ }++ var object map[string]json.RawMessage+ if err := json.Unmarshal(raw, &object); err != nil || len(object) == 0 {+ return 0+ }++ for _, key := range []string{"schedules", "reports", "items"} {+ if value, ok := object[key]; ok {+ var nested []json.RawMessage+ if err := json.Unmarshal(value, &nested); err == nil {+ return countEnabledScheduleItems(nested)+ }+ }+ }++ if isScheduleItemEnabled(raw) {+ return 1+ }+ return 0+}++func countEnabledScheduleItems(items []json.RawMessage) int {+ count := 0+ for _, item := range items {+ if isScheduleItemEnabled(item) {+ count+++ }+ }+ return count+}++func isScheduleItemEnabled(raw json.RawMessage) bool {+ var item map[string]any+ if err := json.Unmarshal(raw, &item); err != nil {+ return false+ }+ if enabled, ok := item["enabled"].(bool); ok && !enabled {+ return false+ }+ if disabled, ok := item["disabled"].(bool); ok && disabled {+ return false+ }+ return len(item) > 0+}++func readMaybeEncryptedJSON(configDir string, leaf string, out any) (bool, error) {+ path, ok := safeConfigLeafPath(configDir, leaf)+ if !ok {+ return false, nil+ }++ data, err := os.ReadFile(path)+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ return false, nil+ }+ return false, err+ }+ if len(strings.TrimSpace(string(data))) == 0 {+ return true, nil+ }++ if err := json.Unmarshal(data, out); err == nil {+ return true, nil+ }++ keyPath := filepath.Join(configDir, ".encryption.key")+ if _, err := os.Stat(keyPath); err != nil {+ return false, err+ }++ manager, err := crypto.NewCryptoManagerAt(configDir)+ if err != nil {+ return false, err+ }+ decrypted, err := manager.Decrypt(data)+ if err != nil {+ return false, err+ }+ if err := json.Unmarshal(decrypted, out); err != nil {+ return false, err+ }+ return true, nil+}++func safeConfigLeafPath(configDir string, leaf string) (string, bool) {+ configDir = strings.TrimSpace(configDir)+ leaf = strings.TrimSpace(leaf)+ if configDir == "" || leaf == "" || filepath.IsAbs(leaf) {+ return "", false+ }+ cleanLeaf := filepath.Clean(leaf)+ if cleanLeaf == "." || cleanLeaf == ".." || strings.HasPrefix(cleanLeaf, ".."+string(os.PathSeparator)) {+ return "", false+ }+ return filepath.Join(configDir, cleanLeaf), true+}diff --git a/internal/cloudcp/portal/setup_facts_test.go b/internal/cloudcp/portal/setup_facts_test.gonew file mode 100644index 0000000000..33cc7c1054--- /dev/null+++ b/internal/cloudcp/portal/setup_facts_test.go@@ -0,0 +1,130 @@+package portal++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/notifications"+)++func writeSetupFactJSON(t *testing.T, dir string, leaf string, payload any) {+ t.Helper()+ data, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("marshal %s: %v", leaf, err)+ }+ path := filepath.Join(dir, leaf)+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatalf("mkdir %s: %v", filepath.Dir(path), err)+ }+ if err := os.WriteFile(path, data, 0o600); err != nil {+ t.Fatalf("write %s: %v", path, err)+ }+}++func TestTenantDirWorkspaceSetupFactReaderCountsTenantFacts(t *testing.T) {+ tenantsDir := t.TempDir()+ orgDir := filepath.Join(tenantsDir, "ws_one", "orgs", "ws_one")+ if err := os.MkdirAll(orgDir, 0o755); err != nil {+ t.Fatal(err)+ }++ lastUsed := time.Date(2026, 4, 1, 10, 0, 0, 0, time.UTC)+ expiredAt := time.Date(2026, 3, 1, 10, 0, 0, 0, time.UTC)+ writeSetupFactJSON(t, orgDir, "api_tokens.json", []config.APITokenRecord{+ {+ ID: "agent-used",+ Name: "Agent",+ Hash: "hash",+ CreatedAt: lastUsed.Add(-time.Hour),+ LastUsedAt: &lastUsed,+ Scopes: []string{config.ScopeAgentReport},+ },+ {+ ID: "agent-generated-only",+ Name: "Generated only",+ Hash: "hash",+ CreatedAt: lastUsed.Add(-time.Hour),+ Scopes: []string{config.ScopeAgentReport},+ },+ {+ ID: "expired-agent",+ Name: "Expired",+ Hash: "hash",+ CreatedAt: expiredAt.Add(-time.Hour),+ LastUsedAt: &expiredAt,+ ExpiresAt: &expiredAt,+ Scopes: []string{config.ScopeAgentReport},+ },+ {+ ID: "settings-only",+ Name: "Settings",+ Hash: "hash",+ CreatedAt: lastUsed.Add(-time.Hour),+ LastUsedAt: &lastUsed,+ Scopes: []string{config.ScopeSettingsRead},+ },+ })+ writeSetupFactJSON(t, orgDir, "email.enc", notifications.EmailConfig{+ Enabled: true,+ To: []string{"[email protected]", " ", "[email protected]"},+ })+ writeSetupFactJSON(t, orgDir, "apprise.enc", notifications.AppriseConfig{+ Enabled: true,+ Targets: []string{"discord://token"},+ })+ writeSetupFactJSON(t, orgDir, "webhooks.enc", []notifications.WebhookConfig{+ {Enabled: true, URL: "https://example.com/hook"},+ {Enabled: false, URL: "https://example.com/disabled"},+ {Enabled: true},+ })+ writeSetupFactJSON(t, orgDir, "report_schedules.json", []map[string]any{+ {"name": "Monthly", "enabled": true},+ {"name": "Disabled", "enabled": false},+ })++ facts := NewTenantDirWorkspaceSetupFactReader(tenantsDir).FactsForWorkspace("ws_one")+ if facts.AgentCount == nil || *facts.AgentCount != 1 {+ t.Fatalf("AgentCount = %v, want 1", facts.AgentCount)+ }+ if facts.LastAgentSeenAt == nil || !facts.LastAgentSeenAt.Equal(lastUsed) {+ t.Fatalf("LastAgentSeenAt = %v, want %v", facts.LastAgentSeenAt, lastUsed)+ }+ if facts.AlertRouteCount == nil || *facts.AlertRouteCount != 4 {+ t.Fatalf("AlertRouteCount = %v, want 4", facts.AlertRouteCount)+ }+ if facts.ReportScheduleCount == nil || *facts.ReportScheduleCount != 1 {+ t.Fatalf("ReportScheduleCount = %v, want 1", facts.ReportScheduleCount)+ }+}++func TestTenantDirWorkspaceSetupFactReaderMissingFactsAreZero(t *testing.T) {+ tenantsDir := t.TempDir()+ orgDir := filepath.Join(tenantsDir, "ws_empty", "orgs", "ws_empty")+ if err := os.MkdirAll(orgDir, 0o755); err != nil {+ t.Fatal(err)+ }++ facts := NewTenantDirWorkspaceSetupFactReader(tenantsDir).FactsForWorkspace("ws_empty")+ if facts.AgentCount == nil || *facts.AgentCount != 0 {+ t.Fatalf("AgentCount = %v, want 0", facts.AgentCount)+ }+ if facts.AlertRouteCount == nil || *facts.AlertRouteCount != 0 {+ t.Fatalf("AlertRouteCount = %v, want 0", facts.AlertRouteCount)+ }+ if facts.ReportScheduleCount == nil || *facts.ReportScheduleCount != 0 {+ t.Fatalf("ReportScheduleCount = %v, want 0", facts.ReportScheduleCount)+ }+}++func TestTenantDirWorkspaceSetupFactReaderRejectsUnsafeTenantID(t *testing.T) {+ tenantsDir := t.TempDir()+ facts := NewTenantDirWorkspaceSetupFactReader(tenantsDir).FactsForWorkspace("../ws")+ if facts.AgentCount != nil || facts.AlertRouteCount != nil || facts.ReportScheduleCount != nil {+ t.Fatalf("unsafe tenant facts = %+v, want empty facts", facts)+ }+}diff --git a/internal/cloudcp/routes.go b/internal/cloudcp/routes.goindex 8cc6da4750..4ae4b9136b 100644--- a/internal/cloudcp/routes.go+++ b/internal/cloudcp/routes.go@@ -68,6 +68,7 @@ func RegisterRoutes(mux *http.ServeMux, deps *Deps) {}accountMutationAuth := requireAnyAccountRole(registry.MemberRoleOwner, registry.MemberRoleAdmin)rawCommercialLookup := newCommercialIdentityLookup(deps.Config)+ portalSetupFacts := portal.NewTenantDirWorkspaceSetupFactReader(deps.Config.TenantsDir())portalCommercialLookup := func(ctx context.Context, email string) (*portal.CommercialIdentity, error) {if rawCommercialLookup == nil {return nil, nil@@ -246,8 +247,8 @@ func RegisterRoutes(mux *http.ServeMux, deps *Deps) {mux.Handle("/api/accounts/{account_id}/tenants/{tenant_id}/handoff", accountAPILimiter.Middleware(accountSessionAuth(accountIDFromPath, handoffHandler)))// MSP portal API (session + account-membership authenticated)- mux.Handle(portal.PortalBootstrapPath, portalAPILimiter.Middleware(sessionAuth(portal.HandlePortalBootstrapWithSignupPath(deps.MagicLinks, deps.Registry, portalCommercialLookup, publicCloudSignupPath))))- mux.Handle(portal.PortalDashboardPath, portalAPILimiter.Middleware(accountSessionAuth(accountIDFromPortalRequest, portal.HandlePortalDashboard(deps.Registry))))+ mux.Handle(portal.PortalBootstrapPath, portalAPILimiter.Middleware(sessionAuth(portal.HandlePortalBootstrapWithSignupPathAndSetupFacts(deps.MagicLinks, deps.Registry, portalCommercialLookup, publicCloudSignupPath, portalSetupFacts))))+ mux.Handle(portal.PortalDashboardPath, portalAPILimiter.Middleware(accountSessionAuth(accountIDFromPortalRequest, portal.HandlePortalDashboardWithSetupFacts(deps.Registry, portalSetupFacts))))mux.Handle(portal.PortalWorkspacePath, portalAPILimiter.Middleware(accountSessionAuth(accountIDFromPortalRequest, portal.HandlePortalWorkspaceDetail(deps.Registry))))// Stripe Customer Portal redirect (session + account-membership authenticated)@@ -262,5 +263,5 @@ func RegisterRoutes(mux *http.ServeMux, deps *Deps) {// MSP/Cloud portal HTML page — self-authenticating (shows login form if no session)portalPageLimiter := NewCPRateLimiter(60, time.Minute)- mux.Handle(portal.PortalPagePath, portalPageLimiter.Middleware(http.HandlerFunc(portal.HandlePortalPageWithSignupPath(deps.MagicLinks, deps.Registry, portalCommercialLookup, controlPlaneFaviconHref(), publicCloudSignupPath))))+ mux.Handle(portal.PortalPagePath, portalPageLimiter.Middleware(http.HandlerFunc(portal.HandlePortalPageWithSignupPathAndSetupFacts(deps.MagicLinks, deps.Registry, portalCommercialLookup, controlPlaneFaviconHref(), publicCloudSignupPath, portalSetupFacts))))}diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.pyindex 28c2050ac8..c94b31f3c9 100644--- a/scripts/release_control/subsystem_lookup_test.py+++ b/scripts/release_control/subsystem_lookup_test.py@@ -2860,7 +2860,7 @@ class SubsystemLookupTest(unittest.TestCase):{"heading": "## Shared Boundaries","path": "internal/api/access_control_handlers.go",- "line": 306,+ "line": 313,"heading_line": 112,}],