Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/shared-view-create-for-metadata-admins.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@object-ui/app-shell': patch
'@object-ui/i18n': patch
---

Clause-②: yes (widening)
Metadata-protocol: none

A shared list view is offered only to an administrator who may write one, and it is shared at once. Add view offers Shared only to an administrator whose session holds `manage_metadata`, the capability the shared view's write door asks; an organization administrator without it is no longer offered a Shared choice the server answers `403`. A view created Shared is saved and published in one act, so everyone sees it on their next read instead of waiting behind a draft; a refused save publishes nothing. A reader who opens a view the server says no longer exists is told so once, and the list shows its default view. Two new `@object-ui/i18n` keys under `view.switcher` carry the notices in every locale.
7 changes: 7 additions & 0 deletions content/docs/ui/views.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,13 @@ The split pane beside an open record keeps the same switcher.
`sys_personal_view` object, not view metadata, so a package never carries them. A user the
server grants that object nothing (an external member, today) is offered neither the section
nor the save.
- **Shared views** are seen by everyone who can see the list, and only an administrator makes
one: a user whose session holds `manage_metadata`, the capability the view's write door
(`PUT /api/v1/meta/view/:name`) asks, so the server refuses everyone else whatever the
Console shows. For that administrator **Add view** offers **Shared** beside **My view**
(**My view** stays the default). A view created shared is published at once: there is no
draft to publish first. A user who opens a view that has since been deleted is told so, and
the list shows its default view.

## Form View

Expand Down
64 changes: 64 additions & 0 deletions packages/rest/src/meta-write-door-capability-enumeration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ import '@objectstack/objectql';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_STATUS } from '@objectstack/core';
import { RestServer } from './rest-server.js';
import { securityDefaultPermissionSets } from '@objectstack/plugin-security';

/**
* The unscoped mount base, and the `/meta` prefix on it. The `DOORS` table
Expand Down Expand Up @@ -703,3 +704,66 @@ describe('#30675 — the data doors refuse on their own capability, not `manage_
},
);
});

/**
* [objectstack#36409] Only an administrator makes a list view everyone sees.
* A shared view is `view` metadata, so the door that shares one is this
* surface's save (the Console saves `?mode=draft` and publishes at once), the
* publish promotes it, and the delete removes it. Driven
* with the systemPermissions the SHIPPED sets grant, not hand-written ones: a
* member (`member_default`), an organization administrator (that baseline
* plus `organization_admin`, which withholds `manage_metadata`) and the
* platform administrator (`admin_full_access`, the control). The Console asks
* the same capability before it offers Shared (`useCanAuthorMetadata`), so the
* organization administrator's refusal here is why that control is hidden.
*/
describe('#36409 — sharing a list view is an administrator\'s act', () => {
const grants = (...names: string[]): string[] => {
const held = new Set<string>();
for (const name of names) {
const set = securityDefaultPermissionSets.find((ps) => ps.name === name);
if (!set) throw new Error(`no shipped permission set named ${name}`);
for (const capability of set.systemPermissions ?? []) held.add(capability);
}
return [...held];
};
const VIEW = { type: 'view', name: 'account.team_pipeline' };
const viewDoor = (protocolMethod: string): Door => {
const door = DOORS.find((d) => d.protocolMethod === protocolMethod)!;
return {
...door,
params: { ...VIEW },
...(protocolMethod === 'saveMetaItem'
? { body: { name: VIEW.name, object: 'account', viewKind: 'list', label: 'Team pipeline', config: { type: 'grid', data: { provider: 'object', object: 'account' } } } }
: {}),
};
};
const SHARE_DOORS = ['saveMetaItem', 'publishMetaItem', 'deleteMetaItem'].map(viewDoor);

it.each([
['a member', ['member_default']],
['an organization administrator', ['member_default', 'organization_admin']],
] as const)('%s is refused each share door 403 FORBIDDEN, and nothing is written', async (_who, sets) => {
const systemPermissions = grants(...sets);
expect(systemPermissions).not.toContain('manage_metadata');
for (const door of SHARE_DOORS) {
const stack = boot({ userId: 'u_member', systemPermissions });
const out = await stack.knock(door);
expect(out.status, door.label).toBe(403);
expect(out.body, door.label).toMatchObject({ error: { code: 'FORBIDDEN' } });
expect(stack.calls[door.protocolMethod], door.label).toBe(0);
}
});

it('the control: the platform administrator reaches each share door', async () => {
const systemPermissions = grants('admin_full_access');
expect(systemPermissions).toContain('manage_metadata');
for (const door of SHARE_DOORS) {
const stack = boot({ userId: 'u_admin', systemPermissions });
const out = await stack.knock(door);
expect(out.status, door.label).not.toBe(403);
expect(out.status, door.label).not.toBe(401);
expect(stack.calls[door.protocolMethod], door.label).toBe(1);
}
});
});
14 changes: 11 additions & 3 deletions ui/packages/app-shell/src/hooks/useMetaItemRefusal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
* only, so it never answers for the next URL.
* - `refusal` is set for `denied` alone. Every other verdict leaves the page's
* missing-item face: the server said absence, or said nothing.
* - `absent` (objectstack#36409) is set for `not_found` alone: the server
* says the item is not there for anyone, so a page may say it is gone (a
* view deleted since the reader's address named it) rather than fall
* back in silence. Unreachable and unknown answers say nothing.
*
* Nothing is cached across mounts: a verdict about the CALLER goes stale the
* moment they are granted the capability.
Expand All @@ -50,10 +54,13 @@ export interface MetaItemRefusalReading {
readonly checking: boolean;
/** The server refused this caller the item; `null` for every other answer. */
readonly refusal: MetaItemRefusal | null;
/** The server answered that no such item exists. */
readonly absent: boolean;
}

const NOT_REFUSED: MetaItemRefusalReading = Object.freeze({ checking: false, refusal: null });
const CHECKING: MetaItemRefusalReading = Object.freeze({ checking: true, refusal: null });
const NOT_REFUSED: MetaItemRefusalReading = Object.freeze({ checking: false, refusal: null, absent: false });
const CHECKING: MetaItemRefusalReading = Object.freeze({ checking: true, refusal: null, absent: false });
const ABSENT: MetaItemRefusalReading = Object.freeze({ checking: false, refusal: null, absent: true });

export function useMetaItemRefusal(type: 'dashboard' | 'view', name: string | null): MetaItemRefusalReading {
const adapter = useAdapter();
Expand All @@ -79,6 +86,7 @@ export function useMetaItemRefusal(type: 'dashboard' | 'view', name: string | nu

if (!asked) return NOT_REFUSED;
if (!answer || answer.type !== type || answer.name !== asked) return CHECKING;
if (answer.access.verdict === 'not_found') return ABSENT;
if (answer.access.verdict !== 'denied') return NOT_REFUSED;
return { checking: false, refusal: { message: answer.access.message } };
return { checking: false, refusal: { message: answer.access.message }, absent: false };
}
37 changes: 34 additions & 3 deletions ui/packages/app-shell/src/views/ObjectView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ import { useObjectViewListRenderer } from './objectViewListRenderer.js';
import { ListDraftActions } from './ListDraftActions.js';
import { viewSaveRefusalText } from './viewSaveRefusal.js';
import { listDraftPreference, listDraftScope, useListDraft } from './listDraftStore.js';
import { useObjectViewViewCrud } from './objectViewViewCrud.js';
import { useObjectViewViewCrud, useRuntimeCreateApp } from './objectViewViewCrud.js';
import { mayShareViews, useViewSharing } from './objectViewViewSharing.js';
import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js';
import {
PERSONAL_VIEW_OBJECT,
buildInPlaceViewConfig,
Expand Down Expand Up @@ -696,6 +698,17 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
? (requestedViewId.includes('.') ? requestedViewId : `${objectDef.name}.${requestedViewId}`)
: null;
const viewAccess = useMetaItemRefusal('view', missedViewName);
// objectstack#36409 — a view the address names that the server says is
// gone (deleted, or never there): the list opens its default view, and
// says why once per name.
const goneViewNoticed = useRef<string | null>(null);
useEffect(() => {
if (!viewAccess.absent || !missedViewName || goneViewNoticed.current === missedViewName) return;
goneViewNoticed.current = missedViewName;
toast.info(t('view.switcher.viewGone', {
defaultValue: 'The view you opened is no longer available, so the list shows its default view.',
}));
}, [viewAccess.absent, missedViewName, t]);
const activeViewId = resolvedViewId || pinnedViewId || defaultViewId || views[0]?.id;
const baseView = views.find((v: any) => v.id === activeViewId) || views[0];
const activeView = viewDraft && viewDraft.id === baseView?.id
Expand Down Expand Up @@ -1122,6 +1135,24 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
listSeedRef,
});

// objectstack#36409 — only an administrator holding the shared view's write
// capability creates a shared view, and it is published at once
// (`./objectViewViewSharing.ts`).
const canAuthorMetadata = useCanAuthorMetadata();
const canShareViews = mayShareViews(isAdmin, canAuthorMetadata);
const sharingApp = useRuntimeCreateApp(t);
const viewSharing = useViewSharing({
objectName: objectDef.name,
objectDef,
metadataClient,
dataSource,
app: sharingApp,
routeViewId: viewId,
navigate,
refresh: () => setRefreshKey((k) => k + 1),
t,
});

// objectstack#27594: the list title is the view switcher, which replaced the
// view tab strip; the view items `ManageViewsDialog` lists come with it.
const { viewTabItems, titleSwitcher, refusingPackages } = useObjectViewTitleSwitcher({
Expand Down Expand Up @@ -1154,10 +1185,10 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
}),
savePersonal: personalViews.save,
openPersonal: openPersonalView,
createShared: handleViewCreate,
createShared: viewSharing.createShared,
clearSourceListState,
canCreatePersonal: canCreatePersonalView,
canCreateShared: isAdmin,
canCreateShared: canShareViews,
hasUnsavedConditions: listDraftParts.some((part) => part === 'filters' || part === 'sort'),
},
onRenamePersonalView: personalViewsReady && personalGrant('update')
Expand Down
107 changes: 107 additions & 0 deletions ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#36409 — who may create a shared view from a list's view
* dropdown, and the act that creates one (`./objectViewViewSharing.ts`).
*
* WHAT IS PINNED.
* - Who: an administrator whose session holds `manage_metadata`; an
* administrator without it (an organization administrator) is not offered
* a Shared choice the server refuses.
* - Create, shared: saved and published in one act, never left as a draft; a
* refused save publishes nothing, and a name a pending draft holds is said
* (`shareNameTaken`).
*/

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';

const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
vi.mock('sonner', () => ({ toast }));

import { mayShareViews, useViewSharing } from './objectViewViewSharing';

const t = ((key: string, options?: { defaultValue?: string; name?: string }) =>
(options?.defaultValue ?? key).replace('{{name}}', options?.name ?? '')) as never;

const OBJECT = 'crm_lead';
const OBJECT_DEF = { name: OBJECT, fields: { name: { type: 'text' } } };

function rig() {
const metadataClient = {
save: vi.fn(async () => ({})),
publish: vi.fn(async () => ({})),
reset: vi.fn(async () => ({})),
};
const navigate = vi.fn();
const refresh = vi.fn();
const { result } = renderHook(() => useViewSharing({
objectName: OBJECT,
objectDef: OBJECT_DEF,
metadataClient,
dataSource: {},
app: { packageId: null },
routeViewId: undefined,
navigate,
refresh,
t,
}));
return { result, metadataClient, navigate, refresh };
}

beforeEach(() => {
for (const fn of Object.values(toast)) fn.mockClear();
});

describe('objectstack#36409 — who may share views', () => {
it('an administrator holding manage_metadata; neither half alone', () => {
expect(mayShareViews(true, true)).toBe(true);
expect(mayShareViews(true, false)).toBe(false); // an organization administrator
expect(mayShareViews(false, true)).toBe(false);
expect(mayShareViews(false, false)).toBe(false);
});
});

describe('objectstack#36409 — Create, shared', () => {
it('saves and publishes the new view in one act, and opens it', async () => {
const r = rig();
let created = false;
await act(async () => {
created = await r.result.current.createShared({ type: 'grid', label: 'Hot leads', name: 'hot_leads', columns: ['name'] });
});
expect(created).toBe(true);
expect(r.metadataClient.save).toHaveBeenCalledTimes(1);
const [type, name, , options] = r.metadataClient.save.mock.calls[0] as unknown as [string, string, unknown, Record<string, unknown>];
expect([type, name]).toEqual(['view', `${OBJECT}.hot_leads`]);
expect(options).toEqual({ mode: 'draft', ifNoneMatch: '*' });
expect(r.metadataClient.publish).toHaveBeenCalledWith('view', `${OBJECT}.hot_leads`);
expect(r.navigate).toHaveBeenCalledWith(`view/${OBJECT}.hot_leads`);
});

it('a refused save is said and reported unsaved; nothing is published', async () => {
const r = rig();
r.metadataClient.save.mockRejectedValueOnce(Object.assign(new Error('Saving metadata requires the `manage_metadata` capability.'), { status: 403 }));
let created = true;
await act(async () => {
created = await r.result.current.createShared({ type: 'grid', label: 'Hot leads', name: 'hot_leads' });
});
expect(created).toBe(false);
expect(r.metadataClient.publish).not.toHaveBeenCalled();
expect(toast.error).toHaveBeenCalled();
});

it('a name an unpublished draft already holds: told so, reported unsaved, nothing published', async () => {
const r = rig();
r.metadataClient.save.mockRejectedValueOnce(Object.assign(new Error('pending'), { status: 409, code: 'METADATA_CONFLICT' }));
let created = true;
await act(async () => {
created = await r.result.current.createShared({ type: 'grid', label: 'Hot leads', name: 'hot_leads' });
});
expect(created).toBe(false);
expect(r.metadataClient.publish).not.toHaveBeenCalled();
expect(r.refresh).not.toHaveBeenCalled();
expect(r.navigate).not.toHaveBeenCalled();
const [, options] = toast.error.mock.calls[0] as unknown as [string, { description: string }];
expect(options.description).toContain('An unpublished draft already uses this view’s name');
});
});
Loading
Loading