diff --git a/.changeset/37139-studio-package-menu.md b/.changeset/37139-studio-package-menu.md new file mode 100644 index 00000000000..a284e04e6df --- /dev/null +++ b/.changeset/37139-studio-package-menu.md @@ -0,0 +1,20 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(console): a 「⋯」 package menu in Studio's top bar, and Import on Setup → Packages + +Clause-②: no +Metadata-protocol: none + +With the Studio home gone, the whole-package actions of the Packages page's development view had no button anywhere. They are back, in two places: + +- **Studio's top bar.** Beside the app or package name at the left end there is now a 「⋯」 menu (zh: 软件包操作) with six items: Edit package info (编辑软件包信息), Export (导出), Duplicate as a new package (复制为新软件包), Revert to last publish (还原到上次发布), Adopt loose items (收编散落项) and Manage in Setup… (在设置中管理…). Each opens the same dialog and sends the same request as the development view's button; the answer appears as a toast. Revert now asks for confirmation first. On a read-only installed package, Edit, Duplicate, Revert and Adopt are greyed with the reason on hover; Revert is also greyed while nothing has changed since the last publish. Manage in Setup… opens Setup → Packages with that package's detail open, where it is enabled, disabled or deleted. The menu is shown only to people who can author metadata (`manage_metadata`), and not in the organization-flows scope or the all-packages view, where no package is open. Publishing every draft is not in the menu: Studio's Changes / Publish already do that. +- **Setup → Packages.** Import now sits in the header beside New Package and works exactly as on the development view. A Setup → Packages address can open one package's detail directly by adding `&package=ID`. + +The development view itself is unchanged. + +New locale keys in the studio catalogue (en, zh): `engine.studio.packageMenu.trigger`, `.editInfo`, `.duplicate`, `.revert`, `.manageInSetup`, `.noChanges`, `.duplicateTitle`, `.duplicateDescription`, `.revertTitle`, `.revertDescription`. + +Seventeen studio-catalogue rows that no screen read any more are removed: `engine.studio.menu.typeCount` and the app-worded `engine.studio.newApp.*` rows (`title`, `description`, `advancedHint`, `id`, `help.*`, `nsDerived`, `created`, `exists`, `failed`). None of them was in a published `@object-ui/i18n` release; `engine.studio.newApp.nameTaken` and `engine.studio.newApp.appFailed` are still used and stay. diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx index 87e8724e5d9..f770ea46cde 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.installedAppsUpdates-34722.test.tsx @@ -24,8 +24,9 @@ * - a module package (`type: 'module'` declaring its app in `dependencies`) * is folded under that app's line and shown on demand; * - the columns are Name, Version, Status, Source, Update, and the developer - * doors (Import, the platform switch, the Source chip's Show all) are not - * drawn; New Package is, and lands in Studio (objectstack#36834). + * doors (the platform switch, the Source chip's Show all) are not drawn; + * New Package is, and lands in Studio (objectstack#36834), with Import + * beside it (objectstack#37139; see the last describe of this file). * On the Studio door all of the developer doors and columns stay, and the * catalog is never asked. * @@ -91,7 +92,7 @@ vi.mock('./PackageFormDialog', () => ({ import { resolveHref } from '@object-ui/layout'; import { PackageDetailSheet, PackagesPage, type InstalledPackageRow } from './PackagesPage'; import { t } from './i18n'; -import { SETUP_NEW_PACKAGE_PATH } from './packageSource'; +import { SETUP_NEW_PACKAGE_PATH, setupPackagePath } from './packageSource'; // The page's package form reaches the CEL authoring helpers, which load these // two lazily; loaded here so their first load is paid at import, not inside a // test's clocked window. @@ -235,6 +236,10 @@ async function serve({ if (path === '/api/v1/marketplace/install-local' && method === 'GET') { return reply(200, { success: true, data: { items: installs } }); } + // objectstack#37139 — Import: the file's manifest, installed. + if (path === '/api/v1/marketplace/install-local' && method === 'POST') { + return reply(200, { success: true, data: { manifestId: 'com.acme.imported' } }); + } const listing = /^\/api\/v1\/marketplace\/packages\/([^/]+)$/.exec(path); if (listing) { const id = decodeURIComponent(listing[1]); @@ -499,7 +504,7 @@ describe('Setup → Installed Apps: an app is one line, its modules folded under describe('the two doors (objectstack#34722)', () => { const headers = () => screen.getAllByRole('columnheader').map((h) => h.textContent?.trim()); - it('the administration face draws the administrator columns, New Package, and none of the developer doors', async () => { + it('the administration face draws the administrator columns, New Package and Import, and none of the other developer doors', async () => { await serve({ packages: [HOTCRM, ...MODULES, TODO, CODE, PLATFORM] }); renderAt(SETUP_URL); await settled(); @@ -512,9 +517,9 @@ describe('the two doors (objectstack#34722)', () => { row('engine.packages.installedApps.col.update'), row('engine.packages.col.actions'), ]); - expect(screen.queryByRole('button', { name: row('engine.packages.import') })).toBeNull(); - // objectstack#36834 — New Package is the administration face's one header - // action; it lands in Studio (see the create case below). + // objectstack#36834 — New Package lands in Studio (see the create case + // below); objectstack#37139 — Import sits beside it. + expect(screen.getByRole('button', { name: row('engine.packages.import') })).toBeInTheDocument(); expect(screen.getByRole('button', { name: row('engine.packages.new') })).toBeInTheDocument(); expect(screen.queryByTestId('pkg-show-platform')).toBeNull(); expect(screen.queryByTestId('pkg-source-filter')).toBeNull(); @@ -631,12 +636,10 @@ describe('Setup → Packages: the administration face (objectstack#36834)', () = expect(screen.getByTestId('pkg-source-picker-marketplace')).toHaveAttribute('data-state', 'on'); expect(screen.queryByTestId('pkg-row-com.acme.code')).toBeNull(); - expect(screen.queryByRole('button', { name: row('engine.packages.import') })).toBeNull(); // Clearing the filter stays on the administration face. fireEvent.click(screen.getByTestId('pkg-source-picker-all')); await waitFor(() => expect(query().get('face')).toBe('admin')); expect(await screen.findByTestId('pkg-row-com.acme.code')).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: row('engine.packages.import') })).toBeNull(); }); it('an unknown face is refused by name, not read as the development surface', async () => { @@ -927,3 +930,76 @@ describe('Setup → Packages: a read-only base’s customizations in its detail await waitFor(() => expect(customizationReads).toEqual(['com.acme.code'])); }); }); + +// --------------------------------------------------------------------------- +// objectstack#37139 — Import sits in Setup → Packages' header beside New +// Package and works as it does on the development face; Studio's package +// menu's 「Manage in Setup…」 opens this face on one package's row +// (`?package=ID`). +// --------------------------------------------------------------------------- + +/** The header's Import, fed one package file. */ +async function importOn(lang: 'en' | 'zh') { + const button = await screen.findByRole('button', { name: row('engine.packages.import', lang) }); + const input = document.querySelector('input[type="file"]') as HTMLInputElement; + const file = new File([JSON.stringify({ id: 'com.acme.imported', name: 'Imported', version: '1.0.0' })], 'imported.json', { + type: 'application/json', + }); + fireEvent.change(input, { target: { files: [file] } }); + return button; +} + +describe('Setup → Packages: Import beside New Package (objectstack#37139)', () => { + it.each(['en', 'zh'] as const)('%s: the header draws Import, then New Package', async (lang) => { + await serve({ packages: [CODE] }); + renderAt(ADMIN_URL, lang); + await screen.findByTestId('pkg-row-com.acme.code'); + const importButton = screen.getByRole('button', { name: row('engine.packages.import', lang) }); + const newButton = screen.getByRole('button', { name: row('engine.packages.new', lang) }); + expect(importButton.compareDocumentPosition(newButton) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(importButton.parentElement).toBe(newButton.parentElement); + }); + + it.each(['en', 'zh'] as const)('%s: Import installs the file and re-reads the list, as on the development face', async (lang) => { + await serve({ packages: [CODE] }); + renderAt(ADMIN_URL, lang); + await screen.findByTestId('pkg-row-com.acme.code'); + const readsBefore = packagesReads; + await importOn(lang); + expect( + await screen.findByText(t('engine.packages.import.success', lang === 'en' ? 'en-US' : 'zh-CN').replace('{id}', 'com.acme.imported')), + ).toBeInTheDocument(); + expect(writes).toEqual(['POST /api/v1/marketplace/install-local']); + await waitFor(() => expect(packagesReads).toBeGreaterThan(readsBefore)); + }); + + it('CONTROL: the development surface’s Import sends the same request', async () => { + await serve({ packages: [CODE] }); + renderAt(STUDIO_URL); + await screen.findByTestId('pkg-row-com.acme.code'); + await importOn('en'); + await waitFor(() => expect(writes).toEqual(['POST /api/v1/marketplace/install-local'])); + }); +}); + +describe('Setup → Packages on one package’s row: `?package=ID` (objectstack#37139)', () => { + it('opens that package’s detail on arrival and drops the param, keeping the face', async () => { + await serve({ packages: [CODE, AUTHORED] }); + renderAt(setupPackagePath('app.b2r4')); + const sheet = await screen.findByRole('dialog'); + expect(within(sheet).getByText('app.b2r4')).toBeInTheDocument(); + // The administration actions are there: Disable and Delete. + expect(within(sheet).getByRole('button', { name: row('engine.packages.detail.disable') })).toBeInTheDocument(); + expect(within(sheet).getByRole('button', { name: row('engine.packages.detail.deletePackage') })).toBeInTheDocument(); + await waitFor(() => expect(query().has('package')).toBe(false)); + expect(query().get('face')).toBe('admin'); + }); + + it('an id the list does not name opens nothing, and the param is dropped', async () => { + await serve({ packages: [CODE] }); + renderAt(setupPackagePath('com.gone.away')); + await screen.findByTestId('pkg-row-com.acme.code'); + await waitFor(() => expect(query().has('package')).toBe(false)); + expect(screen.queryByRole('dialog')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx index eca3c8540bc..0ea57c22c13 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx @@ -23,8 +23,13 @@ * of every source, one line per app with its modules folded under it, a * Source filter, and in the detail sheet only enable / disable and delete * (with its keep-data choice); New Package lands in Studio on the new - * package. Import, publish, revert, discard drafts, adopt loose items and - * manifest edit stay on the development surface. + * package, and Import sits beside it (objectstack#37139). Publish, revert, + * discard drafts, adopt loose items and manifest edit stay on the + * development surface. + * + * objectstack#37139 — the development face's whole-package actions (Edit, + * Export, Duplicate, Revert, Adopt loose items) are shared with Studio's 「⋯」 + * package menu through `packageActions.tsx`. */ import * as React from 'react'; @@ -95,6 +100,17 @@ import { useMetadataLocale, t, tFormat } from './i18n.js'; import { useMetadataClient } from './useMetadata.js'; import { newAppStep } from '../studio-design/newAppDoor.js'; import { PackageFormDialog } from './PackageFormDialog.js'; +import { + AdoptLooseItemsDialog, + DuplicatePackageForm, + EditPackageDialog, + PACKAGES_API, + adoptLooseItems, + adoptedText, + exportPackageFile, + packagesApiJson, + revertPackage, +} from './packageActions.js'; import { readPackageRemovalContents, type PackageRemovalState } from './packageRemovalContents.js'; import { PackageRemovalSummary } from './PackageRemovalSummary.js'; import { useAdapter } from '@object-ui/react'; @@ -104,9 +120,8 @@ import { readEnvelopeFailureText } from '../../utils/apiErrorEnvelope.js'; import { refusedItemsText } from '../../preview/publishRefusal.js'; import { RefusalMessage } from '../../components/RefusalMessage.js'; import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; -import { duplicatePackage, forgetPackageListReads, isSpecPackageId } from '../studio-design/packages-io.js'; -import { PackageIdInput } from '../studio-design/PackageIdInput.js'; -import { createAuthenticatedFetch, useWorkspaceAdminStatus } from '@object-ui/auth'; +import { duplicatePackage, forgetPackageListReads } from '../studio-design/packages-io.js'; +import { useWorkspaceAdminStatus } from '@object-ui/auth'; import { getRuntimeConfig, isMarketplaceEnabled } from '../../runtime-config.js'; import { getMarketplacePackage, @@ -122,7 +137,6 @@ import { useProtocolCheckSkippedText } from '../../console/marketplace/protocolC import { ProtocolCheckSkippedNote } from '../../console/marketplace/ProtocolCheckSkippedNote.js'; import type { InstalledPackageAtEitherStage } from '@objectstack/spec/api-assembled'; import type { PackagePublishResult } from '@objectstack/spec/system'; -import type { ReassignOrphanedMetadataResponse } from '@objectstack/spec/api'; import { studioHomePath } from '../studio-design/studioAddress.js'; import { PackageCustomizationsPanel } from '../studio-design/PackageCustomizationsPanel.js'; import { isCustomizationPackage } from '@objectstack/spec/kernel'; @@ -132,6 +146,7 @@ import { PACKAGES_FACE_PARAM, PACKAGES_NEW_PACKAGE_VALUE, PACKAGES_NEW_PARAM, + PACKAGES_PACKAGE_PARAM, PACKAGES_SOURCE_PARAM, PackageSourceRefusal, readPackagesFace, @@ -226,12 +241,10 @@ type UncheckedPackageRow = Omit & { writable?: unknown; }; -const API = '/api/v1/packages'; - -/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ -function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { - return createAuthenticatedFetch()(input, init); -} +// objectstack#37139 — the package REST surface and the whole-package actions +// live in `packageActions.tsx`, shared with Studio's 「⋯」 package menu. +const API = PACKAGES_API; +const apiJson = packagesApiJson; /** * The code `PATCH /packages/:id/disable` answers, with `409`, while a @@ -241,54 +254,6 @@ function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise(path: string, init?: RequestInit): Promise { - // objectstack#29119 — every write this page sends (publish, revert, discard, - // delete, adopt, enable/disable, import) may change the package list, so the - // list reads from before it are forgotten however it ends, the session's - // held list the app → Studio entries read included. - const writes = (init?.method ?? 'GET').toUpperCase() !== 'GET'; - const res = await authFetch(path, { - credentials: 'include', - headers: { Accept: 'application/json', ...(init?.headers || {}) }, - ...init, - }).finally(() => { - if (writes) forgetPackageListReads(); - }); - const text = await res.text(); - const payload = text ? JSON.parse(text) : null; - if (!res.ok || payload?.success === false) { - // The ADR-0112 envelope first, by the ONE shared rule — a producer-marked - // `error.userMessage` outranks the diagnostic `error.message`, and - // `error.code` rides along behind whichever won. This helper used to read - // `error.message` and stop, so a marked sentence arrived on the wire (both - // doors serving these package routes emit the channel) and had nowhere to - // appear. See {@link readEnvelopeFailureText}. - // - // The two rungs BELOW it stay, and stay here rather than moving into the - // shared reader: they are not the ADR-0112 envelope. A bare-string `error` - // and a top-level `message` are older runtimes' shapes, live for this page - // and not for the Studio readers, and folding them in would have handed - // every other consumer of the rule a tolerant dialect it never asked for. - const msg = - readEnvelopeFailureText(payload) || - payload?.error || - payload?.message || - `Request failed (${res.status})`; - const err = new Error(typeof msg === 'string' ? msg : `Request failed (${res.status})`) as Error & { - code?: string; - details?: unknown; - }; - // ADR-0141 D2 — the envelope's `code` and `details` ride on the error, so a - // caller that draws a refusal from its facts (`DEPENDENCY_MISSING` at the - // import door) can; every other caller reads the message as before. - if (typeof payload?.error?.code === 'string') err.code = payload.error.code; - if (payload?.error?.details !== undefined) err.details = payload.error.details; - throw err; - } - // Runtime wraps successful payloads in { data, ... } or returns the object directly. - return (payload?.data ?? payload) as T; -} - /* -------------------------------------------------------------------------- */ /* Scope badge */ /* -------------------------------------------------------------------------- */ @@ -683,34 +648,9 @@ function DetailRow({ label, children }: { label: string; children: React.ReactNo ); } -/** - * EditPackageDialog — thin wrapper over the spec-driven {@link PackageFormDialog} - * in `edit` mode. The manifest form locks `id` / `type` / `namespace` / scope - * as immutable and submits only name / description / version — all the REST - * `PATCH /api/v1/packages/:id` persists. Kept as a named export so existing - * call sites don't change. - */ -export function EditPackageDialog({ - pkg, - open, - onOpenChange, - onSaved, -}: { - pkg: InstalledPackageRow | null; - open: boolean; - onOpenChange: (v: boolean) => void; - onSaved: (updated: InstalledPackageRow) => void; -}) { - return ( - onSaved((r.package as unknown as InstalledPackageRow) ?? (pkg as InstalledPackageRow))} - /> - ); -} +// objectstack#37139 — moved to `packageActions.tsx` (Studio's 「⋯」 menu opens +// it too); still exported from here so existing call sites don't change. +export { EditPackageDialog }; /** * What *Delete app* removes (ADR-0070 D4, Q3). `structure` removes the @@ -797,8 +737,6 @@ export function PackageDetailSheet({ }); const [discardOpen, setDiscardOpen] = React.useState(false); const [dupOpen, setDupOpen] = React.useState(false); - const [dupName, setDupName] = React.useState(''); - const [dupId, setDupId] = React.useState(''); const fieldId = React.useId(); React.useEffect(() => { @@ -895,9 +833,6 @@ export function PackageDetailSheet({ // title shows. const displayName = pkg.manifest.name || id; const deleteArmed = deleteMode !== '' && deleteTyped.trim() === displayName.trim(); - // The spec's id rule (`isSpecPackageId`), the one the package id input - // and the duplicate route judge by, not a second one (objectui#11855). - const dupArmed = dupName.trim().length > 0 && isSpecPackageId(dupId.trim()); // objectui#13339 — the sheet's one message line answers the action the // author started LAST. An action that runs straight away clears it as it @@ -1056,7 +991,7 @@ export function PackageDetailSheet({ const revert = () => run( 'revert', - () => apiJson(`${API}/${encodeURIComponent(id)}/revert`, { method: 'POST' }), + () => revertPackage(id), t('engine.packages.detail.reverted', locale), ); @@ -1129,25 +1064,19 @@ export function PackageDetailSheet({ // ADR-0070 D4 — duplicate this base into a NEW writable package // (re-namespaced). An inline duplicate form, on this sheet - // (objectui#11784): the same id input (`PackageIdInput`), the same id rule - // (`isSpecPackageId`) and the same call (`duplicatePackage`, which also refuses - // a 200 whose verdict is `success: false`), instead of a `window.prompt`. + // (objectui#11784): `DuplicatePackageForm` (`packageActions.tsx`, shared + // with Studio's package menu) asks for the name and id by the spec's id + // rule, and the same call (`duplicatePackage`, which also refuses a 200 + // whose verdict is `success: false`) sends it, instead of a `window.prompt`. const toggleDuplicate = () => { if (dupOpen) { setDupOpen(false); return; } - startAction(() => { - setDupName(tFormat('engine.studio.landing.dupDefaultName', locale, { name: displayName })); - setDupId(`${id}-copy`); - setDupOpen(true); - }); + startAction(() => setDupOpen(true)); }; - const duplicateApp = async () => { - const target = dupId.trim(); - const name = dupName.trim(); - if (!name || !isSpecPackageId(target)) return; + const duplicateApp = async (target: string, name: string) => { setBusy('duplicate'); setMsg(null); try { @@ -1180,19 +1109,8 @@ export function PackageDetailSheet({ setBusy('adopt'); setMsg(null); try { - const r = await apiJson( - `${API}/${encodeURIComponent(id)}/adopt-orphans`, - { method: 'POST' }, - ); - const count = r.reassignedCount; - setMsg({ - kind: 'ok', - text: tFormat( - count === 1 ? 'engine.packages.detail.adoptedOne' : 'engine.packages.detail.adoptedOther', - locale, - { count }, - ), - }); + const count = await adoptLooseItems(id); + setMsg({ kind: 'ok', text: adoptedText(count, locale) }); onChanged(); } catch (e: any) { setMsg({ kind: 'err', text: e?.message ?? 'Adopt failed' }); @@ -1211,25 +1129,7 @@ export function PackageDetailSheet({ enabled ? t('engine.packages.detail.disabled', locale) : t('engine.packages.detail.enabled', locale), ); - const exportPkg = () => - run( - 'export', - async () => { - const manifest = await apiJson(`${API}/${encodeURIComponent(id)}/export`); - const blob = new Blob([JSON.stringify(manifest, null, 2)], { - type: 'application/json', - }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `${id}.package.json`; - document.body.appendChild(a); - a.click(); - a.remove(); - URL.revokeObjectURL(url); - }, - t('engine.packages.detail.exported', locale), - ); + const exportPkg = () => run('export', () => exportPackageFile(id), t('engine.packages.detail.exported', locale)); return ( @@ -1469,43 +1369,15 @@ export function PackageDetailSheet({ )} {authoring && writable && dupOpen && ( -
- setDupName(e.target.value)} - onKeyDown={(e) => { - if (e.key === 'Enter' && dupArmed && !busy) void duplicateApp(); - if (e.key === 'Escape') setDupOpen(false); - }} - placeholder={t('engine.studio.landing.dupNamePlaceholder', locale)} - aria-label={t('engine.studio.landing.dupNamePlaceholder', locale)} - data-testid="pkg-detail-dup-name-input" - className="h-7 w-full rounded-md border bg-background px-2 text-[11px] outline-none focus:ring-1 focus:ring-primary" - /> - { - if (dupArmed && !busy) void duplicateApp(); - }} - onEscape={() => setDupOpen(false)} - placeholder={t('engine.studio.landing.dupIdPlaceholder', locale)} - locale={locale} - testId="pkg-detail-dup-id-input" - /> -
- - -
-
+ void duplicateApp(target, name)} + onCancel={() => setDupOpen(false)} + locale={locale} + /> )} @@ -1690,26 +1562,13 @@ export function PackageDetailSheet({ - - - - - {tFormat('engine.packages.detail.adoptTitle', locale, { name: displayName })} - - - {t('engine.packages.detail.adoptDescription', locale)} - - - - - {t('engine.cancel', locale)} - - void adoptOrphans()}> - {t('engine.packages.detail.adoptOrphans', locale)} - - - - + void adoptOrphans()} + locale={locale} + /> @@ -1885,8 +1744,10 @@ export function PackagesPage() { // with its modules folded under it, the columns an administrator reads (Name, // Version, Status, Source, Update), a Source filter, New Package — which // lands in Studio on the new package — and none of the developer's doors: - // Import, the platform packages switch and the authoring actions stay on the - // development surface Studio opens (this page with no `face`). + // the platform packages switch and the authoring actions stay on the + // development surface (this page with no `face`). Import sits in both faces' + // headers beside New Package (objectstack#37139): it creates a package from + // a file, which is not an action on one package. const adminFace = sourceFilter.face === 'admin'; // objectstack#36908 — the console's new-package doors land here with New @@ -1909,6 +1770,30 @@ export function PackagesPage() { ); }, [newParam, adminFace, setSearchParams]); + // objectstack#37139 — Studio's 「Manage in Setup…」 lands here on one + // package (`setupPackagePath`, `?package=ID`): once the list has loaded, that + // package's detail sheet opens, where it is enabled, disabled or deleted. Read + // on arrival and dropped with a replace, as `?new=package` is above, so a + // refresh or Back does not open it again. Keyed on primitives and the loaded + // list (ui/AGENTS.md #10). + const packageParam = searchParams.get(PACKAGES_PACKAGE_PARAM); + React.useEffect(() => { + if (packageParam === null || loading) return; + const target = packages.find((p) => p.manifest.id === packageParam); + if (target) { + setSelected(target); + setDetailOpen(true); + } + setSearchParams( + (prev) => { + const next = new URLSearchParams(prev); + next.delete(PACKAGES_PACKAGE_PARAM); + return next; + }, + { replace: true }, + ); + }, [packageParam, loading, packages, setSearchParams]); + const filtered = React.useMemo(() => { const q = query.trim().toLowerCase(); return rows.filter((r) => { @@ -2093,10 +1978,10 @@ export function PackagesPage() { } icon={} refresh={{ onRefresh: () => void load(), label: t('engine.packages.refresh', locale), busy: loading }} - // objectstack#36834 — Import is a developer door: Studio's Packages - // keeps it. The administration face draws New Package alone. + // objectstack#37139 — Import beside New Package on both faces: Setup → + // Packages draws it as the development face does, and it works the same. actions={ - adminFace ? newPackageButton : <> + <> {importInput} + + + + ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/packageSource.ts b/ui/packages/app-shell/src/views/metadata-admin/packageSource.ts index bba6a9824bb..8285edfc182 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/packageSource.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/packageSource.ts @@ -211,3 +211,20 @@ export const SETUP_PACKAGES_PATH = `${packagesHref('/apps/setup')}?${PACKAGES_FA * 「Add app」 menu). The create lands in Studio on the new package. */ export const SETUP_NEW_PACKAGE_PATH = `${SETUP_PACKAGES_PATH}&${PACKAGES_NEW_PARAM}=${PACKAGES_NEW_PACKAGE_VALUE}`; + +/** + * The administration face opened on one package's row (objectstack#37139): + * `?package=ID` opens that package's detail sheet once the list has loaded, + * read once and dropped from the address like {@link PACKAGES_NEW_PARAM}. + * Page-local, like {@link PACKAGES_SOURCE_PARAM}. + */ +export const PACKAGES_PACKAGE_PARAM = 'package'; + +/** + * Setup → Packages on one package's row (objectstack#37139): Studio's package + * menu's 「Manage in Setup…」, where the package is enabled, disabled or + * deleted. + */ +export function setupPackagePath(packageId: string): string { + return `${SETUP_PACKAGES_PATH}&${PACKAGES_PACKAGE_PARAM}=${encodeURIComponent(packageId)}`; +} diff --git a/ui/packages/app-shell/src/views/studio-design/StudioBackToApp.tsx b/ui/packages/app-shell/src/views/studio-design/StudioBackToApp.tsx index c8ca1691b35..1996fe5648a 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioBackToApp.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioBackToApp.tsx @@ -28,6 +28,10 @@ * * Leaving asks first when a pillar holds unsaved work, like every other * header departure (`beforeNavigate`). + * + * objectstack#37139 — right of the name, the host may draw the package's 「⋯」 + * menu (`menu`, `StudioPackageMenu`): only where there is a current package and + * only for a `manage_metadata` holder, which the host decides. */ import * as React from 'react'; @@ -84,6 +88,7 @@ export function StudioBackToApp({ locale, beforeNavigate, navigate, + menu, }: { /** The open package, or `null` in the package-less scope. */ packageId: string | null; @@ -99,6 +104,8 @@ export function StudioBackToApp({ /** The header's unsaved-work veto: return false to stay in Studio. */ beforeNavigate: () => boolean; navigate: (path: string) => void; + /** objectstack#37139 — the package's 「⋯」 menu, drawn right of the name; absent draws none. */ + menu?: React.ReactNode; }): React.ReactElement { // Read once per visit: nothing in Studio is an app page, so the record // cannot change while the author is here. @@ -146,6 +153,7 @@ export function StudioBackToApp({ )} + {menu} 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 4a69a0730c6..c97a391c320 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx @@ -63,6 +63,8 @@ import { PACKAGE_LIST_TOAST_ID } from './PackageSwitcher.js'; import { studioEntryFallbackPath, useStudioEntryPermissions } from './studioEntryPermissions.js'; import { SETUP_PACKAGES_PATH } from '../metadata-admin/packageSource.js'; import { StudioBackToApp, type StudioAppTarget } from './StudioBackToApp.js'; +import { StudioPackageMenu } from './StudioPackageMenu.js'; +import { useCanAuthorMetadata } from '../../hooks/useCanAuthorMetadata.js'; import { type NewFlowTrigger } from './AutomationsFlowRail.js'; import { CreateTakenNotice, @@ -943,6 +945,20 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re // Setup → Packages for a principal who may open it, the "All metadata" area // for a Studio-only author (the same choice as Studio's entry). const notFoundExit = studioEntryFallbackPath(useStudioEntryPermissions()); + // objectstack#37139 — the package's 「⋯」 menu (`StudioPackageMenu`) is a + // manage_metadata holder's. A revert or an adoption changes what the package + // holds: the pillars re-read their baseline, the pending count re-reads (the + // nonce's effect above), and the other surfaces hear of it. Saved package + // info renames the bar's package name in place. + const canAuthorPackage = useCanAuthorMetadata(); + const onPackageChanged = React.useCallback(() => { + setPublishNonce((n) => n + 1); + emitMetadataRefresh(); + }, []); + const onPackageRenamed = React.useCallback( + (name: string) => setPkgEntry((prev) => (prev && prev.id === packageId ? { ...prev, name } : prev)), + [packageId], + ); React.useEffect(() => { openAccessRef.current = () => { if (confirmLeavePillar()) shellNavigate(studioPillarPath(scopeSegment, 'access', { segmentEncoding: 'verbatim' })); @@ -1412,6 +1428,23 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re locale={locale} beforeNavigate={confirmLeavePillar} navigate={shellNavigate} + // objectstack#37139 — the package's 「⋯」 menu: a current package + // (never `~org` or `~all`) that is there, and a manage_metadata holder. + menu={ + packageId !== null && !pkgMissing && canAuthorPackage ? ( + + ) : null + } /> diff --git a/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu-37139.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu-37139.test.tsx new file mode 100644 index 00000000000..f4a7a0119b6 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu-37139.test.tsx @@ -0,0 +1,476 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37139 — the 「⋯」 package menu beside the app or package name + * at the Studio top bar's left end: the door to the Packages page's + * development-face actions now that the Studio home is gone. + * + * 1. A `manage_metadata` holder on a package's Studio page sees it, right of + * the name, with the maintainer's six items in the table's order, in en + * and zh-CN. + * 2. Each item's greyed state: on a read-only package Edit package info, + * Duplicate, Revert and Adopt are greyed (the server refuses each there); + * Revert is greyed too while nothing has changed since the last publish. + * Export and Manage in Setup… are never greyed. + * 3. No 「⋯」 on `~org` or `~all` (no current package), and none for a user + * without `manage_metadata`. + * 4. Each item does what the development face's action does: the same door, + * the same confirmation, the same answer; Manage in Setup… opens Setup → + * Packages on this package's row. + * 5. The menu and the development face's sheet share one copy of each + * action (`metadata-admin/packageActions.tsx`), read off the source. + * + * The REAL `StudioDesignSurface`, metadata client and permission provider over + * a fetch stub that serves the package list, the package's drafts and the + * package doors, recording every write. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +// 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'; +// 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 { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; +import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio'; +await loadStudioCatalogue('zh'); + +let localeFixture: 'en-US' | 'zh-CN' = 'en-US'; +vi.mock('../metadata-admin/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataLocale: () => localeFixture, +})); +vi.mock('@object-ui/react', async (importOriginal) => { + const actual = await importOriginal>(); + return { ...actual, useAdapter: () => ({}) }; +}); +vi.mock('sonner', () => ({ + toast: { warning: vi.fn(), error: vi.fn(), success: vi.fn(), info: vi.fn(), message: vi.fn(), dismiss: vi.fn() }, + Toaster: () => null, +})); +vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); +vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); +vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); +vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); + +import { toast } from 'sonner'; +import { StudioDesignSurface } from './StudioDesignSurface'; +import { t, tFormat } from '../metadata-admin/i18n'; +import { setupPackagePath } from '../metadata-admin/packageSource'; +import { STUDIO_PACKAGE_MENU_ITEMS } from './StudioPackageMenu'; + +const OWN = 'com.example.sales'; +const INSTALLED = 'com.vendor.crm'; + +window.matchMedia = ((query: string) => ({ + matches: false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, +})) as unknown as typeof window.matchMedia; +(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = + (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver ?? + class { + observe() {} + unobserve() {} + disconnect() {} + }; + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); +} + +interface Write { + method: string; + path: string; + body: Record | null; +} + +const srv = { + /** The open package's pending drafts. */ + drafts: [] as Array<{ type: string; name: string }>, + writes: [] as Write[], + exports: 0, +}; + +const PACKAGE_LIST = { + success: true, + data: [ + { + manifest: { id: OWN, name: 'Sales', namespace: 'sales', version: '0.1.0', type: 'app', scope: 'project', description: 'Pipeline' }, + writable: true, + source: 'authored', + }, + { + manifest: { id: INSTALLED, name: 'Vendor CRM', namespace: 'vcrm', version: '2.0.0', type: 'app' }, + writable: false, + source: 'marketplace', + }, + ], +}; + +beforeEach(() => { + localeFixture = 'en-US'; + srv.drafts = [{ type: 'object', name: 'sales_lead' }]; + srv.writes = []; + srv.exports = 0; + vi.mocked(toast.success).mockClear(); + vi.mocked(toast.error).mockClear(); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: unknown, init?: RequestInit) => { + const url = new URL(String(input), 'http://localhost'); + const path = url.pathname; + const method = (init?.method ?? 'GET').toUpperCase(); + if (method !== 'GET') { + srv.writes.push({ method, path, body: init?.body ? JSON.parse(String(init.body)) : null }); + if (path.endsWith('/revert')) { + srv.drafts = []; + return json({ success: true, data: { success: true } }); + } + if (path.endsWith('/adopt-orphans')) return json({ success: true, data: { success: true, reassignedCount: 3, reassigned: [] } }); + if (path.endsWith('/duplicate')) return json({ success: true, data: { success: true, copiedCount: 2, failedCount: 0 } }); + return json({ success: true, data: {} }); + } + if (path === '/api/v1/packages') return json(PACKAGE_LIST); + if (path === `/api/v1/packages/${OWN}/export`) { + srv.exports += 1; + return json({ success: true, data: { manifest: { id: OWN } } }); + } + if (path === '/api/v1/meta/_drafts') { + const pkg = url.searchParams.get('package'); + return json({ drafts: pkg === OWN ? srv.drafts : [] }); + } + if (path === '/api/v1/meta/app') return json([]); + if (path === '/api/v1/meta/object') return json([]); + if (path.endsWith('/layers')) return json({ code: null, overlay: null, overlayScope: null, effective: null }); + if (/^\/api\/v1\/meta\/[^/]+\/[^/]+$/.test(path)) return json({}, 404); + return json([]); + }) as unknown as typeof fetch, + ); + // Export downloads a file: the browser half is stubbed, the request is real. + URL.createObjectURL = vi.fn(() => 'blob:export'); + URL.revokeObjectURL = vi.fn(); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +/** A `/me/permissions` answer holding exactly `held`. */ +function answer(held: string[]): MePermissionsAuthenticatedResponse { + return { + authenticated: true, + userId: 'u1', + tenantId: null, + positions: [], + hasAnyQueue: false, + objectsUsingQueues: [], + permissionSets: [], + systemPermissions: held, + objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, + fields: {}, + } as MePermissionsAuthenticatedResponse; +} + +const AUTHOR = answer(['studio.access', 'manage_metadata', 'setup.access', 'manage_platform_settings']); +const STUDIO_ONLY = answer(['studio.access']); + +function Elsewhere() { + const location = useLocation(); + return

{`${location.pathname}${location.search}`}

; +} + +function renderAt(entry: string, perms = AUTHOR) { + return render( + + + + } /> + } /> + } /> + + + , + ); +} + +const header = () => screen.getByTestId('studio-shell-header'); + +/** The package name settles in the bar (the list read answered). */ +async function settledOn(name: string) { + await waitFor(() => expect(within(header()).getByTestId('studio-back-app-name')).toHaveTextContent(name), { + timeout: 8000, + }); +} + +async function openMenu(): Promise { + const trigger = await within(header()).findByTestId('studio-package-menu', undefined, { timeout: 8000 }); + fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + return screen.findByTestId('studio-package-menu-content'); +} + +const menuItem = (id: string) => screen.getByTestId(`studio-package-menu-${id}`); +const isGreyed = (id: string) => menuItem(id).hasAttribute('data-disabled'); + +/** Wait until the pending-changes count is read (the Changes pill shows it). */ +async function pendingRead(count: number) { + if (count > 0) { + await waitFor(() => expect(within(header()).getByTestId('studio-changes-count')).toHaveTextContent(String(count)), { + timeout: 8000, + }); + } +} + +// --------------------------------------------------------------------------- +// 1. Where it is and what it holds +// --------------------------------------------------------------------------- + +const LABELS: Record<'en-US' | 'zh-CN', string[]> = { + 'en-US': ['Edit package info', 'Export', 'Duplicate as a new package', 'Revert to last publish', 'Adopt loose items', 'Manage in Setup…'], + 'zh-CN': ['编辑软件包信息', '导出', '复制为新软件包', '还原到上次发布', '收编散落项', '在设置中管理…'], +}; + +describe('the 「⋯」 package menu: right of the name, six items in the table’s order (objectstack#37139)', () => { + it.each(['en-US', 'zh-CN'] as const)('%s: a manage_metadata holder sees it beside the package name', async (locale) => { + localeFixture = locale; + renderAt(`/studio/${OWN}/data`); + await settledOn('Sales'); + const back = within(header()).getByTestId('studio-back'); + const trigger = within(back).getByTestId('studio-package-menu'); + expect(trigger).toHaveAccessibleName(locale === 'zh-CN' ? '软件包操作' : 'Package actions'); + // Right of the name, left of the Studio mark. + const order = [...back.querySelectorAll('[data-testid]')].map((n) => n.getAttribute('data-testid')); + expect(order.indexOf('studio-package-menu')).toBe(order.indexOf('studio-back-app-name') + 1); + expect(order.indexOf('studio-mark')).toBeGreaterThan(order.indexOf('studio-package-menu')); + + const content = await openMenu(); + const items = within(content).getAllByRole('menuitem'); + expect(items.map((i) => i.getAttribute('data-testid'))).toEqual( + STUDIO_PACKAGE_MENU_ITEMS.map((id) => `studio-package-menu-${id}`), + ); + expect(items.map((i) => i.textContent?.trim())).toEqual(LABELS[locale]); + // No 「发布全部草稿」: the top bar's Changes / Publish already do it. + expect(content.textContent).not.toMatch(locale === 'zh-CN' ? /发布全部|草稿/ : /Publish all|draft/i); + }); +}); + +// --------------------------------------------------------------------------- +// 2. Each item's greyed state +// --------------------------------------------------------------------------- + +describe('which items are greyed (objectstack#37139)', () => { + it.each(['en-US', 'zh-CN'] as const)('%s: a writable package with changes greys nothing', async (locale) => { + localeFixture = locale; + renderAt(`/studio/${OWN}/data`); + await settledOn('Sales'); + await pendingRead(1); + await openMenu(); + for (const id of STUDIO_PACKAGE_MENU_ITEMS) expect(isGreyed(id), id).toBe(false); + }); + + it.each(['en-US', 'zh-CN'] as const)('%s: a read-only installed package greys Edit, Duplicate, Revert and Adopt, and says why', async (locale) => { + localeFixture = locale; + renderAt(`/studio/${INSTALLED}/data`); + await settledOn('Vendor CRM'); + // The writability verdict has landed when the surface reads read-only. + await waitFor(() => expect(within(header()).getByTestId('studio-package-menu')).toBeInTheDocument(), { timeout: 8000 }); + await openMenu(); + await waitFor(() => expect(isGreyed('edit')).toBe(true), { timeout: 8000 }); + expect({ + edit: isGreyed('edit'), + export: isGreyed('export'), + duplicate: isGreyed('duplicate'), + revert: isGreyed('revert'), + adopt: isGreyed('adopt'), + manage: isGreyed('manage'), + }).toEqual({ edit: true, export: false, duplicate: true, revert: true, adopt: true, manage: false }); + const reason = t('engine.studio.pkg.readonlyHint', locale); + for (const id of ['edit', 'duplicate', 'revert', 'adopt']) { + expect(menuItem(id)).toHaveAttribute('data-disabled-reason', reason); + } + }); + + it.each(['en-US', 'zh-CN'] as const)('%s: with nothing changed since the last publish, only Revert is greyed', async (locale) => { + localeFixture = locale; + srv.drafts = []; + renderAt(`/studio/${OWN}/data`); + await settledOn('Sales'); + await openMenu(); + await waitFor(() => expect(isGreyed('revert')).toBe(true), { timeout: 8000 }); + expect(menuItem('revert')).toHaveAttribute('data-disabled-reason', t('engine.studio.packageMenu.noChanges', locale)); + for (const id of ['edit', 'export', 'duplicate', 'adopt', 'manage']) expect(isGreyed(id), id).toBe(false); + }); +}); + +// --------------------------------------------------------------------------- +// 3. Where there is none +// --------------------------------------------------------------------------- + +describe('no 「⋯」 without a current package or without manage_metadata (objectstack#37139)', () => { + it.each(['en-US', 'zh-CN'] as const)('%s: none on ~org and none on ~all', async (locale) => { + localeFixture = locale; + renderAt('/studio/~org/metadata/flow'); + await waitFor(() => expect(within(header()).getByTestId('studio-back-app-name')).toHaveTextContent(t('engine.studio.menu.orgFlows', locale)), { + timeout: 8000, + }); + expect(within(header()).queryByTestId('studio-package-menu')).toBeNull(); + cleanup(); + + renderAt('/studio/~all/metadata'); + await waitFor(() => expect(within(header()).getByTestId('studio-back-app-name')).toHaveTextContent(t('engine.studio.menu.environment', locale)), { + timeout: 8000, + }); + expect(within(header()).queryByTestId('studio-package-menu')).toBeNull(); + }); + + it.each(['en-US', 'zh-CN'] as const)('%s: none for a user without manage_metadata', async (locale) => { + localeFixture = locale; + renderAt(`/studio/${OWN}/data`, STUDIO_ONLY); + await settledOn('Sales'); + expect(within(header()).queryByTestId('studio-package-menu')).toBeNull(); + }); + + it('CONTROL: the same page with manage_metadata draws it', async () => { + renderAt(`/studio/${OWN}/data`, AUTHOR); + await settledOn('Sales'); + expect(within(header()).getByTestId('studio-package-menu')).toBeInTheDocument(); + }); +}); + +// --------------------------------------------------------------------------- +// 4. Each item does what the development face's action does +// --------------------------------------------------------------------------- + +describe('each item runs the development face’s action (objectstack#37139)', () => { + it('Export reads the export door and downloads the file', async () => { + renderAt(`/studio/${OWN}/data`); + await settledOn('Sales'); + await openMenu(); + fireEvent.click(menuItem('export')); + await waitFor(() => expect(toast.success).toHaveBeenCalledWith(t('engine.packages.detail.exported', 'en-US'))); + expect(srv.exports).toBe(1); + expect(URL.createObjectURL).toHaveBeenCalledTimes(1); + expect(srv.writes).toEqual([]); + }); + + it('Revert asks first: Cancel sends nothing; confirm sends the revert', async () => { + renderAt(`/studio/${OWN}/data`); + await settledOn('Sales'); + await pendingRead(1); + await openMenu(); + fireEvent.click(menuItem('revert')); + let dialog = await screen.findByTestId('studio-package-menu-revert-dialog'); + expect(within(dialog).getByRole('heading')).toHaveTextContent( + tFormat('engine.studio.packageMenu.revertTitle', 'en-US', { name: 'Sales' }), + ); + fireEvent.click(within(dialog).getByTestId('studio-package-menu-revert-cancel')); + await waitFor(() => expect(screen.queryByTestId('studio-package-menu-revert-dialog')).toBeNull()); + expect(srv.writes).toEqual([]); + + await openMenu(); + fireEvent.click(menuItem('revert')); + dialog = await screen.findByTestId('studio-package-menu-revert-dialog'); + fireEvent.click(within(dialog).getByTestId('studio-package-menu-revert-confirm')); + await waitFor(() => expect(toast.success).toHaveBeenCalledWith(t('engine.packages.detail.reverted', 'en-US'))); + expect(srv.writes.map((w) => `${w.method} ${w.path}`)).toEqual([`POST /api/v1/packages/${OWN}/revert`]); + // The pending count re-reads: nothing is left to publish. + await waitFor(() => expect(within(header()).queryByTestId('studio-changes-count')).toBeNull(), { timeout: 8000 }); + }); + + it('Adopt loose items asks first, then adopts and says how many moved', async () => { + renderAt(`/studio/${OWN}/data`); + await settledOn('Sales'); + await openMenu(); + fireEvent.click(menuItem('adopt')); + const dialog = await screen.findByTestId('pkg-detail-adopt-dialog'); + expect(srv.writes).toEqual([]); + fireEvent.click(within(dialog).getByTestId('pkg-detail-adopt-confirm')); + await waitFor(() => + expect(toast.success).toHaveBeenCalledWith(tFormat('engine.packages.detail.adoptedOther', 'en-US', { count: 3 })), + ); + expect(srv.writes.map((w) => `${w.method} ${w.path}`)).toEqual([`POST /api/v1/packages/${OWN}/adopt-orphans`]); + }); + + it('Duplicate opens the development face’s form on 「Copy of NAME」 and `-copy`, and sends the duplicate', async () => { + renderAt(`/studio/${OWN}/data`); + await settledOn('Sales'); + await openMenu(); + fireEvent.click(menuItem('duplicate')); + const dialog = await screen.findByTestId('studio-package-menu-duplicate-dialog'); + const form = within(dialog).getByTestId('pkg-detail-dup-form'); + expect(within(form).getByTestId('pkg-detail-dup-name-input')).toHaveValue( + tFormat('engine.studio.landing.dupDefaultName', 'en-US', { name: 'Sales' }), + ); + expect(within(form).getByTestId('pkg-detail-dup-id-input')).toHaveValue(`${OWN}-copy`); + fireEvent.click(within(form).getByRole('button', { name: t('engine.packages.detail.duplicateGo', 'en-US') })); + await waitFor(() => expect(toast.success).toHaveBeenCalledWith(t('engine.packages.detail.duplicated', 'en-US'))); + expect(srv.writes).toEqual([ + { + method: 'POST', + path: `/api/v1/packages/${OWN}/duplicate`, + body: { targetPackageId: `${OWN}-copy`, targetName: tFormat('engine.studio.landing.dupDefaultName', 'en-US', { name: 'Sales' }) }, + }, + ]); + await waitFor(() => expect(screen.queryByTestId('studio-package-menu-duplicate-dialog')).toBeNull()); + }); + + it('Edit package info opens the development face’s Edit dialog on the listed manifest', async () => { + renderAt(`/studio/${OWN}/data`); + await settledOn('Sales'); + await openMenu(); + fireEvent.click(menuItem('edit')); + const dialog = await screen.findByRole('dialog', undefined, { timeout: 8000 }); + expect(within(dialog).getByRole('heading', { name: t('engine.packages.edit.title', 'en-US') })).toBeInTheDocument(); + expect(within(dialog).getByText(OWN)).toBeInTheDocument(); + expect(srv.writes).toEqual([]); + }); + + it('Manage in Setup… opens Setup → Packages on this package’s row', async () => { + renderAt(`/studio/${OWN}/data`); + await settledOn('Sales'); + await openMenu(); + fireEvent.click(menuItem('manage')); + expect(await screen.findByTestId('elsewhere')).toHaveTextContent(setupPackagePath(OWN)); + expect(setupPackagePath(OWN)).toBe(`/apps/setup/component/developer/packages?face=admin&package=${OWN}`); + }); +}); + +// --------------------------------------------------------------------------- +// 5. One copy of each action +// --------------------------------------------------------------------------- + +const HERE = dirname(fileURLToPath(import.meta.url)); + +describe('the menu and the development face share one copy of each action (objectstack#37139)', () => { + const menu = readFileSync(resolve(HERE, 'StudioPackageMenu.tsx'), 'utf8'); + const page = readFileSync(resolve(HERE, '../metadata-admin/PackagesPage.tsx'), 'utf8'); + const shared = ['revertPackage', 'exportPackageFile', 'adoptLooseItems', 'AdoptLooseItemsDialog', 'DuplicatePackageForm', 'EditPackageDialog']; + + it.each(shared)('%s comes from packageActions in both surfaces', (name) => { + for (const source of [menu, page]) { + const imported = source.match(/import \{([^}]*)\} from '(?:\.\.\/metadata-admin\/|\.\/)packageActions\.js';/)?.[1] ?? ''; + expect(imported.split(',').map((s) => s.trim())).toContain(name); + } + }); + + it('neither surface spells the revert or adopt door itself', () => { + for (const source of [menu, page]) { + // A request spelled in place: `${…}/revert` in a template literal. + expect(source).not.toMatch(/\}\/revert`|\}\/adopt-orphans`/); + } + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu.tsx b/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu.tsx new file mode 100644 index 00000000000..030dbab4fa9 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/StudioPackageMenu.tsx @@ -0,0 +1,334 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The 「⋯」 package menu beside the app or package name at the Studio top + * bar's left end (objectstack#37139). With the Studio home gone + * (objectstack#36908), it is the door to the Packages page's development-face + * actions on the open package — the maintainer's table, in its order: + * + * 1. Edit package info — the development face's Edit dialog; greyed on a + * read-only package. + * 2. Export — the export door's file, downloaded. + * 3. Duplicate as a new package — the development face's Duplicate form, in + * a dialog. The server refuses to duplicate a read-only package + * (`DUPLICATE_SOURCE_NOT_A_BASE`) and the development face does not offer + * it there, so it is greyed there too. + * 4. Revert to last publish — the development face's Revert, asked first; + * greyed on a read-only package and while nothing has changed since the + * last publish (the pending-changes count the top bar already reads). + * 5. Adopt loose items — the development face's confirmation, then its + * adoption; greyed on a read-only package. + * 6. Manage in Setup… — Setup → Packages on this package's row, where it is + * enabled, disabled or deleted. + * + * Every request, dialog and form is the development face's own, imported from + * `metadata-admin/packageActions.tsx`; ⛔ never a second copy. What differs is + * where the answer goes: a toast, as everywhere else in Studio, instead of the + * sheet's message line. Publishing every draft is not here: the top bar's + * Changes and Publish already do it. + * + * The host draws the menu only where there is a current package (never on + * `~org` or `~all`) and only for a `manage_metadata` holder + * (`useCanAuthorMetadata`). Writability the host has not learned yet (still + * reading, or the read failed) greys nothing: the server's write gate stays the + * authority, the same courtesy posture as the rest of Studio. + */ + +import * as React from 'react'; +import { toast } from 'sonner'; +import { Copy, Download, Inbox, MoreHorizontal, Pencil, Settings, Undo2 } from 'lucide-react'; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '@object-ui/components'; +import { t, tFormat } from '../metadata-admin/i18n.js'; +import { + AdoptLooseItemsDialog, + DuplicatePackageForm, + EditPackageDialog, + adoptLooseItems, + adoptedText, + exportPackageFile, + revertPackage, +} from '../metadata-admin/packageActions.js'; +import type { PackageManifestRow } from '../metadata-admin/PackagesPage.js'; +import { setupPackagePath } from '../metadata-admin/packageSource.js'; +import { duplicatePackage, fetchListedPackageManifests } from './packages-io.js'; + +/** The menu's items, in the table's order; each `data-testid` is `studio-package-menu-`. */ +export const STUDIO_PACKAGE_MENU_ITEMS = ['edit', 'export', 'duplicate', 'revert', 'adopt', 'manage'] as const; +export type StudioPackageMenuItem = (typeof STUDIO_PACKAGE_MENU_ITEMS)[number]; + +type Busy = 'edit' | 'export' | 'duplicate' | 'revert' | 'adopt' | null; + +const failureText = (e: unknown, locale: string): string => + e instanceof Error && e.message ? e.message : t('engine.packages.detail.actionFailed', locale); + +export function StudioPackageMenu({ + packageId, + packageName, + writable, + pendingCount, + locale, + onChanged, + onRenamed, + beforeNavigate, + navigate, +}: { + /** The open package. */ + packageId: string; + /** Its display name, as the top bar shows it; the id while unknown. */ + packageName: string; + /** The server's verdict; `null` / `undefined` while unknown greys nothing. */ + writable: boolean | null | undefined; + /** The open package's pending changes; `null` while unknown greys nothing. */ + pendingCount: number | null; + locale: string; + /** A revert or an adoption changed what the package holds: the host re-reads it. */ + onChanged: () => void; + /** The package info was saved under this name. */ + onRenamed: (name: string) => void; + /** The host's unsaved-work veto: return false to stay. */ + beforeNavigate: () => boolean; + navigate: (path: string) => void; +}): React.ReactElement { + const [busy, setBusy] = React.useState(null); + const [editRow, setEditRow] = React.useState<{ manifest: PackageManifestRow } | null>(null); + const [editOpen, setEditOpen] = React.useState(false); + const [dupOpen, setDupOpen] = React.useState(false); + const [dupRefusal, setDupRefusal] = React.useState(null); + const [revertOpen, setRevertOpen] = React.useState(false); + const [adoptOpen, setAdoptOpen] = React.useState(false); + + const readOnly = writable === false; + const readOnlyReason = t('engine.studio.pkg.readonlyHint', locale); + const noChanges = pendingCount === 0; + const revertReason = readOnly ? readOnlyReason : noChanges ? t('engine.studio.packageMenu.noChanges', locale) : null; + + /** One action from start to answer: busy while it runs, a toast with its answer. */ + async function run(action: Exclude, fn: () => Promise) { + setBusy(action); + try { + toast.success(await fn()); + } catch (e) { + toast.error(failureText(e, locale)); + } finally { + setBusy(null); + } + } + + // The Edit dialog reads the package's manifest as `/api/v1/packages` lists + // it, the row the development face's sheet opens it on. + const openEdit = () => + void (async () => { + setBusy('edit'); + try { + const listed = (await fetchListedPackageManifests()).get(packageId); + if (!listed) throw new Error(t('engine.packages.loadFailed', locale)); + setEditRow({ manifest: listed.manifest as PackageManifestRow }); + setEditOpen(true); + } catch (e) { + toast.error(failureText(e, locale)); + } finally { + setBusy(null); + } + })(); + + const duplicate = async (target: string, name: string) => { + setBusy('duplicate'); + setDupRefusal(null); + try { + await duplicatePackage(packageId, target, name); + setDupOpen(false); + toast.success(t('engine.packages.detail.duplicated', locale)); + } catch (e) { + // The dialog stays open on the names the author typed, the refusal under them. + setDupRefusal(failureText(e, locale)); + } finally { + setBusy(null); + } + }; + + const item = ( + id: StudioPackageMenuItem, + icon: React.ReactNode, + label: string, + onSelect: () => void, + disabledReason: string | null = null, + ) => ( + + {icon} + {label} + + ); + const iconClass = 'mr-2 h-3.5 w-3.5'; + + return ( + <> + + + + + + {item( + 'edit', + + + + { + toast.success(t('engine.packages.edit.saved', locale)); + const name = updated?.manifest?.name; + if (typeof name === 'string' && name.trim()) onRenamed(name); + }} + /> + + busy !== 'duplicate' && setDupOpen(open)}> + + + {tFormat('engine.studio.packageMenu.duplicateTitle', locale, { name: packageName })} + {t('engine.studio.packageMenu.duplicateDescription', locale)} + + {dupOpen && ( + void duplicate(target, name)} + onCancel={() => setDupOpen(false)} + locale={locale} + /> + )} + {dupRefusal && ( +

+ {dupRefusal} +

+ )} +
+
+ + + + + {tFormat('engine.studio.packageMenu.revertTitle', locale, { name: packageName })} + {t('engine.studio.packageMenu.revertDescription', locale)} + + + {t('engine.cancel', locale)} + + void run('revert', async () => { + await revertPackage(packageId); + onChanged(); + return t('engine.packages.detail.reverted', locale); + }) + } + > + {t('engine.packages.detail.revert', locale)} + + + + + + { + setAdoptOpen(false); + void run('adopt', async () => { + const count = await adoptLooseItems(packageId); + onChanged(); + return adoptedText(count, locale); + }); + }} + locale={locale} + /> + + ); +} diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 1b5e9a52bf8..4d76a72a92e 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -3550,7 +3550,6 @@ const STUDIO_EN: Record = { 'engine.studio.menu.noMatches': 'Nothing in the menu matches.', 'engine.studio.menu.expand': 'Show the menu', 'engine.studio.menu.collapse': 'Hide the menu', - 'engine.studio.menu.typeCount': '{count} types', 'engine.studio.menu.itemCount': '{count} items', 'engine.studio.menu.orgFlows': 'Organization flows', 'engine.studio.menu.owd': 'Default sharing', @@ -3571,6 +3570,18 @@ const STUDIO_EN: Record = { 'engine.studio.backToAppTitle': 'Leave Studio and go back to {app}', 'engine.studio.backToAppTitleNoApp': 'Leave Studio and go back to your apps', 'engine.studio.mark': 'Studio', + // objectstack#37139 — the 「⋯」 package menu beside the app or package name: + // the development face's whole-package actions, for a manage_metadata holder. + 'engine.studio.packageMenu.trigger': 'Package actions', + 'engine.studio.packageMenu.editInfo': 'Edit package info', + 'engine.studio.packageMenu.duplicate': 'Duplicate as a new package', + 'engine.studio.packageMenu.revert': 'Revert to last publish', + 'engine.studio.packageMenu.manageInSetup': 'Manage in Setup…', + 'engine.studio.packageMenu.noChanges': 'Nothing has changed since the last publish.', + 'engine.studio.packageMenu.duplicateTitle': 'Duplicate “{name}” as a new package', + 'engine.studio.packageMenu.duplicateDescription': 'The copy is a new package you can change on its own. Its objects are renamed to the new package’s namespace.', + 'engine.studio.packageMenu.revertTitle': 'Revert “{name}” to its last publish?', + 'engine.studio.packageMenu.revertDescription': 'Every change made since the last publish is discarded, and the package goes back to its last published version. Discarded changes cannot be recovered.', 'engine.studio.publishTitle': 'Review and publish every pending draft in this package together', 'engine.studio.publishNoneTitle': 'No drafts pending publish', 'engine.studio.publishedAll': 'Published all drafts in this package', @@ -3651,27 +3662,8 @@ const STUDIO_EN: Record = { 'engine.studio.org.description': 'The organization’s own flows that belong to no package, such as a clone of a packaged flow. They open editable.', // ADR-0146 D11 — no link out: no Setup page copies a flow into this scope any more. 'engine.studio.org.none': 'No flows outside a package. To change a packaged flow, open its package and use New similar.', - // objectstack#36748 — the new-app step of the package dialog (`newAppDoor.ts`). - // The Studio home's app-worded dialog was removed (objectstack#36908); the - // create-package dialog's 「同时创建应用」 (objectstack#37134) runs the step - // and reads `nameTaken` and `appFailed`. The app-worded rows have no reader - // since; they stay as released rows. - 'engine.studio.newApp.title': 'New app', - 'engine.studio.newApp.description': 'Give your app a name; everything else is filled in for you. It opens as soon as it is created.', - 'engine.studio.newApp.advancedHint': 'App ID, namespace, version and type, filled in from the name.', - 'engine.studio.newApp.id': 'App ID', - 'engine.studio.newApp.help.id': 'The app’s unique ID, in reverse-domain form. It is also the app’s address.', - 'engine.studio.newApp.help.name': 'The app’s name, as people see it.', - 'engine.studio.newApp.help.description': 'What the app is for.', - 'engine.studio.newApp.help.namespace': 'A short identifier that starts the name of every object in this app (e.g. “todo” → “todo_task”, “todo_project”).', - 'engine.studio.newApp.help.version': 'The app’s version (semantic versioning).', - 'engine.studio.newApp.help.type': 'The app’s kind.', - 'engine.studio.newApp.help.defaultDatasource': 'Where every object in this app stores its data by default.', - 'engine.studio.newApp.help.dependencies': 'Other apps or modules this app builds on.', - 'engine.studio.newApp.nsDerived': 'Filled in from the app ID until you edit it.', - 'engine.studio.newApp.created': 'Created app “{name}”.', - 'engine.studio.newApp.exists': 'An app with the same ID already exists.', - 'engine.studio.newApp.failed': 'Could not create the app', + // objectstack#36748 — the new-app step of the package dialog (`newAppDoor.ts`), + // run by the create-package dialog's 「同时创建应用」 (objectstack#37134). 'engine.studio.newApp.nameTaken': 'The app “{label}” already uses the identifier “{name}”. Change the namespace under Advanced.', 'engine.studio.newApp.appFailed': '“{name}” was created, but its app could not go live: {reason}. Use Create app in the Studio top bar to try again.', // objectstack#28561 — assignments are Setup's (ADR-0146 D7): the area links diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index ca132b30608..ee668a7bdb0 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -3134,7 +3134,6 @@ const STUDIO_ZH: Record = { 'engine.studio.menu.noMatches': '菜单里没有匹配的项。', 'engine.studio.menu.expand': '展开菜单', 'engine.studio.menu.collapse': '收起菜单', - 'engine.studio.menu.typeCount': '{count} 种类型', 'engine.studio.menu.itemCount': '{count} 项', 'engine.studio.menu.orgFlows': '组织级流程', 'engine.studio.menu.owd': '默认共享', @@ -3153,6 +3152,17 @@ const STUDIO_ZH: Record = { 'engine.studio.backToAppTitle': '离开 Studio,回到 {app}', 'engine.studio.backToAppTitleNoApp': '离开 Studio,回到你的应用', 'engine.studio.mark': 'Studio', + // objectstack#37139 — 应用名或包名右侧的「⋯」软件包菜单。 + 'engine.studio.packageMenu.trigger': '软件包操作', + 'engine.studio.packageMenu.editInfo': '编辑软件包信息', + 'engine.studio.packageMenu.duplicate': '复制为新软件包', + 'engine.studio.packageMenu.revert': '还原到上次发布', + 'engine.studio.packageMenu.manageInSetup': '在设置中管理…', + 'engine.studio.packageMenu.noChanges': '上次发布之后没有改动。', + 'engine.studio.packageMenu.duplicateTitle': '将「{name}」复制为新软件包', + 'engine.studio.packageMenu.duplicateDescription': '副本是一个新的软件包,可以单独修改。其中的对象会改用新软件包的命名空间。', + 'engine.studio.packageMenu.revertTitle': '将「{name}」还原到上次发布?', + 'engine.studio.packageMenu.revertDescription': '上次发布之后的所有改动都会被丢弃,软件包回到上次发布的版本。丢弃的改动无法恢复。', 'engine.studio.publishTitle': '检查并一并发布本软件包的全部待发布草稿', 'engine.studio.publishNoneTitle': '没有待发布的草稿', 'engine.studio.publishedAll': '已发布本软件包的全部草稿', @@ -3222,24 +3232,7 @@ const STUDIO_ZH: Record = { 'engine.studio.org.hint': '不属于任何软件包的流程', 'engine.studio.org.description': '本组织自有、不属于任何软件包的流程,例如软件包流程的克隆副本。可直接编辑。', 'engine.studio.org.none': '没有不属于软件包的流程。要修改软件包中的流程,请打开它所在的软件包,使用“新建类似”。', - // objectstack#36748 — the package dialog's new-app step: one dialog creates the package and its app. - // The Studio home that opened it was removed (objectstack#36908); it stays for objectstack#37134. - 'engine.studio.newApp.title': '新建应用', - 'engine.studio.newApp.description': '给应用起个名字,其余都会自动填好。创建后立即可以打开。', - 'engine.studio.newApp.advancedHint': '应用 ID、命名空间、版本和类型,已根据名称自动填写。', - 'engine.studio.newApp.id': '应用 ID', - 'engine.studio.newApp.help.id': '应用的唯一标识,采用反向域名格式,也是应用的访问地址。', - 'engine.studio.newApp.help.name': '大家看到的应用名称。', - 'engine.studio.newApp.help.description': '这个应用是做什么的。', - 'engine.studio.newApp.help.namespace': '简短的命名空间标识;同时是本应用内每个对象名称的强制前缀(例如 “todo” → 对象名 “todo_task”、“todo_project”)。', - 'engine.studio.newApp.help.version': '应用版本(语义化版本号)。', - 'engine.studio.newApp.help.type': '应用的类型。', - 'engine.studio.newApp.help.defaultDatasource': '本应用内所有对象默认存放数据的地方。', - 'engine.studio.newApp.help.dependencies': '这个应用所依赖的其他应用或模块。', - 'engine.studio.newApp.nsDerived': '编辑前会根据应用 ID 自动填写。', - 'engine.studio.newApp.created': '已创建应用「{name}」。', - 'engine.studio.newApp.exists': '已存在相同 ID 的应用。', - 'engine.studio.newApp.failed': '创建应用失败', + // objectstack#36748 — the package dialog's new-app step, run by 「同时创建应用」 (objectstack#37134). 'engine.studio.newApp.nameTaken': '应用「{label}」已经在用标识「{name}」。请在“高级”中换一个命名空间。', 'engine.studio.newApp.appFailed': '「{name}」已创建,但应用没能上线:{reason}。可以在 Studio 顶栏点「创建应用」重试。', 'engine.studio.area.assignments.position': '此岗位的任职人员在设置中分配。',