Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Keep organization sharing bound to the selected read
pulse-triage[bot]e0a1fc5f16d0
diff --git a/frontend-modern/browser-verification/ec9dfc2a02d82ff8.json b/frontend-modern/browser-verification/ec9dfc2a02d82ff8.jsonnew file mode 100644index 0000000000..1265a7ae7f--- /dev/null+++ b/frontend-modern/browser-verification/ec9dfc2a02d82ff8.json@@ -0,0 +1,72 @@+{+ "version": 1,+ "base_sha": "c3693ddd0eb4957476e1c7678104f78e2a8fc6eb",+ "verified_at": "2026-10-31T19:30:15.163Z",+ "result": "passed",+ "changed_paths": [+ "frontend-modern/src/api/orgs.ts",+ "frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx",+ "frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx",+ "frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts",+ "frontend-modern/src/utils/organizationSettingsPresentation.ts"+ ],+ "content_sha256": {+ "frontend-modern/src/api/orgs.ts": "ecffe2e19003d75d01d7d926427bc0bfed24655b62b561bb698c72e75cbb72ee",+ "frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx": "626cc1966a57082881e0aaec468684d92c070f9179aa370bf056ce25d4d7d5ea",+ "frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx": "2d2cd583fe36ee43ed57c5904001b04185a5292ded7049cc7e438fb4c378c56c",+ "frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts": "54304acd62d391eb8c713e5869ffa9e6791e7d4b0c8252f12e8c96bf8ef6ae21",+ "frontend-modern/src/utils/organizationSettingsPresentation.ts": "423579376089ce984f8381a5fa51bfcac30bf9741801f83af279175e06820b61"+ },+ "routes": [+ "Existing Organization Sharing settings: production panel, state owner, OrgsAPI/client, unified resource hook and real stylesheet with local synthetic HTTP/WS producers"+ ],+ "viewports": [+ {+ "width": 1440,+ "height": 1050+ },+ {+ "width": 320,+ "height": 900+ }+ ],+ "states": [+ "Selected sharing unavailable, never previous-org or false-empty sharing",+ "Pending read-only reload",+ "Accepted current sharing and accepted empty lists",+ "Unconfirmed change requires read reconciliation",+ "Read-only and non-manager sessions without change controls",+ "Interrupted writes and obsolete reads cannot replace the current selection",+ "Disappeared quick pick cannot turn into an implicit manual share"+ ],+ "interactions": [+ "Keyboard/touch read retry, same-selection draft preservation and peer draft clearing",+ "Explicit create/outgoing remove/incoming accept/accepted removal/pending decline through real grid rows",+ "HTTP 403 mutation is not retried or redirected; reload is read-only",+ "Switch org during pending read/write, user change, capability loss/return and explicit default scope",+ "Real unified-resource snapshot removal shows the selected-resource warning and disables create"+ ],+ "browsers": [+ {+ "engine": "Chromium",+ "version": "141.0.7390.37"+ },+ {+ "engine": "WebKit",+ "version": "26.0"+ }+ ],+ "playwright_version": "1.56.1",+ "checks": 53,+ "captures": 16,+ "pixel_review": "All 16 captures opened with native view_image. Inline copy and controls are legible at 320px; existing grids retain horizontal scrolling. Toast overlay limitations are recorded separately.",+ "evidence": [+ "RECEIPTS.md",+ "BROWSER-SUMMARY.json",+ "PIXEL-REVIEW.json",+ "CURRENT.tar.xz",+ "first-captures/browser-result.json",+ "remaining-captures/browser-result.json"+ ],+ "limitations": "Safe fixtures, not a hosted private install, native SSO recovery, published release or customer acceptance. First fixture touch-context failure remains retained; only remaining proof was executed afterwards."+}diff --git a/frontend-modern/src/api/__tests__/orgs.access.test.ts b/frontend-modern/src/api/__tests__/orgs.access.test.tsindex ea4a0a96f2..b573592b8d 100644--- a/frontend-modern/src/api/__tests__/orgs.access.test.ts+++ b/frontend-modern/src/api/__tests__/orgs.access.test.ts@@ -9,6 +9,58 @@ const accessRequests: {path: string;method: string;}[] = [+ {+ name: 'organization directory',+ run: (options) => OrgsAPI.list(options),+ path: '/api/orgs',+ method: 'GET',+ },+ {+ name: 'outgoing shares',+ run: (options) => OrgsAPI.listShares('org/a', options),+ path: '/api/orgs/org%2Fa/shares',+ method: 'GET',+ },+ {+ name: 'incoming shares',+ run: (options) => OrgsAPI.listIncomingShares('org/a', options),+ path: '/api/orgs/org%2Fa/shares/incoming',+ method: 'GET',+ },+ {+ name: 'create share',+ run: (options) =>+ OrgsAPI.createShare(+ 'org/a',+ {+ targetOrgId: 'org-b',+ resourceType: 'vm',+ resourceId: 'opaque::id',+ accessRole: 'viewer',+ },+ options,+ ),+ path: '/api/orgs/org%2Fa/shares',+ method: 'POST',+ },+ {+ name: 'delete share',+ run: (options) => OrgsAPI.deleteShare('org/a', 'share/b', options),+ path: '/api/orgs/org%2Fa/shares/share%2Fb',+ method: 'DELETE',+ },+ {+ name: 'accept share',+ run: (options) => OrgsAPI.acceptIncomingShare('org/a', 'share/b', options),+ path: '/api/orgs/org%2Fa/shares/incoming/share%2Fb/accept',+ method: 'POST',+ },+ {+ name: 'decline share',+ run: (options) => OrgsAPI.declineIncomingShare('org/a', 'share/b', options),+ path: '/api/orgs/org%2Fa/shares/incoming/share%2Fb',+ method: 'DELETE',+ },{name: 'organization',run: (options) => OrgsAPI.get('org/a', options),@@ -116,20 +168,23 @@ describe('Organization Access strict transport', () => {},);- it.each([400, 403, 429])(- 'does not replay an access mutation or change selection after HTTP %i',- async (status) => {- mockFetch.mockResolvedValue(- new Response(JSON.stringify({ error: 'invalid_org' }), {- status,- headers: { 'X-CSRF-Token': 'new-csrf', 'Retry-After': '1' },- }),+ describe.each(accessRequests.filter((request) => request.method !== 'GET'))(+ '$name refusal',+ ({ run }) => {+ it.each([400, 403, 429])(+ 'does not replay or change selection after HTTP %i',+ async (status) => {+ mockFetch.mockResolvedValue(+ new Response(JSON.stringify({ error: 'invalid_org' }), {+ status,+ headers: { 'X-CSRF-Token': 'new-csrf', 'Retry-After': '1' },+ }),+ );+ await expect(run(options())).rejects.toThrow();+ expect(mockFetch).toHaveBeenCalledTimes(1);+ expect(getOrgID()).toBe('org-a');+ },);- await expect(- OrgsAPI.inviteMember('org-a', { userId: 'new-user', role: 'viewer' }, options()),- ).rejects.toThrow();- expect(mockFetch).toHaveBeenCalledTimes(1);- expect(getOrgID()).toBe('org-a');},);diff --git a/frontend-modern/src/api/orgs.ts b/frontend-modern/src/api/orgs.tsindex 529f647c20..b2153608ad 100644--- a/frontend-modern/src/api/orgs.ts+++ b/frontend-modern/src/api/orgs.ts@@ -61,7 +61,7 @@ export interface IncomingOrganizationShare extends OrganizationShare {sourceOrgName: string;}-// Organization Access can bind an explicit read or change to the selection+// Organization panels can bind an explicit read or change to the selection// that produced it, including the pre-dispatch CSRF wait. Other callers keep// their existing transport behaviour unless they opt in.export interface OrganizationAccessRequestOptions {@@ -71,10 +71,11 @@ export interface OrganizationAccessRequestOptions {}export const OrgsAPI = {- list: () =>+ list: (options?: OrganizationAccessRequestOptions) =>apiFetchJSON<Organization[]>('/api/orgs', {preferSessionAuth: true,skipOrgContext: true,+ ...options,}),create: (payload: { id: string; displayName: string }) =>@@ -195,38 +196,42 @@ export const OrgsAPI = {},),- listShares: (id: string) =>+ listShares: (id: string, options?: OrganizationAccessRequestOptions) =>apiFetchJSON<OrganizationShare[]>(`/api/orgs/${encodeURIComponent(id)}/shares`, {preferSessionAuth: true,skipOrgContext: true,+ ...options,}),- listIncomingShares: (id: string) =>+ listIncomingShares: (id: string, options?: OrganizationAccessRequestOptions) =>apiFetchJSON<IncomingOrganizationShare[]>(`/api/orgs/${encodeURIComponent(id)}/shares/incoming`,{preferSessionAuth: true,skipOrgContext: true,+ ...options,},),- acceptIncomingShare: (id: string, shareId: string) =>+ acceptIncomingShare: (id: string, shareId: string, options?: OrganizationAccessRequestOptions) =>apiFetchJSON<OrganizationShare>(`/api/orgs/${encodeURIComponent(id)}/shares/incoming/${encodeURIComponent(shareId)}/accept`,{method: 'POST',preferSessionAuth: true,skipOrgContext: true,+ ...options,},),- declineIncomingShare: (id: string, shareId: string) =>+ declineIncomingShare: (id: string, shareId: string, options?: OrganizationAccessRequestOptions) =>apiFetchJSON<void>(`/api/orgs/${encodeURIComponent(id)}/shares/incoming/${encodeURIComponent(shareId)}`,{method: 'DELETE',preferSessionAuth: true,skipOrgContext: true,+ ...options,},),@@ -239,21 +244,24 @@ export const OrgsAPI = {resourceName?: string;accessRole: Exclude<OrganizationRole, 'owner'> | 'viewer';},+ options?: OrganizationAccessRequestOptions,) =>apiFetchJSON<OrganizationShare>(`/api/orgs/${encodeURIComponent(id)}/shares`, {method: 'POST',body: JSON.stringify(payload),preferSessionAuth: true,skipOrgContext: true,+ ...options,}),- deleteShare: (id: string, shareId: string) =>+ deleteShare: (id: string, shareId: string, options?: OrganizationAccessRequestOptions) =>apiFetchJSON<void>(`/api/orgs/${encodeURIComponent(id)}/shares/${encodeURIComponent(shareId)}`,{method: 'DELETE',preferSessionAuth: true,skipOrgContext: true,+ ...options,},),};diff --git a/frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx b/frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsxindex db02bb1671..ef7522b22c 100644--- a/frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx+++ b/frontend-modern/src/components/Settings/OrganizationSharingCreateSection.tsx@@ -18,7 +18,10 @@ export const OrganizationSharingCreateSection: Component<OrganizationSharingCrea<><Show when={props.state.canManageCurrentOrg()}><div class="p-4 sm:p-6">- <div class="rounded-md border border-border p-4 space-y-3">+ <fieldset+ disabled={props.state.saving()}+ class="rounded-md border border-border p-4 space-y-3"+ ><h4 class="text-sm font-semibold text-base-content">Create Share</h4><div class="grid gap-3 lg:grid-cols-2">@@ -91,6 +94,12 @@ export const OrganizationSharingCreateSection: Component<OrganizationSharingCrea</div></Show>+ <Show when={props.state.quickPickUnavailable()}>+ <p role="status" class="text-sm text-amber-700 dark:text-amber-300">+ The selected resource is no longer available. Choose another resource or enter it+ manually.+ </p>+ </Show><Showwhen={props.state.unifiedResourceOptions().length === 0 || props.state.manualEntryExpanded()@@ -162,11 +171,11 @@ export const OrganizationSharingCreateSection: Component<OrganizationSharingCrea{props.state.saving() ? 'Saving...' : 'Create Share'}</Button></div>- </div>+ </fieldset></div></Show>- <Show when={!props.state.canManageCurrentOrg()}>+ <Show when={!props.state.canManageCurrentOrg() && !props.state.readOnly()}><div class="p-4 sm:p-6"><div class="rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-900/25 dark:text-amber-300">Admin or owner role required to create or remove organization shares.diff --git a/frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx b/frontend-modern/src/components/Settings/OrganizationSharingPanel.tsxindex a9e034bf8b..dabdd450ac 100644--- a/frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx+++ b/frontend-modern/src/components/Settings/OrganizationSharingPanel.tsx@@ -1,8 +1,13 @@import { Component, Show } from 'solid-js';+import { Button } from '@/components/shared/Button';+import { Card } from '@/components/shared/Card';import SettingsPanel from '@/components/shared/SettingsPanel';import { isMultiTenantEnabled } from '@/stores/license';import { presentationPolicyHidesOrganizationSurfaces } from '@/stores/sessionPresentationPolicy';import {+ getOrganizationSharingReloadMessage,+ ORGANIZATION_SHARING_RELOAD_LABEL,+ ORGANIZATION_SHARING_UNAVAILABLE_TITLE,ORGANIZATION_SETTINGS_UNAVAILABLE_CLASS,ORGANIZATION_SETTINGS_UNAVAILABLE_MESSAGE,} from '@/utils/organizationSettingsPresentation';@@ -33,9 +38,45 @@ export const OrganizationSharingPanel: Component<OrganizationSharingPanelProps><div class="space-y-6"><SettingsPanel title="Organization Sharing" noPadding bodyClass="divide-y divide-border"><Show when={!state.loading()} fallback={<OrganizationSharingLoadingState />}>- <OrganizationSharingCreateSection state={state} />- <OrganizationOutgoingSharesSection state={state} />- <OrganizationIncomingSharesSection state={state} />+ <Show when={state.loadError()}>+ <div class="p-4 sm:p-6">+ <Card tone="warning" padding="md">+ <div role="alert" class="space-y-3 text-sm">+ <p class="font-semibold">{ORGANIZATION_SHARING_UNAVAILABLE_TITLE}</p>+ <p>{state.loadError()}</p>+ <p>{getOrganizationSharingReloadMessage(state.selectedOrgID())}</p>+ <Button+ onClick={() => void state.loadSharingData()}+ disabled={state.loading() || state.saving()}+ class="w-full sm:w-auto"+ >+ {ORGANIZATION_SHARING_RELOAD_LABEL}+ </Button>+ </div>+ </Card>+ </div>+ </Show>+ <Show when={!state.loadError() && state.org()}>+ {(currentOrg) => (+ <>+ <div class="p-4 sm:px-6 space-y-2 text-sm text-muted break-words">+ <p>+ Sharing for{' '}+ <span class="font-medium text-base-content" data-sharing-organization>+ {currentOrg().displayName || currentOrg().id}+ </span>{' '}+ ({currentOrg().id})+ </p>+ <Show when={state.readOnly()}>+ <p>This session is read-only. Sharing changes are disabled.</p>+ </Show>+ </div>+ <OrganizationSharingCreateSection state={state} />+ <OrganizationOutgoingSharesSection state={state} />+ <OrganizationIncomingSharesSection state={state} />+ </>+ )}+ </Show></Show></SettingsPanel></div>diff --git a/frontend-modern/src/components/Settings/__tests__/OrganizationSharingPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/OrganizationSharingPanel.test.tsxindex c7010e2e1f..535db29d71 100644--- a/frontend-modern/src/components/Settings/__tests__/OrganizationSharingPanel.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/OrganizationSharingPanel.test.tsx@@ -1,10 +1,14 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { syncSessionPresentationPolicy } from '@/stores/sessionPresentationPolicy';import type { Resource } from '@/types/resource';+import { useOrganizationSharingPanelState } from '../useOrganizationSharingPanelState';import { OrganizationSharingPanel } from '../OrganizationSharingPanel';import organizationSharingStateSource from '../useOrganizationSharingPanelState.ts?raw';let mockResources: Resource[] = [];+let readResources = () => mockResources;const orgGetMock = vi.fn();const listMembersMock = vi.fn();@@ -20,6 +24,9 @@ const getOrgIDMock = vi.fn();const notificationSuccessMock = vi.fn();const notificationErrorMock = vi.fn();const eventBusOnMock = vi.fn();+const eventBusEmitMock = vi.fn();+const listeners = new Map<string, Set<() => void>>();+const emit = (event: string) => listeners.get(event)?.forEach((listener) => listener());const loggerErrorMock = vi.fn();vi.mock('@/api/orgs', () => ({@@ -38,7 +45,7 @@ vi.mock('@/api/orgs', () => ({vi.mock('@/hooks/useResources', () => ({useResources: () => ({- resources: () => mockResources,+ resources: () => readResources(),}),}));@@ -60,6 +67,7 @@ vi.mock('@/stores/notifications', () => ({vi.mock('@/stores/events', () => ({eventBus: {on: (...args: unknown[]) => eventBusOnMock(...args),+ emit: (...args: unknown[]) => eventBusEmitMock(...args),},}));@@ -121,8 +129,12 @@ beforeEach(() => {notificationSuccessMock.mockReset();notificationErrorMock.mockReset();eventBusOnMock.mockReset();+ eventBusEmitMock.mockReset();+ listeners.clear();+ syncSessionPresentationPolicy(null);loggerErrorMock.mockReset();+ readResources = () => mockResources;mockResources = [makeResource({ id: 'vm-200', name: 'Zulu VM', displayName: 'Zulu VM' }),makeResource({ id: 'vm-100', name: 'Alpha VM', displayName: '' }),@@ -132,7 +144,12 @@ beforeEach(() => {isMultiTenantEnabledMock.mockReturnValue(true);getOrgIDMock.mockReturnValue('org-a');- eventBusOnMock.mockReturnValue(() => undefined);+ eventBusOnMock.mockImplementation((event: string, callback: () => void) => {+ if (!listeners.has(event)) listeners.set(event, new Set());+ listeners.get(event)!.add(callback);+ return () => listeners.get(event)?.delete(callback);+ });+ eventBusEmitMock.mockImplementation(emit);vi.stubGlobal('confirm',vi.fn(() => true),@@ -274,13 +291,21 @@ describe('OrganizationSharingPanel', () => {fireEvent.click(screen.getByRole('button', { name: 'Create Share' }));await waitFor(() => {- expect(createShareMock).toHaveBeenCalledWith('org-a', {- targetOrgId: 'org-b',- resourceType: 'vm',- resourceId: 'vm-100',- resourceName: 'Alpha VM',- accessRole: 'viewer',- });+ expect(createShareMock).toHaveBeenCalledWith(+ 'org-a',+ {+ targetOrgId: 'org-b',+ resourceType: 'vm',+ resourceId: 'vm-100',+ resourceName: 'Alpha VM',+ accessRole: 'viewer',+ },+ expect.objectContaining({+ expectedOrgID: 'org-a',+ retry: false,+ signal: expect.any(AbortSignal),+ }),+ );});});@@ -311,13 +336,21 @@ describe('OrganizationSharingPanel', () => {fireEvent.click(screen.getByRole('button', { name: 'Create Share' }));await waitFor(() => {- expect(createShareMock).toHaveBeenCalledWith('org-a', {- targetOrgId: 'org-b',- resourceType: 'vm',- resourceId: 'vm-200',- resourceName: 'Production VM',- accessRole: 'viewer',- });+ expect(createShareMock).toHaveBeenCalledWith(+ 'org-a',+ {+ targetOrgId: 'org-b',+ resourceType: 'vm',+ resourceId: 'vm-200',+ resourceName: 'Production VM',+ accessRole: 'viewer',+ },+ expect.objectContaining({+ expectedOrgID: 'org-a',+ retry: false,+ signal: expect.any(AbortSignal),+ }),+ );});});@@ -360,7 +393,11 @@ describe('OrganizationSharingPanel', () => {fireEvent.click(screen.getByRole('button', { name: 'Accept' }));await waitFor(() => {- expect(acceptIncomingShareMock).toHaveBeenCalledWith('org-a', 'share-in-1');+ expect(acceptIncomingShareMock).toHaveBeenCalledWith(+ 'org-a',+ 'share-in-1',+ expect.objectContaining({ expectedOrgID: 'org-a', retry: false }),+ );});await waitFor(() => {@@ -372,7 +409,11 @@ describe('OrganizationSharingPanel', () => {fireEvent.click(screen.getByRole('button', { name: 'Decline' }));await waitFor(() => {- expect(declineIncomingShareMock).toHaveBeenCalledWith('org-a', 'share-in-1');+ expect(declineIncomingShareMock).toHaveBeenCalledWith(+ 'org-a',+ 'share-in-1',+ expect.objectContaining({ expectedOrgID: 'org-a', retry: false }),+ );});});@@ -381,3 +422,446 @@ describe('OrganizationSharingPanel', () => {expect(organizationSharingStateSource).not.toContain("getOrgID() || 'default'");});});++describe('selected sharing snapshot', () => {+ it('does not expose previous-org shares or controls after a failed switch', async () => {+ listSharesMock.mockResolvedValue([+ {+ id: 'alpha-share',+ targetOrgId: 'org-b',+ resourceType: 'vm',+ resourceId: 'vm-alpha',+ resourceName: 'Alpha private workload',+ accessRole: 'viewer',+ status: 'pending',+ createdAt: '2026-10-01T00:00:00Z',+ createdBy: 'user-1',+ },+ ]);+ renderPanel();+ await screen.findByText('Alpha private workload');+ getOrgIDMock.mockReturnValue('org-b');+ orgGetMock.mockRejectedValue(new Error('unavailable'));+ emit('org_switched');+ await waitFor(() =>+ expect(screen.queryByText('Alpha private workload')).not.toBeInTheDocument(),+ );+ expect(screen.queryByRole('button', { name: 'Remove', exact: true })).not.toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'Create Share' })).not.toBeInTheDocument();+ expect(await screen.findByRole('button', { name: 'Reload sharing' })).toBeEnabled();+ });++ it('does not let late prior-org shares replace the selected snapshot', async () => {+ const alpha = {+ id: 'alpha-share',+ targetOrgId: 'org-b',+ resourceType: 'vm',+ resourceId: 'vm-alpha',+ resourceName: 'Alpha private workload',+ accessRole: 'viewer',+ status: 'pending',+ createdAt: '2026-10-01T00:00:00Z',+ createdBy: 'user-1',+ };+ const first = deferred<(typeof alpha)[]>();+ listSharesMock.mockReturnValueOnce(first.promise);+ renderPanel();+ await waitFor(() => expect(listSharesMock).toHaveBeenCalledTimes(1));+ getOrgIDMock.mockReturnValue('org-b');+ orgGetMock.mockResolvedValue({ ...targetOrg, ownerUserId: 'user-1' });+ listSharesMock.mockResolvedValue([+ { ...alpha, id: 'beta-share', targetOrgId: 'org-a', resourceName: 'Beta workload' },+ ]);+ emit('org_switched');+ await screen.findByText('Beta workload');+ first.resolve([alpha]);+ await Promise.resolve();+ await Promise.resolve();+ expect(screen.queryByText('Alpha private workload')).not.toBeInTheDocument();+ expect(screen.getByText('Beta workload')).toBeInTheDocument();+ });+});++const outgoing = {+ id: 'outgoing-1',+ targetOrgId: 'org-b',+ resourceType: 'vm',+ resourceId: 'vm-alpha',+ resourceName: 'Alpha shared workload',+ accessRole: 'viewer' as const,+ status: 'pending' as const,+ createdAt: '2026-10-01T00:00:00Z',+ createdBy: 'user-1',+};+const incoming = {+ ...outgoing,+ id: 'incoming-1',+ targetOrgId: 'org-a',+ sourceOrgId: 'org-b',+ sourceOrgName: 'Organization B',+ resourceName: 'Incoming workload',+};+function renderState() {+ let state!: ReturnType<typeof useOrganizationSharingPanelState>;+ const [user, setUser] = createSignal<string | undefined>('user-1');+ const view = render(() => {+ state = useOrganizationSharingPanelState({+ get currentUser() {+ return user();+ },+ });+ return <div />;+ });+ return { state, setUser, ...view };+}+const accepted = async (state: ReturnType<typeof useOrganizationSharingPanelState>) =>+ waitFor(() => {+ expect(state.loading()).toBe(false);+ expect(state.loadError()).toBeNull();+ expect(state.org()).not.toBeNull();+ });++const strictOptions = (org = 'org-a') =>+ expect.objectContaining({+ expectedOrgID: org,+ retry: false,+ signal: expect.any(AbortSignal),+ });++describe('sharing read admission and recovery', () => {+ it.each(['organization', 'members', 'organizations', 'outgoing', 'incoming'])(+ 'keeps a failed %s read distinct from empty sharing and permits a deliberate read-only retry',+ async (part) => {+ const mocks = {+ organization: orgGetMock,+ members: listMembersMock,+ organizations: listOrgsMock,+ outgoing: listSharesMock,+ incoming: listIncomingSharesMock,+ };+ mocks[part as keyof typeof mocks].mockRejectedValueOnce(new Error('503'));+ renderPanel();+ expect(await screen.findByRole('button', { name: 'Reload sharing' })).toBeEnabled();+ expect(screen.queryByRole('heading', { name: 'Create Share' })).not.toBeInTheDocument();+ expect(screen.queryByText(/No (incoming|outgoing) shares/)).not.toBeInTheDocument();+ const calls = orgGetMock.mock.calls.length;+ fireEvent.click(screen.getByRole('button', { name: 'Reload sharing' }));+ await screen.findByRole('heading', { name: 'Outgoing Shares' });+ expect(orgGetMock.mock.calls.length).toBe(calls + 1);+ expect(createShareMock).not.toHaveBeenCalled();+ expect(deleteShareMock).not.toHaveBeenCalled();+ },+ );++ it.each(['wrong organization', 'missing shares', 'foreign incoming target'])(+ 'does not admit %s as a valid empty snapshot',+ async (problem) => {+ if (problem === 'wrong organization') orgGetMock.mockResolvedValue(targetOrg);+ if (problem === 'missing shares') listSharesMock.mockResolvedValue(null);+ if (problem === 'foreign incoming target')+ listIncomingSharesMock.mockResolvedValue([{ ...incoming, targetOrgId: 'org-foreign' }]);+ const { state } = renderState();+ await waitFor(() => expect(state.loadError()).toBeTruthy());+ expect(state.org()).toBeNull();+ expect(state.canManageCurrentOrg()).toBe(false);+ await state.createShare();+ expect(createShareMock).not.toHaveBeenCalled();+ },+ );++ it('binds every read to the selected scope and invalidates all siblings after a partial failure', async () => {+ listSharesMock.mockRejectedValue(new Error('403'));+ const { state } = renderState();+ await waitFor(() => expect(state.loadError()).toBeTruthy());+ for (const method of [orgGetMock, listMembersMock, listSharesMock, listIncomingSharesMock]) {+ expect(method).toHaveBeenCalledWith('org-a', strictOptions());+ expect(method.mock.calls[0][1].signal.aborted).toBe(true);+ }+ expect(listOrgsMock).toHaveBeenCalledWith(strictOptions());+ });++ it('hides old rows and actions while a same-selection reload is pending', async () => {+ listSharesMock.mockResolvedValue([outgoing]);+ renderPanel();+ await screen.findByText(outgoing.resourceName);+ const next = deferred<(typeof outgoing)[]>();+ listSharesMock.mockReturnValueOnce(next.promise);+ emit('organizations_changed');+ expect(screen.queryByText(outgoing.resourceName)).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Remove', exact: true })).not.toBeInTheDocument();+ next.resolve([]);+ await screen.findByRole('heading', { name: 'Outgoing Shares' });+ expect(screen.queryByText(outgoing.resourceName)).not.toBeInTheDocument();+ });++ it('preserves same-selection drafts across failed reloads but clears every peer draft', async () => {+ const { state } = renderState();+ await accepted(state);+ state.updateResourceType('vm');+ state.updateResourceId('unsent-alpha');+ state.updateResourceName('Alpha draft');+ state.setAccessRole('admin');+ orgGetMock.mockRejectedValueOnce(new Error('503'));+ await state.loadSharingData();+ expect(state.resourceId()).toBe('unsent-alpha');+ await state.loadSharingData();+ expect(state.resourceId()).toBe('unsent-alpha');+ getOrgIDMock.mockReturnValue('org-b');+ orgGetMock.mockResolvedValue({ ...targetOrg, ownerUserId: 'user-1' });+ emit('org_switched');+ await accepted(state);+ expect(state.resourceId()).toBe('');+ expect(state.resourceType()).toBe('');+ expect(state.resourceName()).toBe('');+ expect(state.selectedQuickPick()).toBe('');+ expect(state.accessRole()).toBe('viewer');+ expect(state.targetOrgId()).toBe('org-a');+ });++ it('ignores a late failure without suppressing current actions or emitting a stale error', async () => {+ const old = deferred<typeof baseOrg>();+ orgGetMock.mockReturnValueOnce(old.promise);+ const { state } = renderState();+ getOrgIDMock.mockReturnValue('org-b');+ orgGetMock.mockResolvedValue({ ...targetOrg, ownerUserId: 'user-1' });+ emit('org_switched');+ await accepted(state);+ old.reject(new Error('old read failure'));+ await Promise.resolve();+ await Promise.resolve();+ expect(state.org()?.id).toBe('org-b');+ expect(state.canManageCurrentOrg()).toBe(true);+ expect(state.loadError()).toBeNull();+ expect(notificationErrorMock).not.toHaveBeenCalled();+ });++ it('does not apply an older same-selection reload and cancels subscriptions on disposal', async () => {+ const { state, unmount } = renderState();+ await accepted(state);+ const old = deferred<(typeof outgoing)[]>();+ listSharesMock.mockReturnValueOnce(old.promise);+ const pending = state.loadSharingData();+ await state.loadSharingData();+ old.resolve([outgoing]);+ await pending;+ expect(state.outgoingShares()).toEqual([]);+ const count = orgGetMock.mock.calls.length;+ unmount();+ emit('organizations_changed');+ emit('org_switched');+ expect(orgGetMock.mock.calls.length).toBe(count);+ });++ it('uses the explicit default selection without changing global context', async () => {+ getOrgIDMock.mockReturnValue(null);+ orgGetMock.mockResolvedValue({ ...baseOrg, id: 'default' });+ const { state } = renderState();+ await accepted(state);+ expect(orgGetMock).toHaveBeenCalledWith('default', strictOptions('default'));+ expect(state.selectedOrgID()).toBe('default');+ });+});++describe('sharing changes require an admitted current snapshot', () => {+ const actions = [+ {+ name: 'create',+ mock: createShareMock,+ run: (state: ReturnType<typeof useOrganizationSharingPanelState>) => {+ state.applyResourceQuickPick('vm::vm-100');+ return state.createShare();+ },+ },+ {+ name: 'remove outgoing',+ mock: deleteShareMock,+ run: (state: ReturnType<typeof useOrganizationSharingPanelState>) =>+ state.deleteShare(state.outgoingShares()[0]),+ },+ {+ name: 'accept incoming',+ mock: acceptIncomingShareMock,+ run: (state: ReturnType<typeof useOrganizationSharingPanelState>) =>+ state.acceptIncomingShare(state.incomingShares()[0]),+ },+ {+ name: 'decline incoming',+ mock: declineIncomingShareMock,+ run: (state: ReturnType<typeof useOrganizationSharingPanelState>) =>+ state.declineIncomingShare(state.incomingShares()[0]),+ },+ ];+ const populate = () => {+ listSharesMock.mockResolvedValue([outgoing]);+ listIncomingSharesMock.mockResolvedValue([incoming]);+ };++ it.each(actions)(+ 'binds $name once and requires a read after an uncertain response',+ async ({ mock, run }) => {+ populate();+ mock.mockRejectedValueOnce(new Error('403'));+ const { state } = renderState();+ await accepted(state);+ state.updateResourceId('saved-draft');+ await run(state);+ expect(mock).toHaveBeenCalledTimes(1);+ expect(mock.mock.calls[0].at(-1)).toEqual(strictOptions());+ expect(state.loadError()).toContain('could not be confirmed');+ expect(state.canManageCurrentOrg()).toBe(false);+ await state.createShare();+ await state.deleteShare(outgoing);+ await state.acceptIncomingShare(incoming);+ await state.declineIncomingShare(incoming);+ expect(mock).toHaveBeenCalledTimes(1);+ await state.loadSharingData();+ await accepted(state);+ await run(state);+ expect(mock).toHaveBeenCalledTimes(2);+ expect(eventBusEmitMock).toHaveBeenCalledWith('organizations_changed');+ await accepted(state);+ },+ );++ it.each(actions)(+ 'does not replay $name or use a late result after switching organizations',+ async ({ mock, run }) => {+ populate();+ const pending = deferred<unknown>();+ mock.mockReturnValueOnce(pending.promise);+ const { state } = renderState();+ await accepted(state);+ const change = run(state);+ await run(state);+ expect(mock).toHaveBeenCalledTimes(1);+ const signal = mock.mock.calls[0].at(-1).signal;+ getOrgIDMock.mockReturnValue('org-b');+ orgGetMock.mockResolvedValue({ ...targetOrg, ownerUserId: 'user-1' });+ listIncomingSharesMock.mockResolvedValue([]);+ emit('org_switched');+ await accepted(state);+ state.updateResourceId('beta-draft');+ pending.resolve({});+ await change;+ expect(signal.aborted).toBe(true);+ expect(state.org()?.id).toBe('org-b');+ expect(state.resourceId()).toBe('beta-draft');+ expect(notificationSuccessMock).not.toHaveBeenCalled();+ expect(notificationErrorMock).not.toHaveBeenCalled();+ expect(mock).toHaveBeenCalledTimes(1);+ },+ );++ it.each(['viewer', 'anonymous', 'read-only'])(+ 'blocks all direct changes for a %s session',+ async (kind) => {+ populate();+ if (kind === 'viewer') {+ orgGetMock.mockResolvedValue({ ...baseOrg, ownerUserId: 'other' });+ }+ if (kind === 'read-only')+ syncSessionPresentationPolicy({+ presentationPolicy: {+ demoMode: false,+ readOnly: true,+ hideCommercial: false,+ hideUpgrade: true,+ },+ });+ const { state, setUser } = renderState();+ if (kind === 'anonymous') setUser(undefined);+ await accepted(state);+ expect(state.canManageCurrentOrg()).toBe(false);+ for (const { run, mock } of actions) {+ await run(state);+ expect(mock).not.toHaveBeenCalled();+ }+ },+ );++ it.each(['user', 'capability', 'read-only', 'disposal'])(+ 'invalidates an in-flight write on %s change',+ async (kind) => {+ populate();+ const [enabled, setEnabled] = createSignal(true);+ isMultiTenantEnabledMock.mockImplementation(enabled);+ const pending = deferred<unknown>();+ createShareMock.mockReturnValueOnce(pending.promise);+ const { state, setUser, unmount } = renderState();+ await accepted(state);+ const change = actions[0].run(state);+ const signal = createShareMock.mock.calls[0].at(-1).signal;+ if (kind === 'user') setUser('other-user');+ if (kind === 'capability') setEnabled(false);+ if (kind === 'read-only')+ syncSessionPresentationPolicy({+ presentationPolicy: {+ demoMode: false,+ readOnly: true,+ hideCommercial: false,+ hideUpgrade: true,+ },+ });+ if (kind === 'disposal') unmount();+ expect(signal.aborted).toBe(true);+ pending.resolve({});+ await change;+ expect(notificationSuccessMock).not.toHaveBeenCalled();+ expect(createShareMock).toHaveBeenCalledTimes(1);+ if (kind === 'capability') {+ setEnabled(true);+ await accepted(state);+ expect(createShareMock).toHaveBeenCalledTimes(1);+ }+ },+ );++ it('rejects foreign or obsolete rows and does not reaccept an accepted incoming share', async () => {+ populate();+ const { state } = renderState();+ await accepted(state);+ const priorOutgoing = state.outgoingShares()[0];+ const priorIncoming = state.incomingShares()[0];+ listSharesMock.mockResolvedValue([{ ...outgoing }]);+ listIncomingSharesMock.mockResolvedValue([{ ...incoming, status: 'accepted' }]);+ await state.loadSharingData();+ await state.deleteShare(priorOutgoing);+ await state.declineIncomingShare(priorIncoming);+ await state.acceptIncomingShare(state.incomingShares()[0]);+ expect(deleteShareMock).not.toHaveBeenCalled();+ expect(declineIncomingShareMock).not.toHaveBeenCalled();+ expect(acceptIncomingShareMock).not.toHaveBeenCalled();+ });++ it.each(['outgoing', 'incoming'])(+ 'rechecks the %s row after confirmation changes scope',+ async (kind) => {+ populate();+ const { state } = renderState();+ await accepted(state);+ vi.mocked(confirm).mockImplementation(() => {+ getOrgIDMock.mockReturnValue('org-b');+ return true;+ });+ if (kind === 'outgoing') await state.deleteShare(state.outgoingShares()[0]);+ else await state.declineIncomingShare(state.incomingShares()[0]);+ expect(deleteShareMock).not.toHaveBeenCalled();+ expect(declineIncomingShareMock).not.toHaveBeenCalled();+ },+ );++ it('keeps opaque quick-pick IDs intact and refuses a disappeared selection', async () => {+ const [resources, setResources] = createSignal([makeResource({ id: 'opaque::vm/100' })]);+ readResources = resources;+ const { state } = renderState();+ await accepted(state);+ state.applyResourceQuickPick('vm::opaque::vm/100');+ await state.createShare();+ await accepted(state);+ expect(createShareMock.mock.calls[0][1].resourceId).toBe('opaque::vm/100');+ setResources([]);+ expect(state.canCreateShare()).toBe(false);+ await state.createShare();+ expect(createShareMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts b/frontend-modern/src/components/Settings/useOrganizationSharingPanelState.tsindex db264069de..a5e6c0ee87 100644--- a/frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts+++ b/frontend-modern/src/components/Settings/useOrganizationSharingPanelState.ts@@ -1,15 +1,20 @@-import { createEffect, createMemo, createSignal, onCleanup, onMount } from 'solid-js';+import { batch, createEffect, createMemo, createSignal, on, onCleanup } from 'solid-js';+import { unwrap } from 'solid-js/store';import {OrgsAPI,type IncomingOrganizationShare,type Organization,+ type OrganizationAccessRequestOptions,type OrganizationShare,} from '@/api/orgs';import { useResources } from '@/hooks/useResources';import { eventBus } from '@/stores/events';import { isMultiTenantEnabled } from '@/stores/license';import { notificationStore } from '@/stores/notifications';-import { presentationPolicyHidesOrganizationSurfaces } from '@/stores/sessionPresentationPolicy';+import {+ presentationPolicyHidesOrganizationSurfaces,+ presentationPolicyIsReadOnly,+} from '@/stores/sessionPresentationPolicy';import { getOrgID } from '@/utils/apiClient';import {INVALID_RESOURCE_TYPE_ERROR,@@ -35,6 +40,7 @@ import {getOrganizationShareTargetOrgDifferentMessage,getOrganizationShareTargetOrgRequiredMessage,getOrganizationSettingsLoadErrorMessage,+ ORGANIZATION_SHARING_UNCONFIRMED_CHANGE_MESSAGE,} from '@/utils/organizationSettingsPresentation';import { canManageOrg } from '@/utils/orgUtils';@@ -50,6 +56,7 @@ export type ResourceOption = {export function useOrganizationSharingPanelState(props: OrganizationSharingPanelProps) {const [loading, setLoading] = createSignal(true);+ const [loadError, setLoadError] = createSignal<string | null>(null);const [saving, setSaving] = createSignal(false);const [org, setOrg] = createSignal<Organization | null>(null);const [orgs, setOrgs] = createSignal<Organization[]>([]);@@ -67,6 +74,28 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanelconst [resourceIdError, setResourceIdError] = createSignal('');const activeOrgId = () => normalizeOrgScope(getOrgID());+ const [selectedOrgID, setSelectedOrgID] = createSignal(activeOrgId());+ const [selectedUser, setSelectedUser] = createSignal(props.currentUser);+ let generation = 0;+ let disposed = false;+ let readController: AbortController | undefined;+ let mutationController: AbortController | undefined;+ const surfaceEnabled = () =>+ isMultiTenantEnabled() && !presentationPolicyHidesOrganizationSurfaces();+ const selectionIsCurrent = () =>+ !disposed &&+ surfaceEnabled() &&+ selectedOrgID() === activeOrgId() &&+ selectedUser() === props.currentUser;+ const hasCurrentSharing = () =>+ selectionIsCurrent() && !loading() && !loadError() && org()?.id === activeOrgId();+ const canManageCurrentOrg = createMemo(+ () =>+ hasCurrentSharing() &&+ !presentationPolicyIsReadOnly() &&+ canManageOrg(org(), props.currentUser),+ );+ const canChangeSharing = () => hasCurrentSharing() && canManageCurrentOrg() && !saving();const { resources } = useResources();const targetOrgOptions = createMemo(() =>@@ -93,14 +122,22 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanel);const normalizedResourceId = createMemo(() => resourceId().trim());const hasTargetOrg = createMemo(() => targetOrgId().trim() !== '');- const hasQuickPickSelection = createMemo(() => selectedQuickPick().trim() !== '');+ // Match the complete opaque resource ID rather than splitting on a delimiter+ // that may occur inside it. A removed quick pick is not a valid manual draft.+ const selectedResource = createMemo(() =>+ unifiedResourceOptions().find(+ (resource) => `${resource.type}::${resource.id}` === selectedQuickPick(),+ ),+ );const manualEntryValid = createMemo(() => isCanonicalResourceType(normalizedResourceType()) && normalizedResourceId() !== '',);const canCreateShare = createMemo(- () => !saving() && hasTargetOrg() && (hasQuickPickSelection() || manualEntryValid()),+ () =>+ canChangeSharing() &&+ hasTargetOrg() &&+ (selectedQuickPick() ? !!selectedResource() : manualEntryValid()),);- const canManageCurrentOrg = createMemo(() => canManageOrg(org(), props.currentUser));const orgNameById = createMemo(() => {const map = new Map<string, string>();@@ -122,49 +159,141 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanel};createEffect(() => {- if (unifiedResourceOptions().length > 0) return;- setManualEntryExpanded(true);- setSelectedQuickPick('');+ if (unifiedResourceOptions().length === 0 && !selectedQuickPick()) setManualEntryExpanded(true);});- const loadShares = async (orgId: string) => {- const [outgoing, incoming] = await Promise.all([- OrgsAPI.listShares(orgId),- OrgsAPI.listIncomingShares(orgId),- ]);- setOutgoingShares(outgoing);- setIncomingShares(incoming);+ const clearSharing = () => {+ setOrg(null);+ setOrgs([]);+ setOutgoingShares([]);+ setIncomingShares([]);+ };+ const clearDraft = () => {+ setTargetOrgId('');+ setResourceType('');+ setResourceId('');+ setResourceName('');+ setAccessRole('viewer');+ setSelectedQuickPick('');+ setManualEntryExpanded(false);+ setTargetOrgError('');+ setResourceTypeError('');+ setResourceIdError('');+ };+ const invalidateRequests = () => {+ generation += 1;+ readController?.abort();+ readController = undefined;+ mutationController?.abort();+ mutationController = undefined;+ setSaving(false);};const loadSharingData = async () => {- setLoading(true);+ if (disposed) return;+ invalidateRequests();+ const orgId = activeOrgId();+ const user = props.currentUser;+ const request = generation;+ const isCurrent = () => request === generation && selectionIsCurrent();+ batch(() => {+ if (selectedOrgID() !== orgId || selectedUser() !== user) clearDraft();+ setSelectedOrgID(orgId);+ setSelectedUser(user);+ clearSharing();+ setLoadError(null);+ setLoading(surfaceEnabled());+ });+ if (!surfaceEnabled()) return;++ const controller = new AbortController();+ readController = controller;+ const options: OrganizationAccessRequestOptions = {+ expectedOrgID: orgId,+ signal: controller.signal,+ retry: false,+ };try {- const orgId = activeOrgId();- const [orgData, memberData, allOrgs] = await Promise.all([- OrgsAPI.get(orgId),- OrgsAPI.listMembers(orgId),- OrgsAPI.list(),+ // Publish one accepted snapshot, never a new org with old share rows (or+ // a partial read presented as an empty share list).+ const [orgData, memberData, allOrgs, outgoing, incoming] = await Promise.all([+ OrgsAPI.get(orgId, options),+ OrgsAPI.listMembers(orgId, options),+ OrgsAPI.list(options),+ OrgsAPI.listShares(orgId, options),+ OrgsAPI.listIncomingShares(orgId, options),]);-- setOrg({ ...orgData, members: memberData });- setOrgs(allOrgs);- if (unifiedResourceOptions().length === 0) {- setManualEntryExpanded(true);- setSelectedQuickPick('');+ if (!isCurrent()) return;+ if (+ !orgData ||+ orgData.id !== orgId ||+ !Array.isArray(memberData) ||+ !Array.isArray(allOrgs) ||+ !Array.isArray(outgoing) ||+ !Array.isArray(incoming) ||+ incoming.some((share) => share.targetOrgId !== orgId)+ ) {+ throw new Error('Organization sharing returned an invalid selection');}-- await loadShares(orgId);-- const firstTarget =- targetOrgId().trim() || allOrgs.find((candidate) => candidate.id !== orgId)?.id || '';- setTargetOrgId(firstTarget);- setTargetOrgError(firstTarget === '' ? getOrganizationShareTargetOrgRequiredMessage() : '');+ batch(() => {+ setOrg({ ...orgData, members: memberData });+ setOrgs(allOrgs);+ setOutgoingShares(outgoing);+ setIncomingShares(incoming);+ const firstTarget =+ targetOrgId().trim() || allOrgs.find((candidate) => candidate.id !== orgId)?.id || '';+ setTargetOrgId(firstTarget);+ setTargetOrgError(firstTarget === '' ? getOrganizationShareTargetOrgRequiredMessage() : '');+ });} catch (error) {+ if (!isCurrent()) return;logger.error('Failed to load organization sharing data', error);const message = error instanceof Error ? error.message : '';- notificationStore.error(getOrganizationSettingsLoadErrorMessage(message, 'sharing'));+ setLoadError(getOrganizationSettingsLoadErrorMessage(message, 'sharing'));+ } finally {+ if (!disposed && request === generation) {+ controller.abort(); // Cancel sibling reads after a partial failure.+ readController = undefined;+ setLoading(false);+ if (!selectionIsCurrent()) void loadSharingData();+ }+ }+ };++ const changeSharing = async (+ change: (options: OrganizationAccessRequestOptions) => Promise<unknown>,+ successMessage: string,+ errorMessage: (message?: string) => string,+ ) => {+ if (!canChangeSharing()) return;+ const request = generation;+ const isCurrent = () => request === generation && selectionIsCurrent();+ const controller = new AbortController();+ mutationController = controller;+ setSaving(true);+ try {+ await change({ expectedOrgID: selectedOrgID(), signal: controller.signal, retry: false });+ if (!isCurrent()) return;+ notificationStore.success(successMessage);+ mutationController = undefined;+ setSaving(false);+ eventBus.emit('organizations_changed');+ } catch (error) {+ if (!isCurrent()) return;+ logger.error('Failed to change organization sharing', error);+ notificationStore.error(errorMessage(error instanceof Error ? error.message : undefined));+ // A failed response cannot tell us whether a change was applied. Read+ // before allowing another change; never replay a write automatically.+ batch(() => {+ clearSharing();+ setLoadError(ORGANIZATION_SHARING_UNCONFIRMED_CHANGE_MESSAGE);+ });} finally {- setLoading(false);+ if (mutationController === controller) {+ mutationController = undefined;+ setSaving(false);+ if (!disposed && !selectionIsCurrent()) void loadSharingData();+ }}};@@ -174,10 +303,7 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanelsetResourceIdError('');if (!value) return;- const [nextType, nextID] = value.split('::');- const match = unifiedResourceOptions().find(- (resource) => resource.id === (nextID ?? '') && resource.type === (nextType ?? ''),- );+ const match = selectedResource();if (!match) return;setResourceType(normalizeCanonicalResourceTypeInput(match.type));setResourceId(match.id);@@ -221,13 +347,18 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanelconst createShare = async () => {const currentOrg = org();- if (!currentOrg) return;+ if (!currentOrg || !canChangeSharing()) return;const nextTargetOrgId = targetOrgId().trim();- const nextResourceType = normalizedResourceType();- const nextResourceId = normalizedResourceId();- const nextResourceName = resourceName().trim();- const hasQuickPick = hasQuickPickSelection();+ const quickPick = selectedResource();+ const hasQuickPick = selectedQuickPick() !== '';+ if (hasQuickPick && !quickPick) {+ notificationStore.error(getOrganizationShareInvalidResourceMessage());+ return;+ }+ const nextResourceType = quickPick?.type ?? normalizedResourceType();+ const nextResourceId = quickPick?.id ?? normalizedResourceId();+ const nextResourceName = quickPick?.name ?? resourceName().trim();const hasValidManualType = isCanonicalResourceType(nextResourceType);const hasValidManualResourceId = nextResourceId !== '';@@ -255,109 +386,91 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanelreturn;}- setSaving(true);- try {- await OrgsAPI.createShare(currentOrg.id, {- targetOrgId: nextTargetOrgId,- resourceType: nextResourceType,- resourceId: nextResourceId,- resourceName: nextResourceName,- accessRole: accessRole(),- });- notificationStore.success(getOrganizationShareCreateSuccessMessage());- await loadShares(currentOrg.id);- } catch (error) {- logger.error('Failed to create organization share', error);- notificationStore.error(- getOrganizationShareCreateErrorMessage(error instanceof Error ? error.message : undefined),- );- } finally {- setSaving(false);- }+ await changeSharing(+ (options) =>+ OrgsAPI.createShare(+ currentOrg.id,+ {+ targetOrgId: nextTargetOrgId,+ resourceType: nextResourceType,+ resourceId: nextResourceId,+ resourceName: nextResourceName,+ accessRole: accessRole(),+ },+ options,+ ),+ getOrganizationShareCreateSuccessMessage(),+ getOrganizationShareCreateErrorMessage,+ );};+ // Grid rows are Solid store proxies; unwrap without admitting an object from+ // an older snapshot just because it happens to have the same ID.+ const isCurrentOutgoing = (share: OrganizationShare) => outgoingShares().includes(unwrap(share));+ const isCurrentIncoming = (share: IncomingOrganizationShare) =>+ incomingShares().includes(unwrap(share));+const deleteShare = async (share: OrganizationShare) => {const currentOrg = org();- if (!currentOrg) return;+ if (!currentOrg || !canChangeSharing() || !isCurrentOutgoing(share)) return;if (!confirm(`Remove share for ${share.resourceType}:${share.resourceId}?`)) return;-- setSaving(true);- try {- await OrgsAPI.deleteShare(currentOrg.id, share.id);- notificationStore.success(getOrganizationShareDeleteSuccessMessage());- await loadShares(currentOrg.id);- } catch (error) {- logger.error('Failed to delete organization share', error);- notificationStore.error(- getOrganizationShareDeleteErrorMessage(error instanceof Error ? error.message : undefined),- );- } finally {- setSaving(false);- }+ if (org() !== currentOrg || !isCurrentOutgoing(share) || !canChangeSharing()) return;+ await changeSharing(+ (options) => OrgsAPI.deleteShare(currentOrg.id, share.id, options),+ getOrganizationShareDeleteSuccessMessage(),+ getOrganizationShareDeleteErrorMessage,+ );};const acceptIncomingShare = async (share: IncomingOrganizationShare) => {const currentOrg = org();- if (!currentOrg) return;-- setSaving(true);- try {- await OrgsAPI.acceptIncomingShare(currentOrg.id, share.id);- notificationStore.success(- getOrganizationIncomingShareAcceptSuccessMessage(getShareLabel(share)),- );- await loadShares(currentOrg.id);- } catch (error) {- logger.error('Failed to accept incoming organization share', error);- notificationStore.error(- getOrganizationIncomingShareAcceptErrorMessage(- error instanceof Error ? error.message : undefined,- ),- );- } finally {- setSaving(false);- }+ if (+ !currentOrg ||+ !canChangeSharing() ||+ !isCurrentIncoming(share) ||+ share.targetOrgId !== currentOrg.id ||+ share.status !== 'pending'+ )+ return;+ await changeSharing(+ (options) => OrgsAPI.acceptIncomingShare(currentOrg.id, share.id, options),+ getOrganizationIncomingShareAcceptSuccessMessage(getShareLabel(share)),+ getOrganizationIncomingShareAcceptErrorMessage,+ );};const declineIncomingShare = async (share: IncomingOrganizationShare) => {const currentOrg = org();- if (!currentOrg) return;-+ if (+ !currentOrg ||+ !canChangeSharing() ||+ !isCurrentIncoming(share) ||+ share.targetOrgId !== currentOrg.id+ )+ return;const shareLabel = getShareLabel(share);- if (!confirm(getOrganizationIncomingShareDeclineConfirmMessage(shareLabel, share.status))) {+ if (!confirm(getOrganizationIncomingShareDeclineConfirmMessage(shareLabel, share.status)))return;- }-- setSaving(true);- try {- await OrgsAPI.declineIncomingShare(currentOrg.id, share.id);- notificationStore.success(- getOrganizationIncomingShareDeclineSuccessMessage(shareLabel, share.status),- );- await loadShares(currentOrg.id);- } catch (error) {- logger.error('Failed to remove incoming organization share', error);- notificationStore.error(- getOrganizationIncomingShareDeclineErrorMessage(- error instanceof Error ? error.message : undefined,- ),- );- } finally {- setSaving(false);- }+ if (org() !== currentOrg || !isCurrentIncoming(share) || !canChangeSharing()) return;+ await changeSharing(+ (options) => OrgsAPI.declineIncomingShare(currentOrg.id, share.id, options),+ getOrganizationIncomingShareDeclineSuccessMessage(shareLabel, share.status),+ getOrganizationIncomingShareDeclineErrorMessage,+ );};- onMount(() => {- if (!isMultiTenantEnabled() || presentationPolicyHidesOrganizationSurfaces()) {- setLoading(false);- return;- }- void loadSharingData();-- const unsubscribe = eventBus.on('org_switched', () => {+ const unsubscribeOrg = eventBus.on('org_switched', () => void loadSharingData());+ const unsubscribeChanged = eventBus.on('organizations_changed', () => void loadSharingData());+ createEffect(+ on([surfaceEnabled, () => props.currentUser, presentationPolicyIsReadOnly], () => {void loadSharingData();- });- onCleanup(unsubscribe);+ }),+ );+ onCleanup(() => {+ disposed = true;+ invalidateRequests();+ unsubscribeOrg();+ unsubscribeChanged();});return {@@ -371,6 +484,11 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPaneldeleteShare,incomingShares,loading,+ loadError,+ loadSharingData,+ org,+ readOnly: presentationPolicyIsReadOnly,+ selectedOrgID,manualEntryExpanded,orgNameById,outgoingShares,@@ -381,6 +499,7 @@ export function useOrganizationSharingPanelState(props: OrganizationSharingPanelresourceTypeError,saving,selectedQuickPick,+ quickPickUnavailable: () => !!selectedQuickPick() && !selectedResource(),setAccessRole,targetOrgError,targetOrgId,diff --git a/frontend-modern/src/utils/organizationSettingsPresentation.ts b/frontend-modern/src/utils/organizationSettingsPresentation.tsindex 9a70822f12..d1cd6737ac 100644--- a/frontend-modern/src/utils/organizationSettingsPresentation.ts+++ b/frontend-modern/src/utils/organizationSettingsPresentation.ts@@ -12,6 +12,14 @@ export function getOrganizationAccessReloadMessage(orgId: string): string {return `Reload checks saved members and invitations for ${orgId}. It does not repeat an access change.`;}+export const ORGANIZATION_SHARING_UNCONFIRMED_CHANGE_MESSAGE =+ 'The last sharing change could not be confirmed. Reload saved sharing before making another change.';+export const ORGANIZATION_SHARING_RELOAD_LABEL = 'Reload sharing';+export const ORGANIZATION_SHARING_UNAVAILABLE_TITLE = 'Organization sharing unavailable';+export function getOrganizationSharingReloadMessage(orgId: string): string {+ return `Reload checks saved incoming and outgoing shares for ${orgId}. It does not repeat a sharing change.`;+}+export type OrganizationSettingsLoadContext ='access' | 'overview' | 'sharing' | 'billing' | 'billing-admin';