Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Use shared API error extraction for reporting

rcourtman71c2df99578b
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index ebdccb5902..4b9e7832b8 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -270,7 +270,21 @@ instance, not as a generic purchase funnel. Recovery-contact fields such as
work email and optional company name must remain clearly secondary to the
instance-bound entitlement handoff. Hosted form-stage issuance conflicts must
also preserve the canonical reason shape: duplicate recovery-email usage must
-not be flattened into an organization-level message.
+not be flattened into an organization-level message, and terminal conflicts
+must render as owned hosted outcome UX rather than editable inline form state.
+Expired or invalid hosted backup-link states must follow that same rule rather
+than falling back to a form with missing Pulse initiation context.
+Hosted service/configuration failures during verification, hosted checkout
+preparation, or checkout-session creation must also render as owned
+"temporarily unavailable" outcome UX rather than inline form errors.
+The self-hosted activation return notice on `/settings/system-pro` is part of
+that same boundary: the `trial` query result is a one-shot handoff outcome and
+must be consumed into owned UI state, then removed from the URL rather than
+becoming sticky page state across refresh and sharing.
+That same shared notice owner must also keep activation-result framing
+customer-facing: replayed handoffs should confirm the current entitlement state
+rather than reading like a fresh failure, while invalid and unavailable states
+should direct the operator back to the secure trial handoff on this instance.
That same hosted owner also applies after Stripe returns to
`/trial-signup/complete`: customer-facing completion failures must stay inside
owned trial UX rather than dropping raw control-plane error strings, and they
@@ -630,6 +644,11 @@ MSP tenant provisioning must seed a canonical tenant-scoped `org.json` under
hosted runtime user; otherwise hosted magic-link handoff can preserve the
correct tenant org cookie while the tenant API still fails closed with
`invalid_org` because no tenant organization metadata exists on disk.
+That same shared browser client boundary also owns structured error extraction
+for hosted tenant requests. Cloud and MSP surfaces may show failures from
+`frontend-modern/src/utils/apiClient.ts`, but they must resolve canonical JSON
+`error` / `message` fields before showing UI feedback instead of leaking raw
+response payloads while tenant-scoped org headers are still in flight.
Hosted tenant runtime env is part of the same contract too: provisioned
containers must carry hosted-safe tenant context such as
`PULSE_TENANT_ID=<tenant-id>`, `PULSE_MULTI_TENANT_ENABLED=true`, and an explicit
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 2fb173068a..6e371004e9 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -208,6 +208,10 @@ helpers.
That same fallback contract also includes the single-report filename subject,
so frontend download builders may not substitute resource display names when
the catalog says fallback attachment names are keyed off canonical resource IDs.
+That same reporting shell must also route failed catalog/report/export
+responses through the shared API error extractor in `frontend-modern/src/utils/apiClient.ts`
+rather than surfacing raw JSON payload text from `response.text()` directly in
+warning UI.
That same reporting transport contract also means the frontend download path
must prefer the backend `Content-Disposition` filename over any locally built
fallback name when a report or inventory export response arrives.
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index 67b483f7e0..35292a463d 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -1104,6 +1104,7 @@ describe('Settings architecture guardrails', () => {
expect(reportingPanelStateSource).not.toContain('!licenseLoaded()');
expect(reportingPanelStateSource).not.toContain('!isReportingEnabled()');
expect(reportingPanelStateSource).toContain('buildVMInventoryExportRequest');
+ expect(reportingPanelStateSource).toContain('apiErrorFromResponse');
expect(reportingPanelStateSource).toContain('getReportingGenerateSuccessMessage');
expect(reportingPanelStateSource).toContain('resolveReportingDownloadFilename');
expect(reportingPanelStateSource).not.toContain("'advanced_reporting'");
diff --git a/frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts b/frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts
index 9d36220757..b0ce21bb7c 100644
--- a/frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts
@@ -89,9 +89,13 @@ describe('useReportingPanelState', () => {
hasReportingFeature = true;
loadLicenseStatusMock = vi.fn();
- vi.doMock('@/utils/apiClient', () => ({
- apiFetch: apiFetchMock,
- }));
+ vi.doMock('@/utils/apiClient', async () => {
+ const actual = await vi.importActual<typeof import('@/utils/apiClient')>('@/utils/apiClient');
+ return {
+ ...actual,
+ apiFetch: apiFetchMock,
+ };
+ });
vi.doMock('@/utils/toast', () => ({
showSuccess: vi.fn(),
@@ -173,9 +177,13 @@ describe('useReportingPanelState', () => {
hasReportingFeature = false;
loadLicenseStatusMock = vi.fn();
- vi.doMock('@/utils/apiClient', () => ({
- apiFetch: apiFetchMock,
- }));
+ vi.doMock('@/utils/apiClient', async () => {
+ const actual = await vi.importActual<typeof import('@/utils/apiClient')>('@/utils/apiClient');
+ return {
+ ...actual,
+ apiFetch: apiFetchMock,
+ };
+ });
vi.doMock('@/utils/toast', () => ({
showSuccess: vi.fn(),
@@ -222,9 +230,13 @@ describe('useReportingPanelState', () => {
.mockResolvedValueOnce(new Response('temporary failure', { status: 500 }))
.mockResolvedValueOnce(new Response(JSON.stringify(catalogPayload), { status: 200 }));
- vi.doMock('@/utils/apiClient', () => ({
- apiFetch: apiFetchMock,
- }));
+ vi.doMock('@/utils/apiClient', async () => {
+ const actual = await vi.importActual<typeof import('@/utils/apiClient')>('@/utils/apiClient');
+ return {
+ ...actual,
+ apiFetch: apiFetchMock,
+ };
+ });
vi.doMock('@/utils/toast', () => ({
showSuccess: vi.fn(),
@@ -265,4 +277,54 @@ describe('useReportingPanelState', () => {
dispose();
});
+
+ it('extracts structured API error messages for reporting catalog failures', async () => {
+ vi.resetModules();
+
+ apiFetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ error: 'Catalog is unavailable right now' }), { status: 503 }),
+ );
+
+ vi.doMock('@/utils/apiClient', async () => {
+ const actual = await vi.importActual<typeof import('@/utils/apiClient')>('@/utils/apiClient');
+ return {
+ ...actual,
+ apiFetch: apiFetchMock,
+ };
+ });
+
+ vi.doMock('@/utils/toast', () => ({
+ showSuccess: vi.fn(),
+ showWarning: vi.fn(),
+ }));
+
+ vi.doMock('@/utils/trialStartAction', () => ({
+ runStartProTrialAction: vi.fn(),
+ }));
+
+ vi.doMock('@/utils/upgradeMetrics', () => ({
+ trackPaywallViewed: vi.fn(),
+ }));
+
+ vi.doMock('@/stores/license', () => ({
+ entitlements: vi.fn(() => ({ trial_eligible: true })),
+ getUpgradeActionUrlOrFallback: vi.fn(() => '/pricing'),
+ hasFeature: vi.fn((feature: string) => feature === 'advanced_reporting' && hasReportingFeature),
+ licenseLoaded: vi.fn(() => true),
+ loadLicenseStatus: loadLicenseStatusMock,
+ }));
+
+ ({ useReportingPanelState } = await import('../useReportingPanelState'));
+ const { hookState, dispose } = mountHook();
+
+ await flushAsync();
+ await flushAsync();
+
+ expect(hookState.reportingCatalog()).toBeNull();
+ expect(hookState.reportingCatalogError()).toBe('Catalog is unavailable right now');
+
+ dispose();
+ });
});
diff --git a/frontend-modern/src/components/Settings/useReportingPanelState.ts b/frontend-modern/src/components/Settings/useReportingPanelState.ts
index 8baccfcb77..06d3e5cc9f 100644
--- a/frontend-modern/src/components/Settings/useReportingPanelState.ts
+++ b/frontend-modern/src/components/Settings/useReportingPanelState.ts
@@ -1,5 +1,5 @@
import { createEffect, createSignal, onMount } from 'solid-js';
-import { apiFetch } from '@/utils/apiClient';
+import { apiErrorFromResponse, apiFetch } from '@/utils/apiClient';
import { showSuccess, showWarning } from '@/utils/toast';
import type { SelectedResource } from '@/components/Settings/ResourcePicker';
import {
@@ -86,8 +86,7 @@ export const useReportingPanelState = () => {
const request = buildReportingCatalogRequest();
const response = await apiFetch(request.url);
if (!response.ok) {
- const text = await response.text();
- throw new Error(text || getReportingCatalogErrorMessage());
+ throw await apiErrorFromResponse(response, getReportingCatalogErrorMessage());
}
setReportingCatalog(parseReportingCatalog(await response.json()));
@@ -185,8 +184,7 @@ export const useReportingPanelState = () => {
const response = await apiFetch(request.request.url, request.request.init);
if (!response.ok) {
- const text = await response.text();
- throw new Error(text || getReportingGenerateErrorMessage());
+ throw await apiErrorFromResponse(response, getReportingGenerateErrorMessage());
}
await downloadResponseBlob(request.filename, response);
@@ -212,8 +210,7 @@ export const useReportingPanelState = () => {
const request = buildVMInventoryExportRequest(new Date(), inventoryDefinition);
const response = await apiFetch(request.request.url);
if (!response.ok) {
- const text = await response.text();
- throw new Error(text || getReportingInventoryExportErrorMessage());
+ throw await apiErrorFromResponse(response, getReportingInventoryExportErrorMessage());
}
await downloadResponseBlob(request.filename, response);
diff --git a/frontend-modern/src/utils/__tests__/apiClient.error.test.ts b/frontend-modern/src/utils/__tests__/apiClient.error.test.ts
new file mode 100644
index 0000000000..1b0b495130
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/apiClient.error.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+import { apiErrorFromResponse } from '@/utils/apiClient';
+
+describe('apiClient structured error extraction', () => {
+ it('prefers structured JSON error messages over fallback copy', async () => {
+ const error = await apiErrorFromResponse(
+ new Response(JSON.stringify({ error: 'Canonical API error' }), { status: 400 }),
+ 'Fallback message',
+ );
+
+ expect(error.message).toBe('Canonical API error');
+ expect(error.status).toBe(400);
+ });
+
+ it('falls back to plain text when the response is not JSON', async () => {
+ const error = await apiErrorFromResponse(
+ new Response('temporary failure', { status: 500 }),
+ 'Fallback message',
+ );
+
+ expect(error.message).toBe('temporary failure');
+ expect(error.status).toBe(500);
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/apiClient.org.test.ts b/frontend-modern/src/utils/__tests__/apiClient.org.test.ts
index bfc302ff0f..a999c6ff06 100644
--- a/frontend-modern/src/utils/__tests__/apiClient.org.test.ts
+++ b/frontend-modern/src/utils/__tests__/apiClient.org.test.ts
@@ -164,4 +164,23 @@ describe('apiClient org context', () => {
requiredScope: 'settings:write',
});
});
+
+ it('preserves org context while extracting structured JSON errors', async () => {
+ mockFetch.mockResolvedValue(
+ new Response(JSON.stringify({ error: 'Catalog is unavailable right now' }), {
+ status: 503,
+ headers: { 'Content-Type': 'application/json' },
+ }),
+ );
+
+ setOrgID('tenant-reporting');
+ await expect(apiFetchJSON('/api/admin/reports/catalog')).rejects.toMatchObject({
+ message: 'Catalog is unavailable right now',
+ status: 503,
+ });
+
+ const [, options] = mockFetch.mock.calls[0] as [string, RequestInit];
+ const headers = options.headers as Record<string, string>;
+ expect(headers['X-Pulse-Org-ID']).toBe('tenant-reporting');
+ });
});
diff --git a/frontend-modern/src/utils/apiClient.ts b/frontend-modern/src/utils/apiClient.ts
index 35e25c63b3..559327892e 100644
--- a/frontend-modern/src/utils/apiClient.ts
+++ b/frontend-modern/src/utils/apiClient.ts
@@ -81,6 +81,60 @@ type APIErrorShape = Error & {
status?: number;
};
+async function createAPIErrorFromResponse(
+ response: Response,
+ fallbackMessage?: string,
+): Promise<APIErrorShape> {
+ const text = await response.text();
+ let errorMessage = fallbackMessage || text;
+
+ let errorDetail: string | undefined;
+ let errorFeature: string | undefined;
+ let errorRequiredScope: string | undefined;
+ let errorUpgradeUrl: string | undefined;
+ try {
+ const jsonError = JSON.parse(text);
+ if (jsonError.message) {
+ errorMessage = jsonError.message;
+ } else if (jsonError.error && typeof jsonError.error === 'string') {
+ errorMessage = jsonError.error;
+ }
+ if (typeof jsonError.detail === 'string') {
+ errorDetail = jsonError.detail;
+ }
+ errorRequiredScope = sanitizeBoundedText(jsonError.requiredScope, 128) ?? undefined;
+ errorFeature = sanitizeBoundedText(jsonError.feature, 128) ?? undefined;
+ errorUpgradeUrl = sanitizeBoundedText(jsonError.upgrade_url, 2048) ?? undefined;
+ } catch {
+ if (text.includes('<pre>') && text.includes('</pre>')) {
+ const match = text.match(/<pre>(.*?)<\/pre>/s);
+ if (match) errorMessage = match[1];
+ }
+
+ if (!text.includes('<') && text.length < 200) {
+ errorMessage = text;
+ } else if (!errorMessage && text.length > 200) {
+ errorMessage = `Request failed with status ${response.status}`;
+ }
+ }
+
+ const err = new Error(errorMessage || `Request failed with status ${response.status}`) as APIErrorShape;
+ err.status = response.status;
+ if (errorDetail) {
+ err.detail = errorDetail;
+ }
+ if (errorRequiredScope) {
+ err.requiredScope = errorRequiredScope;
+ }
+ if (errorFeature) {
+ err.feature = errorFeature;
+ }
+ if (errorUpgradeUrl) {
+ err.upgrade_url = errorUpgradeUrl;
+ }
+ return err;
+}
+
function createAbortError(): Error {
if (typeof DOMException !== 'undefined') {
return new DOMException('The operation was aborted.', 'AbortError');
@@ -672,62 +726,7 @@ class ApiClient {
});
if (!response.ok) {
- const text = await response.text();
- // Try to extract just the error message without HTTP status codes
- let errorMessage = text;
-
- // First try to parse as JSON (our API returns structured errors like {error, message, feature, upgrade_url})
- let errorDetail: string | undefined;
- let errorFeature: string | undefined;
- let errorRequiredScope: string | undefined;
- let errorUpgradeUrl: string | undefined;
- try {
- const jsonError = JSON.parse(text);
- if (jsonError.message) {
- errorMessage = jsonError.message;
- } else if (jsonError.error && typeof jsonError.error === 'string') {
- // Some APIs return {error: "message"} format
- errorMessage = jsonError.error;
- }
- if (typeof jsonError.detail === 'string') {
- errorDetail = jsonError.detail;
- }
- errorRequiredScope = sanitizeBoundedText(jsonError.requiredScope, 128) ?? undefined;
- errorFeature = sanitizeBoundedText(jsonError.feature, 128) ?? undefined;
- errorUpgradeUrl = sanitizeBoundedText(jsonError.upgrade_url, 2048) ?? undefined;
- } catch {
- // Not JSON, try other formats
-
- // If it looks like an HTML error page, try to extract the message
- if (text.includes('<pre>') && text.includes('</pre>')) {
- const match = text.match(/<pre>(.*?)<\/pre>/s);
- if (match) errorMessage = match[1];
- }
-
- // If the backend sent a plain text error, use it directly
- if (!text.includes('<') && text.length < 200) {
- errorMessage = text;
- } else if (text.length > 200) {
- // For long responses, just use a generic message
- errorMessage = `Request failed with status ${response.status}`;
- }
- }
-
- const err = new Error(errorMessage || `Request failed with status ${response.status}`) as APIErrorShape;
- err.status = response.status;
- if (errorDetail) {
- err.detail = errorDetail;
- }
- if (errorRequiredScope) {
- err.requiredScope = errorRequiredScope;
- }
- if (errorFeature) {
- err.feature = errorFeature;
- }
- if (errorUpgradeUrl) {
- err.upgrade_url = errorUpgradeUrl;
- }
- throw err;
+ throw await createAPIErrorFromResponse(response);
}
const text = await response.text();
@@ -749,6 +748,8 @@ export const apiClient = new ApiClient();
export const apiFetch = (url: string, options?: FetchOptions) => apiClient.fetch(url, options);
export const apiFetchJSON = <T = unknown>(url: string, options?: FetchOptions) =>
apiClient.fetchJSON<T>(url, options);
+export const apiErrorFromResponse = (response: Response, fallbackMessage?: string) =>
+ createAPIErrorFromResponse(response, fallbackMessage);
export const setApiToken = (token: string) => apiClient.setApiToken(token);
export const getApiToken = () => apiClient.getApiToken();
export const clearAuth = () => apiClient.clearAuth();