Skip to content

armgit / Pulse

Public Imported from GitHub
0

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

Stabilize demo resource ordering

rcourtmanf1713b5fee6c
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index c2da69eeed..af396cfb16 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -149,6 +149,11 @@ an add-only capacity posture.
`quickstart:pulse-hosted` alias in AI settings payloads, but they must not
bake vendor model IDs or provider-model fallback rules into install or
activation flows just because those routes share the backend API tree.
+ Lifecycle-adjacent resource reads that traverse `internal/api/resources.go`
+ must also preserve the canonical unified-resource `name -> type -> id`
+ order instead of inheriting map order or page-local re-sorts, so install
+ and runtime hydration do not present one resource ordering at first load and
+ a different ordering after the first live refresh.
Persisted legacy hosted quickstart model IDs are therefore not lifecycle
truth either: when shared settings helpers load or save historical
quickstart values, they must normalize them back to
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index e191ea3bb7..1758cec4f7 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -154,7 +154,8 @@ when the disabled candidate no longer counts toward monitored-system capacity.
4. Route unified resource sensitivity, routing, and `aiSafeSummary` payload changes through `internal/api/resources.go`, `internal/api/contract_test.go`, and the canonical frontend resource consumer proofs together; resource governance metadata must not ship as an API-only or frontend-only heuristic
5. Route unified-resource action, lifecycle, and export audit reads through `internal/api/activity_audit_handlers.go`, `internal/api/router_routes_licensing.go`, and `internal/api/contract_test.go` together so the control-plane execution trail stays on a governed API contract instead of a store-only shape
6. Route dedicated unified-resource timeline and facet-bundle reads through `frontend-modern/src/api/resources.ts`, `internal/api/resources.go`, and `internal/api/contract_test.go` together so the backend facet contract and the frontend client stay aligned on one timeline-first surface, while capability and relationship detail stays backend-owned for AI correlation and change detection
-7. Route canonical AI intelligence summary and resource-intelligence reads through `frontend-modern/src/api/ai.ts`, `frontend-modern/src/stores/aiIntelligence.ts`, `frontend-modern/src/stores/aiIntelligenceSummaryModel.ts`, `frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts`, `frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx`, the Patrol-owned section files under `frontend-modern/src/features/patrol/`, `frontend-modern/src/pages/AIIntelligence.tsx`, `internal/api/ai_handlers.go`, and `internal/api/contract_test.go` together so the summary card, store normalization owner, runtime hook, feature shell, section owners, route shell, and backend payload stay aligned on one governed surface, including the canonical recent-changes slice
+7. Route unified-resource list ordering through `internal/api/resources.go`, `internal/api/contract_test.go`, and the owned unified-resource registry helpers together; list payloads must stay deterministic for equal-name resources by carrying one canonical `name -> type -> id` tie-break across cold seed, REST pagination, and websocket-backed refreshes instead of inheriting map order or page-local re-sorts
+8. Route canonical AI intelligence summary and resource-intelligence reads through `frontend-modern/src/api/ai.ts`, `frontend-modern/src/stores/aiIntelligence.ts`, `frontend-modern/src/stores/aiIntelligenceSummaryModel.ts`, `frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts`, `frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx`, the Patrol-owned section files under `frontend-modern/src/features/patrol/`, `frontend-modern/src/pages/AIIntelligence.tsx`, `internal/api/ai_handlers.go`, and `internal/api/contract_test.go` together so the summary card, store normalization owner, runtime hook, feature shell, section owners, route shell, and backend payload stay aligned on one governed surface, including the canonical recent-changes slice
while keeping the learning counters backend-only coverage, so the summary page keeps Patrol health and findings primary and renders timeline, correlation, and policy-posture data as secondary investigation context rather than as a separate headline product metric
and the Patrol findings empty-state behavior, so `0 active findings` only renders as a healthy frontend conclusion when the same governed AI summary contract still reports healthy overall health; degraded or not-fully-verified health predictions must flow through to the Patrol findings surface instead of being replaced by page-local "looks healthy" copy
and the Patrol assessment headline plus compact summary-strip behavior, so the same governed AI summary contract decides whether the page leads with verified health, issues detected, coverage incomplete, or another attention state instead of letting count-only page fragments emit a stale `No issues found` conclusion
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index b1d7e563bc..77b7d6aa38 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -79,6 +79,10 @@ querying, and the operator-facing storage health presentation layer.
current/projected grouped systems plus enforced limit verdicts for setup and
support clarity, but storage and recovery must not reinterpret those routes
as recovery-local onboarding or restore APIs.
+ Any adjacent list surfaces that reuse `internal/api/resources.go` must also
+ preserve the canonical unified-resource `name -> type -> id` order so
+ duplicate-name storage and recovery resources do not reshuffle between cold
+ hydrate, paginated reads, and later live runtime updates.
That same adjacent API boundary now also owns SSO outbound discovery and metadata fetch trust: storage- and recovery-adjacent surfaces may share `internal/api/sso_outbound.go`, `internal/api/saml_service.go`, and `internal/api/oidc_service.go`, but they must not fork separate metadata/discovery HTTP clients, redirect policies, or credential-file read rules when they depend on shared backend auth helpers.
5. Route canonical storage/recovery resource selection through `frontend-modern/src/hooks/useUnifiedResources.ts` and the owning `unified-resources` contract
That shared hook now also projects resource `clusterId` through the shared cluster-name helper, so storage and recovery links keep the same cluster-context label as other unified-resource consumers instead of rebuilding a local fallback chain.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 1bd6c05359..b2733d05db 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -143,6 +143,11 @@ assembly branch.
`internal/unifiedresources/pbs_rollups.go`,
`internal/unifiedresources/monitored_systems.go`,
`internal/unifiedresources/monitored_system_projection.go`, and
+ the shared list-order helpers consumed by `internal/api/resources.go`;
+ canonical unified-resource lists must preserve one deterministic
+ `name -> type -> id` order across registry reads, REST pagination, and
+ websocket-backed refreshes so equal-name resources do not silently reshuffle
+ between cold hydrate and later runtime updates
`internal/unifiedresources/top_level_systems.go`
6. Add canonical governed name-resolution or policy-aware resource lookup behavior through `internal/unifiedresources/resolve.go` and `internal/unifiedresources/resolve_context.go`
7. Add or change resource drawer timeline/facet presentation through `frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx`, `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx`, `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerDebugTab.tsx`, `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts`, `frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx`, `frontend-modern/src/components/Infrastructure/resourceDetailMappers.ts`, and the governed `internal/api/resources.go` facet/timeline contract together
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 82a8350e53..6f79edfff1 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -8931,6 +8931,49 @@ func TestContract_ResourceListPolicyMetadata(t *testing.T) {
}
}
+func TestContract_ResourceListUsesDeterministicNameTieBreakers(t *testing.T) {
+ now := time.Date(2026, 4, 11, 0, 0, 0, 0, time.UTC)
+ h := NewResourceHandlers(&config.Config{DataPath: t.TempDir()})
+ h.SetStateProvider(resourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now},
+ resources: []unifiedresources.Resource{
+ {ID: "storage-c", Type: unifiedresources.ResourceTypeStorage, Name: "backup-vault-a", Status: unifiedresources.StatusOnline, LastSeen: now},
+ {ID: "storage-a", Type: unifiedresources.ResourceTypeStorage, Name: "backup-vault-a", Status: unifiedresources.StatusOnline, LastSeen: now},
+ {ID: "storage-b", Type: unifiedresources.ResourceTypeStorage, Name: "backup-vault-a", Status: unifiedresources.StatusOnline, LastSeen: now},
+ },
+ })
+
+ for attempt := 0; attempt < 2; attempt++ {
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/api/resources?type=storage&page=1&limit=100", nil)
+ h.HandleListResources(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("attempt %d: status = %d, body=%s", attempt+1, rec.Code, rec.Body.String())
+ }
+
+ var resp ResourcesResponse
+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
+ t.Fatalf("attempt %d: decode response: %v", attempt+1, err)
+ }
+
+ gotIDs := make([]string, 0, len(resp.Data))
+ for _, resource := range resp.Data {
+ gotIDs = append(gotIDs, resource.ID)
+ }
+
+ wantIDs := []string{"storage-a", "storage-b", "storage-c"}
+ if len(gotIDs) != len(wantIDs) {
+ t.Fatalf("attempt %d: expected %d resources, got %d (%v)", attempt+1, len(wantIDs), len(gotIDs), gotIDs)
+ }
+ for index := range wantIDs {
+ if gotIDs[index] != wantIDs[index] {
+ t.Fatalf("attempt %d: position %d = %q, want %q (got=%v)", attempt+1, index, gotIDs[index], wantIDs[index], gotIDs)
+ }
+ }
+ }
+}
+
func TestContract_ResourceListCarriesTimelineAndCapabilityContracts(t *testing.T) {
now := time.Date(2026, 3, 18, 12, 0, 0, 0, time.UTC)
occurredAt := now.Add(-2 * time.Minute)
diff --git a/internal/api/resources.go b/internal/api/resources.go
index a834b116f1..14863a13e6 100644
--- a/internal/api/resources.go
+++ b/internal/api/resources.go
@@ -2059,24 +2059,31 @@ func applyFilters(resources []unified.Resource, filters listFilters) []unified.R
}
func applySorting(resources []unified.Resource, field, order string) {
- sort.Slice(resources, func(i, j int) bool {
+ sort.SliceStable(resources, func(i, j int) bool {
a := resources[i]
b := resources[j]
- less := false
+ comparison := 0
switch field {
case "status":
- less = a.Status < b.Status
+ comparison = strings.Compare(string(a.Status), string(b.Status))
case "type":
- less = a.Type < b.Type
+ comparison = strings.Compare(string(a.Type), string(b.Type))
case "lastSeen":
- less = a.LastSeen.Before(b.LastSeen)
+ if a.LastSeen.Before(b.LastSeen) {
+ comparison = -1
+ } else if b.LastSeen.Before(a.LastSeen) {
+ comparison = 1
+ }
default:
- less = strings.ToLower(a.Name) < strings.ToLower(b.Name)
+ comparison = unified.CompareResourcesByCanonicalName(a, b)
+ }
+ if comparison == 0 {
+ comparison = unified.CompareResourcesByCanonicalName(a, b)
}
if order == "desc" {
- return !less
+ return comparison > 0
}
- return less
+ return comparison < 0
})
}
diff --git a/internal/api/resources_test.go b/internal/api/resources_test.go
index 09960e678d..be360302f1 100644
--- a/internal/api/resources_test.go
+++ b/internal/api/resources_test.go
@@ -252,6 +252,49 @@ func TestResourceListUsesUnifiedSeedProvider(t *testing.T) {
}
}
+func TestResourceListUsesDeterministicNameTieBreakers(t *testing.T) {
+ now := time.Date(2026, 4, 11, 0, 0, 0, 0, time.UTC)
+ cfg := &config.Config{DataPath: t.TempDir()}
+ h := NewResourceHandlers(cfg)
+ h.SetStateProvider(resourceUnifiedSeedProvider{
+ snapshot: models.StateSnapshot{LastUpdate: now},
+ resources: []unified.Resource{
+ {ID: "storage-c", Type: unified.ResourceTypeStorage, Name: "backup-vault-a", Status: unified.StatusOnline, LastSeen: now},
+ {ID: "storage-a", Type: unified.ResourceTypeStorage, Name: "backup-vault-a", Status: unified.StatusOnline, LastSeen: now},
+ {ID: "storage-b", Type: unified.ResourceTypeStorage, Name: "backup-vault-a", Status: unified.StatusOnline, LastSeen: now},
+ },
+ })
+
+ for attempt := 0; attempt < 2; attempt++ {
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/api/resources?type=storage&page=1&limit=100", nil)
+ h.HandleListResources(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("attempt %d: status = %d, body=%s", attempt+1, rec.Code, rec.Body.String())
+ }
+
+ var resp ResourcesResponse
+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
+ t.Fatalf("attempt %d: decode response: %v", attempt+1, err)
+ }
+
+ gotIDs := make([]string, 0, len(resp.Data))
+ for _, resource := range resp.Data {
+ gotIDs = append(gotIDs, resource.ID)
+ }
+ wantIDs := []string{"storage-a", "storage-b", "storage-c"}
+ if len(gotIDs) != len(wantIDs) {
+ t.Fatalf("attempt %d: expected %d resources, got %d (%v)", attempt+1, len(wantIDs), len(gotIDs), gotIDs)
+ }
+ for index := range wantIDs {
+ if gotIDs[index] != wantIDs[index] {
+ t.Fatalf("attempt %d: position %d = %q, want %q (got=%v)", attempt+1, index, gotIDs[index], wantIDs[index], gotIDs)
+ }
+ }
+ }
+}
+
func TestResourceListInvalidatesUnifiedSeedCacheOnFreshnessChange(t *testing.T) {
now := time.Now().UTC()
provider := &mutableResourceUnifiedSeedProvider{
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index 90f9aa242f..152b01dfd1 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -1742,3 +1742,28 @@ func TestResourceAPIHotPathUsesSingleRegistryListSnapshot(t *testing.T) {
t.Fatalf("%s: duplicate registry.List() hot-path aggregation detected", normalizedPath)
}
}
+
+func TestCanonicalResourceOrderingContractsStayShared(t *testing.T) {
+ repoRoot := filepath.Join("..", "..")
+ resourcesPath := filepath.Join(repoRoot, "internal", "api", "resources.go")
+ registryPath := filepath.Join(repoRoot, "internal", "unifiedresources", "registry.go")
+
+ resourcesSource, err := os.ReadFile(resourcesPath)
+ if err != nil {
+ t.Fatalf("failed to read %s: %v", resourcesPath, err)
+ }
+ registrySource, err := os.ReadFile(registryPath)
+ if err != nil {
+ t.Fatalf("failed to read %s: %v", registryPath, err)
+ }
+
+ if !strings.Contains(string(resourcesSource), "unified.CompareResourcesByCanonicalName") {
+ t.Fatalf("%s: /api/resources must route deterministic list ordering through unified.CompareResourcesByCanonicalName", filepath.ToSlash(resourcesPath))
+ }
+ if !strings.Contains(string(registrySource), "sortResourcesByName(out)") {
+ t.Fatalf("%s: ResourceRegistry.List() must normalize map iteration through sortResourcesByName(out)", filepath.ToSlash(registryPath))
+ }
+ if !strings.Contains(string(registrySource), "sortNamedResourceViewsByName(rr.cachedStorage)") {
+ t.Fatalf("%s: cached unified resource views must share the canonical deterministic name ordering helper", filepath.ToSlash(registryPath))
+ }
+}
diff --git a/internal/unifiedresources/registry.go b/internal/unifiedresources/registry.go
index 51f02d9685..90024f5c03 100644
--- a/internal/unifiedresources/registry.go
+++ b/internal/unifiedresources/registry.go
@@ -323,6 +323,7 @@ func (rr *ResourceRegistry) List() []Resource {
for _, r := range rr.resources {
out = append(out, cloneResource(r))
}
+ sortResourcesByName(out)
return out
}
@@ -1847,8 +1848,19 @@ func exclusionKey(a, b string) string {
// Stable ordering helper for deterministic output.
func sortResourcesByName(resources []Resource) {
- sort.Slice(resources, func(i, j int) bool {
- return strings.ToLower(resources[i].Name) < strings.ToLower(resources[j].Name)
+ sort.SliceStable(resources, func(i, j int) bool {
+ return CompareResourcesByCanonicalName(resources[i], resources[j]) < 0
+ })
+}
+
+type namedResourceView interface {
+ ID() string
+ Name() string
+}
+
+func sortNamedResourceViewsByName[T namedResourceView](views []T) {
+ sort.SliceStable(views, func(i, j int) bool {
+ return compareResourceNameIdentity(views[i].Name(), "", views[i].ID(), views[j].Name(), "", views[j].ID()) < 0
})
}
@@ -1957,23 +1969,22 @@ func (rr *ResourceRegistry) rebuildViews() {
}
}
- // Sort all caches by name for deterministic output.
- sort.Slice(rr.cachedVMs, func(i, j int) bool { return rr.cachedVMs[i].Name() < rr.cachedVMs[j].Name() })
- sort.Slice(rr.cachedLXC, func(i, j int) bool { return rr.cachedLXC[i].Name() < rr.cachedLXC[j].Name() })
- sort.Slice(rr.cachedNodes, func(i, j int) bool { return rr.cachedNodes[i].Name() < rr.cachedNodes[j].Name() })
- sort.Slice(rr.cachedHosts, func(i, j int) bool { return rr.cachedHosts[i].Name() < rr.cachedHosts[j].Name() })
- sort.Slice(rr.cachedDocker, func(i, j int) bool { return rr.cachedDocker[i].Name() < rr.cachedDocker[j].Name() })
- sort.Slice(rr.cachedDockerContainers, func(i, j int) bool { return rr.cachedDockerContainers[i].Name() < rr.cachedDockerContainers[j].Name() })
- sort.Slice(rr.cachedStorage, func(i, j int) bool { return rr.cachedStorage[i].Name() < rr.cachedStorage[j].Name() })
- sort.Slice(rr.cachedPhysicalDisks, func(i, j int) bool { return rr.cachedPhysicalDisks[i].Name() < rr.cachedPhysicalDisks[j].Name() })
- sort.Slice(rr.cachedPBS, func(i, j int) bool { return rr.cachedPBS[i].Name() < rr.cachedPBS[j].Name() })
- sort.Slice(rr.cachedPMG, func(i, j int) bool { return rr.cachedPMG[i].Name() < rr.cachedPMG[j].Name() })
- sort.Slice(rr.cachedK8s, func(i, j int) bool { return rr.cachedK8s[i].Name() < rr.cachedK8s[j].Name() })
- sort.Slice(rr.cachedK8sNodes, func(i, j int) bool { return rr.cachedK8sNodes[i].Name() < rr.cachedK8sNodes[j].Name() })
- sort.Slice(rr.cachedPods, func(i, j int) bool { return rr.cachedPods[i].Name() < rr.cachedPods[j].Name() })
- sort.Slice(rr.cachedK8sDeployments, func(i, j int) bool { return rr.cachedK8sDeployments[i].Name() < rr.cachedK8sDeployments[j].Name() })
- sort.Slice(rr.cachedWorkload, func(i, j int) bool { return rr.cachedWorkload[i].Name() < rr.cachedWorkload[j].Name() })
- sort.Slice(rr.cachedInfra, func(i, j int) bool { return rr.cachedInfra[i].Name() < rr.cachedInfra[j].Name() })
+ sortNamedResourceViewsByName(rr.cachedVMs)
+ sortNamedResourceViewsByName(rr.cachedLXC)
+ sortNamedResourceViewsByName(rr.cachedNodes)
+ sortNamedResourceViewsByName(rr.cachedHosts)
+ sortNamedResourceViewsByName(rr.cachedDocker)
+ sortNamedResourceViewsByName(rr.cachedDockerContainers)
+ sortNamedResourceViewsByName(rr.cachedStorage)
+ sortNamedResourceViewsByName(rr.cachedPhysicalDisks)
+ sortNamedResourceViewsByName(rr.cachedPBS)
+ sortNamedResourceViewsByName(rr.cachedPMG)
+ sortNamedResourceViewsByName(rr.cachedK8s)
+ sortNamedResourceViewsByName(rr.cachedK8sNodes)
+ sortNamedResourceViewsByName(rr.cachedPods)
+ sortNamedResourceViewsByName(rr.cachedK8sDeployments)
+ sortNamedResourceViewsByName(rr.cachedWorkload)
+ sortNamedResourceViewsByName(rr.cachedInfra)
rr.viewsDirty = false
}
diff --git a/internal/unifiedresources/registry_test.go b/internal/unifiedresources/registry_test.go
index bfe37de09d..daa75907ce 100644
--- a/internal/unifiedresources/registry_test.go
+++ b/internal/unifiedresources/registry_test.go
@@ -100,6 +100,26 @@ func TestResourceRegistry_ListByType_Empty(t *testing.T) {
}
}
+func TestResourceRegistry_ListUsesDeterministicNameTieBreakers(t *testing.T) {
+ rr := NewRegistry(nil)
+ now := time.Date(2026, 4, 11, 0, 0, 0, 0, time.UTC)
+
+ rr.IngestResources([]Resource{
+ {ID: "storage-z", Type: ResourceTypeStorage, Name: "backup-vault-a", Status: StatusOnline, LastSeen: now},
+ {ID: "storage-b", Type: ResourceTypeStorage, Name: "backup-vault-a", Status: StatusOnline, LastSeen: now},
+ {ID: "agent-1", Type: ResourceTypeAgent, Name: "alpha-host", Status: StatusOnline, LastSeen: now},
+ {ID: "storage-a", Type: ResourceTypeStorage, Name: "backup-vault-a", Status: StatusOnline, LastSeen: now},
+ })
+
+ got := rr.List()
+ gotIDs := make([]string, 0, len(got))
+ for _, resource := range got {
+ gotIDs = append(gotIDs, resource.ID)
+ }
+
+ assertStringSlice(t, gotIDs, []string{"agent-1", "storage-a", "storage-b", "storage-z"})
+}
+
func TestResourceRegistry_MergesPhysicalDiskTemperatureAggregate(t *testing.T) {
rr := NewRegistry(nil)
now := time.Date(2026, 3, 29, 12, 0, 0, 0, time.UTC)
diff --git a/internal/unifiedresources/sort_order.go b/internal/unifiedresources/sort_order.go
new file mode 100644
index 0000000000..afc1bc050e
--- /dev/null
+++ b/internal/unifiedresources/sort_order.go
@@ -0,0 +1,30 @@
+package unifiedresources
+
+import "strings"
+
+func canonicalResourceNameKey(name string) string {
+ return strings.ToLower(strings.TrimSpace(name))
+}
+
+func compareResourceNameIdentity(
+ nameA string,
+ typeA ResourceType,
+ idA string,
+ nameB string,
+ typeB ResourceType,
+ idB string,
+) int {
+ if cmp := strings.Compare(canonicalResourceNameKey(nameA), canonicalResourceNameKey(nameB)); cmp != 0 {
+ return cmp
+ }
+ if cmp := strings.Compare(string(typeA), string(typeB)); cmp != 0 {
+ return cmp
+ }
+ return strings.Compare(idA, idB)
+}
+
+// CompareResourcesByCanonicalName provides the canonical deterministic ordering
+// for unified resources across REST, websocket, and cached read-state views.
+func CompareResourcesByCanonicalName(a, b Resource) int {
+ return compareResourceNameIdentity(a.Name, a.Type, a.ID, b.Name, b.Type, b.ID)
+}
diff --git a/internal/unifiedresources/sort_order_test.go b/internal/unifiedresources/sort_order_test.go
new file mode 100644
index 0000000000..c61c7eebaa
--- /dev/null
+++ b/internal/unifiedresources/sort_order_test.go
@@ -0,0 +1,50 @@
+package unifiedresources
+
+import (
+ "testing"
+ "time"
+)
+
+func TestCompareResourcesByCanonicalNameUsesDeterministicTieBreakers(t *testing.T) {
+ now := time.Date(2026, 4, 11, 0, 0, 0, 0, time.UTC)
+ left := Resource{
+ ID: "storage-b",
+ Type: ResourceTypeStorage,
+ Name: "Backup-Vault-A",
+ Status: StatusOnline,
+ LastSeen: now,
+ }
+ right := Resource{
+ ID: "storage-a",
+ Type: ResourceTypeStorage,
+ Name: "backup-vault-a",
+ Status: StatusOnline,
+ LastSeen: now,
+ }
+
+ if got := CompareResourcesByCanonicalName(left, right); got <= 0 {
+ t.Fatalf("expected storage-b to sort after storage-a for equal canonical names, got %d", got)
+ }
+ if got := CompareResourcesByCanonicalName(right, left); got >= 0 {
+ t.Fatalf("expected storage-a to sort before storage-b for equal canonical names, got %d", got)
+ }
+}
+
+func TestRegistryListUsesDeterministicNameTieBreakers(t *testing.T) {
+ now := time.Date(2026, 4, 11, 0, 0, 0, 0, time.UTC)
+ registry := NewRegistry(nil)
+ registry.IngestResources([]Resource{
+ {ID: "storage-z", Type: ResourceTypeStorage, Name: "backup-vault-a", Status: StatusOnline, LastSeen: now},
+ {ID: "storage-b", Type: ResourceTypeStorage, Name: "backup-vault-a", Status: StatusOnline, LastSeen: now},
+ {ID: "agent-1", Type: ResourceTypeAgent, Name: "alpha-host", Status: StatusOnline, LastSeen: now},
+ {ID: "storage-a", Type: ResourceTypeStorage, Name: "backup-vault-a", Status: StatusOnline, LastSeen: now},
+ })
+
+ got := registry.List()
+ gotIDs := make([]string, 0, len(got))
+ for _, resource := range got {
+ gotIDs = append(gotIDs, resource.ID)
+ }
+
+ assertStringSlice(t, gotIDs, []string{"agent-1", "storage-a", "storage-b", "storage-z"})
+}