diff --git a/.changeset/36905-permission-fullscreen.md b/.changeset/36905-permission-fullscreen.md new file mode 100644 index 00000000000..62a926600d5 --- /dev/null +++ b/.changeset/36905-permission-fullscreen.md @@ -0,0 +1,16 @@ +--- +'@object-ui/app-shell': patch +--- + +feat(studio): a permission set opens full-screen at its metadata address; the record-visibility overview gets its own route + +Clause-②: no +Metadata-protocol: none + +A permission set in Studio now opens at its own address, `/studio/PACKAGE/metadata/permission/NAME`, full-screen beside the left menu, instead of the Access pillar's rail and workbench. The header is the one every full-screen item page has: × back to the list of sets (its filters kept), ‹ › through it, the set's label (its machine name on the title's tooltip), type and package, and a ⋯ menu. The Access pillar's own page and its list of sets are gone. The tab row is the matrix's five sections (Objects, System capabilities, Row-level security, Tab visibility, Delegated admin), then References, History and Source; History replaces the matrix's History sheet and is addressable (`?tab=history`). Save stays the Studio top bar's, and leaving with unsaved edits (×, ‹ ›, the menu, a reload, closing the tab) asks first; the browser's Back button does not ask. + +What the pillar drew around the matrix comes along: Discard draft, Explain access, the suggested-audience strip, and on a read-only base "New similar", now in ⋯ and also on each of the base's rows in the list of sets; the copy opens at its own address with the strip saying where it landed. A draft the AI assistant left (copilot or MCP) shows the designers' notice, and 「放弃 AI 的改动」 drops that one set's draft; a person's own leftover draft keeps Discard draft. + +The organization-wide default sharing overview ("Who can see which records") is a page of its own, `/studio/PACKAGE/owd`, the Access group's menu entry; a set's per-object visibility badge opens it on that object (`?object=NAME`). + +Old addresses keep working: `/studio/PACKAGE/access?surface=permission:NAME` redirects to the set's address (a set a read-only base's `.custom` pair adds, a "New similar" copy among them, to the pair's address, where it opens writable as the pillar opened it), `?surface=owd:overview` to the overview, and a bare `/studio/PACKAGE/access` to the list of sets; other query parameters are kept. `/studio/PACKAGE/metadata/permission/NAME/history` opens the History tab. The cross-package leg (`/studio/~all/...`) keeps the matrix's environment page. No locale keys, props of published packages or exports change: the catalogue rows only the Access pillar read stay in `@object-ui/i18n`, unread. diff --git a/ui/apps/console/src/components/StudioRoute.metadataArea-28561.test.tsx b/ui/apps/console/src/components/StudioRoute.metadataArea-28561.test.tsx index cdc411daca5..1e971dccd4b 100644 --- a/ui/apps/console/src/components/StudioRoute.metadataArea-28561.test.tsx +++ b/ui/apps/console/src/components/StudioRoute.metadataArea-28561.test.tsx @@ -168,6 +168,8 @@ describe('/studio — the "All metadata" area\'s routes (objectstack#28561)', () '/studio/com.example.crm/metadata', // objectstack#36899 — the left menu's targets that are not an area list. '/studio/~org/automations', + // objectstack#36905 — the sharing overview's own route, and the old address that redirects to it. + '/studio/com.example.crm/owd', '/studio/com.example.crm/access?surface=owd%3Aoverview', '/studio/com.example.crm/metadata/_diagnostics', ])( diff --git a/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts b/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts index 14f506ae2cf..a5f524b2399 100644 --- a/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts +++ b/ui/packages/app-shell/src/__tests__/homeRecoveryRedirectsFollowDeclaration-7373.test.ts @@ -143,7 +143,6 @@ const RECOVERY_SITES: ReadonlyArray<{ 'packages/app-shell/src/views/studio-design/StudioPillarKit.tsx', 'packages/app-shell/src/views/studio-design/DataPillarHelpers.tsx', 'packages/app-shell/src/views/studio-design/AutomationsPillar.tsx', - 'packages/app-shell/src/views/studio-design/AccessPillar.tsx', 'packages/app-shell/src/views/studio-design/DataPillar.tsx', ], site: 'Studio: the header Back to app, with no app to name', diff --git a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx index dd5dcb46810..ef11e489ca8 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx @@ -4,14 +4,15 @@ * objectui#12725 (the remainder, item 1) — the permission matrix names its * authoring surface only under the Studio host. * - * `PermissionMatrixEditPage` serves two hosts: Studio's Access pillar mounts it + * `PermissionMatrixEditPage` serves two hosts: Studio's permission set page + * (objectstack#36905; the Access pillar before it) mounts it * with `packageId` and `embedded`, and its draft save is a person's edit in * Studio, so it sends `?surface=studio` (recorded as `by: 'studio'` in the * draft's `draftChanges`, objectstack#24395). metadata-admin mounts it through * the resource registry with only `type` and `name`: its save is the * environment door's live write and states no surface. * - * Both hosts are the REAL ones (`AccessPillar`, `MetadataResourceEditPage` + * Both hosts are the REAL ones (`StudioPermissionSetPage`, `MetadataResourceEditPage` * through the built-in registration), and the save goes through a REAL * `MetadataClient` whose transport records each `PUT`, so the pins read the * query string the server would read. @@ -89,7 +90,7 @@ vi.mock('../studio-design/StudioAiCopilot', () => ({ StudioChatDock: () => null import '../../services/builtinComponents.js'; import { MetadataResourceEditPage } from './ResourceEditPage'; -import { AccessPillar } from '../studio-design/StudioDesignSurface'; +import { StudioPermissionSetPage } from '../studio-design/StudioPermissionSetPage'; import { StudioSaveHarness, pressStudioSave } from '../studio-design/__tests__/studioSaveHarness'; window.matchMedia = ((query: string) => ({ @@ -115,11 +116,11 @@ beforeEach(() => { afterEach(cleanup); describe('the permission matrix states `surface` only under the Studio host (objectui#12725)', () => { - it('Studio’s Access pillar: the draft save sends `?surface=studio`, once', async () => { + it('Studio’s permission set page: the draft save sends `?surface=studio`, once', async () => { render( - + , ); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.studioSave-36511.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.studioSave-36511.test.tsx index 71c97611dd7..c1b5d597fd6 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.studioSave-36511.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.studioSave-36511.test.tsx @@ -1,8 +1,9 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectstack#36511 — a permission set in the Studio's Access pillar saves with - * the top bar's Save and Cancel, and a Save is live at once. + * objectstack#36511 — a permission set in Studio (since objectstack#36905 on + * its full-screen page) saves with the top bar's Save and Cancel, and a Save + * is live at once. * * - A grant clicked sends nothing: no draft write leaves before Save is * pressed, however long the page waits (the set's 1.5 s autosave is gone @@ -13,7 +14,7 @@ * - A refused publish keeps the grant unsaved, says why on the page, and takes * back the draft the Save wrote. * - * The REAL `AccessPillar` inside the top bar's coordinator; the writes go + * The REAL `StudioPermissionSetPage` inside the top bar's coordinator; the writes go * through a REAL `MetadataClient` whose transport records each one, so the pins * read the URL the server would read. The environment door (metadata-admin, * no package) keeps its own Save and live write: pinned in @@ -101,7 +102,7 @@ vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPan vi.mock('../studio-design/StudioAiCopilot', () => ({ StudioChatDock: () => null })); import { toast } from 'sonner'; -import { AccessPillar } from '../studio-design/StudioDesignSurface'; +import { StudioPermissionSetPage } from '../studio-design/StudioPermissionSetPage'; import { StudioSaveHarness, pressStudioCancel, pressStudioSave } from '../studio-design/__tests__/studioSaveHarness'; import { tFormat } from './i18n'; @@ -130,7 +131,7 @@ async function mount(): Promise { render( - + , ); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.tsx b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.tsx index 55c761de980..93541cee3c2 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.tsx @@ -106,7 +106,7 @@ import { useDraftAutoSave, type DraftSend } from '../studio-design/useDraftAutoS // objectstack#36511 — in the Studio the set is sent by the top bar's Save, which makes it live. import { publishSavedItem, useStudioSaveEntry, type StudioSaveResult } from '../studio-design/studioSaveBar.js'; import { publishFailureOf, publishRefusal } from '../studio-design/metadataError.js'; -// objectui#12456 — the Studio Access pillar's presentation draws the shared item header. +// objectui#12456 — the Studio presentation draws the shared item header when no frame draws one. import { StudioItemHeader, StudioTab } from '../studio-design/StudioItemHeader.js'; import type { CustomizationMarkKind } from '../studio-design/customizationMarks.js'; import { useDisplayLocale } from '@object-ui/i18n'; @@ -139,7 +139,7 @@ import { holdingOfRead, holdingPackage, type PermissionSetHolding } from './perm import { isEnvironmentScope, useWalledCatalogReadOnly } from './catalog-scope.js'; import { useCanAuthorMetadata, useCanReadAuthoringTrail } from '../../hooks/useCanAuthorMetadata.js'; import { errorCodeIs } from '@object-ui/types'; -import { formatMetadataError, type MetadataError } from '@object-ui/data-objectstack'; +import { formatMetadataError, readDraftChanges, type DraftChange, type MetadataError } from '@object-ui/data-objectstack'; import { PermissionSetCloneDialog } from './PermissionSetCloneDialog.js'; import { isStudioHiddenSystemField } from '../studio-design/studioHiddenSystemField.js'; import { permissionSetCloneNoticeText, type PermissionSetCloned } from './permission-set-clone.js'; @@ -520,9 +520,10 @@ function headersAbbreviate(actions: ReturnType, locale: } /** - * objectui#12456 — the five tabs of the Studio Access pillar's permission-set - * page (epic objectui#12446, decision C): each holds one of the sections the - * routed page stacks in one column. + * objectui#12456 — the five tabs of the Studio's permission-set page (epic + * objectui#12446, decision C; since objectstack#36905 the set's full-screen + * page, `StudioPermissionSetPage`): each holds one of the sections the routed + * page stacks in one column. */ export type PermissionStudioTab = 'objects' | 'capabilities' | 'rls' | 'tabs' | 'admin'; @@ -534,26 +535,71 @@ export const PERMISSION_STUDIO_TABS: ReadonlyArray<{ key: PermissionStudioTab; l { key: 'admin', labelKey: 'engine.studio.access.tab.admin' }, ]; -/** What the Studio Access pillar hands the page for its tabbed presentation. */ +/** What the Studio host (`StudioPermissionSetPage`) hands the page for its tabbed presentation. */ export interface PermissionStudioChrome { - /** The open tab; the pillar holds it (default `objects`). */ + /** The open tab; the host holds it (default `objects`). */ tab: PermissionStudioTab; onTabChange: (tab: PermissionStudioTab) => void; - /** Before the header's icon tile (the pillar's mobile rail toggle). */ + /** Before the header's icon tile. Drawn only without a {@link frame}. */ leading?: React.ReactNode; - /** The pillar's draft / read-only note, at the right end of the tab row. */ + /** A draft / read-only note at the right end of the tab row. Drawn only without a {@link frame}. */ chips?: React.ReactNode; - /** Before History in the header's actions (the pillar's Explain access). */ + /** Before History in the header's actions. Drawn only without a {@link frame}. */ actions?: React.ReactNode; /** * objectstack#32774 — told, for the set `name` this editor shows, the * package the clone door must name to copy it (`holdingPackage` of the * holding this editor read): `undefined` where the name alone addresses it - * (one holder, the environment's own set) or no holder was read. The pillar - * hosts its own clone dialog ("New similar") and passes it as + * (one holder, the environment's own set) or no holder was read. The Studio + * host keeps its own clone dialog ("New similar") and passes it as * `sourcePackage`. */ onCloneSourceRead?: (name: string, sourcePackage: string | undefined) => void; + /** + * objectstack#36905 — the full-screen item page's frame (`StudioPermissionSetPage`): + * the host draws the header (`StudioDetailHeader`) from the parts this page + * hands it, and its tab row carries the item tools (References, History, + * Source) after the five section tabs, so History is a tab there and this + * page draws no History button. Omitted, the page draws its own + * `StudioItemHeader`: no Studio host mounts it that way since the Access + * pillar was deleted (objectstack#36905), and only this page's own unit + * tests draw it; the pillar's leftovers go with objectstack#36909. + */ + frame?: PermissionStudioFrame; +} + +/** The pieces of the page's header a {@link PermissionStudioFrame} host composes. */ +export interface PermissionStudioHeaderParts { + /** The set's label, or its name before one is known. */ + title: string; + /** The line under the title: provenance, default and lock labels. */ + note: React.ReactNode; + /** The granted-object and field-override counts, once loaded. */ + meta?: string; + /** The page's own actions: the save status, the environment's Save, the artifact tier's Clone. */ + actions: React.ReactNode; + /** The page's own ⋯ items (`DropdownMenuItem`s): the name and label editor. */ + menuItems: React.ReactNode; + /** The five section tabs (`StudioTab`s), none active while {@link PermissionStudioFrame.toolOpen}. */ + sectionTabs: React.ReactNode; +} + +export interface PermissionStudioFrame { + /** Draw the header from the page's parts. */ + renderHeader: (parts: PermissionStudioHeaderParts) => React.ReactNode; + /** + * An item tool's panel is open in place of the sections: they stay mounted + * and hidden, so an edit survives the visit, and no section tab is active. + */ + toolOpen?: boolean; + /** The open tool's panel, drawn in the body while {@link toolOpen}. */ + toolPanel?: React.ReactNode; + /** + * Told, on every load, who wrote the set's pending draft: its per-key + * provenance (`draftChanges`), `null` with no draft or none recorded. The + * host draws the AI-draft notice from it (epic decision 1). + */ + onDraftChangesRead?: (changes: DraftChange[] | null) => void; } export interface PermissionMatrixEditPageProps { @@ -589,21 +635,20 @@ export interface PermissionMatrixEditPageProps { /** * objectui#2505 — when provided, the per-object OWD badge becomes a link that * opens the package-level Record Sharing Baseline (OWD) overview, scrolled to - * that object. Set only by the Studio Access pillar (which hosts the sibling - * overview surface); omitted at environment scope / metadata-admin, where the - * badge stays a plain read-only chip. + * that object. Set only by the Studio host (objectstack#36905: the overview + * is its own route, `/studio//owd`); omitted at environment scope / + * metadata-admin, where the badge stays a plain read-only chip. */ onOpenOwd?: (objectName: string) => void; /** * Fires on every unsaved-edit transition (false → true → false). The Studio - * Access pillar keys this page per set (`key={name}`) and swaps it out for - * the OWD overview, so the HOST must know before a surface switch whether a - * remount would discard edits. Reset to `false` on unmount so a discarded + * host keys this page per set, so the HOST must know before a departure + * whether a remount would discard edits. Reset to `false` on unmount so a discarded * editor never leaves the host thinking edits are still pending. */ onDirtyChange?: (dirty: boolean) => void; /** - * Host-level read-only gate — set by the Studio Access pillar when the + * Host-level read-only gate — set by the Studio host when the * surrounding PACKAGE is read-only. Independent of the TYPE-level * `allowEnvironmentOverlay` writability: either gate locks the matrix (checkboxes, * bulk buttons, name/label, facets), hides Save, and shows the read-only @@ -612,17 +657,18 @@ export interface PermissionMatrixEditPageProps { */ readOnly?: boolean; /** - * When true, the editor is hosted inside another surface (the Studio Access - * pillar) rather than the routed metadata admin. Relative navigation would - * resolve against the HOST's route (`/studio/:packageId/access/...`), where - * the metadata-admin routes don't exist — so History opens as an in-place + * When true, the editor is hosted inside another surface (the Studio's + * permission-set page) rather than the routed metadata admin. Relative + * navigation would resolve against the HOST's route, where the + * metadata-admin routes don't exist — so History opens as an in-place * sheet instead of navigating, and the PageShell breadcrumb loses its * `/metadata` links (same rule as MetadataResourceEditPage's `embedded`). */ embedded?: boolean; /** - * objectui#12456 — the Studio Access pillar's presentation (set with - * `embedded`). The page draws the Studio item header (the set's label, api + * objectui#12456 — the Studio presentation (set with `embedded`; since + * objectstack#36905 by `StudioPermissionSetPage`, with a {@link + * PermissionStudioChrome.frame}). The page draws the Studio item header (the set's label, api * name, Package chip, granted / override counts, History and a more menu * holding the name / label editor) instead of the PageShell breadcrumb, * badge row and collapsible set header, and splits its sections into five @@ -637,7 +683,7 @@ export interface PermissionMatrixEditPageProps { * draws for this set (`customizationMarks.ts`, the one rule): on a read-only * base, `'added'` for a set its `.custom` pair holds (a New similar * copy or a set created there), `'customized'` for a served override of a - * base set. Set only by the Studio Access pillar; omitted (Setup, the + * base set. Set only by the Studio host; omitted (Setup, the * metadata admin) or `null` (no mark, or the read has not answered), * nothing changes. Read by the provenance badge alone. */ @@ -709,7 +755,7 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, // the block below the state declaration for why the type tier alone is // not the whole gate. // - // • HOST gate — the package-level `readOnly` prop the Studio Access pillar + // • HOST gate — the package-level `readOnly` prop the Studio host // passes for a read-only package. UNCHANGED and still dominant: this is // the "Studio 维持包级只读" half of the objectstack#5768 ruling, and a // code-defined package stays locked here exactly as before. @@ -836,6 +882,8 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, const cloneSourcePackage = holdingPackage(assignmentsHolding ?? undefined); const onCloneSourceReadRef = React.useRef(studio?.onCloneSourceRead); onCloneSourceReadRef.current = studio?.onCloneSourceRead; + const onDraftChangesReadRef = React.useRef(studio?.frame?.onDraftChangesRead); + onDraftChangesReadRef.current = studio?.frame?.onDraftChangesRead; React.useEffect(() => { onCloneSourceReadRef.current?.(name, cloneSourcePackage); }, [name, cloneSourcePackage]); @@ -1119,6 +1167,7 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, } const pendingDraft = pendingRead?.answer ?? null; hadDraftRef.current = !!pendingDraft; + onDraftChangesReadRef.current?.(pendingDraft ? readDraftChanges(pendingDraft) : null); verdictReadSeq.current += 1; setServedVerdict( editedItemDiagnostics({ @@ -1627,7 +1676,7 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, // answers the 404 shape, which `MetadataClient.layered` resolves as // `{ effective: null, … }` — that arm keeps the `?? payload` base on // purpose: a set that exists only as a package draft (what the Studio - // Access pillar's "+ New" creates) has no published rows for anyone to + // create leaves before its first publish) has no published rows for anyone to // lose, and refusing there would block its first save. // // objectstack#26837 — and this door's save WRITES the pending draft, so @@ -1670,7 +1719,7 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, // objectui#11773 — the guard pins the package door's DRAFT save; the // environment door's live write passes through it unpinned, as before. // objectui#12725 — the draft names its authoring surface only under the - // Studio host (`embedded`, the Access pillar), so a person's edit there + // Studio host (`embedded`, the set's Studio page), so a person's edit there // is recorded `studio`, not `api`. metadata-admin mounts this page with // neither `packageId` nor `embedded`, and states no surface. const outcome = await saveVersioned(type, payload.name, toSave, { @@ -1976,7 +2025,7 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, ); // objectui#12456 — the pieces both presentations draw: the routed page - // (PageShell) and the Studio Access pillar's tabbed one (`studio`). + // (PageShell) and the Studio's tabbed one (`studio`). const envSaveEl = ( <> {/* ADR-0086 D7 — the environment door's explicit Save: a live write. */} @@ -2417,33 +2466,64 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, // set's machine name is the title's tooltip, and the provenance, default // and lock labels are the line under it. const studioTitle = headerLabel || name; + const frame = chrome.frame; + const titleNoteEl = ( + + {/* Same test id and the same answer as the page's badge. */} + {/* objectstack#35018 — in the builder's words: a set the app + brings reads 「随应用提供」, not the package term 「包内置」. */} + + {shippedByPackage ? t('engine.studio.access.origin.app') : t('perm.badge.custom')} + + {!!draft.isDefault && ( + <> + + {t('perm.badge.default')} + + )} + {/* A host-locked package says so in the host's note; the + other gates (type, artifact, wall) keep their own badge. */} + {!readOnly && lockBadgeEl} + + ); + const basicsItemEl = ( + setBasicsOpen((o) => !o)}>{t('perm.basics.editHint')} + ); + const sectionTabsEl = PERMISSION_STUDIO_TABS.map((tab) => ( + chrome.onTabChange(tab.key)} + > + {t(tab.labelKey)} + + )); return (
+ {frame ? ( + frame.renderHeader({ + title: studioTitle, + note: titleNoteEl, + meta, + actions: ( + <> + {autosaveStatusEl} + {envSaveEl} + {lockedByArtifactTier && cloneButton} + + ), + menuItems: basicsItemEl, + sectionTabs: sectionTabsEl, + }) + ) : ( - {/* Same test id and the same answer as the page's badge. */} - {/* objectstack#35018 — in the builder's words: a set the app - brings reads 「随应用提供」, not the package term 「包内置」. */} - - {shippedByPackage ? t('engine.studio.access.origin.app') : t('perm.badge.custom')} - - {!!draft.isDefault && ( - <> - - {t('perm.badge.default')} - - )} - {/* A host-locked package says so in the pillar's note; the - other gates (type, artifact, wall) keep their own badge. */} - {!readOnly && lockBadgeEl} - - } + note={titleNoteEl} meta={meta} actions={ <> @@ -2475,26 +2555,13 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, - - setBasicsOpen((o) => !o)}> - {t('perm.basics.editHint')} - - + {basicsItemEl} } tabs={ <> - {PERMISSION_STUDIO_TABS.map((tab) => ( - chrome.onTabChange(tab.key)} - > - {t(tab.labelKey)} - - ))} + {sectionTabsEl} {/* The pillar's draft / read-only note, whole, at the tab row's right: in the title row it squeezed the label and the counts at the 1280 px design width. */} @@ -2502,14 +2569,23 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, } /> + )} + {frame?.toolOpen &&
{frame.toolPanel}
} {loading ? ( -
- {t('perm.loading').replace('{name}', name)} -
+ !frame?.toolOpen && ( +
+ {t('perm.loading').replace('{name}', name)} +
+ ) ) : draftRefusedEl ? ( - draftRefusedEl + !frame?.toolOpen && draftRefusedEl ) : ( -
+ // objectstack#36905 — kept mounted under an open item tool, so an + // edit survives the visit. +
{noticesEl} {basicsOpen && (
diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx index 831aed3a963..22c352f8e59 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx @@ -100,6 +100,9 @@ import { resolveAffordance, type SchemaLike } from '@object-ui/core'; import { useAdapter, useMetadata } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; import { SharingRuleCloneDialog, type SharingRuleCloneDialogProps } from './SharingRuleCloneDialog.js'; +import { PermissionSetCloneDialog } from './PermissionSetCloneDialog.js'; +import { permissionSetCloneNoticeText } from './permission-set-clone.js'; +import { newSimilarOutcome } from '../studio-design/permissionNewSimilar.js'; import { postureHasOrgWall, useTenancyPosture } from '../../hooks/useTenancyPosture.js'; import { applyListState, @@ -355,6 +358,10 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string }).allowed; const CloneDialog = authoredObject && canClone ? DECLARATION_CLONE_DIALOGS[type] : undefined; const [cloning, setCloning] = React.useState | null>(null); + // objectstack#36905 — "New similar" on a read-only base's permission sets in + // Studio's area, where the Access pillar's rail offered it before: the clone + // door picks the package, and the copy opens at its own address. + const [newSimilarFrom, setNewSimilarFrom] = React.useState<{ name: string; sourcePackage?: string } | null>(null); // Studio is scoped to a single *project* package at a time. Load the // installed packages and keep only project-scoped ones — anything not @@ -842,6 +849,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string size="sm" variant={config.createFields ? 'default' : 'outline'} onClick={handleCreate} + data-testid="metadata-list-create" title={ config.createFields ? tFormat('engine.list.createHint', locale, { type: typeLabel }) @@ -927,6 +935,8 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string // then the row's controls — the Active switch, Clone, or both in one cell — // pinned at its right edge (objectui#13091). One column, because the grid // holds one column at that edge. + // On the base's own rows only: a row its pair adds is writable where it opens. + const newSimilarRows = type === 'permission' && !!host?.packageId && host.readOnly === true && canAuthor && !walled; const gridColumns: MetadataGridColumn[] = [ ...shownColumns.map((c, ci) => ({ key: c.key, @@ -936,7 +946,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string // objectstack#36898 — the item's change time and its pending-draft mark. { key: CHANGED_COLUMN, label: t('engine.list.col.changedAt', locale) }, { key: SOURCE_COLUMN, label: t('engine.list.col.source', locale) }, - ...(activation || CloneDialog + ...(activation || CloneDialog || newSimilarRows ? [ { key: CONTROLS_COLUMN, @@ -1140,12 +1150,26 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string ); }; - if (activation || CloneDialog) { + if (activation || CloneDialog || newSimilarRows) { cellDraws[pageField(CONTROLS_COLUMN)] = (_value, rec) => { const info = rowInfoOf(rec); if (!info) return null; + const newSimilar = newSimilarRows && (!info.rowPkg || info.rowPkg === host?.packageId); return ( + {newSimilar && ( + + )} {activation && ( {t('engine.catalog.declaredOnly.switchReadOnly', locale)}
)} + {newSimilarFrom && ( + setNewSimilarFrom(null)} + onCloned={(copy) => { + setNewSimilarFrom(null); + const outcome = newSimilarOutcome(copy); + if ('open' in outcome) { + navigate(outcome.open.to, { state: outcome.open.state }); + return; + } + // Nothing to open: said where the person is, in the strip's words. + toast.warning( + outcome.strip.kind === 'noPackage' + ? tFormat('engine.studio.access.newSimilar.noPackage', locale, { name: outcome.strip.name }) + : t('perm.clone.noName', locale), + outcome.strip.notice + ? { + description: permissionSetCloneNoticeText( + { notice: outcome.strip.notice, noticeCode: outcome.strip.noticeCode, package: null }, + locale, + ), + } + : undefined, + ); + }} + /> + )} {cloning && CloneDialog && ( > = []; + const CLIENT = { list: async (type: string) => type === 'package' @@ -43,7 +54,7 @@ const CLIENT = { { manifest: { id: PROJECT, scope: 'project', name: 'CRM' } }, ] : type === 'permission' - ? PERMISSION_SETS + ? [...PERMISSION_SETS, ...EXTRA_SETS] : [], }; @@ -94,7 +105,7 @@ vi.mock('../../hooks/useCanAuthorMetadata', async (importOriginal) => ({ import { MetadataDirectoryPage } from './DirectoryPage'; import { MetadataResourceListPage } from './ResourceListPage'; -import { t } from './i18n'; +import { t, tFormat } from './i18n'; beforeEach(() => { vi.stubGlobal( @@ -112,6 +123,8 @@ beforeEach(() => { afterEach(() => { cleanup(); vi.unstubAllGlobals(); + vi.restoreAllMocks(); + EXTRA_SETS.length = 0; }); const crmArea = (readOnly = false): MetadataAreaHost => ({ @@ -193,7 +206,9 @@ describe('the directory under the area (objectstack#28561)', () => { describe('the list under the area', () => { const rowLink = (container: HTMLElement, name: string) => container.querySelector(`a[href*="/${name}"]`); - const createButton = () => screen.queryByRole('button', { name: new RegExp(t('engine.list.create', 'en-US')) }); + // By its test id: a read-only base's row offers "New similar" (objectstack#36905), which is no + // create, and a label query would match it. + const createButton = () => screen.queryByTestId('metadata-list-create'); it('a package\'s area lists that package\'s rows, with no repair, and offers create', async () => { const { container } = mount(crmArea(), `/studio/${PROJECT}/metadata/permission?package=${PROJECT}`, ); @@ -231,3 +246,93 @@ describe('the list under the area', () => { expect(where()).toBe('/studio/~all/metadata/permission?scope=environment'); }); }); + +/** + * objectstack#36905 (card item 2) — "New similar" on the rows of a read-only + * base's list of sets: the row action the Access pillar's rail had, on the + * REAL list page, over the REAL clone dialog and clone door (`fetch`). + */ +describe('"New similar" on a read-only base\'s rows (objectstack#36905)', () => { + const PAIR = `${PROJECT}.custom`; + const LIST_URL = `/studio/${PROJECT}/metadata/permission?package=${PROJECT}`; + const newSimilar = (name: string) => screen.queryByTestId(`list-new-similar-${name}`); + + /** The clone door answers `data`; every other read answers as the harness does. */ + function serveClone(data: Record) { + const calls: string[] = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => { + const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + if (String(url).includes('/security/permission-sets/')) { + calls.push(String(url)); + return json(200, { success: true, data }); + } + if (String(url).startsWith('/api/v1/data/sys_metadata_activation')) { + return json(200, { object: 'sys_metadata_activation', records: [], hasMore: false }); + } + return json(404, { success: false }); + }), + ); + return calls; + } + + async function openBaseList() { + EXTRA_SETS.push({ name: 'crm_rep_copy', label: 'CRM Rep copy', _packageId: PAIR, _provenance: 'package' }); + const view = mount(crmArea(true), LIST_URL, ); + await waitFor(() => expect(rowLink(view.container, 'crm_rep')).not.toBeNull()); + await waitFor(() => expect(rowLink(view.container, 'crm_rep_copy')).not.toBeNull()); + return view; + } + + async function copyFrom(name: string) { + fireEvent.click(newSimilar(name)!); + const dialog = await screen.findByRole('dialog'); + fireEvent.change(within(dialog).getByLabelText(t('perm.clone.name', 'en-US')), { target: { value: 'my_rep' } }); + fireEvent.change(within(dialog).getByLabelText(t('perm.clone.label', 'en-US')), { target: { value: 'My rep' } }); + fireEvent.click(within(dialog).getByRole('button', { name: t('perm.clone.confirm', 'en-US') })); + } + + const rowLink = (container: HTMLElement, name: string) => container.querySelector(`a[href*="/${name}?"]`); + + it("the base's own row offers it; its pair's row does not", async () => { + serveClone({}); + await openBaseList(); + expect(newSimilar('crm_rep')).toBeInTheDocument(); + expect(newSimilar('crm_rep_copy')).toBeNull(); + }); + + it('the copy opens at its metadata address in the package the clone door names', async () => { + const calls = serveClone({ permissionSet: { name: 'my_rep', label: 'My rep' }, package: PAIR, notice: 'Saved.' }); + await openBaseList(); + await copyFrom('crm_rep'); + await waitFor(() => + expect(where()).toBe(`/studio/${PAIR}/metadata/permission/my_rep?package=${encodeURIComponent(PAIR)}`), + ); + expect(calls).toHaveLength(1); + expect(calls[0]).toContain('/security/permission-sets/crm_rep/clone'); + }); + + it('an answer naming no package opens nothing and says so', async () => { + const warning = vi.spyOn(toast, 'warning'); + serveClone({ permissionSet: { name: 'my_rep', label: 'My rep' }, notice: 'Saved.' }); + await openBaseList(); + await copyFrom('crm_rep'); + await waitFor(() => + expect(warning).toHaveBeenCalledWith( + tFormat('engine.studio.access.newSimilar.noPackage', 'en-US', { name: 'my_rep' }), + expect.anything(), + ), + ); + expect(where()).toBe(LIST_URL); + }); + + it('CONTROL: a writable package offers no New similar, and offers create', async () => { + serveClone({}); + const { container } = mount(crmArea(), LIST_URL, ); + await waitFor(() => expect(rowLink(container, 'crm_rep')).not.toBeNull()); + expect(newSimilar('crm_rep')).toBeNull(); + expect(screen.getByTestId('metadata-list-create')).toBeInTheDocument(); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/AccessPillar.tsx b/ui/packages/app-shell/src/views/studio-design/AccessPillar.tsx deleted file mode 100644 index 364777d4e56..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/AccessPillar.tsx +++ /dev/null @@ -1,1115 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * The Access pillar — the permission-set rail and the embedded permission - * workbench — with its "New similar" arrival reader and the list-row name - * label only it draws, moved out of `StudioDesignSurface.tsx` unchanged by - * objectstack#36893 (the move-only split's pillar slice; the surface - * re-exports it). - */ - -import * as React from 'react'; -import { useNavigate, useLocation } from 'react-router-dom'; -import { formatMetadataError } from '@object-ui/data-objectstack'; -import { type I18nLabel } from '@objectstack/spec/ui'; -import { type StudioSurfaceLabel } from './StudioAiCopilot.js'; -import { StudioItemHeader, StudioStatusChip, type StudioItemStatus } from './StudioItemHeader.js'; -import { StudioRail, StudioRailRow } from './StudioRail.js'; -import { StudioEmptyState, StudioEmptyStateAction } from './StudioEmptyState.js'; -import { pairIdOf } from './AutomationsFlowRail.js'; -import { - confirmDropUnsavedWork, - CreateTakenNotice, - findTakenIdentifier, - type StudioBaseCustomization, - StudioReadOnlyLink, -} from './StudioPillarKit.js'; -import { useIsMobile } from '@object-ui/components'; -import { Copy, Shield, ShieldCheck, ShieldQuestion, Menu, Undo2 } from 'lucide-react'; -import { PermissionMatrixEditPage, type PermissionStudioTab } from '../metadata-admin/PermissionMatrixEditor.js'; -import { AccessExplainPanel } from '../metadata-admin/AccessExplainPanel.js'; -import { useMetadataClient } from '../metadata-admin/useMetadata.js'; -import { publishSavedItem } from './studioSaveBar.js'; -import { studioPillarItemPath } from './metadataArea.js'; -import { PermissionSetCloneDialog } from '../metadata-admin/PermissionSetCloneDialog.js'; -import { permissionSetCloneNoticeText, type PermissionSetCloned } from '../metadata-admin/permission-set-clone.js'; -import { useWalledCatalogReadOnly } from '../metadata-admin/catalog-scope.js'; -import { useCanAuthorMetadata } from '../../hooks/useCanAuthorMetadata.js'; -import { useMetadataRefreshNonce } from './useMetadataRefreshNonce.js'; -import { useSurfaceDeepLink, resolveSurfaceDeepLink } from './useSurfaceDeepLink.js'; -import { buildPermissionSkeleton } from './skeletons.js'; -import { t, tFormat, translateMetadataType, useMetadataLocale } from '../metadata-admin/i18n.js'; -import { SuggestedBindingsPanel } from '../../components/SuggestedBindingsPanel.js'; -import type { SuggestedBinding } from '../../services/suggestedBindingsApi.js'; -import { suggestedSetLabel as suggestedSetLabelOf } from '../../components/suggestedSetLabel.js'; -import { - navItemLabelText, -} from '../metadata-admin/previews/navItemLabel.js'; -import { errorCodeIs } from '@object-ui/types'; -import { CreateItemDialog } from './CreateItemDialog.js'; -import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel.js'; -import { - RailCustomizationFilter, - RailCustomizationMark, - StudioPairItemChip, - railCustomizationsOf, - useDeepLinkFallback, - useRailCustomizationsOnly, -} from './StudioRailCustomizations.js'; -import { toast } from 'sonner'; - -/** - * A Studio list row's name (objectui#11862, on the maintainer's word - * 「所有地方以标签为主,机器名只作为次要信息」): the label as the primary text, and - * the machine name beneath it as secondary text — smaller and monospace — when - * it differs from the label. With no label the name alone is the text. - * - * Display only: it reads what the row already holds and writes nothing. The - * secondary name is `aria-hidden`, so a row's accessible name stays the label - * it was; the nav rail carries the machine name for assistive tech on the - * row's `title` (`type · name`), as it did before. - */ -function StudioNameLabel({ label, name }: { label: string; name?: string }): React.ReactElement { - const primary = label.trim() ? label : (name ?? ''); - const secondary = name && name !== primary ? name : ''; - return ( - - {primary} - {secondary ? ( - - ) : null} - - ); -} - -/** - * objectstack#28573 — what the Access pillar's "New similar" strip says: the - * copy the clone door saved (shown on that copy, in the package the answer - * named), or an answer the pillar could not open (no copy named, or no - * package). `notice` is the server's sentence, and `noticeCode` the code it - * names it by (objectstack#29727): shown in the console's language for a known - * code, as sent otherwise. - */ -type NewSimilarStrip = - | { kind: 'landed'; name: string; package: string; notice: string; noticeCode?: string } - | { kind: 'noPackage'; name: string; notice: string; noticeCode?: string } - | { kind: 'noName'; notice: string; noticeCode?: string }; - -/** The navigation-state key the copy's landing rides to the copy's pillar on. */ -const NEW_SIMILAR_ARRIVAL_STATE = 'accessNewSimilar'; - -/** - * The landing a "New similar" navigation carried, for the pillar it opened: - * kept only when it names THIS package, so a stale history entry of another - * package's pillar shows nothing. - */ -function readNewSimilarArrival(state: unknown, packageId: string): NewSimilarStrip | null { - const arrival = (state as Record | null | undefined)?.[NEW_SIMILAR_ARRIVAL_STATE] as - | Partial> - | undefined; - if (!arrival || arrival.kind !== 'landed' || arrival.package !== packageId || typeof arrival.name !== 'string') { - return null; - } - return { - kind: 'landed', - name: arrival.name, - package: packageId, - notice: typeof arrival.notice === 'string' ? arrival.notice : '', - ...(typeof arrival.noticeCode === 'string' ? { noticeCode: arrival.noticeCode } : {}), - }; -} - -/** - * Access pillar — the permission workbench (builder-ui §7, ADR-0084's fourth - * content pillar). Left rail: the environment's permission sets / profiles; - * main: the Salesforce-style PermissionMatrixEditPage (objects × CRUD/VAMA + - * field-level R/W). - * - * Scope note (ADR-0086 P0/P1/P2): the pillar is scoped to the current package. - * The left rail lists only permission sets this package owns — the metadata API - * filters `permission` by the record-level `package_id` provenance server-side - * (P1), so environment-owned platform defaults (`admin_full_access`, - * `member_default`, …) are excluded by the backend. The object MATRIX lists only - * the objects this package declares, and Save merges just that slice back, - * leaving other packages' contributed rows untouched (P0). Save writes a package - * DRAFT and publishes with the whole package via the top-bar Publish (P2, D6). - */ -// Exported for tests — routed only through StudioDesignSurface in production. -export function AccessPillar({ - packageId: railPackageId, - publishNonce, - onDraftSaved, - readOnly: packageReadOnly = false, - customization = null, - onDirtyChange, - onSurfaceLabelChange, -}: { - packageId: string; - publishNonce?: number; - onDraftSaved?: () => void; - /** Courtesy gate: hide/disable permission-authoring affordances. */ - readOnly?: boolean; - /** objectstack#28572 — on a read-only base, its pair: the rail lists the pair's sets too, and New lands there. */ - customization?: StudioBaseCustomization | null; - /** objectui#2600 — mirrors the pillar's unsaved-edit state (permission - * matrix or OWD overview rows) up to the Studio header, whose - * pillar/Home/package navigation unmounts this whole pillar (SPA nav, so no - * beforeunload). Reports `false` when the pillar unmounts, same contract as - * PermissionMatrixEditPage's own onDirtyChange. */ - onDirtyChange?: (dirty: boolean) => void; - /** - * objectstack#35018 — the open set's label (or the record-visibility - * overview's title) for the copilot's chip: 「正在看:权限 · 组织成员」, - * never the type word and machine name. Same seam as the Data and - * Interfaces pillars' reports. - */ - onSurfaceLabelChange?: (surface: StudioSurfaceLabel | null) => void; -}): React.ReactElement { - const client = useMetadataClient(); - const locale = useMetadataLocale(); - // See DataPillar's rail — same mobile-overlay treatment for the permission-set list. - const isMobile = useIsMobile(); - const [railOpen, setRailOpen] = React.useState(false); - // objectui#7255 — same live-pulse subscription as the sibling rails; this - // one only replaces the permission-set LIST, so no edit-buffer hold. - const metadataRefreshNonce = useMetadataRefreshNonce(); - const [perms, setPerms] = React.useState< - Array<{ name: string; label: string; isDefault?: boolean; addedIn?: string }> - >([]); - const [loaded, setLoaded] = React.useState(false); - const [error, setError] = React.useState(null); - const [current, setCurrent] = React.useState(null); - // objectstack#28572 (ADR-0146 D3) — the rail is the base's; on a read-only - // base it lists the sets its pair adds too, and New lands in the pair. A set - // the pair adds opens writable, read and saved at the pair: the open set's - // matrix names `packageId` and asks `readOnly`, the open set's own. The - // package-wide surfaces (the OWD overview, suggested bindings, Explain) - // stay the base's. - const railPairId = packageReadOnly && customization ? customization.pairId : null; - const railMarks = railCustomizationsOf(customization?.marks, railPackageId); - const [onlyCustomized, toggleOnlyCustomized] = useRailCustomizationsOnly(); - const newInPair = packageReadOnly && customization !== null && !customization.walled; - const currentAddedIn = perms.find((p) => p.name === current)?.addedIn; - const packageId = currentAddedIn ?? railPackageId; - const readOnly = packageReadOnly && !currentAddedIn; - // The Record Sharing Baseline (OWD) overview is a sibling surface to the - // permission-set matrix (objectui#2505) — same package-author ownership - // boundary, no principal dimension. `owdOpen` swaps the main panel to it; - // `owdHighlight` carries the object a permission-matrix badge deep-linked to. - const [owdOpen, setOwdOpen] = React.useState(false); - const [owdHighlight, setOwdHighlight] = React.useState(null); - const appliedOwdDeepLink = React.useRef(false); - // `?surface=permission:` / `?surface=owd:overview` capture + mirror — - // shared plumbing (see useSurfaceDeepLink). This rail keys `current` by name, - // so wrap the open surface in the identity the param carries. - const currentSurface = React.useMemo( - () => - owdOpen - ? { type: 'owd', name: 'overview' } - : current - ? { type: 'permission', name: current } - : null, - [owdOpen, current], - ); - const initialSurface = useSurfaceDeepLink(currentSurface); - // objectstack#28572 — see `useDeepLinkFallback`. - const deepLinkUpgrade = useDeepLinkFallback(); - // objectstack#35018 — lift the open set's label to the copilot's chip, the - // pillar's word first: 「正在看:权限 · 组织成员」. Keyed on primitives, the - // callback read through a ref (the Data pillar's report). - const onSurfaceLabelChangeRef = React.useRef(onSurfaceLabelChange); - React.useEffect(() => { - onSurfaceLabelChangeRef.current = onSurfaceLabelChange; - }); - const accessSubject = t('engine.studio.copilot.subject.access', locale); - const currentSetLabel = current ? perms.find((p) => p.name === current)?.label : undefined; - const surfaceReportLabel = owdOpen - ? `${accessSubject} · ${t('engine.studio.owd.title', locale)}` - : current && currentSetLabel - ? `${accessSubject} · ${currentSetLabel}` - : undefined; - const surfaceReportType = currentSurface?.type; - const surfaceReportName = currentSurface?.name; - React.useEffect(() => { - onSurfaceLabelChangeRef.current?.( - surfaceReportType && surfaceReportName && surfaceReportLabel - ? { type: surfaceReportType, name: surfaceReportName, label: surfaceReportLabel } - : null, - ); - }, [surfaceReportType, surfaceReportName, surfaceReportLabel]); - React.useEffect( - () => () => { - onSurfaceLabelChangeRef.current?.(null); - }, - [], - ); - const currentRef = React.useRef(current); - React.useLayoutEffect(() => { - currentRef.current = current; - }); - const [query, setQuery] = React.useState(''); - // inline creator (same rail pattern as the Data pillar's object creator) - const [creating, setCreating] = React.useState(false); - const [createErr, setCreateErr] = React.useState(null); - const [busy, setBusy] = React.useState(false); - // objectstack#26836 — a create refused because the name is taken: which set - // holds it, and whether it is this package's, so the dialog can open it. - const [createTaken, setCreateTaken] = React.useState<{ name: string; label: string; here: boolean } | null>(null); - // Which of the rail's sets are published, and which hold a pending draft: - // the draft discard's two inputs, read by `load` with the rail. - const [publishedNames, setPublishedNames] = React.useState>(() => new Set()); - const [draftNames, setDraftNames] = React.useState>(() => new Set()); - const [discarding, setDiscarding] = React.useState(false); - // Bumped by a discard: the open matrix re-reads as it does after a publish, - // since in both its draft is gone (added to `publishNonce` below). - const [draftGoneNonce, setDraftGoneNonce] = React.useState(0); - // [ADR-0090 D6] "why can this user access?" — right-side explain sheet. - const [explainOpen, setExplainOpen] = React.useState(false); - // objectstack#28573 (ADR-0146 D6) — "New similar" on a read-only base's set: - // whether its dialog is open, and what the strip above the matrix says. A - // `landed` strip is the copy the clone door saved, shown on that copy; a - // `noPackage` / `noName` strip is an answer this pillar cannot open, shown - // on the base. The copy usually opens in ANOTHER package, which remounts - // this pillar (keyed by package), so the strip rides the navigation's state - // and is read once here. - const navigate = useNavigate(); - const location = useLocation(); - const [newSimilarOpen, setNewSimilarOpen] = React.useState(false); - // objectstack#32774 — the package "New similar" clones the open set from, - // as the matrix read it: named only where the set's name has more than one - // holder (`onCloneSourceRead`), so a name with one holder is cloned by name. - const [newSimilarSource, setNewSimilarSource] = React.useState<{ name: string; sourcePackage: string | undefined } | null>( - null, - ); - const onCloneSourceRead = React.useCallback((name: string, sourcePackage: string | undefined) => { - setNewSimilarSource((prev) => - prev && prev.name === name && prev.sourcePackage === sourcePackage ? prev : { name, sourcePackage }, - ); - }, []); - const [newSimilarStrip, setNewSimilarStrip] = React.useState(() => { - // objectstack#28572 — a copy that landed in the base's pair arrives on - // the base's surface; matched by the spec's pairing rule (a read). - const pair = pairIdOf(railPackageId); - return readNewSimilarArrival(location.state, railPackageId) ?? (pair ? readNewSimilarArrival(location.state, pair) : null); - }); - // Who may press it: the clone door asks the metadata door's verdict - // (`manage_metadata`), and under a wall the catalog is the platform - // operator's (ADR-0131 D3), refused whatever the capability. Either way the - // action draws disabled, with the console's own sentence for why. - const canAuthorSets = useCanAuthorMetadata(); - const walledSets = useWalledCatalogReadOnly('permission'); - // objectui#12456 — the open set's tab (epic objectui#12446, decision C): - // Objects, System capabilities, Row-level security, Tab visibility, - // Delegated admin. Objects is the landing; the choice holds across sets. - const [accessTab, setAccessTab] = React.useState('objects'); - // Both main-panel surfaces hold unsaved edits and unmount on a rail-driven - // swap: the matrix page is keyed by `current` (and unmounts entirely when - // the OWD overview swaps in), and the OWD overview batch-editor unmounts - // when a set swaps back in. Each editor reports its dirty state up - // (`onDirtyChange` — the two never coexist, so at most one bit is set), and - // every swap is gated on this confirm — same native prompt as the metadata - // editor's leave guard. Each editor resets its report on unmount, so a - // confirmed discard clears its bit by itself. - const [matrixDirty, setMatrixDirty] = React.useState(false); - const [owdDirty, setOwdDirty] = React.useState(false); - const pillarDirty = matrixDirty || owdDirty; - // The combined bit also gates the Studio header's pillar/Home/package - // navigation, which unmounts this whole pillar (objectui#2600) — mirror it - // up alongside the local rail guard. Ref-stabilized like the editors' own - // reports; the unmount cleanup reports `false` so a discarded pillar clears - // the surface's guard state. - const onDirtyChangeRef = React.useRef(onDirtyChange); - React.useEffect(() => { - onDirtyChangeRef.current = onDirtyChange; - }); - React.useEffect(() => { - onDirtyChangeRef.current?.(pillarDirty); - }, [pillarDirty]); - React.useEffect( - () => () => { - onDirtyChangeRef.current?.(false); - }, - [], - ); - const confirmDiscardEdits = React.useCallback( - () => confirmDropUnsavedWork(pillarDirty, locale), - [pillarDirty, locale], - ); - - // objectstack#28572 — the latest rail read wins: a read the pair's arrival - // re-ran can finish before or after one a New in the pair asked for. - const loadSeqRef = React.useRef(0); - const load = React.useCallback(async (pairOverride?: string) => { - const seq = ++loadSeqRef.current; - const railPair = pairOverride ?? railPairId; - try { - // Scope the rail to this package server-side (ADR-0086 P1): the metadata - // API filters `permission` by the record-level `package_id` provenance, so - // it returns only the sets this package owns — environment-owned platform - // defaults (`admin_full_access`, `member_default`, …) are excluded by the - // backend, not the client. (The `?package=` list rows don't echo the - // provenance columns, so a client-side filter can't do this.) - // - // ADR-0086 P2 (D6): a package permission set is draft/published metadata, - // so the rail shows published ∪ pending-draft sets — a set created (or - // renamed) as a draft but not yet published must still appear, just like - // the Data/Interfaces pillars merge their drafts. Draft headers are - // already package-scoped by `listDrafts({ packageId })`. - const packageId = railPackageId; - // objectstack#28572 — and, on a read-only base with a pair, the pair's - // published and draft sets: those the base's list does not hold are the - // sets the pair adds. A failed pair read lists none of them. - const readPair = async () => - railPair === null - ? null - : Promise.all([ - client.list('permission', { packageId: railPair }) as Promise>>, - client.listDrafts({ packageId: railPair, type: 'permission' }).catch(() => []), - ]); - const [list, drafts, pair] = await Promise.all([ - client.list('permission', { packageId }) as Promise>>, - client.listDrafts({ packageId, type: 'permission' }).catch(() => []), - readPair().catch(() => null), - ]); - if (seq !== loadSeqRef.current) return; - const byName = new Map(); - for (const p of list || []) { - const name = String(p.name ?? (p as Record).id ?? ''); - if (!name) continue; - byName.set(name, { - name, - label: String(p.label ?? p.name ?? ''), - isDefault: !!(p as Record).isDefault, - }); - } - // objectui#11862 — a draft-only set reads as the label its `_drafts` row - // carries (objectstack-ai/objectstack#22200), in the designer locale; the - // set is not read for it (ruling `6053526025`, question 1). A row with - // no label leaves `label` empty, and the rail shows the name alone. - for (const d of (drafts as Array<{ name?: string; label?: I18nLabel | null }>) || []) { - const name = String(d?.name ?? ''); - if (!name || byName.has(name)) continue; - byName.set(name, { name, label: navItemLabelText(d?.label ?? undefined, locale).trim() }); - } - const [pairList, pairDrafts] = pair ?? [[], []]; - if (railPair !== null) { - for (const p of pairList || []) { - const name = String(p.name ?? (p as Record).id ?? ''); - if (!name || byName.has(name)) continue; - byName.set(name, { name, label: String(p.label ?? p.name ?? ''), addedIn: railPair }); - } - for (const d of (pairDrafts as Array<{ name?: string; label?: I18nLabel | null }>) || []) { - const name = String(d?.name ?? ''); - if (!name || byName.has(name)) continue; - byName.set(name, { name, label: navItemLabelText(d?.label ?? undefined, locale).trim(), addedIn: railPair }); - } - } - const scoped = [...byName.values()]; - setPerms(scoped); - const nameOf = (p: Record) => String(p.name ?? p.id ?? ''); - setPublishedNames(new Set([...(list || []), ...(pairList || [])].map(nameOf))); - setDraftNames( - new Set( - [...((drafts as Array<{ name?: string }>) || []), ...((pairDrafts as Array<{ name?: string }>) || [])] - .map((d) => String(d?.name ?? '')) - .filter(Boolean), - ), - ); - // A `?surface=owd:overview` deep-link opens the OWD overview instead of a - // permission set; `current` still defaults to the first set so switching - // back to the matrix has a target. Applied once — a later publish re-runs - // `load`, and we must not yank the user back to OWD then. - if (!appliedOwdDeepLink.current && initialSurface?.type === 'owd') { - appliedOwdDeepLink.current = true; - setOwdOpen(true); - } - const deepLinked = resolveSurfaceDeepLink(scoped, initialSurface, 'permission'); - // objectstack#28572 — a set the pair adds is listed once the pair is - // known (`useDeepLinkFallback`). - if (deepLinked && deepLinkUpgrade.take(currentRef.current, deepLinked.name)) { - setCurrent(deepLinked.name); - } else { - if (!deepLinked && initialSurface?.type === 'permission' && currentRef.current === null) { - deepLinkUpgrade.note(scoped[0]?.name ?? null); - } - setCurrent((c) => c ?? deepLinked?.name ?? scoped[0]?.name ?? null); - } - } catch (e) { - if (seq === loadSeqRef.current) setError(formatMetadataError(e)); - } finally { - if (seq === loadSeqRef.current) setLoaded(true); - } - }, [client, railPackageId, railPairId, locale]); - - React.useEffect(() => { - void load(); - // Re-read after a package publish so drafts that went live collapse into - // the published rail (ADR-0086 P2), and on the live-metadata pulse so a - // copilot turn's permission set appears without a page reload (#7255). - }, [load, publishNonce, metadataRefreshNonce]); - - const doCreate = React.useCallback( - async (label: string, name: string) => { - setBusy(true); - setCreateErr(null); - setCreateTaken(null); - try { - // A name a permission set already holds, published or as a draft, in - // this package or any other, is refused here and nothing is written: - // over a published set the first-write pin below would write this - // blank skeleton as its pending draft (`findTakenIdentifier`). - const taken = await findTakenIdentifier(client, 'permission', name, locale); - if (taken) { - setCreateTaken({ ...taken, here: perms.some((p) => p.name === name) }); - return; - } - // objectstack#28572 (ADR-0146 D3) — on a read-only base the set is - // created in its pair, which the ensure door answers (creating it on - // first use, without a prompt). - const target = - packageReadOnly && customization ? (await customization.ensurePackage()).packageId : railPackageId; - // Package door → a DRAFT stamped with this package (D6/D7). - // objectui#11773 — and the door refuses a draft row too (the - // first-write pin), for one that lands between the check above and - // this save. A set published in that window is not refused by it. - await client.save('permission', name, buildPermissionSkeleton(name, label), { - mode: 'draft', - packageId: target, - ifNoneMatch: '*', - surface: 'studio', - }); - // objectstack#36511 — then that one set is published, so it is live at - // once like every Save in Studio. A refused publish takes back the - // draft it wrote, so nothing is created, and says why. - const live = await publishSavedItem(client, { type: 'permission', name, packageId: target }, false); - if (!live.ok) { - setCreateErr(formatMetadataError(live.error)); - return; - } - toast.success(tFormat('engine.studio.access.created', locale, { label })); - setCreating(false); - // A set made in the pair is read back from the pair the door named. - await load(target === railPackageId ? undefined : target); - // Land on the new set's matrix — also from the OWD overview, whose - // discard the "+ New" gate already confirmed up front. - setOwdOpen(false); - setCurrent(name); - } catch (e) { - // objectstack#26846 — the first-write pin's refusal, for a draft that - // landed after the check above, read by its code: this create sent - // the pin, so a conflict means the identifier holds a draft. The - // door's sentence speaks of the pin itself and is not shown. - setCreateErr( - errorCodeIs(e, 'METADATA_CONFLICT') - ? tFormat('engine.studio.access.createDraftTaken', locale, { name }) - : formatMetadataError(e), - ); - } finally { - setBusy(false); - } - }, - [client, load, railPackageId, packageReadOnly, customization, locale, perms], - ); - - // The refusal's way out: the taken set is this package's, so it opens in - // the matrix instead of a second one being made. The "+ New" gate already - // confirmed any discard of unsaved edits. - const openTakenSet = React.useCallback((name: string) => { - setCreating(false); - setCreateTaken(null); - setOwdOpen(false); - setCurrent(name); - }, []); - - // objectstack#28573 — the clone door saved a copy of the open set. It opens - // only where the answer says it landed: that package's Access pillar with - // the copy selected. An answer that names no copy, or no package, is said - // so and opens nothing; the landing is never derived from the base. - const onNewSimilarSaved = React.useCallback( - (copy: PermissionSetCloned) => { - setNewSimilarOpen(false); - if (!copy.name) { - setNewSimilarStrip({ kind: 'noName', notice: copy.notice, noticeCode: copy.noticeCode }); - return; - } - if (typeof copy.package !== 'string') { - setNewSimilarStrip({ kind: 'noPackage', name: copy.name, notice: copy.notice, noticeCode: copy.noticeCode }); - return; - } - const landed: NewSimilarStrip = { - kind: 'landed', - name: copy.name, - package: copy.package, - notice: copy.notice, - noticeCode: copy.noticeCode, - }; - // objectstack#28572 — the pair's sets are this surface's too. - if (copy.package === railPackageId || (railPairId !== null && copy.package === railPairId)) { - setNewSimilarStrip(landed); - setOwdOpen(false); - setCurrent(copy.name); - void load(); - return; - } - navigate(studioPillarItemPath(copy.package, 'access', { type: 'permission', name: copy.name }), { - state: { [NEW_SIMILAR_ARRIVAL_STATE]: landed }, - }); - }, - [railPackageId, railPairId, navigate, load], - ); - - // Discard the open set's pending draft (`DELETE ?state=draft` at this - // package's address, the door the metadata editor's "Discard draft" uses). - // A published set goes back to its live body; a set that was never - // published has nothing left, so it leaves the rail. - const discardDraft = React.useCallback( - async (name: string) => { - const row = perms.find((p) => p.name === name); - const item = row?.label || name; - const neverPublished = !publishedNames.has(name); - // One confirm: an unsaved edit on the open matrix is an unpublished - // change of this same set, and the discard removes it with the rest. - if ( - !window.confirm( - tFormat( - neverPublished ? 'engine.studio.access.discardConfirmUnpublished' : 'engine.studio.access.discardConfirm', - locale, - { item }, - ), - ) - ) { - return; - } - setDiscarding(true); - try { - await client.reset('permission', name, { state: 'draft', packageId }); - toast.success(tFormat('engine.edit.draftDiscarded', locale, { item })); - if (neverPublished) setCurrent((c) => (c === name ? null : c)); - // The open matrix holds the discarded draft and the pin it was read - // with: read it again, as after a publish (its draft is gone). - setDraftGoneNonce((n) => n + 1); - onDraftSaved?.(); - await load(); - } catch (e) { - toast.error(t('engine.studio.access.discardFailed', locale), { - description: formatMetadataError(e), - classNames: { description: 'whitespace-pre-line' }, - }); - } finally { - setDiscarding(false); - } - }, - [perms, publishedNames, locale, client, packageId, onDraftSaved, load], - ); - - const filtered = perms.filter( - (p) => - (!query.trim() || - p.label.toLowerCase().includes(query.trim().toLowerCase()) || - p.name.toLowerCase().includes(query.trim().toLowerCase())) && - // objectstack#28572 — "only customizations" keeps the marked rows. - (!onlyCustomized || railMarks?.markOf({ type: 'permission', ...p }) != null), - ); - const markedSets = railMarks ? perms.filter((p) => railMarks.markOf({ type: 'permission', ...p }) !== null).length : 0; - - // objectui#12459 — the item header inside the content column. The - // "Permission matrix" band above the rail retires. objectui#12456 — an - // open set's header is the matrix page's own (its label, api name, Package - // chip, granted / override counts, History, the tab row), fed the three - // pieces below; this pillar draws the header for the OWD overview and for - // the empty states. - const accessRailToggleEl = ( - - ); - // objectui#11781 — "saved as draft" is what an editable package does. A - // read-only one saves nothing: objectui#12453 puts the read-only link where - // the note was, and the link's title carries the note's sentence. An open - // set's header draws it at the tab row's right end (objectui#12456: the - // title row truncated the set's label at the 1280 px design width). - // objectui#12524 — the writable note is this pillar's draft status: the - // header draws it in the status place every pillar shares. The read-only - // link is an action, so it stays in the actions slot. - // The note speaks for what the main panel shows: the open set, or the - // package-wide OWD overview and empty header, which are the base's. - const noteReadOnly = owdOpen || current === null ? packageReadOnly : readOnly; - // objectstack#29674 — an open set the pair adds lists its base's objects - // too (`permissionObjectScopePackages`), so its note names the base instead - // of claiming "this package's objects" only. - const notePairBase = !owdOpen && current !== null && currentAddedIn ? (customization?.baseLabel ?? railPackageId) : null; - const accessStatus: StudioItemStatus | undefined = noteReadOnly - ? undefined - : notePairBase !== null - ? { - label: tFormat('engine.studio.access.bannerPair', locale, { package: notePairBase }), - title: tFormat('engine.studio.access.bannerTitlePair', locale, { package: notePairBase }), - } - : { label: t('engine.studio.access.banner', locale), title: t('engine.studio.access.bannerTitle', locale) }; - const accessNoteEl = accessStatus ? ( - - ) : ( - - ); - const accessExplainEl = ( - - ); - // The rail's "+" — and the empty block's button, which runs this same - // handler (objectui#12514). Creating a set lands on the new set's matrix — a - // remount of the open matrix, or a swap out of the OWD overview — so gate - // the flow up front. - const openCreateSet = packageReadOnly && !newInPair - ? undefined - : () => { - if (!confirmDiscardEdits()) return; - setCreateErr(null); - setCreateTaken(null); - setCreating(true); - }; - // objectstack#26836 — the open set's pending draft can be discarded where - // the set is edited; nothing in Studio offered it, so a blank draft over a - // live set could only be published. - const accessDiscardEl = - !readOnly && current && !owdOpen && draftNames.has(current) ? ( - - ) : null; - // objectstack#28573 (ADR-0146 D6) — a read-only base's set offers "New - // similar", never an override: the copy is a NEW set, in the package the - // clone door chooses. Disabled, it says why in the console's words. - const newSimilarBlocked = walledSets - ? tFormat('engine.catalog.readOnly.walled', locale, { type: translateMetadataType('permission', locale) }) - : canAuthorSets - ? null - : t('engine.edit.capabilityReadOnly', locale); - const accessNewSimilarEl = - readOnly && current && !owdOpen ? ( - - - {newSimilarBlocked !== null && ( - - {newSimilarBlocked} - - )} - - ) : null; - const newSimilarStripEl = - newSimilarStrip && !owdOpen && (newSimilarStrip.kind !== 'landed' || newSimilarStrip.name === current) ? ( -
- -
-

- {newSimilarStrip.kind === 'landed' - ? tFormat('engine.studio.access.newSimilar.done', locale, { - name: newSimilarStrip.name, - package: newSimilarStrip.package, - }) - : newSimilarStrip.kind === 'noPackage' - ? tFormat('engine.studio.access.newSimilar.noPackage', locale, { name: newSimilarStrip.name }) - : t('perm.clone.noName', locale)} -

- {/* objectstack#29727 — in the console's language for its known code, else as sent. */} - {newSimilarStrip.notice && ( -

- {permissionSetCloneNoticeText( - { - notice: newSimilarStrip.notice, - noticeCode: newSimilarStrip.noticeCode, - package: newSimilarStrip.kind === 'landed' ? newSimilarStrip.package : null, - }, - locale, - )} -

- )} -
- -
- ) : null; - const accessHeaderEl = ( - - {noteReadOnly && accessNoteEl} - {accessExplainEl} - - } - /> - ); - - // A suggestion names its set by machine name only; the banner, its toasts - // and its state lines name it by the label the rail shows for that set - // (`ux-conventions.labels-over-machine-names`). The suggestions listed here - // are this package's own sets, which the rail read; a set the rail does not - // hold, or one with no label, is named by its machine name. - const suggestedSetLabel = (s: SuggestedBinding): string => suggestedSetLabelOf(s, perms); - - return ( -
- {/* ADR-0090 D5/D9 — this package's suggested audience bindings - (isDefault sets shipped by the package) and the deployment's - decision on each. Renders nothing when there are none or for a - caller without manage_metadata (the list answers 403); accept and - revoke are enforced server-side by the anchor gates. Drawn on a - read-only package too: accepting or dismissing a suggestion is a - deployment decision about the package, not an edit of it, and a - marketplace-installed package — read-only here — is the one that - ships an isDefault set. Only this strip ignores `packageReadOnly`; - every affordance that edits the package keeps its gate. */} - - tFormat( - s.anchor === 'guest' - ? 'engine.studio.access.suggestPromptGuest' - : 'engine.studio.access.suggestPromptEveryone', - locale, - { set: suggestedSetLabel(s) }, - ), - confirm: t('engine.studio.access.suggestConfirm', locale), - confirming: t('engine.studio.access.suggestConfirming', locale), - dismiss: t('engine.studio.access.suggestDismiss', locale), - confirmedToast: (s) => - tFormat('engine.studio.access.suggestConfirmedToast', locale, { - set: suggestedSetLabel(s), - anchor: s.anchor, - }), - dismissedToast: (s) => - tFormat('engine.studio.access.suggestDismissedToast', locale, { set: suggestedSetLabel(s) }), - guestUnsupported: t('engine.studio.access.suggestGuestUnsupported', locale), - acceptedState: (s) => - tFormat('engine.studio.access.suggestAcceptedState', locale, { set: suggestedSetLabel(s) }), - notInForceState: (s) => - tFormat('engine.studio.access.suggestNotInForceState', locale, { set: suggestedSetLabel(s) }), - dismissedState: (s) => - tFormat('engine.studio.access.suggestDismissedState', locale, { set: suggestedSetLabel(s) }), - revoke: t('engine.studio.access.suggestRevoke', locale), - revoking: t('engine.studio.access.suggestRevoking', locale), - revokedToast: (s) => - tFormat('engine.studio.access.suggestRevokedToast', locale, { set: suggestedSetLabel(s) }), - reopen: t('engine.studio.access.suggestReopen', locale), - reopening: t('engine.studio.access.suggestReopening', locale), - reopenedToast: (s) => - tFormat('engine.studio.access.suggestReopenedToast', locale, { set: suggestedSetLabel(s) }), - }} - /> - -
- {isMobile && railOpen && ( -
setRailOpen(false)} - aria-hidden="true" - /> - )} - - } - pinned={ - // Pinned sibling surface: the package-wide Record Sharing Baseline - // (OWD) overview (objectui#2505). Same package-author ownership as - // the sets below, but a distinct surface — not a permission set. -
- { - // Re-clicking the open overview is a no-op — nothing - // remounts, so no confirm (mirrors the set re-click below). - if (owdOpen) { - setOwdHighlight(null); - if (isMobile) setRailOpen(false); - return; - } - if (!confirmDiscardEdits()) return; - setOwdOpen(true); - setOwdHighlight(null); - if (isMobile) setRailOpen(false); - }} - icon={} - className="font-medium" - > - {t('engine.studio.owd.railLabel', locale)} - -
- } - isMobile={isMobile} - open={railOpen} - > - {/* objectui#12514 — the empty sentence names the "+" it points at; - without one, the content column's block speaks alone. */} - {perms.length === 0 && (error || !loaded || openCreateSet) && ( -

- {error ? t('engine.studio.loadFailed', locale) : loaded ? t('engine.studio.access.none', locale) : t('engine.studio.loading', locale)} -

- )} - {filtered.map((p) => ( - { - if (!owdOpen && current === p.name) { - if (isMobile) setRailOpen(false); - return; - } - if (!confirmDiscardEdits()) return; - setOwdOpen(false); - setCurrent(p.name); - if (isMobile) setRailOpen(false); - }} - icon={} - name={p.label.trim() ? p.label : p.name} - trailing={ - <> - - {p.isDefault ? ( - {t('perm.badge.default', locale)} - ) : null} - - } - > - {/* objectui#11862 — the set's label. objectstack#34795: the - machine name is no longer drawn as secondary text; it is the - row's tooltip. A set listed from its draft header alone has - no label in hand (the header carries none), so its name is - the text, as before. */} - - - - - ))} -
- -
- {(owdOpen || !current) && accessHeaderEl} - {newSimilarStripEl} -
- {owdOpen ? ( - /* Sibling surface: the package-wide OWD baseline overview - * (objectui#2505) — object × sharingModel, - * batch-edited as per-object drafts. */ - - ) : current ? ( - /* The existing Salesforce-style matrix page in its Studio - * presentation (objectui#12456): the item header and five tabs - * are the page's own, its autosave + destructive-change guard - * included. The OWD chip deep-links to the overview above. */ - { - // The set now holds a pending draft, so its discard shows. - setDraftNames((names) => (names.has(current) ? names : new Set(names).add(current))); - onDraftSaved?.(); - // objectstack#26846 — and the rail reads the sets again, so a - // label this save changed shows there without a publish or a - // reload. - void load(); - }} - onSaved={() => { - // objectstack#36511 — the top bar's Save published the set: no - // draft of it is left, and the rail reads its label again. - setDraftNames((names) => { - if (!names.has(current)) return names; - const next = new Set(names); - next.delete(current); - return next; - }); - void load(); - }} - readOnly={readOnly} - onDirtyChange={setMatrixDirty} - embedded - // objectstack#29809 — the header's provenance chip reads the - // mark this set's rail row draws, so the two tell one story. - customizationMark={railMarks?.markOf({ type: 'permission', name: current, addedIn: currentAddedIn }) ?? null} - studio={{ - tab: accessTab, - onTabChange: setAccessTab, - onCloneSourceRead, - leading: accessRailToggleEl, - chips: currentAddedIn ? ( - <> - - {accessNoteEl} - - ) : ( - accessNoteEl - ), - actions: ( - <> - {accessNewSimilarEl} - {accessDiscardEl} - {accessExplainEl} - - ), - }} - onOpenOwd={(objectName) => { - // The badge deep-link swaps this page out for the OWD - // overview — same remount, same guard. - if (!confirmDiscardEdits()) return; - setOwdHighlight(objectName || null); - setOwdOpen(true); - }} - /> - ) : loaded && !error && perms.length === 0 ? ( - // objectui#12514 — one centered block whose button runs the rail's "+". -
- - ) - } - /> -
- ) : null} -
-
-
- - - - {/* objectstack#28573 — the clone door's dialog, shared with Setup's - catalog: a name and a label, nothing else, refusals verbatim. */} - {newSimilarOpen && current && ( - setNewSimilarOpen(false)} - onCloned={onNewSimilarSaved} - /> - )} - - openTakenSet(createTaken.name) : undefined} - /> - ) - } - onSubmit={({ label, name }) => void doCreate(label, name)} - /> -
- ); -} diff --git a/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.oneLabel-11787.test.ts b/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.oneLabel-11787.test.ts index 3d8908f7266..fe3ee872a9a 100644 --- a/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.oneLabel-11787.test.ts +++ b/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.oneLabel-11787.test.ts @@ -66,8 +66,12 @@ function createDialogSites(): Site[] { const DRAFT_LABEL = "t('engine.studio.createDraft', locale)"; const LIVE_LABEL = "t('engine.studio.createLive', locale)"; -/** The dialogs of the live editors, by their title key (objectstack#36511). */ -const LIVE_TITLES = ['engine.studio.data.newObject', 'engine.studio.auto.newTitle', 'engine.studio.access.new']; +/** + * The dialogs of the live editors, by their title key (objectstack#36511). + * objectstack#36905 — the Access pillar's went with the pillar: a permission + * set is created from its type's list. + */ +const LIVE_TITLES = ['engine.studio.data.newObject', 'engine.studio.auto.newTitle']; const titleKeyOf = (site: Site): string | undefined => site.props.match(/title=\{t\('([^']+)'/)?.[1]; diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx index b68bef3131d..ba7a1446f1b 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx @@ -30,7 +30,7 @@ */ import * as React from 'react'; -import { Lock, ArrowUpRight } from 'lucide-react'; +import { ArrowUpRight } from 'lucide-react'; import type { MetadataClient, MetadataLayered } from '@object-ui/data-objectstack'; // The ONE draft-envelope reader (objectui#8181): unwrap AND strip the // framework's read decorations in one place. This file used to carry its own @@ -545,20 +545,13 @@ export function PackageOwdOverviewPanel({ ]; return (
- {/* objectui#12456 — the overview's title and subtitle are the Access - pillar's item header above this panel, so its own header is the - toolbar row: what the dials decide. objectstack#36511 — its Save is - the top bar's. */} + {/* objectui#12456 — the overview's title and subtitle are the item + header above this panel, so its own header is the toolbar row: what + the dials decide. objectstack#36511 — its Save is the top bar's. + objectstack#36905 — a read-only package's one mark is that header's + (objectui#12453), so this row draws none. */}

{t('engine.studio.owd.description', locale)}

- {readOnly && ( - - {t('engine.studio.pkg.readonly', locale)} - - )}
!open && setPrereq(null)}> diff --git a/ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx b/ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx index 8c40813d647..f73033752d3 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioAiCopilot.tsx @@ -15,6 +15,7 @@ import { ConversationsSidebar } from '../../console/ai/ConversationsSidebar.js'; import { resolvePublicShareBase } from '../../console/organizations/resolveHomeUrl.js'; import { AiUsageIndicator } from '../../layout/AiUsageIndicator.js'; import { usePlanApprovalPendingCount } from '../../assistant/assistantBus.js'; +import { STUDIO_METADATA_AREA, areaDesignerItemOf } from './metadataArea.js'; /** * objectui#8219 — the display label of the artifact a pillar has open, tagged @@ -73,20 +74,30 @@ export function StudioCopilotConversation({ // deep-link every pillar already mirrors (useSurfaceDeepLink). Derived per // render; the ChatPane transport reads it per send, so each turn carries // what the user is looking at RIGHT NOW. - const { tab } = useParams<{ tab?: string }>(); + const { tab, packageId: segment } = useParams<{ tab?: string; packageId?: string }>(); const copilotLocation = useLocation(); const surfaceContext = React.useMemo(() => { const raw = new URLSearchParams(copilotLocation.search).get('surface'); let artifact: { type: string; name: string } | undefined; + let pillar = tab; if (raw) { const idx = raw.indexOf(':'); if (idx > 0 && idx < raw.length - 1) { artifact = { type: raw.slice(0, idx), name: raw.slice(idx + 1) }; } } - if (!tab && !artifact) return undefined; - return { ...(tab ? { pillar: tab } : {}), ...(artifact ? { artifact } : {}) }; - }, [tab, copilotLocation.search]); + // objectstack#36905 — a designer that opens full-screen at its metadata + // address carries its item in the path, under the area's segment. + if (!tab && !artifact) { + const item = areaDesignerItemOf(copilotLocation.pathname, segment); + if (item) { + artifact = item; + pillar = STUDIO_METADATA_AREA; + } + } + if (!pillar && !artifact) return undefined; + return { ...(pillar ? { pillar } : {}), ...(artifact ? { artifact } : {}) }; + }, [tab, segment, copilotLocation.pathname, copilotLocation.search]); // objectui#8219 — the chip's display label, read beside the context rather // than inside it. Shown only when it labels the artifact the URL names: the // URL stays the single source of WHAT is discussed, so a label that lags or diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessCreateTaken-26836.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessCreateTaken-26836.test.tsx deleted file mode 100644 index 0f7d28a3629..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessCreateTaken-26836.test.tsx +++ /dev/null @@ -1,346 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#26836 — the Access pillar's "+ New" over an identifier a - * permission set already holds, and the discard of a set's pending draft. - * - * The create's first-write pin (`If-None-Match: *` with `?mode=draft`) - * asserts that no DRAFT row exists, so a name that derived to a PUBLISHED - * set's identifier wrote a blank draft over the live set, and publishing the - * package would have replaced its grants. Studio offered no way to remove that - * draft. - * - * - Create over a published id (this package's): refused, nothing written, - * the sentence names the set, and "Open" opens it. - * - Create over a published id another package holds: refused, nothing - * written, and no "Open". - * - Create over a draft id: refused before the save, and the save still - * carries the first-write pin for a draft that lands after the check; - * that pin's refusal reads in the author's words (objectstack#26846). - * - A fresh id: created as before. - * - Discard: a published set's draft goes and the matrix reads the live - * set again; a never-published set leaves the rail. - * - * The REAL `AccessPillar` and `PermissionMatrixEditPage`, over a client that - * keeps published and draft rows the way the metadata door does. - */ - -import '@testing-library/jest-dom/vitest'; -// The source under test reaches these through dynamic imports: their first load is paid at collection. -import '@objectstack/lint'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -const PKG = 'com.acme.app'; -const OTHER_PKG = 'com.other.app'; - -type Row = { pkg: string; body: Record }; - -let clientImpl: ReturnType; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useMetadataClient: () => clientImpl, - useMetadataTypes: () => ({ - loading: false, - error: null, - entries: [{ type: 'permission', label: 'Permission', allowEnvironmentOverlay: true }], - }), - }; -}); -vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); -vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); - -import { toast } from 'sonner'; -import { t, tFormat } from '../metadata-admin/i18n'; -import { AccessPillar } from './StudioDesignSurface'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -const en = (key: string) => t(key, 'en'); - -const EDITOR = { name: 'project_editor', label: 'Project Editor', objects: { crm_lead: { allowRead: true } }, fields: {} }; - -/** A metadata door double: published rows and draft rows, each owned by a package. */ -function makeClient(seed: { published?: Record; drafts?: Record } = {}) { - const published: Record = { ...(seed.published ?? {}) }; - const drafts: Record = { ...(seed.drafts ?? {}) }; - const save = vi.fn( - async (_type: string, name: string, body: Record, opts: { packageId?: string; ifNoneMatch?: string }) => { - if (opts?.ifNoneMatch === '*' && drafts[name]) { - throw Object.assign(new Error(`permission/${name}: this save asserted that no draft row exists`), { - status: 409, - code: 'METADATA_CONFLICT', - }); - } - drafts[name] = { pkg: opts?.packageId ?? '', body }; - return body; - }, - ); - const reset = vi.fn(async (_type: string, name: string, _opts: { state?: string; packageId?: string }) => { - delete drafts[name]; - return {}; - }); - // objectstack#36511 — the single-item publish: the pending draft becomes the live row. - const publish = vi.fn(async (_type: string, name: string) => { - if (drafts[name]) { - published[name] = drafts[name]; - delete drafts[name]; - } - return { success: true }; - }); - return { - published, - drafts, - save, - publish, - reset, - // objectstack#26840 — the Access matrix reads its objects through the draft-overlaid door. - withPreviewDrafts() { return this; }, - list: vi.fn(async (type: string, opts: { packageId?: string } = {}) => { - if (type === 'object') { - return [ - { name: 'crm_account', label: 'Account' }, - { name: 'crm_lead', label: 'Lead' }, - ]; - } - if (type !== 'permission') return []; - return Object.values(published) - .filter((r) => !opts.packageId || r.pkg === opts.packageId) - .map((r) => ({ name: r.body.name, label: r.body.label })); - }), - listDrafts: vi.fn(async (opts: { packageId?: string; type?: string } = {}) => - Object.values(drafts) - .filter((r) => !opts.packageId || r.pkg === opts.packageId) - .map((r) => ({ type: 'permission', name: r.body.name, label: r.body.label, packageId: r.pkg })), - ), - layered: vi.fn(async (_type: string, name: string) => ({ - effective: published[name]?.body ?? null, - code: null, - overlay: null, - overlayScope: null, - })), - getDraft: vi.fn(async (type: string, name: string) => - drafts[name] ? { type, name, item: drafts[name].body } : null, - ), - get: vi.fn(async () => ({ fields: [] })), - }; -} - -beforeEach(() => { - window.confirm = vi.fn(() => true) as unknown as typeof window.confirm; -}); - -afterEach(() => { - cleanup(); - vi.clearAllMocks(); -}); - -function renderAccess(readOnly = false) { - render( - - - , - ); -} - -const header = () => within(screen.getByTestId('access-item-header')); -const rail = () => within(screen.getByTestId('studio-rail-access')); - -async function openCreate(label: string, name?: string) { - fireEvent.click(await screen.findByTestId('studio-rail-add', undefined, { timeout: 8000 })); - const dialog = await screen.findByRole('dialog', { name: en('engine.studio.access.new') }); - fireEvent.change(within(dialog).getByLabelText(en('engine.studio.access.nameLabel')), { target: { value: label } }); - if (name) { - fireEvent.change(within(dialog).getByLabelText(en('engine.studio.access.idLabel')), { target: { value: name } }); - } - fireEvent.click(within(dialog).getByRole('button', { name: en('engine.studio.createLive') })); - return dialog; -} - -describe('objectstack#26836 — "+ New" over a taken identifier', () => { - it('a published set of this package: refused, nothing written, the set named, and "Open" opens it', async () => { - clientImpl = makeClient({ published: { project_editor: { pkg: PKG, body: EDITOR } } }); - renderAccess(); - await screen.findByText('1 object granted · 0 field overrides', undefined, { timeout: 8000 }); - // Leave the set, so "Open" has somewhere to go back from. - fireEvent.click(rail().getByText(en('engine.studio.owd.railLabel'))); - - const dialog = await openCreate('Project Editor'); - const taken = await within(dialog).findByTestId('access-create-taken'); - expect(taken).toHaveTextContent( - tFormat('engine.studio.access.createTaken', 'en', { name: 'project_editor', label: 'Project Editor' }), - ); - expect(clientImpl.save).not.toHaveBeenCalled(); - expect(clientImpl.drafts).toEqual({}); - - fireEvent.click(within(taken).getByTestId('access-create-open-existing')); - await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); - expect(await screen.findByText('1 object granted · 0 field overrides')).toBeInTheDocument(); - expect(header().getByRole('heading', { level: 1 })).toHaveTextContent('Project Editor'); - expect(clientImpl.save).not.toHaveBeenCalled(); - }); - - it('a published set another package holds: refused, nothing written, and no "Open"', async () => { - clientImpl = makeClient({ published: { project_editor: { pkg: OTHER_PKG, body: EDITOR } } }); - renderAccess(); - const dialog = await openCreate('Project Editor'); - const taken = await within(dialog).findByTestId('access-create-taken'); - expect(taken).toHaveTextContent( - tFormat('engine.studio.access.createTakenElsewhere', 'en', { name: 'project_editor', label: 'Project Editor' }), - ); - expect(within(taken).queryByTestId('access-create-open-existing')).toBeNull(); - expect(clientImpl.save).not.toHaveBeenCalled(); - expect(clientImpl.drafts).toEqual({}); - }); - - it('a draft set: refused before the save', async () => { - clientImpl = makeClient({ - drafts: { project_editor: { pkg: PKG, body: { name: 'project_editor', label: 'Project Editor', objects: {} } } }, - }); - renderAccess(); - const dialog = await openCreate('Project Editor'); - expect(await within(dialog).findByTestId('access-create-taken')).toHaveTextContent( - tFormat('engine.studio.access.createTaken', 'en', { name: 'project_editor', label: 'Project Editor' }), - ); - expect(clientImpl.save).not.toHaveBeenCalled(); - }); - - it('a draft that lands after the check: the door\'s first-write pin still refuses it (objectui#11773)', async () => { - clientImpl = makeClient(); - renderAccess(); - await screen.findByTestId('access-empty', undefined, { timeout: 8000 }); - // The draft appears between the pillar's read and its save. - clientImpl.drafts.project_editor = { - pkg: PKG, - body: { name: 'project_editor', label: 'Somebody else', objects: { crm_lead: { allowRead: true } } }, - }; - clientImpl.listDrafts.mockResolvedValueOnce([]); - const dialog = await openCreate('Project Editor'); - await waitFor(() => expect(clientImpl.save).toHaveBeenCalledTimes(1)); - expect(clientImpl.save.mock.calls[0][3]).toMatchObject({ mode: 'draft', packageId: PKG, ifNoneMatch: '*' }); - // objectstack#26846 — read by its code, in the author's words: the door's - // sentence about the pin never reaches the dialog. - expect( - await within(dialog).findByText(tFormat('engine.studio.access.createDraftTaken', 'en', { name: 'project_editor' })), - ).toBeInTheDocument(); - expect(within(dialog).queryByText(/asserted that no draft row exists/)).toBeNull(); - expect(clientImpl.drafts.project_editor.body.label).toBe('Somebody else'); - }); - - it('CONTROL (objectstack#26846): a refusal with another code keeps its own text', async () => { - clientImpl = makeClient(); - renderAccess(); - await screen.findByTestId('access-empty', undefined, { timeout: 8000 }); - clientImpl.save.mockRejectedValueOnce( - Object.assign(new Error('permission/project_editor: label is too long'), { status: 422, code: 'VALIDATION_ERROR' }), - ); - const dialog = await openCreate('Project Editor'); - expect(await within(dialog).findByText(/label is too long/)).toBeInTheDocument(); - expect( - within(dialog).queryByText(tFormat('engine.studio.access.createDraftTaken', 'en', { name: 'project_editor' })), - ).toBeNull(); - }); - - it('a fresh identifier: created as a draft, then published at once (objectstack#36511), and opened', async () => { - clientImpl = makeClient({ published: { project_editor: { pkg: PKG, body: EDITOR } } }); - renderAccess(); - await screen.findByText('1 object granted · 0 field overrides', undefined, { timeout: 8000 }); - await openCreate('Project Viewer'); - await waitFor(() => expect(clientImpl.save).toHaveBeenCalledTimes(1)); - const [type, name, , opts] = clientImpl.save.mock.calls[0]; - expect([type, name]).toEqual(['permission', 'project_viewer']); - expect(opts).toMatchObject({ mode: 'draft', packageId: PKG, ifNoneMatch: '*', surface: 'studio' }); - await waitFor(() => expect(clientImpl.publish).toHaveBeenCalledWith('permission', 'project_viewer', { packageId: PKG })); - expect(toast.success).toHaveBeenCalledWith(tFormat('engine.studio.access.created', 'en', { label: 'Project Viewer' })); - await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); - expect(await rail().findByTitle('project_viewer')).toBeInTheDocument(); - await waitFor(() => expect(header().getByTitle('project_viewer')).toBeInTheDocument()); - }); -}); - -describe('objectstack#26836 — discarding a set\'s pending draft', () => { - it('a published set: the draft goes, the matrix reads the live set again, and the set stays', async () => { - clientImpl = makeClient({ - published: { project_editor: { pkg: PKG, body: EDITOR } }, - drafts: { project_editor: { pkg: PKG, body: { name: 'project_editor', label: 'Project Editor', objects: {} } } }, - }); - renderAccess(); - // The blank draft is what the matrix shows. - expect(await screen.findByText('0 objects granted · 0 field overrides', undefined, { timeout: 8000 })).toBeInTheDocument(); - - fireEvent.click(await header().findByTestId('access-discard-draft')); - expect(window.confirm).toHaveBeenCalledWith( - tFormat('engine.studio.access.discardConfirm', 'en', { item: 'Project Editor' }), - ); - await waitFor(() => expect(clientImpl.reset).toHaveBeenCalledTimes(1)); - expect(clientImpl.reset.mock.calls[0].slice(0, 3)).toEqual(['permission', 'project_editor', { state: 'draft', packageId: PKG }]); - expect(clientImpl.drafts).toEqual({}); - expect(toast.success).toHaveBeenCalledWith(tFormat('engine.edit.draftDiscarded', 'en', { item: 'Project Editor' })); - - expect(await screen.findByText('1 object granted · 0 field overrides')).toBeInTheDocument(); - expect(rail().getByTitle('project_editor')).toBeInTheDocument(); - await waitFor(() => expect(screen.queryByTestId('access-discard-draft')).toBeNull()); - expect(clientImpl.save).not.toHaveBeenCalled(); - }); - - it('a set never published: discarding its draft takes it off the rail', async () => { - clientImpl = makeClient({ - published: { project_editor: { pkg: PKG, body: EDITOR } }, - drafts: { project_viewer: { pkg: PKG, body: { name: 'project_viewer', label: 'Project Viewer', objects: {} } } }, - }); - renderAccess(); - fireEvent.click(await rail().findByTitle('project_viewer', undefined, { timeout: 8000 })); - fireEvent.click(await header().findByTestId('access-discard-draft')); - expect(window.confirm).toHaveBeenCalledWith( - tFormat('engine.studio.access.discardConfirmUnpublished', 'en', { item: 'Project Viewer' }), - ); - await waitFor(() => expect(rail().queryByTitle('project_viewer')).toBeNull()); - expect(clientImpl.reset.mock.calls[0].slice(0, 3)).toEqual(['permission', 'project_viewer', { state: 'draft', packageId: PKG }]); - // The rail's remaining set opens in its place. - expect(await screen.findByText('1 object granted · 0 field overrides')).toBeInTheDocument(); - }); - - it('a declined confirm discards nothing', async () => { - clientImpl = makeClient({ - published: { project_editor: { pkg: PKG, body: EDITOR } }, - drafts: { project_editor: { pkg: PKG, body: { name: 'project_editor', label: 'Project Editor', objects: {} } } }, - }); - window.confirm = vi.fn(() => false) as unknown as typeof window.confirm; - renderAccess(); - fireEvent.click(await screen.findByTestId('access-discard-draft', undefined, { timeout: 8000 })); - expect(window.confirm).toHaveBeenCalledTimes(1); - expect(clientImpl.reset).not.toHaveBeenCalled(); - expect(screen.getByTestId('access-discard-draft')).toBeInTheDocument(); - }); - - it('no discard without a pending draft, nor on a read-only package', async () => { - clientImpl = makeClient({ published: { project_editor: { pkg: PKG, body: EDITOR } } }); - renderAccess(); - await screen.findByText('1 object granted · 0 field overrides', undefined, { timeout: 8000 }); - expect(screen.queryByTestId('access-discard-draft')).toBeNull(); - cleanup(); - - clientImpl = makeClient({ - published: { project_editor: { pkg: PKG, body: EDITOR } }, - drafts: { project_editor: { pkg: PKG, body: { name: 'project_editor', label: 'Project Editor', objects: {} } } }, - }); - renderAccess(true); - await screen.findByText('0 objects granted · 0 field overrides', undefined, { timeout: 8000 }); - expect(screen.queryByTestId('access-discard-draft')).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessGuard.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessGuard.test.tsx deleted file mode 100644 index f01ef5d55a9..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessGuard.test.tsx +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * Access pillar — unsaved-changes guard on rail-driven surface swaps. - * - * The permission matrix in the main panel is keyed by the selected set - * (`key={current}`) and unmounts entirely when the OWD overview swaps in, so - * before this guard existed a rail click silently REMOUNTED the matrix and - * discarded any unsaved cell edits. The OWD overview batch-editor holds - * unsaved rows the same way and unmounts when a set swaps back in - * (objectui#2600). The pillar now holds both editors' reported dirty state - * (`onDirtyChange`) and gates every swap on a native confirm: - * - * • dirty + switch to another set → confirm; cancel keeps the edits, - * • dirty + swap to the OWD overview → same confirm, - * • dirty OWD rows + swap to a set / create flow → same confirm, - * • clean switches never prompt, - * • re-clicking the already-open set / overview never prompts (nothing - * remounts), - * • a confirmed discard clears the guard (the editor resets on unmount). - */ - -import '@testing-library/jest-dom/vitest'; -// The source under test reaches these through dynamic imports: their first load is paid at collection. -import '@objectstack/lint'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, within, waitFor } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -let clientImpl: any; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useMetadataClient: () => clientImpl, - useMetadataTypes: () => ({ - loading: false, - error: null, - entries: [{ type: 'permission', label: 'Permission', allowEnvironmentOverlay: true }], - }), - }; -}); - -// Rail siblings that are irrelevant to the guard — keep the render light. -// (The OWD overview is NOT mocked: its dirty report is under test.) -vi.mock('../../components/SuggestedBindingsPanel', () => ({ - SuggestedBindingsPanel: () => null, -})); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ - AccessExplainPanel: () => null, -})); -vi.mock('./StudioAiCopilot', () => ({ - StudioChatDock: () => null, -})); - -import { t } from '../metadata-admin/i18n'; -import { AccessPillar } from './StudioDesignSurface'; - -// jsdom has no matchMedia — useIsMobile (rail overlay) needs a stub. -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as any; - -interface Server { - byName: Record>; - saved: Array>; -} - -function freshServer(): Server { - return { - saved: [], - byName: { - set_a: { - name: 'set_a', - label: 'Set A', - objects: { a_account: { allowRead: true } }, - fields: {}, - }, - set_b: { - name: 'set_b', - label: 'Set B', - objects: { a_account: {} }, - fields: {}, - }, - }, - }; -} - -function makeClient(server: Server) { - return { - // Serves BOTH the pillar rail (list('permission', { packageId })) and the - // embedded matrix (list('object', { packageId }) + list('permission', {}) - // for the assignable-set allowlist). - // objectstack#26840 — the Access matrix reads its objects through the draft-overlaid door. - withPreviewDrafts() { return this; }, - list: async (type: string) => { - if (type === 'permission') { - return Object.values(server.byName).map((s) => ({ name: s.name, label: s.label })); - } - if (type === 'object') return [{ name: 'a_account' }]; - return []; - }, - listDrafts: async () => [], - layered: async (_type: string, name: string) => ({ - effective: server.byName[name], - code: null, - overlay: null, - overlayScope: null, - }), - getDraft: async () => null, - get: async (type: string) => - type === 'object' ? { fields: [{ name: 'name', label: 'Name' }] } : null, - save: async (_t: string, name: string, payload: Record) => { - server.saved.push(payload); - // Register the set so the post-create reload can list and open it. - server.byName[name] = payload; - return payload; - }, - // objectstack#36511 — a create and a Save publish that one set at once. - publish: async () => ({ success: true }), - reset: async () => ({}), - } as any; -} - -// This jsdom environment ships no window.confirm at all — install a mock -// outright rather than spying. -let confirmSpy: ReturnType; - -beforeEach(() => { - clientImpl = makeClient(freshServer()); - confirmSpy = vi.fn(); - window.confirm = confirmSpy as unknown as typeof window.confirm; -}); - -afterEach(cleanup); - -async function renderPillarOnSetA() { - render( - - - , - ); - // First set auto-selects; wait for its matrix row so the whole editor (not - // just the breadcrumb) has loaded before a test flips a cell. - await screen.findByText('a_account'); -} - -/** - * objectui#11862 — the rail shows each set's machine name as secondary text, so - * an open set's name is on the page more than once. objectui#12456 — the open - * set's api name is its item header's mono chip (the Delegated admin tab, kept - * mounted, lists every set name too), so "the matrix shows set X" is asked of - * that header alone. - */ -const inSetHeader = () => within(screen.getByTestId('access-item-header')); -// The header is re-queried on each retry: the pillar's own header stands in -// while no set is open, and the set's header replaces it once the page loads. -const findInSetHeader = (name: string) => waitFor(() => inSetHeader().getByTitle(name)); - -/** Flip a cell in the open matrix so the editor reports dirty. */ -function dirtyTheMatrix() { - const row = screen.getByText('a_account').closest('tr')!; - // objectui#12456 — the bulk strip draws on the row under the pointer. - fireEvent.mouseEnter(row); - fireEvent.click(within(row).getByRole('button', { name: 'None' })); -} - -describe('AccessPillar — unsaved matrix edits guard', () => { - it('asks before switching sets when dirty; cancel keeps the edits in place', async () => { - await renderPillarOnSetA(); - dirtyTheMatrix(); - - confirmSpy.mockReturnValueOnce(false); - fireEvent.click(screen.getByRole('button', { name: 'Set B' })); - - expect(confirmSpy).toHaveBeenCalledTimes(1); - // Still on set A, and the edit survived (row "None" left Read unchecked — - // a remount would have reloaded allowRead: true). - expect(inSetHeader().getByTitle('set_a')).toBeInTheDocument(); - const row = screen.getByText('a_account').closest('tr')!; - expect(within(row).getByRole('checkbox', { name: 'a_account Read' })).not.toBeChecked(); - - // Confirming the same switch discards and loads set B. - confirmSpy.mockReturnValueOnce(true); - fireEvent.click(screen.getByRole('button', { name: 'Set B' })); - expect(confirmSpy).toHaveBeenCalledTimes(2); - await findInSetHeader('set_b'); - }); - - it('switches sets without prompting when the matrix is clean', async () => { - await renderPillarOnSetA(); - - fireEvent.click(screen.getByRole('button', { name: 'Set B' })); - - expect(confirmSpy).not.toHaveBeenCalled(); - await findInSetHeader('set_b'); - }); - - it('gates the OWD overview swap too, and a confirmed discard clears the guard', async () => { - await renderPillarOnSetA(); - dirtyTheMatrix(); - - // Cancel keeps the matrix mounted. - confirmSpy.mockReturnValueOnce(false); - fireEvent.click(screen.getByRole('button', { name: 'Who can see which records' })); - expect(confirmSpy).toHaveBeenCalledTimes(1); - expect(screen.queryByTestId('owd-overview')).not.toBeInTheDocument(); - - // Confirm swaps to the overview (matrix unmounts → guard resets). - confirmSpy.mockReturnValueOnce(true); - fireEvent.click(screen.getByRole('button', { name: 'Who can see which records' })); - expect(await screen.findByTestId('owd-overview')).toBeInTheDocument(); - - // Back to a set: the discarded editor must NOT have left the guard armed. - fireEvent.click(screen.getByRole('button', { name: 'Set A' })); - expect(confirmSpy).toHaveBeenCalledTimes(2); - await findInSetHeader('set_a'); - }); - - it('never prompts when re-clicking the already-open set (nothing remounts)', async () => { - await renderPillarOnSetA(); - dirtyTheMatrix(); - - fireEvent.click(screen.getByRole('button', { name: 'Set A' })); - - expect(confirmSpy).not.toHaveBeenCalled(); - // Not remounted — the unsaved edit is still visible. - const row = screen.getByText('a_account').closest('tr')!; - expect(within(row).getByRole('checkbox', { name: 'a_account Read' })).not.toBeChecked(); - }); -}); - -/** Swap the main panel to the (real) OWD overview and edit a row so the panel - * reports dirty. Assumes the open matrix is clean, so the swap never prompts. */ -async function openAndDirtyTheOwd() { - fireEvent.click(screen.getByRole('button', { name: 'Who can see which records' })); - await screen.findByTestId('owd-internal-a_account'); - // The dial is the shared Select (objectui#11865): open it and pick, as a user does. - fireEvent.keyDown(screen.getByTestId('owd-internal-a_account'), { key: 'ArrowDown' }); - const listbox = await screen.findByRole('listbox'); - fireEvent.click(within(listbox).getByRole('option', { name: OWD_PRIVATE })); - await screen.findByTestId('owd-dirty-a_account'); -} - -const OWD_PRIVATE = t('engine.studio.settings.sharingPrivate', 'en-US'); -const OWD_UNSET = t('engine.studio.settings.sharingUnset', 'en-US'); - -/** What the dial's trigger shows. */ -const owdInternalValue = () => screen.getByTestId('owd-internal-a_account').textContent; - -describe('AccessPillar — unsaved OWD overview edits guard (#2600)', () => { - it('asks before swapping a dirty overview for a set; cancel keeps the edits', async () => { - await renderPillarOnSetA(); - await openAndDirtyTheOwd(); - - confirmSpy.mockReturnValueOnce(false); - fireEvent.click(screen.getByRole('button', { name: 'Set A' })); - expect(confirmSpy).toHaveBeenCalledTimes(1); - // Still on the overview, edit intact. - expect(owdInternalValue()).toBe(OWD_PRIVATE); - - // Confirming the same swap discards and mounts the set A matrix. - confirmSpy.mockReturnValueOnce(true); - fireEvent.click(screen.getByRole('button', { name: 'Set A' })); - expect(confirmSpy).toHaveBeenCalledTimes(2); - await findInSetHeader('set_a'); - - // The discarded panel reset the guard on unmount — swapping back to the - // overview must NOT prompt, and it reloads the untouched baseline. - fireEvent.click(screen.getByRole('button', { name: 'Who can see which records' })); - expect(confirmSpy).toHaveBeenCalledTimes(2); - await screen.findByTestId('owd-internal-a_account'); - expect(owdInternalValue()).toBe(OWD_UNSET); - }); - - it('never prompts when re-clicking the OWD rail entry (nothing remounts)', async () => { - await renderPillarOnSetA(); - await openAndDirtyTheOwd(); - - fireEvent.click(screen.getByRole('button', { name: 'Who can see which records' })); - - expect(confirmSpy).not.toHaveBeenCalled(); - // Not remounted — the unsaved edit is still visible. - expect(owdInternalValue()).toBe(OWD_PRIVATE); - }); - - it('gates the create-set flow, and creating lands on the new set matrix', async () => { - await renderPillarOnSetA(); - await openAndDirtyTheOwd(); - - // Cancel keeps the overview (and its edits) — no dialog. - confirmSpy.mockReturnValueOnce(false); - fireEvent.click(screen.getByRole('button', { name: 'New permission set' })); - expect(confirmSpy).toHaveBeenCalledTimes(1); - expect(screen.queryByRole('dialog')).toBeNull(); - expect(owdInternalValue()).toBe(OWD_PRIVATE); - - // Confirm opens the creator; submitting swaps the overview out for the - // new set's matrix (the discard the gate warned about). - confirmSpy.mockReturnValueOnce(true); - fireEvent.click(screen.getByRole('button', { name: 'New permission set' })); - const dialog = await screen.findByRole('dialog'); - fireEvent.change(within(dialog).getByPlaceholderText('Display name (e.g. Sales permissions)'), { - target: { value: 'Set C' }, - }); - // objectstack#36511 — a permission set is created live: the dialog says Create. - fireEvent.click(within(dialog).getByRole('button', { name: t('engine.studio.createLive', 'en-US') })); - - await findInSetHeader('set_c'); - expect(screen.queryByTestId('owd-overview')).not.toBeInTheDocument(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessNewSimilar-28573.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessNewSimilar-28573.test.tsx index 627cf3b7f6b..45bab7c95cb 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessNewSimilar-28573.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessNewSimilar-28573.test.tsx @@ -2,7 +2,8 @@ /** * objectstack#28573 (ADR-0146 D6, N-20b) — "New similar" on a read-only base's - * permission set, in Studio's Access pillar. + * permission set, on the set's full-screen page (objectstack#36905: in its ⋯ + * menu; the Access pillar that drew it is gone). * * The clone door (`POST /security/permission-sets/:name/clone`) decides where * the copy lands: since #28563 a set a read-only package X ships is copied into @@ -11,8 +12,8 @@ * * - offers "New similar" on a read-only base's open set, and posts exactly * `{ name, label }` (no package, no facet); - * - opens the copy where the answer says it landed: that package's Access - * pillar with the copy selected, the server's notice shown as sent; + * - opens the copy where the answer says it landed: the copy's metadata + * address in that package, the server's notice shown as sent; * - opens nothing on an answer that names no package (absent or `null`), and * says so; * - shows a refusal (409) in the server's words, staying on the base; @@ -21,9 +22,9 @@ * - draws no override gesture on a base set, and no "New similar" on a * writable package's set. * - * The REAL `AccessPillar`, `PermissionMatrixEditPage` and - * `PermissionSetCloneDialog`, routed the way `StudioDesignSurface` mounts the - * pillar (`/studio/:packageId/access`, keyed by package). The door's answer is + * The REAL `StudioPermissionSetPage`, `PermissionMatrixEditPage` and + * `PermissionSetCloneDialog`, routed the way the "All metadata" area mounts the + * page (`/studio/:packageId/metadata/permission/:name`, keyed by item). The door's answer is * the shape `packages/runtime/src/domains/permission-set-clone.ts` sends: * `{ permissionSet, package, notice }`. */ @@ -91,7 +92,7 @@ vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); import { t, tFormat, translateMetadataType } from '../metadata-admin/i18n'; -import { AccessPillar } from './StudioDesignSurface'; +import { StudioPermissionSetPage } from './StudioPermissionSetPage'; window.matchMedia = ((query: string) => ({ matches: false, @@ -166,23 +167,25 @@ function stubFetch() { ); } -/** `StudioDesignSurface`'s mount of the pillar: one route, keyed by package. */ +/** The area's mount of the page: one route, keyed by item. */ function StudioAccessRoute() { - const { packageId = '' } = useParams<{ packageId?: string }>(); + const { packageId = '', name = '' } = useParams<{ packageId?: string; name?: string }>(); const { pathname, search } = useLocation(); return ( <> {pathname + search} - + ); } +/** A package's set at its metadata address: the base's own set, or the copy in the pair. */ function renderAccess(pkg = BASE_PKG, lang: 'en' | 'zh' = 'en') { + const set = pkg === BASE_PKG ? BASE_SET : COPY_NAME; const tree = ( - + - } /> + } /> ); @@ -194,8 +197,20 @@ function renderAccess(pkg = BASE_PKG, lang: 'en' | 'zh' = 'en') { render({tree}); } -const newSimilar = () => screen.findByRole('button', { name: en('perm.clone.action') }, { timeout: 8000 }); +/** The header's ⋯ menu, opened. */ +async function openMore() { + const more = await screen.findByTestId('studio-detail-more', undefined, { timeout: 8000 }); + fireEvent.pointerDown(more, { button: 0, ctrlKey: false, pointerType: 'mouse' }); +} +/** "New similar" in the open ⋯ menu. */ +const newSimilar = async (label = en('perm.clone.action')) => { + await openMore(); + return screen.findByRole('menuitem', { name: label }, { timeout: 8000 }); +}; const route = () => screen.getByTestId('route').textContent ?? ''; +/** The copy's metadata address in `pkg`. */ +const copyAt = (pkg: string) => `/studio/${pkg}/metadata/permission/${COPY_NAME}`; +const baseAt = `/studio/${BASE_PKG}/metadata/permission/${BASE_SET}`; async function fillAndCreate() { fireEvent.click(await newSimilar()); @@ -225,7 +240,7 @@ afterEach(() => { describe('objectstack#28573 — New similar on a read-only base permission set', () => { it('reads "New similar" (en) and draws no override gesture on the base set', async () => { renderAccess(); - expect(await newSimilar()).toBeEnabled(); + expect(await newSimilar()).not.toHaveAttribute('aria-disabled', 'true'); expect(en('perm.clone.action')).toBe('New similar'); expect(screen.queryByRole('button', { name: /customi[sz]e|override/i })).toBeNull(); }); @@ -237,13 +252,11 @@ describe('objectstack#28573 — New similar on a read-only base permission set', await waitFor(() => expect(calls).toHaveLength(1)); expect(calls[0]).toEqual({ url: DOOR, method: 'POST', body: { name: COPY_NAME, label: COPY_LABEL } }); - // The pair's Access pillar, with the copy selected. - await waitFor(() => expect(new URL(route(), 'http://x').pathname).toBe(`/studio/${CUSTOM_PKG}/access`)); - expect(new URL(route(), 'http://x').searchParams.get('surface')).toBe(`permission:${COPY_NAME}`); + // The copy's own address, in the pair. + await waitFor(() => expect(new URL(route(), 'http://x').pathname).toBe(copyAt(CUSTOM_PKG))); + expect(new URL(route(), 'http://x').searchParams.get('package')).toBe(CUSTOM_PKG); expect(await screen.findByRole('heading', { level: 1, name: COPY_LABEL }, { timeout: 8000 })).toBeInTheDocument(); expect(clientImpl.list).toHaveBeenCalledWith('permission', { packageId: CUSTOM_PKG }); - // Writable there: the copy is no base, so no New similar is offered on it. - expect(screen.queryByRole('button', { name: en('perm.clone.action') })).toBeNull(); // Where it went and what was not copied, in the server's words. const strip = screen.getByTestId('access-new-similar-strip'); expect(strip).toHaveTextContent( @@ -280,7 +293,7 @@ describe('objectstack#28573 — New similar on a read-only base permission set', const strip = await screen.findByTestId('access-new-similar-strip'); expect(strip).toHaveTextContent(tFormat('engine.studio.access.newSimilar.noPackage', 'en', { name: COPY_NAME })); expect(strip).toHaveTextContent(NOTICE); - expect(route()).toBe(`/studio/${BASE_PKG}/access?surface=permission%3A${BASE_SET}`); + expect(route()).toBe(`${baseAt}?package=${BASE_PKG}`); expect(clientImpl.layered.mock.calls.every((c: unknown[]) => c[1] === BASE_SET)).toBe(true); }); } @@ -291,7 +304,7 @@ describe('objectstack#28573 — New similar on a read-only base permission set', await fillAndCreate(); expect(await screen.findByTestId('access-new-similar-strip')).toHaveTextContent(en('perm.clone.noName')); - expect(new URL(route(), 'http://x').pathname).toBe(`/studio/${BASE_PKG}/access`); + expect(new URL(route(), 'http://x').pathname).toBe(baseAt); }); it('409: the server\'s sentence in the dialog, which stays open on the base', async () => { @@ -304,14 +317,14 @@ describe('objectstack#28573 — New similar on a read-only base permission set', expect(await within(dialog).findByRole('alert')).toHaveTextContent(NAME_TAKEN); expect(screen.getByRole('dialog')).toBeInTheDocument(); - expect(new URL(route(), 'http://x').pathname).toBe(`/studio/${BASE_PKG}/access`); + expect(new URL(route(), 'http://x').pathname).toBe(baseAt); }); it('walled posture: disabled, in the console\'s own words, and nothing is sent', async () => { walled = true; renderAccess(); const button = await newSimilar(); - expect(button).toBeDisabled(); + expect(button).toHaveAttribute('aria-disabled', 'true'); expect(button).toHaveAccessibleDescription( tFormat('engine.catalog.readOnly.walled', 'en', { type: translateMetadataType('permission', 'en') }), ); @@ -324,7 +337,7 @@ describe('objectstack#28573 — New similar on a read-only base permission set', canAuthor = false; renderAccess(); const button = await newSimilar(); - expect(button).toBeDisabled(); + expect(button).toHaveAttribute('aria-disabled', 'true'); expect(button).toHaveAccessibleDescription(en('engine.edit.capabilityReadOnly')); }); @@ -332,7 +345,9 @@ describe('objectstack#28573 — New similar on a read-only base permission set', clientImpl = makeClient({ [COPY_NAME]: { pkg: CUSTOM_PKG, body: { ...BASE_BODY, name: COPY_NAME, label: COPY_LABEL } } }); renderAccess(CUSTOM_PKG); expect(await screen.findByRole('heading', { level: 1, name: COPY_LABEL }, { timeout: 8000 })).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: en('perm.clone.action') })).toBeNull(); + await openMore(); + await screen.findByRole('menuitem', { name: en('perm.basics.editHint') }); + expect(screen.queryByRole('menuitem', { name: en('perm.clone.action') })).toBeNull(); }); }); @@ -349,7 +364,7 @@ describe('objectstack#29727 — New similar on a permission set: the notice in t async function cloneInZh(): Promise { renderAccess(BASE_PKG, 'zh'); - fireEvent.click(await screen.findByRole('button', { name: zh('perm.clone.action') }, { timeout: 8000 })); + fireEvent.click(await newSimilar(zh('perm.clone.action'))); const dialog = await screen.findByRole('dialog'); fireEvent.change(within(dialog).getByLabelText(zh('perm.clone.name')), { target: { value: COPY_NAME } }); fireEvent.change(within(dialog).getByLabelText(zh('perm.clone.label')), { target: { value: COPY_LABEL } }); @@ -369,7 +384,7 @@ describe('objectstack#29727 — New similar on a permission set: the notice in t const strip = await cloneInZh(); if (pkg !== null) { // The copy opens in the package the answer names: the code rides the navigation there. - await waitFor(() => expect(new URL(route(), 'http://x').pathname).toBe(`/studio/${pkg}/access`)); + await waitFor(() => expect(new URL(route(), 'http://x').pathname).toBe(copyAt(pkg))); } expect(strip).not.toHaveTextContent(NOTICE); expect(zh(key)).not.toBe(key); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessPairCopy-29674.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessPairCopy-29674.test.tsx index 7f65c9db2f4..00081c5d2ac 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessPairCopy-29674.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessPairCopy-29674.test.tsx @@ -8,8 +8,17 @@ * it read "0 objects granted · 0 field overrides" and listed nothing, though * the server holds 8 objects and 3 field overrides. * - * The REAL `StudioDesignSurface`, `AccessPillar` and `PermissionMatrixEditPage` - * over the REAL metadata client and a fetch stub serving the package list (the + * objectstack#36905 — each set opens at its own metadata address, the copy at + * its pair's (`/studio//metadata/permission/`, as the base's list + * links it), in the full-screen page (`StudioPermissionSetPage`). The retired + * pillar opened the copy on the BASE's address, + * `/studio//access?surface=permission:`: that old bookmark + * redirects to the pair's address, where the copy opens writable, and the + * base's own set's old address stays on the base (CONTROL). The address's + * other parameters ride along through the real surface. + * + * The REAL `StudioDesignSurface` (its area), `StudioPermissionSetPage` and + * `PermissionMatrixEditPage` over the REAL metadata client and a fetch stub serving the package list (the * base read-only, its pair writable), the base's customization read, the * base's objects and sets, and the copy, published in the pair. * @@ -21,17 +30,21 @@ * keeping every grant it holds; no write names the base; * - CONTROL: the base's own (read-only) set lists the base's objects and * reads no pair list for them; - * - objectstack#29809: the header's provenance chip follows the rail's mark, - * Custom for a set the pair holds (copied or created there), Package for - * the base's own set. + * - objectstack#29809: the header's provenance chip reads Custom for a set + * the pair holds (copied or created there), Package for the base's own + * set. Only the header's half is pinned here: the rail that drew the + * matching mark beside it went with the Access pillar (objectstack#36905). */ import '@testing-library/jest-dom/vitest'; // The source under test reaches these through dynamic imports: their first load is paid at collection. import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; const BASE = 'com.example.showcase'; const PAIR = 'com.example.showcase.custom'; @@ -203,17 +216,38 @@ afterEach(() => { vi.unstubAllGlobals(); }); +/** A set at its metadata address: the copy and a set created there at the pair's, the base's own at the base's. */ function renderAccess(set: string) { + const pkg = set === BASE_SET.name ? BASE : PAIR; + return render( + + + } /> + + , + ); +} + +/** Where the router stands. */ +function LocationProbe() { + const location = useLocation(); + return {`${location.pathname}${location.search}`}; +} + +/** The retired pillar's address of `set`, on the base, with `extra` beside its `?surface=`. */ +function renderPillarAddress(set: string, extra = '') { return render( - + + } /> } /> + , ); } -const header = () => screen.getByTestId('access-item-header'); +const header = () => screen.getByTestId('permission-detail-header'); const matrix = () => screen.getByTestId('perm-studio-matrix'); const countsText = (objects: number, fields: number) => `${tFormat('engine.studio.access.grantedOther', 'en', { count: objects })} · ${tFormat( @@ -284,46 +318,89 @@ describe('CONTROL: the base’s own set (objectstack#29674)', () => { }); /** - * objectstack#29809 (ADR-0146 D3) — the header's provenance chip and the rail - * row's customization mark tell one story: a set the pair holds reads Custom - * beside the rail's Added, and the base's own set still reads Package with no - * mark. Same harness: the real surface, pillar and page. + * objectstack#29809 (ADR-0146 D3) — the header's provenance chip: a set the + * pair holds reads Custom, and the base's own set still reads Package. Same + * harness: the real surface, area and page. The header alone is read here; + * no list is drawn beside the page. */ -describe('the header’s provenance chip follows the rail’s mark (objectstack#29809)', () => { - /** A set created in the pair: its draft, never published, listed from the pair’s drafts. */ +describe('the header’s provenance chip: Custom in the pair, Package on the base (objectstack#29809)', () => { + /** A set created in the pair: its draft, never published. */ const CREATED = 'pair_auditor'; - const accessRail = () => screen.getByTestId('studio-rail-access'); - /** The rail row holding `text`, and the kind of mark it carries (`null`: none). */ - const railMarkOf = (text: string) => - within(accessRail()) - .getByText(text) - .closest('button') - ?.querySelector('[data-testid="customization-mark"]') - ?.getAttribute('data-kind') ?? null; const chip = () => within(header()).getByTestId('perm-provenance-badge'); - it('a New similar copy in the pair: Custom in the header, Added in the rail', async () => { + it('a New similar copy in the pair: Custom in the header', async () => { renderAccess(COPY); await copyOpen(); - await waitFor(() => expect(railMarkOf('My contributor')).toBe('added'), { timeout: 8000 }); expect(chip()).toHaveTextContent(t('perm.badge.custom', 'en')); expect(chip()).not.toHaveTextContent(t('engine.studio.access.origin.app', 'en')); }); - it('a set created in the pair: Custom in the header, Added in the rail', async () => { + it('a set created in the pair: Custom in the header', async () => { srv.pairDrafts.set(`permission/${CREATED}`, { name: CREATED, label: 'Pair auditor', objects: {}, fields: {} }); renderAccess(CREATED); await waitFor(() => expect(within(header()).getAllByTitle(CREATED).length).toBeGreaterThan(0), { timeout: 8000 }); - await waitFor(() => expect(railMarkOf(CREATED)).toBe('added'), { timeout: 8000 }); - expect(chip()).toHaveTextContent(t('perm.badge.custom', 'en')); + await waitFor(() => expect(chip()).toHaveTextContent(t('perm.badge.custom', 'en')), { timeout: 8000 }); }); - it('CONTROL: the base’s own set reads Package, and its rail row carries no mark', async () => { + it('CONTROL: the base’s own set reads Package', async () => { renderAccess(BASE_SET.name); await waitFor(() => expect(within(header()).getByText(/(^|· )Contributor$/)).toBeInTheDocument(), { timeout: 8000 }); - // The read has answered: the copy's row is marked, the base set's is not. - await waitFor(() => expect(railMarkOf('My contributor')).toBe('added'), { timeout: 8000 }); - expect(railMarkOf('Contributor')).toBeNull(); - expect(chip()).toHaveTextContent(t('engine.studio.access.origin.app', 'en')); + await waitFor(() => expect(chip()).toHaveTextContent(t('engine.studio.access.origin.app', 'en')), { timeout: 8000 }); + }); +}); + +/** + * objectstack#36905 — the retired pillar's address of a set. On a read-only + * base it listed the sets the pair adds and opened them at the pair, writable, + * while the address named the base; the redirect sends such a set to the + * pair's address, not to the base's stack, which does not hold it. + */ +describe('the retired pillar’s address of a set the pair adds opens it at the pair (objectstack#36905)', () => { + const location = () => screen.getByTestId('location').textContent; + + it('`/studio//access?surface=permission:` lands on the pair’s address, and the copy opens writable there', async () => { + renderPillarAddress(COPY); + await waitFor(() => expect(location()).toBe(`/studio/${PAIR}/metadata/permission/${COPY}?package=${PAIR}`), { + timeout: 8000, + }); + await copyOpen(); + await waitFor(() => expect(header()).toHaveTextContent(countsText(8, 3))); + expect(within(header()).getByTestId('perm-provenance-badge')).toHaveTextContent(t('perm.badge.custom', 'en')); + // Writable: an edit saves the copy's draft at the pair. + fireEvent.click(within(matrix()).getByLabelText(`sc_note ${t('perm.action.edit', 'en')}`)); + await pressStudioSave(); + await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); + expect(new URLSearchParams(srv.saves[0]!.search).get('package')).toBe(PAIR); + }); + + it('a set created in the pair, still a draft, lands on the pair’s address too', async () => { + const CREATED = 'pair_auditor'; + srv.pairDrafts.set(`permission/${CREATED}`, { name: CREATED, label: 'Pair auditor', objects: {}, fields: {} }); + renderPillarAddress(CREATED); + await waitFor(() => expect(location()).toBe(`/studio/${PAIR}/metadata/permission/${CREATED}?package=${PAIR}`), { + timeout: 8000, + }); + }); + + it('the address’s other parameters ride along through the surface', async () => { + // A parameter no Studio page consumes (`?changes=review` is, by the surface: it opens the drawer). + renderPillarAddress(COPY, '&ref=bookmark'); + await waitFor( + () => expect(location()).toBe(`/studio/${PAIR}/metadata/permission/${COPY}?ref=bookmark&package=${PAIR}`), + { timeout: 8000 }, + ); + await copyOpen(); + }); + + it('CONTROL: the base’s own set’s old address stays on the base', async () => { + renderPillarAddress(BASE_SET.name); + await waitFor( + () => expect(location()).toBe(`/studio/${BASE}/metadata/permission/${BASE_SET.name}?package=${BASE}`), + { timeout: 8000 }, + ); + await waitFor(() => expect(within(header()).getByText(/(^|· )Contributor$/)).toBeInTheDocument(), { timeout: 8000 }); + await waitFor(() => expect(within(header()).getByTestId('perm-provenance-badge')).toHaveTextContent( + t('engine.studio.access.origin.app', 'en'), + ), { timeout: 8000 }); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessRailLabelLive-26846.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessRailLabelLive-26846.test.tsx deleted file mode 100644 index d51c8636a4c..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessRailLabelLive-26846.test.tsx +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectstack#26846 — a label the open set's draft save changed shows on the - * Access rail at once: the pillar reads its sets again on the matrix's - * `onDraftSaved`, with no publish and no reload. The matrix page is a stand-in - * that reports one draft save; the pillar and its rail are the real ones. - * - * CONTROL: before that save the rail reads the label it loaded. - */ - -import '@testing-library/jest-dom/vitest'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -let draftLabel = 'Dispatcher'; - -const mockClient = { - list: vi.fn(async () => []), - listDrafts: vi.fn(async () => [{ type: 'permission', name: 'dispatcher', packageId: 'app.a', label: draftLabel }]), - layered: vi.fn(async () => null), - getDraft: vi.fn(async () => null), - get: vi.fn(async () => null), - save: vi.fn(async () => ({})), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useMetadataClient: () => mockClient, - useMetadataTypes: () => ({ - loading: false, - error: null, - entries: [{ type: 'permission', label: 'Permission', allowEnvironmentOverlay: true }], - }), - }; -}); -// The open set's editor: one button that stands for an autosave of its label. -vi.mock('../metadata-admin/PermissionMatrixEditor', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - PermissionMatrixEditPage: ({ onDraftSaved }: { onDraftSaved?: () => void }) => ( - - ), - }; -}); -vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); - -import { AccessPillar } from './StudioDesignSurface'; - -// jsdom has no matchMedia — useIsMobile (rail overlay) needs a stub. -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -afterEach(cleanup); - -describe('objectstack#26846 — the Access rail follows a draft save of the open set', () => { - it('a label the save changed shows on the rail without a publish or a reload', async () => { - draftLabel = 'Dispatcher'; - const onDraftSaved = vi.fn(); - render( - - - , - ); - const rail = within(await screen.findByTestId('studio-rail-access')); - // CONTROL: the label the rail loaded. - expect(await rail.findByRole('button', { name: 'Dispatcher' })).toBeInTheDocument(); - - fireEvent.click(await screen.findByTestId('matrix-autosave')); - expect(onDraftSaved).toHaveBeenCalledTimes(1); - await waitFor(() => expect(rail.getByRole('button', { name: 'Dispatcher v2' })).toBeInTheDocument()); - expect(rail.queryByRole('button', { name: 'Dispatcher' })).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessRailLabels-11862.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessRailLabels-11862.test.tsx deleted file mode 100644 index 7c06ba99f9f..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessRailLabels-11862.test.tsx +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#11862 — the Access pillar's permission-set list shows a set's label - * as the primary text and its machine name as secondary information: since - * objectstack#34795 (the page shows no machine name) that is the row's tooltip. - * - * On the maintainer's word 「所有地方以标签为主,机器名只作为次要信息」: - * - * - a set with a label reads as the label, with its machine name as the - * tooltip, and the row's accessible name stays the label; - * - CONTROL: a set with no label reads as its name alone, once; - * - a set that exists only as a draft reads as the label its `_drafts` row - * carries (objectstack-ai/objectstack#22200, ruling `6053526025` question 1), - * with its machine name as the tooltip. The label is read off that row: the - * set itself is not read for it; - * - a draft's locale-map label reads in the designer locale, never as - * `[object Object]`; - * - CONTROL: a draft whose `_drafts` row carries no label (`null`, the - * producer's honest answer) reads as its name alone, once. - */ - -import '@testing-library/jest-dom/vitest'; -// The source under test reaches these through dynamic imports: their first load is paid at collection. -import '@objectstack/lint'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, render, screen, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -const mockClient = { - list: vi.fn(async (type: string) => { - if (type === 'permission') return [{ name: 'technician', label: 'Technician' }, { name: 'field_lead' }]; - if (type === 'object') return [{ name: 'a_account' }]; - return []; - }), - // Draft-only sets: each `_drafts` row carries the draft body's own label, - // or `null` when the body declares none (objectstack-ai/objectstack#22200). - listDrafts: vi.fn(async () => [ - { type: 'permission', name: 'dispatcher', packageId: 'app.a', label: 'Dispatcher' }, - { type: 'permission', name: 'night_shift', packageId: 'app.a', label: { en: 'Night shift', 'zh-CN': '夜班' } }, - { type: 'permission', name: 'auditor', packageId: 'app.a', label: null }, - ]), - layered: vi.fn(async (_type: string, name: string) => ({ - effective: { name, label: name === 'technician' ? 'Technician' : undefined, objects: {}, fields: {} }, - code: null, - overlay: null, - overlayScope: null, - })), - getDraft: vi.fn(async () => null), - get: vi.fn(async () => null), - save: vi.fn(async () => ({})), -}; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useMetadataClient: () => mockClient, - useMetadataTypes: () => ({ - loading: false, - error: null, - entries: [{ type: 'permission', label: 'Permission', allowEnvironmentOverlay: true }], - }), - }; -}); -vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); -vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); - -import { AccessPillar } from './StudioDesignSurface'; - -// jsdom has no matchMedia — useIsMobile (rail overlay) needs a stub. -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as unknown as typeof window.matchMedia; - -afterEach(cleanup); - -function renderPillar() { - render( - - - , - ); -} - -// objectstack#34795 — the machine name is the row's tooltip, no longer its secondary text. -describe('objectui#11862 — the permission-set list: the label, the machine name its tooltip', () => { - it('a set with a label reads as the label, its machine name as the tooltip', async () => { - renderPillar(); - const row = await screen.findByRole('button', { name: 'Technician' }); - expect(within(row).getByText('Technician')).toBeInTheDocument(); - expect(within(row).queryByText('technician')).toBeNull(); - expect(within(row).getByTitle('technician')).toHaveTextContent('Technician'); - }); - - it('CONTROL: a set with no label reads as its name alone, once', async () => { - renderPillar(); - const row = await screen.findByRole('button', { name: 'field_lead' }); - expect(within(row).getAllByText('field_lead')).toHaveLength(1); - }); - - it("a draft-only set reads as its `_drafts` row's label, its machine name as the tooltip", async () => { - renderPillar(); - const row = await screen.findByRole('button', { name: 'Dispatcher' }); - expect(within(row).getByText('Dispatcher')).toBeInTheDocument(); - expect(within(row).queryByText('dispatcher')).toBeNull(); - expect(within(row).getByTitle('dispatcher')).toHaveTextContent('Dispatcher'); - // Read off the row: the draft-only set is never read for its label. - const reads = [...mockClient.layered.mock.calls, ...mockClient.getDraft.mock.calls, ...mockClient.get.mock.calls]; - expect(reads.filter((call) => (call as unknown[])[1] === 'dispatcher')).toEqual([]); - }); - - it("a draft's locale-map label reads in the designer locale", async () => { - renderPillar(); - const row = await screen.findByRole('button', { name: 'Night shift' }); - expect(within(row).getByTitle('night_shift')).toHaveTextContent('Night shift'); - expect(row).not.toHaveTextContent('[object Object]'); - }); - - it('CONTROL: a draft whose `_drafts` row carries no label reads as its name alone, once', async () => { - renderPillar(); - const row = await screen.findByRole('button', { name: 'auditor' }); - expect(within(row).getAllByText('auditor')).toHaveLength(1); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSegment-12452.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSegment-12452.test.tsx index ee586e1d63e..7c1696d06d1 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSegment-12452.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSegment-12452.test.tsx @@ -14,7 +14,8 @@ * 1. The menu's Access group holds the permission-set entry, a real router * link, with no "More" trigger anywhere; the group carries the shield glyph, * the Data group's is not it. - * 2. With the Access pillar open (under any package id) that entry is the + * 2. With the Access pillar's address open (under any package id) — which + * lands on the list of sets since objectstack#36905 — that entry is the * current page and carries the active state; with Data open it carries * neither, and the object entry carries both. * @@ -115,6 +116,14 @@ vi.mock('sonner', () => ({ vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); +// objectstack#36905 — the area's pages, where the Access pillar's address lands. +vi.mock('../metadata-admin/index.js', () => ({ + MetadataDirectoryPage: () =>
, + MetadataDiagnosticsPage: () =>
, + MetadataResourceListPage: () =>
, + MetadataResourceEditPage: () =>
, + MetadataResourceHistoryPage: () =>
, +})); vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); @@ -123,6 +132,9 @@ import { translateMetadataDomain } from '../metadata-admin/i18n'; // The source under test reaches dynamic imports of `@objectstack/lint`; their first // load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; window.matchMedia = ((query: string) => ({ matches: false, @@ -184,6 +196,7 @@ function renderAt(path: string) { } /> + } /> , @@ -222,7 +235,8 @@ describe('Studio menu: Access is a group of its own, and More is gone (objectui# it.each(['app.objectstack.hotcrm', PKG])('with Access open in %s, the permission-set entry is the current page', async (pkg) => { fetchPackagesMock.mockResolvedValue([{ id: pkg, name: 'Pkg', writable: true, namespace: 'pkg' }]); renderAt(`/studio/${pkg}/access`); - await screen.findByTestId('studio-shell-header'); + await screen.findByTestId('area-page'); + expect(screen.getByTestId('location-path')).toHaveTextContent(`/studio/${pkg}/metadata/permission`); const access = entry(PERMISSION_ENTRY); expect(access).toHaveAttribute('aria-current', 'page'); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSuggestionsReadOnly-33158.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSuggestionsReadOnly-33158.test.tsx index bf2e6af79a3..1a03835c3dd 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSuggestionsReadOnly-33158.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessSuggestionsReadOnly-33158.test.tsx @@ -1,21 +1,22 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectstack#33158 (ADR-0090 D5/D9) — the Access pillar's suggested-bindings - * strip on a READ-ONLY package. A marketplace-installed package is read-only in + * objectstack#33158 (ADR-0090 D5/D9) — Studio's suggested-bindings strip on a + * READ-ONLY package, drawn since objectstack#36905 on the permission set's + * full-screen page (`StudioPermissionSetPage`), as the Access pillar drew it. A marketplace-installed package is read-only in * Studio, and it is the package that ships an `isDefault` set; accepting or * dismissing that suggestion is a deployment decision about the package, not * an edit of it, so the strip is drawn whatever `readOnly` says. * - * The REAL `AccessPillar` and `SuggestedBindingsPanel`, over a metadata client + * The REAL `StudioPermissionSetPage` and `SuggestedBindingsPanel`, over a metadata client * double and a stub of the suggestion door's client. * * Pinned: * - on a read-only package a pending suggestion renders the strip with Accept * and Dismiss, listed for this package; * - CONTROL: a writable package renders the same strip; - * - CONTROL: on the read-only package the pillar's authoring affordance (the - * rail's "+ New") stays absent, while the writable package offers it; + * - CONTROL: on the read-only package the page still says nothing is saved + * (its header's read-only link), while the writable package draws none; * - a list refused `403` (a caller without `manage_metadata`) renders no * strip and no error. */ @@ -44,10 +45,12 @@ vi.mock('../../services/suggestedBindingsApi', () => ({ reopenSuggestedBinding: api.reopen, })); +/** The label the package's set list serves for `crm_user` (a case may serve none). */ +let setLabel = 'CRM user'; const client = { withPreviewDrafts() { return this; }, list: vi.fn(async (type: string) => - type === 'permission' ? [{ name: 'crm_user', label: 'CRM user', isDefault: true }] : [], + type === 'permission' ? [{ name: 'crm_user', label: setLabel, isDefault: true }] : [], ), listDrafts: vi.fn(async () => []), layered: vi.fn(async () => ({ effective: null, code: null, overlay: null, overlayScope: null })), @@ -75,7 +78,7 @@ vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); import { toast } from 'sonner'; import { t, tFormat } from '../metadata-admin/i18n'; -import { AccessPillar } from './StudioDesignSurface'; +import { StudioPermissionSetPage } from './StudioPermissionSetPage'; window.matchMedia = ((query: string) => ({ matches: false, @@ -105,12 +108,13 @@ function refused(status: number, code: string, message: string): Error { afterEach(() => { cleanup(); vi.clearAllMocks(); + setLabel = 'CRM user'; }); function renderAccess(readOnly: boolean) { render( - + , ); } @@ -137,17 +141,17 @@ describe('objectstack#33158 — the suggested-bindings strip on a read-only pack expect(api.list).toHaveBeenCalledWith({ packageId: PKG }); }); - it('CONTROL: the read-only package keeps its authoring affordance absent; the writable one offers it', async () => { + it('CONTROL: the read-only package still says nothing is saved; the writable one does not', async () => { api.list.mockResolvedValue([PENDING]); renderAccess(true); await screen.findByTestId('suggested-bindings-panel', undefined, { timeout: 8000 }); - await screen.findByTestId('studio-rail-access'); - expect(screen.queryByTestId('studio-rail-add')).toBeNull(); + expect(await screen.findByTestId('studio-readonly-link')).toBeInTheDocument(); cleanup(); renderAccess(false); await screen.findByTestId('suggested-bindings-panel', undefined, { timeout: 8000 }); - expect(await screen.findByTestId('studio-rail-add')).toBeInTheDocument(); + await screen.findByTestId('permission-detail-header'); + expect(screen.queryByTestId('studio-readonly-link')).toBeNull(); }); it('a list refused 403 (no manage_metadata) renders no strip and no error', async () => { @@ -155,7 +159,7 @@ describe('objectstack#33158 — the suggested-bindings strip on a read-only pack refused(403, 'PERMISSION_DENIED', 'listing audience-binding suggestions requires the `manage_metadata` capability.'), ); renderAccess(true); - await screen.findByTestId('studio-rail-access', undefined, { timeout: 8000 }); + await screen.findByTestId('permission-detail-header', undefined, { timeout: 8000 }); await waitFor(() => expect(api.list).toHaveBeenCalledTimes(1)); // Let the refused read settle before asserting its absence. await new Promise((r) => setTimeout(r, 0)); @@ -225,14 +229,12 @@ describe('objectstack#33864 — the suggested-bindings strip names its set by la ); }); - it('CONTROL: a set the rail holds no label for is named by its machine name', async () => { - client.list.mockImplementationOnce(async (type: string) => - type === 'permission' ? [{ name: 'crm_user', label: '', isDefault: true }] : [], - ); + it('CONTROL: a set the list holds no label for is named by its machine name', async () => { + setLabel = ''; api.list.mockResolvedValue([PENDING]); renderAccess(false); const row = await screen.findByTestId('suggested-binding-crm_user', undefined, { timeout: 8000 }); - await screen.findByTestId('studio-rail-access'); + await waitFor(() => expect(client.list).toHaveBeenCalledWith('permission', { packageId: PKG })); await waitFor(() => expect(row).toHaveTextContent(fmt('engine.studio.access.suggestPromptEveryone', 'crm_user')), ); @@ -243,7 +245,7 @@ describe('objectstack#33864 — the suggested-bindings strip names its set by la * objectstack#33865 (`ux-conventions.write-feedback`) — Revoke on a granted * suggestion is a write, and it answers with a toast naming the set, as Grant * and Dismiss do. The Studio mount hands the strip its own `revokedToast` - * sentence; this reads it through the REAL pillar: Grant, then Revoke on the + * sentence; this reads it through the REAL page: Grant, then Revoke on the * row the Grant left. * * Pinned: diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessTabs-12456.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessTabs-12456.test.tsx deleted file mode 100644 index 47e66bed08f..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessTabs-12456.test.tsx +++ /dev/null @@ -1,239 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * objectui#12456 — the Access pillar's open permission set (epic - * objectui#12446, decision C): - * - * • the item header carries the set: its label (its api name the title's - * tooltip since objectstack#34795), the Package label and "N objects - * granted · M field overrides"; the PageShell breadcrumb and badge row it - * replaces are gone, - * • five tabs, Objects the landing; each other tab shows its section, - * • the object matrix's bulk strip draws on every row (objectstack#34795; - * it drew only on the row under the pointer or with keyboard focus), - * • the tab bodies stay mounted, so a closed facet tab still reports to the - * Save gate. - */ - -import '@testing-library/jest-dom/vitest'; -// The source under test reaches these through dynamic imports: their first load is paid at collection. -import '@objectstack/lint'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import { MemoryRouter } from 'react-router-dom'; - -let clientImpl: any; - -vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { - const actual = await importOriginal>(); - return { - ...actual, - useMetadataClient: () => clientImpl, - useMetadataTypes: () => ({ - loading: false, - error: null, - entries: [{ type: 'permission', label: 'Permission', allowEnvironmentOverlay: true }], - }), - }; -}); -vi.mock('../../components/SuggestedBindingsPanel', () => ({ - SuggestedBindingsPanel: () => null, -})); -vi.mock('../metadata-admin/AccessExplainPanel', () => ({ - AccessExplainPanel: () => null, -})); -vi.mock('./StudioAiCopilot', () => ({ - StudioChatDock: () => null, -})); - -import { t } from '../metadata-admin/i18n'; -import { AccessPillar } from './StudioDesignSurface'; - -window.matchMedia = ((query: string) => ({ - matches: false, - media: query, - onchange: null, - addEventListener: () => {}, - removeEventListener: () => {}, - addListener: () => {}, - removeListener: () => {}, - dispatchEvent: () => false, -})) as any; - -const en = (key: string) => t(key, 'en-US'); - -function makeClient() { - const sets: Record> = { - guest_portal: { - name: 'guest_portal', - label: 'Guest (Public Forms)', - objects: { crm_lead: { allowCreate: true } }, - fields: {}, - }, - }; - return { - // objectstack#26840 — the Access matrix reads its objects through the draft-overlaid door. - withPreviewDrafts() { return this; }, - list: async (type: string) => { - if (type === 'permission') return Object.values(sets).map((s) => ({ name: s.name, label: s.label })); - if (type === 'object') { - return [ - { name: 'crm_account', label: 'Account' }, - { name: 'crm_lead', label: 'Lead' }, - ]; - } - return []; - }, - listDrafts: async () => [], - layered: async (_type: string, name: string) => ({ - effective: sets[name], - code: null, - overlay: null, - overlayScope: null, - }), - getDraft: async () => null, - get: async () => ({ fields: [] }), - save: async (_t: string, _n: string, payload: Record) => payload, - } as any; -} - -beforeEach(() => { - clientImpl = makeClient(); - window.confirm = vi.fn() as unknown as typeof window.confirm; -}); - -afterEach(cleanup); - -async function renderGuestPortal() { - render( - - - , - ); - await screen.findByTestId('perm-row-crm_lead'); -} - -const header = () => within(screen.getByTestId('access-item-header')); -const tab = (key: string) => screen.getByTestId(`perm-tab-${key}`); - -describe('Access pillar — the open set is a header and five tabs (objectui#12456)', () => { - it('the header reads the label, the api name, Package and the grant counts', async () => { - await renderGuestPortal(); - expect(header().getByRole('heading', { level: 1 })).toHaveTextContent('Guest (Public Forms)'); - // objectstack#34795 — the api name is the title's tooltip, not a chip. - expect(header().getByRole('heading', { level: 1 })).toHaveAttribute('title', 'guest_portal'); - expect(header().queryByText('guest_portal')).toBeNull(); - // objectstack#35018 — the Studio note reads the builder's words, not the package term. - expect(header().getByTestId('perm-provenance-badge')).toHaveTextContent(en('engine.studio.access.origin.app')); - expect(header().getByText('1 object granted · 0 field overrides')).toBeInTheDocument(); - expect(header().getByRole('button', { name: en('engine.studio.access.explain.open') })).toBeInTheDocument(); - expect(header().getByRole('button', { name: en('engine.edit.history') })).toBeInTheDocument(); - expect(header().getByRole('button', { name: en('engine.studio.access.more') })).toBeInTheDocument(); - }); - - it('the breadcrumb, the badge row and the band are gone', async () => { - await renderGuestPortal(); - expect(screen.queryByText('Permission Set')).toBeNull(); - expect(screen.queryByText(en('perm.stat.objectsGranted'))).toBeNull(); - expect(screen.queryByText(en('engine.studio.access.subtitle'))).toBeNull(); - // Exactly one item header: the pillar's own stands down while a set is open. - expect(screen.getAllByTestId('access-item-header')).toHaveLength(1); - }); - - it('five tabs in order, Objects the landing', async () => { - await renderGuestPortal(); - const tabs = within(header().getByRole('navigation')).getAllByRole('button'); - expect(tabs.map((b) => b.textContent)).toEqual([ - en('engine.studio.access.tab.objects'), - en('engine.studio.access.tab.capabilities'), - en('engine.studio.access.tab.rls'), - en('engine.studio.access.tab.tabs'), - en('engine.studio.access.tab.admin'), - ]); - expect(tab('objects')).toHaveAttribute('aria-pressed', 'true'); - expect(screen.getByTestId('perm-tabpanel-objects')).toBeVisible(); - expect(screen.getByTestId('perm-tabpanel-capabilities')).not.toBeVisible(); - expect(screen.getByTestId('perm-tabpanel-facets')).not.toBeVisible(); - }); - - it('each other tab shows its existing section', async () => { - await renderGuestPortal(); - - fireEvent.click(tab('capabilities')); - expect(tab('capabilities')).toHaveAttribute('aria-pressed', 'true'); - expect(screen.getByTestId('perm-tabpanel-objects')).not.toBeVisible(); - expect(within(screen.getByTestId('perm-tabpanel-capabilities')).getByText(en('perm.field.systemCapabilities'))).toBeVisible(); - - for (const [key, help] of [ - ['rls', 'perm.rls.help'], - ['tabs', 'perm.tabs.title'], - ['admin', 'perm.admin.title'], - ] as const) { - fireEvent.click(tab(key)); - const panel = screen.getByTestId(`perm-facet-${key}`); - expect(panel).toBeVisible(); - expect(panel).toHaveAccessibleName(en(help === 'perm.rls.help' ? 'perm.rls.title' : help)); - for (const other of ['rls', 'tabs', 'admin'].filter((k) => k !== key)) { - expect(screen.getByTestId(`perm-facet-${other}`)).not.toBeVisible(); - } - } - expect(within(screen.getByTestId('perm-facet-rls')).getByText(en('perm.rls.help'))).toBeInTheDocument(); - }); - - it('the facet tabs stay mounted while Objects is open', async () => { - await renderGuestPortal(); - for (const key of ['rls', 'tabs', 'admin']) { - expect(screen.getByTestId(`perm-facet-${key}`)).toBeInTheDocument(); - } - }); -}); - -describe('Objects tab — the bulk strip is on every row (objectui#12456, objectstack#34795)', () => { - it('draws on every row at rest, All · Read only · None, then the CRUD arm', async () => { - await renderGuestPortal(); - for (const obj of ['crm_lead', 'crm_account']) { - const strip = screen.getByTestId(`perm-bulk-${obj}`); - expect(within(strip).getAllByRole('button').map((b) => b.textContent)).toEqual([ - en('perm.bulk.all'), - en('perm.bulk.read'), - en('perm.bulk.none'), - en('perm.bulk.crud'), - ]); - } - }); - - it("keyboard focus on a row's first checkbox still marks the row; focus leaving the row clears it", async () => { - await renderGuestPortal(); - const row = screen.getByTestId('perm-row-crm_account'); - const first = within(row).getAllByRole('checkbox')[0]; - act(() => first.focus()); - expect(first).toHaveFocus(); - expect(row).toHaveAttribute('data-active', 'true'); - // The strip's buttons are in the row's tab order. - act(() => within(screen.getByTestId('perm-bulk-crm_account')).getAllByRole('button')[0].focus()); - expect(row).toHaveAttribute('data-active', 'true'); - act(() => within(screen.getByTestId('perm-row-crm_lead')).getAllByRole('checkbox')[0].focus()); - await waitFor(() => expect(row).not.toHaveAttribute('data-active')); - }); - - it('a bulk action writes what it wrote before: CRUD grants the four CRUD cells', async () => { - await renderGuestPortal(); - const row = screen.getByTestId('perm-row-crm_account'); - fireEvent.mouseEnter(row); - fireEvent.click(within(row).getByRole('button', { name: en('perm.bulk.crud') })); - for (const action of ['perm.action.create', 'perm.action.read', 'perm.action.edit', 'perm.action.delete']) { - expect(within(row).getByRole('checkbox', { name: `crm_account ${en(action)}` })).toBeChecked(); - } - expect(within(row).getByRole('checkbox', { name: `crm_account ${en('perm.action.viewAll')}` })).not.toBeChecked(); - await waitFor(() => - expect(header().getByText('2 objects granted · 0 field overrides')).toBeInTheDocument(), - ); - }); - - it('the OWD column is a chip; the toolbar counts the objects', async () => { - await renderGuestPortal(); - const row = screen.getByTestId('perm-row-crm_lead'); - expect(within(row).getByTestId('owd-badge-crm_lead')).toHaveTextContent(en('perm.owd.defaultPrivate')); - expect(screen.getByTestId('perm-object-count')).toHaveTextContent('2 objects'); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessWording-34795.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessWording-34795.test.tsx index b38a3b39e3f..2eb1b23df24 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessWording-34795.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessWording-34795.test.tsx @@ -8,7 +8,8 @@ * (the dismiss door on the accepted row, ADR-0090 D5/D9 unchanged); * • the open set's title is the set's label alone (objectstack#35018: the * app's name is the top bar's, not repeated); the set's machine name is - * the title's tooltip, not page text, and the rail row's too; + * the title's tooltip, not page text (since objectstack#36905 on the + * set's full-screen page, `StudioPermissionSetPage`, the rail gone); * • every object row draws 「全选 · 只读 · 清空」 (and the CRUD arm as a * fourth) without a hover, and each writes what All / R / None / CRUD * wrote before; @@ -94,7 +95,7 @@ vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); import { t } from '../metadata-admin/i18n'; -import { AccessPillar } from './StudioDesignSurface'; +import { StudioPermissionSetPage } from './StudioPermissionSetPage'; window.matchMedia = ((query: string) => ({ matches: false, @@ -128,7 +129,7 @@ async function mountZh(withSuggestion = true) { render( - + , ); @@ -170,16 +171,15 @@ describe('objectstack#34795 — the accepted suggestion reads as one business se }); describe('objectstack#34795 — the open set: title, tooltip, terms', () => { - it('the title reads the set label alone — no app name; the machine name is its tooltip and the rail row tooltip', async () => { + it('the title reads the set label alone — no app name; the machine name is its tooltip', async () => { api.list.mockResolvedValue([ACCEPTED]); await mountZh(); - const title = within(screen.getByTestId('access-item-header')).getByTestId('perm-studio-title'); + const title = within(screen.getByTestId('permission-detail-header')).getByTestId('perm-studio-title'); // objectstack#35018 — the app's name is the top bar's; the title is the set's label, whole. expect(title.textContent).toBe('组织成员'); - expect(screen.getByTestId('access-item-header').textContent).not.toContain('会议纪要'); - // CONTROL: the machine name stays reachable — on the title's tooltip and the rail row's. + expect(screen.getByTestId('permission-detail-header').textContent).not.toContain('会议纪要'); + // CONTROL: the machine name stays reachable — on the title's tooltip. expect(title).toHaveAttribute('title', SET); - expect(screen.getByTestId(`access-rail-set-${SET}`)).toHaveAttribute('title', SET); // The three labels are the line under the title. const note = screen.getByTestId('perm-studio-title-note'); expect(note).toHaveTextContent(zh('engine.studio.access.origin.app')); @@ -189,7 +189,7 @@ describe('objectstack#34795 — the open set: title, tooltip, terms', () => { it('objectstack#35018 — the note and the tab row say it in the builder words: no 包内置, no 本包', async () => { api.list.mockResolvedValue([ACCEPTED]); await mountZh(); - const header = screen.getByTestId('access-item-header'); + const header = screen.getByTestId('permission-detail-header'); expect(within(header).getByTestId('perm-studio-title-note')).toHaveTextContent( `${zh('engine.studio.access.origin.app')}·${zh('perm.badge.default')}`, ); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.aiChipLabel.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.aiChipLabel.test.tsx index 5e7580ec12e..22cbeb74e50 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.aiChipLabel.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.aiChipLabel.test.tsx @@ -110,6 +110,9 @@ vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () // The source loads `@objectstack/lint` lazily; paid here, at collection, not // inside a case's clock (check:test-source-alias). import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; import { StudioDesignSurface } from './StudioDesignSurface'; window.matchMedia = ((query: string) => ({ @@ -189,6 +192,8 @@ function renderStudio(entry = `/studio/${PACKAGE_ID}/interfaces`) { } /> + {/* objectstack#36905 — a permission set opens at its metadata address. */} + } /> , @@ -202,16 +207,18 @@ const agentSurface = () => // item's label too: the chip reads the rail's word and the label, as the Data // rail's 「会议 · 记录」 does — never the type word (`permission` / `flow`) or // the machine name, which stay on the tooltip and in the agent's data. +// objectstack#36905 — a permission set now opens full-screen at its metadata +// address, and keeps its chip there: the agent reads the item off the path. describe('objectstack#35018 — 正在看 on the Access and Automations rails reads a label', () => { it('Access: 「正在看:权限 · 组织成员」, no type word, no machine name', async () => { - renderStudio(`/studio/${PACKAGE_ID}/access?surface=permission:${SET}`); + renderStudio(`/studio/${PACKAGE_ID}/metadata/permission/${SET}?package=${PACKAGE_ID}`); await waitFor(() => expect(chip.surfaceContextLabel).toBe('正在看:权限 · 组织成员'), { timeout: 6000 }); expect(String(chip.surfaceContextLabel)).not.toContain('permission'); expect(String(chip.surfaceContextLabel)).not.toContain(SET); // CONTROL: the identity stays reachable on the tooltip, and the agent's data is the URL's. expect(chip.surfaceContextTitle).toBe(`permission · ${SET}`); expect(JSON.stringify(agentSurface())).toBe( - JSON.stringify({ pillar: 'access', artifact: { type: 'permission', name: SET } }), + JSON.stringify({ pillar: 'metadata', artifact: { type: 'permission', name: SET } }), ); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx index 8ec2e8b67ea..78808d6fd10 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.backToApp-36501.test.tsx @@ -31,6 +31,9 @@ import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; // The surface's reach loads `@objectstack/lint` lazily; pay that load during // collection, not inside a case's clocked window (`check:test-source-alias`). import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; const OWN = 'com.example.sales'; const FLAT_KERNEL = 'sys.env-artifact-cache'; @@ -190,7 +193,7 @@ describe('opened directly, 「‹ Back to app」 lands on the package app\'s fir it('with several published apps, the first, addressed by its name', async () => { srv.apps = [SERVICE_APP, SALES_APP]; - renderAt(`/studio/${OWN}/access`); + renderAt(`/studio/${OWN}/owd`); await waitFor(() => expect(within(header()).getByTestId('studio-back-app-name')).toHaveTextContent('Service desk'), { timeout: 8000, }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.changesCount-11787.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.changesCount-11787.test.tsx index a5077000722..a3bdd58be04 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.changesCount-11787.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.changesCount-11787.test.tsx @@ -62,6 +62,9 @@ vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => nul // The console's preview and authoring code loads `@objectstack/lint` lazily; // warmed here so its first load is paid at import, not inside a test's clock. import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; import { StudioDesignSurface } from './StudioDesignSurface'; import { t } from '../metadata-admin/i18n'; @@ -143,7 +146,7 @@ async function createAppThroughTheDialog() { describe('the Changes count after a draft save (objectui#11787)', () => { it('says a draft is pending from the render the save lands in, and the read it asks for is its own', async () => { render( - + } /> diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDraftBadge-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDraftBadge-12725.test.tsx index 33aa6c664ec..bb967bd4b23 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDraftBadge-12725.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.copilotDraftBadge-12725.test.tsx @@ -124,6 +124,9 @@ import { uiMessagesToChatMessages } from '@object-ui/plugin-chatbot'; // The console's preview and authoring code loads `@objectstack/lint` lazily; // warmed here so its first load is paid at import, not inside a test's clock. import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; import { StudioDesignSurface } from './StudioDesignSurface'; import { subscribeMetadataRefresh } from '../../assistant/assistantBus'; @@ -250,7 +253,7 @@ function LocationProbe(): React.ReactElement { function renderStudio() { return render( - + } /> diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.emptyStates-12514.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.emptyStates-12514.test.tsx index 9f8e4d6b8e9..1301f1c1f1a 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.emptyStates-12514.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.emptyStates-12514.test.tsx @@ -1,22 +1,29 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectui#12514 — the Automations and Access pillars of a package that holds - * no flow, or no permission set, show one centered block in the content - * column: the pillar's icon, one sentence, and a primary button that opens the - * create dialog the rail's "+" opens, through the same handler. + * objectui#12514 — the Automations pillar of a package that holds no flow + * shows one centered block in the content column: the pillar's icon, one + * sentence, and a primary button that opens the create dialog the rail's "+" + * opens, through the same handler. (The Access pillar's block went with the + * pillar, objectstack#36905: an empty package's permission sets are its + * type's empty list.) * * - Automations: no aside while there is nothing to select, and the rail's * empty sentence names the "+" it points at. - * - Access: the rail's empty sentence names the "+" too. * - Read-only: the block's sentence stands alone — no button, no "+", and no * rail sentence pointing at a control that is not there. * - * The REAL `AutomationsPillar` and `AccessPillar`, over a client that lists + * The REAL `AutomationsPillar`, over a client that lists * nothing. */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches a dynamic `import('@objectstack/lint')`; its first load is paid +// here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; @@ -59,7 +66,7 @@ vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPan vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); -import { AccessPillar, AutomationsPillar } from './StudioDesignSurface'; +import { AutomationsPillar } from './StudioDesignSurface'; import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; import { t } from '../metadata-admin/i18n'; @@ -99,14 +106,6 @@ function renderAutomations(readOnly = false) { ); } -function renderAccess(readOnly = false) { - render( - - - , - ); -} - describe('objectui#12514 — Automations with no flow', () => { it('one block in the content column, no aside, and a rail sentence that names its "+"', async () => { renderAutomations(); @@ -145,35 +144,3 @@ describe('objectui#12514 — Automations with no flow', () => { expect(screen.queryByText(t('engine.studio.auto.none', 'en'))).toBeNull(); }); }); - -describe('objectui#12514 — Access with no permission set', () => { - it('one block in the content column, and a rail sentence that names its "+"', async () => { - renderAccess(); - const block = await screen.findByTestId('access-empty', undefined, { timeout: 8000 }); - expect(block).toHaveTextContent(t('engine.studio.access.emptyMain', 'en')); - expect(within(block).getByTestId('access-empty-new')).toHaveTextContent(t('engine.studio.access.new', 'en')); - const rail = screen.getByTestId('studio-rail-access'); - expect(within(rail).getByText(t('engine.studio.access.none', 'en'))).toBeInTheDocument(); - expect(t('engine.studio.access.none', 'en')).toContain('“+”'); - }); - - it('the button opens the dialog the rail’s "+" opens', async () => { - renderAccess(); - fireEvent.click(await screen.findByTestId('access-empty-new', undefined, { timeout: 8000 })); - const fromEmpty = await screen.findByRole('dialog', { name: t('engine.studio.access.new', 'en') }); - fireEvent.keyDown(fromEmpty, { key: 'Escape' }); - expect(screen.queryByRole('dialog')).toBeNull(); - - fireEvent.click(screen.getByTestId('studio-rail-add')); - expect(await screen.findByRole('dialog', { name: t('engine.studio.access.new', 'en') })).toBeInTheDocument(); - }); - - it('read-only: the sentence alone — no button, no "+", no rail pointer', async () => { - renderAccess(true); - const block = await screen.findByTestId('access-empty', undefined, { timeout: 8000 }); - expect(block).toHaveTextContent(t('engine.studio.access.emptyMain', 'en')); - expect(screen.queryByTestId('access-empty-new')).toBeNull(); - expect(screen.queryByTestId('studio-rail-add')).toBeNull(); - expect(screen.queryByText(t('engine.studio.access.none', 'en'))).toBeNull(); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx index eea40c4c4b4..6020aa1c95d 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.metadataArea-28561.test.tsx @@ -398,15 +398,17 @@ describe('⌘K and the header ask before they drop edits the item page holds (ob expect(confirmSpy).not.toHaveBeenCalled(); }); - it('Default sharing picked on the Access pillar remounts the pillar on its overview', async () => { + // objectstack#36905 — a permission set opens full-screen at its metadata address and the + // overview has its own route, so the pick leaves the set's page for the overview's. + it("Default sharing picked on a permission set's page opens the overview at its own route", async () => { itemPage.dirty = false; mockClient.list.mockImplementation(async (type?: string) => type === 'permission' ? [{ name: 'sales_rep', label: 'Sales Rep', _packageId: PACKAGE_ID }] : [], ); try { servePackages(); - renderAt(`/studio/${PACKAGE_ID}/access?surface=permission%3Asales_rep`); - await screen.findByTestId('access-rail-set-sales_rep'); + renderAt(`/studio/${PACKAGE_ID}/metadata/permission/sales_rep?package=${PACKAGE_ID}`); + await screen.findByTestId('studio-permission-set-page'); expect(screen.queryByTestId('owd-overview')).toBeNull(); fireEvent.keyDown(document, { key: 'k', ctrlKey: true }); @@ -414,7 +416,8 @@ describe('⌘K and the header ask before they drop edits the item page holds (ob fireEvent.click(paletteItem('studio-entry owd')!); expect(await screen.findByTestId('owd-overview')).toBeInTheDocument(); - expect(where()).toBe(`/studio/${PACKAGE_ID}/access?surface=owd%3Aoverview`); + expect(where()).toBe(`/studio/${PACKAGE_ID}/owd`); + expect(screen.queryByTestId('studio-permission-set-page')).toBeNull(); expect(overlay()).toBeNull(); expect(confirmSpy).not.toHaveBeenCalled(); } finally { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx index 6c5611a7543..4ec52d0ba6f 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.notFound-26708.test.tsx @@ -23,6 +23,9 @@ import '@testing-library/jest-dom/vitest'; // The source under test reaches `import('@objectstack/lint')`: paid here, at collection, never inside a test's clock. import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react'; import * as React from 'react'; @@ -148,7 +151,7 @@ const menu = () => screen.getByTestId('studio-menu'); const menuLinks = () => within(menu()).getAllByRole('link'); describe('Studio: a package id no package has renders "package not found" (objectstack#26708)', () => { - it.each(['data', 'automations', 'interfaces', 'access'])('%s: not found, no menu, no package actions', async (pillar) => { + it.each(['data', 'automations', 'interfaces', 'owd'])('%s: not found, no menu, no package actions', async (pillar) => { const fetchMock = servePackages(); renderAt(`/studio/${PHANTOM}/${pillar}`); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarNavGuard.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarNavGuard.test.tsx index 484243c5a11..470371fd531 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarNavGuard.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarNavGuard.test.tsx @@ -14,11 +14,10 @@ * • dirty + a menu entry that leaves the pillar → confirm; cancel keeps the * pillar and its edits, * • dirty + 「‹ Back to app」 → same confirm; cancel stays, confirm leaves, - * • dirty OWD overview rows + leaving → same confirm (the pillar folds the - * overview's report into the same bit, objectui#2600 follow-up), - * • dirty + the menu's default-sharing entry, which re-enters the open - * Access pillar on another query (remounting it) → same confirm, once; - * cancel keeps the edit, confirm opens the overview, + * • dirty OWD overview rows + leaving → same confirm (the overview reports + * into the same bit, objectui#2600 follow-up), + * • dirty + the menu's default-sharing entry → same confirm, once; cancel + * keeps the edit, confirm opens the overview, * • clean navigation never prompts, * • a confirmed discard clears the guard (the pillar resets on unmount). * @@ -29,16 +28,25 @@ * window's URL is kept at the router's, as `BrowserRouter` keeps it, because * that guard reads the window's URL to skip a link to the page already shown. * - * Rendered through the real StudioDesignSurface + AccessPillar + - * PermissionMatrixEditPage stack (mocking only data I/O and heavy rail - * siblings), so the dirty report crosses every real seam. + * objectstack#36905 — a permission set opens full-screen at its metadata + * address (`StudioPermissionSetPage` in the area), and the overview on its own + * route (`/studio//owd`); epic decision 12 keeps every departure + * above guarded there. + * + * Rendered through the real StudioDesignSurface + StudioMetadataArea + + * StudioPermissionSetPage + PermissionMatrixEditPage stack (mocking only data + * I/O, the area's other pages and heavy siblings), so the dirty report crosses + * every real seam. */ import '@testing-library/jest-dom/vitest'; // The source under test reaches these through dynamic imports: their first load is paid at collection. import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; let clientImpl: any; @@ -88,6 +96,14 @@ vi.mock('./StudioAiCopilot', () => ({ vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null, })); +// The area's other pages: a type's list is where a menu entry lands. +vi.mock('../metadata-admin/index.js', () => ({ + MetadataDirectoryPage: () =>
, + MetadataDiagnosticsPage: () =>
, + MetadataResourceListPage: () =>
, + MetadataResourceEditPage: () =>
, + MetadataResourceHistoryPage: () =>
, +})); import { t } from '../metadata-admin/i18n'; import { StudioDesignSurface } from './StudioDesignSurface'; @@ -193,32 +209,45 @@ function SearchProbe() { return {useLocation().search}; } -async function renderSurfaceOnAccess() { - window.history.replaceState(null, '', '/studio/app.a/access'); +const SET_ADDRESS = '/studio/app.a/metadata/permission/set_a?package=app.a'; + +async function renderSurfaceAt(url: string) { + window.history.replaceState(null, '', url); render( - + } /> {/* objectstack#36899 — a menu type entry opens that type's area list. */} - } /> + } /> } /> } /> , ); - // First set auto-selects; wait for its matrix row so the whole editor (not - // just the breadcrumb) has loaded before a test flips a cell. - await screen.findByText('a_account'); +} + +/** objectstack#36905 — the set's full-screen page at its metadata address. */ +async function renderSurfaceOnSet() { + await renderSurfaceAt(SET_ADDRESS); + // Wait for its matrix row so the whole editor (not just the header) has + // loaded before a test flips a cell. + await screen.findByText('a_account', undefined, { timeout: 8000 }); +} + +/** objectstack#36905 — the overview's own route. */ +async function renderSurfaceOnOwd() { + await renderSurfaceAt('/studio/app.a/owd'); + await screen.findByTestId('owd-internal-a_account', undefined, { timeout: 8000 }); } /** objectstack#36899 — a left-menu entry: a real router Link. */ const menuEntry = (key: string) => within(screen.getByTestId('studio-menu')).getByTestId(`studio-menu-entry-${key}`); -/** The entry that leaves the Access pillar: the flows' list in the area. */ +/** The entry that leaves the page: the flows' list in the area. */ const leave = () => fireEvent.click(menuEntry('type:flow')); -/** The entry that re-enters the open Access pillar on its default-sharing overview. */ -const reenterOnOwd = () => fireEvent.click(menuEntry('owd')); +/** The default-sharing overview's entry. */ +const openOwd = () => fireEvent.click(menuEntry('owd')); /** The departure is done and nothing is held: a shell departure goes at once. */ async function leftAndGuardCleared(asked: number) { @@ -231,21 +260,14 @@ async function leftAndGuardCleared(asked: number) { } /** - * objectui#11862 — the rail shows each set's machine name as secondary text, so - * an open set's name is on the page more than once. objectui#12456 — the open - * set's api name is its item header's mono chip (the Delegated admin tab, kept - * mounted, lists every set name too), so "the matrix shows set X" is asked of - * that header alone. + * The open set's machine name is its header title's tooltip (the Delegated + * admin tab, kept mounted, lists every set name too), so "the matrix shows set + * X" is asked of that header alone. */ -const inSetHeader = () => within(screen.getByTestId('access-item-header')); -// The header is re-queried on each retry: the pillar's own header stands in -// while no set is open, and the set's header replaces it once the page loads. -const findInSetHeader = (name: string) => waitFor(() => inSetHeader().getByTitle(name)); +const inSetHeader = () => within(screen.getByTestId('permission-detail-header')); -/** Swap the main panel to the (real) OWD overview and edit a row. */ +/** Edit a row of the (real) OWD overview. */ async function dirtyTheOwdOverview() { - fireEvent.click(screen.getByRole('button', { name: 'Who can see which records' })); - await screen.findByTestId('owd-internal-a_account'); const owdPrivate = t('engine.studio.settings.sharingPrivate', 'en-US'); fireEvent.keyDown(screen.getByTestId('owd-internal-a_account'), { key: 'ArrowDown' }); const listbox = await screen.findByRole('listbox'); @@ -269,7 +291,7 @@ const matrixEditSurvived = () => { describe('Studio — unsaved pillar edits guard (#2600)', () => { it('asks before a menu entry leaves the pillar when dirty; cancel keeps the pillar and its edits', async () => { - await renderSurfaceOnAccess(); + await renderSurfaceOnSet(); dirtyTheMatrix(); confirmSpy.mockReturnValueOnce(false); @@ -288,7 +310,7 @@ describe('Studio — unsaved pillar edits guard (#2600)', () => { }); it('gates leaving on dirty OWD overview rows (#2600 follow-up)', async () => { - await renderSurfaceOnAccess(); + await renderSurfaceOnOwd(); const owdPrivate = await dirtyTheOwdOverview(); confirmSpy.mockReturnValueOnce(false); @@ -304,40 +326,39 @@ describe('Studio — unsaved pillar edits guard (#2600)', () => { }); it('leaves without prompting when clean', async () => { - await renderSurfaceOnAccess(); + await renderSurfaceOnSet(); leave(); expect(confirmSpy).not.toHaveBeenCalled(); await screen.findByTestId('area-landed'); }); - it('the default-sharing entry re-enters the open pillar: dirty, it asks once; cancel keeps the edit, confirm opens the overview', async () => { - await renderSurfaceOnAccess(); + it('the default-sharing entry, from a dirty set: it asks once; cancel keeps the edit, confirm opens the overview', async () => { + await renderSurfaceOnSet(); dirtyTheMatrix(); confirmSpy.mockReturnValueOnce(false); - reenterOnOwd(); + openOwd(); expect(confirmSpy).toHaveBeenCalledTimes(1); expect(inSetHeader().getByTitle('set_a')).toBeInTheDocument(); matrixEditSurvived(); confirmSpy.mockReturnValueOnce(true); - reenterOnOwd(); + openOwd(); expect(confirmSpy).toHaveBeenCalledTimes(2); - await screen.findByTestId('owd-internal-a_account'); + await screen.findByTestId('owd-internal-a_account', undefined, { timeout: 8000 }); expect(menuEntry('owd')).toHaveAttribute('aria-current', 'page'); }); it('CONTROL: clean, the default-sharing entry opens the overview without asking', async () => { - await renderSurfaceOnAccess(); - // As an author's click comes after it: the pillar has mirrored its open set. - await waitFor(() => expect(decodeURIComponent(screen.getByTestId('router-search').textContent ?? '')).toContain('permission:set_a')); - reenterOnOwd(); - await screen.findByTestId('owd-internal-a_account'); + await renderSurfaceOnSet(); + openOwd(); + await screen.findByTestId('owd-internal-a_account', undefined, { timeout: 8000 }); + expect(screen.getByTestId('router-search').textContent).toBe(''); expect(confirmSpy).not.toHaveBeenCalled(); }); it('gates 「‹ Back to app」; cancel stays, confirm leaves Studio (objectstack#36501)', async () => { - await renderSurfaceOnAccess(); + await renderSurfaceOnSet(); dirtyTheMatrix(); confirmSpy.mockReturnValueOnce(false); @@ -352,7 +373,7 @@ describe('Studio — unsaved pillar edits guard (#2600)', () => { }); it('never prompts a clean 「‹ Back to app」', async () => { - await renderSurfaceOnAccess(); + await renderSurfaceOnSet(); fireEvent.click(screen.getByTestId('studio-back-to-app')); @@ -363,7 +384,7 @@ describe('Studio — unsaved pillar edits guard (#2600)', () => { describe('a dirty pillar registers with the shell seam (objectui#13253)', () => { it('dirty OWD rows (only the surface registers them): a shell departure asks once; Cancel keeps the edit', async () => { - await renderSurfaceOnAccess(); + await renderSurfaceOnOwd(); const owdPrivate = await dirtyTheOwdOverview(); confirmSpy.mockReturnValueOnce(false); @@ -376,7 +397,7 @@ describe('a dirty pillar registers with the shell seam (objectui#13253)', () => }); it('a dirty matrix: a shell departure asks once, though the matrix and the surface both register', async () => { - await renderSurfaceOnAccess(); + await renderSurfaceOnSet(); dirtyTheMatrix(); confirmSpy.mockReturnValueOnce(true); @@ -387,7 +408,7 @@ describe('a dirty pillar registers with the shell seam (objectui#13253)', () => }); it('CONTROL: a clean pillar registers nothing — a shell departure goes at once', async () => { - await renderSurfaceOnAccess(); + await renderSurfaceOnSet(); const go = vi.fn(); confirmUnsavedLeave(go); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarsClaimSlot-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarsClaimSlot-12725.test.tsx index 23a56a167e2..ec2f06720c4 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarsClaimSlot-12725.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.pillarsClaimSlot-12725.test.tsx @@ -19,7 +19,8 @@ * - While 属性 shows, the copilot strip stays at the slot's foot. * - A hidden slot unfolds on a new selection (objectstack#26737); hidden again * over the same selection, it stays hidden. - * - CONTROL: the Access pillar claims nothing — the slot shows the copilot + * - CONTROL: the sharing overview (objectstack#36905; the Access pillar before + * it) claims nothing — the slot shows the copilot * alone; the Interfaces pillar's own pins live in `rightSlot-12725`. * * The copilot, the flow canvas and both inspectors are stubs: the canvas @@ -116,6 +117,9 @@ vi.mock('./StudioAiCopilot', () => ({ // The source loads `@objectstack/lint` lazily; paid here, at collection, not // inside a case's clock (check:test-source-alias). import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; import { StudioDesignSurface } from './StudioDesignSurface'; import { t } from '../metadata-admin/i18n'; import { registerMetadataPreview } from '../metadata-admin/preview-registry'; @@ -427,8 +431,8 @@ describe('Automations: the Configuration is in the right slot (objectui#12725)', }); describe('CONTROL — a pillar that claims nothing (objectui#12725)', () => { - it('Access keeps its own layout: the slot shows the copilot alone, with no properties half', async () => { - renderAt('access'); + it('the sharing overview keeps its own layout: the slot shows the copilot alone, with no properties half', async () => { + renderAt('owd'); await waitFor(() => expect(slot()).toHaveAttribute('data-mode', 'copilot')); expect(within(slot()).queryAllByRole('tab')).toHaveLength(0); expect(slotProps()).toBeEmptyDOMElement(); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.publishPosture-12517.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.publishPosture-12517.test.tsx index 6b9f89304ed..f1435dcb67f 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.publishPosture-12517.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.publishPosture-12517.test.tsx @@ -67,6 +67,9 @@ vi.mock('../../preview/DraftChangesPanel', () => ({ // The console's preview and authoring code loads `@objectstack/lint` lazily; // warmed here so its first load is paid at import, not inside a test's clock. import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; import { StudioDesignSurface } from './StudioDesignSurface'; import { t } from '../metadata-admin/i18n'; @@ -116,7 +119,7 @@ afterEach(() => { function renderSurface() { render( - + } /> diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyPosture-12453.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyPosture-12453.test.tsx index 70407670da3..3bfad306c6e 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyPosture-12453.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyPosture-12453.test.tsx @@ -18,6 +18,9 @@ import '@testing-library/jest-dom/vitest'; // The surface's reach loads `@objectstack/lint` lazily; pay that load during // collection, not inside a case's clocked window (`check:test-source-alias`). import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, render, screen, waitFor } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; @@ -61,7 +64,8 @@ import { StudioDesignSurface } from './StudioDesignSurface'; import { t } from '../metadata-admin/i18n'; const answer = (body: unknown) => ({ ok: true, status: 200, json: async () => body }); -const PILLARS = ['data', 'automations', 'interfaces', 'access'] as const; +// objectstack#36905 — the sharing overview's own page took the Access pillar's place here. +const PILLARS = ['data', 'automations', 'interfaces', 'owd'] as const; const READ_ONLY = t('engine.studio.pkg.readonly', 'en'); function servePackage(writable: boolean) { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyWording-11781.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyWording-11781.test.tsx index 284268cbb25..de667c7a6f4 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyWording-11781.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.readOnlyWording-11781.test.tsx @@ -2,7 +2,8 @@ /** * objectui#11781 — a read-only package says it is read-only, in the Data - * pillar's Form view and in the Access pillar's banner. + * pillar's Form view (and in the Access banner, pinned now on the permission + * set's page, objectstack#36905). * * Measured on the showcase (a source-loaded, read-only package) in a Studio * browser pass: the Form view still read "Draft layout" and "Drag to reorder / @@ -16,6 +17,12 @@ */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches a dynamic `import('@objectstack/lint')`; its first load is paid +// here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; import * as React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { render, screen, fireEvent, cleanup } from '@testing-library/react'; @@ -62,7 +69,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); -import { AccessPillar, DataPillar } from './StudioDesignSurface'; +import { DataPillar } from './StudioDesignSurface'; import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; import { t, tFormat } from '../metadata-admin/i18n'; @@ -139,33 +146,5 @@ describe('Data pillar Form view — a read-only package reads as read-only (obje }); }); -describe('Access pillar banner — a read-only package saves no draft (objectui#11781)', () => { - function renderAccess(readOnly: boolean) { - render( - - - , - ); - } - - // objectui#12453 — the read-only note retires; its sentence is the header - // link's title. - it('read-only: says read-only, not "saved as draft"', async () => { - renderAccess(true); - - const link = await screen.findByTestId('studio-readonly-link'); - expect(link).toHaveAttribute('title', row('engine.studio.access.bannerTitleReadOnly')); - expect(screen.queryByText(absent('engine.studio.access.banner'))).toBeNull(); - }); - - it('CONTROL — writable: still says its edits save as a draft', async () => { - renderAccess(false); - - // objectui#12611 — the sentence is the status chip's tooltip and its - // accessible description (the objectui#12303 pattern), no longer a `title`. - const banner = await screen.findByText(row('engine.studio.access.banner')); - const chip = banner.closest('[data-testid="studio-item-status"]'); - expect(chip).toHaveAccessibleDescription(row('engine.studio.access.bannerTitle')); - expect(screen.queryByTestId('studio-readonly-link')).toBeNull(); - }); -}); +// objectstack#36905 — the Access pillar's banner pins moved with the banner to the permission +// set's full-screen page (`StudioPermissionSetPage.fullScreen-36905.test.tsx`). diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.rightSlot-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.rightSlot-12725.test.tsx index d5c377c2aa1..73e815abd01 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.rightSlot-12725.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.rightSlot-12725.test.tsx @@ -14,7 +14,7 @@ * - The canvas has no 画布 / 源码 / 属性 tabs: one status line, and the item's * definition opens from its ⋯ menu. * - The pillar names are visible from 1024 px (`lg`), icons below. - * - CONTROLS: a pillar that claims nothing (Access) gets the copilot alone; no + * - CONTROLS: a page that claims nothing (the sharing overview) gets the copilot alone; no * copilot served → the properties alone; an injected `aiSlot` (the cloud * seam) keeps the classic layout with no slot. * @@ -87,6 +87,9 @@ vi.mock('./StudioAiCopilot', () => ({ // The source loads `@objectstack/lint` lazily; paid here, at collection, not // inside a case's clock (check:test-source-alias). import '@objectstack/lint'; +// objectstack#36900 — the surface mounts the command palette, which reaches the +// record preview's `lazy()` detail entry: its first load is paid at collection too. +import '@object-ui/plugin-detail'; import { StudioDesignSurface } from './StudioDesignSurface'; import { t } from '../metadata-admin/i18n'; import { registerMetadataPreview } from '../metadata-admin/preview-registry'; @@ -171,11 +174,12 @@ describe('Studio right slot — controls (objectui#12725)', () => { }); // objectui#12725 phase 2 — Data and Automations now claim the slot, so the - // pillar that claims nothing is Access (its panels are in the main column - // and in dialogs; it has no properties aside). The Data pillar with nothing - // selected claims nothing either: `pillarsClaimSlot-12725`. - it('a pillar that claims nothing gets the copilot alone: a title, no switch, no strip', async () => { - renderAt('access'); + // page that claims nothing was Access; objectstack#36905 — it is the sharing + // overview's own page now (one table in the main column, no properties + // aside). The Data pillar with nothing selected claims nothing either: + // `pillarsClaimSlot-12725`. + it('a page that claims nothing gets the copilot alone: a title, no switch, no strip', async () => { + renderAt('owd'); await waitFor(() => expect(slot()).toHaveAttribute('data-mode', 'copilot')); expect(within(slot()).queryAllByRole('tab')).toHaveLength(0); expect(within(slot()).getByTestId('studio-slot-title')).toHaveTextContent(t('engine.studio.aiCopilot', 'en')); @@ -192,9 +196,9 @@ describe('Studio right slot — controls (objectui#12725)', () => { // measures, and it says whether the slot squeezes it. describe('Studio right slot — the rails read whether it squeezes the pillars (objectstack#35061)', () => { - it('a pillar with no slot to show (Access, no copilot) keeps its host closed', async () => { + it('a page with no slot to show (the sharing overview, no copilot) keeps its host closed', async () => { copilot.available = false; - renderAt('access'); + renderAt('owd'); await screen.findByTestId('studio-shell-header'); await act(async () => {}); expect(slot()).not.toBeVisible(); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx index 09a8f70dd38..f0f5e28568a 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx @@ -77,7 +77,6 @@ import { type StudioSavedDraft, } from './StudioPillarKit.js'; import { AutomationsPillar } from './AutomationsPillar.js'; -import { AccessPillar } from './AccessPillar.js'; import { DataPillar, renderStudioGridList } from './DataPillar.js'; import { cn, @@ -134,6 +133,8 @@ import { import { STUDIO_METADATA_AREA, isStudioAllPackagesScope } from './metadataArea.js'; import { StudioMenu, StudioMenuDataProvider, StudioMenuProvider, StudioMenuTrigger } from './StudioMenu.js'; import { StudioMetadataArea } from './StudioMetadataArea.js'; +import { StudioOwdOverviewPage } from './StudioOwdOverviewPage.js'; +import { AccessPillarLanding } from './accessPillarLanding.js'; import { useMetadataRefreshNonce } from './useMetadataRefreshNonce.js'; import { type SurfaceTarget, @@ -173,7 +174,7 @@ import { type DraftPublishOptions, } from '../../preview/DraftChangesPanel.js'; import { toast } from 'sonner'; -import { studioPillarItemAddress, studioPillarPath } from './studioAddress.js'; +import { STUDIO_OWD_SECTION, studioPillarItemAddress, studioPillarPath } from './studioAddress.js'; /** The batch door's `backfillApplied` receipt, by reference to what the client returns (objectui#12929). */ type PublishBackfillReceipt = NonNullable< @@ -1589,6 +1590,17 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re publishNonce={publishNonce} onDraftSaved={onDraftSaved} publishRefusalFor={publishRefusalFor} + onSurfaceLabelChange={setSurfaceLabel} + /> + ) : tab === STUDIO_OWD_SECTION ? ( + // objectstack#36905 (decision 11) — the organization-wide default + // sharing overview's own route; its unsaved rows gate the header. + ) : !pillarKnown ? ( ) : ( - // objectstack#28573 — keyed by package like its siblings: "New - // similar" opens the copy in ANOTHER package's Access pillar - // (the base's `.custom`), and that route keeps this element - // mounted. Unkeyed, the open set, the rail and the `?surface=` - // capture stayed the base's. - )} @@ -1747,8 +1754,9 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re // objectstack#29988 — the Automations rail's flow helpers moved to their own module; re-exported for their pins. export { FlowStatusDot, type NewFlowTrigger }; -// objectstack#36893 — the Automations and Access pillars moved to their own modules; re-exported for their pins. -export { AutomationsPillar, AccessPillar }; +// objectstack#36893 — the Automations pillar moved to its own module; re-exported for its pins. +// objectstack#36905 — the Access pillar is gone: its addresses redirect (`accessPillarRedirect.ts`). +export { AutomationsPillar }; // objectstack#36893 — the Data pillar moved to its own module; re-exported for its pins. export { DataPillar, renderStudioGridList }; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioItemHeader.statusPlace-12524.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioItemHeader.statusPlace-12524.test.tsx index 924c51a9503..c1b944df0df 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioItemHeader.statusPlace-12524.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioItemHeader.statusPlace-12524.test.tsx @@ -17,8 +17,9 @@ * the fourth until objectstack#36502 retired that pillar.) * * The REAL pillars against one server double that serves a pending draft - * for the open object and the open flow. Access has no - * item-level draft: its writable "saved as draft" note is the pillar's status. + * for the open object and the open flow. Access (since objectstack#36905 the + * permission set's full-screen page) has no item-level draft: its writable + * "saved as draft" note is the page's status. * * Pinned: * - with a draft, the chip in all three headers is a child of the header's @@ -114,7 +115,8 @@ vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () // The source under test reaches a dynamic import of `@objectstack/lint`: its first // load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). import '@objectstack/lint'; -import { AccessPillar, AutomationsPillar, DataPillar } from './StudioDesignSurface'; +import { AutomationsPillar, DataPillar } from './StudioDesignSurface'; +import { StudioPermissionSetPage } from './StudioPermissionSetPage'; import '../../services/builtinComponents.js'; import { t } from '../metadata-admin/i18n'; import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; @@ -190,9 +192,10 @@ const CASES: PillarCase[] = [ }, }, { + // objectstack#36905 — a permission set's full-screen page took the Access pillar's place. pillar: 'Access', - testId: 'access-item-header', - element: (readOnly) => , + testId: 'permission-detail-header', + element: (readOnly) => , settled: async (header) => { await within(header).findByRole('button', { name: en('engine.studio.access.explain.open') }, { timeout: 8000 }); }, @@ -271,7 +274,10 @@ describe('the status chip sits in the same place in every pillar’s item header expect(within(header).queryByTestId('studio-item-status')).toBeNull(); const link = within(header).getByTestId('studio-readonly-link'); const row = titleRow(header); - expect(link.parentElement).toBe(row.lastElementChild); - expect(link.parentElement).toHaveClass('ml-auto'); + // A direct child of the page's primary action group, the group a direct + // child of the right-aligned actions slot: not merely somewhere inside it. + const slot = row.lastElementChild; + expect(slot).toHaveClass('ml-auto'); + expect(link.parentElement!.parentElement).toBe(slot); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.routes-28561.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.routes-28561.test.tsx index cfde5f18fb6..4462c4d476f 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.routes-28561.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.routes-28561.test.tsx @@ -62,6 +62,15 @@ vi.mock('./StudioBundleItemEditor.js', () => ({ ), })); +/** objectstack#36905 — the permission set's full-screen page, a stub printing what the area handed it. */ +vi.mock('./StudioPermissionSetPage.js', () => ({ + StudioPermissionSetPage: ({ packageId, name, readOnly }: { packageId: string; name: string; readOnly?: boolean }) => ( +
+ +
+ ), +})); + /** `GET /api/v1/packages` as the listed manifests read it: one writable, one read-only, one kernel. */ let listed: Map }>; let listFails = false; @@ -287,7 +296,6 @@ describe('a pillar type opened from the area opens its pillar', () => { for (const [type, pillar] of [ ['object', 'data'], ['flow', 'automations'], - ['permission', 'access'], ] as const) { it(`${type} → ${pillar}, with \`?surface=\``, async () => { mount(`/studio/${WRITABLE}/metadata/${type}/item_1?package=${WRITABLE}`); @@ -338,6 +346,41 @@ describe('a pillar type opened from the area opens its pillar', () => { }); }); +describe('a permission set opens its matrix full-screen at its metadata address (objectstack#36905)', () => { + const item = () => JSON.parse(screen.getByTestId('permission-page').getAttribute('data-item') ?? 'null'); + + it('on a writable package, in place: no pillar', async () => { + mount(`/studio/${WRITABLE}/metadata/permission/sales_rep?package=${WRITABLE}`); + expect((await page()).page).toBe('permission-page'); + expect(item()).toEqual({ packageId: WRITABLE, name: 'sales_rep', readOnly: false }); + expect(where()).toBe(`/studio/${WRITABLE}/metadata/permission/sales_rep?package=${WRITABLE}`); + expect(screen.queryByTestId('pillar')).toBeNull(); + }); + + it('on a read-only package, under its gate', async () => { + mount(`/studio/${READ_ONLY}/metadata/permission/hr_viewer?package=${READ_ONLY}`); + expect((await page()).page).toBe('permission-page'); + expect(item()).toEqual({ packageId: READ_ONLY, name: 'hr_viewer', readOnly: true }); + }); + + it('CONTROL: the cross-package leg keeps the generic page (the matrix\'s environment presentation)', async () => { + mount('/studio/~all/metadata/permission/admin_full_access?scope=environment'); + expect((await page()).page).toBe('item'); + expect(screen.queryByTestId('permission-page')).toBeNull(); + }); + + it('its old history address opens the page\'s History tab; the cross-package leg keeps the standalone page', async () => { + // As `builtinComponents` registers it: the matrix is the type's own editor. + registerMetadataResource({ type: 'permission', EditPage: () => null }); + mount(`/studio/${WRITABLE}/metadata/permission/sales_rep/history?package=${WRITABLE}`); + expect((await page()).page).toBe('permission-page'); + expect(where()).toBe(`/studio/${WRITABLE}/metadata/permission/sales_rep?package=${WRITABLE}&tab=history`); + cleanup(); + mount('/studio/~all/metadata/permission/admin_full_access/history?scope=environment'); + expect((await page()).page).toBe('history'); + }); +}); + describe('an email template or a translation opens the form editor (objectstack#28569)', () => { const item = () => JSON.parse(screen.getByTestId('form-editor').getAttribute('data-item') ?? 'null'); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx index 59360eedffe..c5e8291982d 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.tsx @@ -13,10 +13,12 @@ * /_diagnostics diagnostics * /:type a type's list * /:type/new create (a writable package only) - * /:type/:name the generic item page, the item's pillar, or - * the form editor of an email template or a + * /:type/:name the generic item page, the item's pillar, the + * form editor of an email template or a * translation (`StudioBundleItemEditor`, #28569), - * and of a read-only package's dataset (#30064) + * and of a read-only package's dataset (#30064), + * or a permission set's full-screen matrix + * (`StudioPermissionSetPage`, #36905) * /:type/:name/history the item's history: its History tab * (`?tab=history`), the old address redirected; * the history page for a type with an editor of @@ -45,16 +47,19 @@ import { t, useMetadataLocale } from '../metadata-admin/i18n.js'; import { fetchListedPackageManifests } from './packages-io.js'; import { STUDIO_ALL_PACKAGES_SEGMENT, + areaItemOpensDesignerPage, areaItemOpensFormEditor, areaItemPillarPath, areaLocationRedirect, studioMetadataAreaPath, } from './metadataArea.js'; import { StudioBundleItemEditor } from './StudioBundleItemEditor.js'; +import { StudioPermissionSetPage } from './StudioPermissionSetPage.js'; import { BUNDLE_MEMBER_PARAM, getMetadataResource } from '../metadata-admin/registry.js'; import { ITEM_TOOL_TAB_PARAM } from '../item-tools/ItemToolTabs.js'; import type { StudioBaseCustomization } from './StudioDesignSurface.js'; import type { StudioRefusal } from './metadataError.js'; +import type { StudioSurfaceLabel } from './StudioAiCopilot.js'; /* * The pages load with the area, through the specifier `AppContent` loads them @@ -130,6 +135,8 @@ interface AreaEditorProps { publishNonce: number; onDraftSaved?: (saved?: { type: string; name: string }) => void; publishRefusalFor?: (type: string, name: string) => StudioRefusal | null; + /** objectstack#36905 — a designer page's open item label, for the copilot's chip. */ + onSurfaceLabelChange?: (surface: StudioSurfaceLabel | null) => void; } /** @@ -168,6 +175,19 @@ function AreaItemOpen({ return { formEditor: false, pillarPath: areaItemPillarPath({ ...at, name }) }; }); if (opens.pillarPath) return ; + // objectstack#36905 — a permission set opens its matrix full-screen here. + if (host?.packageId && areaItemOpensDesignerPage({ packageId: host.packageId, type })) { + return ( + editor.onDraftSaved?.({ type, name }) : undefined} + onSurfaceLabelChange={editor.onSurfaceLabelChange} + /> + ); + } if (opens.formEditor && host?.packageId) { return ( (); const { pathname, search } = useLocation(); const host = useMetadataAreaHost(); const params = new URLSearchParams(search); - const ownEditor = !!getMetadataResource(type)?.EditPage; + const designerPage = areaItemOpensDesignerPage({ packageId: host?.packageId ?? null, type }); + const ownEditor = !designerPage && !!getMetadataResource(type)?.EditPage; // An item a pillar's designer opens has no tab row yet (its tabs are the // designers' cards): its history keeps the standalone page too. const pillarItem = areaItemPillarPath({ packageId: host?.packageId ?? null, type, name, search: params }) !== null; @@ -295,6 +318,11 @@ export interface StudioMetadataAreaProps { * at the item it refused. */ publishRefusalFor?: (type: string, name: string) => StudioRefusal | null; + /** + * objectstack#36905 — told the open designer page's item label (the + * permission set's), for the copilot's chip, as a pillar tells it. + */ + onSurfaceLabelChange?: (surface: StudioSurfaceLabel | null) => void; } export function StudioMetadataArea({ @@ -303,6 +331,7 @@ export function StudioMetadataArea({ publishNonce = 0, onDraftSaved, publishRefusalFor, + onSurfaceLabelChange, }: StudioMetadataAreaProps): React.ReactElement { const { pathname, search } = useLocation(); const locale = useMetadataLocale(); @@ -321,7 +350,7 @@ export function StudioMetadataArea({ () => ({ packageId, readOnly, basePath, ...(pairCreate ? { pairCreate } : {}) }), [packageId, readOnly, basePath, pairCreate], ); - const editor: AreaEditorProps = { customization, publishNonce, onDraftSaved, publishRefusalFor }; + const editor: AreaEditorProps = { customization, publishNonce, onDraftSaved, publishRefusalFor, onSurfaceLabelChange }; // The query names the leg (`areaLocationRedirect`). Settled before any page // mounts, so no page reads a scope the URL is about to change. diff --git a/ui/packages/app-shell/src/views/studio-design/StudioOwdOverviewPage.tsx b/ui/packages/app-shell/src/views/studio-design/StudioOwdOverviewPage.tsx new file mode 100644 index 00000000000..393a17672c0 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/StudioOwdOverviewPage.tsx @@ -0,0 +1,88 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A package's organization-wide default sharing overview, on its own route + * (objectstack#36905, Studio redesign epic #36890 decision 11): + * `/studio//owd`, the Access group's entry in the left menu. Before, + * it was the Access pillar's pinned rail row (`?surface=owd:overview`), which + * now redirects here (`accessPillarRedirect.ts`). + * + * Not a metadata item: one table of every object the package owns, each row + * its record visibility (`PackageOwdOverviewPanel`, unchanged). A permission + * set's per-object visibility badge opens it on that object (`?object=`). + * + * Save is the Studio top bar's (objectstack#36511); the panel's unsaved rows + * are reported to the surface (`onDirtyChange`), whose leave guard asks before + * the menu, a reload or a tab close drops them (decision 12). + */ + +import * as React from 'react'; +import { useSearchParams } from 'react-router-dom'; +import { ShieldCheck, ShieldQuestion } from 'lucide-react'; +import { AccessExplainPanel } from '../metadata-admin/AccessExplainPanel.js'; +import { useMetadataClient } from '../metadata-admin/useMetadata.js'; +import { t, useMetadataLocale } from '../metadata-admin/i18n.js'; +import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel.js'; +import { StudioItemHeader } from './StudioItemHeader.js'; +import { StudioReadOnlyLink } from './StudioPillarKit.js'; +import { STUDIO_OWD_OBJECT_PARAM } from './studioAddress.js'; + +export interface StudioOwdOverviewPageProps { + packageId: string; + publishNonce?: number; + /** The package is read-only: the table shows its badges only. */ + readOnly?: boolean; + /** Mirrors the table's unsaved rows up to the surface's leave guard; `false` on unmount. */ + onDirtyChange?: (dirty: boolean) => void; +} + +export function StudioOwdOverviewPage({ + packageId, + publishNonce, + readOnly = false, + onDirtyChange, +}: StudioOwdOverviewPageProps): React.ReactElement { + const client = useMetadataClient(); + const locale = useMetadataLocale(); + const [searchParams] = useSearchParams(); + const highlight = searchParams.get(STUDIO_OWD_OBJECT_PARAM); + const [explainOpen, setExplainOpen] = React.useState(false); + return ( +
+ + {readOnly && ( + + )} + + + } + /> +
+ +
+ +
+ ); +} diff --git a/ui/packages/app-shell/src/views/studio-design/StudioPaletteGroups.surfaceScope-36900.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioPaletteGroups.surfaceScope-36900.test.tsx index 1afddd4d038..5b25536bda0 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioPaletteGroups.surfaceScope-36900.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioPaletteGroups.surfaceScope-36900.test.tsx @@ -300,7 +300,7 @@ describe("on a package, the palette lists the left menu and the package's items '/studio/com.acme.crm/data?surface=object%3Acrm_account', ); expect(await openedBy(`studio-item permission ${PKG} sales_rep`)).toBe( - '/studio/com.acme.crm/access?surface=permission%3Asales_rep', + '/studio/com.acme.crm/metadata/permission/sales_rep?package=com.acme.crm', ); expect(await openedBy(`studio-item dashboard ${PKG} crm_pipeline`)).toBe( '/studio/com.acme.crm/metadata/dashboard/crm_pipeline?package=com.acme.crm', @@ -313,7 +313,7 @@ describe("on a package, the palette lists the left menu and the package's items it('opens a menu entry where the menu entry goes, and the palette closes', async () => { expect(await openedBy('studio-entry type:hook')).toBe('/studio/com.acme.crm/metadata/hook?package=com.acme.crm'); expect(await openedBy('studio-entry orgFlows')).toBe('/studio/~org/automations'); - expect(await openedBy('studio-entry owd')).toBe('/studio/com.acme.crm/access?surface=owd%3Aoverview'); + expect(await openedBy('studio-entry owd')).toBe('/studio/com.acme.crm/owd'); expect(await openedBy('studio-entry diagnostics')).toBe('/studio/com.acme.crm/metadata/_diagnostics'); mount(PKG); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioPermissionSetPage.fullScreen-36905.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioPermissionSetPage.fullScreen-36905.test.tsx new file mode 100644 index 00000000000..8cf799f6c8b --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/StudioPermissionSetPage.fullScreen-36905.test.tsx @@ -0,0 +1,551 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36905 — a permission set's full-screen page at its metadata + * address: the REAL `StudioPermissionSetPage` and `PermissionMatrixEditPage`, + * routed as the "All metadata" area routes an item. + * + * - the header is the full-screen detail's (× back to the list), and the + * matrix draws no header of its own; + * - the tab row is the five sections, then References, History and Source; + * a tool tab is addressable (`?tab=`) and keeps the matrix mounted; + * - × opens the list of sets with the list's context; + * - "New similar" sits in ⋯ on a read-only base, and the copy opens at its + * own metadata address with the strip saying where it landed; + * - the draft discard drops this set's draft at its package; a declined + * question discards nothing, a never-published set goes back to the list, + * a read-only package offers no discard, and an unanswered read of the + * package's sets never counts a set as never published; + * - the matrix's sections behave as they did in the Access pillar + * (objectui#12456): five tabs, Objects the landing, each other tab its + * section, the facet panels kept mounted for the Save gate, the bulk strip + * on every row with keyboard focus marking the row, CRUD granting the four + * cells, and the sharing chip and the object count; + * - the sharing chip leaves a dirty matrix only after the unsaved-edits + * question: declined, the page stays on the set with the edit; confirmed, + * it opens the overview; a clean matrix asks nothing (CONTROL). + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { MemoryRouter, Route, Routes, useLocation, useParams } from 'react-router-dom'; +// The matrix reaches `@objectstack/lint`'s dynamic imports; their first load is +// paid here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; + +const BASE_PKG = 'hotcrm'; +const CUSTOM_PKG = 'hotcrm.custom'; +const SET = 'hotcrm_sales_rep'; +const COPY_NAME = 'my_sales_rep'; +const BODY = { name: SET, label: 'Sales rep', objects: { crm_lead: { allowRead: true } }, fields: {} }; + +let clientImpl: ReturnType; +vi.mock('../metadata-admin/useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => clientImpl, + useMetadataTypes: () => ({ + loading: false, + error: null, + entries: [{ type: 'permission', label: 'Permission', allowEnvironmentOverlay: false, allowRuntimeCreate: true }], + }), +})); +vi.mock('../../hooks/useCanAuthorMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useCanAuthorMetadata: () => true, + useCanReadAuthoringTrail: () => true, +})); +vi.mock('../metadata-admin/catalog-scope', async (importOriginal) => ({ + ...(await importOriginal>()), + useWalledCatalogReadOnly: () => false, +})); +// The tool panels are `ItemToolTabs`' own (pinned beside it): here, which one opened. +vi.mock('../item-tools/ItemToolTabs.js', async (importOriginal) => ({ + ...(await importOriginal>()), + ItemToolTabPanel: ({ tab }: { tab: string }) =>
, +})); +vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); +vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); +vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); + +import { t, tFormat } from '../metadata-admin/i18n'; +import { StudioPermissionSetPage } from './StudioPermissionSetPage'; + +window.matchMedia = ((query: string) => ({ + matches: false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, +})) as unknown as typeof window.matchMedia; + +const en = (key: string) => t(key, 'en'); + +/** The set's pending draft as the strict draft read serves it, with who wrote it. */ +function draftOf(by: 'copilot' | 'mcp' | 'studio') { + return { + type: 'permission', + name: SET, + item: { ...BODY, label: 'Sales rep (AI)' }, + draftChanges: [{ path: ['label'], by, actor: 'u1', at: '2026-11-24T10:00:00.000Z' }], + }; +} + +function makeClient(drafts: string[] = [], draft: ReturnType | null = null) { + return { + save: vi.fn(async (_t: string, _n: string, body: Record) => body), + reset: vi.fn(async () => ({})), + withPreviewDrafts() { + return this; + }, + list: vi.fn(async (type: string) => { + if (type === 'object') { + return [ + { name: 'crm_lead', label: 'Lead' }, + { name: 'crm_account', label: 'Account' }, + ]; + } + return type === 'permission' ? [{ name: SET, label: 'Sales rep' }] : []; + }), + listDrafts: vi.fn(async () => drafts.map((name) => ({ name }))), + layered: vi.fn(async () => ({ effective: BODY, code: null, overlay: null, overlayScope: null })), + getDraft: vi.fn(async () => draft), + get: vi.fn(async () => ({ fields: [] })), + }; +} + +let doorAnswer: { status: number; body: unknown }; +function stubFetch() { + vi.stubGlobal( + 'fetch', + vi.fn(async () => + new Response(JSON.stringify(doorAnswer.body), { + status: doorAnswer.status, + headers: { 'Content-Type': 'application/json' }, + }), + ), + ); +} + +/** The area's item route: the page keyed per item, as `AreaItem` keys it. */ +function ItemRoute() { + const { packageId = '', name = '' } = useParams<{ packageId: string; name: string }>(); + return ( + + ); +} + +function Where() { + const { pathname, search } = useLocation(); + return {pathname + search}; +} + +function mount(pkg: string, query = '') { + render( + + + + } /> + } /> + + , + ); +} + +const where = () => screen.getByTestId('where').textContent ?? ''; +/** How many times the permission sets were listed: the page re-reads them after a discard that stays. */ +const setsReads = () => clientImpl.list.mock.calls.filter(([type]) => type === 'permission').length; +const title = () => screen.findByTestId('studio-detail-title', undefined, { timeout: 8000 }); + +beforeEach(() => { + // `?tab=` is read from and written to the document's address (`useItemToolTab`). + window.history.replaceState(null, '', '/'); + clientImpl = makeClient(); + doorAnswer = { status: 200, body: { success: true, data: {} } }; + stubFetch(); + window.confirm = vi.fn(() => true) as unknown as typeof window.confirm; +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +describe('the full-screen header and tabs (objectstack#36905)', () => { + it('draws the detail header, the five sections and the item tools; the matrix draws no header of its own', async () => { + mount(CUSTOM_PKG); + expect(await title()).toHaveTextContent('Sales rep'); + expect(screen.getByTestId('studio-detail-close')).toBeInTheDocument(); + expect(screen.queryByTestId('access-item-header')).toBeNull(); + for (const section of ['objects', 'capabilities', 'rls', 'tabs', 'admin']) { + expect(screen.getByTestId(`perm-tab-${section}`)).toBeInTheDocument(); + } + for (const tool of ['references', 'history', 'source']) { + expect(screen.getByTestId(`item-tab-${tool}`)).toBeInTheDocument(); + } + // History is a tab here, never the matrix's sheet button. + expect(screen.queryByTestId('history-button')).toBeNull(); + expect(screen.getByTestId('perm-tab-objects')).toHaveAttribute('aria-pressed', 'true'); + }); + + it('a tool tab is addressable and keeps the matrix mounted; a section tab goes back', async () => { + mount(CUSTOM_PKG); + await title(); + await screen.findByTestId('perm-studio-sections', undefined, { timeout: 8000 }); + fireEvent.click(screen.getByTestId('item-tab-history')); + expect(await screen.findByTestId('tool-panel')).toHaveAttribute('data-tab', 'history'); + await waitFor(() => expect(window.location.search).toContain('tab=history')); + // Mounted and hidden: an edit survives the visit. + expect(screen.getByTestId('perm-studio-sections')).toHaveClass('hidden'); + expect(screen.getByTestId('perm-tab-objects')).toHaveAttribute('aria-pressed', 'false'); + + fireEvent.click(screen.getByTestId('perm-tab-capabilities')); + await waitFor(() => expect(screen.queryByTestId('tool-panel')).toBeNull()); + expect(screen.getByTestId('perm-studio-sections')).not.toHaveClass('hidden'); + expect(screen.getByTestId('perm-tab-capabilities')).toHaveAttribute('aria-pressed', 'true'); + }); + + it('an address on a tool tab opens it', async () => { + window.history.replaceState(null, '', '/?tab=source'); + mount(CUSTOM_PKG, '&tab=source'); + expect(await screen.findByTestId('tool-panel', undefined, { timeout: 8000 })).toHaveAttribute('data-tab', 'source'); + }); + + it('× opens the list of sets, with the package', async () => { + mount(CUSTOM_PKG); + await title(); + fireEvent.click(screen.getByTestId('studio-detail-close')); + await screen.findByTestId('list'); + expect(where()).toBe(`/studio/${CUSTOM_PKG}/metadata/permission?package=${encodeURIComponent(CUSTOM_PKG)}`); + }); +}); + +describe('the status place says what a save does, or that nothing is saved (objectui#11781, #12453, #29674)', () => { + it('read-only: one read-only link carrying the sentence, and no save banner', async () => { + mount(BASE_PKG); + await title(); + const links = screen.getAllByTestId('studio-readonly-link'); + expect(links).toHaveLength(1); + expect(links[0]).toHaveAttribute('title', en('engine.studio.access.bannerTitleReadOnly')); + expect(screen.queryByTestId('studio-item-status')).toBeNull(); + }); + + it('CONTROL — writable, a set of a base\'s pair: the status chip names the base whose objects it lists', async () => { + mount(CUSTOM_PKG); + await title(); + const chip = await screen.findByTestId('studio-item-status'); + expect(chip).toHaveTextContent(tFormat('engine.studio.access.bannerPair', 'en', { package: BASE_PKG })); + expect(chip).toHaveAccessibleDescription(tFormat('engine.studio.access.bannerTitlePair', 'en', { package: BASE_PKG })); + expect(screen.queryByTestId('studio-readonly-link')).toBeNull(); + }); +}); + +describe('the draft discard (objectstack#36905)', () => { + it('drops this set\'s draft at its package, after one question', async () => { + clientImpl = makeClient([SET]); + mount(CUSTOM_PKG); + fireEvent.click(await screen.findByTestId('access-discard-draft', undefined, { timeout: 8000 })); + expect(window.confirm).toHaveBeenCalledTimes(1); + await waitFor(() => expect(clientImpl.reset).toHaveBeenCalledWith('permission', SET, { state: 'draft', packageId: CUSTOM_PKG })); + }); + + it('CONTROL: no draft, no discard', async () => { + mount(CUSTOM_PKG); + await title(); + await waitFor(() => expect(clientImpl.listDrafts).toHaveBeenCalled()); + expect(screen.queryByTestId('access-discard-draft')).toBeNull(); + }); + + // objectstack#26836's discard cases, moved from the Access pillar's pin. + it('a declined question discards nothing, and the discard stays offered', async () => { + clientImpl = makeClient([SET]); + window.confirm = vi.fn(() => false) as unknown as typeof window.confirm; + mount(CUSTOM_PKG); + fireEvent.click(await screen.findByTestId('access-discard-draft', undefined, { timeout: 8000 })); + expect(window.confirm).toHaveBeenCalledTimes(1); + expect(clientImpl.reset).not.toHaveBeenCalled(); + expect(screen.getByTestId('access-discard-draft')).toBeInTheDocument(); + expect(where()).toBe(`/studio/${CUSTOM_PKG}/metadata/permission/${SET}?package=${CUSTOM_PKG}`); + }); + + it('a set never published: its question says so, and its discard goes back to the list of sets', async () => { + clientImpl = makeClient([SET]); + // The package's published sets do not hold it: only its draft does. + clientImpl.list.mockImplementation(async (type: string) => (type === 'object' ? [{ name: 'crm_lead', label: 'Lead' }] : [])); + mount(CUSTOM_PKG); + fireEvent.click(await screen.findByTestId('access-discard-draft', undefined, { timeout: 8000 })); + expect(window.confirm).toHaveBeenCalledWith( + tFormat('engine.studio.access.discardConfirmUnpublished', 'en', { item: 'Sales rep' }), + ); + await waitFor(() => expect(clientImpl.reset).toHaveBeenCalledWith('permission', SET, { state: 'draft', packageId: CUSTOM_PKG })); + await screen.findByTestId('list'); + expect(where()).toBe(`/studio/${CUSTOM_PKG}/metadata/permission?package=${encodeURIComponent(CUSTOM_PKG)}`); + }); + + it('CONTROL: a published set\'s discard asks the published question and stays on the set', async () => { + clientImpl = makeClient([SET]); + mount(CUSTOM_PKG); + const discard = await screen.findByTestId('access-discard-draft', undefined, { timeout: 8000 }); + const readsBefore = setsReads(); + fireEvent.click(discard); + expect(window.confirm).toHaveBeenCalledWith(tFormat('engine.studio.access.discardConfirm', 'en', { item: 'Sales rep' })); + await waitFor(() => expect(clientImpl.reset).toHaveBeenCalledTimes(1)); + // The page stayed: it reads the package's sets again, which a page sent to the list never does. + await waitFor(() => expect(setsReads()).toBeGreaterThan(readsBefore)); + expect(screen.queryByTestId('list')).toBeNull(); + expect(where()).toBe(`/studio/${CUSTOM_PKG}/metadata/permission/${SET}?package=${CUSTOM_PKG}`); + }); + + it('a read-only package offers no discard, even with a pending draft', async () => { + clientImpl = makeClient([SET]); + mount(BASE_PKG); + await title(); + await waitFor(() => expect(clientImpl.listDrafts).toHaveBeenCalled()); + expect(screen.queryByTestId('access-discard-draft')).toBeNull(); + }); + + it('an unanswered read of the package\'s sets never counts the set as never published: the AI discard stays on it', async () => { + clientImpl = makeClient([SET], draftOf('copilot')); + clientImpl.list.mockImplementation(async (type: string) => { + if (type === 'permission') throw new Error('sets unreadable'); + return [{ name: 'crm_lead', label: 'Lead' }]; + }); + mount(CUSTOM_PKG); + const discard = await screen.findByTestId('studio-ai-draft-discard', undefined, { timeout: 8000 }); + const readsBefore = setsReads(); + fireEvent.click(discard); + await waitFor(() => expect(clientImpl.reset).toHaveBeenCalledWith('permission', SET, { state: 'draft', packageId: CUSTOM_PKG })); + // The page stayed: it reads the package's sets again, which a page sent to the list never does. + await waitFor(() => expect(setsReads()).toBeGreaterThan(readsBefore)); + expect(screen.queryByTestId('list')).toBeNull(); + expect(where()).toBe(`/studio/${CUSTOM_PKG}/metadata/permission/${SET}?package=${CUSTOM_PKG}`); + }); +}); + +describe('an AI draft gets the designers\' notice and discard (objectstack#36905 item 6, epic decision 1)', () => { + for (const by of ['copilot', 'mcp'] as const) { + it(`${by}: the notice, its discard drops the set's draft at its package without asking on a clean page`, async () => { + clientImpl = makeClient([SET], draftOf(by)); + mount(CUSTOM_PKG); + expect(await screen.findByTestId('studio-ai-draft-notice', undefined, { timeout: 8000 })).toHaveTextContent( + en('engine.studio.aiDraft.notice'), + ); + // The AI's draft is discarded from its notice, not from the plain button. + expect(screen.queryByTestId('access-discard-draft')).toBeNull(); + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + await waitFor(() => + expect(clientImpl.reset).toHaveBeenCalledWith('permission', SET, { state: 'draft', packageId: CUSTOM_PKG }), + ); + expect(window.confirm).not.toHaveBeenCalled(); + }); + } + + it('CONTROL: a person\'s own draft draws no notice, and keeps Discard draft', async () => { + clientImpl = makeClient([SET], draftOf('studio')); + mount(CUSTOM_PKG); + await screen.findByTestId('access-discard-draft', undefined, { timeout: 8000 }); + expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull(); + }); +}); + +describe('"New similar" in ⋯ on a read-only base (objectstack#36905, #28573)', () => { + async function openNewSimilar() { + await title(); + fireEvent.pointerDown(screen.getByTestId('studio-detail-more'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(await screen.findByTestId('access-new-similar')); + const dialog = await screen.findByRole('dialog'); + fireEvent.change(within(dialog).getByLabelText(en('perm.clone.name')), { target: { value: COPY_NAME } }); + fireEvent.change(within(dialog).getByLabelText(en('perm.clone.label')), { target: { value: 'My sales rep' } }); + fireEvent.click(within(dialog).getByRole('button', { name: en('perm.clone.confirm') })); + } + + it('opens the copy at its metadata address in the package the answer names, with the strip', async () => { + doorAnswer = { + status: 200, + body: { success: true, data: { permissionSet: { ...BODY, name: COPY_NAME }, package: CUSTOM_PKG, notice: 'Saved.' } }, + }; + mount(BASE_PKG); + await openNewSimilar(); + await waitFor(() => + expect(where()).toBe(`/studio/${CUSTOM_PKG}/metadata/permission/${COPY_NAME}?package=${encodeURIComponent(CUSTOM_PKG)}`), + ); + const strip = await screen.findByTestId('access-new-similar-strip'); + expect(strip).toHaveTextContent( + tFormat('engine.studio.access.newSimilar.done', 'en', { name: COPY_NAME, package: CUSTOM_PKG }), + ); + }); + + it('an answer naming no package opens nothing and says so', async () => { + doorAnswer = { status: 200, body: { success: true, data: { permissionSet: { ...BODY, name: COPY_NAME }, notice: 'Saved.' } } }; + mount(BASE_PKG); + await openNewSimilar(); + const strip = await screen.findByTestId('access-new-similar-strip'); + expect(strip).toHaveTextContent(tFormat('engine.studio.access.newSimilar.noPackage', 'en', { name: COPY_NAME })); + expect(where()).toBe(`/studio/${BASE_PKG}/metadata/permission/${SET}?package=${BASE_PKG}`); + }); + + it('CONTROL: a writable package\'s set offers no New similar', async () => { + mount(CUSTOM_PKG); + await title(); + fireEvent.pointerDown(screen.getByTestId('studio-detail-more'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + await screen.findByText(en('perm.basics.editHint')); + expect(screen.queryByTestId('access-new-similar')).toBeNull(); + }); +}); + +/** + * objectui#12456 / objectstack#34795 — the matrix's sections as the Access + * pillar's pin held them, now on the set's page (moved from + * `StudioDesignSurface.accessTabs-12456`; the pillar's own header half went + * with the pillar). + */ +describe('the matrix\'s five sections on the page (objectui#12456)', () => { + const sectionPanel = (key: string) => + screen.getByTestId(key === 'objects' || key === 'capabilities' ? `perm-tabpanel-${key}` : `perm-facet-${key}`); + + async function openWritable() { + mount(CUSTOM_PKG); + await screen.findByTestId('perm-row-crm_lead', undefined, { timeout: 8000 }); + } + + it('five tabs in order, Objects the landing', async () => { + await openWritable(); + const header = screen.getByTestId('permission-detail-header'); + const tabs = Array.from(header.querySelectorAll('[data-testid^="perm-tab-"]')); + expect(tabs.map((b) => b.textContent)).toEqual([ + en('engine.studio.access.tab.objects'), + en('engine.studio.access.tab.capabilities'), + en('engine.studio.access.tab.rls'), + en('engine.studio.access.tab.tabs'), + en('engine.studio.access.tab.admin'), + ]); + expect(screen.getByTestId('perm-tab-objects')).toHaveAttribute('aria-pressed', 'true'); + expect(screen.getByTestId('perm-tabpanel-objects')).toBeVisible(); + expect(screen.getByTestId('perm-tabpanel-capabilities')).not.toBeVisible(); + expect(screen.getByTestId('perm-tabpanel-facets')).not.toBeVisible(); + }); + + it('each other tab shows its own section and hides the rest', async () => { + await openWritable(); + fireEvent.click(screen.getByTestId('perm-tab-capabilities')); + expect(screen.getByTestId('perm-tab-capabilities')).toHaveAttribute('aria-pressed', 'true'); + expect(screen.getByTestId('perm-tabpanel-objects')).not.toBeVisible(); + expect(within(sectionPanel('capabilities')).getByText(en('perm.field.systemCapabilities'))).toBeVisible(); + + for (const [key, name] of [ + ['rls', 'perm.rls.title'], + ['tabs', 'perm.tabs.title'], + ['admin', 'perm.admin.title'], + ] as const) { + fireEvent.click(screen.getByTestId(`perm-tab-${key}`)); + expect(sectionPanel(key)).toBeVisible(); + expect(sectionPanel(key)).toHaveAccessibleName(en(name)); + for (const other of ['rls', 'tabs', 'admin'].filter((k) => k !== key)) { + expect(sectionPanel(other)).not.toBeVisible(); + } + } + }); + + it('the facet panels stay mounted while Objects is open, so each still reports to the Save gate', async () => { + await openWritable(); + for (const key of ['rls', 'tabs', 'admin']) { + expect(screen.getByTestId(`perm-facet-${key}`)).toBeInTheDocument(); + } + }); + + it('the bulk strip draws on every row at rest: All · Read only · None, then the CRUD arm', async () => { + await openWritable(); + await screen.findByTestId('perm-row-crm_account'); + for (const obj of ['crm_lead', 'crm_account']) { + expect(within(screen.getByTestId(`perm-bulk-${obj}`)).getAllByRole('button').map((b) => b.textContent)).toEqual([ + en('perm.bulk.all'), + en('perm.bulk.read'), + en('perm.bulk.none'), + en('perm.bulk.crud'), + ]); + } + }); + + it("keyboard focus on a row's first checkbox marks the row; focus leaving the row clears it", async () => { + await openWritable(); + const row = await screen.findByTestId('perm-row-crm_account'); + const first = within(row).getAllByRole('checkbox')[0]; + act(() => first.focus()); + expect(first).toHaveFocus(); + expect(row).toHaveAttribute('data-active', 'true'); + // The strip's buttons are in the row's tab order. + act(() => within(screen.getByTestId('perm-bulk-crm_account')).getAllByRole('button')[0].focus()); + expect(row).toHaveAttribute('data-active', 'true'); + act(() => within(screen.getByTestId('perm-row-crm_lead')).getAllByRole('checkbox')[0].focus()); + await waitFor(() => expect(row).not.toHaveAttribute('data-active')); + }); + + it('CRUD grants the four CRUD cells and nothing else, and the header counts it', async () => { + await openWritable(); + const row = await screen.findByTestId('perm-row-crm_account'); + fireEvent.mouseEnter(row); + fireEvent.click(within(row).getByRole('button', { name: en('perm.bulk.crud') })); + for (const action of ['perm.action.create', 'perm.action.read', 'perm.action.edit', 'perm.action.delete']) { + expect(within(row).getByRole('checkbox', { name: `crm_account ${en(action)}` })).toBeChecked(); + } + expect(within(row).getByRole('checkbox', { name: `crm_account ${en('perm.action.viewAll')}` })).not.toBeChecked(); + await waitFor(() => + expect(within(screen.getByTestId('permission-detail-header')).getByText('2 objects granted · 0 field overrides')).toBeInTheDocument(), + ); + }); + + it('the sharing column is a chip that opens the overview on its object; the toolbar counts the objects', async () => { + await openWritable(); + const row = screen.getByTestId('perm-row-crm_lead'); + const chip = within(row).getByTestId('owd-badge-crm_lead'); + expect(chip).toHaveTextContent(en('perm.owd.defaultPrivate')); + expect(screen.getByTestId('perm-object-count')).toHaveTextContent('2 objects'); + fireEvent.click(chip); + await waitFor(() => expect(where()).toBe(`/studio/${CUSTOM_PKG}/owd?object=crm_lead`)); + }); +}); + +/** + * The sharing chip is a `role="button"` badge that calls `navigate()`: the + * shell's link-click listener never sees it, so the page's own guard is all + * that keeps a dirty matrix's edits (`confirmUnsavedLeave`). + */ +describe('the sharing chip asks before it leaves a dirty matrix (objectstack#36905)', () => { + const editCell = () => screen.getByRole('checkbox', { name: `crm_lead ${en('perm.action.edit')}` }); + + async function openDirty() { + mount(CUSTOM_PKG); + await screen.findByTestId('perm-row-crm_lead', undefined, { timeout: 8000 }); + fireEvent.click(editCell()); + expect(editCell()).toBeChecked(); + } + + it('declined, the page stays on the set and keeps the edit', async () => { + await openDirty(); + window.confirm = vi.fn(() => false) as unknown as typeof window.confirm; + fireEvent.click(screen.getByTestId('owd-badge-crm_lead')); + expect(window.confirm).toHaveBeenCalledTimes(1); + expect(window.confirm).toHaveBeenCalledWith(en('engine.edit.unsavedLeaveConfirm')); + expect(where()).toBe(`/studio/${CUSTOM_PKG}/metadata/permission/${SET}?package=${CUSTOM_PKG}`); + expect(editCell()).toBeChecked(); + }); + + it('confirmed, it opens the overview on its object', async () => { + await openDirty(); + fireEvent.click(screen.getByTestId('owd-badge-crm_lead')); + expect(window.confirm).toHaveBeenCalledTimes(1); + await waitFor(() => expect(where()).toBe(`/studio/${CUSTOM_PKG}/owd?object=crm_lead`)); + }); + + it('CONTROL: a clean matrix asks nothing', async () => { + mount(CUSTOM_PKG); + await screen.findByTestId('perm-row-crm_lead', undefined, { timeout: 8000 }); + fireEvent.click(screen.getByTestId('owd-badge-crm_lead')); + await waitFor(() => expect(where()).toBe(`/studio/${CUSTOM_PKG}/owd?object=crm_lead`)); + expect(window.confirm).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioPermissionSetPage.tsx b/ui/packages/app-shell/src/views/studio-design/StudioPermissionSetPage.tsx new file mode 100644 index 00000000000..3ac18e32a8c --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/StudioPermissionSetPage.tsx @@ -0,0 +1,471 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A permission set's full-screen page in Studio (objectstack#36905, Studio + * redesign epic #36890): the matrix (`PermissionMatrixEditPage`, its Studio + * presentation) at the set's metadata address, + * `/studio//metadata/permission/`, in the right-hand content + * area beside the left menu. It replaces the Access pillar's rail and + * workbench: a set is chosen from its type's list, and × goes back there. + * + * - The header is the full-screen detail's (`ResourceDetailHeader`, #36892): + * × to the list, ‹ › through it, the set's label (its machine name on the + * title's tooltip, objectstack#34795), type and package, and a ⋯ menu. + * - The tab row is the five sections of the matrix, then the item tools of + * every item page (`ItemToolTabs`, #36901): References, History (with the + * audit log, for a caller the trail door admits) and Source. A tool tab + * keeps the matrix mounted and hidden, so an edit survives the visit, and + * is addressable (`?tab=`); History replaces the matrix's History sheet. + * - What the pillar drew around the matrix comes along: the draft discard, + * Explain access, the suggested audiences strip, and on a read-only base + * "New similar" (now in ⋯) with the strip the copy lands with. + * - Save is the Studio top bar's (objectstack#36511): the matrix registers + * its unsaved edits with the shell's leave guard and the top bar's Save, + * so ×, ‹ ›, the left menu, a reload and a tab close all ask first + * (epic decision 12). The browser's Back is not guarded. + * + * - An AI-written pending draft (copilot or MCP) is the version on screen and + * gets the designers' notice (`StudioAiDraftNotice`): Save makes it live + * with the page's own edits, and 「放弃 AI 的改动」 drops that one set's + * draft at its package, asking first only when the matrix holds unsaved + * edits — the rule the generic item page follows (epic decision 1, + * objectstack#36660). A person's own leftover draft keeps Discard draft + * (decision 14). + */ + +import * as React from 'react'; +import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'; +import { Copy, Shield, ShieldQuestion, Undo2 } from 'lucide-react'; +import { DropdownMenuItem } from '@object-ui/components'; +import { formatMetadataError, type DraftChange } from '@object-ui/data-objectstack'; +import { toast } from 'sonner'; +import { + PermissionMatrixEditPage, + type PermissionStudioHeaderParts, + type PermissionStudioTab, +} from '../metadata-admin/PermissionMatrixEditor.js'; +import { ResourceDetailHeader, detailListHref } from '../metadata-admin/ResourceDetailHeader.js'; +import { ItemToolTabPanel, ItemToolTabStrip, offeredItemToolTabs, useItemToolTab } from '../item-tools/ItemToolTabs.js'; +import { useCanAuthorMetadata, useCanReadAuthoringTrail } from '../../hooks/useCanAuthorMetadata.js'; +import { useMetadataClient } from '../metadata-admin/useMetadata.js'; +import { useWalledCatalogReadOnly } from '../metadata-admin/catalog-scope.js'; +import { t, tFormat, translateMetadataType, useMetadataLocale } from '../metadata-admin/i18n.js'; +import { AccessExplainPanel } from '../metadata-admin/AccessExplainPanel.js'; +import { PermissionSetCloneDialog } from '../metadata-admin/PermissionSetCloneDialog.js'; +import type { PermissionSetCloned } from '../metadata-admin/permission-set-clone.js'; +import { confirmUnsavedLeave } from '../../chrome/unsavedEdits.js'; +import { SuggestedBindingsPanel } from '../../components/SuggestedBindingsPanel.js'; +import { suggestedSetLabel } from '../../components/suggestedSetLabel.js'; +import { StudioReadOnlyLink } from './StudioPillarKit.js'; +import { StudioAiDraftNotice } from './StudioAiDraftNotice.js'; +import { isAgentDraftSurface } from './StudioDraftMark.js'; +import type { StudioItemStatus } from './StudioItemHeader.js'; +import type { StudioSurfaceLabel } from './StudioAiCopilot.js'; +import { customizationPairBaseOf } from './StudioRailCustomizations.js'; +import { fetchListedPackageManifests } from './packages-io.js'; +import { useMetadataRefreshNonce } from './useMetadataRefreshNonce.js'; +import { accessSuggestionStrings } from './accessSuggestionStrings.js'; +import { + NewSimilarStripNotice, + newSimilarOutcome, + readNewSimilarArrival, + type NewSimilarStrip, +} from './permissionNewSimilar.js'; +import { studioOwdOverviewPath } from './studioAddress.js'; + +const ACTION_BUTTON = + 'inline-flex h-7 shrink-0 items-center gap-1.5 rounded-md border px-2.5 text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50'; + +export interface StudioPermissionSetPageProps { + /** The package the set is read and saved at: the area's leg. */ + packageId: string; + /** The set's machine name. */ + name: string; + /** The package is read-only (the area's courtesy gate). */ + readOnly?: boolean; + /** Bumped by the top bar's Publish: the matrix re-reads what is served. */ + publishNonce?: number; + /** Told when a save left a draft, so the top bar's pending count follows it. */ + onDraftSaved?: () => void; + /** objectstack#35018 — the set's label for the copilot's chip: 「正在看:权限 · 组织成员」. */ + onSurfaceLabelChange?: (surface: StudioSurfaceLabel | null) => void; +} + +/** What the page reads of the package's sets: their labels, which are published, which hold a draft. */ +interface SetsRead { + sets: Array<{ name: string; label: string }>; + published: ReadonlySet; + drafts: ReadonlySet; +} + +export function StudioPermissionSetPage({ + packageId, + name, + readOnly = false, + publishNonce = 0, + onDraftSaved, + onSurfaceLabelChange, +}: StudioPermissionSetPageProps): React.ReactElement { + const client = useMetadataClient(); + const locale = useMetadataLocale(); + const navigate = useNavigate(); + const location = useLocation(); + const [searchParams] = useSearchParams(); + const metadataRefreshNonce = useMetadataRefreshNonce(); + + // The section the matrix shows (Objects is the landing), and the item tool + // open over it, which the address carries. + const [section, setSection] = React.useState('objects'); + const canReadTrail = useCanReadAuthoringTrail(); + const canAuthor = useCanAuthorMetadata(); + const offeredTabs = React.useMemo(() => offeredItemToolTabs({ trail: canReadTrail }), [canReadTrail]); + const itemTab = useItemToolTab(offeredTabs); + const toolTab = itemTab.location.tab; + const toolOpen = toolTab !== 'details'; + + // The package's sets: the discard's two inputs and the suggestions' labels. + const [readNonce, setReadNonce] = React.useState(0); + const [read, setRead] = React.useState(null); + React.useEffect(() => { + let cancelled = false; + Promise.all([ + client.list('permission', { packageId }) as Promise>>, + client.listDrafts({ packageId, type: 'permission' }).catch(() => []), + ]).then( + ([list, drafts]) => { + if (cancelled) return; + const nameOf = (p: Record | null | undefined) => String(p?.name ?? p?.id ?? ''); + setRead({ + sets: (list || []).map((p) => ({ name: nameOf(p), label: String(p.label ?? p.name ?? '') })), + published: new Set((list || []).map(nameOf).filter(Boolean)), + drafts: new Set(((drafts as Array<{ name?: string }>) || []).map((d) => String(d?.name ?? '')).filter(Boolean)), + }); + }, + () => { + if (!cancelled) setRead(null); + }, + ); + return () => { + cancelled = true; + }; + }, [client, packageId, publishNonce, metadataRefreshNonce, readNonce]); + + // objectstack#35018 — the copilot's chip reads the pillar's word and the + // set's label, never the type word or the machine name. Keyed on primitives, + // the callback read through a ref; cleared on unmount. + const reportLabelRef = React.useRef(onSurfaceLabelChange); + React.useEffect(() => { + reportLabelRef.current = onSurfaceLabelChange; + }); + const setLabel = read?.sets.find((p) => p.name === name)?.label; + const chipLabel = setLabel ? `${t('engine.studio.copilot.subject.access', locale)} · ${setLabel}` : null; + React.useEffect(() => { + reportLabelRef.current?.(chipLabel ? { type: 'permission', name, label: chipLabel } : null); + }, [name, chipLabel]); + React.useEffect( + () => () => { + reportLabelRef.current?.(null); + }, + [], + ); + + // Bumped by a discard and a rollback: the matrix re-reads as it does after a + // publish, since in each what it holds is gone. + const [rereadNonce, setRereadNonce] = React.useState(0); + // The set's label as the matrix last drew it, for the discard's question. + const titleRef = React.useRef(name); + + const hasDraft = !readOnly && !!read?.drafts.has(name); + // Who wrote the pending draft, as the matrix's load read it. + const [draftChanges, setDraftChanges] = React.useState(null); + const aiDraft = (draftChanges ?? []).some((change) => isAgentDraftSurface(change.by)); + const [matrixDirty, setMatrixDirty] = React.useState(false); + const [discarding, setDiscarding] = React.useState(false); + /** Drop this set's draft at its package (`DELETE ?state=draft`), once `ask` agreed. */ + const dropDraft = React.useCallback( + async (ask: (item: string, neverPublished: boolean) => boolean, failed: (e: unknown) => void) => { + const item = titleRef.current || name; + // Never published only when the package's sets were read and this one is + // not among them: an unanswered read says nothing, so the page stays and + // re-reads, and never sends a published set's page to the list. + const neverPublished = read !== null && !read.published.has(name); + if (!ask(item, neverPublished)) return; + setDiscarding(true); + try { + await client.reset('permission', name, { state: 'draft', packageId }); + toast.success(tFormat('engine.edit.draftDiscarded', locale, { item })); + setDraftChanges(null); + onDraftSaved?.(); + // A set that was never published has nothing left: back to its list. + if (neverPublished) { + navigate(detailListHref(location.pathname, searchParams)); + return; + } + setRereadNonce((n) => n + 1); + setReadNonce((n) => n + 1); + } catch (e) { + failed(e); + } finally { + setDiscarding(false); + } + }, + [read, name, locale, client, packageId, onDraftSaved, navigate, location.pathname, searchParams], + ); + // A person's own draft: one confirm, since an unsaved edit on the matrix is + // an unpublished change of this same set and goes with the rest. + const discardDraft = () => + dropDraft( + (item, neverPublished) => + window.confirm( + tFormat( + neverPublished ? 'engine.studio.access.discardConfirmUnpublished' : 'engine.studio.access.discardConfirm', + locale, + { item }, + ), + ), + (e) => + toast.error(t('engine.studio.access.discardFailed', locale), { + description: formatMetadataError(e), + classNames: { description: 'whitespace-pre-line' }, + }), + ); + // The AI's draft: asked first only when the matrix holds unsaved edits. + const discardAiDraft = () => + dropDraft( + () => !matrixDirty || window.confirm(t('engine.studio.aiDraft.discardConfirmUnsaved', locale)), + (e) => + toast.error(tFormat('engine.studio.aiDraft.discardFailed', locale, { reason: formatMetadataError(e) }), { + classNames: { description: 'whitespace-pre-line' }, + }), + ); + + // "New similar" on a read-only base's set (objectstack#28573): the copy + // opens where the clone door says it landed, with the strip riding the + // navigation; an answer that names no copy or no package is said here. + const [newSimilarOpen, setNewSimilarOpen] = React.useState(false); + const [cloneSource, setCloneSource] = React.useState<{ name: string; sourcePackage: string | undefined } | null>(null); + const onCloneSourceRead = React.useCallback((setName: string, sourcePackage: string | undefined) => { + setCloneSource((prev) => + prev && prev.name === setName && prev.sourcePackage === sourcePackage ? prev : { name: setName, sourcePackage }, + ); + }, []); + const [strip, setStrip] = React.useState(() => readNewSimilarArrival(location.state, packageId)); + const shownStrip = strip && (strip.kind !== 'landed' || strip.name === name) ? strip : null; + const onNewSimilarSaved = React.useCallback( + (copy: PermissionSetCloned) => { + setNewSimilarOpen(false); + const outcome = newSimilarOutcome(copy); + if ('strip' in outcome) setStrip(outcome.strip); + else navigate(outcome.open.to, { state: outcome.open.state }); + }, + [navigate], + ); + const walled = useWalledCatalogReadOnly('permission'); + const newSimilarBlocked = walled + ? tFormat('engine.catalog.readOnly.walled', locale, { type: translateMetadataType('permission', locale) }) + : canAuthor + ? null + : t('engine.edit.capabilityReadOnly', locale); + + const [explainOpen, setExplainOpen] = React.useState(false); + + // The status place: what a save does here, or, read-only, the link that + // says why nothing is saved. A set of a base's pair lists the base's objects + // too (objectstack#29674), so its note names the base, by its label once the + // package list (one shared read, `packages-io.ts`) has said it. + const pairBase = customizationPairBaseOf(packageId); + const [pairBaseLabel, setPairBaseLabel] = React.useState<{ id: string; label: string } | null>(null); + React.useEffect(() => { + if (pairBase === null) return undefined; + let cancelled = false; + fetchListedPackageManifests().then( + (manifests) => { + const label = manifests.get(pairBase)?.name; + if (!cancelled && label) setPairBaseLabel({ id: pairBase, label }); + }, + () => undefined, + ); + return () => { + cancelled = true; + }; + }, [pairBase]); + const baseShown = pairBase === null ? '' : pairBaseLabel?.id === pairBase ? pairBaseLabel.label : pairBase; + const status: StudioItemStatus | undefined = readOnly + ? undefined + : pairBase !== null + ? { + label: tFormat('engine.studio.access.bannerPair', locale, { package: baseShown }), + title: tFormat('engine.studio.access.bannerTitlePair', locale, { package: baseShown }), + } + : { label: t('engine.studio.access.banner', locale), title: t('engine.studio.access.bannerTitle', locale) }; + + const renderHeader = (parts: PermissionStudioHeaderParts): React.ReactNode => { + titleRef.current = parts.title; + return ( + + {parts.title} + + } + typeLabel={translateMetadataType('permission', locale)} + packageLabel={packageId} + status={status} + meta={parts.meta} + note={parts.note} + primaryAction={ +
+ {parts.actions} + {readOnly && ( + + )} + {hasDraft && !aiDraft && ( + + )} + +
+ } + menu={ + <> + {readOnly && ( + { + setStrip(null); + setNewSimilarOpen(true); + }} + > + + {t('perm.clone.action', locale)} + + )} + {parts.menuItems} + + } + tabs={ + <> + {parts.sectionTabs} +