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
Gate mobile pairing codes on relay readiness
rcourtmanc759c9a77a46
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 68eafea28d..8a30cdd55a 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -2352,6 +2352,12 @@ deep-link, and validation reads in `internal/api/router_routes_ai_relay.go`must accept that `relay:mobile:access` scope directly instead of demanding thebroader settings-read privilege that the pairing token was never meant tocarry.+That same bootstrap dependency assumes the API-owned onboarding readiness+gate remains authoritative. Lifecycle-adjacent setup must surface the backend+`409 onboarding_not_ready` diagnostics when relay registration, Remote Access,+or the dedicated mobile credential is incomplete, rather than generating a+partial QR/deep-link payload or retrying through broader settings-read+credentials.That same adjacent `internal/api/` reporting surface also keeps lifecycle-adjacent automation on the canonical time-window transport contract. Any setup,handoff, or scheduled lifecycle flow that triggers performance reports mustdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 1ba0c0f776..43314d960e 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -136,6 +136,13 @@ product API routes free of maintainer commercial analytics.## Shared Boundaries+Mobile onboarding QR/deep-link payload readiness is a shared backend/frontend+contract. `internal/api/onboarding_handlers.go` owns the `409+onboarding_not_ready` diagnostic response when Remote Access, relay+registration, or the dedicated Pulse Mobile credential is incomplete, while+`frontend-modern/src/api/onboarding.ts` and relay settings consumers may only+surface those diagnostics and must not synthesize partial pairing payloads.+Assistant chat `workflow_state` events are a shared AI/API payload boundary.The backend source of truth is `internal/ai/chat.WorkflowStateData`, generatedto `frontend-modern/src/api/generated/aiChatEvents.ts` by@@ -6553,6 +6560,15 @@ also accept the dedicated `relay:mobile:access` scope for`/api/onboarding/qr`, `/api/onboarding/validate`, and`/api/onboarding/deep-link`, because those payloads are the canonicalbootstrap surface for the server-minted mobile credential.+That same onboarding boundary now also owns mobile pairing readiness. The QR+and deep-link reads in `internal/api/onboarding_handlers.go` must return+`409 onboarding_not_ready` with structured diagnostics instead of emitting a+deep link whenever Remote Access is disabled, the relay runtime has not+reported a connected `instance_id`, or the request lacks the dedicated+server-minted mobile credential. A successful QR/deep-link response therefore+continues to mean the payload contains the exact relay registration and token+material Pulse Mobile can validate, while settings surfaces consume the+diagnostics for operator-visible readiness copy.The shared security token contract now also includes single-record metadatareads. `internal/api/security_tokens.go`,`internal/api/router_routes_auth_security.go`,diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.mdindex c3a00c14a7..18f05ea6bf 100644--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md@@ -215,6 +215,12 @@ Stripe-free and avoids a cloud-control-plane report data path across clients.visible banner shell, icon, action slot, and dismiss chrome must compose theshared `InlineNotice` primitive instead of carrying local paid-state toneclasses, raw SVGs, or page-local buttons.+ Pulse Mobile pairing inside `frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts`+ is also a commercial relay surface only for entitlement and operator+ presentation. When the backend returns `409 onboarding_not_ready`, the+ settings surface must preserve API-owned diagnostics and clean up the+ temporary server-minted mobile token; it must not downgrade that response+ into a generic paid-state prompt or create browser-owned relay credentials.2. `frontend-modern/src/components/Settings/MonitoredSystemImpactPreview.tsx` shared with `agent-lifecycle`: the monitored-system impact preview is both a platform-connections lifecycle surface and a canonical cloud-paid monitored-system presentation boundary.3. `frontend-modern/src/useAppRuntimeState.ts` shared with `performance-and-scalability`: the authenticated app runtime bootstrap is both a hosted commercial org-context boundary and a protected app-shell performance boundary.4. `internal/api/licensing_bridge.go` shared with `api-contracts`: commercial licensing bridge handlers carry both API payload contract and cloud-paid entitlement boundary ownership.diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 898df884b9..5ac2eac1d3 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -209,6 +209,10 @@ regression protection.validate request-body setup tokens, but the router-level public-path check muststay O(1) and must not front-run persistence loads, monitor refresh, or otherteardown/register side effects before the canonical handler owns the request.+ Test seams around the router's relay runtime client may expose the current+ relay status to onboarding handlers, but they must remain in-memory+ interface boundaries and must not add persistence probes, network reconnects,+ or metrics fan-out to QR/deep-link request handling.`/api/config/export` and `/api/config/import` follow the same hot-path rule:router auth bypass exists only to let their handlers make route-local auth andpublic-network decisions, and the bypass check must remain a constant-timediff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex 5ff010c30f..218d6c5fac 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -228,6 +228,11 @@ existing resource-policy redaction still governs any model-bound context.metadata, or remediation output.2. Change security policy, hardening guidance, or supported auth boundaries through `SECURITY.md`.3. Change telemetry/privacy settings state handling through `frontend-modern/src/components/Settings/useSystemSettingsState.ts`.+ Relay runtime access through `internal/api/router.go` must stay behind the+ existing protected route and API-token gates. Testable router seams may+ expose relay status to onboarding validation, but they must not broaden+ Pulse Mobile token scopes, bypass the server-minted credential requirement,+ or expose relay secrets beyond the existing public onboarding diagnostics.4. Change security/auth/token transport behavior through the shared `frontend-modern/src/api/security.ts`, `frontend-modern/src/components/Settings/APITokenManager.tsx`, `frontend-modern/src/components/Settings/apiTokenManagerModel.ts`, `frontend-modern/src/components/Settings/useAPITokenManagerState.ts`, `internal/api/security.go`, `internal/api/security_tokens.go`, and `internal/api/system_settings.go` boundary.Release metadata surfaced through `/api/version` remains outside token,auth, and privacy state. Adding or changing `agentUpdateTargetVersion`diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 5112f163d4..7cfa5f0396 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -63,6 +63,13 @@ state.## Extension Points+Mobile onboarding reads exposed through `internal/api/onboarding_handlers.go`+are storage/recovery-adjacent only as hosted recovery/support handoff+surfaces. Recovery code may consume the API-owned+`409 onboarding_not_ready` diagnostics, but it must not construct a partial+mobile pairing QR/deep-link payload from relay settings when relay+registration or the dedicated Pulse Mobile credential is incomplete.+Shared command-agent token binding in `internal/api/agent_exec_token_binding.go`is API-owned adjacent infrastructure. Storage- and recovery-adjacent setup ordiagnostics flows may observe the API-owned `bound_agent_id`,@@ -3621,6 +3628,12 @@ connection-validation reads, so hosted recovery/support flows that hand apaired device back into onboarding do not need to escalate the mobile token tothe broader settings-read privilege just to fetch the canonical bootstrappayload.+Those adjacent reads must also preserve the API-owned readiness semantics:+when Remote Access is disabled, relay registration has not supplied a connected+`instance_id`, or the dedicated mobile credential is missing, recovery and+support surfaces must surface the backend `409 onboarding_not_ready`+diagnostics rather than constructing a partial mobile pairing payload from+relay settings or retrying with broader settings credentials.That same adjacent `internal/api/` boundary also owns provider-backed recoveryonboarding. Storage and recovery may consume resulting TrueNAS snapshots andreplication points, but connection CRUD, masked-secret preservation on update,diff --git a/frontend-modern/src/api/__tests__/onboarding.test.ts b/frontend-modern/src/api/__tests__/onboarding.test.tsindex 22cd593ee1..669455bcef 100644--- a/frontend-modern/src/api/__tests__/onboarding.test.ts+++ b/frontend-modern/src/api/__tests__/onboarding.test.ts@@ -1,9 +1,10 @@import { describe, expect, it, vi, beforeEach } from 'vitest';-import { OnboardingAPI, type OnboardingQRResponse } from '../onboarding';-import { apiFetchJSON } from '@/utils/apiClient';+import { OnboardingAPI, OnboardingNotReadyError, type OnboardingQRResponse } from '../onboarding';+import { apiErrorFromResponse, apiFetch } from '@/utils/apiClient';vi.mock('@/utils/apiClient', () => ({- apiFetchJSON: vi.fn(),+ apiErrorFromResponse: vi.fn(),+ apiFetch: vi.fn(),}));describe('OnboardingAPI', () => {@@ -21,11 +22,13 @@ describe('OnboardingAPI', () => {auth_token: 'token-123',deep_link: 'pulse://connect',};- vi.mocked(apiFetchJSON).mockResolvedValueOnce(mockResponse);+ vi.mocked(apiFetch).mockResolvedValueOnce(+ new Response(JSON.stringify(mockResponse), { status: 200 }),+ );const result = await OnboardingAPI.getQRPayload();- expect(apiFetchJSON).toHaveBeenCalledWith('/api/onboarding/qr');+ expect(apiFetch).toHaveBeenCalledWith('/api/onboarding/qr');expect(result).toEqual(mockResponse);});@@ -38,13 +41,54 @@ describe('OnboardingAPI', () => {auth_token: 'token-123',deep_link: 'pulse://connect',};- vi.mocked(apiFetchJSON).mockResolvedValueOnce(mockResponse);+ vi.mocked(apiFetch).mockResolvedValueOnce(+ new Response(JSON.stringify(mockResponse), { status: 200 }),+ );await OnboardingAPI.getQRPayload('token-123');- expect(apiFetchJSON).toHaveBeenCalledWith('/api/onboarding/qr', {+ expect(apiFetch).toHaveBeenCalledWith('/api/onboarding/qr', {headers: { 'X-API-Token': 'token-123' },});});++ it('throws readiness diagnostics when the backend refuses an incomplete pairing payload', async () => {+ const diagnostics = [+ {+ code: 'relay_registration_unavailable',+ severity: 'error' as const,+ message: 'Remote Access is enabled, but this Pulse instance is not connected yet.',+ field: 'instance_id',+ },+ ];+ vi.mocked(apiFetch).mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ code: 'onboarding_not_ready',+ message: 'Pulse Mobile pairing is not ready yet.',+ diagnostics,+ }),+ { status: 409 },+ ),+ );++ await expect(OnboardingAPI.getQRPayload('token-123')).rejects.toMatchObject({+ name: 'OnboardingNotReadyError',+ code: 'onboarding_not_ready',+ status: 409,+ diagnostics,+ } satisfies Partial<OnboardingNotReadyError>);+ });++ it('delegates non-readiness failures to the shared API error parser', async () => {+ const response = new Response('server failed', { status: 500 });+ const parsedError = new Error('parsed server failure');+ vi.mocked(apiFetch).mockResolvedValueOnce(response);+ vi.mocked(apiErrorFromResponse).mockResolvedValueOnce(parsedError);++ await expect(OnboardingAPI.getQRPayload('token-123')).rejects.toBe(parsedError);++ expect(apiErrorFromResponse).toHaveBeenCalledWith(response);+ });});});diff --git a/frontend-modern/src/api/onboarding.ts b/frontend-modern/src/api/onboarding.tsindex b1f4c2132b..9fb1ef87af 100644--- a/frontend-modern/src/api/onboarding.ts+++ b/frontend-modern/src/api/onboarding.ts@@ -1,4 +1,4 @@-import { apiFetchJSON } from '@/utils/apiClient';+import { apiErrorFromResponse, apiFetch } from '@/utils/apiClient';export interface OnboardingRelayDetails {enabled: boolean;@@ -26,15 +26,63 @@ export interface OnboardingQRResponse {diagnostics?: OnboardingDiagnostic[];}+export interface OnboardingNotReadyResponse {+ code: string;+ error?: string;+ message?: string;+ diagnostics?: OnboardingDiagnostic[];+}++export class OnboardingNotReadyError extends Error {+ readonly code: string;+ readonly status: number;+ readonly diagnostics: OnboardingDiagnostic[];++ constructor(response: OnboardingNotReadyResponse, status: number) {+ super(response.message || response.error || 'Pulse Mobile pairing is not ready yet.');+ this.name = 'OnboardingNotReadyError';+ this.code = response.code;+ this.status = status;+ this.diagnostics = response.diagnostics ?? [];+ }+}++const readJSON = async (response: Response): Promise<unknown> => {+ try {+ return await response.json();+ } catch {+ return null;+ }+};++const isOnboardingNotReadyResponse = (value: unknown): value is OnboardingNotReadyResponse => {+ if (!value || typeof value !== 'object') {+ return false;+ }+ const candidate = value as Partial<OnboardingNotReadyResponse>;+ return candidate.code === 'onboarding_not_ready';+};+export class OnboardingAPI {private static baseUrl = '/api/onboarding';static async getQRPayload(authToken?: string): Promise<OnboardingQRResponse> {- if (!authToken) {- return apiFetchJSON(this.baseUrl + '/qr') as Promise<OnboardingQRResponse>;+ const url = this.baseUrl + '/qr';+ const response = authToken+ ? await apiFetch(url, { headers: { 'X-API-Token': authToken } })+ : await apiFetch(url);++ if (response.ok) {+ return (await response.json()) as OnboardingQRResponse;+ }++ if (response.status === 409) {+ const body = await readJSON(response.clone());+ if (isOnboardingNotReadyResponse(body)) {+ throw new OnboardingNotReadyError(body, response.status);+ }}- return apiFetchJSON(this.baseUrl + '/qr', {- headers: { 'X-API-Token': authToken },- }) as Promise<OnboardingQRResponse>;++ throw await apiErrorFromResponse(response);}}diff --git a/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx b/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsxindex befb43bf0f..4ae6c756f5 100644--- a/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.runtime.test.tsx@@ -19,6 +19,23 @@ const loggerErrorMock = vi.fn();const loggerWarnMock = vi.fn();const qrToDataUrlMock = vi.fn();+const MockOnboardingNotReadyError = vi.hoisted(+ () =>+ class MockOnboardingNotReadyError extends Error {+ readonly code = 'onboarding_not_ready';+ readonly status = 409;+ readonly diagnostics: Array<{ code: string; severity: 'warning' | 'error'; message: string }>;++ constructor(+ diagnostics: Array<{ code: string; severity: 'warning' | 'error'; message: string }>,+ ) {+ super('Pulse Mobile pairing is not ready yet.');+ this.name = 'OnboardingNotReadyError';+ this.diagnostics = diagnostics;+ }+ },+);+vi.mock('@/stores/license', () => ({hasFeature: (...args: unknown[]) => hasFeatureMock(...args),runtimeCapabilitiesLoaded: () => true,@@ -45,6 +62,7 @@ vi.mock('@/api/relay', () => ({}));vi.mock('@/api/onboarding', () => ({+ OnboardingNotReadyError: MockOnboardingNotReadyError,OnboardingAPI: {getQRPayload: (...args: unknown[]) => getQRPayloadMock(...args),},@@ -284,6 +302,35 @@ describe('RelaySettingsPanel runtime', () => {expect(screen.queryByAltText('Pulse mobile pairing QR code')).not.toBeInTheDocument();});+ it('shows onboarding readiness diagnostics when pairing payload generation is gated', async () => {+ const diagnosticMessage =+ 'Remote Access is enabled, but this Pulse instance is not connected to the relay yet.';+ getQRPayloadMock.mockRejectedValueOnce(+ new MockOnboardingNotReadyError([+ {+ code: 'relay_registration_unavailable',+ severity: 'error',+ message: diagnosticMessage,+ },+ ]),+ );++ render(() => <RelaySettingsPanel canManage />);++ await waitFor(() => {+ expect(screen.getByDisplayValue('wss://relay.example.test/ws/instance')).toBeInTheDocument();+ });++ fireEvent.click(screen.getByRole('button', { name: 'Pair New Device' }));++ await waitFor(() => {+ expect(deleteTokenMock).toHaveBeenCalledWith('relay-token-1');+ });++ expect(showErrorMock).toHaveBeenCalledWith(diagnosticMessage);+ expect(screen.queryByAltText('Pulse mobile pairing QR code')).not.toBeInTheDocument();+ });+it('replaces the previous pairing token when refreshing the QR code', async () => {createTokenMock.mockResolvedValueOnce({diff --git a/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.test.ts b/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.test.tsindex 88b94c94a2..1f5f32063f 100644--- a/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.test.ts+++ b/frontend-modern/src/components/Settings/__tests__/RelaySettingsPanel.test.ts@@ -21,7 +21,8 @@ const relaySettingsPanelSource = Object.values(describe('OnboardingAPI', () => {it('getQRPayload calls /api/onboarding/qr', () => {expect(onboardingSource).toContain("private static baseUrl = '/api/onboarding';");- expect(onboardingSource).toContain("apiFetchJSON(this.baseUrl + '/qr')");+ expect(onboardingSource).toContain("const url = this.baseUrl + '/qr';");+ expect(onboardingSource).toContain('throw new OnboardingNotReadyError');});});@@ -41,6 +42,8 @@ describe('Onboarding QR payload contract', () => {expect(onboardingSource).toContain('auth_token: string;');expect(onboardingSource).toContain('deep_link: string;');expect(onboardingSource).toContain('diagnostics?: OnboardingDiagnostic[];');+ expect(onboardingSource).toContain('export interface OnboardingNotReadyResponse');+ expect(onboardingSource).toContain('export class OnboardingNotReadyError');});it('keeps relay settings split into shell, runtime, and pairing owners', () => {diff --git a/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts b/frontend-modern/src/components/Settings/useRelaySettingsPanelState.tsindex 124e31dc74..4407e09436 100644--- a/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts+++ b/frontend-modern/src/components/Settings/useRelaySettingsPanelState.ts@@ -5,7 +5,11 @@ import { presentationPolicyHidesUpgradePrompts } from '@/stores/sessionPresentatimport { loadRuntimeCapabilities } from '@/stores/license';import { showError, showSuccess } from '@/utils/toast';import { RelayAPI, type RelayConfig, type RelayStatus } from '@/api/relay';-import { OnboardingAPI, type OnboardingQRResponse } from '@/api/onboarding';+import {+ OnboardingAPI,+ OnboardingNotReadyError,+ type OnboardingQRResponse,+} from '@/api/onboarding';import { SecurityAPI, type APITokenRecord } from '@/api/security';import { logger } from '@/utils/logger';import {@@ -84,6 +88,17 @@ export function useRelaySettingsPanelState(props: RelaySettingsPanelProps) {}};+ const pairingGenerationErrorMessage = (error: unknown): string => {+ if (error instanceof OnboardingNotReadyError) {+ return (+ error.diagnostics.find((diagnostic) => diagnostic.severity === 'error')?.message ||+ error.message ||+ 'Pulse Mobile pairing is not ready yet.'+ );+ }+ return 'Failed to generate pairing QR code';+ };+const loadConfig = async () => {try {const nextConfig = await RelayAPI.getConfig();@@ -216,7 +231,7 @@ export function useRelaySettingsPanelState(props: RelaySettingsPanelProps) {setPairingPayload(previousPayload);setPairingQRCode(previousQRCode);setPairingTokenId(previousTokenId);- showError('Failed to generate pairing QR code');+ showError(pairingGenerationErrorMessage(error));logger.error('[RelaySettings] Failed to generate onboarding QR', error);} finally {setPairingLoading(false);diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 91a4a865ad..ea29daed68 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -8812,6 +8812,36 @@ func TestContract_OnboardingQRResponseJSONSnapshot(t *testing.T) {assertJSONSnapshot(t, got, want)}+func TestContract_OnboardingNotReadyResponseJSONSnapshot(t *testing.T) {+ payload := onboardingNotReadyResponse{+ Code: onboardingNotReadyCode,+ Error: onboardingNotReadyMessage,+ Message: onboardingNotReadyMessage,+ Diagnostics: []onboardingDiagnostic{+ {+ Code: "relay_registration_unavailable",+ Severity: "error",+ Field: "instance_id",+ Message: "Remote Access is enabled, but this Pulse instance is not connected to the relay yet. Wait for the status to show Connected before generating a mobile pairing code.",+ },+ },+ }++ got, err := json.Marshal(payload)+ if err != nil {+ t.Fatalf("marshal onboarding not-ready response: %v", err)+ }++ const want = `{+ "code":"onboarding_not_ready",+ "error":"Pulse Mobile pairing is not ready yet.",+ "message":"Pulse Mobile pairing is not ready yet.",+ "diagnostics":[{"code":"relay_registration_unavailable","severity":"error","message":"Remote Access is enabled, but this Pulse instance is not connected to the relay yet. Wait for the status to show Connected before generating a mobile pairing code.","field":"instance_id"}]+ }`++ assertJSONSnapshot(t, got, want)+}+func TestContract_HostedRelayConfigResponseJSONSnapshot(t *testing.T) {router, _, instanceHost := newHostedRelayRuntimeTestRouter(t)diff --git a/internal/api/onboarding_handlers.go b/internal/api/onboarding_handlers.goindex ba10ee71aa..c82aa3b095 100644--- a/internal/api/onboarding_handlers.go+++ b/internal/api/onboarding_handlers.go@@ -13,6 +13,8 @@ import ()const onboardingSchemaVersion = "pulse-mobile-onboarding-v1"+const onboardingNotReadyCode = "onboarding_not_ready"+const onboardingNotReadyMessage = "Pulse Mobile pairing is not ready yet."type onboardingRelayDetails struct {Enabled bool `json:"enabled"`@@ -56,6 +58,13 @@ type onboardingDiagnostic struct {Received string `json:"received,omitempty"`}+type onboardingNotReadyResponse struct {+ Code string `json:"code"`+ Error string `json:"error"`+ Message string `json:"message"`+ Diagnostics []onboardingDiagnostic `json:"diagnostics"`+}+func emptyOnboardingQRResponse() onboardingQRResponse {return onboardingQRResponse{}.normalizeCollections()}@@ -107,6 +116,10 @@ func (r *Router) handleGetOnboardingQR(w http.ResponseWriter, req *http.Request)}payload, diagnostics := r.buildOnboardingPayload(req, relayCfg, onboardingAuthTokenFromRequest(req))+ if hasOnboardingError(diagnostics) {+ writeOnboardingNotReady(w, diagnostics)+ return+ }if len(diagnostics) > 0 {payload.Diagnostics = diagnostics}@@ -249,6 +262,10 @@ func (r *Router) handleGetOnboardingDeepLink(w http.ResponseWriter, req *http.Re}payload, diagnostics := r.buildOnboardingPayload(req, relayCfg, onboardingAuthTokenFromRequest(req))+ if hasOnboardingError(diagnostics) {+ writeOnboardingNotReady(w, diagnostics)+ return+ }response := onboardingDeepLinkResponse{URL: payload.DeepLink,Diagnostics: diagnostics,@@ -280,36 +297,57 @@ func (r *Router) buildOnboardingPayload(req *http.Request, relayCfg *relay.ConfiIdentityPublicKey: strings.TrimSpace(relayCfg.IdentityPublicKey),}.normalizeCollections()payload.AuthToken = authToken- payload.DeepLink = buildOnboardingDeepLink(payload)diagnostics := make([]onboardingDiagnostic, 0, 4)if !payload.Relay.Enabled {diagnostics = append(diagnostics, onboardingDiagnostic{Code: "relay_disabled",- Severity: "warning",+ Severity: "error",Field: "relay.enabled",- Message: "Relay is disabled. Hosted mobile connection will not work until relay is enabled.",+ Message: "Remote Access is disabled. Turn on Remote Access and wait for the relay status to show Connected before pairing Pulse Mobile.",})}if payload.InstanceID == "" {diagnostics = append(diagnostics, onboardingDiagnostic{- Code: "instance_id_unavailable",- Severity: "warning",+ Code: "relay_registration_unavailable",+ Severity: "error",Field: "instance_id",- Message: "Relay instance_id is not available until relay registration succeeds.",+ Message: "Remote Access is enabled, but this Pulse instance is not connected to the relay yet. Wait for the status to show Connected before generating a mobile pairing code.",})}if payload.AuthToken == "" {diagnostics = append(diagnostics, onboardingDiagnostic{Code: "auth_token_missing",- Severity: "warning",+ Severity: "error",Field: "auth_token",- Message: "No API token was provided in the request. Include X-API-Token or Authorization: Bearer for QR bootstrap payloads.",+ Message: "A dedicated Pulse Mobile access token is required before generating a pairing code.",})}+ if !hasOnboardingError(diagnostics) {+ payload.DeepLink = buildOnboardingDeepLink(payload)+ }return payload, diagnostics}+func writeOnboardingNotReady(w http.ResponseWriter, diagnostics []onboardingDiagnostic) {+ response := onboardingNotReadyResponse{+ Code: onboardingNotReadyCode,+ Error: onboardingNotReadyMessage,+ Message: onboardingNotReadyMessage,+ Diagnostics: normalizeOnboardingDiagnostics(diagnostics),+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusConflict)+ _ = json.NewEncoder(w).Encode(response)+}++func normalizeOnboardingDiagnostics(diagnostics []onboardingDiagnostic) []onboardingDiagnostic {+ if diagnostics == nil {+ return []onboardingDiagnostic{}+ }+ return diagnostics+}+func (r *Router) loadRelayConfigForOnboarding() (*relay.Config, error) {return r.loadRelayConfigForRuntime(context.Background())}diff --git a/internal/api/onboarding_handlers_test.go b/internal/api/onboarding_handlers_test.goindex c4be894688..5d70ef6676 100644--- a/internal/api/onboarding_handlers_test.go+++ b/internal/api/onboarding_handlers_test.go@@ -39,6 +39,9 @@ func TestOnboardingQRPayloadStructure(t *testing.T) {if payload.InstanceURL != "https://pulse.example.test" {t.Fatalf("unexpected instance_url: %q", payload.InstanceURL)}+ if payload.InstanceID != "instance-local" {+ t.Fatalf("unexpected instance_id: got %q want %q", payload.InstanceID, "instance-local")+ }if payload.Relay.URL != wantRelayURL {t.Fatalf("unexpected relay URL: got %q want %q", payload.Relay.URL, wantRelayURL)}@@ -53,6 +56,53 @@ func TestOnboardingQRPayloadStructure(t *testing.T) {}}+func TestOnboardingQRRejectsIncompleteRelayRegistration(t *testing.T) {+ router, rawToken, _ := newOnboardingContractRouter(t)+ router.relayClient = nil++ req := httptest.NewRequest(http.MethodGet, "https://pulse.example.test/api/onboarding/qr", nil)+ req.Header.Set("X-API-Token", rawToken)+ rec := httptest.NewRecorder()++ router.handleGetOnboardingQR(rec, req)++ if rec.Code != http.StatusConflict {+ t.Fatalf("expected status 409, got %d: %s", rec.Code, rec.Body.String())+ }++ var response onboardingNotReadyResponse+ if err := json.NewDecoder(rec.Body).Decode(&response); err != nil {+ t.Fatalf("decode not-ready response: %v", err)+ }+ if response.Code != onboardingNotReadyCode {+ t.Fatalf("unexpected code: got %q want %q", response.Code, onboardingNotReadyCode)+ }+ if !diagnosticCodePresent(response.Diagnostics, "relay_registration_unavailable") {+ t.Fatalf("expected relay_registration_unavailable diagnostic, got %#v", response.Diagnostics)+ }+}++func TestOnboardingQRRejectsMissingMobileToken(t *testing.T) {+ router, _, _ := newOnboardingContractRouter(t)++ req := httptest.NewRequest(http.MethodGet, "https://pulse.example.test/api/onboarding/qr", nil)+ rec := httptest.NewRecorder()++ router.handleGetOnboardingQR(rec, req)++ if rec.Code != http.StatusConflict {+ t.Fatalf("expected status 409, got %d: %s", rec.Code, rec.Body.String())+ }++ var response onboardingNotReadyResponse+ if err := json.NewDecoder(rec.Body).Decode(&response); err != nil {+ t.Fatalf("decode not-ready response: %v", err)+ }+ if !diagnosticCodePresent(response.Diagnostics, "auth_token_missing") {+ t.Fatalf("expected auth_token_missing diagnostic, got %#v", response.Diagnostics)+ }+}+func TestOnboardingValidateSuccessAndFailure(t *testing.T) {router, rawToken, _ := newOnboardingContractRouter(t)@@ -146,6 +196,28 @@ func TestOnboardingDeepLinkFormat(t *testing.T) {}}+func TestOnboardingDeepLinkRejectsIncompleteRelayRegistration(t *testing.T) {+ router, rawToken, _ := newOnboardingContractRouter(t)+ router.relayClient = nil++ req := httptest.NewRequest(http.MethodGet, "https://pulse.example.test/api/onboarding/deep-link", nil)+ req.Header.Set("Authorization", "Bearer "+rawToken)+ rec := httptest.NewRecorder()+ router.handleGetOnboardingDeepLink(rec, req)++ if rec.Code != http.StatusConflict {+ t.Fatalf("expected status 409, got %d: %s", rec.Code, rec.Body.String())+ }++ var response onboardingNotReadyResponse+ if err := json.NewDecoder(rec.Body).Decode(&response); err != nil {+ t.Fatalf("decode not-ready response: %v", err)+ }+ if !diagnosticCodePresent(response.Diagnostics, "relay_registration_unavailable") {+ t.Fatalf("expected relay_registration_unavailable diagnostic, got %#v", response.Diagnostics)+ }+}+func TestOnboardingResponsesUseCanonicalEmptyCollections(t *testing.T) {qrJSON, err := json.Marshal(emptyOnboardingQRResponse())if err != nil {@@ -263,6 +335,12 @@ func newOnboardingContractRouter(t *testing.T) (*Router, string, relay.Config) {router := &Router{config: cfg,persistence: config.NewConfigPersistence(dataPath),+ relayClient: fakeRelayRuntimeClient{+ status: relay.ClientStatus{+ Connected: true,+ InstanceID: "instance-local",+ },+ },}relayCfg := relay.Config{@@ -278,6 +356,20 @@ func newOnboardingContractRouter(t *testing.T) (*Router, string, relay.Config) {return router, rawToken, relayCfg}+type fakeRelayRuntimeClient struct {+ status relay.ClientStatus+}++func (f fakeRelayRuntimeClient) Status() relay.ClientStatus {+ return f.status+}++func (f fakeRelayRuntimeClient) Close() {}++func (f fakeRelayRuntimeClient) SendPushNotification(relay.PushNotificationPayload) error {+ return nil+}+func diagnosticCodePresent(diagnostics []onboardingDiagnostic, code string) bool {for _, diagnostic := range diagnostics {if diagnostic.Code == code {diff --git a/internal/api/router.go b/internal/api/router.goindex b4cf08d365..f4bea7eab7 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -80,6 +80,12 @@ type cachedWorkloadChartsEntry struct {cachedAt time.Time}+type relayRuntimeClient interface {+ Status() relay.ClientStatus+ Close()+ SendPushNotification(relay.PushNotificationPayload) error+}+// Router handles HTTP routingtype Router struct {mux *http.ServeMux@@ -163,7 +169,7 @@ type Router struct {workloadsSummaryCharts map[string]summaryChartsCacheEntryinstallScriptClient *http.ClientrelayMu sync.RWMutex- relayClient *relay.Client+ relayClient relayRuntimeClientrelayCancel context.CancelFunclifecycleCtx context.ContextlifecycleCancel context.CancelFuncdiff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.pyindex ac92725213..05a9218be3 100644--- a/scripts/release_control/subsystem_lookup_test.py+++ b/scripts/release_control/subsystem_lookup_test.py@@ -2917,7 +2917,7 @@ class SubsystemLookupTest(unittest.TestCase):{"heading": "## Shared Boundaries","path": "internal/api/access_control_handlers.go",- "line": 1099,+ "line": 1106,"heading_line": 137,}],