diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md index 9fc4842d90..1d844b511b 100644 --- a/docs/release-control/v6/internal/subsystems/cloud-paid.md +++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md @@ -182,22 +182,27 @@ billing, provider mutation or original administrator recovery is claimed. ### Organization billing reads are a selected snapshot, not fallback plan data -The existing Billing & Usage panel displays plan and member figures only after -all three reads for its current organization succeed. Selection, capability, +The existing Billing & Usage panel waits for the current organization's +session-bound reads. When the organization's plan and member list are verified +but directory enumeration returns the server's HTTP 500 `list_failed`, +the panel keeps the plan, current member count, and usage visible and labels +the Organizations total **Unavailable**. Reload billing rereads the same +selection without changing it. Selection, capability, presentation withdrawal and disposal invalidate the generation and abort its reads; an older response cannot overwrite the new selection or finish its spinner. License status prefers the browser session just as the organization reads do, carries the expected organization and cancellation signal, and disables automatic retries for this selected read without changing other status callers. -An incomplete or malformed read clears the former snapshot and renders a fixed, +Any other failed or malformed read clears the former snapshot and renders a fixed, inline unavailable notice with a deliberate reload of the same selection. It must not fabricate a Free plan, zero members, unconfigured email or unlimited usage from failed input. Accepted empty member lists still mean zero members. Organization-change events refresh the saved snapshot; no purchase, entitlement, pricing, plan or hosted-mode authority changes. Normal-suite Billing panel and OrganizationReadLifetimes tests cover failed/obsolete reads, A/B/A races, -withdrawal, disposal and recovery. Desktop/narrow proof consumes actual source +withdrawal and disposal; OrganizationBillingTransport covers the exact +directory failure, denial and explicit recovery. Desktop/narrow proof consumes actual source through the real API client with safe fixtures; it is not installed billing or commercial delivery acceptance. diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.md index 63a4fa748e..fad257657b 100644 --- a/docs/release-control/v6/internal/subsystems/organization-settings.md +++ b/docs/release-control/v6/internal/subsystems/organization-settings.md @@ -439,6 +439,36 @@ late completion after actual principal, organization, policy, entitlement or component withdrawal. `OrganizationOverviewPanel.test.tsx` also pins normalized request scopes through the pending rename and resulting saved read. +### Sharing preserves verified selected data when a peer blocks enumeration + +The organization directory and the incoming-sharing scan can return the +server's explicit HTTP 500 `list_failed` even when the selected organization +is readable. If current-organization detail, membership and outgoing shares +are all verified for the same selection, Sharing keeps the selected identity +and outgoing rows. The recipient list and incoming rows are marked unavailable +only when their own enumeration failed. No synthetic organization, share, +target, or empty incoming inventory replaces an unread result. + +A verified owner or administrator continues to see the existing form and +any saved row controls, but all sharing writes still require the complete +snapshot, including remove, accept and decline. Reload sharing makes only +read-only requests for the same selection. An explicit draft recipient is +not replaced by another target and must still be present in the verified +directory before the form can submit. Other errors, stale readers, +malformed bodies, failed selected-scope reads, policy and authority withdrawal +keep their existing fail-closed behavior. Server authorization is unchanged. + +The create form's browser code is loaded only for a current owner or +administrator who can manage shares. Its loading and failure states are local +to the form, so neither suspends independently verified incoming or outgoing +rows. The form uses the same snapshot and complete-read write gate when ready. + +The registered OrganizationSharingPanel and OrganizationSharingTransport tests +cover individual and concurrent list failures, fresh scoped data versus a +failed selected read, native controls, no mutation or CSRF preparation, and +explicit recovery. Comparable desktop/narrow Settings browser proof uses +the native saved-workspace fixture's response bodies, not live client recovery. + ### Invitation decisions identify the exact organization Your Invitations shows each organization's display name **and** ID beside its @@ -651,8 +681,15 @@ one cancellation signal and the expected organization through the existing session-preferred API client, with automatic retries disabled. Only the current read generation may publish a matching organization and a complete member list; a late success, failure or completion cannot replace a newer selection or end -its loading state. A failed read is an inline unavailable state, never an empty -member list, and offers an explicit read-only reload. +its loading state. Overview uses the normalized member array already returned +in the authorized organization detail, so the name, member count, roles and +existing rename gate ordinarily describe the same saved read. There is no +parallel request for the same members. If detail omits the member field (the +server omits an empty array), Overview requests the dedicated member list with +the same org binding and cancellation signal before showing the panel. A +malformed field or row is not an omitted list. A required read that fails is an +inline unavailable state, never an empty member list, and offers an explicit +read-only reload. The server routes and their authorization are unchanged. Renaming requires the current accepted snapshot, owner/admin authority and a non-read-only session. Dispatch binds the exact organization even across a CSRF @@ -661,7 +698,10 @@ withdrawn or disposed completion cannot change data or notify a later selection. An unconfirmed write clears the editable snapshot and requires a saved read; reload does not repeat the rename. Successful writes notify the existing organization-change bus and refresh the saved snapshot. Normal-suite Overview, -OrganizationReadLifetimes and organization-client tests cover those boundaries; +OrganizationReadLifetimes and organization-client tests cover those boundaries. +`OrganizationOverviewKeyboard.transport.test.tsx` also covers the single +authorized request, malformed member rows, distinguishing omitted/unread from +verified empty, and rejecting a fallback completion after a workspace switch; desktop/narrow browser proof exercises the actual panels and API client with safe HTTP fixtures, not an installed tenant or SSO recovery claim. diff --git a/frontend-modern/browser-verification/23edf6c61f607378.json b/frontend-modern/browser-verification/23edf6c61f607378.json new file mode 100644 index 0000000000..23bb34db21 --- /dev/null +++ b/frontend-modern/browser-verification/23edf6c61f607378.json @@ -0,0 +1,33 @@ +{ + "version": 1, + "base_sha": "d62573ce6d19cc712a9c4f7cb1a39b1c74fa1008", + "verified_at": "2026-11-18T23:21:04Z", + "result": "passed", + "changed_paths": [ + "frontend-modern/src/features/alerts/AlertOverviewActiveAlertsSection.tsx" + ], + "content_sha256": { + "frontend-modern/src/features/alerts/AlertOverviewActiveAlertsSection.tsx": "f2651c417e20e07df3475354189d4395b0e6df7fead971d2073001b15067defb" + }, + "routes": [ + "/alerts/overview" + ], + "viewports": [ + { + "width": 1440, + "height": 900 + }, + { + "width": 390, + "height": 844 + } + ], + "states": [ + "Production Pulse App, Chromium 141 desktop and touch WebKit 26 narrow, light, same top anchors and fixed clock: six inspected before/after pairs.", + "Native PMG REST Warning rows through the HTTP recovery route show both scopes as before. The same rows projected to the model.Alert shape enter through initialState and rawData; the peer stays first, and the gateway age, 15-minute threshold and controls are now visible without a disclosure. The peer threshold remains 9 minutes." + ], + "interactions": [ + "Verified both independent card controls and Warning counts; expanded the baseline related row and toggled the candidate gateway More controls. Observed actual rawData replacement via the intervening peer-only fixture, then both current rows; no mutation.", + "The compact frame is an exact source-derived projection of retained native alert records, not a captured server WebSocket frame or installed-appliance result." + ] +} diff --git a/frontend-modern/browser-verification/50543f6c76ccb5ab.json b/frontend-modern/browser-verification/50543f6c76ccb5ab.json new file mode 100644 index 0000000000..ecdad751e5 --- /dev/null +++ b/frontend-modern/browser-verification/50543f6c76ccb5ab.json @@ -0,0 +1,36 @@ +{ + "version": 1, + "base_sha": "107411a34665a133511a457976605fbbc440c477", + "verified_at": "2026-11-18T23:21:00Z", + "result": "passed", + "changed_paths": [ + "frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx", + "frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx" + ], + "content_sha256": { + "frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx": "6ae4bc8b4248932400684b7cf6a933b91f02ae75e1852a6e27a4ee37c2484be6", + "frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx": "7fb7cb3e23049bfc580f540b8874512e09d020e109a909778b6744b7bbfaeb7f" + }, + "routes": [ + "/settings/organization/sharing" + ], + "viewports": [ + { + "width": 1440, + "height": 900 + }, + { + "width": 390, + "height": 844 + } + ], + "states": [ + "Production Pulse App in Playwright 1.56.1, Chromium 141 desktop and touch WebKit 26 narrow, light. Eight inspected before/after pairs; separate form pending on both widths and desktop form-module failure.", + "With the same healthy selection and unread directory/incoming scan, verified selected identity and outgoing row stay visible. Incoming is unavailable, not empty; all writes are disabled. Fixture uses retained producer detail/member/directory statuses with explicitly synthetic share rows.", + "After same-selection reload, the complete owner and viewer screens preserve fields, role notice, identity, row roles, status and control positions at the same anchors. Viewers do not request the manager form module." + ], + "interactions": [ + "Delayed the module deliberately and retained visible rows. Interrupted just the form module and verified a local warning, without removing verified incoming/outgoing rows.", + "Read-only reload and retry kept the saved workspace. Forced submit under an incomplete snapshot dispatched no write; deliberate target and resource became enabled only after complete recovery, without submitting." + ] +} diff --git a/frontend-modern/browser-verification/7c06e629d6206de7.json b/frontend-modern/browser-verification/7c06e629d6206de7.json new file mode 100644 index 0000000000..14d6b8afb2 --- /dev/null +++ b/frontend-modern/browser-verification/7c06e629d6206de7.json @@ -0,0 +1,51 @@ +{ + "version": 1, + "base_sha": "c13c7048ee8241fd4e7e8c7a2abb3629f501ca47", + "verified_at": "2026-11-18T22:07:49Z", + "result": "passed", + "changed_paths": [ + "frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx", + "frontend-modern/src/components/Settings/OrganizationIncomingSharesSection.tsx", + "frontend-modern/src/components/Settings/OrganizationOutgoingSharesSection.tsx", + "frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx", + "frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx", + "frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts", + "frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts", + "frontend-modern/src/utils/commercialBillingModel.ts", + "frontend-modern/src/utils/orgUtils.ts" + ], + "content_sha256": { + "frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx": "85afa817dd73c597dd08ab6dc924aab218ada584dc1e12556388b81df413cc79", + "frontend-modern/src/components/Settings/OrganizationIncomingSharesSection.tsx": "765d4b0c985dbb1dc54091c1863efc95ab6580bfd2e30f9214a99ca646f2ac16", + "frontend-modern/src/components/Settings/OrganizationOutgoingSharesSection.tsx": "c877a00725959374f58db36328e4d5fa5490e6e423982ca2dd4157c362d04fd1", + "frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx": "c816ce65677d8cb9a5bcf37ec3bc78d3149022018afe537a8107cec4aa60a84e", + "frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx": "533e58266616f7558afef8e2fefdd590479742b8e31510ad7a00b0c01b58f061", + "frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts": "ff242fa6778aac5f0c1023fcfe95e047d2a53d6387e732e302c58fee3975b2e1", + "frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts": "875c280fa6580a45dbc9c40816283c582fe371cc469864342843dab3cc74e97e", + "frontend-modern/src/utils/commercialBillingModel.ts": "c32f128143f962e589f727d8fc37483ab82c201feea0858f2e417d3b66b599fd", + "frontend-modern/src/utils/orgUtils.ts": "d68a0dc5aa096525d30e0247349c2f723c6d8021e00516be8c7c0f3c9bf47f2a" + }, + "routes": [ + "/settings/organization/billing", + "/settings/organization/sharing" + ], + "viewports": [ + { + "width": 1365, + "height": 900 + }, + { + "width": 390, + "height": 844 + } + ], + "states": [ + "Production Pulse Settings frontend with the same retained native fixture responses on both sides (synthetic plan and bootstrap). Playwright 1.56.1 Chromium 141 desktop and WebKit 26 narrow, light. Eight comparable viewport pairs and two additional narrow detail views inspected.", + "With the saved organization healthy and another workspace unreadable, Billing keeps the active plan, verified current members and usage; Organizations reads Unavailable. Sharing keeps the selected name, verified outgoing state and existing owner form with native disabled controls. Incoming is unavailable, not empty.", + "After read-only Reload and Retry, the same selection restores the complete counts and the real incoming result, and the unchosen recipient becomes available. The ordinary recovered screen preserves the previous controls and layout." + ], + "interactions": [ + "Retained 134 checks across eight browser cases. Same selected ID in cookie, session storage and socket, no prod origin or writes. An incomplete sharing snapshot rejects form requestSubmit; recovery never replays a mutation.", + "After complete recovery, selecting an explicit recipient and resource enables Create Share; no submission is made. Existing server authorization and complete-snapshot write rules remain in effect." + ] +} diff --git a/frontend-modern/browser-verification/8d8019b0de8b66f9.json b/frontend-modern/browser-verification/8d8019b0de8b66f9.json new file mode 100644 index 0000000000..7610216e17 --- /dev/null +++ b/frontend-modern/browser-verification/8d8019b0de8b66f9.json @@ -0,0 +1,36 @@ +{ + "version": 1, + "base_sha": "61bb11ca9a62ba964f786bfbcb23b78e167ba49c", + "verified_at": "2026-11-18T22:38:02Z", + "result": "passed", + "changed_paths": [ + "frontend-modern/src/components/Settings/useOrganizationOverviewPanelState.ts" + ], + "content_sha256": { + "frontend-modern/src/components/Settings/useOrganizationOverviewPanelState.ts": "08fae70c7af2401d8e143b9159393aafd145c38c073acaee33606fc8dfbc7c69" + }, + "routes": [ + "/settings/organization" + ], + "viewports": [ + { + "width": 1365, + "height": 900 + }, + { + "width": 390, + "height": 844 + } + ], + "states": [ + "Production Settings route with offline synthetic authentication and selected organization responses; Playwright 1.56.1, Chromium 141.0.7390.37 desktop light and WebKit 26.0 phone dark.", + "Matching selected detail 200 contained the normalized two-member snapshot; when the duplicate list returned HTTP 500, the parent hid the overview. Candidate makes no duplicate list request and visibly retains the name, ID, creation date, member count, both identities with roles, and the existing owner edit control.", + "A selected detail HTTP 403 leaves the existing unavailable state and focused read-only reload available; no metadata, rows, false empty or rename controls. The omitted-field fixture still reads members and renders the same metadata and rows as before.", + "Both builds retain keyboard reload focus, desktop per-member dates, and phone identities with role distinctions; nine before/after pairs opened and inspected, including the phone membership after reload. Fixture proof, not installed or live tenant acceptance." + ], + "interactions": [ + "Opened the selected organization route with identical fixture data, viewport and theme in both builds; compared no-scroll failure, denied, reloaded, and omitted-list states.", + "Focused Reload organization and pressed Enter after the selected-detail failure; read back the same selected organization, complete memberships and visible panel focus without any writes.", + "Scrolled the recovered narrow panel to Membership and checked both identities and roles at the same anchor. Compared request paths and verified unchanged selected workspace and zero mutations in all cases." + ] +} diff --git a/frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx b/frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx index df772eaa59..a945285385 100644 --- a/frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx +++ b/frontend-modern/src/components/Settings/OrganizationBillingPanel.tsx @@ -26,6 +26,7 @@ export const OrganizationBillingPanel: Component loadError, reloadBillingData, selectedOrgID, + organizationCountUnavailable, } = useOrganizationBillingPanelState(props); const warningTitleID = createUniqueId(); let panel: HTMLDivElement | undefined; @@ -90,6 +91,13 @@ export const OrganizationBillingPanel: Component > + Reload billing + + ) : undefined + } loading={loading()} loadingFallback={} > diff --git a/frontend-modern/src/components/Settings/OrganizationIncomingSharesSection.tsx b/frontend-modern/src/components/Settings/OrganizationIncomingSharesSection.tsx index 80c811799f..ddd21702f0 100644 --- a/frontend-modern/src/components/Settings/OrganizationIncomingSharesSection.tsx +++ b/frontend-modern/src/components/Settings/OrganizationIncomingSharesSection.tsx @@ -112,7 +112,7 @@ export const OrganizationIncomingSharesSection: Component< onClick={() => { void props.state.acceptIncomingShare(share); }} - disabled={props.state.saving()} + disabled={props.state.saving() || props.state.sharingChangesPaused()} > Accept @@ -128,7 +128,7 @@ export const OrganizationIncomingSharesSection: Component< onClick={() => { void props.state.declineIncomingShare(share); }} - disabled={props.state.saving()} + disabled={props.state.saving() || props.state.sharingChangesPaused()} > {share.status === 'pending' ? 'Decline' : 'Remove'} @@ -138,7 +138,11 @@ export const OrganizationIncomingSharesSection: Component< }, ]} keyExtractor={(share) => share.id} - emptyState={getOrganizationIncomingSharesEmptyState()} + emptyState={ + props.state.unavailableLists()?.incoming + ? 'Incoming shares could not be loaded.' + : getOrganizationIncomingSharesEmptyState() + } desktopMinWidth="100%" /> diff --git a/frontend-modern/src/components/Settings/OrganizationOutgoingSharesSection.tsx b/frontend-modern/src/components/Settings/OrganizationOutgoingSharesSection.tsx index 667be88815..367e28f735 100644 --- a/frontend-modern/src/components/Settings/OrganizationOutgoingSharesSection.tsx +++ b/frontend-modern/src/components/Settings/OrganizationOutgoingSharesSection.tsx @@ -119,7 +119,7 @@ export const OrganizationOutgoingSharesSection: Component< onClick={() => { void props.state.deleteShare(share); }} - disabled={props.state.saving()} + disabled={props.state.saving() || props.state.sharingChangesPaused()} > Remove diff --git a/frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx b/frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx index 99bb048fc7..fd8b328bab 100644 --- a/frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx +++ b/frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx @@ -16,13 +16,15 @@ interface OrganizationSharingCreateSectionProps { state: ReturnType; } -export const OrganizationSharingCreateSection: Component = ( +const OrganizationSharingCreateSection: Component = ( props, ) => { const fieldID = createUniqueId(); const targetOrgID = `${fieldID}-target-org`; const resourceTypeID = `${fieldID}-resource-type`; const resourceID = `${fieldID}-resource-id`; + const targetError = () => + props.state.unavailableLists()?.directory ? '' : props.state.targetOrgError(); // Keep names stable; expose changing validation as each control's description. // Describe only a current choice, not leftover draft fields after withdrawal. const selectedTarget = createMemo(() => @@ -41,255 +43,239 @@ export const OrganizationSharingCreateSection: Component - -
{ - event.preventDefault(); - void props.state.createShare(); - }} - class="p-4 sm:p-6" - > -
-

Create Share

+ { + event.preventDefault(); + void props.state.createShare(); + }} + class="p-4 sm:p-6" + > +
+

Create Share

-
-
- props.state.updateTargetOrg(event.currentTarget.value)} - help={ - selectedTarget() && ( - <> - - {selectedTarget()?.displayName} ·{' '} - - ID:{' '} - - {selectedTarget()?.id} - - - ) - } - helpClass="text-xs [overflow-wrap:anywhere]" - selectBaseClass={`w-full rounded-md border bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-500 ${props.state.targetOrgError() ? 'border-red-400 dark:border-red-500' : 'border-border'}`} - > - - - {(target) => ( - - )} - - - -

- {props.state.targetOrgError()} -

-
-
- - - props.state.setAccessRole(event.currentTarget.value as ShareAccessRole) - } - selectBaseClass="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-500" - > - - {(option) => } - - -
- - 0}> -
- - props.state.applyResourceQuickPick(event.currentTarget.value) - } - help={ - selectedResource() && ( - <> - Resource:{' '} - - {selectedResource()?.name} ·{' '} - - - {selectedResource()?.type}:{selectedResource()?.id} - - - ) - } - helpClass="text-xs text-blue-700 dark:text-blue-300 [overflow-wrap:anywhere]" - selectBaseClass="w-full rounded-md border border-blue-300 bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-500 dark:border-blue-700" - > - - - {(resource) => ( - - )} - - -
-

- Choose a discovered resource, or switch to manual entry. -

- -
-
-
- - -

- The selected resource is no longer available. Choose another resource or enter it - manually. +

+
+ props.state.updateTargetOrg(event.currentTarget.value)} + help={ + selectedTarget() && ( + <> + + {selectedTarget()?.displayName} ·{' '} + + ID:{' '} + + {selectedTarget()?.id} + + + ) + } + helpClass="text-xs [overflow-wrap:anywhere]" + selectBaseClass={`w-full rounded-md border bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-500 ${targetError() ? 'border-red-400 dark:border-red-500' : 'border-border'}`} + > + + + {(target) => ( + + )} + + + +

+ {targetError()}

- Manual entry is hidden while quick pick is active.

- } - > -
-
- - props.state.updateResourceType(event.currentTarget.value)} - placeholder={CANONICAL_RESOURCE_TYPES.join(' | ')} - class={`w-full rounded-md border bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-500 ${props.state.resourceTypeError() ? 'border-red-400 dark:border-red-500' : 'border-border'}`} - /> - -

+ + + props.state.setAccessRole(event.currentTarget.value as ShareAccessRole) + } + selectBaseClass="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-500" + > + + {(option) => } + + +

+ + 0}> +
+ props.state.applyResourceQuickPick(event.currentTarget.value)} + help={ + selectedResource() && ( + <> + Resource:{' '} + - {props.state.resourceTypeError()} -

-
-
- -
- - props.state.updateResourceId(event.currentTarget.value)} - placeholder="resource identifier" - class={`w-full rounded-md border bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-500 ${props.state.resourceIdError() ? 'border-red-400 dark:border-red-500' : 'border-border'}`} - /> - -

- {props.state.resourceIdError()} -

-
-
- - -
-
- -
+ {selectedResource()?.name} ·{' '} + + + {selectedResource()?.type}:{selectedResource()?.id} + + + ) + } + helpClass="text-xs text-blue-700 dark:text-blue-300 [overflow-wrap:anywhere]" + selectBaseClass="w-full rounded-md border border-blue-300 bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-500 dark:border-blue-700" + > + + + {(resource) => ( + + )} + + +
+

+ Choose a discovered resource, or switch to manual entry. +

-
- - - - -
-
- Admin or owner role required to create or remove organization shares.
+ + + +

+ The selected resource is no longer available. Choose another resource or enter it + manually. +

+
+ Manual entry is hidden while quick pick is active.

+ } + > +
+
+ + props.state.updateResourceType(event.currentTarget.value)} + placeholder={CANONICAL_RESOURCE_TYPES.join(' | ')} + class={`w-full rounded-md border bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-500 ${props.state.resourceTypeError() ? 'border-red-400 dark:border-red-500' : 'border-border'}`} + /> + +

+ {props.state.resourceTypeError()} +

+
+
+ +
+ + props.state.updateResourceId(event.currentTarget.value)} + placeholder="resource identifier" + class={`w-full rounded-md border bg-surface px-3 py-2 text-sm text-base-content shadow-xs focus:border-blue-500 focus:outline-hidden focus:ring-2 focus:ring-blue-500 ${props.state.resourceIdError() ? 'border-red-400 dark:border-red-500' : 'border-border'}`} + /> + +

+ {props.state.resourceIdError()} +

+
+
+ + +
+
+ +
+
- - +
+ ); }; + +export default OrganizationSharingCreateSection; diff --git a/frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx b/frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx index d8332e791f..8470bca27b 100644 --- a/frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx +++ b/frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx @@ -1,4 +1,13 @@ -import { Component, Show, createEffect, createUniqueId, onCleanup } from 'solid-js'; +import { + Component, + ErrorBoundary, + Show, + Suspense, + createEffect, + createUniqueId, + lazy, + onCleanup, +} from 'solid-js'; import { Button } from '@/components/shared/Button'; import { Card } from '@/components/shared/Card'; import SettingsPanel from '@/components/shared/SettingsPanel'; @@ -13,10 +22,11 @@ import { } from '@/utils/organizationSettingsPresentation'; import { OrganizationIncomingSharesSection } from './OrganizationIncomingSharesSection'; import { OrganizationOutgoingSharesSection } from './OrganizationOutgoingSharesSection'; -import { OrganizationSharingCreateSection } from './OrganizationSharingCreateSection'; import { OrganizationSharingLoadingState } from './OrganizationSharingLoadingState'; import { useOrganizationSharingPanelState } from './useOrganizationSharingPanelState'; +const OrganizationSharingCreateSection = lazy(() => import('./OrganizationSharingCreateSection')); + export interface OrganizationSharingPanelProps { currentUser?: string; } @@ -141,7 +151,16 @@ export const OrganizationSharingPanel: Component } }} > - + {ORGANIZATION_SHARING_RELOAD_LABEL} + ) : undefined + } + noPadding + bodyClass="divide-y divide-border" + > }>
@@ -187,8 +206,44 @@ export const OrganizationSharingPanel: Component

This session is read-only. Sharing changes are disabled.

+ +

+ {state.canManageCurrentOrg() + ? 'Sharing changes are paused until the missing information loads.' + : 'Some sharing information could not be loaded.'} +

+
- + +
+
+ Admin or owner role required to create or remove organization shares. +
+
+
+ } + > + + Share creation controls could not be loaded. Reload the page to try again. +

+ } + > + + Loading share creation controls... +

+ } + > + +
+
+
diff --git a/frontend-modern/src/components/Settings/__tests__/OrganizationBillingPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/OrganizationBillingPanel.test.tsx index 6b8e3f33b3..9d84ca0986 100644 --- a/frontend-modern/src/components/Settings/__tests__/OrganizationBillingPanel.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/OrganizationBillingPanel.test.tsx @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen, waitFor } from '@solidjs/testing-library'; +import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library'; import { OrganizationBillingPanel } from '../OrganizationBillingPanel'; @@ -137,6 +137,29 @@ describe('OrganizationBillingPanel', () => { expect(errorMock).not.toHaveBeenCalled(); }); + it('keeps the current plan, member count and usage visible when the list cannot enumerate a peer', async () => { + listOrgsMock.mockRejectedValueOnce( + Object.assign(new Error('unread directory'), { status: 500, code: 'list_failed' }), + ); + render(() => ); + + await screen.findByText('Cloud'); + expect(screen.getByText('Organizations').parentElement).toHaveTextContent('Unavailable'); + expect(screen.getByText('Members (Current Org)').parentElement).toHaveTextContent('3'); + expect(screen.getByText('2 / 5')).toBeInTheDocument(); + expect(screen.getByText('5 / Not metered')).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Reload billing' })); + await waitFor(() => + expect(screen.getByText('Organizations').parentElement).toHaveTextContent('2'), + ); + expect(screen.queryByRole('button', { name: 'Reload billing' })).not.toBeInTheDocument(); + expect(listMembersMock).toHaveBeenLastCalledWith( + 'org-1', + expect.objectContaining({ expectedOrgID: 'org-1', retry: false }), + ); + }); + it('stays unavailable in demo mode without loading organization billing data', () => { presentationPolicyHidesOrganizationSurfacesMock.mockReturnValue(true); diff --git a/frontend-modern/src/components/Settings/__tests__/OrganizationBillingTransport.test.tsx b/frontend-modern/src/components/Settings/__tests__/OrganizationBillingTransport.test.tsx index b6c59cb423..67311ceb86 100644 --- a/frontend-modern/src/components/Settings/__tests__/OrganizationBillingTransport.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/OrganizationBillingTransport.test.tsx @@ -277,6 +277,32 @@ describe('organization billing through its real read transport', () => { expect(screen.getByText('2 / 17')).toBeInTheDocument(); }); + it('publishes only verified values and can reload the same scope after a directory list failure', async () => { + const pending = deferred(); + reply = async (source, org) => { + if (source === 'organizations') return json({ code: 'list_failed' }, 500); + if (source === 'members') return pending.promise; + return json(dataFor(source, org)); + }; + mount(); + await waitFor(() => expect(billingReads()).toHaveLength(3)); + await settle(); + expect(screen.getByLabelText('Loading organization billing')).toBeInTheDocument(); + expect(screen.queryByText('Plan Tier')).not.toBeInTheDocument(); + pending.resolve(json(dataFor('members', north))); + await screen.findByText(emailFor(north)); + expect(screen.getByText('Organizations').parentElement).toHaveTextContent('Unavailable'); + expect(screen.getByText('Members (Current Org)').parentElement).toHaveTextContent('3'); + expect(screen.getByText('2 / 17')).toBeInTheDocument(); + expectBoundReads(); + + reply = async (source, org) => json(dataFor(source, org)); + fireEvent.click(screen.getByRole('button', { name: 'Reload billing' })); + await accepted(); + expect(screen.getByText('Organizations').parentElement).toHaveTextContent('2'); + expectBoundReads(north, billingReads().slice(3)); + }); + it.each(sources)( 'does not publish a partial snapshot while the %s body is still unread', async (held) => { @@ -298,6 +324,23 @@ describe('organization billing through its real read transport', () => { }, ); + it.each([ + ['organizations', 500, 'unrelated_failure'], + ['organizations', 403, 'list_failed'], + ['license', 500, 'list_failed'], + ['members', 500, 'list_failed'], + ] as const)( + 'does not use %s HTTP %d %s as the directory fallback', + async (failed, status, code) => { + reply = async (source, org) => + source === failed ? json({ code }, status) : json(dataFor(source, org)); + mount(); + await screen.findByRole('alert'); + expectUnknown(); + expectBoundReads(); + }, + ); + it.each(sources.flatMap((source) => [400, 403, 429, 503].map((status) => ({ source, status }))))( 'keeps HTTP $status from $source unknown without retry or workspace fallback', async ({ source, status }) => { diff --git a/frontend-modern/src/components/Settings/__tests__/OrganizationOverviewKeyboard.transport.test.tsx b/frontend-modern/src/components/Settings/__tests__/OrganizationOverviewKeyboard.transport.test.tsx index 8fe890273b..9755c6ec53 100644 --- a/frontend-modern/src/components/Settings/__tests__/OrganizationOverviewKeyboard.transport.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/OrganizationOverviewKeyboard.transport.test.tsx @@ -1,6 +1,6 @@ import { createSignal } from 'solid-js'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@solidjs/testing-library'; import { OrganizationOverviewPanel } from '../OrganizationOverviewPanel'; import { clearApiToken, setOrgID } from '@/utils/apiClient'; import { eventBus } from '@/stores/events'; @@ -26,17 +26,24 @@ let completion: ReturnType>; let savedName: string; let readGate: ReturnType> | undefined; let failRead: boolean; +let detailResponse: ((id: string) => Response) | undefined; +let memberResponse: (() => Response | Promise) | undefined; const requests: { url: string; method: string; options: RequestInit }[] = []; const writes = () => requests.filter((request) => request.method === 'PUT'); const reads = () => requests.filter( (request) => request.method === 'GET' && request.url === '/api/orgs/operations%2Feast', ); +const memberReads = () => requests.filter((request) => request.url.endsWith('/members')); const organization = (id = orgID) => ({ id, displayName: id === orgID ? savedName : 'Operations West', ownerUserId: owner, createdAt: '2026-10-01T10:00:00Z', + members: [ + { userId: owner, role: 'owner', addedAt: '2026-10-01T10:00:00Z' }, + { userId: `${id}-viewer`, role: 'viewer', addedAt: '2026-10-02T10:00:00Z' }, + ], }); const policy = (readOnly = false) => syncSessionPresentationPolicy({ @@ -48,6 +55,8 @@ beforeEach(async () => { completion = deferred(); readGate = undefined; failRead = false; + detailResponse = undefined; + memberResponse = undefined; requests.length = 0; clearApiToken(); setOrgID(orgID); @@ -62,10 +71,10 @@ beforeEach(async () => { return response({ capabilities: ['multi_tenant'], limits: [] }); if (method === 'PUT') return completion.promise; if (readGate) await readGate.promise; - if (url.endsWith('/members')) - return response([{ userId: owner, role: 'owner', addedAt: '' }]); + if (url.endsWith('/members')) return memberResponse?.() ?? response(organization().members); if (failRead) return response({ error: 'Synthetic read unavailable' }, 503); - return response(organization(decodeURIComponent(url.split('/').at(-1)!))); + const id = decodeURIComponent(url.split('/').at(-1)!); + return detailResponse?.(id) ?? response(organization(id)); }), ); await loadRuntimeCapabilities(true); @@ -105,6 +114,95 @@ const rename = async () => { }; const settleFocus = () => new Promise((resolve) => window.setTimeout(resolve, 15)); +describe('Organization Overview selected membership snapshot', () => { + it('shows the saved name, member count and roles from one authorized detail request', async () => { + memberResponse = () => response({ code: 'org_load_failed' }, 500); + const { input } = await open(); + const table = screen.getByRole('table'); + expect(within(table).getByRole('row', { name: /owner@example\.test.*owner/i })).toBeVisible(); + expect( + within(table).getByRole('row', { name: /operations\/east-viewer.*viewer/i }), + ).toBeVisible(); + expect(screen.getByText('Members', { exact: true }).nextElementSibling).toHaveTextContent( + /^2$/, + ); + expect(input).toBeEnabled(); + expect(reads()).toHaveLength(1); + expect(memberReads()).toHaveLength(0); + expect(writes()).toHaveLength(0); + }); + + it.each([ + { members: null }, + { members: {} }, + { members: [null] }, + { members: [{ userId: 'viewer', role: 'owner', addedAt: null }] }, + { members: [{ userId: 'viewer', role: 'unknown', addedAt: '' }] }, + ])( + 'withdraws the complete panel for present malformed membership $members', + async ({ members }) => { + detailResponse = (id) => response({ ...organization(id), members }); + render(() => ); + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Unable to load organization details.', + ); + expect(screen.queryByRole('table')).not.toBeInTheDocument(); + expect(screen.queryByLabelText('Display Name')).not.toBeInTheDocument(); + expect(screen.queryByText('No members found.')).not.toBeInTheDocument(); + expect(memberReads()).toHaveLength(0); + expect(writes()).toHaveLength(0); + }, + ); + + it('verifies an omitted count with the bound list, keeping unread distinct from empty', async () => { + setOrgID('default'); + detailResponse = (id) => response({ id, displayName: 'Default organization' }); + memberResponse = () => response({ code: 'org_load_failed' }, 500); + render(() => ); + expect(await screen.findByRole('alert')).toHaveTextContent('Unable to load organization'); + expect(screen.queryByText('No members found.')).not.toBeInTheDocument(); + expect(screen.queryByLabelText('Display Name')).not.toBeInTheDocument(); + expect(memberReads()).toHaveLength(1); + const request = memberReads()[0]!; + expect(request.url).toBe('/api/orgs/default/members'); + expect(new Headers(request.options.headers).get('X-Pulse-Org-ID')).toBe('default'); + expect(request.options.signal).toBe( + requests.find((read) => read.url === '/api/orgs/default')?.options.signal, + ); + memberResponse = () => response([]); + fireEvent.click(screen.getByRole('button', { name: 'Reload organization' })); + expect(await screen.findByText('No members found.')).toBeVisible(); + expect(screen.getByText('Members', { exact: true }).nextElementSibling).toHaveTextContent( + /^0$/, + ); + expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled(); + expect(memberReads()).toHaveLength(2); + expect(writes()).toHaveLength(0); + }); + + it('discards a late list for an omitted selection after switching workspaces', async () => { + const previousMembers = deferred(); + detailResponse = (id) => + response(id === orgID ? { ...organization(id), members: undefined } : organization(id)); + memberResponse = () => previousMembers.promise; + render(() => ); + await waitFor(() => expect(memberReads()).toHaveLength(1)); + const oldSignal = memberReads()[0]!.options.signal; + expect(oldSignal).toBe(reads()[0]!.options.signal); + setOrgID('operations/west'); + eventBus.emit('org_switched'); + expect(oldSignal?.aborted).toBe(true); + expect(await screen.findByLabelText('Display Name')).toHaveValue('Operations West'); + previousMembers.resolve(response(organization().members)); + await settleFocus(); + expect(screen.getByText('operations/west-viewer')).toBeVisible(); + expect(screen.queryByText('operations/east-viewer')).not.toBeInTheDocument(); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + expect(memberReads()).toHaveLength(1); + expect(writes()).toHaveLength(0); + }); +}); + describe('Organization Overview native submission and keyboard continuation', () => { it('submits the named form once with trimmed text and exact org/CSRF, retaining pending controls', async () => { const { input } = await rename(); diff --git a/frontend-modern/src/components/Settings/__tests__/OrganizationOverviewPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/OrganizationOverviewPanel.test.tsx index 54f59c5ea4..917ab5ccc0 100644 --- a/frontend-modern/src/components/Settings/__tests__/OrganizationOverviewPanel.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/OrganizationOverviewPanel.test.tsx @@ -124,7 +124,7 @@ afterEach(() => { }); describe('OrganizationOverviewPanel', () => { - it('keeps each full saved member ID paired with its own role and added date', async () => { + it('keeps each full ID, role and added date paired within one saved overview', async () => { const members = [ { userId: 'oidc:operations-north:platform-owner@example.test', @@ -147,7 +147,7 @@ describe('OrganizationOverviewPanel', () => { addedAt: '2026-10-07T10:00:00Z', }, ]; - listMembersMock.mockResolvedValue(members); + orgGetMock.mockResolvedValue({ ...baseOrg, members }); renderPanel(); const table = await screen.findByRole('table'); @@ -178,10 +178,11 @@ describe('OrganizationOverviewPanel', () => { ...member, role: member.role === 'viewer' ? 'editor' : member.role, })); - listMembersMock.mockResolvedValue(refreshed); + orgGetMock.mockResolvedValue({ ...baseOrg, members: refreshed }); eventBusEmitMock('organizations_changed'); await expectSavedMembership(refreshed); - expect(listMembersMock).toHaveBeenCalledTimes(2); + expect(orgGetMock).toHaveBeenCalledTimes(2); + expect(listMembersMock).not.toHaveBeenCalled(); expect(updateOrgMock).not.toHaveBeenCalled(); }); diff --git a/frontend-modern/src/components/Settings/__tests__/OrganizationReadLifetimes.test.tsx b/frontend-modern/src/components/Settings/__tests__/OrganizationReadLifetimes.test.tsx index 1a864ffcc2..09b440f6ce 100644 --- a/frontend-modern/src/components/Settings/__tests__/OrganizationReadLifetimes.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/OrganizationReadLifetimes.test.tsx @@ -282,6 +282,7 @@ describe('overview read and rename lifetime', () => { a.resolve(org('org-a')); await settle(); expect(signal.aborted).toBe(true); + expect(mocks.members).not.toHaveBeenCalled(); expect( container.querySelector('[aria-label="Loading organization overview"]'), ).toBeInTheDocument(); diff --git a/frontend-modern/src/components/Settings/__tests__/OrganizationSaveConflict.transport.test.tsx b/frontend-modern/src/components/Settings/__tests__/OrganizationSaveConflict.transport.test.tsx index 2b38c4326f..7d4b5174d1 100644 --- a/frontend-modern/src/components/Settings/__tests__/OrganizationSaveConflict.transport.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/OrganizationSaveConflict.transport.test.tsx @@ -53,6 +53,7 @@ const reads = () => ([url, options]) => (options?.method ?? 'GET') === 'GET' && String(url).startsWith('/api/org'), ); let winning: boolean; +let fixturePanel: Panel; let recovery: Recovery; let completion: ReturnType>; let readGate: ReturnType> | undefined; @@ -183,7 +184,9 @@ async function expectWinningSnapshot(panel: Panel) { if (panel === 'overview') { expect(await screen.findByLabelText('Display Name')).toHaveValue(winningName); expect(screen.queryByDisplayValue('Refused stale name')).not.toBeInTheDocument(); - expect(screen.getByText(nextOwner)).toBeInTheDocument(); + expectOverviewMemberRole(user, 'admin'); + expectOverviewMemberRole(memberID, 'editor'); + expectOverviewMemberRole(nextOwner, 'owner'); expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled(); } else if (panel === 'access') { expect(await screen.findByRole('combobox', { name: `Role for ${memberID}` })).toHaveValue( @@ -205,6 +208,10 @@ async function expectWinningSnapshot(panel: Panel) { expect(shareRemoveButton()).toBeEnabled(); } } +function expectOverviewMemberRole(member: string, role: string) { + const row = screen.getByText(member).closest('tr')!; + expect(within(row).getByText(role)).toBeInTheDocument(); +} async function deliberatelyChangeCurrent(panel: Panel) { if (panel === 'overview') { fireEvent.input(screen.getByLabelText('Display Name'), { @@ -251,6 +258,7 @@ beforeEach(async () => { syncSessionPresentationPolicy(null); document.cookie = `pulse_csrf=${csrf}; Path=/`; winning = false; + fixturePanel = 'overview'; recovery = 'manager'; completion = deferred(); readGate = undefined; @@ -286,7 +294,14 @@ beforeEach(async () => { if (readGate) await readGate.promise; if (winning && recovery === 'denied') return json({ error: 'Forbidden', code: 'forbidden' }, 403); - if (path === orgPath) return json(organization()); + if (path === orgPath) { + const detail = organization(); + // An embedded array is already complete. Exercise a required list + // refusal only after the selected detail omits that array. + if (fixturePanel === 'overview' && winning && recovery === 'partial') + delete detail.members; + return json(detail); + } if (path === `${orgPath}/members`) return winning && recovery === 'partial' ? json({ error: 'Synthetic saved members unavailable' }, 503) @@ -327,9 +342,11 @@ describe('organization save conflict recovery through real controls and transpor it.each(panels.flatMap((panel) => recoveries.map((next) => ({ panel, next }))))( 'reloads the winning $next snapshot after a refused $panel change, without replay or restored grants', async ({ panel, next }) => { + fixturePanel = panel; recovery = next; await openAndSubmit(panel); const originalReads = reads().length; + if (panel === 'overview') expect(reads().map(([path]) => path)).toEqual([orgPath]); // Another operation won on the server. The refused request has not // changed this fixture and must never be merged into it by the client. winning = true; @@ -375,6 +392,9 @@ describe('organization save conflict recovery through real controls and transpor expect(screen.queryByLabelText('Member user ID')).not.toBeInTheDocument(); if (panel === 'overview') { expect(screen.getByLabelText('Display Name')).toHaveValue(winningName); + expectOverviewMemberRole(user, 'viewer'); + expectOverviewMemberRole(memberID, 'editor'); + expectOverviewMemberRole(nextOwner, 'owner'); expect(screen.getByLabelText('Display Name')).toBeDisabled(); expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled(); fireEvent.click(screen.getByRole('button', { name: 'Save' })); @@ -390,7 +410,7 @@ describe('organization save conflict recovery through real controls and transpor } const recoveryPaths = panel === 'overview' - ? [orgPath, `${orgPath}/members`] + ? [orgPath, ...(next === 'partial' ? [`${orgPath}/members`] : [])] : panel === 'sharing' ? [ orgPath, @@ -409,12 +429,11 @@ describe('organization save conflict recovery through real controls and transpor ]; // Viewer recovery must not even request the manager-only pending list. // Exact paths also catch a repeated read or fallback to another tenant. - expect( - reads() - .slice(originalReads) - .map(([path]) => String(path)) - .sort(), - ).toEqual(recoveryPaths.sort()); + const actualPaths = reads() + .slice(originalReads) + .map(([path]) => String(path)); + if (panel === 'overview') expect(actualPaths).toEqual(recoveryPaths); + else expect(actualPaths.sort()).toEqual(recoveryPaths.sort()); expect(writes()).toHaveLength(1); expect(notices.success).not.toHaveBeenCalled(); expectBoundRequests(); diff --git a/frontend-modern/src/components/Settings/__tests__/OrganizationSharingCreate.transport.test.tsx b/frontend-modern/src/components/Settings/__tests__/OrganizationSharingCreate.transport.test.tsx index 4c0ed0cb84..82ebd6b421 100644 --- a/frontend-modern/src/components/Settings/__tests__/OrganizationSharingCreate.transport.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/OrganizationSharingCreate.transport.test.tsx @@ -603,6 +603,7 @@ describe('rendered Create Share controls through the real transport', () => { .some((row) => within(row).queryByText(`vm:${selectedResourceID}`)), ).toBe(false); } + await screen.findByRole('heading', { name: 'Create Share' }); expect(targetInput()).toHaveAccessibleDescription(`${target.displayName} · ID: ${target.id}`); expect(resourceInput()).toHaveAccessibleDescription( `Resource: Namesake workload · vm:${selectedResourceID}`, @@ -739,6 +740,7 @@ describe('Create Share through real capability withdrawal', () => { await waitFor(() => expect(inventoryReads()).toHaveLength(10)); await screen.findByRole('heading', { name: 'Outgoing Shares' }); expectSavedGrant('quick pick', 'editor'); + await screen.findByRole('heading', { name: 'Create Share' }); fillForm('manual entry', 'admin'); fireEvent.input(screen.getByLabelText('Resource ID'), { target: { value: 'current::draft/independent' }, diff --git a/frontend-modern/src/components/Settings/__tests__/OrganizationSharingPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/OrganizationSharingPanel.test.tsx index 1d0b470308..0028d53d40 100644 --- a/frontend-modern/src/components/Settings/__tests__/OrganizationSharingPanel.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/OrganizationSharingPanel.test.tsx @@ -605,6 +605,39 @@ describe('OrganizationSharingPanel', () => { }); describe('selected sharing snapshot', () => { + it('keeps verified identity and outgoing rows visible without enabling a write from an incomplete list', async () => { + const unread = Object.assign(new Error('unread peer'), { status: 500, code: 'list_failed' }); + listOrgsMock.mockRejectedValueOnce(unread); + listIncomingSharesMock.mockRejectedValueOnce(unread); + listSharesMock.mockResolvedValue([outgoing]); + renderPanel(); + + await screen.findByText('Incoming shares could not be loaded.'); + expect(screen.getByText(baseOrg.displayName)).toBeInTheDocument(); + expect(screen.getByText(outgoing.resourceName)).toBeInTheDocument(); + expect( + screen.queryByText('No incoming shares from other organizations.'), + ).not.toBeInTheDocument(); + const form = await screen.findByRole('form', { name: 'Create Share' }); + const recipient = within(form).getByRole('combobox', { name: 'Target Organization' }); + expect(recipient).toBeDisabled(); + expect(recipient).toHaveValue(''); + expect( + within(recipient).getByRole('option', { name: 'Organization list unavailable' }), + ).toBeInTheDocument(); + expect(within(form).getByRole('combobox', { name: 'Access Role' })).toBeDisabled(); + expect(within(form).getByRole('button', { name: 'Create Share' })).toBeDisabled(); + expect(screen.getByRole('button', { name: /^Remove share of / })).toBeDisabled(); + fireEvent.submit(form); + expect(createShareMock).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole('button', { name: 'Reload sharing' })); + await screen.findByText('No incoming shares from other organizations.'); + expect(screen.getByRole('button', { name: /^Remove share of / })).toBeEnabled(); + expect(await screen.findByRole('combobox', { name: 'Target Organization' })).toHaveValue(''); + expect(deleteShareMock).not.toHaveBeenCalled(); + }); + it('does not expose previous-org shares or controls after a failed switch', async () => { listSharesMock.mockResolvedValue([ { diff --git a/frontend-modern/src/components/Settings/__tests__/OrganizationSharingTransport.test.tsx b/frontend-modern/src/components/Settings/__tests__/OrganizationSharingTransport.test.tsx index 5d7a1173be..765451cf10 100644 --- a/frontend-modern/src/components/Settings/__tests__/OrganizationSharingTransport.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/OrganizationSharingTransport.test.tsx @@ -84,6 +84,7 @@ let incomingInventory: IncomingOrganizationShare[]; let healthReply: () => Promise; let writeReply: (url: string, options: RequestInit) => Promise; let failedRead: string | undefined; +let failedLists: string[]; function apply(operation: Operation) { if (operation === 'create') @@ -174,6 +175,7 @@ beforeEach(() => { outgoingInventory = [outgoing]; incomingInventory = [incoming]; failedRead = undefined; + failedLists = []; healthReply = async () => { document.cookie = `pulse_csrf=${csrfToken}; Path=/`; return json({}); @@ -185,6 +187,7 @@ beforeEach(() => { if (url === '/api/health' && method === 'GET') return healthReply(); if (method !== 'GET') return writeReply(url, options); if (url === failedRead) return json({ error: 'synthetic-unavailable' }, 503); + if (failedLists.includes(url)) return json({ code: 'list_failed' }, 500); if (url === '/api/orgs') return json([north, south]); for (const organization of [north, south]) { const base = orgPath(organization.id); @@ -341,25 +344,79 @@ describe('organization sharing through the real transport', () => { }, ); - it.each(readPaths(north.id))('rejects the whole sharing snapshot when %s fails', async (path) => { - failedRead = path; - const { state } = mount(); - await waitFor(() => expect(state.loading()).toBe(false)); - expect(state.loadError()).toBeTruthy(); - expect(state.org()).toBeNull(); - expect(state.outgoingShares()).toEqual([]); - expect(state.incomingShares()).toEqual([]); - expect(state.canManageCurrentOrg()).toBe(false); - expect(state.canCreateShare()).toBe(false); - expect(reads()).toHaveLength(5); - for (const [, options] of reads()) { - expectSessionRequest(options); - expect(options?.signal?.aborted).toBe(true); - } - for (const operation of operations) await confirm(state, operation); - expect(writes()).toHaveLength(0); - expect(getOrgID()).toBe(north.id); - }); + it.each(readPaths(north.id))( + 'rejects the whole sharing snapshot when %s returns an unrelated failure', + async (path) => { + failedRead = path; + const { state } = mount(); + await waitFor(() => expect(state.loading()).toBe(false)); + expect(state.loadError()).toBeTruthy(); + expect(state.org()).toBeNull(); + expect(state.outgoingShares()).toEqual([]); + expect(state.incomingShares()).toEqual([]); + expect(state.canManageCurrentOrg()).toBe(false); + expect(state.canCreateShare()).toBe(false); + expect(reads()).toHaveLength(5); + for (const [, options] of reads()) { + expectSessionRequest(options); + expect(options?.signal?.aborted).toBe(true); + } + for (const operation of operations) await confirm(state, operation); + expect(writes()).toHaveLength(0); + expect(getOrgID()).toBe(north.id); + }, + ); + + it.each(['directory', 'incoming', 'both'] as const)( + 'keeps the verified current selection but pauses every change when %s cannot enumerate', + async (failed) => { + const { state } = await prepared(); + const directory = failed !== 'incoming'; + const onlyIncoming = failed !== 'directory'; + failedLists = [ + ...(directory ? ['/api/orgs'] : []), + ...(onlyIncoming ? [`${orgPath(north.id)}/shares/incoming`] : []), + ]; + await state.loadSharingData(); + expect(state.org()?.id).toBe(north.id); + expect(state.canManageCurrentOrg()).toBe(true); + expect(state.sharingChangesPaused()).toBe(true); + expect(state.unavailableLists()).toEqual({ directory, incoming: onlyIncoming }); + expect(state.outgoingShares()).toEqual(outgoingInventory); + expect(state.incomingShares()).toEqual(onlyIncoming ? [] : incomingInventory); + expect(state.canCreateShare()).toBe(false); + for (const operation of operations) await confirm(state, operation); + expect(writes()).toHaveLength(0); + expect(fetchMock.mock.calls.filter(([url]) => url === '/api/health')).toHaveLength(0); + expect(reads().map(([url]) => url)).toEqual([...readPaths(north.id), ...readPaths(north.id)]); + for (const [, options] of reads()) expectSessionRequest(options); + + failedLists = []; + await state.loadSharingData(); + await accepted(state); + expect(state.sharingChangesPaused()).toBe(false); + expect(state.targetOrgId()).toBe(draft.targetOrgId); + expect(state.canCreateShare()).toBe(true); + expect(writes()).toHaveLength(0); + expect(getOrgID()).toBe(north.id); + }, + ); + + it.each([orgPath(north.id), `${orgPath(north.id)}/members`, `${orgPath(north.id)}/shares`])( + 'does not mistake selected read %s for an aggregate or keep any old rows', + async (failed) => { + const { state } = await prepared(); + failedLists = ['/api/orgs', failed]; + await state.loadSharingData(); + expect(state.loadError()).toBeTruthy(); + expect(state.org()).toBeNull(); + expect(state.outgoingShares()).toEqual([]); + expect(state.canManageCurrentOrg()).toBe(false); + for (const operation of operations) await confirm(state, operation); + expect(writes()).toHaveLength(0); + expect(getOrgID()).toBe(north.id); + }, + ); it.each(operations)( 'ignores a late %s confirmation after selecting a different organization', diff --git a/frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts b/frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts index 58bfc2d1c3..825a4869dd 100644 --- a/frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts +++ b/frontend-modern/src/components/Settings/useOrganizationBillingPanelState.ts @@ -12,6 +12,7 @@ import { getOrganizationBillingLicenseStatusLabel, } from '@/utils/licensePresentation'; import { getOrganizationSettingsLoadErrorMessage } from '@/utils/organizationSettingsPresentation'; +import { readOrganizationAggregate } from '@/utils/orgUtils'; import { buildHostedCommercialPlanModel, buildHostedCommercialUsageModel, @@ -33,7 +34,7 @@ export function useOrganizationBillingPanelState(props: OrganizationBillingPanel const [loading, setLoading] = createSignal(true); const [loadError, setLoadError] = createSignal(null); const [status, setStatus] = createSignal(null); - const [orgCount, setOrgCount] = createSignal(0); + const [orgCount, setOrgCount] = createSignal(); const [memberCount, setMemberCount] = createSignal(0); const activeOrgID = () => normalizeOrgScope(getOrgID()); @@ -87,7 +88,7 @@ export function useOrganizationBillingPanelState(props: OrganizationBillingPanel batch(() => { setSelectedOrgID(orgId); setStatus(null); - setOrgCount(0); + setOrgCount(undefined); setMemberCount(0); setLoadError(null); setLoading(isBillingAvailable()); @@ -105,7 +106,7 @@ export function useOrganizationBillingPanelState(props: OrganizationBillingPanel try { const [licenseStatus, orgs, members] = await Promise.all([ LicenseAPI.getStatus(options), - OrgsAPI.list(options), + readOrganizationAggregate(OrgsAPI.list(options)), OrgsAPI.listMembers(orgId, options), ]); if (!isCurrent()) return; @@ -113,14 +114,14 @@ export function useOrganizationBillingPanelState(props: OrganizationBillingPanel !licenseStatus || typeof licenseStatus.valid !== 'boolean' || typeof licenseStatus.tier !== 'string' || - !Array.isArray(orgs) || + (orgs !== undefined && !Array.isArray(orgs)) || !Array.isArray(members) ) { throw new Error('Organization billing returned invalid data'); } batch(() => { setStatus(licenseStatus); - setOrgCount(orgs.length); + setOrgCount(orgs?.length); setMemberCount(members.length); }); } catch (error) { @@ -129,7 +130,7 @@ export function useOrganizationBillingPanelState(props: OrganizationBillingPanel setLoadError(getOrganizationSettingsLoadErrorMessage('', 'billing')); } finally { if (!disposed && request === generation) { - // Stop sibling reads too when just one Promise.all member failed. + // Stop sibling reads after a fatal failure. controller.abort(); readController = undefined; setLoading(false); @@ -155,6 +156,7 @@ export function useOrganizationBillingPanelState(props: OrganizationBillingPanel return { commercialPlanModel, commercialUsageModel, + organizationCountUnavailable: () => status() !== null && orgCount() === undefined, isBillingAvailable, loading, loadError, diff --git a/frontend-modern/src/components/Settings/useOrganizationOverviewPanelState.ts b/frontend-modern/src/components/Settings/useOrganizationOverviewPanelState.ts index eccebae872..261425143a 100644 --- a/frontend-modern/src/components/Settings/useOrganizationOverviewPanelState.ts +++ b/frontend-modern/src/components/Settings/useOrganizationOverviewPanelState.ts @@ -23,6 +23,24 @@ interface OrganizationOverviewPanelProps { currentUser?: string; } +const isMemberList = (value: unknown): value is OrganizationMember[] => + Array.isArray(value) && + value.every( + (member: unknown) => + typeof member === 'object' && + member !== null && + 'userId' in member && + typeof member.userId === 'string' && + member.userId.trim() !== '' && + 'role' in member && + (member.role === 'owner' || + member.role === 'admin' || + member.role === 'editor' || + member.role === 'viewer') && + 'addedAt' in member && + typeof member.addedAt === 'string', + ); + export function useOrganizationOverviewPanelState(props: OrganizationOverviewPanelProps) { const [loading, setLoading] = createSignal(true); const [loadError, setLoadError] = createSignal(null); @@ -90,13 +108,19 @@ export function useOrganizationOverviewPanelState(props: OrganizationOverviewPan readController = controller; const options = { expectedOrgID: orgId, signal: controller.signal, retry: false as const }; try { - const [orgData, memberData] = await Promise.all([ - OrgsAPI.get(orgId, options), - OrgsAPI.listMembers(orgId, options), - ]); + const orgData = await OrgsAPI.get(orgId, options); if (!isCurrent()) return; - if (!orgData || orgData.id !== orgId || !Array.isArray(memberData)) { - throw new Error('Organization overview returned invalid data for the selection'); + if (!orgData || orgData.id !== orgId) { + throw new Error('Organization overview returned a different selection'); + } + // An embedded list is the same authorized snapshot as the other details. + // Omission is ambiguous (the server omits an empty list); only then use + // the dedicated read to distinguish a verified empty list from no data. + const memberData = + orgData.members === undefined ? await OrgsAPI.listMembers(orgId, options) : orgData.members; + if (!isCurrent()) return; + if (!isMemberList(memberData)) { + throw new Error('Organization overview returned an invalid member list'); } batch(() => { setOrg(orgData); diff --git a/frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts b/frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts index 51b08700cd..1c102cd7f1 100644 --- a/frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts +++ b/frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts @@ -42,7 +42,7 @@ import { getOrganizationSettingsLoadErrorMessage, ORGANIZATION_SHARING_UNCONFIRMED_CHANGE_MESSAGE, } from '@/utils/organizationSettingsPresentation'; -import { canManageOrg } from '@/utils/orgUtils'; +import { canManageOrg, readOrganizationAggregate } from '@/utils/orgUtils'; interface OrganizationSharingPanelProps { currentUser?: string; @@ -62,6 +62,10 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanel const [orgs, setOrgs] = createSignal([]); const [outgoingShares, setOutgoingShares] = createSignal([]); const [incomingShares, setIncomingShares] = createSignal([]); + const [unavailableLists, setUnavailableLists] = createSignal<{ + directory: boolean; + incoming: boolean; + }>(); const [targetOrgId, setTargetOrgId] = createSignal(''); const [resourceType, setResourceType] = createSignal(''); const [resourceId, setResourceId] = createSignal(''); @@ -98,7 +102,9 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanel !presentationPolicyIsReadOnly() && canManageOrg(org(), props.currentUser), ); - const canChangeSharing = () => hasCurrentSharing() && canManageCurrentOrg() && !saving(); + const sharingChangesPaused = () => unavailableLists() !== undefined; + const canChangeSharing = () => + hasCurrentSharing() && canManageCurrentOrg() && !sharingChangesPaused() && !saving(); const { resources } = useResources(); const targetOrgOptions = createMemo(() => @@ -172,6 +178,7 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanel setOrgs([]); setOutgoingShares([]); setIncomingShares([]); + setUnavailableLists(undefined); }; const clearDraft = () => { targetOrgNeedsReselection = false; @@ -224,32 +231,38 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanel retry: false, }; try { - // Publish one accepted snapshot, never a new org with old share rows (or - // a partial read presented as an empty share list). + // Publish only current, verified data. A failed aggregate can leave the + // selected scope readable, but not authorize a write or imply zero rows. const [orgData, memberData, allOrgs, outgoing, incoming] = await Promise.all([ OrgsAPI.get(orgId, options), OrgsAPI.listMembers(orgId, options), - OrgsAPI.list(options), + readOrganizationAggregate(OrgsAPI.list(options)), OrgsAPI.listShares(orgId, options), - OrgsAPI.listIncomingShares(orgId, options), + readOrganizationAggregate(OrgsAPI.listIncomingShares(orgId, options)), ]); if (!isCurrent()) return; if ( !orgData || orgData.id !== orgId || !Array.isArray(memberData) || - !Array.isArray(allOrgs) || + (allOrgs !== undefined && !Array.isArray(allOrgs)) || !Array.isArray(outgoing) || - !Array.isArray(incoming) || - incoming.some((share) => share.targetOrgId !== orgId) + (incoming !== undefined && + (!Array.isArray(incoming) || incoming.some((share) => share.targetOrgId !== orgId))) ) { throw new Error('Organization sharing returned an invalid selection'); } batch(() => { setOrg({ ...orgData, members: memberData }); - setOrgs(allOrgs); + setOrgs(allOrgs ?? []); setOutgoingShares(outgoing); - setIncomingShares(incoming); + setIncomingShares(incoming ?? []); + if (!allOrgs || !incoming) { + setUnavailableLists({ directory: !allOrgs, incoming: !incoming }); + } + // An unread directory neither verifies nor withdraws an explicit draft + // recipient. Recheck it when a complete directory is read. + if (!allOrgs) return; const draftTarget = targetOrgId().trim(); // If a previously chosen destination disappeared, require a new choice // rather than retaining an invisible value or choosing a different org. @@ -529,6 +542,8 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanel targetOrgOptions, toggleManualEntry, unifiedResourceOptions, + unavailableLists, + sharingChangesPaused, updateResourceId, updateResourceName, updateResourceType, diff --git a/frontend-modern/src/features/alerts/AlertOverviewActiveAlertsSection.tsx b/frontend-modern/src/features/alerts/AlertOverviewActiveAlertsSection.tsx index 3b472d674b..4207847129 100644 --- a/frontend-modern/src/features/alerts/AlertOverviewActiveAlertsSection.tsx +++ b/frontend-modern/src/features/alerts/AlertOverviewActiveAlertsSection.tsx @@ -27,9 +27,11 @@ function pmgMessageAgeScope(alert: Alert): 'gateway' | 'node' | undefined { return undefined; } // The PMG evaluator uses the gateway resource for both readings. The - // canonical spec, not the alert text or the node display name, names scope. - if (alert.canonicalSpecId === `${alert.resourceId}-oldest-message`) return 'gateway'; - if (alert.node && alert.canonicalSpecId === `${alert.resourceId}-${alert.node}-oldest-message`) { + // canonical spec names scope. REST sends it at the top level; connected + // state retains the same identifier in metadata. + const specId = alert.canonicalSpecId ?? alert.metadata.canonicalSpecID; + if (specId === `${alert.resourceId}-oldest-message`) return 'gateway'; + if (alert.node && specId === `${alert.resourceId}-${alert.node}-oldest-message`) { return 'node'; } return undefined; diff --git a/frontend-modern/src/features/alerts/__tests__/OverviewTab.pmgMessageAge.test.tsx b/frontend-modern/src/features/alerts/__tests__/OverviewTab.pmgMessageAge.test.tsx index c941a21038..008874009d 100644 --- a/frontend-modern/src/features/alerts/__tests__/OverviewTab.pmgMessageAge.test.tsx +++ b/frontend-modern/src/features/alerts/__tests__/OverviewTab.pmgMessageAge.test.tsx @@ -46,6 +46,12 @@ const peer: Alert = { startTime: '2026-11-18T12:01:00Z', }; +// BuildFrontendState's compact models.Alert retains metadata, not the REST +// top-level field. Whole-snapshot updates can supersede REST-shaped rows. +function connectedShape({ canonicalSpecId, ...alert }: Alert): Alert { + return { ...alert, metadata: { ...alert.metadata, canonicalSpecID: canonicalSpecId } }; +} + function renderOverview(...alerts: Alert[]) { const index = (rows: Alert[]) => Object.fromEntries(rows.map((alert) => [alert.id, alert])); const [activeAlerts, setActiveAlerts] = createSignal(index(alerts)); @@ -69,6 +75,22 @@ function renderOverview(...alerts: Alert[]) { describe('OverviewTab PMG message age', () => { afterEach(cleanup); + function expectPair(lead: Alert, companion: Alert, companionLabel: string) { + const leadCard = screen.getByText(lead.message).closest('[id^="alert-"]')!; + const secondaryCard = screen + .getByText(companion.message) + .closest('[id^="alert-"]')!; + expect(leadCard.id).toBe(`alert-${lead.id}`); + expect(secondaryCard.id).toBe(`alert-${companion.id}`); + expect( + leadCard.compareDocumentPosition(secondaryCard) & Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + expect(within(secondaryCard).getByText(companionLabel)).toBeInTheDocument(); + expect(screen.getAllByRole('button', { name: 'Acknowledge' })).toHaveLength(2); + expect(screen.getAllByRole('button', { name: 'Acknowledge all (2)' })).toHaveLength(2); + expect(screen.queryByRole('button', { name: '+1 related' })).not.toBeInTheDocument(); + } + it.each([ { lead: peer, companion: gateway, label: 'Gateway-wide' }, { @@ -78,14 +100,39 @@ describe('OverviewTab PMG message age', () => { }, ])('keeps both scope readings when $lead.canonicalSpecId leads', ({ lead, companion, label }) => { renderOverview(lead, companion); + expectPair(lead, companion, label); + }); - expect(screen.getByText(lead.message).closest('[id^="alert-"]')?.id).toBe(`alert-${lead.id}`); - const secondaryCard = screen.getByText(companion.message).closest('[id^="alert-"]')!; - expect(secondaryCard.id).toBe(`alert-${companion.id}`); - expect(within(secondaryCard as HTMLElement).getByText(label)).toBeInTheDocument(); - expect(screen.getAllByRole('button', { name: 'Acknowledge' })).toHaveLength(2); - expect(screen.getAllByRole('button', { name: 'Acknowledge all (2)' })).toHaveLength(2); - expect(screen.queryByRole('button', { name: '+1 related' })).not.toBeInTheDocument(); + it('shows both readings in a cold connected snapshot, with the later peer still leading', () => { + renderOverview(connectedShape(gateway), connectedShape(peer)); + expectPair(peer, gateway, 'Gateway-wide'); + }); + + it('keeps both readings when connected updates replace REST rows', () => { + const page = renderOverview(gateway, peer); + expectPair(peer, gateway, 'Gateway-wide'); + + page.replace(connectedShape(gateway), connectedShape(peer)); + expectPair(peer, gateway, 'Gateway-wide'); + }); + + it('takes the REST identifier when present, even if metadata disagrees', () => { + renderOverview( + { ...gateway, metadata: { ...gateway.metadata, canonicalSpecID: peer.canonicalSpecId } }, + { ...peer, metadata: { ...peer.metadata, canonicalSpecID: gateway.canonicalSpecId } }, + ); + expectPair(peer, gateway, 'Gateway-wide'); + }); + + it('does not infer an identifier from the message, display name, or malformed metadata', () => { + renderOverview( + { ...connectedShape(gateway), metadata: { ...gateway.metadata, canonicalSpecID: {} } }, + connectedShape(peer), + ); + expect(screen.getByText(peer.message)).toBeInTheDocument(); + expect(screen.queryByText(gateway.message)).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: '+1 related' })); + expect(screen.getByText(gateway.message)).toBeInTheDocument(); }); it('does not surface acknowledged or closed incidents excluded by the current view', () => { diff --git a/frontend-modern/src/utils/commercialBillingModel.ts b/frontend-modern/src/utils/commercialBillingModel.ts index bcd7c67c60..a2d0b5f70d 100644 --- a/frontend-modern/src/utils/commercialBillingModel.ts +++ b/frontend-modern/src/utils/commercialBillingModel.ts @@ -36,7 +36,7 @@ export interface HostedCommercialModelInput { status?: Pick | null; tierLabel: string; licenseStatusLabel: string; - organizationCount: number; + organizationCount: number | undefined; memberCount: number; nodeUsage: number; guestUsage: number; @@ -124,7 +124,7 @@ export const buildHostedCommercialPlanModel = ( }, { label: 'Organizations', - value: input.organizationCount, + value: input.organizationCount ?? 'Unavailable', }, { label: 'Members (Current Org)', diff --git a/frontend-modern/src/utils/orgUtils.ts b/frontend-modern/src/utils/orgUtils.ts index c4c5ebf9cc..989915ee81 100644 --- a/frontend-modern/src/utils/orgUtils.ts +++ b/frontend-modern/src/utils/orgUtils.ts @@ -20,6 +20,24 @@ export const canManageOrg = (org: Organization | null, currentUser?: string): bo return role === 'admin' || role === 'owner'; }; +// The directory and the incoming-share scan can fail to enumerate a peer even +// when the selected organization is healthy. Only the server's explicit list +// failure is a readable-but-incomplete snapshot, not denial or malformed JSON. +export function readOrganizationAggregate(request: Promise): Promise { + return request.catch((error: unknown) => { + if ( + error instanceof Error && + 'status' in error && + error.status === 500 && + 'code' in error && + error.code === 'list_failed' + ) { + return undefined; + } + throw error; + }); +} + export const roleBadgeClass = (role: string): string => { return roleBadgeClasses[role as OrganizationRole] ?? defaultBadgeClass; };