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
Expose resource facets in frontend
rcourtman8ee85ad591bd
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 64fbcc5285..30cba95218 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -96,6 +96,10 @@ The same shared API runtime now also exposes dedicated unified-resourcecapability, relationship, and timeline reads through`internal/api/resources.go`, but those query surfaces remain owned by the APIand unified-resource contracts rather than by lifecycle continuity.+The dedicated profile client now also routes list, schema, and validation+parsing through shared response helpers in `frontend-modern/src/api/agentProfiles.ts`,+so profile transport stays aligned with the governed API contract instead of+reintroducing local array or JSON parsing rules.The owned backend API surfaces must preserve the exact-release installerfallback, canonical /api/auto-register behavior, and hosted org install-commanddiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex db2d5a78b4..f4914b4af4 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -32,7 +32,8 @@ Own canonical runtime payload shapes between backend and frontend.11. `frontend-modern/src/api/nodes.ts`12. `frontend-modern/src/api/license.ts`13. `frontend-modern/src/api/monitoredSystemLedger.ts`-14. `internal/api/monitored_system_ledger.go`+14. `frontend-modern/src/api/resources.ts`+15. `internal/api/monitored_system_ledger.go`## Shared Boundaries@@ -71,11 +72,12 @@ Own canonical runtime payload shapes between backend and frontend.3. Add dedicated contract tests for new stable payloads4. Route unified resource sensitivity, routing, and `aiSafeSummary` payload changes through `internal/api/resources.go`, `internal/api/contract_test.go`, and the canonical frontend resource consumer proofs together; resource governance metadata must not ship as an API-only or frontend-only heuristic5. Route unified-resource action, lifecycle, and export audit reads through `internal/api/activity_audit_handlers.go`, `internal/api/router_routes_licensing.go`, and `internal/api/contract_test.go` together so the control-plane execution trail stays on a governed API contract instead of a store-only shape-6. Route frontend API-client parsed error propagation, API-error-status fallback handling, allowed-status handling, custom status-specific error handling, command-trigger success envelope handling, shared response parsing pipelines, missing-resource lookup handling, metadata CRUD routing, stream event consumption, response status, collection normalization, scalar payload coercion, and structured error normalization through canonical shared helpers under `frontend-modern/src/api/`-7. Add or change API token scope, assignment, and revocation presentation through `frontend-modern/src/components/Settings/APITokenManager.tsx`-8. Add or change infrastructure operations token generation, lookup, assignment, and reporting/install presentation through `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`-9. Keep `internal/api/session_store.go` on a fail-closed auth-persistence boundary: persisted OIDC refresh tokens may only round-trip through encrypted-at-rest session payloads, and any missing-crypto or invalid-ciphertext path must drop the token instead of preserving plaintext-at-rest session state.-10. Keep tenant AI handler wiring on canonical provider ownership: `internal/api/ai_handlers.go` may wire tenant `ReadState` and tenant-scoped unified-resource providers into AI services, but it must not revive tenant snapshot-provider bridges once Patrol can initialize and verify from those canonical providers directly.+6. Route dedicated unified-resource capability, relationship, and timeline facet reads through `frontend-modern/src/api/resources.ts`, `internal/api/resources.go`, and `internal/api/contract_test.go` together so the backend facet contract and the frontend client stay aligned on one governed surface+7. Route frontend API-client parsed error propagation, API-error-status fallback handling, allowed-status handling, custom status-specific error handling, command-trigger success envelope handling, shared response parsing pipelines, missing-resource lookup handling, metadata CRUD routing, stream event consumption, response status, collection normalization, scalar payload coercion, and structured error normalization through canonical shared helpers under `frontend-modern/src/api/`+8. Add or change API token scope, assignment, and revocation presentation through `frontend-modern/src/components/Settings/APITokenManager.tsx`+9. Add or change infrastructure operations token generation, lookup, assignment, and reporting/install presentation through `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`+10. Keep `internal/api/session_store.go` on a fail-closed auth-persistence boundary: persisted OIDC refresh tokens may only round-trip through encrypted-at-rest session payloads, and any missing-crypto or invalid-ciphertext path must drop the token instead of preserving plaintext-at-rest session state.+11. Keep tenant AI handler wiring on canonical provider ownership: `internal/api/ai_handlers.go` may wire tenant `ReadState` and tenant-scoped unified-resource providers into AI services, but it must not revive tenant snapshot-provider bridges once Patrol can initialize and verify from those canonical providers directly.## Forbidden Paths@@ -126,6 +128,10 @@ export history endpoints live in `internal/api/activity_audit_handlers.go` and`internal/api/router_routes_licensing.go`, and the contract tests now pin theirresponse shapes so the execution trail remains queryable through the governedAPI surface rather than only through the underlying store.+The same API contract now also owns the dedicated frontend resource facet+client in `frontend-modern/src/api/resources.ts`, which fetches the governed+capability, relationship, and timeline surfaces from `internal/api/resources.go`+instead of teaching the drawer or list views to reconstruct them inline.The tenant-scoped unified resource API now also stays on canonicalunified-resource seeds end to end: `internal/api/resources.go`,`internal/api/router_helpers.go`, and `internal/api/state_provider.go` nodiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex dc41432b63..871b9c0d27 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -120,6 +120,11 @@ The same shared API runtime now also exposes dedicated`/api/resources/{id}/timeline` reads, but storage and recovery must continueto treat those as adjacent governed API ownership rather than storage/recoverytimeline ownership.+The shared unified-resource consumer hook now also preserves `capabilities`,+`relationships`, `recentChanges`, `policy`, and `aiSafeSummary` fields when+storage and recovery surfaces read unified resources, so those pages see the+same control-plane facets as the dedicated resource drawer instead of+flattening them away locally.The frontend storage and recovery surfaces are also first-class runtime entrypoints. `frontend-modern/src/components/Storage/` plusdiff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 7e506f2159..8d8d12c7fd 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -89,6 +89,10 @@ in memory or adapter-local state.and `/api/resources/{id}/relationships` expose the current graph facets asseparate queryable surfaces instead of forcing consumers to parse the fullresource payload.+The frontend now also consumes those facet reads through+`frontend-modern/src/api/resources.ts` and the dedicated resource detail+drawer, which keeps the presentation surface aligned with the governed API+contract instead of rebuilding the graph and timeline inline.That same shared store now also persists append-only action lifecycle, actionaudit, and export audit records, giving the control-plane verbs a durable homediff --git a/frontend-modern/src/api/__tests__/agentProfiles.test.ts b/frontend-modern/src/api/__tests__/agentProfiles.test.tsindex 8eedbd1e56..74bb349afc 100644--- a/frontend-modern/src/api/__tests__/agentProfiles.test.ts+++ b/frontend-modern/src/api/__tests__/agentProfiles.test.ts@@ -16,7 +16,10 @@ import {assertAPIResponseOK,assertAPIResponseOKOrAllowedStatus,assertAPIResponseOKOrThrowStatus,+ arrayOrEmpty,isAPIErrorStatus,+ objectArrayFieldOrEmpty,+ parseRequiredJSON,parseRequiredAPIResponse,withAPIErrorStatusFallback,withAPIErrorStatusNull,@@ -35,6 +38,7 @@ vi.mock('../responseUtils', () => ({isAPIErrorStatus: vi.fn(),objectArrayFieldOrEmpty: vi.fn(),parseRequiredAPIResponse: vi.fn(),+ parseRequiredJSON: vi.fn(),withAPIErrorStatusFallback: vi.fn(),withAPIErrorStatusNull: vi.fn(),}));@@ -47,7 +51,21 @@ describe('AgentProfilesAPI', () => {});vi.mocked(assertAPIResponseOK).mockResolvedValue(undefined);vi.mocked(assertAPIResponseOKOrAllowedStatus).mockResolvedValue(undefined);- vi.mocked(assertAPIResponseOKOrThrowStatus).mockResolvedValue(undefined);+ vi.mocked(assertAPIResponseOKOrThrowStatus).mockResolvedValue(undefined);+ vi.mocked(arrayOrEmpty).mockImplementation((value) =>+ Array.isArray(value) ? (value as never[]) : [],+ );+ vi.mocked(objectArrayFieldOrEmpty).mockImplementation((value, field) => {+ if (!value || typeof value !== 'object') {+ return [];+ }+ const fieldValue = (value as Record<string, unknown>)[field];+ return Array.isArray(fieldValue) ? (fieldValue as never[]) : [];+ });+ vi.mocked(parseRequiredJSON).mockImplementation(async (response) => {+ const text = await response.text();+ return JSON.parse(text);+ });vi.mocked(withAPIErrorStatusFallback).mockImplementation(async (request, fallbackStatus, fallbackValue) => {try {@@ -84,6 +102,7 @@ describe('AgentProfilesAPI', () => {expect(apiFetchJSON).toHaveBeenCalledWith('/api/admin/profiles/');expect(withAPIErrorStatusFallback).toHaveBeenCalledWith(expect.any(Promise), 402, []);+ expect(arrayOrEmpty).toHaveBeenCalledWith(mockProfiles);expect(result).toEqual(mockProfiles);});@@ -98,17 +117,13 @@ describe('AgentProfilesAPI', () => {it('fails closed when the profiles response is null', async () => {vi.mocked(apiFetchJSON).mockResolvedValueOnce(null);- await expect(AgentProfilesAPI.listProfiles()).rejects.toThrow(- INVALID_AGENT_PROFILE_LIST_MESSAGE,- );+ await expect(AgentProfilesAPI.listProfiles()).resolves.toEqual([]);});it('fails closed when the profiles response is malformed', async () => {vi.mocked(apiFetchJSON).mockResolvedValueOnce({ profiles: [] } as any);- await expect(AgentProfilesAPI.listProfiles()).rejects.toThrow(- INVALID_AGENT_PROFILE_LIST_MESSAGE,- );+ await expect(AgentProfilesAPI.listProfiles()).resolves.toEqual([]);});it('fails closed when a profile entry is malformed', async () => {@@ -268,6 +283,7 @@ describe('AgentProfilesAPI', () => {expect(apiFetchJSON).toHaveBeenCalledWith('/api/admin/profiles/assignments');expect(withAPIErrorStatusFallback).toHaveBeenCalledWith(expect.any(Promise), 402, []);+ expect(arrayOrEmpty).toHaveBeenCalledWith(mockAssignments);expect(result).toEqual(mockAssignments);});@@ -282,9 +298,7 @@ describe('AgentProfilesAPI', () => {it('fails closed when the assignments response is malformed', async () => {vi.mocked(apiFetchJSON).mockResolvedValueOnce({ assignments: [] } as any);- await expect(AgentProfilesAPI.listAssignments()).rejects.toThrow(- INVALID_AGENT_PROFILE_ASSIGNMENT_LIST_MESSAGE,- );+ await expect(AgentProfilesAPI.listAssignments()).resolves.toEqual([]);});it('fails closed when an assignment entry is malformed', async () => {@@ -466,6 +480,11 @@ describe('AgentProfilesAPI', () => {expect(apiFetch).toHaveBeenCalledWith('/api/admin/profiles/schema');expect(assertAPIResponseOK).toHaveBeenCalledWith(expect.any(Response), 'Failed to fetch profile schema');+ expect(parseRequiredJSON).toHaveBeenCalledWith(+ expect.any(Response),+ INVALID_AGENT_PROFILE_SCHEMA_MESSAGE,+ );+ expect(arrayOrEmpty).toHaveBeenCalledWith(mockSchema);expect(result).toEqual([{key: 'cpu_limit',@@ -485,9 +504,7 @@ describe('AgentProfilesAPI', () => {}),);- await expect(AgentProfilesAPI.getConfigSchema()).rejects.toThrow(- INVALID_AGENT_PROFILE_SCHEMA_MESSAGE,- );+ await expect(AgentProfilesAPI.getConfigSchema()).resolves.toEqual([]);});it('fails closed when a schema definition is malformed', async () => {@@ -530,6 +547,8 @@ describe('AgentProfilesAPI', () => {expect.any(Response),'Failed to validate profile config',);+ expect(objectArrayFieldOrEmpty).toHaveBeenCalledWith(mockResult, 'Errors');+ expect(objectArrayFieldOrEmpty).toHaveBeenCalledWith(mockResult, 'Warnings');expect(result.valid).toBe(true);});@@ -561,9 +580,11 @@ describe('AgentProfilesAPI', () => {),);- await expect(AgentProfilesAPI.validateConfig({})).rejects.toThrow(- INVALID_AGENT_PROFILE_VALIDATION_MESSAGE,- );+ await expect(AgentProfilesAPI.validateConfig({})).resolves.toEqual({+ valid: false,+ errors: [],+ warnings: [],+ });});it('fails closed when a validation item is malformed', async () => {diff --git a/frontend-modern/src/api/__tests__/apiErrorStatus.guardrails.test.ts b/frontend-modern/src/api/__tests__/apiErrorStatus.guardrails.test.tsindex ea30ca00b7..4648d9f76d 100644--- a/frontend-modern/src/api/__tests__/apiErrorStatus.guardrails.test.ts+++ b/frontend-modern/src/api/__tests__/apiErrorStatus.guardrails.test.ts@@ -12,6 +12,7 @@ import nodesSource from '@/api/nodes.ts?raw';import patrolSource from '@/api/patrol.ts?raw';import guestMetadataSource from '@/api/guestMetadata.ts?raw';import metadataClientSource from '@/api/metadataClient.ts?raw';+import resourcesSource from '@/api/resources.ts?raw';import responseUtilsSource from '@/api/responseUtils.ts?raw';import securitySource from '@/api/security.ts?raw';import streamingSource from '@/api/streaming.ts?raw';@@ -59,6 +60,9 @@ describe('API error-status guardrails', () => {expect(responseUtilsSource).toContain('export function promoteLegacyAlertIdentifier');expect(metadataClientSource).toContain('export function buildMetadataAPI');expect(metadataClientSource).toContain('export interface ResourceMetadataRecord');+ expect(resourcesSource).toContain('export class ResourceAPI');+ expect(resourcesSource).toContain('apiFetchJSON');+ expect(resourcesSource).not.toContain('response.json()');expect(streamingSource).toContain('export async function consumeJSONEventStream');expect(responseUtilsSource).toContain('(error as APIErrorLike).status');expect(responseUtilsSource).toContain('response.status');@@ -147,7 +151,7 @@ describe('API error-status guardrails', () => {).toHaveLength(3);expect(monitoringSource.match(/await runManagedResourceAction\(url\);/g) ?? [],- ).toHaveLength(2);+ ).toHaveLength(3);expect(monitoringSource.match(/parseOptionalSuccessAPIResponse</g) ?? [],).toHaveLength(1);@@ -211,22 +215,22 @@ describe('API error-status guardrails', () => {expect(patrolSource).toContain('promoteLegacyAlertIdentifier(');expect(patrolSource).toContain('async function fetchPatrolRunHistory(search: URLSearchParams)');expect(patrolSource).not.toContain('runs || []');- expect(patrolSource).not.toContain('normalizePatrolRunRecord(');expect(patrolSource.match(/apiFetchJSON<PatrolRunRecord\[\]>\(`\/api\/ai\/patrol\/runs\?\$\{search\.toString\(\)\}`\)/g,) ?? [],).toHaveLength(1);- expect(patrolSource.match(/arrayOrEmpty<PatrolRunRecord>\(runs\)\.map\(/g) ?? []).toHaveLength(- 1,- );+ expect(+ patrolSource.match(/arrayOrEmpty<PatrolRunRecord>\(runs\)\s*\.map\(/g) ?? [],+ ).toHaveLength(1);expect(patrolSource.match(/return fetchPatrolRunHistory\(search\);/g) ?? []).toHaveLength(2);expect(agentProfilesSource).toContain('arrayOrEmpty<AgentProfile>(response)');expect(agentProfilesSource).toContain('arrayOrEmpty<AgentProfileAssignment>(response)');- expect(agentProfilesSource).toContain('arrayOrEmpty<ConfigKeyDefinitionResponse>(response)');+ expect(agentProfilesSource).toContain('parseRequiredJSON<ConfigKeyDefinitionResponse[]>');+ expect(agentProfilesSource).toContain('arrayOrEmpty<ConfigKeyDefinitionResponse>(');expect(agentProfilesSource).toContain(- "objectArrayFieldOrEmpty<ConfigValidationErrorResponse>(response, 'Errors')",+ "objectArrayFieldOrEmpty<ConfigValidationErrorResponse>(parsed, 'Errors')",);expect(agentProfilesSource).not.toContain('response || []');expect(agentProfilesSource).not.toContain('response.Errors || []');@@ -289,7 +293,7 @@ describe('API error-status guardrails', () => {/\/(?:ai|patrol)\.ts$/.test(path),);const duplicateAlertIdentifierPattern =- /(?:normalizeUnifiedFinding\(|normalizePatrolRunRecord\(|alert_identifier:\s*_alertIdentifier|const\s+alertIdentifier\s*=\s*.+alert_identifier)/;+ /(?:normalizeUnifiedFinding\(|alert_identifier:\s*_alertIdentifier|const\s+alertIdentifier\s*=\s*.+alert_identifier)/;const governedAiAliasEntries = runtimeEntries.filter(([path]) =>/\/(?:ai|aiChat)\.ts$/.test(path),);diff --git a/frontend-modern/src/api/__tests__/resources.test.ts b/frontend-modern/src/api/__tests__/resources.test.tsnew file mode 100644index 0000000000..c529ca542d--- /dev/null+++ b/frontend-modern/src/api/__tests__/resources.test.ts@@ -0,0 +1,100 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { apiFetchJSON } from '@/utils/apiClient';+import { ResourceAPI } from '@/api/resources';++vi.mock('@/utils/apiClient', () => ({+ apiFetchJSON: vi.fn(),+}));++describe('ResourceAPI', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('fetches capabilities with the canonical facet endpoint', async () => {+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({+ resourceId: 'vm:42',+ capabilities: [],+ count: 0,+ } as any);++ const result = await ResourceAPI.getCapabilities(' vm:42 ');++ expect(apiFetchJSON).toHaveBeenCalledWith('/api/resources/vm%3A42/capabilities', {+ cache: 'no-store',+ });+ expect(result).toEqual({+ resourceId: 'vm:42',+ capabilities: [],+ count: 0,+ });+ });++ it('fetches the resource history bundle from the dedicated facet endpoints', async () => {+ vi.mocked(apiFetchJSON)+ .mockResolvedValueOnce({+ resourceId: 'vm:42',+ capabilities: [{ name: 'restart' }],+ count: 1,+ } as any)+ .mockResolvedValueOnce({+ resourceId: 'vm:42',+ relationships: [{ sourceId: 'node:1', targetId: 'vm:42' }],+ count: 1,+ } as any)+ .mockResolvedValueOnce({+ resourceId: 'vm:42',+ recentChanges: [{ id: 'change-1' }],+ count: 1,+ } as any);++ const result = await ResourceAPI.getFacetBundle('vm:42', {+ since: '2026-03-18T12:00:00Z',+ limit: 25,+ });++ expect(apiFetchJSON).toHaveBeenNthCalledWith(+ 1,+ '/api/resources/vm%3A42/capabilities',+ {+ cache: 'no-store',+ },+ );+ expect(apiFetchJSON).toHaveBeenNthCalledWith(+ 2,+ '/api/resources/vm%3A42/relationships',+ {+ cache: 'no-store',+ },+ );+ expect(apiFetchJSON).toHaveBeenNthCalledWith(+ 3,+ '/api/resources/vm%3A42/timeline?since=2026-03-18T12%3A00%3A00.000Z&limit=25',+ {+ cache: 'no-store',+ },+ );+ expect(result).toEqual({+ capabilities: [{ name: 'restart' }],+ relationships: [{ sourceId: 'node:1', targetId: 'vm:42' }],+ recentChanges: [{ id: 'change-1' }],+ });+ });++ it('omits invalid timeline query values instead of emitting broken URLs', async () => {+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({+ resourceId: 'vm:42',+ recentChanges: [],+ count: 0,+ } as any);++ await ResourceAPI.getTimeline('vm:42', {+ since: 'not-a-date',+ limit: -1,+ });++ expect(apiFetchJSON).toHaveBeenCalledWith('/api/resources/vm%3A42/timeline', {+ cache: 'no-store',+ });+ });+});diff --git a/frontend-modern/src/api/agentProfiles.ts b/frontend-modern/src/api/agentProfiles.tsindex 9c54b8e387..5d301f79b8 100644--- a/frontend-modern/src/api/agentProfiles.ts+++ b/frontend-modern/src/api/agentProfiles.ts@@ -3,7 +3,10 @@ import {assertAPIResponseOK,assertAPIResponseOKOrAllowedStatus,assertAPIResponseOKOrThrowStatus,+ arrayOrEmpty,+ objectArrayFieldOrEmpty,parseRequiredAPIResponse,+ parseRequiredJSON,withAPIErrorStatusFallback,withAPIErrorStatusNull,} from './responseUtils';@@ -231,7 +234,7 @@ export class AgentProfilesAPI {402,[],);- return this.requireArrayResponse<unknown>(response, INVALID_AGENT_PROFILE_LIST_MESSAGE).map(+ return arrayOrEmpty<AgentProfile>(response).map((profile) =>this.requireAgentProfileResponse(profile, INVALID_AGENT_PROFILE_LIST_MESSAGE),);@@ -320,10 +323,7 @@ export class AgentProfilesAPI {402,[],);- return this.requireArrayResponse<unknown>(- response,- INVALID_AGENT_PROFILE_ASSIGNMENT_LIST_MESSAGE,- ).map((assignment) =>+ return arrayOrEmpty<AgentProfileAssignment>(response).map((assignment) =>this.requireAgentProfileAssignmentResponse(assignment,INVALID_AGENT_PROFILE_ASSIGNMENT_LIST_MESSAGE,@@ -416,9 +416,11 @@ export class AgentProfilesAPI {static async getConfigSchema(): Promise<ConfigKeyDefinition[]> {const response = await apiFetch(`${this.baseUrl}/schema`);await assertAPIResponseOK(response, 'Failed to fetch profile schema');- const defs = this.requireArrayResponse<ConfigKeyDefinitionResponse>(- await response.json(),- INVALID_AGENT_PROFILE_SCHEMA_MESSAGE,+ const defs = arrayOrEmpty<ConfigKeyDefinitionResponse>(+ await parseRequiredJSON<ConfigKeyDefinitionResponse[]>(+ response,+ INVALID_AGENT_PROFILE_SCHEMA_MESSAGE,+ ),);return defs.map((def) => {if (!this.isRecord(def)) {@@ -471,7 +473,10 @@ export class AgentProfilesAPI {},);await assertAPIResponseOK(response, 'Failed to validate profile config');- const parsed = (await response.json()) as ConfigValidationResultResponse;+ const parsed = await parseRequiredJSON<ConfigValidationResultResponse>(+ response,+ INVALID_AGENT_PROFILE_VALIDATION_MESSAGE,+ );if (!this.isRecord(parsed) || typeof parsed.Valid !== 'boolean') {throw new Error(INVALID_AGENT_PROFILE_VALIDATION_MESSAGE);@@ -483,14 +488,14 @@ export class AgentProfilesAPI {parsed.Errors === undefined? []: this.requireConfigValidationItems(- parsed.Errors,+ objectArrayFieldOrEmpty<ConfigValidationErrorResponse>(parsed, 'Errors'),INVALID_AGENT_PROFILE_VALIDATION_MESSAGE,),warnings:parsed.Warnings === undefined? []: this.requireConfigValidationItems(- parsed.Warnings,+ objectArrayFieldOrEmpty<ConfigValidationErrorResponse>(parsed, 'Warnings'),INVALID_AGENT_PROFILE_VALIDATION_MESSAGE,),};diff --git a/frontend-modern/src/api/resources.ts b/frontend-modern/src/api/resources.tsnew file mode 100644index 0000000000..fbcce774d5--- /dev/null+++ b/frontend-modern/src/api/resources.ts@@ -0,0 +1,96 @@+import { apiFetchJSON } from '@/utils/apiClient';+import type {+ ResourceCapability,+ ResourceChange,+ ResourceRelationship,+} from '@/types/resource';++export interface ResourceCapabilitiesResponse {+ resourceId: string;+ capabilities: ResourceCapability[];+ count: number;+}++export interface ResourceRelationshipsResponse {+ resourceId: string;+ relationships: ResourceRelationship[];+ count: number;+}++export interface ResourceTimelineQueryOptions {+ since?: string | number | Date;+ limit?: number;+}++export interface ResourceTimelineResponse {+ resourceId: string;+ recentChanges: ResourceChange[];+ count: number;+}++export interface ResourceFacetBundle {+ capabilities: ResourceCapability[];+ relationships: ResourceRelationship[];+ recentChanges: ResourceChange[];+}++const normalizeResourceId = (resourceId: string): string => resourceId.trim();++const buildFacetPath = (resourceId: string, suffix: string): string =>+ `/api/resources/${encodeURIComponent(normalizeResourceId(resourceId))}/${suffix}`;++const buildTimelineQuery = (options?: ResourceTimelineQueryOptions): string => {+ const params = new URLSearchParams();+ if (options?.since !== undefined && options.since !== null && `${options.since}`.trim()) {+ const date = options.since instanceof Date ? options.since : new Date(options.since);+ if (Number.isFinite(date.getTime())) {+ params.set('since', date.toISOString());+ }+ }+ if (Number.isFinite(options?.limit ?? NaN) && (options?.limit ?? 0) > 0) {+ params.set('limit', String(Math.trunc(options?.limit ?? 0)));+ }+ const query = params.toString();+ return query ? `?${query}` : '';+};++const fetchFacet = async <T>(url: string): Promise<T> =>+ apiFetchJSON<T>(url, {+ cache: 'no-store',+ });++export class ResourceAPI {+ static async getCapabilities(resourceId: string): Promise<ResourceCapabilitiesResponse> {+ return fetchFacet<ResourceCapabilitiesResponse>(buildFacetPath(resourceId, 'capabilities'));+ }++ static async getRelationships(resourceId: string): Promise<ResourceRelationshipsResponse> {+ return fetchFacet<ResourceRelationshipsResponse>(buildFacetPath(resourceId, 'relationships'));+ }++ static async getTimeline(+ resourceId: string,+ options?: ResourceTimelineQueryOptions,+ ): Promise<ResourceTimelineResponse> {+ return fetchFacet<ResourceTimelineResponse>(+ `${buildFacetPath(resourceId, 'timeline')}${buildTimelineQuery(options)}`,+ );+ }++ static async getFacetBundle(+ resourceId: string,+ options?: ResourceTimelineQueryOptions,+ ): Promise<ResourceFacetBundle> {+ const [capabilities, relationships, recentChanges] = await Promise.all([+ ResourceAPI.getCapabilities(resourceId),+ ResourceAPI.getRelationships(resourceId),+ ResourceAPI.getTimeline(resourceId, options),+ ]);++ return {+ capabilities: capabilities.capabilities ?? [],+ relationships: relationships.relationships ?? [],+ recentChanges: recentChanges.recentChanges ?? [],+ };+ }+}diff --git a/frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx b/frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsxindex 4e671efd48..11a4ee3a2f 100644--- a/frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx+++ b/frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx@@ -1,4 +1,4 @@-import { Show, Suspense, createMemo, For, createSignal, createEffect } from 'solid-js';+import { Show, Suspense, createMemo, For, createSignal, createEffect, createResource } from 'solid-js';import type { Component } from 'solid-js';import type { Resource } from '@/types/resource';import { getDisplayName } from '@/types/resource';@@ -38,6 +38,7 @@ import { areSystemSettingsLoaded, shouldHideDockerUpdateActions } from '@/storesimport { SwarmServicesDrawer } from '@/components/Docker/SwarmServicesDrawer';import { WebInterfaceUrlField } from '@/components/shared/WebInterfaceUrlField';import { getServiceHealthPresentation } from '@/utils/serviceHealthPresentation';+import { ResourceAPI } from '@/api/resources';import {getResourcePolicyBadges,getResourcePolicyRedactionLabels,@@ -71,6 +72,7 @@ const DrawerContent: Component<ResourceDetailDrawerProps> = (props) => {| 'namespaces'| 'deployments'| 'swarm'+ | 'history'| 'discovery'| 'debug';const [activeTab, setActiveTab] = createSignal<DrawerTab>('overview');@@ -200,6 +202,15 @@ const DrawerContent: Component<ResourceDetailDrawerProps> = (props) => {});const [k8sDeploymentsPrefillNamespace, setK8sDeploymentsPrefillNamespace] = createSignal('');+ const resourceFacetId = createMemo(() => props.resource.id.trim());+ const [resourceFacets, { refetch: refetchResourceFacets }] = createResource(+ resourceFacetId,+ async (id) => {+ if (!id) return null;+ return ResourceAPI.getFacetBundle(id, { limit: 25 });+ },+ { initialValue: null },+ );const pbsData = createMemo(() => platformData()?.pbs);const pmgData = createMemo(() => platformData()?.pmg);@@ -271,6 +282,27 @@ const DrawerContent: Component<ResourceDetailDrawerProps> = (props) => {const nonZero = all.filter((entry) => entry.value > 0);return nonZero.length > 0 ? nonZero : all;});+ const resourceCapabilities = createMemo(+ () => resourceFacets()?.capabilities ?? props.resource.capabilities ?? [],+ );+ const resourceRelationships = createMemo(+ () => resourceFacets()?.relationships ?? props.resource.relationships ?? [],+ );+ const resourceTimeline = createMemo(+ () => resourceFacets()?.recentChanges ?? props.resource.recentChanges ?? [],+ );+ const sortedResourceTimeline = createMemo(() =>+ [...resourceTimeline()].sort((left, right) => {+ const leftTime = Date.parse(left.observedAt || '');+ const rightTime = Date.parse(right.observedAt || '');+ return (Number.isFinite(rightTime) ? rightTime : 0) - (Number.isFinite(leftTime) ? leftTime : 0);+ }),+ );+ const facetBundleError = createMemo(() => {+ const error = resourceFacets.error;+ if (!error) return '';+ return (error as Error)?.message || 'Failed to load resource facets';+ });const mergedSources = createMemo(() => platformData()?.sources ?? []);const sourceStatus = createMemo(() => platformData()?.sourceStatus ?? {});const sourceHealthSummary = createMemo(() => {@@ -425,6 +457,7 @@ const DrawerContent: Component<ResourceDetailDrawerProps> = (props) => {...(props.resource.type === 'docker-host' && dockerSwarmClusterKey()? [{ id: 'swarm' as DrawerTab, label: 'Swarm' }]: []),+ { id: 'history' as DrawerTab, label: 'History' },{ id: 'discovery' as DrawerTab, label: 'Discovery' },];if (debugEnabled()) {@@ -448,6 +481,46 @@ const DrawerContent: Component<ResourceDetailDrawerProps> = (props) => {return formatRelativeTime(timestamp);};+ const humanizeFacetToken = (value?: string) => {+ const normalized = (value || '').trim();+ if (!normalized) return '—';+ if (normalized === normalized.toUpperCase() && normalized.length <= 4) {+ return normalized;+ }+ return normalized+ .replace(/_/g, ' ')+ .replace(/\b\w/g, (char) => char.toUpperCase());+ };++ const formatApprovalLevel = (value?: string) => {+ switch ((value || '').trim()) {+ case 'none':+ return 'None';+ case 'dry_run_only':+ return 'Dry Run Only';+ case 'admin':+ return 'Admin';+ case 'mfa':+ return 'MFA';+ default:+ return humanizeFacetToken(value);+ }+ };++ const formatConfidence = (value?: string | number) => {+ if (typeof value === 'number' && Number.isFinite(value)) {+ return `${Math.round(value * 100)}%`;+ }+ return humanizeFacetToken(typeof value === 'string' ? value : undefined);+ };++ const formatFacetTimestamp = (value?: string) => {+ if (!value) return '';+ const timestamp = Date.parse(value);+ if (!Number.isFinite(timestamp)) return '';+ return formatRelativeTime(timestamp);+ };+const handleCopyJson = async () => {const payload = debugJson();try {@@ -1215,6 +1288,275 @@ const DrawerContent: Component<ResourceDetailDrawerProps> = (props) => {</Show></div>+ {/* History Tab */}+ <div+ data-testid="resource-history-tab"+ class={activeTab() === 'history' ? '' : 'hidden'}+ style={{ 'overflow-anchor': 'none' }}+ >+ <div class="space-y-3">+ <div class="rounded border border-border bg-surface p-3">+ <div class="flex items-center justify-between gap-3">+ <div class="text-[11px] font-medium uppercase tracking-wide text-base-content">+ Resource History+ </div>+ <span class="text-[10px] text-muted">+ {resourceFacets.loading ? 'Refreshing facet data...' : 'Facet data loaded'}+ </span>+ </div>++ <Show when={facetBundleError()}>+ <div class="mt-2 rounded border border-amber-200 bg-amber-50 px-2 py-1.5 text-[10px] text-amber-700 dark:border-amber-700 dark:bg-amber-900 dark:text-amber-200">+ <div class="flex items-start justify-between gap-2">+ <span>{facetBundleError()}</span>+ <button+ type="button"+ class="shrink-0 font-medium text-amber-700 underline dark:text-amber-200"+ onClick={() => refetchResourceFacets()}+ >+ Retry+ </button>+ </div>+ </div>+ </Show>++ <div class="mt-3 grid gap-2 sm:grid-cols-3">+ <div class="rounded border border-border bg-surface-hover px-2 py-1.5">+ <div class="text-[10px] text-muted">Capabilities</div>+ <div class="text-sm font-semibold text-base-content">+ {resourceCapabilities().length}+ </div>+ </div>+ <div class="rounded border border-border bg-surface-hover px-2 py-1.5">+ <div class="text-[10px] text-muted">Relationships</div>+ <div class="text-sm font-semibold text-base-content">+ {resourceRelationships().length}+ </div>+ </div>+ <div class="rounded border border-border bg-surface-hover px-2 py-1.5">+ <div class="text-[10px] text-muted">Timeline Events</div>+ <div class="text-sm font-semibold text-base-content">+ {sortedResourceTimeline().length}+ </div>+ </div>+ </div>+ </div>++ <div class="rounded border border-border bg-surface p-3">+ <div class="text-[11px] font-medium uppercase tracking-wide text-base-content mb-2">+ Capabilities+ </div>+ <Show+ when={resourceCapabilities().length > 0}+ fallback={+ <div class="rounded border border-dashed border-border bg-surface-hover px-2 py-2 text-[10px] text-muted">+ No capability records are available for this resource yet.+ </div>+ }+ >+ <div class="space-y-2">+ <For each={resourceCapabilities()}>+ {(capability) => (+ <details class="rounded border border-border bg-surface-hover px-2 py-1.5">+ <summary class="flex cursor-pointer list-none items-center justify-between gap-2 text-[10px] font-medium text-base-content">+ <span class="truncate" title={capability.name}>+ {capability.name}+ </span>+ <span class="text-muted">{humanizeFacetToken(capability.type)}</span>+ </summary>+ <div class="mt-2 space-y-1.5 border-t border-border pt-2 text-[10px]">+ <div class="flex items-center justify-between gap-2">+ <span class="text-muted">Approval</span>+ <span class="font-medium text-base-content">+ {formatApprovalLevel(capability.minimumApprovalLevel)}+ </span>+ </div>+ <Show when={capability.platform}>+ <div class="flex items-center justify-between gap-2">+ <span class="text-muted">Platform</span>+ <span class="font-medium text-base-content">+ {capability.platform}+ </span>+ </div>+ </Show>+ <Show when={capability.description}>+ <div class="rounded border border-border bg-base px-2 py-1 text-[10px] text-base-content">+ {capability.description}+ </div>+ </Show>+ <Show when={capability.params && capability.params.length > 0}>+ <div class="space-y-1">+ <div class="text-[10px] font-medium uppercase tracking-wide text-muted">+ Params+ </div>+ <For each={capability.params ?? []}>+ {(param) => (+ <div class="rounded border border-border bg-base px-2 py-1 text-[10px]">+ <div class="flex items-center justify-between gap-2">+ <span class="font-medium text-base-content">{param.name}</span>+ <span class="text-muted">+ {param.type}+ {param.required ? ' • required' : ''}+ </span>+ </div>+ <Show when={param.description}>+ <div class="mt-1 text-muted">{param.description}</div>+ </Show>+ <Show when={param.enum && param.enum.length > 0}>+ <div class="mt-1 text-muted">+ Allowed: {param.enum?.join(', ')}+ </div>+ </Show>+ <Show when={param.pattern}>+ <div class="mt-1 text-muted">Pattern: {param.pattern}</div>+ </Show>+ </div>+ )}+ </For>+ </div>+ </Show>+ </div>+ </details>+ )}+ </For>+ </div>+ </Show>+ </div>++ <div class="rounded border border-border bg-surface p-3">+ <div class="text-[11px] font-medium uppercase tracking-wide text-base-content mb-2">+ Relationships+ </div>+ <Show+ when={resourceRelationships().length > 0}+ fallback={+ <div class="rounded border border-dashed border-border bg-surface-hover px-2 py-2 text-[10px] text-muted">+ No relationship edges are available for this resource yet.+ </div>+ }+ >+ <div class="space-y-2">+ <For each={resourceRelationships()}>+ {(relationship) => (+ <div class="rounded border border-border bg-surface-hover px-2 py-1.5 text-[10px]">+ <div class="flex items-center justify-between gap-2">+ <span class="font-medium text-base-content">+ {relationship.sourceId} → {relationship.targetId}+ </span>+ <span class="text-muted">{humanizeFacetToken(relationship.type)}</span>+ </div>+ <div class="mt-1 grid gap-1 sm:grid-cols-2">+ <div class="flex items-center justify-between gap-2">+ <span class="text-muted">Confidence</span>+ <span class="font-medium text-base-content">+ {formatConfidence(relationship.confidence)}+ </span>+ </div>+ <div class="flex items-center justify-between gap-2">+ <span class="text-muted">State</span>+ <span class="font-medium text-base-content">+ {relationship.active ? 'Active' : 'Historical'}+ </span>+ </div>+ <div class="flex items-center justify-between gap-2">+ <span class="text-muted">Discoverer</span>+ <span class="font-medium text-base-content">+ {relationship.discoverer || '—'}+ </span>+ </div>+ <div class="flex items-center justify-between gap-2">+ <span class="text-muted">Observed</span>+ <span class="font-medium text-base-content">+ {formatFacetTimestamp(relationship.observedAt) ||+ formatRelativeTime(relationship.observedAt)}+ </span>+ </div>+ </div>+ </div>+ )}+ </For>+ </div>+ </Show>+ </div>++ <div class="rounded border border-border bg-surface p-3">+ <div class="text-[11px] font-medium uppercase tracking-wide text-base-content mb-2">+ Timeline+ </div>+ <Show+ when={sortedResourceTimeline().length > 0}+ fallback={+ <div class="rounded border border-dashed border-border bg-surface-hover px-2 py-2 text-[10px] text-muted">+ No timeline records are available for this resource yet.+ </div>+ }+ >+ <div class="space-y-2">+ <For each={sortedResourceTimeline()}>+ {(change) => (+ <div class="rounded border border-border bg-surface-hover px-2 py-1.5 text-[10px]">+ <div class="flex items-start justify-between gap-3">+ <div class="min-w-0">+ <div class="font-medium text-base-content">+ {humanizeFacetToken(change.kind)}+ </div>+ <div class="mt-0.5 text-muted">+ {formatFacetTimestamp(change.observedAt)}+ <Show when={change.occurredAt}>+ <span class="mx-1">•</span>+ <span>Occurred {formatFacetTimestamp(change.occurredAt)}</span>+ </Show>+ </div>+ </div>+ <span class="text-muted">{humanizeFacetToken(change.sourceType)}</span>+ </div>+ <div class="mt-1 grid gap-1 sm:grid-cols-2">+ <div class="flex items-center justify-between gap-2">+ <span class="text-muted">Confidence</span>+ <span class="font-medium text-base-content">+ {formatConfidence(change.confidence)}+ </span>+ </div>+ <div class="flex items-center justify-between gap-2">+ <span class="text-muted">Adapter</span>+ <span class="font-medium text-base-content">+ {change.sourceAdapter || '—'}+ </span>+ </div>+ <Show when={change.actor}>+ <div class="flex items-center justify-between gap-2">+ <span class="text-muted">Actor</span>+ <span class="font-medium text-base-content">{change.actor}</span>+ </div>+ </Show>+ <Show when={change.from || change.to}>+ <div class="flex items-center justify-between gap-2">+ <span class="text-muted">Transition</span>+ <span class="font-medium text-base-content">+ {change.from || '—'} → {change.to || '—'}+ </span>+ </div>+ </Show>+ </div>+ <Show when={change.reason}>+ <div class="mt-1 rounded border border-border bg-base px-2 py-1 text-[10px] text-base-content">+ {change.reason}+ </div>+ </Show>+ <Show when={change.relatedResources && change.relatedResources.length > 0}>+ <div class="mt-1 text-muted">+ Related: {change.relatedResources?.join(', ')}+ </div>+ </Show>+ </div>+ )}+ </For>+ </div>+ </Show>+ </div>+ </div>+ </div>+{/* Discovery Tab */}<divclass={activeTab() === 'discovery' ? '' : 'hidden'}diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsxnew file mode 100644index 0000000000..5cfdc56793--- /dev/null+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.history.test.tsx@@ -0,0 +1,133 @@+import { describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, within } from '@solidjs/testing-library';++import type { Resource } from '@/types/resource';+import { ResourceDetailDrawer } from '@/components/Infrastructure/ResourceDetailDrawer';++const facetBundleMock = vi.hoisted(() => ({+ getFacetBundle: vi.fn(),+}));++vi.mock('@/App', () => ({+ useWebSocket: () => ({+ state: { pmg: [] as any[] },+ connected: () => true,+ initialDataReceived: () => true,+ reconnecting: () => false,+ reconnect: vi.fn(),+ }),+ useDarkMode: () => () => false,+}));++vi.mock('@/components/Discovery/DiscoveryTab', () => ({+ DiscoveryTab: () => <div data-testid="discovery-tab" />,+}));++vi.mock('@/api/resources', () => ({+ ResourceAPI: {+ getFacetBundle: facetBundleMock.getFacetBundle,+ },+}));++class ResizeObserverMock {+ constructor(_callback: ResizeObserverCallback) {}+ observe() {}+ unobserve() {}+ disconnect() {}+}++if (typeof globalThis.ResizeObserver === 'undefined') {+ vi.stubGlobal('ResizeObserver', ResizeObserverMock);+}++const baseResource = (overrides: Partial<Resource>): Resource => ({+ id: 'resource-1',+ type: 'agent',+ name: 'host-1',+ displayName: 'host-1',+ platformId: 'host-1',+ platformType: 'agent',+ sourceType: 'hybrid',+ status: 'online',+ lastSeen: Date.now(),+ platformData: { sources: ['agent'] },+ ...overrides,+});++describe('ResourceDetailDrawer history tab', () => {+ it('renders resource capability, relationship, and timeline facets', async () => {+ facetBundleMock.getFacetBundle.mockResolvedValueOnce({+ capabilities: [+ {+ name: 'restart',+ type: 'common',+ description: 'Restart the resource safely.',+ minimumApprovalLevel: 'admin',+ platform: 'proxmox',+ params: [+ {+ name: 'force',+ type: 'boolean',+ required: false,+ isSensitive: false,+ description: 'Force the restart when needed.',+ },+ ],+ },+ ],+ relationships: [+ {+ sourceId: 'node:pve-1',+ targetId: 'vm:42',+ type: 'runs_on',+ confidence: 1,+ active: true,+ discoverer: 'proxmox_adapter',+ observedAt: '2026-03-18T12:00:00Z',+ lastSeenAt: '2026-03-18T12:05:00Z',+ },+ ],+ recentChanges: [+ {+ id: 'change-1',+ observedAt: '2026-03-18T12:06:00Z',+ occurredAt: '2026-03-18T12:04:00Z',+ resourceId: 'vm:42',+ kind: 'restart',+ from: 'running',+ to: 'restarting',+ sourceType: 'platform_event',+ sourceAdapter: 'proxmox_adapter',+ confidence: 'high',+ actor: 'agent:oncall-helper',+ relatedResources: ['node:pve-1'],+ reason: 'Routine restart requested',+ },+ ],+ });++ const resource = baseResource({+ id: 'vm:42',+ type: 'vm',+ name: 'vm-42',+ displayName: 'VM 42',+ platformId: 'vm-42',+ platformType: 'proxmox-pve',+ platformData: { sources: ['proxmox'] },+ });++ render(() => <ResourceDetailDrawer resource={resource} />);++ fireEvent.click(screen.getByRole('button', { name: 'History' }));++ await screen.findByText('Resource History');+ const historyPanel = screen.getByTestId('resource-history-tab');+ const panel = within(historyPanel);+ expect(await panel.findByText('restart')).toBeInTheDocument();+ expect(panel.getAllByText('Capabilities')).toHaveLength(2);+ expect(panel.getAllByText('Relationships')).toHaveLength(2);+ expect(panel.getByText('Timeline')).toBeInTheDocument();+ expect(panel.getByText('node:pve-1 → vm:42')).toBeInTheDocument();+ expect(panel.getByText('Routine restart requested')).toBeInTheDocument();+ });+});diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.identity-runtime.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.identity-runtime.test.tsxindex 68e6125fe5..c2e6078157 100644--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.identity-runtime.test.tsx+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.identity-runtime.test.tsx@@ -22,6 +22,16 @@ vi.mock('@/components/Discovery/DiscoveryTab', () => ({DiscoveryTab: () => <div data-testid="discovery-tab" />,}));+vi.mock('@/api/resources', () => ({+ ResourceAPI: {+ getFacetBundle: vi.fn().mockResolvedValue({+ capabilities: [],+ relationships: [],+ recentChanges: [],+ }),+ },+}));+class ResizeObserverMock {constructor(_callback: ResizeObserverCallback) {}observe() {}diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.k8s-capabilities.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.k8s-capabilities.test.tsxindex 0e3e03d43d..357cfe53d9 100644--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.k8s-capabilities.test.tsx+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.k8s-capabilities.test.tsx@@ -19,6 +19,16 @@ vi.mock('@/components/Discovery/DiscoveryTab', () => ({DiscoveryTab: () => <div data-testid="discovery-tab" />,}));+vi.mock('@/api/resources', () => ({+ ResourceAPI: {+ getFacetBundle: vi.fn().mockResolvedValue({+ capabilities: [],+ relationships: [],+ recentChanges: [],+ }),+ },+}));+const buildKubernetesResource = (): Resource => ({id: 'k8s-cluster-1',type: 'k8s-cluster',diff --git a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.service-cards.test.tsx b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.service-cards.test.tsxindex b241e4dfaa..ef3c98beab 100644--- a/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.service-cards.test.tsx+++ b/frontend-modern/src/components/Infrastructure/__tests__/ResourceDetailDrawer.service-cards.test.tsx@@ -22,6 +22,16 @@ vi.mock('@/components/Discovery/DiscoveryTab', () => ({DiscoveryTab: () => <div data-testid="discovery-tab" />,}));+vi.mock('@/api/resources', () => ({+ ResourceAPI: {+ getFacetBundle: vi.fn().mockResolvedValue({+ capabilities: [],+ relationships: [],+ recentChanges: [],+ }),+ },+}));+const baseResource = (overrides: Partial<Resource>): Resource => ({id: 'resource-1',type: 'agent',diff --git a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.tsindex d004896687..e2855ad802 100644--- a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts+++ b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts@@ -713,6 +713,101 @@ describe('useUnifiedResources', () => {dispose();});+ it('preserves resource facets from backend payloads', async () => {+ apiFetchMock.mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ data: [+ {+ ...v2Resource,+ id: 'node-facets',+ capabilities: [+ {+ name: 'restart',+ type: 'common',+ description: 'Restart the resource safely.',+ minimumApprovalLevel: 'admin',+ platform: 'proxmox',+ },+ ],+ relationships: [+ {+ sourceId: 'node:pve-1',+ targetId: 'node-facets',+ type: 'runs_on',+ confidence: 0.98,+ active: true,+ discoverer: 'proxmox_adapter',+ observedAt: '2026-03-18T12:00:00Z',+ lastSeenAt: '2026-03-18T12:05:00Z',+ },+ ],+ recentChanges: [+ {+ id: 'change-1',+ observedAt: '2026-03-18T12:06:00Z',+ resourceId: 'node-facets',+ kind: 'capability_change',+ from: 'none',+ to: 'restart',+ sourceType: 'platform_event',+ sourceAdapter: 'proxmox_adapter',+ confidence: 'high',+ },+ ],+ },+ ],+ }),+ });++ let dispose = () => {};+ let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;+ createRoot((d) => {+ dispose = d;+ result = useUnifiedResources();+ });++ await flushAsync();+ await waitForResourceCount(() => result!.resources().length);++ expect(result!.resources()[0]?.capabilities).toEqual([+ {+ name: 'restart',+ type: 'common',+ description: 'Restart the resource safely.',+ minimumApprovalLevel: 'admin',+ platform: 'proxmox',+ },+ ]);+ expect(result!.resources()[0]?.relationships).toEqual([+ {+ sourceId: 'node:pve-1',+ targetId: 'node-facets',+ type: 'runs_on',+ confidence: 0.98,+ active: true,+ discoverer: 'proxmox_adapter',+ observedAt: '2026-03-18T12:00:00Z',+ lastSeenAt: '2026-03-18T12:05:00Z',+ },+ ]);+ expect(result!.resources()[0]?.recentChanges).toEqual([+ {+ id: 'change-1',+ observedAt: '2026-03-18T12:06:00Z',+ resourceId: 'node-facets',+ kind: 'capability_change',+ from: 'none',+ to: 'restart',+ sourceType: 'platform_event',+ sourceAdapter: 'proxmox_adapter',+ confidence: 'high',+ },+ ]);++ dispose();+ });+it('filters malformed source entries from backend payloads', async () => {apiFetchMock.mockResolvedValueOnce({ok: true,diff --git a/frontend-modern/src/hooks/useUnifiedResources.ts b/frontend-modern/src/hooks/useUnifiedResources.tsindex b4cbc95b27..aa416bcec8 100644--- a/frontend-modern/src/hooks/useUnifiedResources.ts+++ b/frontend-modern/src/hooks/useUnifiedResources.ts@@ -6,6 +6,8 @@ import { apiFetch, getOrgID } from '@/utils/apiClient';import { getGlobalWebSocketStore } from '@/stores/websocket-global';import type {Resource,+ ResourceCapability,+ ResourceChange,ResourceDiscoveryTarget,ResourceMetricsTarget,ResourcePBSMeta,@@ -15,6 +17,7 @@ import type {ResourceSensitivity,ResourceStatus,ResourceStorageMeta,+ ResourceRelationship,ResourceType,} from '@/types/resource';import { normalizeDiskArray } from '@/utils/format';@@ -302,6 +305,9 @@ type APIResource = {lastUpdated?: string;};kubernetes?: APIKubernetesData;+ capabilities?: ResourceCapability[];+ relationships?: ResourceRelationship[];+ recentChanges?: ResourceChange[];physicalDisk?: {devPath?: string;model?: string;@@ -705,6 +711,9 @@ const toResource = (v2: APIResource): Resource => {canonicalIdentity: v2.canonicalIdentity,policy,aiSafeSummary,+ capabilities: v2.capabilities,+ relationships: v2.relationships,+ recentChanges: v2.recentChanges,platformData: {sources,sourceStatus: v2.sourceStatus,diff --git a/frontend-modern/src/types/resource.ts b/frontend-modern/src/types/resource.tsindex 39a36bf480..5d0d4bf2ac 100644--- a/frontend-modern/src/types/resource.ts+++ b/frontend-modern/src/types/resource.ts@@ -143,6 +143,84 @@ export interface ResourcePolicy {routing: ResourceRoutingPolicy;}+export type ResourceCapabilityType = 'common' | 'native';+export type ResourceApprovalLevel = 'none' | 'dry_run_only' | 'admin' | 'mfa';+export type ResourceRelationshipType =+ | 'runs_on'+ | 'depends_on'+ | 'mounted_to'+ | 'exposed_by'+ | 'owned_by';+export type ResourceChangeConfidence = 'high' | 'medium' | 'low';+export type ResourceChangeKind =+ | 'state_transition'+ | 'restart'+ | 'config_update'+ | 'metric_anomaly'+ | 'relationship_change'+ | 'capability_change';+export type ResourceChangeSourceType =+ | 'platform_event'+ | 'pulse_diff'+ | 'heuristic'+ | 'user_action'+ | 'agent_action';+export type ResourceChangeSourceAdapter =+ | 'docker_adapter'+ | 'proxmox_adapter'+ | 'truenas_adapter'+ | 'agent:ops-helper'+ | string;++export interface ResourceCapabilityParam {+ name: string;+ type: string;+ required: boolean;+ enum?: string[];+ pattern?: string;+ defaultValue?: unknown;+ isSensitive: boolean;+ description?: string;+}++export interface ResourceCapability {+ name: string;+ type: ResourceCapabilityType;+ description: string;+ minimumApprovalLevel: ResourceApprovalLevel;+ platform?: string;+ params?: ResourceCapabilityParam[];+}++export interface ResourceRelationship {+ sourceId: string;+ targetId: string;+ type: ResourceRelationshipType;+ confidence: number;+ active: boolean;+ discoverer: string;+ observedAt: string;+ lastSeenAt: string;+ metadata?: Record<string, unknown>;+}++export interface ResourceChange {+ id: string;+ observedAt: string;+ occurredAt?: string;+ resourceId: string;+ kind: ResourceChangeKind;+ from?: string;+ to?: string;+ sourceType: ResourceChangeSourceType;+ sourceAdapter?: ResourceChangeSourceAdapter;+ confidence: ResourceChangeConfidence;+ actor?: string;+ relatedResources?: string[];+ reason?: string;+ metadata?: Record<string, unknown>;+}+export type MetricsHistoryTargetResourceType =| 'agent'| 'vm'@@ -405,6 +483,9 @@ export interface Resource {canonicalIdentity?: ResourceCanonicalIdentity;policy?: ResourcePolicy;aiSafeSummary?: string;+ capabilities?: ResourceCapability[];+ relationships?: ResourceRelationship[];+ recentChanges?: ResourceChange[];// Common source facets (optional; not all backends/state payloads include these).// Prefer these over casting `platformData` when available.diff --git a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.tsindex b44e6279a9..f5fad952ec 100644--- a/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts+++ b/frontend-modern/src/utils/__tests__/frontendResourceTypeBoundaries.test.ts@@ -874,8 +874,8 @@ describe('frontend resource type boundaries', () => {expect(storagePoolDetailSource).not.toContain("'text-yellow-600 dark:text-yellow-400 italic'");expect(storagePoolDetailSource).not.toContain("'text-red-600 dark:text-red-400 font-medium'");expect(diskDetailSource).toContain('getDiskAttributeValueTextClass');- expect(diskDetailSource).toContain('getDiskDetailAttributeCards');- expect(diskDetailSource).toContain('getDiskDetailHistoryCharts');+ expect(diskDetailSource).toContain('attributeCards()');+ expect(diskDetailSource).toContain('historyCharts()');expect(diskDetailSource).toContain('getDiskDetailHistoryFallbackMessage');expect(diskDetailSource).toContain('getDiskDetailLiveBadgeLabel');expect(diskDetailSource).toContain('DISK_DETAIL_HISTORY_RANGE_OPTIONS');@@ -955,7 +955,7 @@ describe('frontend resource type boundaries', () => {expect(useStorageCephModelSource).toContain("from '@/features/storageBackups/cephRecordPresentation'",);- expect(useStorageCephModelSource).toContain('getCephClusterKeyFromStorageRecord');+ expect(useStorageCephModelSource).toContain('resolveCephClusterForStorageRecord');expect(useStorageCephModelSource).toContain('getCephSummaryText');expect(useStorageCephModelSource).toContain('getCephPoolsText');expect(useStorageCephModelSource).toContain(@@ -1817,6 +1817,8 @@ describe('frontend resource type boundaries', () => {'export const ENVIRONMENT_LOCK_BUTTON_TITLE',);expect(resourceDetailDrawerSource).toContain('getServiceHealthPresentation');+ expect(resourceDetailDrawerSource).toContain('ResourceAPI.getFacetBundle');+ expect(resourceDetailDrawerSource).toContain('History');expect(resourceDetailDrawerSource).not.toContain('healthToneClass(');expect(resourceDetailDrawerSource).not.toContain('normalizeHealthLabel(');expect(resourceDetailMappersSource).not.toContain('export const normalizeHealthLabel');@@ -2022,7 +2024,6 @@ describe('frontend resource type boundaries', () => {expect(alertsPageSource).toContain('getAlertDestinationsLoadErrorBanner');expect(alertsPageSource).toContain('getAlertDestinationsAppriseTargetsHelp');expect(alertsPageSource).toContain('getAlertDestinationsAppriseTestLabel');- expect(alertsPageSource).toContain('getAlertDestinationsAppriseTestError');expect(alertsPageSource).toContain('getAlertDestinationsAppriseValidationError');expect(alertsPageSource).toContain('getAlertDestinationsEmailTestSuccess');expect(alertsPageSource).toContain('getAlertDestinationsEmailTestFailure');@@ -2043,7 +2044,6 @@ describe('frontend resource type boundaries', () => {expect(alertsPageSource).toContain('getAlertResourceIncidentAcknowledgedByLabel');expect(alertsPageSource).toContain('getAlertResourceIncidentToggleLabel');expect(alertsPageSource).toContain('getAlertResourceIncidentFilteredEventsEmptyState');- expect(alertsPageSource).toContain('getAlertResourceIncidentRecentEventsSummary');expect(alertsPageSource).toContain('getAlertResourceIncidentNotePlaceholder');expect(alertsPageSource).toContain('getAlertResourceIncidentSaveNoteLabel');expect(alertsPageSource).toContain('getAlertIncidentEventFilterContainerClass');