Skip to content

Commit b6dc566

Browse files
fix(console): offer view management on manage_metadata, not isAdmin alone (#36782)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8SBcaWJ4VnpRmSNLW9FDCPD)_ Fixes #36448 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:没有「管理元数据」权限的组织管理员,在列表页不再看到「管理视图」「视图设置」「新建视图」,数据页也不再有「另存为视图」;有该权限的管理员看到的和以前一样。 - 为什么做:这几个入口保存的都是共享视图定义,服务器只接受有「管理元数据」权限的人;以前只看是不是管理员,没权限的管理员点进去一保存就被拒。紧接上一张「只有元数据管理员能建共享视图」的卡。 - 出错会怎样:最坏是有权限的管理员看不到入口(纯界面开关,服务器规则没动),撤回这个改动即恢复。 - 要你做什么:无。 ## What changes One answer gates every entry on a list page that leads to a `view` metadata write: `mayManageViews(isAdmin, useCanAuthorMetadata())` — an administrator whose session holds `manage_metadata`, the capability `PUT`/`DELETE /meta/view/NAME` asks (`metaWriteCapabilityVerdict`). It is the predicate #36398 introduced for the Shared choice (`mayShareViews`), renamed because it now gates more than sharing. - `ObjectView` computes `canManageViews` once and reads it for: the `ManageViewsDialog` mount, the `ViewConfigPanel` open state and wrapper, the `CreateViewDialog` open state, the title switcher's Add view / Manage views entries (`useObjectViewTitleSwitcher` prop `isAdmin` becomes `canManageViews`), and the plugin view's `allowCreateView` and `viewActions` (settings, share, delete) (`useObjectViewPluginSchema`, same rename). - `ObjectDataPage`'s Save as view (button, folded menu item and its `CreateViewDialog`) — a fourth Create View door, writing `/meta/view` through `createRuntimeMetadata` — reads the same predicate. - Declared bounded in-place fix (same defect class, same file, same gate family; named in the thread's first report to the seat): a saved shared view's Rename in the Options menu and Save to this view (`canSaveToSharedView`) both write `/meta/view` through `updateView` and were offered on `isAdmin` alone; they read `canManageViews` too. - `isAdmin` alone still gates what only reads (the metadata inspector panel, the package-list reads behind the panel's read-only state). A reader's own views (`sys_personal_view`) are untouched: the in-place Add view still offers My view to everyone who may create one. ## Tests - New `ObjectView.viewManagementGate-36448.test.tsx`: the real `ObjectView` under the router; an organization administrator without `manage_metadata` gets no Manage views entry (and no dialog); one with it opens Manage views and Create View from it (control); a member gets neither. The plugin schema: without the capability `allowCreateView` is false and `viewActions` empty; with it, both offered (control). - `ObjectDataPage.saveAsViewRefusal-11578.test.tsx`: new top-level describe in the existing harness — Save as view (button, menu item, dialog) absent without the capability, present with it (control); the existing cases now set the capability explicitly. - `objectViewViewSharing.test.tsx` and `objectViewRecordNavigation.phonePush-29074.test.tsx` follow the rename. ## Acceptance notes - none ## Verification Two-minute check: sign in as an organization administrator who lacks `manage_metadata`, open any object list — the view switcher shows no Manage views and the data page no Save as view; as a metadata administrator both are there. Riskiest hunks to read first: `ObjectView.tsx` (the `canManageViews` line and the three JSX gates), `objectViewPluginSchema.ts` (`allowCreateView` / `viewActions`), `ObjectDataPage.tsx` (`canSaveAsView`). <details><summary>Readings at head 10d4f44</summary> - Targeted tests: `pnpm --dir ui exec vitest run` on `ObjectView.viewManagementGate-36448.test.tsx`, `ObjectDataPage.saveAsViewRefusal-11578.test.tsx`, `objectViewViewSharing.test.tsx`, `objectViewRecordNavigation.phonePush-29074.test.tsx` — Test Files 4 passed (4), Tests 26 passed (26) (lock VERDICT command-exit 0), after `pnpm --filter '@object-ui/app-shell^...' build` (exit 0). - Reverse verification (implementation committed first): the five source files restored to `e0f0e9f7` with the new tests kept — 4 of 10 cases RED: the three without-capability cases (Manage views offered, Save as view offered, plugin Create View and view actions offered) as predicted, plus the plugin-schema control, which goes red because the old hook takes `isAdmin`, not `canManageViews` (the rename, not the gate). Restored with `git checkout HEAD`; `git diff HEAD` empty afterwards. - `pnpm --filter @object-ui/app-shell run type-check` — lock VERDICT command-exit 0. - `dispatch-gates.mjs --commands` derived families, all run locally, all exit 0; `--ran` reconciliation: 38 of 38 accounted for: - exit 0 · `node scripts/check-closing-keyword-parity.mjs` - exit 0 · `node scripts/check-closing-keyword-parity.mjs --self-test` - exit 0 · `node scripts/check-comment-mask-corpus.mjs` - exit 0 · `node scripts/check-sdui-manifest.mjs` - exit 0 · `node scripts/check-sdui-manifest.mjs --self-test` - exit 0 · `pnpm --dir ui exec vitest run scripts/` - exit 0 · `pnpm --filter @objectstack/spec run check:duration-unit-keys` - exit 0 · `pnpm check:adr-anchors` - exit 0 · `pnpm check:cross-package-test-inputs` - exit 0 · `pnpm check:dispatcher-error-vocabulary` - exit 0 · `pnpm check:driver-memory-census` - exit 0 · `pnpm check:engine-double-contract` - exit 0 · `pnpm check:gitlink-declared` - exit 0 · `pnpm check:nul-bytes` - exit 0 · `pnpm check:published-files` - exit 0 · `pnpm check:query-options-erasure` - exit 0 · `pnpm check:refd-timer-probe` - exit 0 · `pnpm check:registry-log-declared` - exit 0 · `pnpm check:rest-log-spy-declared` - exit 0 · `pnpm check:skill-identifier-liveness` - exit 0 · `pnpm check:test-source-alias` - exit 0 · `pnpm check:tier-file-adoption` - exit 0 · `pnpm check:type-check-coverage` - exit 0 · `pnpm check:type-check-debt` - exit 0 · `pnpm check:undeclared-dep-imports` - exit 0 · `pnpm check:watch-hint-literal` - exit 0 · `pnpm check:where-matcher` - exit 0 · `node scripts/check-adr-0087-registration.mjs --base origin/main` - exit 0 · `node scripts/check-adr-0087-registration.mjs --self-test` - exit 0 · `node scripts/check-changeset-no-major.mjs --base origin/main` - exit 0 · `node scripts/check-empty-changeset.mjs --base origin/main` - exit 0 · `node scripts/check-empty-changeset.mjs --self-test` - exit 0 · `node scripts/ci/snapshot-next.mjs --self-test` - exit 0 · `node scripts/pm/check-governed-queue-guard.mjs --self-test` - exit 0 · `node scripts/pm/release-rehearsal-clone.mjs --self-test` - exit 0 · `node scripts/release-pending-publish.mjs --self-test` - exit 0 · `pnpm check:changeset-gate-self-tests` - exit 0 · `pnpm check:closed-ceremony-text` - CI at 10d4f44: 39 success · 13 expected skip · 0 failed (`pr-state.mjs`: mergeable_state clean). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbYXZHUaaZK86HquGRP)_ <!-- signed: repo:objectstack#1 · os-warren · session_01JQwxbYXZHUaaZK86HquGRP --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 79a355b commit b6dc566

10 files changed

Lines changed: 342 additions & 41 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
fix(console): offer view management only to an administrator who may write views
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Manage views, the view settings panel and Create View on a list page, the plugin view's own Create View and view actions, the data page's Save as view, and a saved shared view's rename and save in place were offered to every workspace administrator. Each of them writes `view` metadata, which the server refuses without the `manage_metadata` capability, so an organization administrator who lacks it was offered them and met a refusal on the first save. They now read the answer the Shared choice of a new view already reads (`mayManageViews`): an administrator whose session holds `manage_metadata`. A metadata administrator sees them as before; a reader's own views are unchanged.

‎ui/packages/app-shell/src/views/ObjectDataPage.saveAsViewRefusal-11578.test.tsx‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,8 @@ function wire() {
9393
});
9494
}
9595
let client: MetadataClient;
96+
/** objectstack#36448 — the principal's `manage_metadata` answer, set per case. */
97+
const viewer = vi.hoisted(() => ({ canAuthorMetadata: true }));
9698

9799
vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({
98100
...(await importOriginal<Record<string, unknown>>()),
@@ -110,10 +112,14 @@ vi.mock('@object-ui/permissions', async (importOriginal) => {
110112
useFieldPermissions: () => ({ canRead: () => true, canWrite: () => true, permissions: [] }),
111113
};
112114
});
115+
vi.mock('../hooks/useCanAuthorMetadata', async (importOriginal) => ({
116+
...(await importOriginal<Record<string, unknown>>()),
117+
useCanAuthorMetadata: () => viewer.canAuthorMetadata,
118+
}));
113119
vi.mock('@object-ui/auth', async (importOriginal) => ({
114120
...(await importOriginal<Record<string, unknown>>()),
115121
useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }),
116-
// "Save as view" and its dialog are admin-only.
122+
// "Save as view" and its dialog are for an admin holding `manage_metadata`.
117123
useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }),
118124
createAuthenticatedFetch: () => vi.fn(),
119125
}));
@@ -177,6 +183,7 @@ async function saveAsView() {
177183
beforeEach(() => {
178184
cleanup();
179185
puts.length = 0;
186+
viewer.canAuthorMetadata = true;
180187
client = new MetadataClient({ baseUrl: 'http://localhost', fetch: wire() as unknown as typeof fetch });
181188
vi.spyOn(console, 'error').mockImplementation(() => {});
182189
// objectstack#35624 — the create asks the package list where the app saves
@@ -221,3 +228,31 @@ describe('"Save as view" says a refused save, and never reports it as saved (obj
221228
expect(screen.queryByTestId('create-view-dialog')).toBeNull();
222229
});
223230
});
231+
232+
describe('objectstack#36448 — "Save as view" is offered to an administrator holding manage_metadata', () => {
233+
const mount = () => render(
234+
<ExpressionProvider user={{ id: 'u1', name: 'Ada' }}>
235+
<MemoryRouter initialEntries={[PAGE]}>
236+
<Routes>
237+
<Route
238+
path="/apps/:appName/:objectName/data"
239+
element={<ObjectDataPage dataSource={{ find: vi.fn(async () => ({ data: [] })) }} objects={[DEAL]} />}
240+
/>
241+
</Routes>
242+
</MemoryRouter>
243+
</ExpressionProvider>,
244+
);
245+
246+
it('an organization administrator without it is not offered the save the server refuses', () => {
247+
viewer.canAuthorMetadata = false;
248+
mount();
249+
expect(screen.queryByTestId('object-data-save-as-view')).toBeNull();
250+
expect(screen.queryByTestId('object-data-save-as-view-menu-item')).toBeNull();
251+
expect(screen.queryByTestId('create-view-dialog')).toBeNull();
252+
});
253+
254+
it('with it, the entry is offered (control)', () => {
255+
mount();
256+
expect(screen.getByTestId('object-data-save-as-view')).toBeTruthy();
257+
});
258+
});

‎ui/packages/app-shell/src/views/ObjectDataPage.tsx‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,8 @@ import {
9999
} from '../preview/PreviewModeContext.js';
100100
import { usePreviewListDataSource } from '../preview/unpublishedObjectReads.js';
101101
import { useTenancyPosture } from '../hooks/useTenancyPosture.js';
102+
import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js';
103+
import { mayManageViews } from './objectViewViewSharing.js';
102104
import { servedObjectLabel, servedObjectPluralLabel } from '../hooks/servedObjectLabel.js';
103105
import type { RowCrudPredicates } from '../utils/crudAffordances.js';
104106
import { servesRecordRead } from '../utils/recordReadServed.js';
@@ -332,6 +334,11 @@ export function ObjectDataPage({ dataSource, objects }: any) {
332334
const { canRead } = useFieldPermissions(objectName ?? '');
333335
const { user, activeOrganization } = useAuth();
334336
const { isAdmin } = useWorkspaceAdminStatus();
337+
// objectstack#36448 — "Save as view" writes `view` metadata, which the
338+
// server refuses without `manage_metadata`: offered to an administrator
339+
// holding it (`mayManageViews`), never to one the save would answer 403.
340+
const canAuthorMetadata = useCanAuthorMetadata();
341+
const canSaveAsView = mayManageViews(isAdmin, canAuthorMetadata);
335342
const metadataClient = useMetadataClient();
336343
// ADR-0105: group posture appends a trailing organization_id attribution
337344
// column to the auto-derived columns (reads span all the user's orgs).
@@ -908,7 +915,7 @@ export function ObjectDataPage({ dataSource, objects }: any) {
908915
<span className="hidden sm:inline">{t('console.objectView.new')}</span>
909916
</Button>
910917
) : null;
911-
const saveAsViewButton = isAdmin ? (
918+
const saveAsViewButton = canSaveAsView ? (
912919
<Button
913920
size="sm"
914921
variant="outline"
@@ -981,7 +988,7 @@ export function ObjectDataPage({ dataSource, objects }: any) {
981988
foldedActions={
982989
newButton && <>
983990
{newButton}
984-
{isAdmin && (
991+
{canSaveAsView && (
985992
<DropdownMenu>
986993
<DropdownMenuTrigger asChild>
987994
<Button
@@ -1130,7 +1137,7 @@ export function ObjectDataPage({ dataSource, objects }: any) {
11301137
</NavigationOverlay>
11311138
)}
11321139

1133-
{isAdmin && (
1140+
{canSaveAsView && (
11341141
<CreateViewDialog
11351142
open={showCreateViewDialog}
11361143
onOpenChange={setShowCreateViewDialog}

‎ui/packages/app-shell/src/views/ObjectView.tsx‎

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ import { ListDraftActions } from './ListDraftActions.js';
101101
import { viewSaveRefusalText } from './viewSaveRefusal.js';
102102
import { listDraftPreference, listDraftScope, useListDraft } from './listDraftStore.js';
103103
import { useObjectViewViewCrud, useRuntimeCreateApp } from './objectViewViewCrud.js';
104-
import { mayShareViews, useViewSharing } from './objectViewViewSharing.js';
104+
import { mayManageViews, useViewSharing } from './objectViewViewSharing.js';
105105
import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js';
106106
import {
107107
PERSONAL_VIEW_OBJECT,
@@ -284,6 +284,15 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
284284
const { user, activeOrganization } = useAuth();
285285
const { isAdmin } = useWorkspaceAdminStatus();
286286
const perms = usePermissions();
287+
// objectstack#36448 — who is offered the object's views to change: an
288+
// administrator holding `manage_metadata`, the capability every `view`
289+
// metadata write asks (`./objectViewViewSharing.ts`). Manage views, the
290+
// view settings panel, Create View, a Shared new view, and a saved view's
291+
// rename and save in place all read this one answer, so an organization
292+
// administrator without it is offered none of the writes the server
293+
// refuses with 403. `isAdmin` alone still gates what only reads.
294+
const canAuthorMetadata = useCanAuthorMetadata();
295+
const canManageViews = mayManageViews(isAdmin, canAuthorMetadata);
287296

288297
// Get Object Definition. The outer ObjectView wrapper already guards the
289298
// missing-object case, so this always resolves while this component is
@@ -911,7 +920,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
911920
? savedViews.find((sv: any) => viewRowId(sv) === activeView.id)
912921
: undefined;
913922
const activeViewPackageSaveRead = usePackageSaveRead(studioPackageId(activeSavedViewRow));
914-
const canSaveToSharedView = !isEnvironmentList && !activeIsPersonal && !!activeView && isAdmin
923+
const canSaveToSharedView = !isEnvironmentList && !activeIsPersonal && !!activeView && canManageViews
915924
&& activeViewPackageSaveRead === 'takes' && isSavedViewId(savedViews, String(activeView.id));
916925
const handleSaveToSharedView = async () => {
917926
if (!activeView || !canSaveToSharedView) return;
@@ -1166,10 +1175,8 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
11661175
});
11671176

11681177
// objectstack#36409 — only an administrator holding the shared view's write
1169-
// capability creates a shared view, and it is published at once
1170-
// (`./objectViewViewSharing.ts`).
1171-
const canAuthorMetadata = useCanAuthorMetadata();
1172-
const canShareViews = mayShareViews(isAdmin, canAuthorMetadata);
1178+
// capability (`canManageViews`, above) creates a shared view, and it is
1179+
// published at once (`./objectViewViewSharing.ts`).
11731180
const sharingApp = useRuntimeCreateApp(t);
11741181
const viewSharing = useViewSharing({
11751182
objectName: objectDef.name,
@@ -1197,7 +1204,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
11971204
viewAccess,
11981205
activeViewId,
11991206
handleViewChange,
1200-
isAdmin,
1207+
canManageViews,
12011208
handleAddView,
12021209
setManageViewsOpen,
12031210
pinnedViewId,
@@ -1218,7 +1225,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
12181225
createShared: viewSharing.createShared,
12191226
clearSourceListState,
12201227
canCreatePersonal: canCreatePersonalView,
1221-
canCreateShared: canShareViews,
1228+
canCreateShared: canManageViews,
12221229
hasUnsavedConditions: listDraftParts.some((part) => part === 'filters' || part === 'sort'),
12231230
},
12241231
onRenamePersonalView: personalViewsReady && personalGrant('update')
@@ -1325,7 +1332,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
13251332
? (label: string) => handleRenamePersonalView(String(activeView.id), label)
13261333
// A read-only package's view is renamed too (objectstack#35974):
13271334
// `updateView` writes the label into its customization pair.
1328-
: activeView && isAdmin && savedViews.some((sv: any) => viewRowId(sv) === activeView.id)
1335+
: activeView && canManageViews && savedViews.some((sv: any) => viewRowId(sv) === activeView.id)
13291336
? async (label: string) => { await handleRenameView(String(activeView.id), label); return true; }
13301337
: undefined,
13311338
save: !isEnvironmentList && listDraftParts.length > 0 ? saveToThisView : undefined,
@@ -1350,7 +1357,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
13501357
activeView,
13511358
objectDef,
13521359
onEdit,
1353-
isAdmin,
1360+
canManageViews,
13541361
location,
13551362
navigate,
13561363
viewId,
@@ -1600,7 +1607,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
16001607
the server refused alike. Its Manage views opens the dialog
16011608
below. On a phone the same switcher leads the list's toolbar
16021609
row (objectstack#27058). */}
1603-
{isAdmin && views.length >= 1 && (
1610+
{canManageViews && views.length >= 1 && (
16041611
<ManageViewsDialog
16051612
open={manageViewsOpen}
16061613
onOpenChange={setManageViewsOpen}
@@ -1644,12 +1651,12 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
16441651
<div
16451652
data-testid="view-config-panel-wrapper"
16461653
className={`transition-[max-width,opacity] duration-300 ease-in-out overflow-hidden ${
1647-
showViewConfigPanel && isAdmin ? 'max-w-[280px] opacity-100' : 'max-w-0 opacity-0'
1654+
showViewConfigPanel && canManageViews ? 'max-w-[280px] opacity-100' : 'max-w-0 opacity-0'
16481655
}`}
16491656
>
16501657
<Suspense fallback={null}>
16511658
<ViewConfigPanel
1652-
open={showViewConfigPanel && isAdmin}
1659+
open={showViewConfigPanel && canManageViews}
16531660
onClose={() => { setShowViewConfigPanel(false); setViewConfigPanelMode('edit'); }}
16541661
mode={viewConfigPanelMode}
16551662
activeView={activeView}
@@ -1666,7 +1673,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
16661673
</div>
16671674
<Suspense fallback={null}>
16681675
<CreateViewDialog
1669-
open={showCreateViewDialog && isAdmin}
1676+
open={showCreateViewDialog && canManageViews}
16701677
onOpenChange={setShowCreateViewDialog}
16711678
existingLabels={views.map((v: any) => v.label).filter(Boolean)}
16721679
objectDef={objectDef}

0 commit comments

Comments
 (0)