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
13 changes: 13 additions & 0 deletions .changeset/35933-read-only-package-view-saves.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@object-ui/data-objectstack': patch
'@object-ui/app-shell': patch
---

fix(ui): a view a read-only package ships offers no footer calculation menu and no Rename

Clause-②: no
Metadata-protocol: none

On a list view that ships inside a read-only package (a code or installed package), an admin was offered the footer's calculation menu and the options menu's Rename; the server refuses both saves ("save it into the customization package"), so the pick was taken back with a toast. Neither is offered there now. A shared view the console saved into the customization package, a stored view bound to no package and the reader's own view keep them.

The view's name cannot tell these apart, since every stored view is named `object.key`; the package the row was served under does. `listViews()` in `@object-ui/data-objectstack` now carries the row's served `_packageId` on both of its arms (the `config`-flattening arm dropped it). The console reads the server's `writable` verdict for that package from the package list it already holds for the session, the one the app bar's Studio entries read. While that list is unread, or when the read fails or does not name the package, the menu stays offered as before and the server's refusal still applies.
22 changes: 22 additions & 0 deletions ui/packages/app-shell/src/hooks/useStudioDesignGate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,25 @@ export function useStudioDesignGate(path: string | null | undefined): string | n
const entry = useStudioEntryGate(path);
return entry?.posture === 'edit' ? entry.path : null;
}

/**
* objectstack#35933 — whether the server refuses a save into `packageId`, by
* the same `writable` verdict and the same session-held read as the Studio
* entries above: `true` only when the package list carries the package as
* read-only (a code or installed package). A list's saved shared view hands
* its served package here, and a view the answer is `true` for is offered no
* save of its own (its changes go to the package's customization, which the
* door says on a refused save).
*
* Fails open, the opposite of the entries above and on purpose: `null` (a
* personal view or a view bound to no package), a read still in flight, a
* failed read and a package the list leaves out (a kernel package) all
* answer `false`, so the save stays offered as it was before this read and
* the server's write gate refuses what it refuses. A save hidden from a
* writable view is the worse failure; one the server refuses is said.
* ⛔ Never a derivation from the view's name: every stored view is named
* `object.key`, the console's own saved shared views included.
*/
export function usePackageRefusesSaves(packageId: string | null): boolean {
return usePackagePosture(packageId) === 'view';
}
8 changes: 6 additions & 2 deletions ui/packages/app-shell/src/utils/appRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,12 @@ export function appStudioRoutePath(
return appStudioDesignPath(app, isWorkspaceAdmin);
}

/** Shared guard: the owning package id usable by the Studio design surface. */
function studioPackageId(app: AppRouteLike | null | undefined): string | null {
/**
* Shared guard: the owning package id usable by the Studio design surface.
* Also the reading of a list's saved view row (objectstack#35933): the row
* carries its served `_packageId`, and the same id names the same package.
*/
export function studioPackageId(app: AppRouteLike | null | undefined): string | null {
const packageId = app?._packageId;
if (typeof packageId !== 'string' || !packageId || packageId === 'sys_metadata') return null;
return packageId;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#35933 — a view a read-only package ships offers an admin no save
* of its own: no footer calculation menu (objectstack#35702) and no Rename in
* the list's options menu. A shared view the console saved into the
* customization package, and the reader's own view, still offer the menu.
*
* A dotted view name cannot tell the two apart: every stored view is named
* `object.key`, the console's own saved views included. What tells them apart
* is the package the row was served under (`listViews()` carries the item's
* `_packageId`) and the server's `writable` verdict for that package, read from
* the session-held package list the Studio entries read (`fetchSessionPackages`).
* While that verdict is unknown the menu stays offered, as it was before: the
* server refuses the save and the pick is taken back.
*
* What runs: the real `ObjectView` on a stub data source. `ListView` is
* replaced by a stand-in that records the props it is handed, so the menu's
* presence is read as the `onColumnSummaryPick` the list receives (the grid
* draws the menu exactly when it has one, pinned in plugin-grid's
* `footerCalculationPicker-35702` tests). The package list is stubbed at
* `fetchSessionPackages`.
*/

import * as React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, cleanup, act, waitFor } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
// `ObjectView` reaches a dynamic `import('@objectstack/lint')`: pay its load at
// collection, never inside a case's clocked window (`check:test-source-alias`).
import '@objectstack/lint';

vi.mock('@object-ui/permissions', async (importOriginal) => {
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
// Stable identities: `ListView` names `perms` in its fetch dependencies.
const perms = {
check: () => ({ allowed: true }),
checkField: () => true,
getFieldPermissions: () => [],
getRowFilter: () => undefined,
getObjectApiOperations: () => undefined,
roles: [],
isLoaded: false,
hasCapabilities: () => true,
can: () => true,
cannot: () => false,
};
const fieldPerms = { canRead: () => true, canWrite: () => true, permissions: [] };
return { ...actual, usePermissions: () => perms, useFieldPermissions: () => fieldPerms };
});

vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: { id: 'org1', name: 'Acme' } }),
// The shared view's saves are an administrator's.
useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }),
createAuthenticatedFetch: () => vi.fn(),
}));

vi.mock('@object-ui/collaboration', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useRealtimeSubscription: () => ({ lastMessage: null }),
useConflictResolution: () => ({ hasConflicts: false, resolveAllConflicts: () => {} }),
}));

vi.mock('sonner', () => ({
toast: Object.assign(vi.fn(), {
success: vi.fn(), error: vi.fn(), info: vi.fn(),
warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(),
}),
}));

vi.mock('./MetadataInspector', () => ({
MetadataPanel: () => null,
useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }),
}));
vi.mock('./RecordDetailView', () => ({ RecordDetailView: () => null }));

/** The props the list was last handed. */
const listProps = vi.hoisted(() => ({ current: null as Record<string, any> | null }));
vi.mock('@object-ui/plugin-list', async (importOriginal) => ({
...(await importOriginal<typeof import('@object-ui/plugin-list')>()),
ListView: (props: any) => {
listProps.current = props;
return null;
},
}));

/** The session-held package list, as `GET /api/v1/packages` answers it (parsed). */
const packageList = vi.hoisted(() => ({ answer: (): Promise<any[]> => Promise.resolve([]) }));
vi.mock('./studio-design/packages-io', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
fetchSessionPackages: vi.fn(() => packageList.answer()),
}));

import { ObjectView } from './ObjectView';
import { ExpressionProvider } from '../providers/ExpressionProvider';

const OBJECT = 'showcase_task';
const SHIPPED_PACKAGE = 'com.example.showcase';
const CUSTOM_PACKAGE = 'com.example.showcase.custom';

/** A view the read-only code package ships, as `listViews()` serves it. */
const SHIPPED = {
name: `${OBJECT}.in_progress`, object: OBJECT, label: 'In progress', type: 'grid',
columns: ['name', 'amount'], _packageId: SHIPPED_PACKAGE,
};
/** A shared view the console saved: dotted the same way, in the customization package. */
const CUSTOM = {
name: `${OBJECT}.team_tasks`, object: OBJECT, label: 'Team tasks', type: 'grid',
columns: ['name', 'amount'], _packageId: CUSTOM_PACKAGE,
};
/** A stored view bound to no package. */
const UNBOUND = { name: `${OBJECT}.unbound`, object: OBJECT, label: 'Unbound', type: 'grid', columns: ['name', 'amount'] };
/** The reader's own view (`sys_personal_view`). */
const PERSONAL = {
id: 'pv_mine', user_id: 'u1', object_name: OBJECT, label: 'My tasks',
config: { type: 'grid', columns: ['name', 'amount'], data: { provider: 'object', object: OBJECT } },
};

/** The packages row for each id: the server's `writable` verdict. */
const PACKAGES = [
{ id: SHIPPED_PACKAGE, name: 'Showcase', writable: false, namespace: 'showcase' },
{ id: CUSTOM_PACKAGE, name: 'Showcase (custom)', writable: true, namespace: 'showcase' },
];

function mount(viewId: string) {
const dataSource = {
find: vi.fn(async (resource: string) =>
resource === 'sys_personal_view' ? { data: [PERSONAL], total: 1 } : { data: [], total: 0 }),
findOne: vi.fn(async () => null),
create: vi.fn(async () => ({})),
update: vi.fn(async () => ({})),
delete: vi.fn(async () => ({})),
getObjectSchema: vi.fn(async () => ({ name: OBJECT, fields: {} })),
listViews: vi.fn(async () => [SHIPPED, CUSTOM, UNBOUND]),
updateView: vi.fn(async () => ({})),
};
render(
<ExpressionProvider user={{ id: 'u1', name: 'Ada', profile: 'admin' }}>
<MemoryRouter initialEntries={[`/apps/demo/${OBJECT}/view/${encodeURIComponent(viewId)}`]}>
<Routes>
<Route
path="/apps/:appName/:objectName/view/:viewId"
element={
<ObjectView
dataSource={dataSource as never}
objects={[{
name: OBJECT,
label: 'Task',
fields: { name: { type: 'text', label: 'Name' }, amount: { type: 'number', label: 'Amount' } },
}]}
onEdit={() => {}}
/>
}
/>
</Routes>
</MemoryRouter>
</ExpressionProvider>,
);
}

const settle = () => act(() => new Promise<void>((resolve) => setTimeout(resolve, 300)));

/** Whether the list is handed the footer's calculation pick. */
const offersMenu = () => typeof listProps.current?.onColumnSummaryPick === 'function';

beforeEach(() => {
listProps.current = null;
packageList.answer = () => Promise.resolve(PACKAGES);
localStorage.clear();
});

afterEach(() => {
cleanup();
});

describe('objectstack#35933 — a read-only package\'s view offers no save of its own', () => {
it('a view a read-only package ships: no calculation menu, no Rename', async () => {
mount(SHIPPED.name);
await settle();
await waitFor(() => expect(listProps.current).not.toBeNull());
expect(offersMenu()).toBe(false);
expect(listProps.current?.onRenameView).toBeUndefined();
});

it('a shared view saved into the customization package keeps the menu and Rename', async () => {
mount(CUSTOM.name);
await settle();
await waitFor(() => expect(offersMenu()).toBe(true));
expect(listProps.current?.columnSummaryPickFields).toEqual(['name', 'amount']);
expect(typeof listProps.current?.onRenameView).toBe('function');
});

it('a stored view bound to no package keeps the menu', async () => {
mount(UNBOUND.name);
await settle();
await waitFor(() => expect(offersMenu()).toBe(true));
});

it('the reader\'s own view keeps the menu', async () => {
mount(PERSONAL.id);
await settle();
await waitFor(() => expect(offersMenu()).toBe(true));
});

it('while the package list is unread, the shipped view keeps the menu (the server still refuses)', async () => {
packageList.answer = () => new Promise<any[]>(() => {});
mount(SHIPPED.name);
await settle();
await waitFor(() => expect(offersMenu()).toBe(true));
});

it('a failed package-list read keeps the menu', async () => {
packageList.answer = () => Promise.reject(new Error('offline'));
mount(SHIPPED.name);
await settle();
await waitFor(() => expect(offersMenu()).toBe(true));
});
});
23 changes: 18 additions & 5 deletions ui/packages/app-shell/src/views/ObjectView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ import { importTargetFields } from './importTargetFields.js';
import { resolveViewId } from '../utils/resolveViewId.js';
import { useRecordOpenPreference } from '../utils/recordOpenPreference.js';
import { usePhoneViewport } from '../hooks/usePhoneViewport.js';
import { usePackageRefusesSaves } from '../hooks/useStudioDesignGate.js';
import { studioPackageId } from '../utils/appRoute.js';
import { LIST_PINNED_VIEW_PREFERENCE, objectPreferenceScope, useWorkspacePreference } from '../utils/workspacePreference.js';
import type { ListViewProps } from '@object-ui/plugin-list';
import { defaultListViewId, isSavedViewId, viewRowId } from '../utils/viewIdentity.js';
Expand Down Expand Up @@ -830,6 +832,14 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
// along, and a column the view does not declare is not offered. Each
// resolves whether the pick was saved; on `false` the grid takes it back.
const personalViewRow = activeView ? personalViews.views.find((v) => v.id === activeView.id) : undefined;
// objectstack#35933 — the open saved shared view's own package (its row's
// served `_packageId`), and whether the server refuses saves into it: a
// view a read-only package ships is offered no save of its own. Read for
// an admin only, the one reader offered such a save; unknown offers it.
const activeSavedViewRow = activeView && isAdmin
? savedViews.find((sv: any) => viewRowId(sv) === activeView.id)
: undefined;
const activeViewPackageRefusesSaves = usePackageRefusesSaves(studioPackageId(activeSavedViewRow));
const handlePickPersonalViewSummary = async (field: string, summary: ColumnSummary | null): Promise<boolean> => {
if (!personalViewRow) return false;
const columns = columnsWithSummary(personalViewRow.config.columns as ListColumn[] | string[] | undefined, field, summary);
Expand Down Expand Up @@ -1122,7 +1132,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
listViewActions: {
rename: activeView && activeIsPersonal && personalViewsReady && personalGrant('update')
? (label: string) => handleRenamePersonalView(String(activeView.id), label)
: activeView && isAdmin && savedViews.some((sv: any) => viewRowId(sv) === activeView.id)
: activeView && isAdmin && !activeViewPackageRefusesSaves && savedViews.some((sv: any) => viewRowId(sv) === activeView.id)
? async (label: string) => { await handleRenameView(String(activeView.id), label); return true; }
: undefined,
save: !isEnvironmentList && canUpdatePersonalView && listPersonalizedParts.length > 0 ? () => { void handleSaveToPersonalView(); } : undefined,
Expand All @@ -1140,10 +1150,13 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co
// views is drawn with. Every stored view has a qualified,
// dotted name, the console's own saved views included
// (`object.key` in the custom package), so the name cannot
// tell a view a read-only package ships; the door refuses
// that save by design (it goes to the custom package) and
// the refused pick is taken back, as the panel's save is.
: isAdmin && isSavedViewId(savedViews, String(activeView.id))
// tell a view a read-only package ships: its row's package
// does (objectstack#35933), and such a view is offered no
// menu. While that is unknown the menu stays; the door
// refuses that save by design (it goes to the custom
// package) and the refused pick is taken back, as the
// panel's save is.
: isAdmin && !activeViewPackageRefusesSaves && isSavedViewId(savedViews, String(activeView.id))
? handlePickSharedViewSummary
: undefined,
summaryPickFields: declaredColumnFields(
Expand Down
13 changes: 12 additions & 1 deletion ui/packages/data-objectstack/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6481,6 +6481,11 @@ export class ObjectStackAdapter<T = unknown> implements DataSource<T> {
// unpublished view (ADR-0037). The overlay tags the item, not its
// nested spec, so read from either.
const isDraft = v._draft === true || spec?._draft === true;
// objectstack#35933 — the package the server served the row under
// (the item's `_packageId`, which the overlay stamps on the item,
// not on a nested spec), carried as served on both arms, so the list
// can tell a view a read-only package ships from one it may save.
const packageId = typeof v._packageId === 'string' && v._packageId !== '' ? v._packageId : undefined;
// Canonical ViewItem (ADR-0017) carries its body under `config`;
// the display `type` (grid/kanban/gallery/…) lives at `config.type`,
// and only the list/form *family* sits at the top level (`viewKind`).
Expand Down Expand Up @@ -6516,9 +6521,15 @@ export class ObjectStackAdapter<T = unknown> implements DataSource<T> {
}
row.isDefault = !!spec.isDefault;
if (isDraft) row._draft = true;
if (packageId !== undefined) row._packageId = packageId;
return row;
}
return isDraft ? { ...spec, _draft: true } : spec;
if (!isDraft && (packageId === undefined || spec?._packageId === packageId)) return spec;
return {
...spec,
...(isDraft ? { _draft: true } : {}),
...(packageId !== undefined ? { _packageId: packageId } : {}),
};
});
} catch (err) {
// Kept verbatim, on every arm. The console breadcrumb was never the
Expand Down
Loading
Loading