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
import { batch, createRoot, createSignal } from 'solid-js';
import { createStore, reconcile, unwrap, type SetStoreFunction } from 'solid-js/store';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildProxmoxPageModel } from '@/features/proxmox/proxmoxPageModel';
import { getDockerContainerLifecycleDisabledReason } from '@/features/docker/dockerContainerLifecycleActions';
import type { State } from '@/types/api';
import type { Resource } from '@/types/resource';
import useUnifiedResourcesSource from '../useUnifiedResources.ts?raw';
import { RESOURCE_METADATA_CHANGED_EVENT } from '@/utils/resourceMetadataEvents';
type UseUnifiedResourcesModule = typeof import('@/hooks/useUnifiedResources');
type TestWsState = State & Record<string, unknown>;
const v2Resource = {
id: 'node-1',
type: 'agent',
name: 'node-1',
status: 'online',
lastSeen: '2026-02-06T12:00:00Z',
sources: ['agent'],
health: { verdict: 'ok' as const, reasons: [] },
facetCounts: {
recentChanges: 1,
},
metrics: {
cpu: { percent: 15 },
memory: { used: 4 * 1024 * 1024, total: 8 * 1024 * 1024, percent: 50 },
disk: { used: 30 * 1024 * 1024, total: 100 * 1024 * 1024, percent: 30 },
},
discoveryTarget: {
resourceType: 'agent',
agentId: 'host-1',
resourceId: 'host-1',
hostname: 'pve1',
},
};
const wsResource: Resource = {
id: 'node-1',
type: 'agent',
name: 'node-1',
displayName: 'node-1',
platformId: 'node-1',
platformType: 'agent',
sourceType: 'agent',
status: 'online',
lastSeen: Date.parse('2026-02-06T12:00:00Z'),
cpu: { current: 15 },
memory: { current: 50, used: 4 * 1024 * 1024, total: 8 * 1024 * 1024, free: 4 * 1024 * 1024 },
disk: {
current: 30,
used: 30 * 1024 * 1024,
total: 100 * 1024 * 1024,
free: 70 * 1024 * 1024,
},
discoveryTarget: {
resourceType: 'agent',
agentId: 'host-1',
resourceId: 'host-1',
hostname: 'pve1',
},
facetCounts: {
recentChanges: 1,
},
};
const createWsResource = (overrides: Partial<Resource> = {}): Resource => ({
...wsResource,
...overrides,
});
const createThinWsPBSResource = (overrides: Partial<Resource> = {}): Resource =>
({
id: 'pbs-1',
type: 'pbs',
name: 'backup-vault',
displayName: 'backup-vault',
platformId: 'pbs-main',
platformType: 'proxmox-pbs',
sourceType: 'api',
status: 'online',
lastSeen: Date.parse('2026-02-06T12:00:00Z'),
cpu: { current: 9 },
memory: {
current: 36,
used: 6 * 1024 * 1024,
total: 16 * 1024 * 1024,
free: 10 * 1024 * 1024,
},
platformData: {
host: '198.51.100.10',
version: '3.2.1',
connectionHealth: 'healthy',
numDatastores: 2,
},
...overrides,
}) as Resource;
const flushAsync = async () => {
await Promise.resolve();
await Promise.resolve();
};
const waitForResourceCount = async (getCount: () => number, expectedMin = 1) => {
for (let i = 0; i < 20; i++) {
if (getCount() >= expectedMin) {
return;
}
await flushAsync();
}
throw new Error(`Timed out waiting for at least ${expectedMin} resources`);
};
const waitForValue = async <T>(readValue: () => T, expected: T) => {
for (let i = 0; i < 20; i++) {
if (readValue() === expected) {
return;
}
await flushAsync();
}
throw new Error(`Timed out waiting for expected value: ${String(expected)}`);
};
const deferred = <T>() => {
let resolve!: (value: T | PromiseLike<T>) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
};
const resourceResponse = (data: unknown[]) => ({
ok: true,
status: 200,
json: async () => ({ data }),
});
describe('useUnifiedResources', () => {
let apiFetchMock: ReturnType<typeof vi.fn>;
let setWsState: SetStoreFunction<TestWsState>;
let setWsConnected: (value: boolean) => boolean;
let setWsInitialDataReceived: (value: boolean) => boolean;
let setWsResourceChange: (value: {
version: number;
changedIds: ReadonlySet<string> | null;
}) => unknown;
let wsStoreMock: Record<string, unknown>;
let useUnifiedResources: UseUnifiedResourcesModule['useUnifiedResources'];
let useStorageRecoveryResources: UseUnifiedResourcesModule['useStorageRecoveryResources'];
let resetUnifiedResourcesCacheForTests: UseUnifiedResourcesModule['__resetUnifiedResourcesCacheForTests'];
let resolveIncrementalResourcePatchIndices: UseUnifiedResourcesModule['resolveIncrementalResourcePatchIndices'];
let eventBus: (typeof import('@/stores/events'))['eventBus'];
it('keeps API-selected memory annotation through the canonical normalizer', async () => {
setWsConnected(false);
setWsState('resources', []);
const observation = {
state: 'last-known',
source: 'guest-agent-meminfo',
observedAt: '2026-10-04T14:00:00Z',
};
apiFetchMock.mockResolvedValue(
resourceResponse([
{
...v2Resource,
metrics: { ...v2Resource.metrics, memory: { ...v2Resource.metrics.memory, observation } },
},
]),
);
let dispose = () => {};
let result!: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']>;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
try {
await waitForResourceCount(() => result.resources().length);
expect(result.resources()[0].memory).toMatchObject({ current: 50, observation });
apiFetchMock.mockResolvedValue(
resourceResponse([
{
...v2Resource,
lastSeen: '2026-10-04T17:00:00Z',
metrics: {
...v2Resource.metrics,
memory: { ...v2Resource.metrics.memory, observation },
},
},
]),
);
await result.refetch();
expect(result.resources()[0].memory).toMatchObject({ current: 50, observation });
apiFetchMock.mockResolvedValue(resourceResponse([v2Resource]));
await result.refetch();
expect(result.resources()[0].memory).not.toHaveProperty('observation');
} finally {
dispose();
}
});
beforeEach(async () => {
vi.useFakeTimers();
vi.resetModules();
apiFetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ data: [v2Resource] }),
});
const [connected, _setConnected] = createSignal(true);
const [initialDataReceived, _setInitialDataReceived] = createSignal(true);
const [resourceChange, _setResourceChange] = createSignal<{
version: number;
changedIds: ReadonlySet<string> | null;
}>({ version: 0, changedIds: null });
setWsConnected = _setConnected;
setWsInitialDataReceived = _setInitialDataReceived;
setWsResourceChange = _setResourceChange;
const [state, _setWsState] = createStore<TestWsState>({
connectedInfrastructure: [],
metrics: [],
performance: {
apiCallDuration: {},
lastPollDuration: 0,
pollingStartTime: '',
totalApiCalls: 0,
failedApiCalls: 0,
cacheHits: 0,
cacheMisses: 0,
},
connectionHealth: {},
stats: {
startTime: '',
uptime: 0,
pollingCycles: 0,
webSocketClients: 0,
version: '2.0.0',
},
activeAlerts: [],
recentlyResolved: [],
pveTagColors: {},
pveTagStyles: {},
resources: [wsResource],
lastUpdate: 0,
});
setWsState = _setWsState;
const wsStore = { connected, initialDataReceived, state, resourceChange };
wsStoreMock = wsStore as unknown as Record<string, unknown>;
vi.doMock('@/utils/apiClient', () => ({
apiFetch: apiFetchMock,
getOrgID: () => 'default',
}));
vi.doMock('@/stores/websocket-global', () => ({
getGlobalWebSocketStore: () => wsStore,
}));
({
useUnifiedResources,
useStorageRecoveryResources,
__resetUnifiedResourcesCacheForTests: resetUnifiedResourcesCacheForTests,
resolveIncrementalResourcePatchIndices,
} = await import('@/hooks/useUnifiedResources'));
({ eventBus } = await import('@/stores/events'));
resetUnifiedResourcesCacheForTests();
});
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
vi.resetModules();
});
it('bounds realtime store reconciliation to changed rows in a large estate', () => {
const current = Array.from({ length: 1_508 }, (_, index): Resource => ({
...createWsResource(),
id: `resource-${index}`,
name: `resource-${index}`,
displayName: `resource-${index}`,
type: index < 50 ? 'agent' : 'vm',
}));
const next = current.map((resource, index) =>
index === 900 ? { ...resource, cpu: { current: 73 } } : resource,
);
expect(
resolveIncrementalResourcePatchIndices(current, next, new Set(['resource-900'])),
).toEqual([900]);
// Each server row is one display row, so a changed agent patches only
// itself rather than the whole agent subset.
expect(
resolveIncrementalResourcePatchIndices(
current,
next,
new Set(['resource-7', 'resource-900']),
),
).toEqual([7, 900]);
});
it('falls back to a full keyed reconcile when realtime membership or order changes', () => {
const first = createWsResource({ id: 'first' });
const second = createWsResource({ id: 'second' });
expect(
resolveIncrementalResourcePatchIndices(
[first, second],
[second, first],
new Set(['first', 'second']),
),
).toBeNull();
expect(
resolveIncrementalResourcePatchIndices([first], [first, second], new Set(['second'])),
).toBeNull();
});
it('applies sequential changed-ID revisions through the incremental route store path', async () => {
const vm = createWsResource({
id: 'vm-1',
name: 'vm-1',
displayName: 'vm-1',
type: 'vm',
});
setWsState('resources', [vm]);
setWsResourceChange({ version: 1, changedIds: null });
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: '',
cacheKey: 'all-resources',
initialHydration: 'prefer-ws',
});
});
await waitForResourceCount(() => result!.resources().length);
expect(result!.resources()[0]?.cpu?.current).toBe(15);
expect(result!.resourceSnapshotChange().changedIds).toBeNull();
batch(() => {
setWsState('resources', 0, 'cpu', 'current', 88);
setWsResourceChange({ version: 2, changedIds: new Set(['vm-1']) });
setWsState('lastUpdate', 1738843201000);
});
await waitForValue(() => result!.resources()[0]?.cpu?.current, 88);
expect(result!.resourceSnapshotChange().changedIds).toEqual(new Set(['vm-1']));
expect(apiFetchMock).not.toHaveBeenCalled();
dispose();
});
it('keeps an operator-split host pair as two rows and an unchanged agent peer by identity', async () => {
// Broadcast shape: a joined host's platformData is the flattened Proxmox
// facts; the split agent row arrives agent-only under the
// joined row's id and the node arrives as a new row.
const proxmoxFacet = { nodeName: 'pve1', instance: 'pve1', clusterName: 'homelab' };
const joined = createWsResource({
id: 'agent-machine-pve1',
name: 'pve1',
displayName: 'pve1',
platformType: 'proxmox-pve',
sourceType: 'hybrid',
sources: ['agent', 'proxmox'],
clusterId: 'cluster:homelab',
cpu: { current: 15 },
proxmox: proxmoxFacet,
platformData: { instance: 'pve1', pveVersion: '9.1.9', clusterName: 'homelab' },
} as Partial<Resource>);
const peer = createWsResource({
id: 'agent-peer',
name: 'peer',
displayName: 'peer',
sources: ['agent'],
cpu: { current: 20 },
} as Partial<Resource>);
setWsState('resources', [joined, peer]);
setWsResourceChange({ version: 1, changedIds: null });
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: '',
cacheKey: 'all-resources',
initialHydration: 'prefer-ws',
});
});
await waitForResourceCount(() => result!.resources().length);
expect(result!.resources()).toHaveLength(2);
const peerBefore = result!.resources().find((resource) => resource.id === 'agent-peer');
const splitAgent = createWsResource({
id: 'agent-machine-pve1',
name: 'pve1',
displayName: 'pve1',
sources: ['agent'],
cpu: { current: 15 },
platformData: { platform: 'linux', osName: 'Debian GNU/Linux' },
} as Partial<Resource>);
const splitNode = createWsResource({
id: 'agent-node-pve1',
name: 'pve1',
displayName: 'pve1',
platformType: 'proxmox-pve',
sourceType: 'api',
sources: ['proxmox'],
clusterId: 'cluster:homelab',
proxmox: proxmoxFacet,
platformData: { instance: 'pve1', pveVersion: '9.1.9', clusterName: 'homelab' },
} as Partial<Resource>);
batch(() => {
setWsState('resources', [splitAgent, peer, splitNode]);
setWsResourceChange({
version: 2,
changedIds: new Set(['agent-machine-pve1', 'agent-node-pve1']),
});
setWsState('lastUpdate', 1738843202000);
});
await waitForResourceCount(() => result!.resources().length, 3);
const agentRow = result!.resources().find((resource) => resource.id === 'agent-machine-pve1');
const nodeRow = result!.resources().find((resource) => resource.id === 'agent-node-pve1');
expect(agentRow?.sources).toEqual(['agent']);
expect(agentRow?.proxmox).toBeUndefined();
expect(agentRow?.clusterId).toBeUndefined();
expect((agentRow?.platformData as Record<string, unknown>).pveVersion).toBeUndefined();
expect(nodeRow?.sources).toEqual(['proxmox']);
expect(nodeRow?.proxmox).toMatchObject({ nodeName: 'pve1' });
expect(result!.resources().find((resource) => resource.id === 'agent-peer')).toBe(peerBefore);
// A tick on the split agent alone patches that row; the node and the
// unchanged agent peer stay as they were.
batch(() => {
setWsState('resources', 0, 'cpu', 'current', 42);
setWsResourceChange({ version: 3, changedIds: new Set(['agent-machine-pve1']) });
setWsState('lastUpdate', 1738843203000);
});
await waitForValue(
() =>
result!.resources().find((resource) => resource.id === 'agent-machine-pve1')?.cpu?.current,
42,
);
expect(result!.resources()).toHaveLength(3);
expect(result!.resources().find((resource) => resource.id === 'agent-peer')).toBe(peerBefore);
expect(
result!.resources().find((resource) => resource.id === 'agent-node-pve1')?.sources,
).toEqual(['proxmox']);
expect(apiFetchMock).not.toHaveBeenCalled();
dispose();
});
it('drops REST enrichment of a departed source when the store reconciles a split in place', async () => {
// The websocket store reconciles a split into its own rows in place. Cache
// rows built by the hook's first full merge must not share nested arrays
// with those rows, or the in-place edit flips the cached row's sources
// while its REST-only enrichment (source status, platform scopes) stays,
// and no later merge sees a source leave.
const proxmoxFacet = { nodeName: 'pve1', instance: 'pve1', clusterName: 'homelab' };
const joined = createWsResource({
id: 'agent-machine-pve1',
name: 'pve1',
displayName: 'pve1',
platformType: 'proxmox-pve',
sourceType: 'hybrid',
sources: ['agent', 'proxmox'],
proxmox: proxmoxFacet,
} as Partial<Resource>);
setWsState('resources', reconcile([joined], { key: 'id' }));
setWsResourceChange({ version: 1, changedIds: null });
apiFetchMock.mockResolvedValue(
resourceResponse([
{
...v2Resource,
id: 'agent-machine-pve1',
name: 'pve1',
sources: ['agent', 'proxmox'],
platformScopes: ['agent', 'proxmox-pve'],
sourceStatus: {
agent: { status: 'online', lastSeen: '2026-02-06T12:00:00Z' },
proxmox: { status: 'online', lastSeen: '2026-02-06T12:00:00Z' },
},
proxmox: proxmoxFacet,
},
]),
);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: 'type=agent',
cacheKey: 'standalone-workspace',
initialHydration: 'prefer-ws',
});
});
await waitForResourceCount(() => result!.resources().length);
// Rows the hook's full merge built share no nested array with the store's
// rows, which the store reconciles in place.
const storeRow = (unwrap((wsStoreMock.state as TestWsState).resources) as Resource[]).find(
(resource) => resource.id === 'agent-machine-pve1',
);
const hookRow = unwrap(result!.resources()).find(
(resource) => resource.id === 'agent-machine-pve1',
);
expect(hookRow?.sources).toEqual(['agent', 'proxmox']);
expect(hookRow?.sources).not.toBe(storeRow?.sources);
expect(hookRow?.platformData).not.toBe(storeRow?.platformData);
await result!.refetch();
const enriched = result!.resources().find((resource) => resource.id === 'agent-machine-pve1');
expect(enriched?.sourceStatus).toHaveProperty('proxmox');
expect(enriched?.platformScopes).toContain('proxmox-pve');
// The server splits the pair: the agent keeps the id, the node is a new row.
const splitAgent = createWsResource({
id: 'agent-machine-pve1',
name: 'pve1',
displayName: 'pve1',
sources: ['agent'],
} as Partial<Resource>);
const splitNode = createWsResource({
id: 'agent-node-pve1',
name: 'pve1',
displayName: 'pve1',
platformType: 'proxmox-pve',
sourceType: 'api',
sources: ['proxmox'],
proxmox: proxmoxFacet,
} as Partial<Resource>);
batch(() => {
setWsState('resources', reconcile([splitAgent, splitNode], { key: 'id' }));
setWsResourceChange({
version: 2,
changedIds: new Set(['agent-machine-pve1', 'agent-node-pve1']),
});
setWsState('lastUpdate', 1738843202000);
});
await waitForResourceCount(() => result!.resources().length, 2);
const agentRow = result!.resources().find((resource) => resource.id === 'agent-machine-pve1');
expect(agentRow?.sources).toEqual(['agent']);
expect(Object.keys(agentRow?.sourceStatus ?? {})).not.toContain('proxmox');
expect(
Object.keys(
((agentRow?.platformData as Record<string, unknown> | undefined)?.sourceStatus ??
{}) as Record<string, unknown>,
),
).not.toContain('proxmox');
expect(agentRow?.platformData?.sources).toEqual(['agent']);
expect(agentRow?.platformScopes ?? []).not.toContain('proxmox-pve');
expect(
((agentRow?.platformData as Record<string, unknown> | undefined)?.platformScopes ??
[]) as string[],
).not.toContain('proxmox-pve');
dispose();
});
it('catches up multi-tick version gaps through the changed-id history instead of a full remerge', async () => {
// Distinct nested cpu objects: the shared wsResource base would otherwise
// alias one cpu object across both rows and the two writes below.
const vm1 = createWsResource({
id: 'vm-1',
name: 'vm-1',
displayName: 'vm-1',
type: 'vm',
cpu: { current: 15 },
});
const vm2 = createWsResource({
id: 'vm-2',
name: 'vm-2',
displayName: 'vm-2',
type: 'vm',
cpu: { current: 15 },
});
setWsState('resources', [vm1, vm2]);
setWsResourceChange({ version: 1, changedIds: null });
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: '',
cacheKey: 'all-resources',
initialHydration: 'prefer-ws',
});
});
await waitForResourceCount(() => result!.resources().length);
const vm2RowBefore = result!.resources().find((resource) => resource.id === 'vm-2');
// Two ticks land while no instance applies them (version 1 -> 3). The
// store's history union names only vm-1, so the delta path must re-merge
// vm-1 and keep the unflagged vm-2 row by identity — a full remerge would
// rebuild it.
const historySpy = vi.fn().mockReturnValue(new Set(['vm-1']));
wsStoreMock.changedResourceIdsSince = historySpy;
batch(() => {
setWsState('resources', 0, 'cpu', 'current', 88);
setWsState('resources', 1, 'cpu', 'current', 99);
setWsResourceChange({ version: 3, changedIds: new Set(['vm-1']) });
setWsState('lastUpdate', 1738843203000);
});
await waitForValue(
() => result!.resources().find((resource) => resource.id === 'vm-1')?.cpu?.current,
88,
);
expect(historySpy).toHaveBeenCalledWith(1);
const vm2RowAfter = result!.resources().find((resource) => resource.id === 'vm-2');
expect(vm2RowAfter).toBe(vm2RowBefore);
expect(apiFetchMock).not.toHaveBeenCalled();
dispose();
});
it('hydrates realtime store entries that arrive without being flagged changed', async () => {
// The incremental path only unwraps raw subtrees for entries it expects to
// clone (changed ids, agents, and ids missing from the merge cache). An
// unflagged addition exercises the missing-from-cache branch: without its
// defensive unwrap, structuredClone on the store proxy would throw here.
const vm = createWsResource({
id: 'vm-1',
name: 'vm-1',
displayName: 'vm-1',
type: 'vm',
});
setWsState('resources', [vm]);
setWsResourceChange({ version: 1, changedIds: null });
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: '',
cacheKey: 'all-resources',
initialHydration: 'prefer-ws',
});
});
await waitForResourceCount(() => result!.resources().length);
batch(() => {
setWsState('resources', [
vm,
createWsResource({ id: 'vm-2', name: 'vm-2', displayName: 'vm-2', type: 'vm' }),
]);
setWsResourceChange({ version: 2, changedIds: new Set(['vm-1']) });
setWsState('lastUpdate', 1738843202000);
});
await waitForValue(() => result!.resources().length, 2);
expect(result!.resources().map((resource) => resource.id)).toContain('vm-2');
dispose();
});
it('uses canonical websocket resource updates without a REST refetch for supported queries', async () => {
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
await waitForResourceCount(() => result!.resources().length);
expect(apiFetchMock).toHaveBeenNthCalledWith(
1,
'/api/resources?type=agent%2Cdocker-host%2Cpbs%2Cpmg%2Ck8s-cluster%2Ck8s-node%2Cnetwork-endpoint&page=1&limit=100',
{ cache: 'no-store' },
);
await flushAsync();
await flushAsync();
// Simulate a metric update where reconcile keeps array identity stable.
batch(() => {
setWsState(
'resources',
reconcile(
[
createWsResource({
cpu: { current: 42 },
status: 'degraded',
incidentSummary: 'Unraid array is running without parity protection',
canonicalIdentity: {
primaryId: 'agent:host-1',
hostname: 'pve1',
},
metricsTarget: {
resourceType: 'agent',
resourceId: 'host-1',
},
agent: {
storagePostureSummary: 'Unraid array is running without parity protection',
rebuildSummary: 'Unraid array is running check',
unraid: {
risk: {
level: 'warning',
reasons: [
{
code: 'unraid_no_parity',
severity: 'warning',
summary: 'Unraid array is running without parity protection',
},
],
},
},
},
storage: {
postureSummary: 'Unraid array is running without parity protection',
},
}),
],
{ key: 'id' },
),
);
setWsState('lastUpdate', 1738843201000);
});
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(result!.resources()[0]?.cpu?.current).toBe(42);
expect(result!.resources()[0].discoveryTarget).toEqual({
resourceType: 'agent',
agentId: 'host-1',
resourceId: 'host-1',
hostname: 'pve1',
});
expect(result!.resources()[0].facetCounts).toEqual({
recentChanges: 1,
});
expect(result!.resources()[0].canonicalIdentity?.primaryId).toBe('agent:host-1');
expect(result!.resources()[0].metricsTarget).toEqual({
resourceType: 'agent',
resourceId: 'host-1',
});
expect(result!.resources()[0].incidentSummary).toBe(
'Unraid array is running without parity protection',
);
expect(result!.resources()[0].agent?.storagePostureSummary).toBe(
'Unraid array is running without parity protection',
);
expect(result!.resources()[0].agent?.unraid?.risk?.reasons?.[0]?.code).toBe('unraid_no_parity');
expect(result!.resources()[0].storage?.postureSummary).toBe(
'Unraid array is running without parity protection',
);
dispose();
});
it('refetches the canonical tenant snapshot after same-tab metadata changes', async () => {
apiFetchMock.mockResolvedValueOnce(resourceResponse([v2Resource])).mockResolvedValueOnce(
resourceResponse([
{
...v2Resource,
customUrl: 'https://node-1.internal',
},
]),
);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await waitForResourceCount(() => result!.resources().length);
expect(apiFetchMock).toHaveBeenCalledTimes(1);
window.dispatchEvent(
new CustomEvent(RESOURCE_METADATA_CHANGED_EVENT, {
detail: {
metadataKind: 'agent',
metadataId: 'host-1',
customUrl: 'https://node-1.internal',
},
}),
);
await waitForValue(() => result!.resources()[0]?.customUrl, 'https://node-1.internal');
expect(apiFetchMock).toHaveBeenCalledTimes(2);
dispose();
});
it('keeps an attached availability check distinct from its host across REST and websocket updates', async () => {
const host = createWsResource({
id: 'agent-core2026',
name: 'core2026',
displayName: 'core2026',
availability: {
targetId: 'stats-pv',
correlationState: 'attached',
available: true,
},
availabilityChecks: [
{
targetId: 'stats-pv',
correlationState: 'attached',
available: true,
},
],
});
const check = createWsResource({
id: 'network-endpoint-stats-pv',
type: 'network-endpoint',
name: 'stats_pv',
displayName: 'stats_pv',
platformId: 'stats_pv',
platformType: 'availability',
sourceType: 'api',
sources: ['availability'],
availability: {
targetId: 'stats-pv',
correlationState: 'attached',
available: true,
},
});
setWsState('resources', reconcile([host, check]));
apiFetchMock.mockResolvedValueOnce(
resourceResponse([
{
...v2Resource,
id: host.id,
name: host.name,
availability: host.availability,
availabilityChecks: host.availabilityChecks,
},
{
...v2Resource,
id: check.id,
type: 'network-endpoint',
name: check.name,
sources: ['availability'],
availability: check.availability,
},
]),
);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await waitForResourceCount(() => result!.resources().length, 2);
expect(
result!
.resources()
.map((resource) => resource.id)
.sort(),
).toEqual(['agent-core2026', 'network-endpoint-stats-pv']);
batch(() => {
setWsState(
'resources',
reconcile([
host,
{
...check,
status: 'offline',
availability: {
...check.availability,
available: false,
consecutiveFailures: 2,
},
},
]),
);
setWsState('lastUpdate', 1);
});
await flushAsync();
expect(result!.resources()).toHaveLength(2);
expect(
result!.resources().find((resource) => resource.id === 'network-endpoint-stats-pv'),
).toEqual(
expect.objectContaining({
status: 'offline',
availability: expect.objectContaining({ available: false }),
}),
);
expect(
result!.resources().find((resource) => resource.id === 'agent-core2026')?.availabilityChecks,
).toHaveLength(1);
dispose();
});
it('keeps comma-separated type filters in the browser-encoded resource query shape', async () => {
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: 'type=agent,docker-host,app-container',
cacheKey: 'docker-overview-contract',
});
});
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(apiFetchMock).toHaveBeenNthCalledWith(
1,
'/api/resources?type=agent%2Cdocker-host%2Capp-container&page=1&limit=100',
{ cache: 'no-store' },
);
await waitForResourceCount(() => result!.resources().length);
dispose();
});
it('keeps source filters in the canonical resource request', async () => {
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: 'type=agent,vm,storage,network&source=vmware-vsphere',
cacheKey: 'vmware-overview-contract',
});
});
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(apiFetchMock).toHaveBeenNthCalledWith(
1,
'/api/resources?type=agent%2Cvm%2Cstorage%2Cnetwork&source=vmware-vsphere&page=1&limit=100',
{ cache: 'no-store' },
);
await waitForResourceCount(() => result!.resources().length);
dispose();
});
it('projects source-scoped queries from the canonical websocket snapshot', async () => {
const vmwareVM = createWsResource({
id: 'vmware-vm-1',
type: 'vm',
name: 'vmware-vm-1',
displayName: 'vmware-vm-1',
platformId: 'vmware-vm-1',
platformType: 'vmware-vsphere',
sourceType: 'api',
sources: ['vmware'],
});
const proxmoxVM = createWsResource({
id: 'proxmox-vm-1',
type: 'vm',
name: 'proxmox-vm-1',
displayName: 'proxmox-vm-1',
platformId: 'proxmox-vm-1',
platformType: 'proxmox-pve',
sourceType: 'api',
sources: ['proxmox'],
});
batch(() => {
setWsState('resources', [vmwareVM, proxmoxVM]);
setWsState('lastUpdate', 1738843200100);
setWsResourceChange({
version: 1738843200100,
changedIds: new Set([vmwareVM.id, proxmoxVM.id]),
});
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: 'type=agent,vm&source=vmware-vsphere',
cacheKey: 'vmware-websocket-projection',
initialHydration: 'prefer-ws',
});
});
await waitForValue(() => result!.resources().length, 1);
expect(result!.resources().map((resource) => resource.id)).toEqual(['vmware-vm-1']);
expect(apiFetchMock).not.toHaveBeenCalled();
dispose();
});
it('keeps unsupported source filters on the canonical REST fallback path', async () => {
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: 'source=future-provider',
cacheKey: 'unsupported-source-filter',
initialHydration: 'prefer-ws',
});
});
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
await waitForResourceCount(() => result!.resources().length);
dispose();
});
it('loads physical disks beyond the first resource page without dropping wide-node inventory', async () => {
const firstPage = Array.from({ length: 100 }, (_, index) => ({
...v2Resource,
id: `disk-${index + 1}`,
type: 'physical_disk',
name: `disk-${index + 1}`,
physicalDisk: {
devPath: `/dev/sd${index + 1}`,
serial: `SERIAL-${index + 1}`,
diskType: index === 0 ? 'nvme' : 'sas',
},
}));
const secondPage = Array.from({ length: 25 }, (_, index) => ({
...v2Resource,
id: `disk-${index + 101}`,
type: 'physical_disk',
name: `disk-${index + 101}`,
physicalDisk: {
devPath: `/dev/sg${index + 101}`,
serial: `SERIAL-${index + 101}`,
diskType: 'sas',
},
}));
apiFetchMock
.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ data: firstPage, meta: { totalPages: 2 } }),
})
.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ data: secondPage, meta: { totalPages: 2 } }),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: 'type=physical_disk',
cacheKey: 'issue-1516-wide-node',
});
});
await waitForResourceCount(() => result!.resources().length, 125);
expect(result!.resources()).toHaveLength(125);
expect(result!.resources().some((resource) => resource.id === 'disk-125')).toBe(true);
expect(apiFetchMock).toHaveBeenNthCalledWith(
2,
'/api/resources?type=physical_disk&page=2&limit=100',
{ cache: 'no-store' },
);
dispose();
});
it('requests the pages after the first concurrently instead of one round trip at a time', async () => {
const releasePage = new Map<number, () => void>();
const requestedPages: number[] = [];
apiFetchMock.mockImplementation((url: string) => {
const page = Number(new URLSearchParams(url.split('?')[1] ?? '').get('page') ?? '1');
requestedPages.push(page);
const response = {
ok: true,
status: 200,
json: async () => ({
data: [{ ...v2Resource, id: `resource-page-${page}`, name: `resource-page-${page}` }],
meta: { totalPages: 3 },
}),
};
if (page === 1) {
return Promise.resolve(response);
}
return new Promise((resolve) => {
releasePage.set(page, () => resolve(response));
});
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: 'type=vm',
cacheKey: 'first-paint-page-fanout',
});
});
for (let i = 0; i < 10 && requestedPages.length < 3; i += 1) {
await flushAsync();
}
// Walking the pages serially would still be blocked on page 2 here, so
// page 3 would not have been requested yet.
expect(requestedPages).toEqual([1, 2, 3]);
releasePage.get(2)?.();
releasePage.get(3)?.();
await waitForResourceCount(() => result!.resources().length, 3);
expect(result!.resources()).toHaveLength(3);
dispose();
});
it('does not hold the canonical fetch behind the websocket wait on prefer-ws-then-rest routes', async () => {
setWsConnected(false);
setWsInitialDataReceived(false);
setWsState('resources', []);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: 'type=vm',
cacheKey: 'prefer-ws-then-rest-no-wait',
initialHydration: 'prefer-ws-then-rest',
});
});
// No timer advance here on purpose: these routes revalidate over REST
// anyway, so the canonical fetch must not sit behind the hydration wait.
await flushAsync();
await flushAsync();
expect(apiFetchMock).toHaveBeenCalled();
await waitForResourceCount(() => result!.resources().length, 1);
expect(result!.loading()).toBe(false);
dispose();
});
it('still waits for the websocket snapshot on prefer-ws routes', async () => {
setWsConnected(false);
setWsInitialDataReceived(false);
setWsState('resources', []);
let dispose = () => {};
createRoot((d) => {
dispose = d;
useUnifiedResources({
query: '',
cacheKey: 'prefer-ws-still-waits',
initialHydration: 'prefer-ws',
});
});
await flushAsync();
await flushAsync();
expect(apiFetchMock).not.toHaveBeenCalled();
dispose();
});
it('prefers websocket initial hydration over an immediate REST fetch for dashboard snapshots', async () => {
setWsConnected(false);
setWsInitialDataReceived(false);
setWsState('resources', []);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: '',
cacheKey: 'all-resources',
initialHydration: 'prefer-ws',
});
});
await flushAsync();
expect(apiFetchMock).not.toHaveBeenCalled();
expect(result!.loading()).toBe(true);
batch(() => {
setWsConnected(true);
setWsState(
'resources',
reconcile(
[
createWsResource({ id: 'node-1', type: 'agent' }),
createWsResource({ id: 'storage-1', type: 'storage', name: 'storage-1' }),
],
{ key: 'id' },
),
);
setWsState('lastUpdate', 1738843202000);
setWsInitialDataReceived(true);
});
await waitForResourceCount(() => result!.resources().length, 2);
expect(apiFetchMock).not.toHaveBeenCalled();
expect(result!.loading()).toBe(false);
await vi.advanceTimersByTimeAsync(2_000);
expect(apiFetchMock).not.toHaveBeenCalled();
dispose();
});
it('uses an already-available websocket snapshot before the fallback REST timer for prefer-ws screens', async () => {
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: '',
cacheKey: 'all-resources',
initialHydration: 'prefer-ws',
});
});
await waitForResourceCount(() => result!.resources().length);
expect(result!.resources()[0]?.id).toBe(wsResource.id);
expect(result!.loading()).toBe(false);
expect(apiFetchMock).not.toHaveBeenCalled();
dispose();
});
it('applies inclusive and exclusive source filters to websocket hydration and updates', async () => {
const standaloneAgent = createWsResource({
id: 'standalone-agent',
name: 'standalone-agent',
displayName: 'standalone-agent',
platformId: 'standalone-agent',
sources: ['agent', 'docker'],
discoveryTarget: {
resourceType: 'agent',
agentId: 'standalone-agent',
resourceId: 'standalone-agent',
},
});
const providerAgent = createWsResource({
id: 'provider-agent',
name: 'provider-agent',
displayName: 'provider-agent',
platformId: 'provider-agent',
type: 'vm',
sources: ['agent', 'proxmox'],
discoveryTarget: {
resourceType: 'agent',
agentId: 'provider-agent',
resourceId: 'provider-agent',
},
});
const availabilityTarget = createWsResource({
id: 'availability-target',
name: 'availability-target',
displayName: 'availability-target',
type: 'network-endpoint',
platformType: 'availability',
sources: ['availability'],
});
setWsState('resources', [standaloneAgent, providerAgent, availabilityTarget]);
setWsResourceChange({ version: 1, changedIds: null });
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query:
'source=agent,availability&excludeSource=proxmox,kubernetes,truenas,vmware&type=agent,vm,network-endpoint',
cacheKey: 'standalone-excluded-source-projection',
initialHydration: 'prefer-ws',
});
});
await waitForValue(() => result!.resources().length, 2);
expect(result!.resources().map((resource) => resource.id)).toEqual([
'standalone-agent',
'availability-target',
]);
expect(apiFetchMock).not.toHaveBeenCalled();
batch(() => {
setWsState('resources', [
standaloneAgent,
providerAgent,
availabilityTarget,
createWsResource({
id: 'truenas-agent',
name: 'truenas-agent',
displayName: 'truenas-agent',
platformId: 'truenas-agent',
type: 'vm',
sources: ['agent', 'truenas'],
discoveryTarget: {
resourceType: 'agent',
agentId: 'truenas-agent',
resourceId: 'truenas-agent',
},
}),
]);
setWsResourceChange({ version: 2, changedIds: new Set(['truenas-agent']) });
setWsState('lastUpdate', 1738843205000);
});
await flushAsync();
expect(result!.resources().map((resource) => resource.id)).toEqual([
'standalone-agent',
'availability-target',
]);
dispose();
});
it('paints from websocket before revalidating prefer-ws-then-rest screens in the background', async () => {
let resolveFetch:
| ((value: { ok: true; json: () => Promise<{ data: Array<typeof v2Resource> }> }) => void)
| undefined;
apiFetchMock.mockImplementation(
() =>
new Promise((resolve) => {
resolveFetch = resolve;
}),
);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
initialHydration: 'prefer-ws-then-rest',
});
});
await waitForResourceCount(() => result!.resources().length);
await flushAsync();
expect(result!.resources()[0]?.id).toBe(wsResource.id);
expect(result!.loading()).toBe(false);
expect(apiFetchMock).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(15_250);
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
resolveFetch?.({
ok: true,
json: async () => ({ data: [{ ...v2Resource, name: 'node-rest' }] }),
});
await waitForValue(() => result!.resources()[0]?.displayName, 'node-rest');
expect(result!.loading()).toBe(false);
dispose();
});
it('revalidates a prefer-ws-then-rest screen seeded from a websocket-only cache on mount', async () => {
// In-app navigation onto a platform page: the all-resources cache is fed
// by the websocket alone, so the scoped route seeds from it and reads as
// fresh. Action readiness only arrives over REST, and a route that never
// fetched it offered Docker updates the server had already refused.
apiFetchMock.mockImplementation(() => new Promise(() => undefined));
let disposeAll = () => {};
let allResources: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
disposeAll = d;
allResources = useUnifiedResources({
query: '',
cacheKey: 'all-resources',
initialHydration: 'prefer-ws-then-rest',
});
});
await waitForResourceCount(() => allResources!.resources().length);
await flushAsync();
expect(apiFetchMock).not.toHaveBeenCalled();
disposeAll();
apiFetchMock.mockReset();
apiFetchMock.mockResolvedValue(
resourceResponse([
{
...v2Resource,
actionReadiness: [
{
name: 'update',
available: false,
reasonCode: 'command_agent_disconnected',
reason: 'Docker / Podman command agent is not connected.',
},
],
},
]),
);
let disposeScoped = () => {};
let scoped: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
disposeScoped = d;
scoped = useUnifiedResources({
query: 'type=agent',
cacheKey: 'seeded-platform-overview',
initialHydration: 'prefer-ws-then-rest',
});
});
await flushAsync();
expect(scoped!.resources()[0]?.id).toBe('node-1');
expect(apiFetchMock).toHaveBeenCalledTimes(1);
await waitForValue(() => scoped!.resources()[0]?.actionReadiness?.[0]?.name, 'update');
expect(scoped!.loading()).toBe(false);
disposeScoped();
});
it('waits for the first canonical REST snapshot before painting immediate hydration screens', async () => {
let resolveFetch:
| ((value: { ok: true; json: () => Promise<{ data: Array<typeof v2Resource> }> }) => void)
| undefined;
apiFetchMock.mockImplementation(
() =>
new Promise((resolve) => {
resolveFetch = resolve;
}),
);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(result!.loading()).toBe(true);
expect(result!.resources()).toHaveLength(0);
resolveFetch?.({
ok: true,
json: async () => ({ data: [v2Resource] }),
});
await waitForResourceCount(() => result!.resources().length);
await waitForValue(() => result!.loading(), false);
expect(result!.resources()[0]?.id).toBe(v2Resource.id);
expect(result!.resources()[0]?.displayName).toBe(v2Resource.name);
expect(result!.resources()[0]?.health).toEqual({ verdict: 'ok', reasons: [] });
dispose();
});
it('preserves backend platform scopes and falls back to source-derived membership', async () => {
apiFetchMock.mockResolvedValueOnce(
resourceResponse([
{
...v2Resource,
id: 'docker-container-frigate-141',
type: 'app-container',
name: 'frigate',
sources: ['docker'],
platformScopes: ['proxmox-pve', 'docker'],
docker: {
hostSourceId: 'proxmox-lxc-docker:pve-a:node-a:141',
containerId: 'frigate',
runtime: 'docker',
},
},
{
...v2Resource,
id: 'truenas-app-nextcloud',
type: 'app-container',
name: 'nextcloud',
sources: ['truenas'],
truenas: {
hostname: 'truenas-main',
app: {
id: 'nextcloud',
state: 'RUNNING',
usedPorts: [
{
containerPort: 443,
protocol: 'tcp',
hostPorts: [{ hostPort: 30443, hostIp: '0.0.0.0' }],
},
],
},
},
docker: {
containerId: 'nextcloud',
runtime: 'docker',
},
},
]),
);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await waitForValue(
() =>
Boolean(
result!.resources().find((resource) => resource.id === 'docker-container-frigate-141'),
),
true,
);
const dockerResource = result!
.resources()
.find((resource) => resource.id === 'docker-container-frigate-141');
const truenasResource = result!
.resources()
.find((resource) => resource.id === 'truenas-app-nextcloud');
expect(dockerResource?.platformScopes).toEqual(['proxmox-pve', 'docker']);
expect(dockerResource?.docker?.containerId).toBe('frigate');
expect((dockerResource?.platformData as Record<string, unknown>)?.platformScopes).toEqual([
'proxmox-pve',
'docker',
]);
expect(truenasResource?.platformScopes).toEqual(['truenas']);
expect(truenasResource?.truenas?.hostname).toBe('truenas-main');
expect(truenasResource?.truenas?.app?.usedPorts?.[0]?.hostPorts?.[0]?.hostPort).toBe(30443);
dispose();
});
it('skips unified resource hydration while disabled and resumes when enabled', async () => {
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
const [enabled, setEnabled] = createSignal(false);
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: '',
cacheKey: 'all-resources',
enabled,
});
});
await flushAsync();
expect(apiFetchMock).not.toHaveBeenCalled();
expect(result!.loading()).toBe(false);
setEnabled(true);
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
await waitForResourceCount(() => result!.resources().length);
dispose();
});
it('keeps a prefetched route inert until realtime updates are enabled', async () => {
const [realtimeEnabled, setRealtimeEnabled] = createSignal(false);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ realtimeEnabled });
});
await waitForResourceCount(() => result!.resources().length);
expect(result!.resources()[0]?.cpu?.current).toBe(15);
batch(() => {
setWsState(
'resources',
reconcile([createWsResource({ cpu: { current: 77 } })], { key: 'id' }),
);
setWsState('lastUpdate', 1738843204000);
});
await flushAsync();
expect(result!.resources()[0]?.cpu?.current).toBe(15);
setRealtimeEnabled(true);
await waitForValue(() => result!.resources()[0]?.cpu?.current, 77);
dispose();
});
it('falls back to REST when websocket initial hydration does not arrive in time', async () => {
setWsConnected(false);
setWsInitialDataReceived(false);
setWsState('resources', []);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: '',
cacheKey: 'all-resources',
initialHydration: 'prefer-ws',
});
});
await flushAsync();
expect(apiFetchMock).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1_250);
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(result!.resources().length).toBeGreaterThanOrEqual(1);
dispose();
});
it('projects kubernetes clusterId from the canonical context prefix', async () => {
apiFetchMock.mockResolvedValue({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
type: 'pod',
kubernetes: {
clusterName: 'cluster-a',
context: 'cluster-context',
clusterId: 'cluster-a-id',
podUid: 'pod-uid-1',
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ query: 'type=pod', cacheKey: 'pods' });
});
await result!.refetch();
expect(result!.resources()[0]?.clusterId).toBe('cluster-a');
dispose();
});
it('keeps an agent-plus-docker NAS out of the Proxmox table after API projection', async () => {
// #1930's supplied field shape, with entirely synthetic identities and no
// addresses or token metadata. This does not reproduce the earlier screenshot.
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
id: 'synthetic-nas',
name: 'synthetic-nas',
technology: 'linux',
sources: ['agent', 'docker'],
platformScopes: ['agent', 'docker'],
canonicalIdentity: { displayName: 'synthetic-nas', platformId: 'synthetic-nas' },
identity: { hostnames: ['synthetic-nas'] },
agent: { platform: 'linux', osName: 'Synology DSM' },
},
{
...v2Resource,
id: 'synthetic-pve',
sources: ['proxmox'],
proxmox: { nodeName: 'synthetic-pve', clusterName: 'synthetic-cluster' },
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ query: 'type=agent', cacheKey: 'nas-boundary' });
});
try {
await result!.refetch();
const resources = result!.resources();
const nas = resources.find((resource) => resource.id === 'synthetic-nas');
expect(nas).toBeDefined();
expect(nas?.clusterId).toBeUndefined();
expect(nas?.proxmox).toBeUndefined();
expect(buildProxmoxPageModel(resources).pveNodes.map((node) => node.id)).toEqual([
'synthetic-pve',
]);
} finally {
dispose();
}
});
it('projects proxmox clusterId from the shared cluster helper', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
type: 'vm',
proxmox: {
sourceId: 'site-a:pve1',
runtimeStatus: 'running',
nodeName: 'pve1',
clusterName: 'cluster-b',
instance: 'site-a',
host: 'https://pve1.example:8006',
guestUrl: 'https://console.example/pve1',
connectionHealth: 'error',
pveVersion: '8.4.1',
kernelVersion: '6.8.12-10-pve',
uptime: 86_400,
lastBackup: '2026-02-06T06:00:00Z',
backupInProgress: true,
osName: 'Debian GNU/Linux',
osVersion: '13',
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ query: 'type=vm', cacheKey: 'vms' });
});
await result!.refetch();
expect(result!.resources()[0]?.clusterId).toBe('cluster-b');
expect(result!.resources()[0]?.proxmox).toMatchObject({
sourceId: 'site-a:pve1',
node: 'pve1',
nodeName: 'pve1',
clusterName: 'cluster-b',
instance: 'site-a',
host: 'https://pve1.example:8006',
guestUrl: 'https://console.example/pve1',
connectionHealth: 'error',
pveVersion: '8.4.1',
kernelVersion: '6.8.12-10-pve',
runtimeStatus: 'running',
uptime: 86_400,
lastBackup: '2026-02-06T06:00:00Z',
backupInProgress: true,
osName: 'Debian GNU/Linux',
osVersion: '13',
});
expect(result!.resources()[0]?.uptime).toBe(86_400);
dispose();
});
it('does not invent standalone cluster ids from resource names', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
id: 'docker-host-1',
type: 'docker-host',
name: 'Ops Services 01',
canonicalIdentity: {
displayName: 'Ops Services 01',
hostname: 'ops-services-01',
platformId: 'ops-services-01',
},
sources: ['docker'],
identity: {
hostnames: ['ops-services-01'],
},
docker: {
hostSourceId: 'orion-2-mock',
hostname: 'ops-services-01',
runtime: 'docker',
runtimeVersion: '27.3.1',
dockerVersion: '27.3.1',
os: 'Alpine Linux 3.19',
kernelVersion: '6.6.32-1-lts',
architecture: 'aarch64',
agentVersion: '0.1.0-dev',
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
expect(result!.resources()[0]?.clusterId).toBeUndefined();
dispose();
});
it('preserves an observed zero without inventing its absent I/O direction', async () => {
setWsConnected(false);
setWsInitialDataReceived(false);
setWsState('resources', []);
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({ data: [{ ...v2Resource, metrics: { diskRead: { value: 0 } } }] }),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
expect(result!.resources()[0]?.diskIO).toEqual({ readRate: 0, writeRate: undefined });
dispose();
});
it('preserves richer REST resource details across thinner websocket updates', async () => {
setWsConnected(false);
setWsInitialDataReceived(false);
setWsState('resources', []);
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
metrics: {
...v2Resource.metrics,
diskRead: { value: 1_250_000 },
diskWrite: { value: 640_000 },
},
},
{
id: 'pbs-1',
type: 'pbs',
name: 'backup-vault',
status: 'online',
lastSeen: '2026-02-06T12:00:00Z',
sources: ['pbs'],
canonicalIdentity: {
displayName: 'backup-vault',
hostname: 'backup-vault',
platformId: '198.51.100.10',
},
metrics: {
cpu: { percent: 9 },
memory: { used: 6 * 1024 * 1024, total: 16 * 1024 * 1024, percent: 36 },
},
pbs: {
instanceId: 'pbs-main',
hostname: '198.51.100.10',
version: '3.2.1',
datastoreCount: 2,
backupJobCount: 4,
connectionHealth: 'healthy',
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
expect(result!.resources().find((resource) => resource.id === 'node-1')?.diskIO).toEqual({
readRate: 1_250_000,
writeRate: 640_000,
});
expect(
result!.resources().find((resource) => resource.id === 'pbs-1')?.platformData?.pbs,
).toEqual(
expect.objectContaining({
datastoreCount: 2,
backupJobCount: 4,
connectionHealth: 'healthy',
}),
);
batch(() => {
setWsState(
'resources',
reconcile(
[
createWsResource({
cpu: { current: 42 },
}),
createThinWsPBSResource(),
],
{ key: 'id' },
),
);
setWsState('lastUpdate', 1738843203000);
setWsConnected(true);
setWsInitialDataReceived(true);
});
await flushAsync();
expect(result!.resources().find((resource) => resource.id === 'node-1')?.cpu?.current).toBe(42);
expect(result!.resources().find((resource) => resource.id === 'node-1')?.diskIO).toEqual({
readRate: 1_250_000,
writeRate: 640_000,
});
expect(
result!.resources().find((resource) => resource.id === 'pbs-1')?.platformData?.pbs,
).toEqual(
expect.objectContaining({
datastoreCount: 2,
backupJobCount: 4,
connectionHealth: 'healthy',
}),
);
dispose();
});
it('keeps PMG metadata on the canonical resource for REST-first paints', async () => {
// The Mail Gateway table reads `resource.pmg`. The mapper used to keep it
// only under platformData, so a REST-sourced row rendered every PMG column
// as a dash until a websocket row happened to replace it.
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
id: 'pmg-1',
type: 'pmg',
name: 'mail-gateway-eu',
status: 'online',
lastSeen: '2026-02-06T12:00:00Z',
sources: ['pmg'],
uptime: 1_555_222,
technology: 'pmg',
sourceStatus: { pmg: { status: 'online', lastSeen: '2026-02-06T12:00:00Z' } },
actionReadiness: [{ name: 'restart', available: true }],
pmg: {
instanceId: 'pmg-eu',
hostname: 'pmg.example.lan',
version: '8.1-2',
nodeCount: 1,
mailCountTotal: 2_740,
spamIn: 321,
virusIn: 14,
queueTotal: 11,
queueDeferred: 5,
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ query: 'type=pmg&source=pmg', cacheKey: 'pmg-first-paint' });
});
await result!.refetch();
const row = result!.resources().find((resource) => resource.id === 'pmg-1');
expect(row?.pmg).toEqual(
expect.objectContaining({ version: '8.1-2', spamIn: 321, queueDeferred: 5 }),
);
expect(row?.platformData?.pmg).toEqual(row?.pmg);
// The per-source status, action readiness, and technology facets ride the
// same race: Docker lifecycle actions and storage freshness read them at
// the top level, where only websocket rows used to carry them.
expect(row?.sourceStatus?.pmg?.status).toBe('online');
expect(row?.actionReadiness?.[0]?.name).toBe('restart');
expect(row?.technology).toBe('pmg');
dispose();
});
it.each([
{
label: 'stale inventory',
sourceStatus: { docker: { status: 'stale', lastSeen: '2026-02-06T12:00:00Z' } },
actionReadiness: [],
expected: 'Docker inventory is stale. Refresh inventory before running lifecycle actions.',
},
{
label: 'failed inventory',
sourceStatus: {
docker: { status: 'online', lastSeen: '2026-02-06T12:00:00Z', error: 'Collector refused' },
},
actionReadiness: [],
expected: 'Docker inventory is not healthy: Collector refused',
},
{
label: 'server action refusal',
sourceStatus: { docker: { status: 'online', lastSeen: '2026-02-06T12:00:00Z' } },
actionReadiness: [
{ name: 'restart', available: false, reason: 'Command agent disconnected' },
],
expected: 'Command agent disconnected',
},
{
label: 'no invented action grant',
sourceStatus: { docker: { status: 'online', lastSeen: '2026-02-06T12:00:00Z' } },
actionReadiness: [],
expected:
'Pulse does not currently advertise a fresh restart command capability for this container.',
},
])('preserves $label through REST mapping into lifecycle controls', async (testCase) => {
apiFetchMock.mockResolvedValue(
resourceResponse([
{
id: 'docker-container-1',
type: 'app-container',
name: 'edge-web',
status: 'running',
lastSeen: '2026-02-06T12:00:00Z',
sources: ['docker'],
technology: 'docker',
docker: { runtime: 'docker', agentId: 'agent-edge', containerState: 'running' },
sourceStatus: testCase.sourceStatus,
actionReadiness: testCase.actionReadiness,
},
]),
);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ query: 'type=app-container', cacheKey: testCase.label });
});
try {
await result!.refetch();
const row = result!.resources()[0];
expect(row.sourceStatus).toEqual(testCase.sourceStatus);
expect(row.actionReadiness).toEqual(testCase.actionReadiness);
expect(row.technology).toBe('docker');
expect(getDockerContainerLifecycleDisabledReason(row, 'restart')).toBe(testCase.expected);
} finally {
dispose();
}
});
it('replaces REST facets without retaining a removed PMG counter or action refusal', async () => {
const base = {
id: 'pmg-1',
type: 'pmg',
name: 'mail-gateway',
status: 'online',
sources: ['pmg'],
lastSeen: '2026-02-06T12:00:00Z',
};
apiFetchMock.mockResolvedValue(
resourceResponse([
{
...base,
technology: 'pmg',
pmg: { version: '8.1-2', queueTotal: 11 },
sourceStatus: { pmg: { status: 'stale', lastSeen: base.lastSeen } },
actionReadiness: [{ name: 'restart', available: false, reason: 'Old refusal' }],
},
]),
);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ query: 'type=pmg', cacheKey: 'removed-rest-facets' });
});
try {
await result!.refetch();
expect(result!.resources()[0].pmg?.queueTotal).toBe(11);
apiFetchMock.mockResolvedValue(
resourceResponse([{ ...base, actionReadiness: [], sourceStatus: {} }]),
);
await result!.refetch();
const row = result!.resources()[0];
expect(row.pmg).toBeUndefined();
expect(row.platformData?.pmg).toBeUndefined();
expect(row.actionReadiness).toEqual([]);
expect(row.sourceStatus).toEqual({});
expect(row.technology).toBeUndefined();
} finally {
dispose();
}
});
it('falls back to canonical resource.uptime when no platform-specific field is set (vSphere)', async () => {
// vSphere ESXi hosts and VMs populate only the canonical
// Resource.Uptime field — there's no vmware-specific UptimeSeconds
// carve-out. The toResource mapping must land on v2.uptime so the
// unified-resources contract surfaces uptime for VMware-backed rows.
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
sources: ['vmware'],
agent: undefined,
proxmox: undefined,
uptime: 9876543,
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ query: 'type=agent', cacheKey: 'vsphere-host-uptime' });
});
await result!.refetch();
expect(result!.resources()[0]?.uptime).toBe(9876543);
dispose();
});
it('projects Proxmox node network interfaces into the resource facet', async () => {
apiFetchMock.mockResolvedValue(
resourceResponse([
{
...v2Resource,
sources: ['proxmox'],
proxmox: {
nodeName: 'pve1',
networkInterfaces: [
{ name: 'eno1', addresses: [] },
{
name: 'vmbr0',
addresses: ['192.168.10.21/24', 'fd42:7065:6c73::21/64'],
},
],
},
},
]),
);
let result: ReturnType<typeof useUnifiedResources> | undefined;
createRoot((dispose) => {
result = useUnifiedResources();
void dispose;
});
await waitForResourceCount(() => result?.resources().length ?? 0);
expect(result!.resources()[0]?.proxmox?.networkInterfaces).toEqual([
{ name: 'eno1', addresses: [] },
{
name: 'vmbr0',
addresses: ['192.168.10.21/24', 'fd42:7065:6c73::21/64'],
},
]);
});
it('falls back to proxmox temperature when agent temperature is unavailable', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
sources: ['proxmox'],
agent: undefined,
proxmox: {
nodeName: 'pve1',
clusterName: 'mock-cluster',
uptime: 1234,
temperature: 58.4,
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ query: 'type=k8s-deployment', cacheKey: 'k8s-deployments' });
});
await result!.refetch();
expect(result!.resources()[0].temperature).toBe(58.4);
dispose();
});
it('passes the proxmox temperature payload and sensor setup verdict through', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
sources: ['proxmox'],
agent: undefined,
proxmox: {
nodeName: 'pve1',
temperature: 58.4,
temperatureDetails: { available: true, legacySensorsFormat: true },
sensorSetupOutdated: true,
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ query: 'type=k8s-deployment', cacheKey: 'k8s-deployments' });
});
await result!.refetch();
expect(result!.resources()[0].proxmox?.temperatureDetails).toEqual({
available: true,
legacySensorsFormat: true,
});
// The outdated sensor setup notice reads the registry's verdict on the
// node, so it must survive the projection that rows on every tab go through.
expect(result!.resources()[0].proxmox?.sensorSetupOutdated).toBe(true);
dispose();
});
it('projects raw VMware sources onto the canonical vSphere platform model', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
id: 'vmware-host-1',
name: 'esxi-01.lab.local',
sources: ['vmware'],
canonicalIdentity: {
displayName: 'ESXi 01',
hostname: 'esxi-01.lab.local',
platformId: 'vmware-host-1',
},
vmware: {
connectionId: 'vc-1',
connectionName: 'Lab VC',
vCenterHost: 'vc.lab.local',
managedObjectId: 'host-101',
entityType: 'host',
datacenterName: 'DC1',
clusterName: 'Compute-A',
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
expect(result!.resources()[0].platformType).toBe('vmware-vsphere');
expect(result!.resources()[0].sourceType).toBe('api');
// Owning-snapshot consumers read the canonical source list directly.
expect(result!.resources()[0].sources).toEqual(['vmware']);
expect(result!.resources()[0].platformData?.sources).toEqual(['vmware']);
expect(result!.resources()[0].vmware).toMatchObject({
connectionId: 'vc-1',
managedObjectId: 'host-101',
entityType: 'host',
datacenterName: 'DC1',
clusterName: 'Compute-A',
});
dispose();
});
it('projects availability endpoints onto the availability platform model', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
id: 'endpoint-1',
type: 'network-endpoint',
name: 'MQTT power meter',
sources: ['availability'],
availability: {
targetId: 'mock-availability-mqtt-meter',
protocol: 'tcp',
address: 'power-meter-01.lab.local',
port: 1883,
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
expect(result!.resources()[0].type).toBe('network-endpoint');
expect(result!.resources()[0].platformType).toBe('availability');
expect(result!.resources()[0].sourceType).toBe('api');
expect(result!.resources()[0].platformData?.availability).toMatchObject({
protocol: 'tcp',
address: 'power-meter-01.lab.local',
port: 1883,
});
dispose();
});
it('maps discoveryTarget.agentId into canonical discovery agentId', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
discoveryTarget: {
resourceType: 'agent',
agentId: 'agent-discovery-1',
resourceId: 'agent-discovery-1',
hostname: 'pve1',
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
expect(result!.resources()[0].discoveryTarget).toEqual({
resourceType: 'agent',
agentId: 'agent-discovery-1',
resourceId: 'agent-discovery-1',
hostname: 'pve1',
});
dispose();
});
it('passes canonical policy metadata and aiSafeSummary through unchanged', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
policy: {
sensitivity: 'restricted',
routing: {
scope: 'local-only',
redact: ['hostname', 'ip-address', 'platform-id', 'alias'],
},
},
aiSafeSummary: 'resource summary safe for remote AI use',
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
expect(result!.resources()[0].policy).toEqual({
sensitivity: 'restricted',
routing: {
scope: 'local-only',
redact: ['hostname', 'ip-address', 'platform-id', 'alias'],
},
});
expect(result!.resources()[0].aiSafeSummary).toBe('resource summary safe for remote AI use');
dispose();
});
it('passes resource policy posture aggregations through unchanged', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [v2Resource],
aggregations: {
policyPosture: {
totalResources: 3,
sensitivityCounts: {
restricted: 1,
sensitive: 2,
},
routingCounts: {
'local-only': 1,
'local-first': 2,
},
redactionCounts: {
hostname: 1,
'ip-address': 1,
},
},
},
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await waitForValue(() => result!.policyPosture()?.totalResources, 3);
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(result!.policyPosture()).toEqual({
totalResources: 3,
sensitivityCounts: {
restricted: 1,
sensitive: 2,
},
routingCounts: {
'local-only': 1,
'local-first': 2,
},
redactionCounts: {
hostname: 1,
'ip-address': 1,
},
});
dispose();
});
it('normalizes global resource counts for evidence-gated platform tabs', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [v2Resource],
aggregations: {
total: 42,
byType: {
agent: 5,
vm: 20,
'system-container': 17,
},
},
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await waitForValue(() => result!.aggregations()?.total, 42);
expect(result!.aggregations()).toEqual({
total: 42,
byType: {
agent: 5,
vm: 20,
'system-container': 17,
},
});
dispose();
});
it('normalizes source-scoped type and incident facets for route navigation', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [v2Resource],
facets: {
byType: {
agent: 1,
vm: 18,
storage: 3,
},
incidentCount: 4,
},
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: 'type=agent,vm&source=vmware-vsphere',
cacheKey: 'vmware-overview-facets',
});
});
await waitForValue(() => result!.facets()?.incidentCount, 4);
expect(result!.facets()).toEqual({
byType: {
agent: 1,
vm: 18,
storage: 3,
},
incidentCount: 4,
});
dispose();
});
it('normalizes legacy k8s discovery targets to pod for frontend consumers', async () => {
apiFetchMock.mockResolvedValue({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
type: 'pod',
discoveryTarget: {
resourceType: 'k8s',
agentId: 'cluster-agent-1',
resourceId: 'pod/default/nginx',
hostname: 'cluster-a',
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ query: 'type=pod', cacheKey: 'pods' });
});
await result!.refetch();
expect(result!.resources()[0].discoveryTarget).toEqual({
resourceType: 'pod',
agentId: 'cluster-agent-1',
resourceId: 'pod/default/nginx',
hostname: 'cluster-a',
});
dispose();
});
it('preserves canonical node metrics targets at the API load boundary', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
metricsTarget: {
resourceType: 'node',
resourceId: 'pve-node-1',
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
expect(result!.resources()[0].metricsTarget).toEqual({
resourceType: 'node',
resourceId: 'pve-node-1',
});
dispose();
});
it('preserves kubernetes deployment metrics targets at the API load boundary', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
type: 'k8s-deployment',
metricsTarget: {
resourceType: 'k8s-deployment',
resourceId: 'cluster-1:deployment:default/api',
},
},
],
}),
});
setWsInitialDataReceived(false);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
await waitForResourceCount(() => result!.resources().length);
expect(result!.resources()[0].metricsTarget).toEqual({
resourceType: 'k8s-deployment',
resourceId: 'cluster-1:deployment:default/api',
});
dispose();
});
it('derives normalized platformId through the shared identity helper precedence', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
id: 'docker-runtime-1',
type: 'agent',
name: 'fallback-name',
proxmox: undefined,
agent: { hostname: 'agent-host.local' },
docker: { hostname: 'docker-host.local' },
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
expect(result!.resources()[0].platformId).toBe('agent-host.local');
dispose();
});
it('prefers backend canonical identity fields over frontend fallback inference', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
id: 'hybrid-host-1',
name: 'fallback-name',
identity: {
hostnames: ['legacy-host.local'],
},
proxmox: { nodeName: 'legacy-node' },
canonicalIdentity: {
displayName: 'Tower',
hostname: 'tower.local',
platformId: 'pve1',
primaryId: 'node:instance-pve1',
aliases: ['node:instance-pve1', 'instance-pve1', 'tower.local'],
supersededIds: ['agent-retired'],
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
expect(result!.resources()[0].name).toBe('Tower');
expect(result!.resources()[0].displayName).toBe('Tower');
expect(result!.resources()[0].platformId).toBe('pve1');
expect(result!.resources()[0].identity?.hostname).toBe('tower.local');
expect(result!.resources()[0].canonicalIdentity).toMatchObject({
primaryId: 'node:instance-pve1',
hostname: 'tower.local',
supersededIds: ['agent-retired'],
});
dispose();
});
it('preserves parentName from backend resources', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
id: 'storage-1',
type: 'storage',
name: 'local-zfs',
parentId: 'agent-123',
parentName: 'pve1',
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ query: 'type=storage' });
});
await result!.refetch();
expect(result!.resources()[0].parentId).toBe('agent-123');
expect(result!.resources()[0].parentName).toBe('pve1');
dispose();
});
it('uses backend resources as canonical infrastructure state even with non-canonical websocket fields', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
id: 'k8s-cluster-native',
type: 'k8s-cluster',
name: 'cluster-a',
status: 'online',
lastSeen: '2026-02-06T12:00:00Z',
sources: ['kubernetes'],
},
{
id: 'k8s-node-native',
type: 'k8s-node',
name: 'worker-1',
status: 'online',
lastSeen: '2026-02-06T12:00:00Z',
parentId: 'k8s-cluster-native',
sources: ['kubernetes'],
},
],
}),
});
batch(() => {
setWsState('legacy_clusters', [
{
id: 'legacy-cluster',
name: 'legacy-cluster',
hidden: false,
status: 'online',
lastSeen: 1738929600000,
nodes: [{ uid: 'legacy-node', name: 'legacy-node', ready: true }],
},
]);
setWsState('lastUpdate', 1738843202000);
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
const resources = result!.resources();
expect(resources).toHaveLength(2);
expect(resources.map((resource) => resource.id)).toEqual([
'k8s-cluster-native',
'k8s-node-native',
]);
dispose();
});
it('ignores non-canonical websocket payload fields for infrastructure resources', async () => {
batch(() => {
setWsState('legacy_hosts', [
{ id: 'legacy-host-1', hostname: 'legacy-host', status: 'online', lastSeen: 1738929600000 },
]);
setWsState('legacy_docker_hosts', [
{
id: 'legacy-docker-1',
hostname: 'legacy-docker',
status: 'online',
lastSeen: 1738929600000,
},
]);
setWsState('legacy_pbs', [{ id: 'legacy-pbs-1', name: 'legacy-pbs' }]);
setWsState('legacy_pmg', [{ id: 'legacy-pmg-1', name: 'legacy-pmg' }]);
setWsState('lastUpdate', 1738843204000);
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await result!.refetch();
const resources = result!.resources();
expect(resources).toHaveLength(1);
expect(resources[0].id).toBe('node-1');
expect(resources[0].type).toBe('agent');
dispose();
});
it('reuses fresh cache on remount without an extra network fetch', async () => {
let disposeFirst = () => {};
let first: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
disposeFirst = d;
first = useUnifiedResources({ query: '', cacheKey: 'all-resources' });
});
await flushAsync();
await waitForResourceCount(() => first!.resources().length);
expect(apiFetchMock).toHaveBeenCalledTimes(1);
await flushAsync();
await flushAsync();
disposeFirst();
let disposeSecond = () => {};
let second: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
disposeSecond = d;
second = useUnifiedResources({ query: '', cacheKey: 'all-resources' });
});
await waitForResourceCount(() => second!.resources().length);
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(second!.resources().length).toBeGreaterThan(0);
disposeSecond();
});
it('seeds a narrower type-filtered cache from a fresh all-resources snapshot', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
v2Resource,
{
...v2Resource,
id: 'storage-1',
type: 'storage',
name: 'tank',
},
],
}),
});
let disposeAll = () => {};
let allResources: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
disposeAll = d;
allResources = useUnifiedResources({ query: '', cacheKey: 'all-resources' });
});
await flushAsync();
await waitForResourceCount(() => allResources!.resources().length, 2);
expect(apiFetchMock).toHaveBeenCalledTimes(1);
batch(() => {
setWsState('resources', [
wsResource,
createWsResource({
id: 'disk-1',
type: 'physical_disk',
name: 'nvme0n1',
displayName: 'nvme0n1',
platformId: 'disk-1',
}),
]);
setWsState('lastUpdate', 1738843202500);
});
await flushAsync();
disposeAll();
let disposeFiltered = () => {};
let filtered: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
disposeFiltered = d;
filtered = useUnifiedResources();
});
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(filtered!.loading()).toBe(false);
expect(filtered!.resources().map((resource) => resource.id)).toEqual(['node-1']);
disposeFiltered();
});
it('seeds a physical-disk filtered cache from a fresh all-resources snapshot', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
v2Resource,
{
...v2Resource,
id: 'disk-1',
type: 'physical_disk',
name: 'nvme0n1',
},
],
}),
});
let disposeAll = () => {};
let allResources: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
disposeAll = d;
allResources = useUnifiedResources({ query: '', cacheKey: 'all-resources' });
});
await flushAsync();
await waitForResourceCount(() => allResources!.resources().length, 2);
expect(apiFetchMock).toHaveBeenCalledTimes(1);
batch(() => {
setWsState('resources', [
wsResource,
createWsResource({
id: 'disk-1',
type: 'physical_disk',
name: 'nvme0n1',
displayName: 'nvme0n1',
platformId: 'disk-1',
}),
]);
setWsState('lastUpdate', 1738843202501);
});
await flushAsync();
await flushAsync();
disposeAll();
let disposeFiltered = () => {};
let filtered: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
disposeFiltered = d;
filtered = useUnifiedResources({ query: 'type=physical_disk' });
});
await waitForValue(() => filtered!.resources().length, 1);
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(filtered!.loading()).toBe(false);
expect(filtered!.resources().map((resource) => resource.id)).toEqual(['disk-1']);
disposeFiltered();
});
it('treats an empty fresh snapshot as cacheable on remount', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({ data: [] }),
});
batch(() => {
setWsState('resources', []);
setWsState('lastUpdate', 1738843202600);
});
let disposeFirst = () => {};
let first: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
disposeFirst = d;
first = useUnifiedResources();
});
await flushAsync();
await waitForValue(() => first!.loading(), false);
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(first!.resources()).toEqual([]);
disposeFirst();
let disposeSecond = () => {};
let second: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
disposeSecond = d;
second = useUnifiedResources();
});
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(second!.loading()).toBe(false);
expect(second!.resources()).toEqual([]);
disposeSecond();
});
it('coalesces burst websocket updates into a single delayed refetch for unsupported queries', async () => {
let dispose = () => {};
createRoot((d) => {
dispose = d;
useUnifiedResources({ query: 'status=online', cacheKey: 'status-online' });
});
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
setWsState('lastUpdate', 1738843201000);
await flushAsync();
vi.advanceTimersByTime(100);
setWsState('lastUpdate', 1738843202000);
await flushAsync();
vi.advanceTimersByTime(100);
setWsState('lastUpdate', 1738843203000);
await flushAsync();
vi.advanceTimersByTime(2_500);
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(2);
vi.advanceTimersByTime(2_500);
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(2);
dispose();
});
it('replaces stale canonical resources through fallback refetches for unsupported queries', async () => {
apiFetchMock
.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
id: 'agent-old',
name: 'seeded-agent-old',
},
],
}),
})
.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
id: 'agent-new',
name: 'seeded-agent-new',
lastSeen: '2026-02-06T12:01:00Z',
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({ query: 'status=online', cacheKey: 'status-online' });
});
await flushAsync();
await waitForResourceCount(() => result!.resources().length);
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(result!.resources()[0]?.id).toBe('agent-old');
expect(result!.resources()[0]?.name).toBe('seeded-agent-old');
setWsState('lastUpdate', 1738843209000);
await flushAsync();
vi.advanceTimersByTime(2_500);
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(2);
await waitForValue(() => result!.resources()[0]?.id, 'agent-new');
expect(result!.resources()[0]?.id).toBe('agent-new');
expect(result!.resources()[0]?.name).toBe('seeded-agent-new');
dispose();
});
it('uses the storage/recovery query variant for storage pages', async () => {
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useStorageRecoveryResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useStorageRecoveryResources();
});
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(apiFetchMock).toHaveBeenNthCalledWith(
1,
'/api/resources?type=storage%2Cpbs%2Cpmg%2Cvm%2Csystem-container%2Cpod%2Cagent%2Ck8s-cluster%2Ck8s-node%2Cphysical_disk%2Cceph&page=1&limit=100',
{ cache: 'no-store' },
);
expect(result!.resources().length).toBeGreaterThanOrEqual(0);
dispose();
});
it('normalizes legacy truenas resources to canonical agent records at ingest', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
id: 'truenas-main',
type: 'truenas',
name: 'truenas-main',
sources: ['agent', 'truenas'],
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await waitForValue(() => result!.resources()[0]?.platformType, 'truenas');
expect(result!.resources()[0]?.type).toBe('agent');
expect(result!.resources()[0]?.platformType).toBe('truenas');
dispose();
});
it('preserves native TrueNAS network-share resources at ingest', async () => {
apiFetchMock.mockResolvedValueOnce(
resourceResponse([
{
...v2Resource,
id: 'share-smb-media',
type: 'network-share',
name: 'Media',
status: 'online',
sources: ['truenas'],
parentName: 'tank/media',
truenas: {
hostname: 'truenas-main',
share: {
id: 'smb-1',
name: 'Media',
protocol: 'SMB',
path: '/mnt/tank/media',
dataset: 'tank/media',
enabled: true,
readOnly: false,
},
},
},
]),
);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources({
query: 'type=network-share',
cacheKey: 'network-share-ingest-test',
initialHydration: 'immediate',
});
});
await waitForValue(() => result!.resources()[0]?.type, 'network-share');
expect(result!.resources()[0]?.platformType).toBe('truenas');
expect(result!.resources()[0]?.truenas?.share?.dataset).toBe('tank/media');
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',
},
],
facetCounts: {
recentChanges: 1,
},
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await waitForValue(() => result!.resources()[0]?.recentChanges?.[0]?.id, 'change-1');
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',
},
]);
expect(result!.resources()[0]?.facetCounts).toEqual({
recentChanges: 1,
});
dispose();
});
it('filters malformed source entries from backend payloads', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
sources: ['agent', 42, null, { bad: true }, 'proxmox'],
},
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await waitForValue(() => result!.resources()[0]?.platformType, 'proxmox-pve');
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(result!.resources()[0]?.id).toBe('node-1');
expect(result!.resources()[0]?.platformType).toBe('proxmox-pve');
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{
...v2Resource,
id: 'node-2',
name: 'node-2',
},
],
}),
});
eventBus.emit('org_switched', 'tenant-b');
await waitForValue(() => result!.resources()[0]?.id, 'node-2');
expect(apiFetchMock).toHaveBeenCalledTimes(2);
expect(result!.resources()[0]?.id).toBe('node-2');
eventBus.emit('org_switched', 'default');
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(2);
expect(result!.resources()[0]?.id).toBe('node-1');
dispose();
});
it('ignores stale refetch errors and keeps the active scope request guard', async () => {
const staleDefaultRequest = deferred<ReturnType<typeof resourceResponse>>();
const activeTenantRequest = deferred<ReturnType<typeof resourceResponse>>();
apiFetchMock
.mockImplementationOnce(() => staleDefaultRequest.promise)
.mockImplementationOnce(() => activeTenantRequest.promise);
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(result!.loading()).toBe(true);
eventBus.emit('org_switched', 'tenant-b');
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(2);
staleDefaultRequest.reject(new Error('stale default-scope refresh failed'));
await flushAsync();
expect(result!.error()).toBeUndefined();
expect(result!.loading()).toBe(true);
void result!.refetch().catch(() => undefined);
await flushAsync();
expect(apiFetchMock).toHaveBeenCalledTimes(2);
activeTenantRequest.resolve(
resourceResponse([
{
...v2Resource,
id: 'tenant-node',
name: 'tenant-node',
},
]),
);
await waitForValue(() => result!.resources()[0]?.id, 'tenant-node');
expect(result!.error()).toBeUndefined();
expect(result!.loading()).toBe(false);
dispose();
});
it('normalizes proxmox service aliases into canonical platform types', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: [
{ ...v2Resource, id: 'pve-1', name: 'pve-1', sources: ['proxmox'] },
{ ...v2Resource, id: 'pbs-1', name: 'pbs-1', sources: ['pbs'] },
{ ...v2Resource, id: 'pmg-1', name: 'pmg-1', sources: ['pmg'] },
],
}),
});
let dispose = () => {};
let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
createRoot((d) => {
dispose = d;
result = useUnifiedResources();
});
await flushAsync();
await waitForResourceCount(() => result!.resources().length, 3);
const byId = new Map(result!.resources().map((resource) => [resource.id, resource]));
expect(byId.get('pve-1')?.platformType).toBe('proxmox-pve');
expect(byId.get('pbs-1')?.platformType).toBe('proxmox-pbs');
expect(byId.get('pmg-1')?.platformType).toBe('proxmox-pmg');
dispose();
});
it('keeps picker read failures through the useResources adapter and cached remounts', async () => {
const { useResources } = await import('../useResources');
setWsConnected(false);
setWsInitialDataReceived(false);
setWsState('resources', []);
const disposals: (() => void)[] = [];
const mount = (retainReadError = true) => {
let result!: ReturnType<typeof useResources>;
createRoot((dispose) => {
disposals.push(dispose);
result = useResources(undefined, { retainReadError });
});
return result;
};
try {
const first = mount();
await waitForResourceCount(() => first.resources().length);
const failure = new Error('canonical picker inventory unavailable');
apiFetchMock.mockRejectedValueOnce(failure);
await expect(first.refetch()).rejects.toBe(failure);
expect(first.error()).toBe(failure);
expect(first.resources()).toHaveLength(1);
disposals.shift()!();
const calls = apiFetchMock.mock.calls.length;
const reopened = mount();
const defaultConsumer = mount(false);
await flushAsync();
expect(reopened.error()).toBe(failure);
expect(defaultConsumer.error()).toBeUndefined();
expect(apiFetchMock).toHaveBeenCalledTimes(calls);
apiFetchMock.mockResolvedValueOnce(resourceResponse([]));
await reopened.refetch();
expect(reopened.error()).toBeUndefined();
expect(reopened.loading()).toBe(false);
expect(reopened.resources()).toHaveLength(0);
} finally {
disposals.forEach((dispose) => dispose());
}
});
it.each(['update', 'reconnect', 'remount'] as const)(
'keeps picker canonical denial through websocket %s until explicit recovery',
async (delivery) => {
const { useResources } = await import('../useResources');
const disposals: (() => void)[] = [];
const mount = () => {
let result!: ReturnType<typeof useResources>;
createRoot((dispose) => {
disposals.push(dispose);
result = useResources(undefined, { retainReadError: true });
});
return result;
};
const publish = (version: number, cpu: number) => {
batch(() => {
setWsState('resources', reconcile([createWsResource({ cpu: { current: cpu } })]));
setWsState('lastUpdate', version);
setWsResourceChange({ version, changedIds: null });
});
};
try {
let picker = mount();
await picker.refetch();
expect(apiFetchMock).toHaveBeenCalledTimes(1);
expect(picker.error()).toBeUndefined();
const failure = new Error('canonical picker inventory denied');
apiFetchMock.mockRejectedValueOnce(failure);
await expect(picker.refetch()).rejects.toBe(failure);
expect(picker.error()).toBe(failure);
const calls = apiFetchMock.mock.calls.length;
if (delivery === 'reconnect') setWsConnected(false);
if (delivery === 'remount') disposals.shift()!();
publish(1, 71);
if (delivery === 'reconnect') setWsConnected(true);
if (delivery === 'remount') picker = mount();
await flushAsync();
// Assert the frame really reached the projection, not just a socket
// toggle that never delivered any inventory to the consumer.
expect(picker.resources()[0].cpu?.current).toBe(71);
expect(picker.loading()).toBe(false);
expect(picker.error()).toBe(failure);
expect(apiFetchMock).toHaveBeenCalledTimes(calls);
const accepted = deferred<ReturnType<typeof resourceResponse>>();
apiFetchMock.mockReturnValueOnce(accepted.promise);
const retry = picker.refetch();
publish(2, 82);
await flushAsync();
expect(picker.resources()[0].cpu?.current).toBe(82);
expect(picker.error()).toBe(failure);
accepted.resolve(resourceResponse([]));
await retry;
expect(picker.error()).toBeUndefined();
expect(picker.loading()).toBe(false);
expect(picker.resources()).toHaveLength(0);
disposals.shift()!();
picker = mount();
await flushAsync();
expect(picker.error()).toBeUndefined();
expect(apiFetchMock).toHaveBeenCalledTimes(calls + 1);
} finally {
disposals.forEach((dispose) => dispose());
}
},
);
it('keeps the default consumer websocket error-clearing policy', async () => {
const { useResources } = await import('../useResources');
let dispose = () => {};
let consumer!: ReturnType<typeof useResources>;
createRoot((d) => {
dispose = d;
consumer = useResources();
});
try {
await consumer.refetch();
const failure = new Error('transient default-consumer failure');
apiFetchMock.mockRejectedValueOnce(failure);
await expect(consumer.refetch()).rejects.toBe(failure);
expect(consumer.error()).toBe(failure);
const calls = apiFetchMock.mock.calls.length;
batch(() => {
setWsState('resources', reconcile([createWsResource({ cpu: { current: 71 } })]));
setWsState('lastUpdate', 1);
setWsResourceChange({ version: 1, changedIds: null });
});
await flushAsync();
expect(consumer.resources()[0].cpu?.current).toBe(71);
expect(consumer.error()).toBeUndefined();
expect(apiFetchMock).toHaveBeenCalledTimes(calls);
} finally {
dispose();
}
});
it('retains a scoped failed read across remounts until a real successful retry', async () => {
const options = {
query: 'type=physical_disk&parent=vm-alpha',
cacheKey: 'guest-physical-disks:vm-alpha',
retainReadError: true,
};
const mount = () => {
let dispose!: () => void;
let result!: ReturnType<typeof useUnifiedResources>;
createRoot((d) => {
dispose = d;
result = useUnifiedResources(options);
});
return { result, dispose };
};
const first = mount();
await waitForResourceCount(() => first.result.resources().length);
const failure = new Error('scoped read unavailable');
apiFetchMock.mockRejectedValueOnce(failure);
await expect(first.result.refetch()).rejects.toBe(failure);
expect(first.result.error()).toBe(failure);
expect(first.result.resources()).toHaveLength(1);
first.dispose();
const calls = apiFetchMock.mock.calls.length;
const reopened = mount();
await flushAsync();
expect(reopened.result.error()).toBe(failure);
expect(apiFetchMock).toHaveBeenCalledTimes(calls);
// The normal cache/cadence is unchanged; cached bytes do not clear failure.
apiFetchMock.mockResolvedValueOnce(resourceResponse([]));
await reopened.result.refetch();
expect(reopened.result.error()).toBeUndefined();
expect(reopened.result.resources()).toHaveLength(0);
reopened.dispose();
const recovered = mount();
await flushAsync();
expect(recovered.result.error()).toBeUndefined();
expect(recovered.result.resources()).toHaveLength(0);
recovered.dispose();
});
it('does not lend a retained read failure to another parent, organisation or default consumer', async () => {
const options = {
query: 'type=physical_disk&parent=vm-alpha',
cacheKey: 'guest-physical-disks:vm-alpha',
retainReadError: true,
};
let dispose!: () => void;
let first!: ReturnType<typeof useUnifiedResources>;
createRoot((d) => {
dispose = d;
first = useUnifiedResources(options);
});
await waitForResourceCount(() => first.resources().length);
const failure = new Error('unavailable');
apiFetchMock.mockRejectedValueOnce(failure);
await expect(first.refetch()).rejects.toBe(failure);
dispose();
const disposals: (() => void)[] = [];
let peer!: ReturnType<typeof useUnifiedResources>;
let defaultConsumer!: ReturnType<typeof useUnifiedResources>;
let retainedConsumer!: ReturnType<typeof useUnifiedResources>;
createRoot((d) => {
disposals.push(d);
peer = useUnifiedResources({
...options,
query: 'type=physical_disk&parent=vm-beta',
cacheKey: 'guest-physical-disks:vm-beta',
});
defaultConsumer = useUnifiedResources({ ...options, retainReadError: false });
retainedConsumer = useUnifiedResources(options);
});
await flushAsync();
expect(peer.error()).toBeUndefined();
expect(defaultConsumer.error()).toBeUndefined();
expect(retainedConsumer.error()).toBe(failure);
// No organisation may inherit the other organisation's unavailable read.
eventBus.emit('org_switched', 'other-org');
await flushAsync();
expect(peer.error()).toBeUndefined();
expect(defaultConsumer.error()).toBeUndefined();
expect(retainedConsumer.error()).toBeUndefined();
for (const cleanup of disposals) cleanup();
});
it('uses the shared org scope helper for cache and fetch state', () => {
expect(useUnifiedResourcesSource).toContain('normalizeOrgScope(getOrgID())');
expect(useUnifiedResourcesSource).not.toContain("const DEFAULT_ORG_SCOPE = 'default'");
});
});