From 9eca8925107e2f496f268d349f96206808ccb527 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 04:42:04 +0000 Subject: [PATCH 01/18] test(dogfood): a position created into a writable package binds sets from outside it The premise the App Studio create ask rests on: a position saved into a new writable package still grants its holder another package's set, a code package's set and a loose set. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- ...e-binds-outside-sets-38149.dogfood.test.ts | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 packages/qa/dogfood/test/position-in-package-binds-outside-sets-38149.dogfood.test.ts diff --git a/packages/qa/dogfood/test/position-in-package-binds-outside-sets-38149.dogfood.test.ts b/packages/qa/dogfood/test/position-in-package-binds-outside-sets-38149.dogfood.test.ts new file mode 100644 index 00000000000..ebc50273a97 --- /dev/null +++ b/packages/qa/dogfood/test/position-in-package-binds-outside-sets-38149.dogfood.test.ts @@ -0,0 +1,149 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0070 D3, ADR-0084 amendment of 2026-11-26, ADR-0150 D3/D7] A position +// the console creates INTO a writable package still confers the permission +// sets an administrator binds from outside that package: a set another +// package holds, a set a code package ships, and a loose (package-less) set. +// +// ## Why this file exists +// +// Setup's Positions and Permission sets pages create through the environment +// scope today, so a new position and a new set name no package and the set is +// written live. The App Studio create ask moves those creates into a package: +// the administrator picks a writable package (or creates one) before the +// first save, and the item is saved there as a draft and published. The +// premise that move rests on is measured here, on a real booted showcase and +// through the same REST doors the console's editor uses (`PUT +// /meta/:type/:name?mode=draft&package=ID`, then `POST +// /meta/:type/:name/publish?package=ID`): a holder of such a position is +// granted every set the position names, whatever package (or none) holds it. +// +// The read that decides it is the security catalog's `referenceCaller` +// (core `security-catalog.ts`): a position a package SHIPS resolves its +// `permissionSets` from that package's closure, while a position authored +// at runtime is the environment's reference, resolved environment-wide. A +// change that made a runtime package's position resolve from its own closure +// would refuse the loose set and the other package's set; the first case +// below goes red on that. +// +// Controls: the position really is held under the new package (the catalog +// says so), the holder really holds it, and a set the position does NOT name +// is not granted. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { resolveUserAuthzGrants, securityCatalogReaderOf } from '@objectstack/core'; +import { type VerifyStack } from '@objectstack/verify'; +import { bootShowcase } from './showcase-boot.js'; + +/** Infrastructure rows, not tenant data: the store's own posture. */ +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] }; + +/** The new writable package the position is created into. */ +const HOME = 'app.pickprobe-home'; +/** A second writable package, holding a set of its own. */ +const OTHER = 'app.pickprobe-other'; + +const POSITION = 'pkhome_reviewer'; +/** A set saved into the position's own package, as the editor saves one. */ +const OWN_SET = 'pkhome_reviewer_set'; +/** A set the second runtime package holds. */ +const OTHER_SET = 'pkother_shared_set'; +/** A set the showcase (a code package) ships (`src/security`). */ +const SHIPPED_SET = 'showcase_auditor'; +/** A set saved through the environment scope: no package holds it. */ +const LOOSE_SET = 'pickprobe_loose_set'; +/** A loose set the position does not name: never granted to its holder. */ +const UNNAMED_SET = 'pickprobe_unnamed_set'; + +const HOLDER_EMAIL = 'pick.probe.holder@example.com'; + +interface Engine { + find(object: string, options?: unknown): Promise>>; + insert(object: string, data: Record, options?: unknown): Promise; +} + +/** The organization a `single` session is active in (ADR-0131 D9). */ +const sessionOrgOf = async (s: VerifyStack): Promise => + (await (await s.kernel.getServiceAsync<{ defaultOrgId(): Promise }>('tenancy')).defaultOrgId()) ?? undefined; + +describe('a position created into a writable package binds sets from outside it', () => { + let stack: VerifyStack; + let admin: string; + let ql: Engine; + let holder: string; + + const call = async (method: string, path: string, body?: unknown) => { + const res = await stack.apiAs(admin, method, path, body); + const text = await res.text(); + let json: any = {}; + try { json = JSON.parse(text); } catch { /* not JSON */ } + return { status: res.status, json, text }; + }; + /** The console editor's create: the item's draft in the package, then its own publish. */ + const createInPackage = async (type: string, name: string, body: Record, pkg: string) => { + const draft = await call('PUT', `/meta/${type}/${name}?mode=draft&package=${encodeURIComponent(pkg)}`, body); + expect(draft.status, `draft ${type}/${name}: ${draft.text}`).toBe(200); + const live = await call('POST', `/meta/${type}/${name}/publish?package=${encodeURIComponent(pkg)}`, {}); + expect(live.status, `publish ${type}/${name}: ${live.text}`).toBe(200); + }; + /** The environment scope's create: a set written live, naming no package. */ + const createLoose = async (name: string) => { + const saved = await call('PUT', `/meta/permission/${name}`, { name, label: name, objects: {} }); + expect(saved.status, `loose permission/${name}: ${saved.text}`).toBe(200); + }; + + beforeAll(async () => { + stack = await bootShowcase(); + admin = await stack.signIn(); + ql = (await stack.kernel.getServiceAsync('objectql')) as unknown as Engine; + + for (const [id, ns] of [[HOME, 'pkhome'], [OTHER, 'pkother']] as const) { + const created = await call('POST', '/packages', { + manifest: { id, name: `Pick probe ${ns}`, version: '0.1.0', type: 'app', namespace: ns }, + }); + expect(created.status, created.text).toBe(201); + } + await createInPackage('permission', OTHER_SET, { name: OTHER_SET, label: 'Other package set', objects: {} }, OTHER); + await createInPackage('permission', OWN_SET, { name: OWN_SET, label: 'Own package set', objects: {} }, HOME); + await createLoose(LOOSE_SET); + await createLoose(UNNAMED_SET); + await createInPackage('position', POSITION, { + name: POSITION, + label: 'Pick probe reviewer', + permissionSets: [OWN_SET, OTHER_SET, SHIPPED_SET, LOOSE_SET], + }, HOME); + + await stack.signUp(HOLDER_EMAIL); + const [user] = await ql.find('sys_user', { where: { email: HOLDER_EMAIL }, limit: 1, context: SYSTEM_CTX }); + expect(user?.id, `no sys_user row for ${HOLDER_EMAIL}`).toBeTruthy(); + holder = String(user.id); + await ql.insert('sys_user_position', { id: 'usp_pick_probe', user_id: holder, position: POSITION }, { context: SYSTEM_CTX }); + }, 180_000); + + afterAll(async () => { + await stack?.stop(); + }); + + it('the position is held under the new package, and the sets under theirs', async () => { + const reader = securityCatalogReaderOf(ql); + expect(reader, 'no security catalog bound to the booted engine').toBeTruthy(); + const position = await reader!.resolve('position', POSITION); + expect(position?.packageId).toBe(HOME); + expect((position?.definition as { permissionSets?: string[] } | undefined)?.permissionSets) + .toEqual([OWN_SET, OTHER_SET, SHIPPED_SET, LOOSE_SET]); + expect((await reader!.resolve('permission', OTHER_SET))?.packageId).toBe(OTHER); + expect((await reader!.resolve('permission', OWN_SET))?.packageId).toBe(HOME); + expect((await reader!.resolve('permission', LOOSE_SET))?.packageId).toBeUndefined(); + }); + + it('a holder is granted the own set, the other package\'s set, the shipped set and the loose set', async () => { + const grants = await resolveUserAuthzGrants(ql as never, holder, { tenantId: await sessionOrgOf(stack) }); + expect(grants.positions).toContain(POSITION); + expect(grants.permissions).toEqual(expect.arrayContaining([OWN_SET, OTHER_SET, SHIPPED_SET, LOOSE_SET])); + }); + + it('control: a loose set the position does not name is not granted', async () => { + const grants = await resolveUserAuthzGrants(ql as never, holder, { tenantId: await sessionOrgOf(stack) }); + expect(grants.permissions).not.toContain(UNNAMED_SET); + }); +}); From 8c326f19cfb277572522e8384b5b4c34f63e729a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 04:46:34 +0000 Subject: [PATCH 02/18] test(dogfood): a live edit naming no package lands on the set a package holds Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- ...kage-binds-outside-sets-38149.dogfood.test.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/qa/dogfood/test/position-in-package-binds-outside-sets-38149.dogfood.test.ts b/packages/qa/dogfood/test/position-in-package-binds-outside-sets-38149.dogfood.test.ts index ebc50273a97..45c70e9c5d3 100644 --- a/packages/qa/dogfood/test/position-in-package-binds-outside-sets-38149.dogfood.test.ts +++ b/packages/qa/dogfood/test/position-in-package-binds-outside-sets-38149.dogfood.test.ts @@ -142,6 +142,22 @@ describe('a position created into a writable package binds sets from outside it' expect(grants.permissions).toEqual(expect.arrayContaining([OWN_SET, OTHER_SET, SHIPPED_SET, LOOSE_SET])); }); + // Setup's permission matrix mounts with no package and saves the set live, + // naming none (`PermissionMatrixEditPage` at the environment door). A set + // the ask put in a package must take that edit in its own row: one row of + // the name, still the package's, carrying the edit. + it('a live edit naming no package lands on the set the package holds', async () => { + const edited = await call('PUT', `/meta/permission/${OWN_SET}`, { name: OWN_SET, label: 'Own package set, edited', objects: {} }); + expect(edited.status, edited.text).toBe(200); + const rows = await ql.find('sys_metadata', { where: { type: 'permission', name: OWN_SET }, context: SYSTEM_CTX }); + const live = rows.filter((r) => r.state !== 'draft'); + expect(live.map((r) => r.package_id ?? null), JSON.stringify(rows.map((r) => [r.package_id, r.state]))).toEqual([HOME]); + const reader = securityCatalogReaderOf(ql); + const set = await reader!.resolve('permission', OWN_SET); + expect(set?.packageId).toBe(HOME); + expect((set?.definition as { label?: string } | undefined)?.label).toBe('Own package set, edited'); + }); + it('control: a loose set the position does not name is not granted', async () => { const grants = await resolveUserAuthzGrants(ql as never, holder, { tenantId: await sessionOrgOf(stack) }); expect(grants.permissions).not.toContain(UNNAMED_SET); From b8dd0d38061a132e7e3f34f5676bd88bdc541354 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 04:55:10 +0000 Subject: [PATCH 03/18] feat(app-shell): a create with no named package asks to pick or create one (WIP) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .../app-shell/src/console/AppContent.tsx | 3 +- .../src/console/ConsoleCreateAppPage.tsx | 46 +++ .../app-shell/src/views/ObjectDataPage.tsx | 11 +- .../app-shell/src/views/ObjectView.tsx | 6 +- .../app-shell/src/views/ReportNewPage.tsx | 53 ++-- .../views/metadata-admin/PackageCreateAsk.tsx | 270 ++++++++++++++++++ .../views/metadata-admin/ResourceEditPage.tsx | 37 ++- .../views/metadata-admin/ResourceListPage.tsx | 89 +++--- .../src/views/metadata-admin/anchors.ts | 8 +- .../datasource/DatasourceResourcePage.tsx | 23 +- .../src/views/metadata-admin/package-scope.ts | 17 +- .../src/views/objectViewViewCrud.tsx | 47 ++- .../src/views/objectViewViewSharing.ts | 13 +- .../src/views/runtime-metadata-persistence.ts | 166 +++++++---- .../src/views/studio-design/packages-io.ts | 4 +- ui/packages/i18n/src/namespaces/studio/en.ts | 17 ++ ui/packages/i18n/src/namespaces/studio/zh.ts | 13 + ui/packages/plugin-designer/src/index.tsx | 2 +- .../src/pages/CreateAppPage.tsx | 27 +- 19 files changed, 687 insertions(+), 165 deletions(-) create mode 100644 ui/packages/app-shell/src/console/ConsoleCreateAppPage.tsx create mode 100644 ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx diff --git a/ui/packages/app-shell/src/console/AppContent.tsx b/ui/packages/app-shell/src/console/AppContent.tsx index e154e610e60..804b2bbf59d 100644 --- a/ui/packages/app-shell/src/console/AppContent.tsx +++ b/ui/packages/app-shell/src/console/AppContent.tsx @@ -167,7 +167,8 @@ const MetadataResourceHistoryPage = routeChunk.lazy(() => import('../views/metad // App authoring + dashboard editor pages — sourced from // @object-ui/plugin-designer so third-party hosts can opt out by not // registering these routes. -const CreateAppPage = routeChunk.lazy(() => import('@object-ui/plugin-designer').then(m => m.CreateAppPage)); +// objectstack#38149 — the console's wrapper saves the new app into a package the author picks or creates. +const CreateAppPage = routeChunk.lazy(() => import('./ConsoleCreateAppPage.js').then(m => m.ConsoleCreateAppPage)); const EditAppPage = routeChunk.lazy(() => import('@object-ui/plugin-designer').then(m => m.EditAppPage)); const DashboardDesignPage = routeChunk.lazy(() => import('@object-ui/plugin-designer').then(m => m.DashboardDesignPage)); diff --git a/ui/packages/app-shell/src/console/ConsoleCreateAppPage.tsx b/ui/packages/app-shell/src/console/ConsoleCreateAppPage.tsx new file mode 100644 index 00000000000..fd573c0611b --- /dev/null +++ b/ui/packages/app-shell/src/console/ConsoleCreateAppPage.tsx @@ -0,0 +1,46 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38149 — the console's create-app route (`/apps/:app/create-app`, + * reached from the no-apps call to action and from App Management): the + * plugin-designer wizard, whose new app is saved into a package the author + * picks or creates first (`PackageCreateAsk.tsx`), never naming none. The app + * is saved as Studio's new-app door saves it (`newAppDoor.ts`): a draft in + * that package under the first-write pin, then that one item's publish, so it + * opens at once. Cancel writes nothing and keeps the wizard open. + */ + +import * as React from 'react'; +import { CreateAppPage } from '@object-ui/plugin-designer'; +import { usePackageCreateAsk } from '../views/metadata-admin/PackageCreateAsk.js'; +import { translateMetadataType, useMetadataLocale } from '../views/metadata-admin/i18n.js'; +import { useMetadataClient } from '../views/metadata-admin/useMetadata.js'; +import { publishSavedItem } from '../views/studio-design/studioSaveBar.js'; +import { draftReceiptVersion } from '../views/metadata-admin/DraftConflictDialog.js'; + +export function ConsoleCreateAppPage() { + const client = useMetadataClient(); + const locale = useMetadataLocale(); + const { ask, dialog } = usePackageCreateAsk(); + const saveApp = React.useCallback( + async (name: string, app: Record): Promise => { + const packageId = await ask({ typeLabel: translateMetadataType('app', locale, 'App') }); + if (!packageId) return false; + const receipt = await client.save('app', name, app, { mode: 'draft', packageId, ifNoneMatch: '*' }); + const live = await publishSavedItem( + client, + { type: 'app', name, packageId, draftVersion: draftReceiptVersion(receipt) }, + false, + ); + if (!live.ok) throw live.error; + return true; + }, + [ask, client, locale], + ); + return ( + <> + + {dialog} + + ); +} diff --git a/ui/packages/app-shell/src/views/ObjectDataPage.tsx b/ui/packages/app-shell/src/views/ObjectDataPage.tsx index 1e7d1be155d..74d51693623 100644 --- a/ui/packages/app-shell/src/views/ObjectDataPage.tsx +++ b/ui/packages/app-shell/src/views/ObjectDataPage.tsx @@ -92,7 +92,8 @@ import { RECORD_PAGE_PUSHED_STATE } from './recordPagePush.js'; import { PageHeader } from '../layout/PageHeader.js'; import { useMetadataClient } from './metadata-admin/useMetadata.js'; import { createRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; -import { useRuntimeCreateApp } from './objectViewViewCrud.js'; +import { reportViewNotSaved, useRuntimeCreateApp } from './objectViewViewCrud.js'; +import { useMetadataLocale } from './metadata-admin/i18n.js'; import { buildNewViewSpec } from './newViewSpec.js'; import { CreateViewDialog } from './CreateViewDialog.js'; import { @@ -336,7 +337,8 @@ export function ObjectDataPage({ dataSource, objects }: any) { const { appName, objectName } = useParams(); const { t, language } = useObjectTranslation(); // objectstack#35624 — the app Save as view saves the new view into. - const createApp = useRuntimeCreateApp(t); + const createApp = useRuntimeCreateApp(); + const metadataLocale = useMetadataLocale(); const { objectLabel, objectPluralLabel, fieldLabel, translateOptions } = useObjectLabel(); const navigate = useNavigate(); const [searchParams, setSearchParams] = useSearchParams(); @@ -838,6 +840,8 @@ export function ObjectDataPage({ dataSource, objects }: any) { } return true; } catch (err) { + // objectstack#38149 — no package took it: nothing was written. + if (reportViewNotSaved(err, metadataLocale)) return false; console.error('[ObjectDataPage] Failed to save view:', err); // objectui#11578: a refused save is SAID, with the door's own message // (the field-anchored issues of a 422, or the refusal's text), and @@ -849,7 +853,7 @@ export function ObjectDataPage({ dataSource, objects }: any) { return false; } }, - [columns, urlFilters, metadataClient, dataSource, navigate, objectName, previewDrafts, t, createApp], + [columns, urlFilters, metadataClient, dataSource, navigate, objectName, previewDrafts, t, createApp, metadataLocale], ); // ─── The CRUD affordance matrix for this surface (#5164) ────────────── @@ -1072,6 +1076,7 @@ export function ObjectDataPage({ dataSource, objects }: any) { return (
+ {createApp.askDialog} {sourceCrumbs}
+ {/* objectstack#38149 — the package ask a view create opens. */} + {packageAskDialog} + {sharingApp.askDialog} {/* objectstack#25992 slice 10: the record pane moved to `./objectViewRecordOverlay.tsx`. On a phone no pane is mounted: a row opens the record's page (objectstack#27058). */} diff --git a/ui/packages/app-shell/src/views/ReportNewPage.tsx b/ui/packages/app-shell/src/views/ReportNewPage.tsx index 167448556f0..5ecb4d79eb2 100644 --- a/ui/packages/app-shell/src/views/ReportNewPage.tsx +++ b/ui/packages/app-shell/src/views/ReportNewPage.tsx @@ -41,10 +41,12 @@ import type { ReportDraft } from '@object-ui/plugin-report'; import { ReportBuilderHost } from './ReportBuilderHost.js'; import { useDesignModeActive, useHoldDesignModeOut } from '../layout/designMode.js'; import { - resolveRuntimeCreatePackage, + isRuntimeCreateNotSaved, + pickRuntimeCreatePackage, saveAndPublishInPackage, - saveAndPublishRuntimeMetadata, } from './runtime-metadata-persistence.js'; +import { runtimeCreateRefusalText, usePackageCreateAsk } from './metadata-admin/PackageCreateAsk.js'; +import { useMetadataLocale } from './metadata-admin/i18n.js'; import { draftBarPackageOf } from '../preview/DraftPreviewBar.js'; import { useMetadataClient } from './metadata-admin/useMetadata.js'; import { useMetadata } from '../providers/MetadataProvider.js'; @@ -122,15 +124,27 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { // objectstack#36906, objectstack#37261 — a new report is saved in the app's // package, where Studio's report list finds it, as a new view made in an app // is (`resolveRuntimeCreatePackage`): the package when it is writable, else - // its customization package through the ensure door, else, when neither can - // be had, naming no package, and a notice says so. One rule for both ways in: - // Studio's report list and the app's own reports index. Outside any app it - // names no package, as a view does. + // its customization package through the ensure door. One rule for both ways + // in: Studio's report list and the app's own reports index. + // objectstack#38149 — when neither can be had, or outside any app, the + // author picks a package or creates one before anything is written; in a + // system app the report is refused, naming where to make it instead. const appPackageId = draftBarPackageOf(appName, apps as Parameters[1]); + const { ask: askPackage, dialog: packageAskDialog } = usePackageCreateAsk(); + const metadataLocale = useMetadataLocale(); const handleSave = React.useCallback( async (draft: ReportDraft): Promise => { if (!metadataClient) return false; + let packageId: string; + try { + packageId = await pickRuntimeCreatePackage({ packageId: appPackageId, askPackage }, 'report'); + } catch (err) { + if (!isRuntimeCreateNotSaved(err)) throw err; + const refusal = runtimeCreateRefusalText(err, 'report', metadataLocale); + if (refusal) toast.error(t('form.saveError'), { description: refusal }); + return false; + } await loadHanRomanizer().catch(() => {}); const taken = new Set(((reports as Array<{ name?: unknown }>) ?? []).map((r) => String(r?.name ?? ''))); // A report needs a name to be listed by: one left blank is saved under @@ -150,19 +164,11 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { } const body = { ...draft, label, name }; const ctx = { metadataClient, dataSource: dataSource as any }; - const packageId = await resolveRuntimeCreatePackage(appPackageId, 'report'); - const outcome = packageId - ? await saveAndPublishInPackage('report', name, body, packageId, ctx) - : await saveAndPublishRuntimeMetadata('report', name, body, ctx); + const outcome = await saveAndPublishInPackage('report', name, body, packageId, ctx); if (outcome === 'pending-draft') { toast.error(t('form.saveError'), { description: t('report.builder.pendingDraft') }); return false; } - // The app's package (or its customization package) could not be had, - // so the report was saved naming no package: Studio's report list does - // not show it. Say so, whichever way the builder was opened, as a new - // view saved outside its app does (`onSavedOutsideApp`). - if (appPackageId && !packageId) toast.info(t('report.builder.savedOutsideApp')); } catch (err) { toast.error(t('form.saveError'), { description: formatMetadataError(err), @@ -177,7 +183,7 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { }); return true; }, - [metadataClient, reports, language, dataSource, refresh, navigate, appName, t, studioReturn, appPackageId], + [metadataClient, reports, language, dataSource, refresh, navigate, appName, t, studioReturn, appPackageId, askPackage, metadataLocale], ); if (loading || !isResolved) { @@ -212,11 +218,14 @@ export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) { } return ( - + <> + + {packageAskDialog} + ); } diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx new file mode 100644 index 00000000000..d1b4e25de11 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx @@ -0,0 +1,270 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38149 — the create ask: a create that names no package asks the + * person to pick a package or create one, before anything is written + * (ADR-0070 D3, ADR-0084's amendment of 2026-11-26: "When no package resolves, + * the interface asks the person to pick a package or create one"; ruling + * 7184753035 on topic objectstack#37424). + * + * One component, every create path: Setup's metadata lists and the item + * editor (`ResourceListPage`, `ResourceEditPage`), Studio's cross-package leg, + * a new view or report in an app (`runtime-metadata-persistence.ts`) and the + * console's create-app wizard. + * + * Invariants: + * - The choose list holds the packages the server says this caller may + * write (`writable: true` on `GET /api/v1/packages`, read through + * {@link fetchPackages}), never a client guess, and never a kernel package. + * A read-only base appears only as its `.custom` pair, and only once that + * pair is a listed writable package. + * - The heuristic pick a caller has (the current app's package, the package + * owning the most rows of the type) is pre-selected, never taken as the + * answer: the person confirms it. + * - "Create a new one" reuses the Packages page's create dialog + * ({@link CreatePackageDialog}); the package it creates is the answer. + * - The answer is a package id; Cancel answers `null`, and the caller then + * writes nothing. + */ + +import * as React from 'react'; +import { + Button, + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + Label, + RadioGroup, + RadioGroupItem, +} from '@object-ui/components'; +import { fetchPackages, type PkgEntry } from '../studio-design/packages-io.js'; +import { CreatePackageDialog } from './PackagesPage.js'; +import { t, tFormat, useMetadataLocale } from './i18n.js'; + +/** + * The location-state key a list's package repair writes beside the + * `?package=` it repaired, holding that package id: the mark that tells a + * heuristic pick from a package the person named (a link, or the scope + * selector, writes no such state). Kept by the list's own address writes. + */ +export const PACKAGE_PICKED_STATE = 'objectui.packagePicked'; + +/** What a caller asks with. */ +export interface PackageAskRequest { + /** The heuristic pick, pre-selected when the list holds it. */ + preselect?: string | null; + /** The type being created, as the reader reads it; names the question. */ + typeLabel?: string; +} + +/** The packages the ask offers: the server's writable verdict, kernel packages out, by name. */ +export function packageAskOptions(entries: readonly PkgEntry[]): PkgEntry[] { + return entries + .filter((p) => p.writable && !p.kernel) + .sort((a, b) => a.name.localeCompare(b.name)); +} + +type ListState = { status: 'loading' } | { status: 'read'; options: PkgEntry[] } | { status: 'failed'; error: string }; + +export function PackageCreateAskDialog({ + open, + preselect, + typeLabel, + onAnswer, + readPackages = fetchPackages, +}: PackageAskRequest & { + open: boolean; + /** The chosen or created package id, or `null` for Cancel. */ + onAnswer: (packageId: string | null) => void; + /** The list read; a test hands its own. */ + readPackages?: () => Promise; +}) { + const locale = useMetadataLocale(); + const [list, setList] = React.useState({ status: 'loading' }); + const [chosen, setChosen] = React.useState(null); + const [creating, setCreating] = React.useState(false); + const answeredRef = React.useRef(false); + + React.useEffect(() => { + if (!open) return; + answeredRef.current = false; + setCreating(false); + setList({ status: 'loading' }); + setChosen(null); + let cancelled = false; + readPackages() + .then((entries) => { + if (cancelled) return; + const options = packageAskOptions(entries); + setList({ status: 'read', options }); + setChosen(preselect && options.some((p) => p.id === preselect) ? preselect : null); + }) + .catch((err: unknown) => { + if (!cancelled) setList({ status: 'failed', error: err instanceof Error ? err.message : String(err) }); + }); + return () => { + cancelled = true; + }; + }, [open, preselect, readPackages]); + + const answer = (packageId: string | null) => { + if (answeredRef.current) return; + answeredRef.current = true; + onAnswer(packageId); + }; + + const options = list.status === 'read' ? list.options : []; + const title = typeLabel + ? tFormat('engine.packageAsk.titleNamed', locale, { type: typeLabel }) + : t('engine.packageAsk.title', locale); + + return ( + <> + { + if (!next && !creating) answer(null); + }} + > + + + {title} + {t('engine.packageAsk.description', locale)} + + {list.status === 'loading' && ( +

+ {t('engine.packageAsk.loading', locale)} +

+ )} + {list.status === 'failed' && ( +

+ {tFormat('engine.packageAsk.loadFailed', locale, { error: list.error })} +

+ )} + {list.status === 'read' && options.length === 0 && ( +

+ {t('engine.packageAsk.none', locale)} +

+ )} + {options.length > 0 && ( +
+ + setChosen(value)} + className="max-h-64 overflow-y-auto rounded-md border p-1" + data-testid="package-create-ask-options" + > + {options.map((p) => ( + + ))} + +
+ )} + + +
+ + +
+
+
+
+ { + if (!next) setCreating(false); + }} + onCreated={(id) => answer(id)} + /> + + ); +} + +/** + * The ask as a promise: `ask()` opens the dialog and resolves with the chosen + * or created package id, or `null` on Cancel. The caller renders `dialog`. + * A second `ask()` while one is open answers the first `null`. + */ +export function usePackageCreateAsk(): { + ask: (request?: PackageAskRequest) => Promise; + dialog: React.ReactElement; +} { + const [pending, setPending] = React.useState< + (PackageAskRequest & { resolve: (id: string | null) => void }) | null + >(null); + const pendingRef = React.useRef(pending); + pendingRef.current = pending; + const ask = React.useCallback( + (request: PackageAskRequest = {}) => + new Promise((resolve) => { + pendingRef.current?.resolve(null); + setPending({ ...request, resolve }); + }), + [], + ); + // An unmount answers the open ask, so no caller waits for ever. + React.useEffect(() => () => pendingRef.current?.resolve(null), []); + const onAnswer = React.useCallback((id: string | null) => { + pendingRef.current?.resolve(id); + setPending(null); + }, []); + const dialog = ( + + ); + return { ask, dialog }; +} + +/** + * objectstack#38149 — what a console create that no package could take says + * (decisions Q-b of topic objectstack#37424, answered C): in a system app the + * reason and where to go instead (My views for a view, a business app for + * either), and for a caller the ensure door refuses, the door's own reason. + * `null` for a cancelled ask, which says nothing. + */ +export function runtimeCreateRefusalText( + notSaved: { reason: 'cancelled' | 'system-app' | 'caller-refused'; message: string }, + kind: 'view' | 'report', + locale: string, +): string | null { + if (notSaved.reason === 'cancelled') return null; + if (notSaved.reason === 'system-app') { + return t(kind === 'view' ? 'engine.packageAsk.systemApp.view' : 'engine.packageAsk.systemApp.report', locale); + } + return tFormat('engine.packageAsk.callerRefused', locale, { reason: notSaved.message }); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index d3cfb801c2e..a88566330e6 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -125,6 +125,7 @@ import { readDraftForSave, useDraftSaveGuard, } from './DraftConflictDialog.js'; +import { usePackageCreateAsk } from './PackageCreateAsk.js'; // objectstack#36902 — Save takes effect at once; the AI draft's notice is the designers'. import { isAiDraft, publishDetailSave } from './detailSaveAtOnce.js'; import { StudioAiDraftNotice } from '../studio-design/StudioAiDraftNotice.js'; @@ -686,7 +687,9 @@ function MetadataResourceEditPageImpl({ embedded, }: MetadataResourceEditPageImplProps) { const navigate = useNavigate(); - const [searchParams] = useSearchParams(); + const [searchParams, setSearchParams] = useSearchParams(); + // objectstack#38149 — a create whose address names no package asks for one first. + const { ask: askPackage, dialog: packageAskDialog } = usePackageCreateAsk(); // ADR-0048 — the owning package of the item being edited, carried on the // edit URL as `?package=` (emitted by the metadata list links). Scopes the // layered/draft read so a same-name collision resolves to the right @@ -2115,7 +2118,30 @@ function MetadataResourceEditPageImpl({ // (`publishDetailSave`), never the package's batch. The draft binds to // the active software package (`?package=`) when the URL carries one; // the publish names the same package and member. - const activePackage = readActivePackageBinding(); + // + // objectstack#38149 (ADR-0070 D3, ADR-0084's amendment of 2026-11-26) — + // a create whose address names no package (a deep link, Studio's + // cross-package leg, Setup's catalog) asks the person to pick a package + // or create one before anything is written, and the address names it + // from then on, so a retried Save and the item it lands on keep it. + // Cancel writes nothing. + let activePackage = readActivePackageBinding(); + if (createMode && !activePackage) { + const chosen = await askPackage({ typeLabel: translateMetadataType(type, locale, entry?.label ?? type) }); + if (!chosen) { + setSaving(false); + return; + } + activePackage = chosen; + setSearchParams( + (prev) => { + const next = new URLSearchParams(prev); + next.set('package', chosen); + return next; + }, + { replace: true }, + ); + } const saveOptions = { force, mode: 'draft' as const, @@ -2138,6 +2164,8 @@ function MetadataResourceEditPageImpl({ if (createMode) { // objectui#7611 — a type whose edit page writes the live item creates // it live too (`createLive`): nothing is left in the draft to publish. + // objectstack#38149 — a create names a package now (the ask above), so + // such a type takes the draft-and-publish path like every other. const live = !!config.createLive && !activePackage; const receipt = await client.save(type, savedName, itemToSave, { ...(live ? { force } : saveOptions), ifNoneMatch: '*' }); wroteDraft = !live; @@ -2273,7 +2301,9 @@ function MetadataResourceEditPageImpl({ // author was working in. Without this the param is dropped and the // editor falls back to the user's default package, where the freshly // saved draft doesn't exist — so it reloads a blank form. - const qs = searchParams.toString(); + const landing = new URLSearchParams(searchParams); + if (activePackage) landing.set('package', activePackage); + const qs = landing.toString(); navigate(`../${encodeURIComponent(savedName)}${qs ? `?${qs}` : ''}`, { relative: 'path', // objectstack#36906 — in a Studio package's area a new dashboard or @@ -4060,6 +4090,7 @@ function MetadataResourceEditPageImpl({ {/* objectui#11773 — the draft-version conflict, apart from the destructive-change confirmation above: two different 409s. */} {draftConflictDialog} + {packageAskDialog} {/* objectui#13333 — reset / delete / discard-draft / discard the AI's draft, asked in-app. */} (routeLocation.state); + routeLocationStateRef.current = routeLocation.state; React.useEffect(() => { if (navigationType !== 'REPLACE') setQueryDraft(urlListState.query); }, [routeLocation.key, navigationType, urlListState.query]); @@ -262,7 +264,9 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string next.delete(LIST_PAGE_PARAM); return next; }, - { replace: true }, + // objectstack#38149 — the location state carries the package repair's + // own-write mark, which a filter or sort write keeps. + { replace: true, state: routeLocationStateRef.current }, ); }, [setSearchParams], @@ -476,7 +480,9 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string if (!activePackage) return; const next = new URLSearchParams(searchParams); next.set('package', activePackage); - setSearchParams(next, { replace: true }); + // objectstack#38149 — the repair marks its own write: a package it wrote + // from a heuristic pick is not one the person named, so a create still asks. + setSearchParams(next, { replace: true, state: { [PACKAGE_PICKED_STATE]: activePackage } }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [projectPackages, urlPackage, items, activePackage, appPackage, host]); @@ -488,10 +494,21 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string ? `?package=${encodeURIComponent(activePackage)}` : ''; - // ADR-0070 D3 — never start a create that would orphan the item. When a real - // writable base exists, create into it (defaulting away from the Local/null - // scope); when none exists yet, prompt to create a base first. - const [showCreateBase, setShowCreateBase] = React.useState(false); + // objectstack#38149 (ADR-0070 D3, ADR-0084's amendment of 2026-11-26) — a + // create that names no package asks the person to pick one or create one + // (`PackageCreateAsk.tsx`), and writes nothing until they answer. A package + // is NAMED by the area's route, or by a `?package=` the person put in the + // address (a link that names it, or a choice in the scope selector). The + // heuristic pick — the current app's package, the package owning the most + // rows of the type, the first — and the address the repair above wrote from + // it are not named: the ask pre-selects that pick instead. + const { ask: askPackage, dialog: packageAskDialog } = usePackageCreateAsk(); + const pickedState = (routeLocation.state as Record | null | undefined)?.[PACKAGE_PICKED_STATE]; + const packageNamed = + !!urlPackage && !!projectPackages?.some((p) => p.id === urlPackage) && pickedState !== urlPackage; + // Packages load only for the package scope; the environment scope and the + // area never wait on them. New waits with them (objectstack#38149). + const packagesPending = !envScope && !host && projectPackages === null; // objectstack#36897 — in the Studio area an object or a flow is created in // the list's own dialog (`MetadataListCreateDialog`), and on a read-only // base every create lands in the base's `.custom` pair (ADR-0146 D3) — where @@ -500,40 +517,32 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string const createInPair = !!host?.readOnly && host.pairCreate === true; const createInDialog = !!host?.packageId && LIST_CREATE_DIALOG_TYPES.includes(type); const [createOpen, setCreateOpen] = React.useState(false); - const handleCreate = React.useCallback(() => { + const handleCreate = React.useCallback(async () => { if (createInDialog) { setCreateOpen(true); return; } - // An environment-authored item belongs to no package (ADR-0131 D3). - if (envScope) { - navigate(`./new?${ENVIRONMENT_SCOPE_QUERY}`); - return; - } // The Studio area creates into its own package. if (host?.packageId) { navigate(`./new${pkgSuffix}`); return; } - const bases = projectPackages ?? []; - // The cross-package leg creates into the package Setup's list would pick; - // the area then opens that package's create (`areaLocationRedirect`). - if (allLeg) { - const pick = pickedPackage ?? bases[0]?.id; - if (pick) navigate(`./new?package=${encodeURIComponent(pick)}`); - else if (projectPackages !== null) setShowCreateBase(true); + if (packagesPending) return; + // Setup's list, scoped to a package the person named. + if (!envScope && !allLeg && packageNamed && activePackage) { + navigate(`./new?package=${encodeURIComponent(activePackage)}`); return; } - if (projectPackages !== null && bases.length === 0) { - setShowCreateBase(true); - return; - } - if (bases.length > 0 && !activePackage) { - navigate(`./new?package=${encodeURIComponent(bases[0].id)}`); - return; - } - navigate(`./new${pkgSuffix}`); - }, [projectPackages, activePackage, pickedPackage, pkgSuffix, navigate, envScope, host?.packageId, allLeg, createInDialog]); + // Setup's catalog (positions and permission sets, decisions Q-a of topic + // objectstack#37424), the cross-package leg, and a Setup list on a + // heuristic pick: ask. The environment scope keeps its own address. + const chosen = await askPackage({ + preselect: envScope ? null : pickedPackage, + typeLabel: translateMetadataType(type, locale, entry?.label ?? type), + }); + if (!chosen) return; + navigate(`./new?${envScope ? `${ENVIRONMENT_SCOPE_QUERY}&` : ''}package=${encodeURIComponent(chosen)}`); + }, [activePackage, pickedPackage, pkgSuffix, navigate, envScope, host?.packageId, allLeg, createInDialog, packagesPending, packageNamed, askPackage, type, locale, entry?.label]); // objectui#7611 — the activation state the switch column shows. Re-read on // the list's own refresh, never on an unrelated render. The anchors arrive @@ -868,10 +877,6 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string // write: a type with no runtime write channel is read-only for the operator // too, and its page says nothing about the wall. const walledDeciding = walled && typeWritable; - // Packages load only for the package scope; the environment scope and the - // area never wait on them. - const packagesPending = !envScope && !host && projectPackages === null; - // Localise a console column's header through `engine.list.col.`. A // served header is already in the reader's locale and is shown as served. const localizeColumnLabel = (col: { key: string; label: string; labelLocalized?: boolean }) => { @@ -919,7 +924,8 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string const studioNewButton = ( diff --git a/ui/packages/app-shell/src/views/metadata-admin/anchors.ts b/ui/packages/app-shell/src/views/metadata-admin/anchors.ts index d6e87cbb74c..af64381e933 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/anchors.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/anchors.ts @@ -444,8 +444,12 @@ export function registerBuiltinAnchors(): void { { from: 'label', to: 'name', transform: 'slugify', untilUserEdits: true }, ], createDefaults: { objects: {} }, - // The set's EditPage, `PermissionMatrixEditPage`, edits the live set - // outside a package and reads no draft (objectui#7611). + // The set's EditPage, `PermissionMatrixEditPage`, edits the live set and + // reads no draft (objectui#7611). objectstack#38149 — a create asks for + // its package first, so a new set is saved as a draft there and published + // at once (`createLive` holds only for a package-less create, which the + // editor no longer starts); the matrix's live save of it, naming no + // package, lands on that package's row. createLive: true, }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.tsx b/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.tsx index 9eb745ab9f5..8ab5ab48fc7 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.tsx @@ -33,8 +33,12 @@ * - **Test** a connection (saved → `POST …/:name/test`; draft in the editor → * `POST …/test`). * - **Sync objects**: introspect remote tables (`GET …/remote-tables`), pick - * which to import, generate an object definition for each (`POST …/object-draft`), - * and create it through the normal metadata channel (`MetadataClient.save('object', …)`). + * which to import, and import each through the federation's import door + * (`POST …/:name/external/tables/:remote/import`), which drafts the object + * and saves it where the server's import landing puts it: the datasource's + * own package, its read-only base's `.custom` pair, or no package for a + * datasource that has none (objectstack#38149; the landing is the server's, + * never chosen here). * Offered only on a federation source (`offersSync`, objectui#13318); a * managed row says why it has none (`explainsNoSync`). Once * an object is created the dialog stays open on the result: it links each @@ -811,13 +815,14 @@ export function DatasourceResourcePage(_props: { type?: string }): React.ReactEl const failed: unknown[] = []; for (const table of selected) { try { - const { draft } = await api(`/api/v1/datasources/${encodeURIComponent(syncName)}/object-draft`, { - method: 'POST', - body: JSON.stringify({ table }), - }); - await metaClient.save('object', draft.name, draft.definition); - const label = draft.definition?.label; - created.push({ name: draft.name, label: typeof label === 'string' ? label : undefined }); + // objectstack#38149 — the import door, never a client save naming no + // package: the server lands the object in the datasource's package. + const { object } = await api( + `/api/v1/datasources/${encodeURIComponent(syncName)}/external/tables/${encodeURIComponent(table)}/import`, + { method: 'POST', body: JSON.stringify({}) }, + ); + const label = object.definition?.label; + created.push({ name: String(object.name), label: typeof label === 'string' ? label : undefined }); } catch (err) { failures.push(`${table}: ${(err as Error).message}`); failed.push(err); diff --git a/ui/packages/app-shell/src/views/metadata-admin/package-scope.ts b/ui/packages/app-shell/src/views/metadata-admin/package-scope.ts index fce84010d0f..4d0f4e8441c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/package-scope.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/package-scope.ts @@ -8,11 +8,18 @@ const SYSTEM_SCOPES = new Set(['system', 'cloud']); * valid authoring destinations (ADR-0070 D2). Code/installed (system|cloud) * packages are filtered out. * - * There is no package-less "Local / Custom" scope: every runtime-authored item - * lives in a writable base (ADR-0070 D1/D5 — the kernel rejects orphan creates - * with `writable_package_required`, and legacy orphans are adopted into a base), - * so the selector never offers an orphan bucket. The kernel keeps `null` / - * `sys_metadata` provenance only as a read-side rehydration tag for legacy rows. + * There is no package-less "Local / Custom" scope, so the selector never + * offers an orphan bucket. A create in the console names its package: where + * none is named, the person is asked to pick one or create one + * (`PackageCreateAsk.tsx`, objectstack#38149, ADR-0070 D3). The kernel does + * NOT yet refuse a create that names no package — the metadata door still + * accepts a `null` package and stores the row package-less (a loose item, + * which Packages → Adopt loose items moves into a base); that refusal is the + * kernel-close card's of topic objectstack#37424. Until it lands, the ask is + * the console's only guard. + * + * These options carry no writability: the server's `writable` verdict is read + * where a create's package is chosen (the ask), not here. */ export function buildPackageScopeOptions( rawList: unknown[] | null | undefined, diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index 992001acf36..f3d42e95239 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -8,7 +8,7 @@ * component reads the returned handlers. */ -import { useCallback, useEffect, useMemo, useRef, type Dispatch, type SetStateAction } from 'react'; +import { useCallback, useEffect, useMemo, useRef, type Dispatch, type ReactElement, type SetStateAction } from 'react'; import { useParams, type useNavigate } from 'react-router-dom'; import { formatMetadataError } from '@object-ui/data-objectstack'; import { viewSaveRefusalText } from './viewSaveRefusal.js'; @@ -20,7 +20,9 @@ import type { usePreviewDrafts } from '../preview/PreviewModeContext.js'; import { isSavedViewId } from '../utils/viewIdentity.js'; import type { useConsoleActionRuntime } from '../hooks/useConsoleActionRuntime.js'; import type { useMetadataClient } from './metadata-admin/useMetadata.js'; -import { persistRuntimeMetadata, createRuntimeMetadata, saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; +import { persistRuntimeMetadata, createRuntimeMetadata, isRuntimeCreateNotSaved, saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; +import { runtimeCreateRefusalText, usePackageCreateAsk } from './metadata-admin/PackageCreateAsk.js'; +import { useMetadataLocale } from './metadata-admin/i18n.js'; import type { RuntimeCreateApp, SaveAndPublishOutcome } from './runtime-metadata-persistence.js'; import type { DraftVersionGuard } from './metadata-admin/draftVersionGuard.js'; import { draftBarPackageOf } from '../preview/DraftPreviewBar.js'; @@ -37,28 +39,38 @@ import { FILTER_FOLD_REFUSAL_KEYS } from './viewFilterFold.js'; * objectstack#35624 — the app a view created here is saved into * (`RuntimePersistCtx.app`): the routed app's package by the draft preview * bar's own rule (`draftBarPackageOf`), so the bar counts and publishes the - * view the create wrote. When the create could not be saved into the app, the - * author is told where it went instead. + * view the create wrote. objectstack#38149 — when no package of the app can + * be had, the author is asked to pick or create one (`askPackage`); the + * caller renders `askDialog`. */ -export function useRuntimeCreateApp(t: ReturnType['t']): RuntimeCreateApp { +export function useRuntimeCreateApp(): RuntimeCreateApp & { askDialog: ReactElement } { const { appName } = useParams(); const { apps } = useMetadata(); const packageId = draftBarPackageOf(appName, apps as Parameters[1]); - // Memoised for cost only: the create reads the two fields, never the identity. + const { ask, dialog } = usePackageCreateAsk(); + // Memoised for cost only: the create reads the fields, never the identity. return useMemo( () => ({ packageId, - onSavedOutsideApp: () => { - toast.info(t('view.savedOutsideApp', { - defaultValue: - 'This view was saved as a draft outside this app, because the app’s customization package cannot be used here. This app’s draft bar does not count or publish it: publish it from Home.', - })); - }, + askPackage: ({ preselect }) => ask({ preselect }), + askDialog: dialog, }), - [packageId, t], + [packageId, ask, dialog], ); } +/** + * objectstack#38149 — a view create that was not saved: a cancelled ask says + * nothing and keeps the dialog open; a refused one says why and where to go. + * `true` when `err` was such a create (the caller answers "not saved"). + */ +export function reportViewNotSaved(err: unknown, locale: string): boolean { + if (!isRuntimeCreateNotSaved(err)) return false; + const text = runtimeCreateRefusalText(err, 'view', locale); + if (text) toast.error(text); + return true; +} + export function useObjectViewViewCrud({ dataSource, objects, @@ -100,7 +112,8 @@ export function useObjectViewViewCrud({ activeViewId: string | undefined; baseView: ReturnType[number]; }) { - const createApp = useRuntimeCreateApp(t); + const createApp = useRuntimeCreateApp(); + const locale = useMetadataLocale(); // objectui#12504 — no toolbar control writes the shared view. The sort and // the columns are the list's draft (`./listDraftStore.ts`), the widths and // the density the reader's layout in this browser (`listLayout`), and @@ -302,6 +315,8 @@ export function useObjectViewViewCrud({ } return true; } catch (err) { + // objectstack#38149 — no package took it: nothing was written. + if (reportViewNotSaved(err, locale)) return false; console.error('[ViewConfigPanel] Failed to create view:', err); // objectui#11578: a refused save is SAID, with the door's own // message (the field-anchored issues of a 422, or the refusal's @@ -312,7 +327,7 @@ export function useObjectViewViewCrud({ }); return false; } - }, [dataSource, objectName, objects, navigate, viewId, metadataClient, previewDrafts, t, createApp]); + }, [dataSource, objectName, objects, navigate, viewId, metadataClient, previewDrafts, t, createApp, locale]); /** Real-time draft field update — propagates each toggle/input change immediately */ const handleViewUpdate = useCallback((field: string, value: any) => { @@ -560,6 +575,8 @@ export function useObjectViewViewCrud({ handleReorderViews, handleConfigView, handleAddView, + // objectstack#38149 — the package ask a view create opens; the component renders it. + packageAskDialog: createApp.askDialog, }; } diff --git a/ui/packages/app-shell/src/views/objectViewViewSharing.ts b/ui/packages/app-shell/src/views/objectViewViewSharing.ts index 0b81c11e926..d3efaf704d0 100644 --- a/ui/packages/app-shell/src/views/objectViewViewSharing.ts +++ b/ui/packages/app-shell/src/views/objectViewViewSharing.ts @@ -27,7 +27,9 @@ import { useCallback } from 'react'; import { toast } from 'sonner'; import type { useObjectTranslation } from '@object-ui/i18n'; import { buildAddViewSpec } from './objectViewTabs.js'; -import { saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; +import { isRuntimeCreateNotSaved, saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; +import { runtimeCreateRefusalText } from './metadata-admin/PackageCreateAsk.js'; +import { useMetadataLocale } from './metadata-admin/i18n.js'; import type { RuntimeCreateApp, RuntimePersistCtx } from './runtime-metadata-persistence.js'; import { viewSaveRefusalText } from './viewSaveRefusal.js'; @@ -76,6 +78,7 @@ export function useViewSharing({ refresh: () => void; t: TFn; }): UseViewSharing { + const locale = useMetadataLocale(); const openView = useCallback((id: string) => { if (routeViewId) navigate(`../${id}`, { relative: 'path' }); else navigate(`view/${id}`); @@ -105,6 +108,12 @@ export function useViewSharing({ openView(env.name); return true; } catch (err) { + // objectstack#38149 — no package took it: nothing was written. + if (isRuntimeCreateNotSaved(err)) { + const text = runtimeCreateRefusalText(err, 'view', locale); + if (text) toast.error(text); + return false; + } console.error('[ObjectView] Failed to create a shared view:', err); toast.error(t('form.saveError'), { description: viewSaveRefusalText(err, t), @@ -112,7 +121,7 @@ export function useViewSharing({ }); return false; } - }, [metadataClient, objectDef, objectName, publishNew, refresh, openView, t]); + }, [metadataClient, objectDef, objectName, publishNew, refresh, openView, t, locale]); return { createShared }; } diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index 59c453d731c..f3c9b896f71 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -146,16 +146,19 @@ export interface RuntimePersistCtx { */ objectName?: string | null; /** - * objectstack#35624 — the app the console is in, for a NEW view - * ({@link createRuntimeMetadata}). Absent (outside any app, or a caller that - * creates no view) → the create saves as before, naming no package. + * objectstack#35624 — the app the console is in, for a NEW item + * ({@link createRuntimeMetadata}, {@link saveAndPublishRuntimeMetadata}): + * the create is saved into a package of the app, or into the one the person + * picks when none can be had (objectstack#38149, + * {@link pickRuntimeCreatePackage}). Absent → a write that creates nothing + * (an in-place save of an existing row), which names no package, as before. */ app?: RuntimeCreateApp | null; } /** - * objectstack#35624 — the app a console create runs in, and what it is told - * when the create cannot be saved there. + * objectstack#35624 — the app a console create runs in, and how a create that + * no package of the app can take is answered (objectstack#38149). */ export interface RuntimeCreateApp { /** @@ -165,17 +168,17 @@ export interface RuntimeCreateApp { */ packageId: string | null; /** - * Called after a create that had an app but was saved naming no package (no - * writable package of the app could be had, {@link resolveRuntimeCreatePackage}). - * The save itself landed; this says where it went. + * objectstack#38149 — ask the person to pick a package or create one + * (`PackageCreateAsk.tsx`), when no package of the app can be had. Resolves + * the package id, or `null` when they cancel: nothing is written then. */ - onSavedOutsideApp?: () => void; + askPackage: (request: { preselect?: string | null }) => Promise; } /** The two package doors {@link resolveRuntimeCreatePackage} asks. */ export interface RuntimeCreatePackageDoors { - /** Every listed package by id, with the server's `writable` verdict. */ - listPackages: () => Promise>; + /** Every listed package by id, with the server's `writable` verdict and its manifest. */ + listPackages: () => Promise }>>; /** `POST /packages/:base/ensure-customization`: the base's pair, created on first use. */ ensureCustomization: (basePackageId: string) => Promise<{ packageId: string; writable: boolean }>; } @@ -185,42 +188,111 @@ const PACKAGE_DOORS: RuntimeCreatePackageDoors = { ensureCustomization: ensureCustomizationPackage, }; +/** Manifest scopes of the packages the platform itself ships (ADR-0016 §3.8). */ +const KERNEL_SCOPES = new Set(['system', 'cloud']); + /** - * objectstack#35624 (ruling C, 「C 存进应用定制包」) — where a view created in - * an app's console is saved: the app's own package when it is writable, else - * the app's customization package `.custom` (ADR-0146 D3, the App is the - * customization unit), asked of the ensure door, which creates it on first use - * and names it, so its id is never spelled here. `null` when neither can be - * had: the app's package is not listed, or the ensure door refuses (a walled - * deployment answers a tenant administrator `403`; a kernel base is refused - * too). The caller then saves naming no package, as before this card, and says - * so ({@link RuntimeCreateApp.onSavedOutsideApp}). + * Where {@link resolveRuntimeCreatePackage} says a console create goes: + * - `package` — that package, named in the save; + * - `ask` — no package of the app can be had, so the person picks one or + * creates one (objectstack#38149); `preselect` is the app's package when + * the list names it as writable, else none; + * - `refused` — no pick could take it: the app is a system app, whose + * package the platform ships and which no customization package can hold + * (`system-app`, decisions Q-b of topic objectstack#37424, answered C), or + * the ensure door refuses this caller itself (`caller-refused`, a walled + * deployment's tenant administrator, `403`), carrying the door's reason. + */ +export type RuntimeCreatePackage = + | { kind: 'package'; packageId: string } + | { kind: 'ask'; preselect: string | null } + | { kind: 'refused'; reason: 'system-app' } + | { kind: 'refused'; reason: 'caller-refused'; message: string }; + +/** + * objectstack#35624 (ruling C, 「C 存进应用定制包」) — where a view or report + * created in an app's console is saved: the app's own package when it is + * writable, else the app's customization package `.custom` (ADR-0146 D3, + * the App is the customization unit), asked of the ensure door, which creates + * it on first use and names it, so its id is never spelled here. * - * A refusal here never fails the create: the ruling's fallback is the - * package-less save, so a door that answers no is reported and passed over. + * objectstack#38149 — when neither can be had, the create is no longer saved + * naming no package. Outside any app, for an app whose package is not listed, + * or where the ensure door refuses the base, the person is asked + * (`kind: 'ask'`). A system app (a kernel-scoped package) and a refusal of the + * caller by the ensure door (`403`) are refused instead, because no pick + * would be taken there either (`kind: 'refused'`). */ export async function resolveRuntimeCreatePackage( appPackageId: string | null | undefined, - /** The metadata type being created, named in the warning when the package-less fallback is taken. */ + /** The metadata type being created, named in the warning when a door fails. */ type: string, doors: RuntimeCreatePackageDoors = PACKAGE_DOORS, -): Promise { - if (!appPackageId) return null; +): Promise { + if (!appPackageId) return { kind: 'ask', preselect: null }; + let listed: { writable: boolean; manifest?: Record } | undefined; + try { + listed = (await doors.listPackages()).get(appPackageId); + } catch (err) { + console.warn(`[runtime-metadata] the package list could not be read; the ${type} asks for its package:`, err); + return { kind: 'ask', preselect: null }; + } + if (!listed) return { kind: 'ask', preselect: null }; + if (listed.writable) return { kind: 'package', packageId: appPackageId }; + const scope = listed.manifest?.scope; + if (typeof scope === 'string' && KERNEL_SCOPES.has(scope)) return { kind: 'refused', reason: 'system-app' }; try { - const listed = (await doors.listPackages()).get(appPackageId); - if (!listed) return null; - if (listed.writable) return appPackageId; const pair = await doors.ensureCustomization(appPackageId); - return pair.writable ? pair.packageId : null; + return pair.writable ? { kind: 'package', packageId: pair.packageId } : { kind: 'ask', preselect: null }; } catch (err) { - console.warn( - `[runtime-metadata] the customization package of "${appPackageId}" could not be had; the ${type} is saved naming no package:`, - err, - ); - return null; + if ((err as { status?: unknown } | null)?.status === 403) { + return { kind: 'refused', reason: 'caller-refused', message: err instanceof Error ? err.message : String(err) }; + } + console.warn(`[runtime-metadata] the customization package of "${appPackageId}" could not be had; the ${type} asks for its package:`, err); + return { kind: 'ask', preselect: null }; } } +/** + * objectstack#38149 — a console create that was not saved, and why: the + * person cancelled the ask (`cancelled`), or no package could take it + * ({@link RuntimeCreatePackage} `refused`). Nothing was written. + */ +export class RuntimeCreateNotSavedError extends Error { + readonly reason: 'cancelled' | 'system-app' | 'caller-refused'; + constructor(reason: 'cancelled' | 'system-app' | 'caller-refused', message?: string) { + super(message ?? `The create was not saved (${reason}).`); + this.name = 'RuntimeCreateNotSavedError'; + this.reason = reason; + } +} + +/** Whether `err` is a {@link RuntimeCreateNotSavedError}. */ +export function isRuntimeCreateNotSaved(err: unknown): err is RuntimeCreateNotSavedError { + return err instanceof RuntimeCreateNotSavedError; +} + +/** + * objectstack#38149 — the package a console create is saved into: the one + * {@link resolveRuntimeCreatePackage} names, else the one the person picks or + * creates when asked. Throws {@link RuntimeCreateNotSavedError} when they + * cancel or the create is refused, before anything is written. + */ +export async function pickRuntimeCreatePackage( + app: RuntimeCreateApp, + type: string, + doors: RuntimeCreatePackageDoors = PACKAGE_DOORS, +): Promise { + const target = await resolveRuntimeCreatePackage(app.packageId, type, doors); + if (target.kind === 'package') return target.packageId; + if (target.kind === 'refused') { + throw new RuntimeCreateNotSavedError(target.reason, target.reason === 'caller-refused' ? target.message : undefined); + } + const chosen = await app.askPackage({ preselect: target.preselect }); + if (!chosen) throw new RuntimeCreateNotSavedError('cancelled'); + return chosen; +} + /** * Drop the view-shaped cache keys a just-written view row stales. * @@ -452,8 +524,10 @@ export function viewEnvelope( * name's one holding package when the request names none (ADR-0146 D8), so * they reach this draft in the pair, and a view saved package-less before this * card keeps its package-less address (a `?package=` there would fork it). - * Only the view callers pass an app; a report, dashboard or page is created - * exactly as before. + * objectstack#38149 — any type a caller passes an app for is saved this way, + * and when no package of the app can be had the person is asked + * ({@link pickRuntimeCreatePackage}): a create never saves naming no package. + * The callers pass an app for every create they make. */ export async function createRuntimeMetadata( type: RuntimeArtifactType, @@ -471,8 +545,7 @@ export async function createRuntimeMetadata( ' The server PUT /meta/:type/:name route requires a name segment.', ); } - const app = type === 'view' ? ctx.app : null; - const packageId = app?.packageId ? await resolveRuntimeCreatePackage(app.packageId, type) : null; + const packageId = ctx.app ? await pickRuntimeCreatePackage(ctx.app, type) : null; // objectstack#36137 — the first-write pin: a create over a name that already // holds a pending draft is refused `409 METADATA_CONFLICT`, never written over it. await ctx.metadataClient.save( @@ -483,14 +556,6 @@ export async function createRuntimeMetadata( ); invalidateViewCaches(type, name, ctx); announceDraftLedgerWrite(); - if (app?.packageId && !packageId) { - // The write landed: a notice that fails must not report it as refused. - try { - app.onSavedOutsideApp?.(); - } catch (err) { - console.warn('[runtime-metadata] the saved-outside-app notice failed:', err); - } - } return name; } @@ -618,9 +683,9 @@ export type SaveAndPublishOutcome = 'published' | 'pending-draft'; * passes the app it was made in * ({@link RuntimePersistCtx.app}): its first write is saved into the app's * package as {@link createRuntimeMetadata} saves it. The publish names no - * package (ADR-0146 D8 addresses the name's one holder). When no package can be - * had it is saved naming none and nothing is said: it is published, so no - * draft bar has to count it. + * package (ADR-0146 D8 addresses the name's one holder). objectstack#38149 — + * when no package of the app can be had the person is asked, and a cancelled + * or refused ask writes nothing ({@link pickRuntimeCreatePackage}). */ export async function saveAndPublishRuntimeMetadata( type: RuntimeArtifactType, @@ -628,8 +693,7 @@ export async function saveAndPublishRuntimeMetadata( body: any, ctx: RuntimePersistCtx, ): Promise { - const app = type === 'view' ? ctx.app : null; - const packageId = app?.packageId ? await resolveRuntimeCreatePackage(app.packageId, type) : null; + const packageId = ctx.app ? await pickRuntimeCreatePackage(ctx.app, type) : null; let draftVersion: string | undefined; try { const receipt = await ctx.metadataClient.save( diff --git a/ui/packages/app-shell/src/views/studio-design/packages-io.ts b/ui/packages/app-shell/src/views/studio-design/packages-io.ts index 6b705857da1..7f5492b8d57 100644 --- a/ui/packages/app-shell/src/views/studio-design/packages-io.ts +++ b/ui/packages/app-shell/src/views/studio-design/packages-io.ts @@ -305,7 +305,9 @@ export async function ensureCustomizationPackage(baseId: string): Promise null)) as Record | null; if (!res.ok) { - throw new Error(readEnvelopeFailureText(payload) ?? `HTTP ${res.status}`); + // objectstack#38149 — the status rides along: a `403` refuses this caller + // itself, which a console create says instead of asking for a package. + throw Object.assign(new Error(readEnvelopeFailureText(payload) ?? `HTTP ${res.status}`), { status: res.status }); } // The dispatcher envelope `{ success, data }`; the declaration is the `data`. const parsed = EnsureCustomizationPackageResponseSchema.safeParse(payload?.data); diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index c90c4531573..b3fe1f2a0b4 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -4062,6 +4062,23 @@ const STUDIO_EN: Record = { 'engine.list.create': 'New', 'engine.list.createNamed': 'New {type}', 'engine.list.createInPairHint': '{package} is read-only. A new {type} is created in its customization package, {pair}.', + // objectstack#38149 — the create ask: a create that names no package asks + // the person to pick a package or create one (`PackageCreateAsk.tsx`). + 'engine.packageAsk.title': 'Choose a package', + 'engine.packageAsk.titleNamed': 'Which package should this {type} go in?', + 'engine.packageAsk.description': 'Everything you create belongs to a package, so you can find it there and export or delete it with the package. Choose one of your packages, or create a new one.', + 'engine.packageAsk.loading': 'Loading packages…', + 'engine.packageAsk.loadFailed': 'The package list could not be read: {error}', + 'engine.packageAsk.none': 'No package can hold it yet. Create a new package to continue.', + 'engine.packageAsk.listLabel': 'Your packages', + 'engine.packageAsk.createNew': 'New package…', + 'engine.packageAsk.cancel': 'Cancel', + 'engine.packageAsk.continue': 'Continue', + // objectstack#38149 — a create in an app that no package can take, said + // instead of saving it outside every package. + 'engine.packageAsk.systemApp.view': 'A shared view can’t be saved in a system app: it ships with the platform and has no package for your changes. Save it to My views instead, or add the view in one of your business apps.', + 'engine.packageAsk.systemApp.report': 'A report can’t be saved in a system app: it ships with the platform and has no package for your changes. Create the report in one of your business apps instead.', + 'engine.packageAsk.callerRefused': 'This can’t be saved in the app’s package for you: {reason}', 'engine.list.refresh': 'Refresh', 'engine.list.search': 'Search name, label, description…', 'engine.list.empty': 'No items yet.', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index db5a151bad9..55b694e2e27 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -3600,6 +3600,19 @@ const STUDIO_ZH: Record = { 'engine.list.create': '新建', 'engine.list.createNamed': '新建{type}', 'engine.list.createInPairHint': '{package} 是只读软件包,新建的{type}会放进它的定制包 {pair}。', + 'engine.packageAsk.title': '选择软件包', + 'engine.packageAsk.titleNamed': '这个{type}放进哪个软件包?', + 'engine.packageAsk.description': '新建的内容都放在一个软件包里,这样才能在软件包里找到它,并随软件包一起导出或删除。请选择一个软件包,或新建一个。', + 'engine.packageAsk.loading': '正在读取软件包…', + 'engine.packageAsk.loadFailed': '读取软件包列表失败:{error}', + 'engine.packageAsk.none': '还没有能放它的软件包。新建一个软件包后继续。', + 'engine.packageAsk.listLabel': '你的软件包', + 'engine.packageAsk.createNew': '新建软件包…', + 'engine.packageAsk.cancel': '取消', + 'engine.packageAsk.continue': '继续', + 'engine.packageAsk.systemApp.view': '系统应用里不能保存共享视图:系统应用随平台提供,没有存放你改动的软件包。请改存到「我的视图」,或者到你的业务应用里添加这个视图。', + 'engine.packageAsk.systemApp.report': '系统应用里不能保存报表:系统应用随平台提供,没有存放你改动的软件包。请到你的业务应用里新建这份报表。', + 'engine.packageAsk.callerRefused': '无法替你存进这个应用的软件包:{reason}', 'engine.list.refresh': '刷新', 'engine.list.search': '搜索名称、显示名或描述…', 'engine.list.empty': '暂无数据。', diff --git a/ui/packages/plugin-designer/src/index.tsx b/ui/packages/plugin-designer/src/index.tsx index 60c4b0a393c..267f9889fb8 100644 --- a/ui/packages/plugin-designer/src/index.tsx +++ b/ui/packages/plugin-designer/src/index.tsx @@ -58,7 +58,7 @@ export { Minimap } from './components/Minimap'; // preferred routes. Each page expects an active app/adapter context from // @object-ui/app-shell and uses react-router-dom hooks // (useParams/useNavigate) for navigation. -export { CreateAppPage } from './pages/CreateAppPage'; +export { CreateAppPage, type CreateAppPageProps } from './pages/CreateAppPage'; export { EditAppPage } from './pages/EditAppPage'; export { DashboardDesignPage } from './pages/DashboardDesignPage'; diff --git a/ui/packages/plugin-designer/src/pages/CreateAppPage.tsx b/ui/packages/plugin-designer/src/pages/CreateAppPage.tsx index 18c8988fa74..4ee2d384537 100644 --- a/ui/packages/plugin-designer/src/pages/CreateAppPage.tsx +++ b/ui/packages/plugin-designer/src/pages/CreateAppPage.tsx @@ -21,7 +21,17 @@ import { toast } from 'sonner'; const DRAFT_STORAGE_KEY = 'objectui-app-wizard-draft'; -export function CreateAppPage() { +export interface CreateAppPageProps { + /** + * objectstack#38149 — the host's save of the new app: it asks which package + * the app goes in (or creates one) and saves the app there. Resolves `false` + * when the author cancelled, and the wizard stays open with nothing written. + * Absent, the app is saved through the client naming no package. + */ + saveApp?: (name: string, app: Record) => Promise; +} + +export function CreateAppPage({ saveApp }: CreateAppPageProps = {}) { const navigate = useNavigate(); const { appName } = useParams(); const { objects, refresh } = useMetadata(); @@ -56,10 +66,15 @@ export function CreateAppPage() { async (draft: AppWizardDraft) => { try { const appSchema = wizardDraftToAppSchema(draft); - // Persist app metadata to backend - const client = adapter?.getClient(); - if (client) { - await client.meta.saveItem('app', draft.name, appSchema); + // Persist app metadata to backend: into the package the host's save + // asks for, or, with no host save, through the client. + if (saveApp) { + if (!(await saveApp(draft.name, appSchema as unknown as Record))) return; + } else { + const client = adapter?.getClient(); + if (client) { + await client.meta.saveItem('app', draft.name, appSchema); + } } // Clear draft from localStorage on successful creation localStorage.removeItem(DRAFT_STORAGE_KEY); @@ -72,7 +87,7 @@ export function CreateAppPage() { toast.error(err?.message || 'Failed to create application'); } }, - [navigate, refresh, adapter], + [navigate, refresh, adapter, saveApp], ); const handleCancel = useCallback(() => { From 337b0294c7b8f2239fbf1691aa8fb64b33984765 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 05:13:18 +0000 Subject: [PATCH 04/18] test(app-shell): pin the create ask, and retarget the package-less create pins The create ask's own tests (the Setup list, the item editor, the console create's package pick), and the existing pins that held the retired package-less create moved to the ask, the refusal, or a named package. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- ...ateViewDialog.viewTypeParse-11581.test.tsx | 4 +- ...tDataPage.saveAsViewRefusal-11578.test.tsx | 4 +- .../ObjectView.createChartView-11576.test.tsx | 22 +- ...ObjectView.createKanbanView-11581.test.tsx | 22 +- .../src/views/ReportNewPage-36692.test.tsx | 67 +++--- .../ResourceEditPage.createAsk-38149.test.tsx | 176 ++++++++++++++++ ...rceEditPage.createDraftSeed-12866.test.tsx | 4 + ...ditPage.createFirstWritePin-11773.test.tsx | 4 + ...itPage.createLandingReplace-36906.test.tsx | 7 +- .../ResourceEditPage.docEditor-10188.test.tsx | 4 + ...esourceEditPage.heldBadName-27865.test.tsx | 8 + ...ourceEditPage.layersUnsaved-11799.test.tsx | 2 + .../ResourceEditPage.liveCreate-7611.test.tsx | 26 ++- ...EditPage.positionCreateLive-26192.test.tsx | 26 ++- ...esourceEditPage.requiredRow-28179.test.tsx | 8 + ...ResourceEditPage.saveAtOnce-36902.test.tsx | 2 + ...rceEditPage.seedPlaceholder-12810.test.tsx | 4 + .../ResourceListPage.createAsk-38149.test.tsx | 198 ++++++++++++++++++ ...ResourceListPage.pairCreate-36897.test.tsx | 8 +- ...eResourcePage.syncNextSteps-30328.test.tsx | 18 +- .../src/views/objectViewViewSharing.test.tsx | 24 ++- ...tadata-persistence.createAsk-38149.test.ts | 141 +++++++++++++ ...ta-persistence.createIntoApp-35624.test.ts | 26 ++- ...sistence.otherTypesUntouched-35624.test.ts | 42 ++-- ...stence.saveAndPublishIntoApp-36409.test.ts | 42 ++-- ...-persistence.walledFallback-35624.test.tsx | 87 ++++---- 26 files changed, 810 insertions(+), 166 deletions(-) create mode 100644 ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createAsk-38149.test.tsx create mode 100644 ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx create mode 100644 ui/packages/app-shell/src/views/runtime-metadata-persistence.createAsk-38149.test.ts diff --git a/ui/packages/app-shell/src/views/CreateViewDialog.viewTypeParse-11581.test.tsx b/ui/packages/app-shell/src/views/CreateViewDialog.viewTypeParse-11581.test.tsx index 8209c2227a8..1d443d3b22d 100644 --- a/ui/packages/app-shell/src/views/CreateViewDialog.viewTypeParse-11581.test.tsx +++ b/ui/packages/app-shell/src/views/CreateViewDialog.viewTypeParse-11581.test.tsx @@ -122,7 +122,9 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }), useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), - createAuthenticatedFetch: () => vi.fn(), + // objectstack#38149 — the package list a create reads goes through the + // page's `fetch`, so the routed app's writable package answers it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, init), })); vi.mock('@object-ui/plugin-list', async (importOriginal) => ({ ...(await importOriginal()), diff --git a/ui/packages/app-shell/src/views/ObjectDataPage.saveAsViewRefusal-11578.test.tsx b/ui/packages/app-shell/src/views/ObjectDataPage.saveAsViewRefusal-11578.test.tsx index d47d0872ddd..4c4fa46a847 100644 --- a/ui/packages/app-shell/src/views/ObjectDataPage.saveAsViewRefusal-11578.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectDataPage.saveAsViewRefusal-11578.test.tsx @@ -121,7 +121,9 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({ useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }), // "Save as view" and its dialog are for an admin holding `manage_metadata`. useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), - createAuthenticatedFetch: () => vi.fn(), + // objectstack#38149 — the package list a create reads goes through the + // page's `fetch`, so the routed app's writable package answers it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, init), })); // The list itself is orthogonal to the save door. vi.mock('@object-ui/plugin-list', async (importOriginal) => ({ diff --git a/ui/packages/app-shell/src/views/ObjectView.createChartView-11576.test.tsx b/ui/packages/app-shell/src/views/ObjectView.createChartView-11576.test.tsx index 7cd3267cbcc..5a91dd00818 100644 --- a/ui/packages/app-shell/src/views/ObjectView.createChartView-11576.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.createChartView-11576.test.tsx @@ -53,7 +53,9 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({ useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }), // The add-view button and the dialog are admin-only. useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), - createAuthenticatedFetch: () => vi.fn(), + // objectstack#38149 — the package list a create reads goes through the + // page's `fetch`, so the routed app's writable package answers it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, init), })); vi.mock('@object-ui/collaboration', async (importOriginal) => ({ @@ -205,20 +207,26 @@ async function createChartViewThroughTheSwitcher() { await waitFor(() => expect(metadataClient.save).toHaveBeenCalledTimes(1)); const [type, , body, opts] = metadataClient.save.mock.calls[0] as unknown as [string, string, any, any]; expect(type).toBe('view'); - expect(opts).toEqual({ mode: 'draft', ifNoneMatch: '*' }); + expect(opts).toEqual({ mode: 'draft', packageId: 'demo', ifNoneMatch: '*' }); return body; } beforeEach(() => { cleanup(); capturedChartSchema = null; + // objectstack#38149 — the create reads the package list for where the app + // saves its views; the routed app `demo` is a writable package here. vi.stubGlobal( 'fetch', - vi.fn(async () => - new Response(JSON.stringify({ data: [] }), { - status: 200, - headers: { 'content-type': 'application/json' }, - }), + vi.fn(async (input: RequestInfo | URL) => + new Response( + JSON.stringify( + String(input) === '/api/v1/packages' + ? { success: true, data: { packages: [{ manifest: { id: 'demo', name: 'Demo' }, writable: true }] } } + : { data: [] }, + ), + { status: 200, headers: { 'content-type': 'application/json' } }, + ), ), ); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.createKanbanView-11581.test.tsx b/ui/packages/app-shell/src/views/ObjectView.createKanbanView-11581.test.tsx index afd223f7694..1dd81c48dde 100644 --- a/ui/packages/app-shell/src/views/ObjectView.createKanbanView-11581.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.createKanbanView-11581.test.tsx @@ -51,7 +51,9 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({ useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }), // The add-view button and the dialog are admin-only. useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), - createAuthenticatedFetch: () => vi.fn(), + // objectstack#38149 — the package list a create reads goes through the + // page's `fetch`, so the routed app's writable package answers it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, init), })); vi.mock('@object-ui/collaboration', async (importOriginal) => ({ @@ -117,13 +119,19 @@ const picker = (key: string) => screen.getByTestId(`create-view-required-${key}` beforeEach(() => { cleanup(); + // objectstack#38149 — the create reads the package list for where the app + // saves its views; the routed app `demo` is a writable package here. vi.stubGlobal( 'fetch', - vi.fn(async () => - new Response(JSON.stringify({ data: [] }), { - status: 200, - headers: { 'content-type': 'application/json' }, - }), + vi.fn(async (input: RequestInfo | URL) => + new Response( + JSON.stringify( + String(input) === '/api/v1/packages' + ? { success: true, data: { packages: [{ manifest: { id: 'demo', name: 'Demo' }, writable: true }] } } + : { data: [] }, + ), + { status: 200, headers: { 'content-type': 'application/json' } }, + ), ), ); }); @@ -164,7 +172,7 @@ describe('ObjectView.handleViewCreate persists a kanban through the one builder await waitFor(() => expect(metadataClient.save).toHaveBeenCalledTimes(1)); const [type, , body, opts] = metadataClient.save.mock.calls[0] as unknown as [string, string, any, any]; expect(type).toBe('view'); - expect(opts).toEqual({ mode: 'draft', ifNoneMatch: '*' }); + expect(opts).toEqual({ mode: 'draft', packageId: 'demo', ifNoneMatch: '*' }); // The spec's verdict first: it is the claim this pin exists for. const listView = ListViewSchema.safeParse(body.config); expect(listView.success, JSON.stringify(listView.error?.issues)).toBe(true); diff --git a/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx b/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx index 46fccabd1b6..46273e2575f 100644 --- a/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx +++ b/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx @@ -343,28 +343,24 @@ describe("the app's own New saves into the app's package, as a new view does (ob expect(toastInfo).not.toHaveBeenCalled(); }); - it('control: when the ensure door refuses, Save falls back to naming no package, and says so, as a new view does', async () => { + // objectstack#38149 (decisions Q-b of topic objectstack#37424, answered C): + // the package-less fallback is retired. The ensure door refusing this caller + // (403) refuses the save with the door's reason, and nothing is written. + it('control: when the ensure door refuses the caller, Save is refused with its reason and nothing is written', async () => { doors.listed = new Map([[PKG, { writable: false }]]); doors.ensure.mockImplementation(async () => { throw Object.assign(new Error('Forbidden'), { status: 403 }); }); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - try { - await saveFromApp(); - expect(doors.ensure).toHaveBeenCalledWith(PKG); - expect(client.save).not.toHaveBeenCalled(); - expect(saveAndPublish).toHaveBeenCalledWith( - 'report', - 'payment_analysis', - { ...DRAFT, name: 'payment_analysis' }, - expect.objectContaining({ metadataClient: client }), - ); - expect(toastInfo).toHaveBeenCalledTimes(1); - expect(toastInfo).toHaveBeenCalledWith('report.builder.savedOutsideApp'); - expect(warn).toHaveBeenCalledWith(expect.stringContaining('the report is saved naming no package'), expect.anything()); - } finally { - warn.mockRestore(); - } + mount(); + fireEvent.click(screen.getByText('save')); + await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1)); + expect(doors.ensure).toHaveBeenCalledWith(PKG); + expect(toastError).toHaveBeenCalledWith('form.saveError', { description: expect.stringContaining('Forbidden') }); + expect(client.save).not.toHaveBeenCalled(); + expect(client.publish).not.toHaveBeenCalled(); + expect(saveAndPublish).not.toHaveBeenCalled(); + expect(toastInfo).not.toHaveBeenCalled(); + expect(screen.getByTestId('where')).not.toHaveTextContent('/apps/crm/report/payment_analysis'); }); }); @@ -466,35 +462,20 @@ describe("opened from Studio's report list (objectstack#36906, decision 13)", () expect(toastInfo).not.toHaveBeenCalled(); }); - it('control: when the ensure door refuses, Save falls back to naming no package, and says so, as a new view does', async () => { + // objectstack#38149: as on the app leg, the refusal is said and nothing is written. + it('control: when the ensure door refuses the caller, Save is refused with its reason and stays on the builder', async () => { doors.listed = new Map([[PKG, { writable: false }]]); doors.ensure.mockImplementation(async () => { throw Object.assign(new Error('Forbidden'), { status: 403 }); }); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - try { - mountFromStudio(); - fireEvent.click(screen.getByText('save')); - await waitFor(() => - expect(screen.getByTestId('where-full').textContent).toBe(`/apps/crm/report/payment_analysis${fromStudio}`), - ); - expect(doors.ensure).toHaveBeenCalledWith(PKG); - expect(client.save).not.toHaveBeenCalled(); - expect(saveAndPublish).toHaveBeenCalledWith( - 'report', - 'payment_analysis', - { ...DRAFT, name: 'payment_analysis' }, - expect.objectContaining({ metadataClient: client }), - ); - // The author is told the report is not where the Studio list looks. - expect(toastInfo).toHaveBeenCalledTimes(1); - // (This harness registers no locale pack, so `t` answers the key itself.) - expect(toastInfo).toHaveBeenCalledWith('report.builder.savedOutsideApp'); - // The developer-console line names the type it saved, not a view. - expect(warn).toHaveBeenCalledWith(expect.stringContaining('the report is saved naming no package'), expect.anything()); - } finally { - warn.mockRestore(); - } + mountFromStudio(); + fireEvent.click(screen.getByText('save')); + await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1)); + expect(doors.ensure).toHaveBeenCalledWith(PKG); + expect(client.save).not.toHaveBeenCalled(); + expect(saveAndPublish).not.toHaveBeenCalled(); + expect(toastInfo).not.toHaveBeenCalled(); + expect(screen.getByTestId('builder')).toBeInTheDocument(); }); it("Save lands on the new report's page, which keeps the way back to Studio", async () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createAsk-38149.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createAsk-38149.test.tsx new file mode 100644 index 00000000000..e7344f7b0d4 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createAsk-38149.test.tsx @@ -0,0 +1,176 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38149 — the item editor's create asks for its package when its + * address names none: a deep link (`/apps/setup/metadata/TYPE/new`), Studio's + * cross-package leg (`/studio/~all/metadata/TYPE/new`), Setup's catalog + * (`?scope=environment`). Nothing is written until the person picks a package + * or creates one; the item is then saved as a draft there and published at + * once, and the editor opens it under that package. + * + * Setup's positions and permission sets (decisions Q-a of topic + * objectstack#37424, answered A, on the premise the dogfood probe + * `position-in-package-binds-outside-sets-38149` measures): a `createLive` + * type takes the draft-and-publish path in the chosen package too. + * + * Over the REAL page and a REAL `MetadataClient`, its transport an in-memory + * server recording each write; the position's and permission set's + * registrations are the real ones. + */ + +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 { MetadataClient } from '@object-ui/data-objectstack'; + +type Write = { method: string; path: string; mode: string | null; packageId: string | null }; +const server = { writes: [] as Write[] }; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + +async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { + const method = (init?.method ?? 'GET').toUpperCase(); + const url = new URL(String(input), 'http://console.test'); + const meta = url.pathname.match(/^\/api\/v1\/meta\/(.+)$/); + if (!meta) return json(200, []); + const seg = meta[1].split('/').map(decodeURIComponent); + if (seg[0] === '_drafts') return json(200, { drafts: [] }); + if (seg.length === 1) return json(200, { items: [] }); + if (method === 'PUT' || method === 'POST') { + server.writes.push({ method, path: url.pathname, mode: url.searchParams.get('mode'), packageId: url.searchParams.get('package') }); + return json(200, { success: true, version: 'hmac-sha256:v1', seq: 1, state: method === 'PUT' ? 'draft' : 'active', message: 'Saved' }); + } + return json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); +} + +const client = vi.hoisted(() => ({ current: null as unknown })); + +const SCHEMA = { + type: 'object', + required: ['name'], + properties: { name: { type: 'string' }, label: { type: 'string' }, description: { type: 'string' } }, +}; + +vi.mock('./useMetadata', async (importOriginal) => { + const mod = await importOriginal(); + return { + ...mod, + useMetadataClient: () => client.current, + useMetadataTypes: () => ({ + loading: false, + entries: [ + { type: 'position', label: 'Position', domain: 'security', allowEnvironmentOverlay: false, allowRuntimeCreate: true, schema: SCHEMA }, + { type: 'permission', label: 'Permission Set', domain: 'security', allowEnvironmentOverlay: false, allowRuntimeCreate: true, schema: SCHEMA }, + ], + }), + }; +}); + +/** The server's package list the ask reads. */ +vi.mock('../studio-design/packages-io', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchPackages: async () => [ + { id: 'app.alpha', name: 'Alpha', writable: true, namespace: 'alpha' }, + { id: 'com.objectstack.setup', name: 'Setup', writable: false, namespace: 'setup' }, + ], +})); + +import { MetadataResourceEditPage } from './ResourceEditPage'; +import './anchors'; +import '../../services/builtinComponents'; + +client.current = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch }); + +beforeEach(() => { + server.writes = []; + window.localStorage.setItem('metadata-admin:autosave', '0'); +}); +afterEach(() => { + cleanup(); + window.localStorage.removeItem('metadata-admin:autosave'); + window.history.replaceState(null, '', '/'); +}); + +function Where() { + const location = useLocation(); + return
{`${location.pathname}${location.search}`}
; +} + +/** Open the create form at `entry`, fill the name, and press Save. */ +async function createAt(type: string, entry: string, name: string) { + render( + + + + + + + } + /> + } /> + + , + ); + const input = await waitFor(() => { + const el = document.getElementById('mdf-name') as HTMLInputElement | null; + expect(el).not.toBeNull(); + return el!; + }, { timeout: 8000 }); + fireEvent.change(input, { target: { value: name } }); + await waitFor(() => expect((document.getElementById('mdf-name') as HTMLInputElement).value).toBe(name)); + fireEvent.click(screen.getByRole('button', { name: /Save \(⌘S\)/ })); +} + +describe('the editor asks for a package before a create its address names none for (objectstack#38149)', () => { + it('a deep link: the ask opens, Cancel writes nothing and stays on the form', async () => { + await createAt('position', '/metadata/position/new', 'regional_lead'); + const dialog = await screen.findByTestId('package-create-ask', {}, { timeout: 8000 }); + // Only the writable package is offered. + await within(dialog).findByTestId('package-create-ask-option-app.alpha'); + expect(within(dialog).queryByTestId('package-create-ask-option-com.objectstack.setup')).toBeNull(); + fireEvent.click(within(dialog).getByTestId('package-create-ask-cancel')); + await waitFor(() => expect(screen.queryByTestId('package-create-ask')).toBeNull()); + expect(server.writes).toEqual([]); + expect(screen.getByTestId('where')).toHaveTextContent('/metadata/position/new'); + }); + + it('a position (Q-a): the chosen package takes a draft and its publish, and the item opens under it', async () => { + await createAt('position', '/metadata/position/new?scope=environment', 'regional_lead'); + const dialog = await screen.findByTestId('package-create-ask', {}, { timeout: 8000 }); + fireEvent.click(await within(dialog).findByTestId('package-create-ask-option-app.alpha')); + fireEvent.click(within(dialog).getByTestId('package-create-ask-continue')); + await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/metadata/position/regional_lead'), { timeout: 8000 }); + expect(screen.getByTestId('where')).toHaveTextContent('scope=environment'); + expect(screen.getByTestId('where')).toHaveTextContent('package=app.alpha'); + expect(server.writes).toEqual([ + { method: 'PUT', path: '/api/v1/meta/position/regional_lead', mode: 'draft', packageId: 'app.alpha' }, + { method: 'POST', path: '/api/v1/meta/position/regional_lead/publish', mode: null, packageId: 'app.alpha' }, + ]); + }); + + it('a permission set (Q-a, `createLive`): a draft in the chosen package and its publish, never a live package-less write', async () => { + await createAt('permission', '/metadata/permission/new?scope=environment', 'regional_set'); + const dialog = await screen.findByTestId('package-create-ask', {}, { timeout: 8000 }); + fireEvent.click(await within(dialog).findByTestId('package-create-ask-option-app.alpha')); + fireEvent.click(within(dialog).getByTestId('package-create-ask-continue')); + await waitFor(() => expect(server.writes).toHaveLength(2), { timeout: 8000 }); + expect(server.writes).toEqual([ + { method: 'PUT', path: '/api/v1/meta/permission/regional_set', mode: 'draft', packageId: 'app.alpha' }, + { method: 'POST', path: '/api/v1/meta/permission/regional_set/publish', mode: null, packageId: 'app.alpha' }, + ]); + }); + + it('control: an address that names a package saves there with no ask', async () => { + window.history.replaceState(null, '', '/?package=com.acme.crm'); + await createAt('position', '/metadata/position/new?package=com.acme.crm', 'regional_lead'); + await waitFor(() => expect(server.writes).toHaveLength(2), { timeout: 8000 }); + expect(screen.queryByTestId('package-create-ask')).toBeNull(); + expect(server.writes[0]).toEqual({ method: 'PUT', path: '/api/v1/meta/position/regional_lead', mode: 'draft', packageId: 'com.acme.crm' }); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createDraftSeed-12866.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createDraftSeed-12866.test.tsx index 9c46d87b751..7743aa5d148 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createDraftSeed-12866.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createDraftSeed-12866.test.tsx @@ -106,6 +106,9 @@ registerBuiltinPreviews(); registerBuiltinInspectors(); beforeEach(() => { + // objectstack#38149 — a create whose address names no package asks for one + // first; this create's address names its package, as Setup's list now writes. + window.history.replaceState(null, '', '/?package=app.test'); server.puts = []; registry.servedAtMount = true; registry.release = null; @@ -113,6 +116,7 @@ beforeEach(() => { }); afterEach(() => { cleanup(); + window.history.replaceState(null, '', '/'); window.localStorage.removeItem('metadata-admin:autosave'); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createFirstWritePin-11773.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createFirstWritePin-11773.test.tsx index ec32d81f330..66157265b19 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createFirstWritePin-11773.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createFirstWritePin-11773.test.tsx @@ -125,6 +125,9 @@ afterAll(() => { }); beforeEach(() => { + // objectstack#38149 — a create whose address names no package asks for one + // first; this create's address names its package, as Setup's list now writes. + window.history.replaceState(null, '', '/?package=app.test'); server.drafts.clear(); server.active.clear(); server.puts = []; @@ -132,6 +135,7 @@ beforeEach(() => { }); afterEach(() => { cleanup(); + window.history.replaceState(null, '', '/'); }); function Where() { diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createLandingReplace-36906.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createLandingReplace-36906.test.tsx index 5aa72730198..340442a7ed5 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createLandingReplace-36906.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createLandingReplace-36906.test.tsx @@ -93,6 +93,8 @@ client.current = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknow registerDefaultMetadataSchemas(); const PKG = 'com.acme.crm'; +/** The package a Setup create's address names. */ +const SETUP_PKG = 'app.setup_side'; const AREA: MetadataAreaHost = { packageId: PKG, readOnly: false, basePath: `/studio/${PKG}/metadata` }; beforeEach(() => { @@ -124,7 +126,8 @@ function Landed() { async function createAndSave(type: 'dashboard' | 'view', host: MetadataAreaHost | null) { const base = host ? host.basePath : '/apps/setup/metadata'; // The page binds its saves to `?package=` (`readActivePackageBinding`), as the area's address does. - if (host?.packageId) window.history.replaceState(null, '', `/?package=${host.packageId}`); + // Setup's create names its package too (objectstack#38149: else it asks first). + window.history.replaceState(null, '', `/?package=${host?.packageId ?? SETUP_PKG}`); const tree = ( @@ -163,6 +166,6 @@ describe("the create landing's history entry, at the real page (objectstack#3690 it("CONTROL: with no area host (Setup), a dashboard's create landing PUSHES, as before", async () => { const item = await createAndSave('dashboard', null); await waitFor(() => expect(screen.getByTestId('landed')).toHaveTextContent(`${item} PUSH`), { timeout: 8000 }); - expect(server.puts).toEqual([{ key: 'dashboard/pipeline', packageId: null }]); + expect(server.puts).toEqual([{ key: 'dashboard/pipeline', packageId: SETUP_PKG }]); }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.docEditor-10188.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.docEditor-10188.test.tsx index 8b8744a367d..e99c540208a 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.docEditor-10188.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.docEditor-10188.test.tsx @@ -133,12 +133,16 @@ afterAll(() => { }); beforeEach(() => { + // objectstack#38149 — a create whose address names no package asks for one + // first; this create's address names its package, as Setup's list now writes. + window.history.replaceState(null, '', '/?package=app.test'); stored = null; for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); window.localStorage.setItem('metadata-admin:autosave', '0'); }); afterEach(() => { cleanup(); + window.history.replaceState(null, '', '/'); window.localStorage.removeItem('metadata-admin:autosave'); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.heldBadName-27865.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.heldBadName-27865.test.tsx index c6d89e4db95..6b4ff6ff828 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.heldBadName-27865.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.heldBadName-27865.test.tsx @@ -54,6 +54,10 @@ async function serve(input: RequestInfo | URL, init?: RequestInit): Promise }); @@ -116,11 +120,15 @@ registerDefaultMetadataSchemas(); registerBuiltinAnchors(); beforeEach(() => { + // objectstack#38149 — a create whose address names no package asks for one + // first; this create's address names its package, as Setup's list now writes. + window.history.replaceState(null, '', '/?package=app.test'); server.puts = []; seedExtra.current = {}; }); afterEach(() => { cleanup(); + window.history.replaceState(null, '', '/'); }); const saveButton = () => screen.getByTestId('resource-save'); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.layersUnsaved-11799.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.layersUnsaved-11799.test.tsx index 3516dd9d2f5..33cc4177294 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.layersUnsaved-11799.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.layersUnsaved-11799.test.tsx @@ -237,6 +237,8 @@ describe('MetadataResourceEditPage — no /layers re-read for an item known to h }); it('CREATE: the refresh after the save asks no /layers for the item just created', async () => { + // objectstack#38149 — the create's address names its package (else it asks first). + window.history.replaceState({}, '', '/?package=app.test'); render( diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.liveCreate-7611.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.liveCreate-7611.test.tsx index b90273db457..4f9df37ec75 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.liveCreate-7611.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.liveCreate-7611.test.tsx @@ -14,12 +14,17 @@ * The REAL page over a REAL `MetadataClient`, its transport an in-memory server * that records each PUT's `mode` and pin, as in * `ResourceEditPage.createFirstWritePin-11773.test.tsx`. + * + * objectstack#38149 (decisions Q-a of topic objectstack#37424, answered A) + * supersedes the live create outside a package: such a create now asks for + * its package first, and is saved there as a draft and published + * (`ResourceEditPage.createAsk-38149.test.tsx`). */ 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 } from '@testing-library/react'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; @@ -72,6 +77,12 @@ vi.mock('./useMetadata', async (importOriginal) => { }; }); +/** The package list the create ask reads (objectstack#38149). */ +vi.mock('../studio-design/packages-io', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchPackages: async () => [{ id: 'app.alpha', name: 'Alpha', writable: true, namespace: 'alpha' }], +})); + import { MetadataResourceEditPage } from './ResourceEditPage'; import { registerBuiltinAnchors } from './anchors'; @@ -121,10 +132,17 @@ async function createSet() { } describe('a permission set is created live (objectui#7611)', () => { - it('outside a package: one live PUT with the first-write pin, then the editor opens', async () => { + // objectstack#38149 (decisions Q-a of topic objectstack#37424, answered A) + // supersedes the live package-less create: a create whose address names no + // package asks for one first, and the live write is never sent. + it('outside a package: the create asks for its package, and no live PUT is sent', async () => { await createSet(); - await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/metadata/permission/qa_parity_set'), { timeout: 8000 }); - expect(server.puts).toEqual([{ name: 'qa_parity_set', mode: null, packageId: null, ifNoneMatch: '*' }]); + const dialog = await screen.findByTestId('package-create-ask', {}, { timeout: 8000 }); + expect(server.puts).toEqual([]); + fireEvent.click(within(dialog).getByTestId('package-create-ask-cancel')); + await waitFor(() => expect(screen.queryByTestId('package-create-ask')).toBeNull()); + expect(server.puts).toEqual([]); + expect(screen.getByTestId('where')).toHaveTextContent('/metadata/permission/new'); }); it('under a package binding the create stays a package draft (control)', async () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.positionCreateLive-26192.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.positionCreateLive-26192.test.tsx index 78c4c5b1a7e..77a1eae1442 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.positionCreateLive-26192.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.positionCreateLive-26192.test.tsx @@ -18,8 +18,9 @@ * its transport an in-memory server that records each PUT's `mode`, package * and first-write pin, as in `ResourceEditPage.liveCreate-7611.test.tsx`: * - * - outside a package: ONE live PUT (no `mode`, no `package`) with the - * first-write pin, and the editor opens the created position; + * - outside a package: superseded by objectstack#38149 (decisions Q-a of + * topic objectstack#37424, answered A): the create asks for its package + * first, and no live PUT is sent; * - under a package binding the create stays a package draft (control), the * ADR-0086 package door's draft semantics. */ @@ -27,7 +28,7 @@ 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 } from '@testing-library/react'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; @@ -84,6 +85,12 @@ vi.mock('./useMetadata', async (importOriginal) => { }; }); +/** The package list the create ask reads (objectstack#38149). */ +vi.mock('../studio-design/packages-io', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchPackages: async () => [{ id: 'app.alpha', name: 'Alpha', writable: true, namespace: 'alpha' }], +})); + import { MetadataResourceEditPage } from './ResourceEditPage'; // The position's registration — its only one — lives in the built-in // component module, not in `anchors.ts`. @@ -134,10 +141,17 @@ async function createPosition() { } describe('a position is created live from Setup (objectstack#26192)', () => { - it('outside a package: one live PUT with the first-write pin, then the editor opens', async () => { + // objectstack#38149 (decisions Q-a of topic objectstack#37424, answered A) + // supersedes the live package-less create: a create whose address names no + // package asks for one first, and the live write is never sent. + it('outside a package: the create asks for its package, and no live PUT is sent', async () => { await createPosition(); - await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/metadata/position/regional_lead'), { timeout: 8000 }); - expect(server.puts).toEqual([{ name: 'regional_lead', mode: null, packageId: null, ifNoneMatch: '*' }]); + const dialog = await screen.findByTestId('package-create-ask', {}, { timeout: 8000 }); + expect(server.puts).toEqual([]); + fireEvent.click(within(dialog).getByTestId('package-create-ask-cancel')); + await waitFor(() => expect(screen.queryByTestId('package-create-ask')).toBeNull()); + expect(server.puts).toEqual([]); + expect(screen.getByTestId('where')).toHaveTextContent('/metadata/position/new'); }); it('under a package binding the create stays a package draft (control)', async () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.requiredRow-28179.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.requiredRow-28179.test.tsx index 9b6ab922fa8..1508ae7e20c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.requiredRow-28179.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.requiredRow-28179.test.tsx @@ -48,6 +48,10 @@ async function serve(input: RequestInfo | URL, init?: RequestInit): Promise }); return json(200, { success: true, version: 'hmac-sha256:v1', seq: 1, state: 'draft', message: `Saved ${seg[0]}/${seg[1]}` }); @@ -120,12 +124,16 @@ registerDefaultMetadataSchemas(); registerBuiltinAnchors(); beforeEach(() => { + // objectstack#38149 — a create whose address names no package asks for one + // first; this create's address names its package, as Setup's list now writes. + window.history.replaceState(null, '', '/?package=app.test'); server.puts = []; served.form = SERVED_FORM; served.schema = PERMISSION_JSON_SCHEMA; }); afterEach(() => { cleanup(); + window.history.replaceState(null, '', '/'); }); const saveButton = () => screen.getByTestId('resource-save'); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.saveAtOnce-36902.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.saveAtOnce-36902.test.tsx index c7055a617f7..31de0c115ac 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.saveAtOnce-36902.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.saveAtOnce-36902.test.tsx @@ -324,6 +324,8 @@ describe('Save takes effect at once (objectstack#36902 item 1)', () => { describe('a create publishes after its save (objectstack#36902 item 2)', () => { function renderCreate() { + // objectstack#38149 — the create's address names its package (else it asks first). + window.history.replaceState(null, '', '/?package=app.test'); render( diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.seedPlaceholder-12810.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.seedPlaceholder-12810.test.tsx index c884eb94a36..e149246737d 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.seedPlaceholder-12810.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.seedPlaceholder-12810.test.tsx @@ -94,11 +94,15 @@ registerBuiltinPreviews(); registerBuiltinInspectors(); beforeEach(() => { + // objectstack#38149 — a create whose address names no package asks for one + // first; this create's address names its package, as Setup's list now writes. + window.history.replaceState(null, '', '/?package=app.test'); server.puts = []; window.localStorage.setItem('metadata-admin:autosave', '0'); }); afterEach(() => { cleanup(); + window.history.replaceState(null, '', '/'); window.localStorage.removeItem('metadata-admin:autosave'); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx new file mode 100644 index 00000000000..6137befc578 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx @@ -0,0 +1,198 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38149 — a create on Setup's metadata list that names no package + * asks the person to pick a package or create one (`PackageCreateAsk.tsx`). + * + * A package is NAMED by a `?package=` the person put in the address — on + * arrival, or by choosing in the scope selector. The list's repair writes the + * heuristic pick into the address too, marked as its own write, and that pick + * is not named: New asks, with the pick pre-selected. Pinned beside each: + * + * - on arrival with no `?package=` (the repair writes the pick): New asks, + * the pick pre-selected; the answer is where the create opens; + * - on arrival with `?package=PKG`, and after a choice in the selector: + * no ask, the create opens there; + * - while the packages load: New is disabled; + * - Setup's catalog (the environment scope, decisions Q-a of topic + * objectstack#37424): New asks, and the create keeps the scope; + * - Cancel opens nothing. + */ +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, cleanup, screen, waitFor, fireEvent, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import * as React from 'react'; +import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom'; +// The page reaches `celAuthoring`'s dynamic `@objectstack/lint` import; its +// first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; +import '@objectstack/spec/identity'; + +const PKG_A = 'app.alpha'; +const PKG_B = 'app.bravo'; +const TYPE = 'permission'; + +/** Package B owns the rows, so the list's heuristic picks it. */ +const ITEMS: Record[] = [ + { name: 'bravo_set', label: 'Bravo set', _packageId: PKG_B, _provenance: 'package' }, +]; + +let packageList: () => Promise = async () => [ + { manifest: { id: PKG_A, scope: 'project', name: 'Alpha' } }, + { manifest: { id: PKG_B, scope: 'project', name: 'Bravo' } }, +]; + +/** Stable singleton — the page's load effect keys on the client identity. */ +const CLIENT = { + list: async (type: string) => (type === 'package' ? packageList() : type === TYPE ? ITEMS : []), +}; + +const ENTRY = { type: TYPE, label: 'Permission Set', allowEnvironmentOverlay: false, allowRuntimeCreate: true }; + +vi.mock('./useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => CLIENT, + useMetadataTypes: () => ({ loading: false, error: null, entries: [ENTRY] }), +})); + +vi.mock('./i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataLocale: () => 'en-US', +})); + +vi.mock('../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => true })); + +/** The server's package list the ask reads, with its `writable` verdict. */ +vi.mock('../studio-design/packages-io', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchPackages: async () => [ + { id: PKG_A, name: 'Alpha', writable: true, namespace: 'alpha' }, + { id: PKG_B, name: 'Bravo', writable: true, namespace: 'bravo' }, + ], +})); + +// Imported AFTER the mocks so the page picks them up. +import { MetadataResourceListPage } from './ResourceListPage'; +import { t } from './i18n'; + +beforeEach(() => { + packageList = async () => [ + { manifest: { id: PKG_A, scope: 'project', name: 'Alpha' } }, + { manifest: { id: PKG_B, scope: 'project', name: 'Bravo' } }, + ]; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => + new Response(JSON.stringify({ object: 'x', records: [], hasMore: false, url }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }), + ), + ); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +/** Where a create opened: the editor route's address. */ +function CreateProbe() { + const location = useLocation(); + return
{location.search}
; +} + +/** The scope selector's write: a navigation that names a package, carrying no state. */ +function SelectorStub() { + const navigate = useNavigate(); + return ( + + ); +} + +function mount(search: string) { + return render( + + + + } /> + } /> + + , + ); +} + +const newButton = () => screen.findByTestId('metadata-list-create'); +const ask = () => screen.findByTestId('package-create-ask'); + +describe('Setup list: a heuristic pick asks (objectstack#38149)', () => { + it('on arrival with no ?package=, New asks with the repaired pick pre-selected, and opens the create where the person chose', async () => { + mount(''); + // The repair has written the heuristic pick (Bravo owns the rows). + await waitFor(() => expect(screen.getByText('bravo_set')).toBeInTheDocument()); + fireEvent.click(await newButton()); + const dialog = await ask(); + const bravo = await within(dialog).findByTestId(`package-create-ask-option-${PKG_B}`); + expect(bravo).toHaveAttribute('data-state', 'checked'); + expect(screen.queryByTestId('create-opened')).toBeNull(); + + fireEvent.click(within(dialog).getByTestId(`package-create-ask-option-${PKG_A}`)); + fireEvent.click(within(dialog).getByTestId('package-create-ask-continue')); + expect(await screen.findByTestId('create-opened')).toHaveTextContent(`?package=${PKG_A}`); + }); + + it('Cancel opens no create', async () => { + mount(''); + await waitFor(() => expect(screen.getByText('bravo_set')).toBeInTheDocument()); + fireEvent.click(await newButton()); + const dialog = await ask(); + fireEvent.click(within(dialog).getByTestId('package-create-ask-cancel')); + await waitFor(() => expect(screen.queryByTestId('package-create-ask')).toBeNull()); + expect(screen.queryByTestId('create-opened')).toBeNull(); + }); +}); + +describe('Setup list: a named package does not ask (objectstack#38149)', () => { + it('on arrival with ?package=PKG, New opens the create there with no ask', async () => { + mount(`?package=${PKG_A}`); + const button = await newButton(); + await waitFor(() => expect(button).not.toBeDisabled()); + fireEvent.click(button); + expect(await screen.findByTestId('create-opened')).toHaveTextContent(`?package=${PKG_A}`); + expect(screen.queryByTestId('package-create-ask')).toBeNull(); + }); + + it('after a choice in the scope selector, New opens the create there with no ask', async () => { + mount(''); + await waitFor(() => expect(screen.getByText('bravo_set')).toBeInTheDocument()); + fireEvent.click(screen.getByTestId('selector-stub')); + const button = await newButton(); + await waitFor(() => expect(button).not.toBeDisabled()); + fireEvent.click(button); + expect(await screen.findByTestId('create-opened')).toHaveTextContent(`?package=${PKG_A}`); + expect(screen.queryByTestId('package-create-ask')).toBeNull(); + }); +}); + +describe('Setup list: New waits for the packages (objectstack#38149)', () => { + it('is disabled while the package list loads', async () => { + packageList = () => new Promise(() => {}); + mount(''); + expect(await newButton()).toBeDisabled(); + }); +}); + +describe('Setup catalog: a new permission set asks for its package (objectstack#38149, Q-a)', () => { + it('New asks with nothing pre-selected, and the create keeps the environment scope', async () => { + mount('?scope=environment'); + fireEvent.click(await screen.findByRole('button', { name: new RegExp(t('engine.list.create', 'en-US')) })); + const dialog = await ask(); + const alpha = await within(dialog).findByTestId(`package-create-ask-option-${PKG_A}`); + expect(alpha).toHaveAttribute('data-state', 'unchecked'); + expect(within(dialog).getByTestId('package-create-ask-continue')).toBeDisabled(); + fireEvent.click(alpha); + fireEvent.click(within(dialog).getByTestId('package-create-ask-continue')); + expect(await screen.findByTestId('create-opened')).toHaveTextContent(`?scope=environment&package=${PKG_A}`); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.pairCreate-36897.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.pairCreate-36897.test.tsx index 66637f3c719..3c801f008bb 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.pairCreate-36897.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.pairCreate-36897.test.tsx @@ -120,10 +120,11 @@ function Location() { return
{`${l.pathname}${l.search}`}
; } -function mount(host: MetadataAreaHost | null, type: string) { +function mount(host: MetadataAreaHost | null, type: string, setupPackage?: string) { const base = host?.basePath ?? '/apps/setup/metadata'; + const named = host?.packageId ?? setupPackage; const tree = ( - + } /> @@ -165,8 +166,9 @@ describe('the list offers 「新建」 on a read-only base, into its pair (objec expect(createButton()).toBeNull(); }); + // Setup's address names the package (objectstack#38149: a heuristic pick asks first). it('CONTROL — Setup: 新建 goes to the item create and opens no dialog', async () => { - mount(null, 'object'); + mount(null, 'object', BASE); await screen.findByTestId(`metadata-row-crm_object_one`); fireEvent.click(createButton()!); await waitFor(() => expect(screen.getByTestId('location').textContent).toMatch(/^\/apps\/setup\/metadata\/object\/new/)); diff --git a/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.syncNextSteps-30328.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.syncNextSteps-30328.test.tsx index e0d698ad30b..4410af88303 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.syncNextSteps-30328.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.syncNextSteps-30328.test.tsx @@ -55,8 +55,9 @@ await loadStudioCatalogue('zh'); beforeEach(() => { state.saved = []; + // A client save would name no package: recorded apart, so a test sees one. state.metadataClient.save = async (_type: string, name: string) => { - state.saved.push(name); + state.saved.push(`client-save:${name}`); return {}; }; vi.mocked(toast.error).mockClear(); @@ -78,7 +79,7 @@ function Where() { /** * Setup's Datasources page with one external row, `parts_db`, whose remote - * tables are `tables`. A table in `refused` answers the draft with a 400. + * tables are `tables`. A table in `refused` answers the import with a 400. */ function renderPage(tables: string[], refused: string[] = [], language = 'en') { state.fetch = (async (url: string, init?: RequestInit) => { @@ -88,13 +89,18 @@ function renderPage(tables: string[], refused: string[] = [], language = 'en') { if (url === '/api/v1/datasources/parts_db/remote-tables') { return ok({ tables: tables.map((name) => ({ name, columnCount: 3 })) }); } - if (url === '/api/v1/datasources/parts_db/object-draft' && init?.method === 'POST') { - const { table } = JSON.parse(String(init.body)) as { table: string }; + // objectstack#38149 — Sync lands each object through the server's import + // door, which places it in the datasource's package (ruling B); the + // client never saves the object itself. + const imported = url.match(/^\/api\/v1\/datasources\/parts_db\/external\/tables\/([^/]+)\/import$/); + if (imported && init?.method === 'POST') { + const table = decodeURIComponent(imported[1]!); if (refused.includes(table)) { - return reply(400, { success: false, error: { code: 'EXTERNAL_DATASOURCE_ERROR', message: `cannot draft ${table}` } }); + return reply(400, { success: false, error: { code: 'EXTERNAL_IMPORT_ERROR', message: `cannot draft ${table}` } }); } + state.saved.push(table); const label = table.split('_').map((w) => w[0].toUpperCase() + w.slice(1)).join(' '); - return ok({ draft: { name: table, datasource: 'parts_db', definition: { name: table, label, fields: {} } } }); + return reply(201, { success: true, data: { object: { name: table, definition: { name: table, label, fields: {} }, review: [] } } }); } return reply(404, { success: false, error: { code: 'NOT_FOUND', message: `unexpected ${url}` } }); }) as typeof state.fetch; diff --git a/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx b/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx index a0e4bdb1cbe..c74a46ba8ae 100644 --- a/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx @@ -11,6 +11,8 @@ * - Create, shared: saved and published in one act, never left as a draft; a * refused save publishes nothing, and a name a pending draft holds is said * (`shareNameTaken`). + * - objectstack#38149: outside an app the create asks for its package and + * saves there; a cancelled ask writes nothing and says nothing. */ import { describe, it, expect, vi, beforeEach } from 'vitest'; @@ -27,6 +29,9 @@ const t = ((key: string, options?: { defaultValue?: string; name?: string }) => const OBJECT = 'crm_lead'; const OBJECT_DEF = { name: OBJECT, fields: { name: { type: 'text' } } }; +/** The package the create ask answers (objectstack#38149): no app here, so it asks. */ +let askAnswer: string | null = 'app.chosen'; + function rig() { const metadataClient = { save: vi.fn(async () => ({})), @@ -40,7 +45,7 @@ function rig() { objectDef: OBJECT_DEF, metadataClient, dataSource: {}, - app: { packageId: null }, + app: { packageId: null, askPackage: async () => askAnswer }, routeViewId: undefined, navigate, refresh, @@ -50,6 +55,7 @@ function rig() { } beforeEach(() => { + askAnswer = 'app.chosen'; for (const fn of Object.values(toast)) fn.mockClear(); }); @@ -73,7 +79,7 @@ describe('objectstack#36409 — Create, shared', () => { expect(r.metadataClient.save).toHaveBeenCalledTimes(1); const [type, name, , options] = r.metadataClient.save.mock.calls[0] as unknown as [string, string, unknown, Record]; expect([type, name]).toEqual(['view', `${OBJECT}.hot_leads`]); - expect(options).toEqual({ mode: 'draft', ifNoneMatch: '*' }); + expect(options).toEqual({ mode: 'draft', packageId: 'app.chosen', ifNoneMatch: '*' }); expect(r.metadataClient.publish).toHaveBeenCalledWith('view', `${OBJECT}.hot_leads`); expect(r.navigate).toHaveBeenCalledWith(`view/${OBJECT}.hot_leads`); }); @@ -104,4 +110,18 @@ describe('objectstack#36409 — Create, shared', () => { const [, options] = toast.error.mock.calls[0] as unknown as [string, { description: string }]; expect(options.description).toContain('An unpublished draft already uses this view’s name'); }); + + it('objectstack#38149: a cancelled package ask writes nothing, says nothing, and reports unsaved', async () => { + askAnswer = null; + const r = rig(); + let created = true; + await act(async () => { + created = await r.result.current.createShared({ type: 'grid', label: 'Hot leads', name: 'hot_leads' }); + }); + expect(created).toBe(false); + expect(r.metadataClient.save).not.toHaveBeenCalled(); + expect(r.metadataClient.publish).not.toHaveBeenCalled(); + expect(toast.error).not.toHaveBeenCalled(); + expect(r.navigate).not.toHaveBeenCalled(); + }); }); diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.createAsk-38149.test.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.createAsk-38149.test.ts new file mode 100644 index 00000000000..d3b784e4c49 --- /dev/null +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.createAsk-38149.test.ts @@ -0,0 +1,141 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38149 — a view or report created in the console is never saved + * naming no package. Where the app's package (or its customization package) + * cannot be had, the person is asked to pick or create one; a system app and + * a caller the ensure door refuses are refused instead, with nothing written + * (decisions Q-b of topic objectstack#37424, answered C). + * + * Controls: an app whose package is writable saves there with no ask (the + * objectstack#35624 path), and a write that creates nothing (no app: an + * in-place save of an existing row) names no package and asks nothing. + */ +import { describe, it, expect, vi } from 'vitest'; +import { + createRuntimeMetadata, + isRuntimeCreateNotSaved, + pickRuntimeCreatePackage, + resolveRuntimeCreatePackage, + saveAndPublishRuntimeMetadata, + type RuntimeCreatePackageDoors, +} from './runtime-metadata-persistence'; + +const APP = 'com.example.crm'; + +function doors( + listed: Record }>, + ensure: RuntimeCreatePackageDoors['ensureCustomization'] = async () => ({ packageId: `${APP}.custom`, writable: true }), +): RuntimeCreatePackageDoors { + return { listPackages: async () => new Map(Object.entries(listed)), ensureCustomization: vi.fn(ensure) }; +} + +const refusal = (status: number, message: string) => Object.assign(new Error(message), { status }); + +describe('resolveRuntimeCreatePackage: where a console create goes (objectstack#38149)', () => { + it('outside any app: ask', async () => { + expect(await resolveRuntimeCreatePackage(null, 'view', doors({}))).toEqual({ kind: 'ask', preselect: null }); + }); + + it('an app whose package is not listed: ask', async () => { + expect(await resolveRuntimeCreatePackage(APP, 'view', doors({}))).toEqual({ kind: 'ask', preselect: null }); + }); + + it('a base the ensure door refuses (not the caller): ask', async () => { + const d = doors({ [APP]: { writable: false, manifest: { scope: 'project' } } }, async () => { + throw refusal(409, 'The package is held by several apps.'); + }); + expect(await resolveRuntimeCreatePackage(APP, 'view', d)).toEqual({ kind: 'ask', preselect: null }); + }); + + it('a system app: refused, and the ensure door is never asked', async () => { + const d = doors({ 'com.objectstack.setup': { writable: false, manifest: { scope: 'system' } } }); + expect(await resolveRuntimeCreatePackage('com.objectstack.setup', 'view', d)).toEqual({ kind: 'refused', reason: 'system-app' }); + expect(d.ensureCustomization).not.toHaveBeenCalled(); + }); + + it('the ensure door refusing the caller itself (403): refused with its reason', async () => { + const d = doors({ [APP]: { writable: false, manifest: { scope: 'project' } } }, async () => { + throw refusal(403, 'Only the platform operator may create a customization package here.'); + }); + expect(await resolveRuntimeCreatePackage(APP, 'report', d)).toEqual({ + kind: 'refused', + reason: 'caller-refused', + message: 'Only the platform operator may create a customization package here.', + }); + }); + + it('control: a writable app package is the answer, a read-only base its pair', async () => { + expect(await resolveRuntimeCreatePackage(APP, 'view', doors({ [APP]: { writable: true } }))).toEqual({ kind: 'package', packageId: APP }); + expect(await resolveRuntimeCreatePackage(APP, 'view', doors({ [APP]: { writable: false, manifest: { scope: 'project' } } }))) + .toEqual({ kind: 'package', packageId: `${APP}.custom` }); + }); +}); + +describe('pickRuntimeCreatePackage: the ask answers, or nothing is written (objectstack#38149)', () => { + it('asks when no package can be had, and takes the answer', async () => { + const askPackage = vi.fn(async () => 'app.chosen'); + expect(await pickRuntimeCreatePackage({ packageId: APP, askPackage }, 'view', doors({}))).toBe('app.chosen'); + expect(askPackage).toHaveBeenCalledTimes(1); + }); + + it('a cancelled ask throws not-saved (cancelled)', async () => { + const err = await pickRuntimeCreatePackage({ packageId: null, askPackage: async () => null }, 'view', doors({})).catch((e) => e); + expect(isRuntimeCreateNotSaved(err) && err.reason).toBe('cancelled'); + }); + + it('a system app throws not-saved (system-app) and never asks', async () => { + const askPackage = vi.fn(async () => 'app.chosen'); + const d = doors({ 'com.objectstack.setup': { writable: false, manifest: { scope: 'system' } } }); + const err = await pickRuntimeCreatePackage({ packageId: 'com.objectstack.setup', askPackage }, 'view', d).catch((e) => e); + expect(isRuntimeCreateNotSaved(err) && err.reason).toBe('system-app'); + expect(askPackage).not.toHaveBeenCalled(); + }); +}); + +describe('the create writes name the package, or write nothing (objectstack#38149)', () => { + const client = () => ({ + save: vi.fn(async () => ({ version: 'v1' })), + publish: vi.fn(async () => ({})), + reset: vi.fn(async () => ({})), + }); + + it('createRuntimeMetadata outside any app saves into the package the person picked', async () => { + const metadataClient = client(); + // `fetch` answers the package list as empty: no app package is listed. + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200 }))); + try { + await createRuntimeMetadata('view', 'account.mine', { name: 'account.mine' }, { + metadataClient, + app: { packageId: null, askPackage: async () => 'app.chosen' }, + }); + } finally { + vi.unstubAllGlobals(); + } + expect(metadataClient.save).toHaveBeenCalledWith('view', 'account.mine', { name: 'account.mine' }, { + mode: 'draft', + packageId: 'app.chosen', + ifNoneMatch: '*', + }); + }); + + it('a cancelled ask writes nothing', async () => { + const metadataClient = client(); + const err = await saveAndPublishRuntimeMetadata('view', 'account.mine', {}, { + metadataClient, + app: { packageId: null, askPackage: async () => null }, + }).catch((e) => e); + expect(isRuntimeCreateNotSaved(err)).toBe(true); + expect(metadataClient.save).not.toHaveBeenCalled(); + expect(metadataClient.publish).not.toHaveBeenCalled(); + }); + + it('control: a write that creates nothing (no app) names no package and asks nothing', async () => { + const metadataClient = client(); + await saveAndPublishRuntimeMetadata('view', 'account.loose', { name: 'account.loose' }, { metadataClient }); + expect(metadataClient.save).toHaveBeenCalledWith('view', 'account.loose', { name: 'account.loose' }, { + mode: 'draft', + ifNoneMatch: '*', + }); + }); +}); diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.createIntoApp-35624.test.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.createIntoApp-35624.test.ts index 33616697265..4191e219220 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.createIntoApp-35624.test.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.createIntoApp-35624.test.ts @@ -92,12 +92,12 @@ afterEach(() => { describe('createRuntimeMetadata saves a new view into the app it was made in (objectstack#35624)', () => { it('a read-only base: the pair the ensure door names, sent as ?package=', async () => { stubPageFetch([{ id: 'com.example.crm', writable: false }]); - const onSavedOutsideApp = vi.fn(); + const askPackage = vi.fn(async () => null); await createRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), objectName: 'crm_account', - app: { packageId: 'com.example.crm', onSavedOutsideApp }, + app: { packageId: 'com.example.crm', askPackage }, }); expect(pageCalls).toEqual([ @@ -108,7 +108,7 @@ describe('createRuntimeMetadata saves a new view into the app it was made in (ob expect(writes[0]!.pathname).toBe('/api/v1/meta/view/crm_account.verified_domestic'); expect(writes[0]!.searchParams.get('mode')).toBe('draft'); expect(writes[0]!.searchParams.get('package')).toBe('com.example.crm.custom'); - expect(onSavedOutsideApp).not.toHaveBeenCalled(); + expect(askPackage).not.toHaveBeenCalled(); }); it('a writable app package: the app itself, and no pair is asked for', async () => { @@ -116,20 +116,32 @@ describe('createRuntimeMetadata saves a new view into the app it was made in (ob await createRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), - app: { packageId: 'com.acme.helpdesk' }, + app: { packageId: 'com.acme.helpdesk', askPackage: async () => null }, }); expect(pageCalls).toEqual(['GET /api/v1/packages']); expect(writes[0]!.searchParams.get('package')).toBe('com.acme.helpdesk'); }); - it('outside any app: saved as before, naming no package, and no package door is asked', async () => { + // objectstack#38149: a create outside any app asks for its package; the + // package doors are not asked, there being no app to ask them about. + it('outside any app: the person is asked, and the create names the package they chose', async () => { + stubPageFetch([{ id: 'com.example.crm', writable: false }]); + const askPackage = vi.fn(async () => 'app.chosen'); + + await createRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), app: { packageId: null, askPackage } }); + + expect(askPackage).toHaveBeenCalledTimes(1); + expect(pageCalls).toEqual([]); + expect(writes.map((u) => u.searchParams.get('package'))).toEqual(['app.chosen']); + }); + + it('control: with no app context (a write that creates nothing in an app), no package is named and none asked', async () => { stubPageFetch([{ id: 'com.example.crm', writable: false }]); - await createRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), app: { packageId: null } }); await createRuntimeMetadata('view', env.name, env, { metadataClient: realClient() }); expect(pageCalls).toEqual([]); - expect(writes.map((u) => u.searchParams.has('package'))).toEqual([false, false]); + expect(writes.map((u) => u.searchParams.has('package'))).toEqual([false]); }); }); diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.otherTypesUntouched-35624.test.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.otherTypesUntouched-35624.test.ts index 9966ba014fd..290c2b82521 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.otherTypesUntouched-35624.test.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.otherTypesUntouched-35624.test.ts @@ -1,38 +1,52 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectstack#35624, design step 4 — only a new VIEW is saved into the app. + * objectstack#35624, design step 4 — only a new VIEW was saved into the app; + * a report, dashboard or page create kept its package-less save. * - * `RuntimeArtifactType` also names report, dashboard and page, and nothing - * creates those through `createRuntimeMetadata` today; where one would be - * saved is not what the ruling decided. So a create of any of the three keeps - * its save exactly as before this card, even when a caller hands it an app: - * no package door is asked, no package is named, and no notice runs. + * objectstack#38149 supersedes that: a console create never names no package + * (ADR-0070 D3, ADR-0084's amendment of 2026-11-26), so a create of any of + * the three that a caller hands an app to is saved into the app's package, + * exactly as a view is. Pinned for each: the package doors are read, and the + * save names the app's writable package. */ import { describe, it, expect, vi, afterEach } from 'vitest'; import { createRuntimeMetadata, type RuntimeArtifactType } from './runtime-metadata-persistence'; +const APP = 'com.example.crm'; + afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); }); -describe('report, dashboard and page creates are untouched by the app destination (objectstack#35624)', () => { - it.each(['report', 'dashboard', 'page'])('%s: saved { mode: "draft" } and nothing else', async (type) => { - const pageFetch = vi.fn(); +describe('report, dashboard and page creates are saved into the app too (objectstack#38149)', () => { + it.each(['report', 'dashboard', 'page'])('%s: saved as a draft naming the app package', async (type) => { + const pageFetch = vi.fn(async (input: RequestInfo | URL) => + String(input) === '/api/v1/packages' + ? new Response( + JSON.stringify({ success: true, data: { packages: [{ manifest: { id: APP, scope: 'project' }, writable: true }] } }), + { status: 200, headers: { 'content-type': 'application/json' } }, + ) + : new Response('{}', { status: 404 }), + ); vi.stubGlobal('fetch', pageFetch); const metadataClient = { save: vi.fn().mockResolvedValue(undefined) }; - const onSavedOutsideApp = vi.fn(); + const askPackage = vi.fn(async () => null); await createRuntimeMetadata(type, `crm_${type}`, { label: type }, { metadataClient, - app: { packageId: 'com.example.crm', onSavedOutsideApp }, + app: { packageId: APP, askPackage }, }); expect(metadataClient.save).toHaveBeenCalledTimes(1); - expect(metadataClient.save).toHaveBeenCalledWith(type, `crm_${type}`, { label: type }, { mode: 'draft', ifNoneMatch: '*' }); - expect(pageFetch).not.toHaveBeenCalled(); - expect(onSavedOutsideApp).not.toHaveBeenCalled(); + expect(metadataClient.save).toHaveBeenCalledWith(type, `crm_${type}`, { label: type }, { + mode: 'draft', + packageId: APP, + ifNoneMatch: '*', + }); + expect(pageFetch.mock.calls.map(([u]) => String(u))).toEqual(['/api/v1/packages']); + expect(askPackage).not.toHaveBeenCalled(); }); }); diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.saveAndPublishIntoApp-36409.test.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.saveAndPublishIntoApp-36409.test.ts index e90539b4155..53d652c7b33 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.saveAndPublishIntoApp-36409.test.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.saveAndPublishIntoApp-36409.test.ts @@ -5,10 +5,11 @@ * and published in one act (`saveAndPublishRuntimeMetadata`), and its first * write lands in the app it was made in, exactly as `createRuntimeMetadata` * saves a new view (objectstack#35624, ruling C): the app's own package when - * the server lists it writable, else the pair the ensure door names, else no + * the server lists it writable, else the pair the ensure door names, else + * (objectstack#38149) the package the person picks when asked — never no * package at all. Only the SAVE names a package: the publish, and the discard * a refused publish runs, address the name's one holder (ADR-0146 D8). A type - * other than `view` ignores the app. + * other than `view` is saved into the app too (objectstack#38149). * * A REAL `MetadataClient` writes, so each pin reads the request the server * would receive; the two package doors answer through the page's `fetch`, @@ -19,6 +20,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { MetadataClient } from '@object-ui/data-objectstack'; import { saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence'; +/** An ask no case here reaches: a writable or paired app package answers first. */ +const NO_ASK = async () => null; + const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); @@ -103,7 +107,7 @@ describe('saveAndPublishRuntimeMetadata saves a new shared view into the app it saveAndPublishRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), objectName: 'crm_account', - app: { packageId: 'com.acme.helpdesk' }, + app: { packageId: 'com.acme.helpdesk', askPackage: NO_ASK }, }), ).resolves.toBe('published'); @@ -122,7 +126,7 @@ describe('saveAndPublishRuntimeMetadata saves a new shared view into the app it await saveAndPublishRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), objectName: 'crm_account', - app: { packageId: 'com.example.crm' }, + app: { packageId: 'com.example.crm', askPackage: NO_ASK }, }); expect(pageCalls).toEqual([ @@ -134,15 +138,25 @@ describe('saveAndPublishRuntimeMetadata saves a new shared view into the app it expect(packagesNamedAfterSave()).toEqual([null]); }); - it('an app whose package cannot be resolved (not listed), or no app: the save names none', async () => { + it('an app whose package cannot be resolved (not listed), or no app: the person is asked, and the save names the answer', async () => { stubPageFetch([{ id: 'com.other.app', writable: true }]); + const askPackage = vi.fn(async () => 'app.chosen'); - await saveAndPublishRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), app: { packageId: 'com.example.crm' } }); - await saveAndPublishRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), app: { packageId: null } }); - await saveAndPublishRuntimeMetadata('view', env.name, env, { metadataClient: realClient() }); + await saveAndPublishRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), app: { packageId: 'com.example.crm', askPackage } }); + await saveAndPublishRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), app: { packageId: null, askPackage } }); + expect(askPackage).toHaveBeenCalledTimes(2); expect(pageCalls).toEqual(['GET /api/v1/packages']); - expect(writes.map((w) => w.url.searchParams.get('package'))).toEqual([null, null, null, null, null, null]); + expect(writes.map((w) => w.url.searchParams.get('package'))).toEqual(['app.chosen', null, 'app.chosen', null]); + }); + + it('control: no app context (a write that creates nothing in an app) names no package and asks nothing', async () => { + stubPageFetch([{ id: 'com.other.app', writable: true }]); + + await saveAndPublishRuntimeMetadata('view', env.name, env, { metadataClient: realClient() }); + + expect(pageCalls).toEqual([]); + expect(writes.map((w) => w.url.searchParams.get('package'))).toEqual([null, null]); }); it('a refused publish: the discard of the draft this call wrote names no package either', async () => { @@ -151,7 +165,7 @@ describe('saveAndPublishRuntimeMetadata saves a new shared view into the app it await expect( saveAndPublishRuntimeMetadata('view', env.name, env, { metadataClient: realClient(true), - app: { packageId: 'com.example.crm' }, + app: { packageId: 'com.example.crm', askPackage: NO_ASK }, }), ).rejects.toBeTruthy(); @@ -161,15 +175,15 @@ describe('saveAndPublishRuntimeMetadata saves a new shared view into the app it expect(packagesNamedAfterSave().every((p) => p === null)).toBe(true); }); - it('a type other than view ignores the app: no package door is asked and the save names none', async () => { + it('a type other than view is saved into the app too (objectstack#38149)', async () => { stubPageFetch([{ id: 'com.acme.helpdesk', writable: true }]); await saveAndPublishRuntimeMetadata('dashboard', 'ops_board', { name: 'ops_board' }, { metadataClient: realClient(), - app: { packageId: 'com.acme.helpdesk' }, + app: { packageId: 'com.acme.helpdesk', askPackage: NO_ASK }, }); - expect(pageCalls).toEqual([]); - expect(writes.map((w) => w.url.searchParams.get('package'))).toEqual([null, null]); + expect(pageCalls).toEqual(['GET /api/v1/packages']); + expect(writes.map((w) => w.url.searchParams.get('package'))).toEqual(['com.acme.helpdesk', null]); }); }); diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.walledFallback-35624.test.tsx b/ui/packages/app-shell/src/views/runtime-metadata-persistence.walledFallback-35624.test.tsx index 181d6aed56d..c8dbb8bd33d 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.walledFallback-35624.test.tsx +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.walledFallback-35624.test.tsx @@ -2,19 +2,20 @@ /** * objectstack#35624, design step 3 — when the app's customization package - * cannot be had, the create still saves, as before this card (naming no - * package), and the author is told where the view went. + * could not be had, the create still saved naming no package, and the author + * was told where the view went. * - * The case the ruling names: under a wall, `POST /packages/:base/ensure-customization` - * answers a tenant administrator `403` (`refuseWalledCatalogPackageWrite`). The - * refusal is answered here in the router's error envelope, the shape - * examples/app-crm served for its `404` (`{ success: false, error: { code, - * message, httpStatus } }`). An app whose package the server does not list - * takes the same fallback: there is no package to judge. + * objectstack#38149 (decisions Q-b of topic objectstack#37424, answered C) + * supersedes that fallback: a console create never names no package. * - * The notice itself is `useRuntimeCreateApp`'s: the routed app's package by - * the draft preview bar's rule, and an info toast that says the bar does not - * count the view and where to publish it. + * - Under a wall, `POST /packages/:base/ensure-customization` answers a + * tenant administrator `403` (`refuseWalledCatalogPackageWrite`), in the + * router's error envelope: the create is refused with the door's reason, + * and nothing is written. + * - An app whose package the server does not list: the person is asked, and + * a cancelled ask writes nothing. + * - `useRuntimeCreateApp` hands the routed app's package (by the draft + * preview bar's rule) and the ask; it toasts nothing itself. */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; @@ -26,7 +27,7 @@ import { toast } from 'sonner'; // collection, never inside a clocked case (`pnpm check:test-source-alias`). import '@objectstack/lint'; import { MetadataClient } from '@object-ui/data-objectstack'; -import { createRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence'; +import { createRuntimeMetadata, isRuntimeCreateNotSaved, viewEnvelope } from './runtime-metadata-persistence'; import { useRuntimeCreateApp } from './objectViewViewCrud'; vi.mock('sonner', () => ({ @@ -92,46 +93,37 @@ afterEach(() => { vi.clearAllMocks(); }); -describe('a create the app cannot take still saves, and says where it went (objectstack#35624)', () => { - it('the ensure door refused 403: saved naming no package, and the notice runs once, after the save', async () => { +describe('a create the app cannot take is refused or asks, and never saves naming no package (objectstack#38149)', () => { + it('the ensure door refused 403: refused with the door\'s reason, nothing written, nothing asked', async () => { stubPageFetch(true); - const order: string[] = []; - const metadataClient = realClient(); - const save = metadataClient.save.bind(metadataClient); - vi.spyOn(metadataClient, 'save').mockImplementation(async (...args: Parameters) => { - const answer = await save(...args); - order.push('saved'); - return answer; - }); - const onSavedOutsideApp = vi.fn(() => order.push('notice')); - - const created = await createRuntimeMetadata('view', env.name, env, { - metadataClient, - app: { packageId: 'com.example.crm', onSavedOutsideApp }, - }); - - expect(created).toBe('crm_account.walled_view'); - expect(writes).toHaveLength(1); - expect(writes[0]!.searchParams.get('mode')).toBe('draft'); - expect(writes[0]!.searchParams.has('package')).toBe(false); - expect(order).toEqual(['saved', 'notice']); + const askPackage = vi.fn(async () => 'app.chosen'); + + const err = await createRuntimeMetadata('view', env.name, env, { + metadataClient: realClient(), + app: { packageId: 'com.example.crm', askPackage }, + }).catch((e: unknown) => e); + + expect(isRuntimeCreateNotSaved(err) && err.reason).toBe('caller-refused'); + expect((err as Error).message).toContain(WALLED.error.message); + expect(askPackage).not.toHaveBeenCalled(); + expect(writes).toEqual([]); }); - it('an app package the server does not list: the same fallback', async () => { + it('an app package the server does not list: the person is asked, and a cancel writes nothing', async () => { stubPageFetch(false); - const onSavedOutsideApp = vi.fn(); + const askPackage = vi.fn(async () => null); - await createRuntimeMetadata('view', env.name, env, { + const err = await createRuntimeMetadata('view', env.name, env, { metadataClient: realClient(), - app: { packageId: 'com.example.crm', onSavedOutsideApp }, - }); + app: { packageId: 'com.example.crm', askPackage }, + }).catch((e: unknown) => e); - expect(writes[0]!.searchParams.has('package')).toBe(false); - expect(onSavedOutsideApp).toHaveBeenCalledTimes(1); + expect(askPackage).toHaveBeenCalledTimes(1); + expect(isRuntimeCreateNotSaved(err) && err.reason).toBe('cancelled'); + expect(writes).toEqual([]); }); - it('useRuntimeCreateApp: the routed app, and an info toast naming where to publish', () => { - const t = ((_key: string, opts?: { defaultValue?: string }) => opts?.defaultValue ?? _key) as never; + it('useRuntimeCreateApp: the routed app and the ask, and no toast of its own', () => { const wrapper = ({ children }: { children: ReactNode }) => ( @@ -139,13 +131,10 @@ describe('a create the app cannot take still saves, and says where it went (obje ); - const { result } = renderHook(() => useRuntimeCreateApp(t), { wrapper }); + const { result } = renderHook(() => useRuntimeCreateApp(), { wrapper }); expect(result.current.packageId).toBe('com.example.crm'); - result.current.onSavedOutsideApp?.(); - expect(toast.info).toHaveBeenCalledTimes(1); - const [text] = vi.mocked(toast.info).mock.calls[0] as [string]; - expect(text).toMatch(/^This view was saved as a draft outside this app/); - expect(text).toContain('publish it from Home'); + expect(typeof result.current.askPackage).toBe('function'); + expect(toast.info).not.toHaveBeenCalled(); }); }); From 0a67e2d90321cd12a45ccda323d5c3b15b1e58cd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 05:15:36 +0000 Subject: [PATCH 05/18] test(app-shell): pin the ask's own wiring, the console create-app route, and the report's ask and refusal Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- ...soleCreateAppPage.createAsk-38149.test.tsx | 98 +++++++++++++ .../src/views/ReportNewPage-36692.test.tsx | 50 ++++++- .../PackageCreateAsk-38149.test.tsx | 133 ++++++++++++++++++ .../ResourceListPage.createAsk-38149.test.tsx | 25 ++++ 4 files changed, 304 insertions(+), 2 deletions(-) create mode 100644 ui/packages/app-shell/src/console/__tests__/ConsoleCreateAppPage.createAsk-38149.test.tsx create mode 100644 ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk-38149.test.tsx diff --git a/ui/packages/app-shell/src/console/__tests__/ConsoleCreateAppPage.createAsk-38149.test.tsx b/ui/packages/app-shell/src/console/__tests__/ConsoleCreateAppPage.createAsk-38149.test.tsx new file mode 100644 index 00000000000..d729b7674c0 --- /dev/null +++ b/ui/packages/app-shell/src/console/__tests__/ConsoleCreateAppPage.createAsk-38149.test.tsx @@ -0,0 +1,98 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38149 — the console's create-app route saves the wizard's new + * app into a package the author picks first (`ConsoleCreateAppPage.tsx`): + * a draft in that package under the first-write pin, then that item's + * publish. Cancel writes nothing and answers the wizard "not saved". + * + * The wizard is a stub that hands its finished app to `saveApp` (the + * wizard's own steps are plugin-designer's subject); the writes go through a + * REAL `MetadataClient` over an in-memory server recording each one. + */ + +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 { MetadataClient } from '@object-ui/data-objectstack'; + +type Write = { method: string; path: string; mode: string | null; packageId: string | null; ifNoneMatch: string | null }; +const server = { writes: [] as Write[] }; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + +async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { + const method = (init?.method ?? 'GET').toUpperCase(); + const url = new URL(String(input), 'http://console.test'); + if (method === 'PUT' || method === 'POST') { + server.writes.push({ + method, + path: url.pathname, + mode: url.searchParams.get('mode'), + packageId: url.searchParams.get('package'), + ifNoneMatch: new Headers(init?.headers).get('If-None-Match'), + }); + return json(200, { success: true, version: 'hmac-sha256:v1', seq: 1, state: method === 'PUT' ? 'draft' : 'active' }); + } + return json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); +} + +const client = vi.hoisted(() => ({ current: null as unknown })); +vi.mock('../../views/metadata-admin/useMetadata.js', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => client.current, +})); + +vi.mock('../../views/studio-design/packages-io.js', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchPackages: async () => [{ id: 'app.alpha', name: 'Alpha', writable: true, namespace: 'alpha' }], +})); + +/** The wizard, cut to its last step: Finish hands the app to `saveApp`. */ +vi.mock('@object-ui/plugin-designer', () => ({ + CreateAppPage: ({ saveApp }: { saveApp?: (name: string, app: Record) => Promise }) => { + const [answer, setAnswer] = React.useState(''); + return ( +
+ + {answer} +
+ ); + }, +})); + +import { ConsoleCreateAppPage } from '../ConsoleCreateAppPage'; + +beforeEach(() => { + server.writes = []; + client.current = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch }); +}); +afterEach(() => cleanup()); + +describe('the console create-app route asks for the package (objectstack#38149)', () => { + it('the chosen package takes the draft under the first-write pin, then its publish', async () => { + render(); + fireEvent.click(screen.getByText('finish')); + const dialog = await screen.findByTestId('package-create-ask'); + expect(server.writes).toEqual([]); + fireEvent.click(await within(dialog).findByTestId('package-create-ask-option-app.alpha')); + fireEvent.click(within(dialog).getByTestId('package-create-ask-continue')); + await waitFor(() => expect(screen.getByTestId('wizard-answer')).toHaveTextContent('true')); + expect(server.writes).toEqual([ + { method: 'PUT', path: '/api/v1/meta/app/crm_lite', mode: 'draft', packageId: 'app.alpha', ifNoneMatch: '*' }, + { method: 'POST', path: '/api/v1/meta/app/crm_lite/publish', mode: null, packageId: 'app.alpha', ifNoneMatch: null }, + ]); + }); + + it('Cancel writes nothing, and the wizard is told the app was not saved', async () => { + render(); + fireEvent.click(screen.getByText('finish')); + fireEvent.click(within(await screen.findByTestId('package-create-ask')).getByTestId('package-create-ask-cancel')); + await waitFor(() => expect(screen.getByTestId('wizard-answer')).toHaveTextContent('false')); + expect(server.writes).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx b/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx index 46273e2575f..6a79d5ca5c8 100644 --- a/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx +++ b/ui/packages/app-shell/src/views/ReportNewPage-36692.test.tsx @@ -23,7 +23,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom'; const DRAFT = vi.hoisted(() => ({ @@ -80,7 +80,7 @@ vi.mock('../providers/MetadataProvider.js', () => ({ /** The package doors `resolveRuntimeCreatePackage` asks: the listed packages, and the ensure door. */ const doors = vi.hoisted(() => ({ - listed: new Map(), + listed: new Map }>(), ensure: vi.fn(async (_base: string): Promise<{ packageId: string; writable: boolean }> => { throw new Error('not asked'); }), @@ -93,6 +93,8 @@ vi.mock('./studio-design/packages-io.js', async (importOriginal) => ({ return doors.listed; }, ensureCustomizationPackage: (base: string) => doors.ensure(base), + // objectstack#38149 — the list the create ask offers. + fetchPackages: async () => [{ id: 'app.alpha', name: 'Alpha', writable: true, namespace: 'alpha' }], })); vi.mock('@object-ui/auth', async (importOriginal) => ({ @@ -362,6 +364,50 @@ describe("the app's own New saves into the app's package, as a new view does (ob expect(toastInfo).not.toHaveBeenCalled(); expect(screen.getByTestId('where')).not.toHaveTextContent('/apps/crm/report/payment_analysis'); }); + + it('objectstack#38149: an app package the server does not list asks, and the report is saved where the person chose', async () => { + doors.listed = new Map(); + mount(); + fireEvent.click(screen.getByText('save')); + const dialog = await screen.findByTestId('package-create-ask'); + expect(client.save).not.toHaveBeenCalled(); + fireEvent.click(await within(dialog).findByTestId('package-create-ask-option-app.alpha')); + fireEvent.click(within(dialog).getByTestId('package-create-ask-continue')); + await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/apps/crm/report/payment_analysis')); + expect(client.save).toHaveBeenCalledWith( + 'report', + 'payment_analysis', + { ...DRAFT, name: 'payment_analysis' }, + { mode: 'draft', ifNoneMatch: '*', packageId: 'app.alpha' }, + ); + expect(saveAndPublish).not.toHaveBeenCalled(); + }); + + it('objectstack#38149: a cancelled ask writes nothing and says nothing', async () => { + doors.listed = new Map(); + mount(); + fireEvent.click(screen.getByText('save')); + fireEvent.click(within(await screen.findByTestId('package-create-ask')).getByTestId('package-create-ask-cancel')); + await waitFor(() => expect(screen.queryByTestId('package-create-ask')).toBeNull()); + expect(client.save).not.toHaveBeenCalled(); + expect(saveAndPublish).not.toHaveBeenCalled(); + expect(toastError).not.toHaveBeenCalled(); + expect(screen.getByTestId('builder')).toBeInTheDocument(); + }); + + it('objectstack#38149 (Q-b, C): in a system app the report is refused with the reason, and the ensure door is never asked', async () => { + doors.listed = new Map([[PKG, { writable: false, manifest: { id: PKG, scope: 'system' } }]]); + mount(); + fireEvent.click(screen.getByText('save')); + await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1)); + expect(toastError).toHaveBeenCalledWith('form.saveError', { + description: expect.stringContaining('Create the report in one of your business apps instead.'), + }); + expect(doors.ensure).not.toHaveBeenCalled(); + expect(client.save).not.toHaveBeenCalled(); + expect(saveAndPublish).not.toHaveBeenCalled(); + expect(screen.queryByTestId('package-create-ask')).toBeNull(); + }); }); describe("opened from Studio's report list (objectstack#36906, decision 13)", () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk-38149.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk-38149.test.tsx new file mode 100644 index 00000000000..11822e532b7 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk-38149.test.tsx @@ -0,0 +1,133 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38149 — the create ask itself (`PackageCreateAsk.tsx`). + * + * Pinned: + * - the list holds what the server says this caller may write, never a + * kernel package, by name; + * - the heuristic pick is pre-selected only when the list holds it, and + * Continue waits for a choice; + * - "New package…" opens the Packages page's create dialog, and the package + * it creates is the answer; closing that dialog without one returns to the + * ask; + * - Cancel answers `null`, once; + * - `usePackageCreateAsk`: a second ask answers the first `null`. + * + * The create dialog is a stub here (its own tests are + * `CreatePackageDialog.namespace.test.tsx` and its neighbours): the subject is + * the ask's wiring around it. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, renderHook, screen, waitFor, within } from '@testing-library/react'; +import type { PkgEntry } from '../studio-design/packages-io'; + +vi.mock('./PackagesPage.js', () => ({ + CreatePackageDialog: ({ open, onOpenChange, onCreated }: { + open: boolean; + onOpenChange: (v: boolean) => void; + onCreated: (id: string) => void; + }) => + open ? ( +
+ + +
+ ) : null, +})); + +import { PackageCreateAskDialog, packageAskOptions, usePackageCreateAsk } from './PackageCreateAsk'; + +afterEach(() => cleanup()); + +const entry = (id: string, name: string, extra: Partial = {}): PkgEntry => + ({ id, name, writable: true, ...extra }) as PkgEntry; + +const LIST: PkgEntry[] = [ + entry('app.zulu', 'Zulu'), + entry('app.alpha', 'Alpha'), + entry('com.vendor.crm', 'Vendor CRM', { writable: false }), + entry('com.objectstack.setup', 'Setup', { kernel: true }), +]; + +function open(props: Partial> = {}) { + const onAnswer = vi.fn(); + render( LIST} {...props} />); + return onAnswer; +} + +describe('packageAskOptions: the server verdict, kernel packages out, by name (objectstack#38149)', () => { + it('keeps the writable, drops the read-only and the kernel, and sorts by name', () => { + expect(packageAskOptions(LIST).map((p) => p.id)).toEqual(['app.alpha', 'app.zulu']); + }); +}); + +describe('PackageCreateAskDialog (objectstack#38149)', () => { + it('offers the writable packages only; Continue waits for a choice, then answers it', async () => { + const onAnswer = open(); + const dialog = await screen.findByTestId('package-create-ask'); + await within(dialog).findByTestId('package-create-ask-option-app.alpha'); + expect(within(dialog).queryByTestId('package-create-ask-option-com.vendor.crm')).toBeNull(); + expect(within(dialog).queryByTestId('package-create-ask-option-com.objectstack.setup')).toBeNull(); + expect(within(dialog).getByTestId('package-create-ask-continue')).toBeDisabled(); + fireEvent.click(within(dialog).getByTestId('package-create-ask-option-app.zulu')); + fireEvent.click(within(dialog).getByTestId('package-create-ask-continue')); + expect(onAnswer).toHaveBeenCalledWith('app.zulu'); + }); + + it('pre-selects the heuristic pick the list holds, and never one it does not', async () => { + open({ preselect: 'app.zulu' }); + expect(await screen.findByTestId('package-create-ask-option-app.zulu')).toHaveAttribute('data-state', 'checked'); + cleanup(); + open({ preselect: 'com.vendor.crm' }); + await screen.findByTestId('package-create-ask-option-app.alpha'); + expect(screen.getByTestId('package-create-ask-continue')).toBeDisabled(); + }); + + it('Cancel answers null, once', async () => { + const onAnswer = open(); + fireEvent.click(await screen.findByTestId('package-create-ask-cancel')); + expect(onAnswer).toHaveBeenCalledTimes(1); + expect(onAnswer).toHaveBeenCalledWith(null); + }); + + it('"New package…" opens the create dialog, and the package it creates is the answer', async () => { + const onAnswer = open(); + fireEvent.click(await screen.findByTestId('package-create-ask-new')); + const stub = await screen.findByTestId('create-package-stub'); + expect(screen.queryByTestId('package-create-ask')).toBeNull(); + fireEvent.click(within(stub).getByText('create')); + expect(onAnswer).toHaveBeenCalledWith('app.fresh'); + }); + + it('closing the create dialog without a package returns to the ask, answering nothing', async () => { + const onAnswer = open(); + fireEvent.click(await screen.findByTestId('package-create-ask-new')); + fireEvent.click(within(await screen.findByTestId('create-package-stub')).getByText('close')); + expect(await screen.findByTestId('package-create-ask')).toBeInTheDocument(); + expect(onAnswer).not.toHaveBeenCalled(); + }); + + it('a list that cannot be read says so, and offers no package', async () => { + open({ readPackages: async () => { throw new Error('HTTP 503'); } }); + expect(await screen.findByTestId('package-create-ask-failed')).toHaveTextContent('HTTP 503'); + expect(screen.getByTestId('package-create-ask-continue')).toBeDisabled(); + }); +}); + +describe('usePackageCreateAsk (objectstack#38149)', () => { + it('a second ask answers the first null', async () => { + const { result } = renderHook(() => usePackageCreateAsk()); + let first: Promise | undefined; + act(() => { + first = result.current.ask(); + }); + act(() => { + void result.current.ask(); + }); + await waitFor(async () => expect(await first).toBeNull()); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx index 6137befc578..1dad707d1c4 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx @@ -16,6 +16,7 @@ * - while the packages load: New is disabled; * - Setup's catalog (the environment scope, decisions Q-a of topic * objectstack#37424): New asks, and the create keeps the scope; + * - Studio's cross-package leg (`/studio/~all/metadata/TYPE`): New asks; * - Cancel opens nothing. */ import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; @@ -73,6 +74,7 @@ vi.mock('../studio-design/packages-io', async (importOriginal) => ({ // Imported AFTER the mocks so the page picks them up. import { MetadataResourceListPage } from './ResourceListPage'; +import { MetadataAreaHostContext, type MetadataAreaHost } from './metadataAreaHost'; import { t } from './i18n'; beforeEach(() => { @@ -196,3 +198,26 @@ describe('Setup catalog: a new permission set asks for its package (objectstack# expect(await screen.findByTestId('create-opened')).toHaveTextContent(`?scope=environment&package=${PKG_A}`); }); }); + +describe("Studio's cross-package leg: New asks for its package (objectstack#38149)", () => { + const ALL: MetadataAreaHost = { packageId: null, readOnly: false, basePath: '/studio/~all/metadata' }; + + it('New asks, and the create opens in the leg under the chosen package', async () => { + render( + + + + } /> + } /> + + + , + ); + fireEvent.click(await newButton()); + const dialog = await ask(); + expect(screen.queryByTestId('create-opened')).toBeNull(); + fireEvent.click(await within(dialog).findByTestId(`package-create-ask-option-${PKG_A}`)); + fireEvent.click(within(dialog).getByTestId('package-create-ask-continue')); + expect(await screen.findByTestId('create-opened')).toHaveTextContent(`?package=${PKG_A}`); + }); +}); From 5c2a6d83df3c2828a4a9fcf462e9b0168389f420 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 05:21:58 +0000 Subject: [PATCH 06/18] chore(changeset): the create ask Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .changeset/38149-create-asks-for-package.md | 22 +++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 .changeset/38149-create-asks-for-package.md diff --git a/.changeset/38149-create-asks-for-package.md b/.changeset/38149-create-asks-for-package.md new file mode 100644 index 00000000000..04c8d9d4152 --- /dev/null +++ b/.changeset/38149-create-asks-for-package.md @@ -0,0 +1,22 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/plugin-designer': patch +'@object-ui/i18n': patch +--- + +feat(app-shell): a create whose address names no package asks the person to pick a package or create one + +Clause-②: yes (widening) +Metadata-protocol: none + +The console no longer saves a new item naming no package. Where a create's package is not named, the person is asked to choose one of the packages the server says they may write (`writable: true` on `GET /api/v1/packages`, kernel packages left out), or to create a new one with the Packages page's create dialog. Nothing is written until they answer, and Cancel writes nothing. + +- Setup's metadata lists: New on a list scoped by the list's own heuristic pick (no `?package=` in the address, or the one the list wrote itself) asks, with that pick pre-selected. A `?package=` the person put in the address, by a link or by the scope selector, opens the create there with no ask, as before. New waits while the package list loads. +- Setup's catalog (`?scope=environment`) and Studio's cross-package leg (`/studio/~all/metadata/TYPE`): New asks, with nothing pre-selected. +- The item editor at a create address naming no package (a deep link to `/new`): Save asks first; the item is saved as a draft in the chosen package and published at once, and the editor opens it under that package. A position or a permission set takes this path too, instead of the live package-less create. +- A new view or report in an app: saved into the app's writable package or its customization package, as before; where neither can be had the person is asked. In a system app the create is refused with the reason (a view: save it to My views or add it in a business app; a report: create it in a business app). Where the customization package's door refuses the caller (`403`), the create is refused with the door's reason. The "saved outside this app" notice no longer runs. +- The console's create-app route asks for the package, then saves the wizard's app as a draft there and publishes it. `CreateAppPage` (plugin-designer) takes an optional `saveApp(name, app)` that replaces its own save; answering `false` keeps the wizard open with nothing done. +- Datasource Sync lands each object through the server's import door (`POST /api/v1/datasources/:name/external/tables/:remote/import`), which places it in the datasource's package, instead of a client save naming none. +- New `studio` catalogue keys `engine.packageAsk.*` (English and Chinese). + +Nothing to migrate. No server route, spec key or stored row changes. From f7433b6a505f9316c522cc164321cb8bda73ca04 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 05:37:16 +0000 Subject: [PATCH 07/18] test(app-shell): the same-address pin hands the ask, not the retired notice Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .../runtime-metadata-persistence.sameAddress-35624.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.sameAddress-35624.test.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.sameAddress-35624.test.ts index 5cbb81ed076..97965c0bb90 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.sameAddress-35624.test.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.sameAddress-35624.test.ts @@ -72,7 +72,8 @@ describe('the edit, read, discard and publish of a view address its holder by na const ctx = { metadataClient, objectName: 'crm_account', - app: { packageId: 'com.example.crm', onSavedOutsideApp: vi.fn() }, + // objectstack#38149: none of the four creates, so none asks for a package. + app: { packageId: 'com.example.crm', askPackage: vi.fn(async () => null) }, }; await persistRuntimeMetadata('view', 'crm_account.verified_domestic', { label: 'Edited' }, ctx); @@ -89,6 +90,6 @@ describe('the edit, read, discard and publish of a view address its holder by na expect(requests.map((r) => r.url.searchParams.has('package'))).toEqual([false, false, false, false]); expect(draft).toMatchObject({ label: 'Verified domestic' }); expect(globalThis.fetch).not.toHaveBeenCalled(); - expect(ctx.app.onSavedOutsideApp).not.toHaveBeenCalled(); + expect(ctx.app.askPackage).not.toHaveBeenCalled(); }); }); From 0119d245db33a77bc164d2ff0b6173346915de00 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 05:52:45 +0000 Subject: [PATCH 08/18] fix(app-shell): the editor holds the create's chosen package for the form, never in the address before the save On Studio's cross-package leg a `?package=` written before the save moved the page into the package's area and remounted the form. The answer is now held for the form: a retried Save reuses it, and the item opens under it. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .../ResourceEditPage.createAsk-38149.test.tsx | 31 ++++++++++++++++++- .../views/metadata-admin/ResourceEditPage.tsx | 25 +++++++-------- 2 files changed, 41 insertions(+), 15 deletions(-) diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createAsk-38149.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createAsk-38149.test.tsx index e7344f7b0d4..110c0375552 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createAsk-38149.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createAsk-38149.test.tsx @@ -26,7 +26,7 @@ import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; type Write = { method: string; path: string; mode: string | null; packageId: string | null }; -const server = { writes: [] as Write[] }; +const server = { writes: [] as Write[], refuseNext: false }; const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); @@ -40,6 +40,11 @@ async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { server.writes = []; + server.refuseNext = false; window.localStorage.setItem('metadata-admin:autosave', '0'); }); afterEach(() => { @@ -173,4 +179,27 @@ describe('the editor asks for a package before a create its address names none f expect(screen.queryByTestId('package-create-ask')).toBeNull(); expect(server.writes[0]).toEqual({ method: 'PUT', path: '/api/v1/meta/position/regional_lead', mode: 'draft', packageId: 'com.acme.crm' }); }); + + it('a refused first save keeps the form and the answer: the retry asks nothing and names the same package', async () => { + server.refuseNext = true; + await createAt('position', '/metadata/position/new', 'regional_lead'); + const dialog = await screen.findByTestId('package-create-ask', {}, { timeout: 8000 }); + fireEvent.click(await within(dialog).findByTestId('package-create-ask-option-app.alpha')); + fireEvent.click(within(dialog).getByTestId('package-create-ask-continue')); + await waitFor(() => expect(server.writes).toHaveLength(1), { timeout: 8000 }); + // The answer is not written into the address before the save: the form stays where it was. + expect(screen.getByTestId('where')).toHaveTextContent('/metadata/position/new'); + expect(screen.getByTestId('where')).not.toHaveTextContent('package='); + // A refusal holds Save until the form changes (the server-refusal gate): the author edits, then saves again. + fireEvent.change(document.getElementById('mdf-label') as HTMLInputElement, { target: { value: 'Regional lead' } }); + await waitFor(() => expect(screen.getByTestId('resource-save')).not.toBeDisabled()); + fireEvent.click(screen.getByTestId('resource-save')); + await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/metadata/position/regional_lead'), { timeout: 8000 }); + expect(screen.queryByTestId('package-create-ask')).toBeNull(); + expect(server.writes).toEqual([ + { method: 'PUT (refused)', path: '/api/v1/meta/position/regional_lead', mode: 'draft', packageId: 'app.alpha' }, + { method: 'PUT', path: '/api/v1/meta/position/regional_lead', mode: 'draft', packageId: 'app.alpha' }, + { method: 'POST', path: '/api/v1/meta/position/regional_lead/publish', mode: null, packageId: 'app.alpha' }, + ]); + }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index a88566330e6..239ac93cf33 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -687,9 +687,11 @@ function MetadataResourceEditPageImpl({ embedded, }: MetadataResourceEditPageImplProps) { const navigate = useNavigate(); - const [searchParams, setSearchParams] = useSearchParams(); - // objectstack#38149 — a create whose address names no package asks for one first. + const [searchParams] = useSearchParams(); + // objectstack#38149 — a create whose address names no package asks for one + // first; the answer is held for this form, so a retried Save reuses it. const { ask: askPackage, dialog: packageAskDialog } = usePackageCreateAsk(); + const chosenCreatePackageRef = React.useRef(null); // ADR-0048 — the owning package of the item being edited, carried on the // edit URL as `?package=` (emitted by the metadata list links). Scopes the // layered/draft read so a same-name collision resolves to the right @@ -2122,25 +2124,20 @@ function MetadataResourceEditPageImpl({ // objectstack#38149 (ADR-0070 D3, ADR-0084's amendment of 2026-11-26) — // a create whose address names no package (a deep link, Studio's // cross-package leg, Setup's catalog) asks the person to pick a package - // or create one before anything is written, and the address names it - // from then on, so a retried Save and the item it lands on keep it. - // Cancel writes nothing. - let activePackage = readActivePackageBinding(); + // or create one before anything is written. The answer is held for this + // form, so a retried Save reuses it, and the item opens under it. It is + // NOT written into the address before the save: on Studio's cross-package + // leg a `?package=` moves the page into that package's area, which would + // remount the form mid-save. Cancel writes nothing. + let activePackage = readActivePackageBinding() ?? (createMode ? chosenCreatePackageRef.current ?? undefined : undefined); if (createMode && !activePackage) { const chosen = await askPackage({ typeLabel: translateMetadataType(type, locale, entry?.label ?? type) }); if (!chosen) { setSaving(false); return; } + chosenCreatePackageRef.current = chosen; activePackage = chosen; - setSearchParams( - (prev) => { - const next = new URLSearchParams(prev); - next.set('package', chosen); - return next; - }, - { replace: true }, - ); } const saveOptions = { force, From 1e5b3fad9471ff48929366ed378cadfee39f8a2b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 06:08:59 +0000 Subject: [PATCH 09/18] test(app-shell): pay the source's dynamic imports at collection, inherit the wizard module's mock, count the create-app chunk Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .../ConsoleCreateAppPage.createAsk-38149.test.tsx | 6 +++++- .../views/metadata-admin/PackageCreateAsk-38149.test.tsx | 3 +++ .../ResourceEditPage.createAsk-38149.test.tsx | 5 +++++ .../ResourceEditPage.createDraftSeed-12866.test.tsx | 3 +++ .../ResourceEditPage.heldBadName-27865.test.tsx | 5 +++++ .../ResourceEditPage.liveCreate-7611.test.tsx | 5 +++++ .../ResourceEditPage.positionCreateLive-26192.test.tsx | 3 +++ .../ResourceEditPage.requiredRow-28179.test.tsx | 5 +++++ .../ResourceEditPage.seedPlaceholder-12810.test.tsx | 3 +++ .../app-shell/src/views/objectViewViewSharing.test.tsx | 3 +++ ui/scripts/__tests__/vite-declared-lazy-views.test.ts | 8 +++++--- 11 files changed, 45 insertions(+), 4 deletions(-) diff --git a/ui/packages/app-shell/src/console/__tests__/ConsoleCreateAppPage.createAsk-38149.test.tsx b/ui/packages/app-shell/src/console/__tests__/ConsoleCreateAppPage.createAsk-38149.test.tsx index d729b7674c0..bc1cfdb2559 100644 --- a/ui/packages/app-shell/src/console/__tests__/ConsoleCreateAppPage.createAsk-38149.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/ConsoleCreateAppPage.createAsk-38149.test.tsx @@ -14,6 +14,9 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// The source under test reaches `celAuthoring`'s dynamic `@objectstack/lint` +// import; its first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MetadataClient } from '@object-ui/data-objectstack'; @@ -51,7 +54,8 @@ vi.mock('../../views/studio-design/packages-io.js', async (importOriginal) => ({ })); /** The wizard, cut to its last step: Finish hands the app to `saveApp`. */ -vi.mock('@object-ui/plugin-designer', () => ({ +vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({ + ...(await importOriginal>()), CreateAppPage: ({ saveApp }: { saveApp?: (name: string, app: Record) => Promise }) => { const [answer, setAnswer] = React.useState(''); return ( diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk-38149.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk-38149.test.tsx index 11822e532b7..4e2904e5908 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk-38149.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk-38149.test.tsx @@ -22,6 +22,9 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; +// The source under test reaches `celAuthoring`'s dynamic `@objectstack/lint` +// import; its first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { act, cleanup, fireEvent, render, renderHook, screen, waitFor, within } from '@testing-library/react'; import type { PkgEntry } from '../studio-design/packages-io'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createAsk-38149.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createAsk-38149.test.tsx index 110c0375552..7627c85362b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createAsk-38149.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createAsk-38149.test.tsx @@ -21,6 +21,11 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// The source under test reaches `celAuthoring`'s dynamic `@objectstack/lint` +// import; its first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; +// …and `anchors.ts`'s dynamic `@object-ui/plugin-detail` import, the same way. +import '@object-ui/plugin-detail'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createDraftSeed-12866.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createDraftSeed-12866.test.tsx index 7743aa5d148..589dd9e2e8f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createDraftSeed-12866.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createDraftSeed-12866.test.tsx @@ -24,6 +24,9 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// The source under test reaches `celAuthoring`'s dynamic `@objectstack/lint` +// import; its first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { z } from 'zod'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.heldBadName-27865.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.heldBadName-27865.test.tsx index 6b4ff6ff828..055204ee4ec 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.heldBadName-27865.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.heldBadName-27865.test.tsx @@ -29,6 +29,11 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// The source under test reaches `celAuthoring`'s dynamic `@objectstack/lint` +// import; its first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; +// …and `anchors.ts`'s dynamic `@object-ui/plugin-detail` import, the same way. +import '@object-ui/plugin-detail'; import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { z } from 'zod'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.liveCreate-7611.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.liveCreate-7611.test.tsx index 4f9df37ec75..9e5f8f38499 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.liveCreate-7611.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.liveCreate-7611.test.tsx @@ -24,6 +24,11 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// The source under test reaches `celAuthoring`'s dynamic `@objectstack/lint` +// import; its first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; +// …and `anchors.ts`'s dynamic `@object-ui/plugin-detail` import, the same way. +import '@object-ui/plugin-detail'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.positionCreateLive-26192.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.positionCreateLive-26192.test.tsx index 77a1eae1442..91d4da21cf2 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.positionCreateLive-26192.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.positionCreateLive-26192.test.tsx @@ -28,6 +28,9 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// The source under test reaches `celAuthoring`'s dynamic `@objectstack/lint` +// import; its first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.requiredRow-28179.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.requiredRow-28179.test.tsx index 1508ae7e20c..5878e727d8f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.requiredRow-28179.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.requiredRow-28179.test.tsx @@ -23,6 +23,11 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// The source under test reaches `celAuthoring`'s dynamic `@objectstack/lint` +// import; its first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; +// …and `anchors.ts`'s dynamic `@object-ui/plugin-detail` import, the same way. +import '@object-ui/plugin-detail'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { z } from 'zod'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.seedPlaceholder-12810.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.seedPlaceholder-12810.test.tsx index e149246737d..84e1a333e8f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.seedPlaceholder-12810.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.seedPlaceholder-12810.test.tsx @@ -23,6 +23,9 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// The source under test reaches `celAuthoring`'s dynamic `@objectstack/lint` +// import; its first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { z } from 'zod'; diff --git a/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx b/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx index c74a46ba8ae..a5ed5d2bb8c 100644 --- a/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewSharing.test.tsx @@ -16,6 +16,9 @@ */ import { describe, it, expect, vi, beforeEach } from 'vitest'; +// The source under test reaches `celAuthoring`'s dynamic `@objectstack/lint` +// import; its first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { renderHook, act } from '@testing-library/react'; const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() })); diff --git a/ui/scripts/__tests__/vite-declared-lazy-views.test.ts b/ui/scripts/__tests__/vite-declared-lazy-views.test.ts index 6abdb339756..e56dcefe395 100644 --- a/ui/scripts/__tests__/vite-declared-lazy-views.test.ts +++ b/ui/scripts/__tests__/vite-declared-lazy-views.test.ts @@ -86,9 +86,10 @@ describe('parseDeclaredLazyViews', () => { // marketplace pages (objectui#6681 measured three; objectui#12733 retired the // Installed Apps one), the app's report index (objectui#13020), the // object list (objectstack#33581), the new-report builder page - // (objectstack#36374) and the full-page inbox (objectstack#36741) = - // fifteen distinct files. - expect(declared).toHaveLength(15); + // (objectstack#36374), the full-page inbox (objectstack#36741) and the + // console's create-app route, which asks for the new app's package + // (objectstack#38149) = sixteen distinct files. + expect(declared).toHaveLength(16); for (const view of declared) { expect(fs.existsSync(path.join(REPO_ROOT, view)), view).toBe(true); } @@ -98,6 +99,7 @@ describe('parseDeclaredLazyViews', () => { expect(declared).toContain('packages/app-shell/src/views/ObjectView.tsx'); expect(declared).toContain('packages/app-shell/src/views/ReportNewPage.tsx'); expect(declared).toContain('packages/app-shell/src/views/inbox/InboxPage.tsx'); + expect(declared).toContain('packages/app-shell/src/console/ConsoleCreateAppPage.tsx'); // The three surfaces objectui#6535 deliberately looked away from and // objectui#6681 measured. Named individually: a bare length assertion goes // on passing if the widened matcher swaps one surface for another. From 328b0d230ae1fd303237baeef11663af11c8a241 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 06:47:20 +0000 Subject: [PATCH 10/18] fix(app-shell): Setup access directory reads its sub-path at the package-id address The shell serves Setup at its package id, not at the setup alias the page prefix-read on, so the sub-path came out empty there and Positions, New rendered a blank page. Read the route's own splat instead. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .changeset/38149-create-asks-for-package.md | 1 + ...sDirectoryPage.aliasAddress-38206.test.tsx | 86 +++++++++++++++++++ .../src/views/setup/AccessDirectoryPage.tsx | 15 +++- 3 files changed, 98 insertions(+), 4 deletions(-) create mode 100644 ui/packages/app-shell/src/views/setup/AccessDirectoryPage.aliasAddress-38206.test.tsx diff --git a/.changeset/38149-create-asks-for-package.md b/.changeset/38149-create-asks-for-package.md index 04c8d9d4152..45ccbd0b453 100644 --- a/.changeset/38149-create-asks-for-package.md +++ b/.changeset/38149-create-asks-for-package.md @@ -17,6 +17,7 @@ The console no longer saves a new item naming no package. Where a create's packa - A new view or report in an app: saved into the app's writable package or its customization package, as before; where neither can be had the person is asked. In a system app the create is refused with the reason (a view: save it to My views or add it in a business app; a report: create it in a business app). Where the customization package's door refuses the caller (`403`), the create is refused with the door's reason. The "saved outside this app" notice no longer runs. - The console's create-app route asks for the package, then saves the wizard's app as a draft there and publishes it. `CreateAppPage` (plugin-designer) takes an optional `saveApp(name, app)` that replaces its own save; answering `false` keeps the wizard open with nothing done. - Datasource Sync lands each object through the server's import door (`POST /api/v1/datasources/:name/external/tables/:remote/import`), which places it in the datasource's package, instead of a client save naming none. +- Setup → Access control → Positions and permissions reads its own sub-path at the address the shell serves Setup at (`/apps/com.objectstack.setup/...`) as well as at the `setup` alias, so New on a position or a permission set opens the editor in Studio instead of a blank page, and a list gets the environment scope on both addresses (objectstack#38206). - New `studio` catalogue keys `engine.packageAsk.*` (English and Chinese). Nothing to migrate. No server route, spec key or stored row changes. diff --git a/ui/packages/app-shell/src/views/setup/AccessDirectoryPage.aliasAddress-38206.test.tsx b/ui/packages/app-shell/src/views/setup/AccessDirectoryPage.aliasAddress-38206.test.tsx new file mode 100644 index 00000000000..b8652ef9717 --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/AccessDirectoryPage.aliasAddress-38206.test.tsx @@ -0,0 +1,86 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38206 — the Setup access directory reads its own sub-path on + * every address the shell serves it at. The shell serves Setup at its package + * id (`/apps/com.objectstack.setup/...`), not at the `setup` alias the page's + * constant spells; a prefix read on the alias left the sub-path empty there, + * so Positions → New rendered a blank page instead of opening the editor. + * + * At both addresses: + * 1. A create (`position/new`) opens in Studio, on the environment scope's + * editor. + * 2. A type's list outside the environment scope gets it, and the list renders. + * + * The metadata-admin pages are stubs; the gate is `usePermissions`' answer, stubbed. + */ + +import '@testing-library/jest-dom/vitest'; +// The page's source reach loads this lazily; pay that load during collection (check:test-source-alias). +import '@objectstack/lint'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import * as React from 'react'; +import { cleanup, render, screen } from '@testing-library/react'; +import { MemoryRouter, Route, Routes, useLocation, useParams } from 'react-router-dom'; + +function PageStub({ page }: { page: string }) { + const { type } = useParams(); + return
; +} + +vi.mock('../metadata-admin/index.js', () => ({ + MetadataDirectoryPage: () => , + MetadataResourceListPage: () => , +})); + +vi.mock('@object-ui/permissions', async (importOriginal) => ({ + ...(await importOriginal>()), + usePermissions: () => ({ + systemPermissions: ['studio.access'], + hasCapabilities: () => true, + }), +})); + +import { AccessDirectoryPage } from './AccessDirectoryPage'; + +function Where() { + const { pathname, search } = useLocation(); + return
{`${pathname}${search}`}
; +} + +function mount(url: string) { + return render( + + + + } /> + } /> + + , + ); +} + +const where = () => screen.getByTestId('where').textContent; + +afterEach(() => cleanup()); + +const ADDRESSES = [ + ['the package-id address the shell serves', '/apps/com.objectstack.setup/component/security/access-directory'], + ['the setup alias', '/apps/setup/component/security/access-directory'], +] as const; + +describe.each(ADDRESSES)('at %s (objectstack#38206)', (_label, base) => { + it('a create opens in Studio, on the environment scope\'s editor', async () => { + mount(`${base}/position/new?scope=environment`); + expect(await screen.findByTestId('studio')).toBeInTheDocument(); + expect(where()).toBe('/studio/~all/metadata/position/new?scope=environment'); + }); + + it('a list outside the environment scope gets it, and the list renders', async () => { + mount(`${base}/position`); + const el = await screen.findByTestId('area-page'); + expect(el.getAttribute('data-page')).toBe('list'); + expect(el.getAttribute('data-type')).toBe('position'); + expect(where()).toBe(`${base}/position?scope=environment`); + }); +}); diff --git a/ui/packages/app-shell/src/views/setup/AccessDirectoryPage.tsx b/ui/packages/app-shell/src/views/setup/AccessDirectoryPage.tsx index 8416707dbe0..0278a56668e 100644 --- a/ui/packages/app-shell/src/views/setup/AccessDirectoryPage.tsx +++ b/ui/packages/app-shell/src/views/setup/AccessDirectoryPage.tsx @@ -17,7 +17,7 @@ */ import * as React from 'react'; -import { Navigate, Route, Routes, useLocation } from 'react-router-dom'; +import { Navigate, Route, Routes, useLocation, useParams } from 'react-router-dom'; import { Alert, AlertDescription } from '@object-ui/components'; import { usePermissions } from '@object-ui/permissions'; import { MetadataAreaHostContext, type MetadataAreaHost } from '../metadata-admin/metadataAreaHost.js'; @@ -49,6 +49,7 @@ function Loading({ locale }: { locale: string }): React.ReactElement { export function AccessDirectoryPage(): React.ReactElement { const { pathname, search } = useLocation(); + const { '*': splat } = useParams(); const locale = useMetadataLocale(); const { systemPermissions } = usePermissions(); const allowed = holdsAccessDirectoryCapability(systemPermissions); @@ -65,9 +66,15 @@ export function AccessDirectoryPage(): React.ReactElement { ); } - const rest = pathname.startsWith(ACCESS_DIRECTORY_PATH) - ? pathname.slice(ACCESS_DIRECTORY_PATH.length).replace(/^\/+/, '') - : ''; + // The sub-path below this page is the route's own splat, so it is read on + // every address the shell serves the page at: the shell serves Setup at its + // package id (`/apps/com.objectstack.setup/...`), not at the `setup` alias + // `ACCESS_DIRECTORY_PATH` spells (objectstack#38206). The prefix read stays + // only for a mount without a splat. + const rest = ( + splat ?? + (pathname.startsWith(ACCESS_DIRECTORY_PATH) ? pathname.slice(ACCESS_DIRECTORY_PATH.length) : '') + ).replace(/^\/+/, ''); const redirect = accessDirectoryLocation(rest, search); if (redirect) return ; From 4b15ae42d80241f7a065fed57ad7af0495af2d0a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 06:55:49 +0000 Subject: [PATCH 11/18] test(app-shell): the scoped list address is spelled at the setup alias Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .../AccessDirectoryPage.aliasAddress-38206.test.tsx | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/ui/packages/app-shell/src/views/setup/AccessDirectoryPage.aliasAddress-38206.test.tsx b/ui/packages/app-shell/src/views/setup/AccessDirectoryPage.aliasAddress-38206.test.tsx index b8652ef9717..b2af4f06634 100644 --- a/ui/packages/app-shell/src/views/setup/AccessDirectoryPage.aliasAddress-38206.test.tsx +++ b/ui/packages/app-shell/src/views/setup/AccessDirectoryPage.aliasAddress-38206.test.tsx @@ -11,6 +11,9 @@ * 1. A create (`position/new`) opens in Studio, on the environment scope's * editor. * 2. A type's list outside the environment scope gets it, and the list renders. + * The scoped address is spelled at the `setup` alias, as + * `accessDirectoryLocation` spells it (kept as is); the shell serves the + * alias at the package id. * * The metadata-admin pages are stubs; the gate is `usePermissions`' answer, stubbed. */ @@ -64,9 +67,11 @@ const where = () => screen.getByTestId('where').textContent; afterEach(() => cleanup()); +const SETUP = '/apps/setup/component/security/access-directory'; + const ADDRESSES = [ ['the package-id address the shell serves', '/apps/com.objectstack.setup/component/security/access-directory'], - ['the setup alias', '/apps/setup/component/security/access-directory'], + ['the setup alias', SETUP], ] as const; describe.each(ADDRESSES)('at %s (objectstack#38206)', (_label, base) => { @@ -81,6 +86,6 @@ describe.each(ADDRESSES)('at %s (objectstack#38206)', (_label, base) => { const el = await screen.findByTestId('area-page'); expect(el.getAttribute('data-page')).toBe('list'); expect(el.getAttribute('data-type')).toBe('position'); - expect(where()).toBe(`${base}/position?scope=environment`); + expect(where()).toBe(`${SETUP}/position?scope=environment`); }); }); From 5bb904f21d6ea139a384414af2450e4e9fb07ef8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:13:56 +0000 Subject: [PATCH 12/18] test(app-shell): the cross-package leg's create answers the package ask The leg's New asks for the package with nothing pre-selected, so the pin that New alone picked the first package retargets to the ask. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .../StudioMetadataArea.allList-29566.test.tsx | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.allList-29566.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.allList-29566.test.tsx index 08214cec063..86cd79ab615 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.allList-29566.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.allList-29566.test.tsx @@ -18,7 +18,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, screen, cleanup, waitFor, fireEvent } from '@testing-library/react'; +import { render, screen, cleanup, waitFor, fireEvent, within } from '@testing-library/react'; import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; const PROJECT = 'com.example.crm'; @@ -81,6 +81,11 @@ vi.mock('./packages-io.js', async (importOriginal) => ({ [OTHER, { id: OTHER, name: 'HR', writable: true, manifest: {} }], ]), ), + /** The same list as the create ask reads it (objectstack#38149). */ + fetchPackages: async () => [ + { id: OTHER, name: 'HR', writable: true, namespace: 'hr' }, + { id: PROJECT, name: 'CRM', writable: true, namespace: 'crm' }, + ], })); import { StudioMetadataArea } from './StudioMetadataArea'; @@ -152,10 +157,15 @@ describe('the cross-package list stays open (objectstack#29566)', () => { expect(where()).toBe('/studio/~all/metadata/flow'); }); - it('create alone picks a package, and opens that package\'s create', async () => { + // Create on the cross-package leg asks which package, with nothing pre-selected + // (objectstack#38149), and opens the chosen package's create. + it('create asks for a package, and opens the chosen package\'s create', async () => { mount('/studio/~all/metadata/object'); await waitFor(() => expect(row('crm_account')).not.toBeNull(), WAIT); fireEvent.click(screen.getAllByRole('button', { name: new RegExp(t('engine.list.create', 'en-US')) })[0]); + const dialog = await screen.findByTestId('package-create-ask', {}, WAIT); + fireEvent.click(await within(dialog).findByTestId(`package-create-ask-option-${PROJECT}`, {}, WAIT)); + fireEvent.click(within(dialog).getByTestId('package-create-ask-continue')); await waitFor(() => expect(where()).toBe(`/studio/${PROJECT}/metadata/object/new?package=${PROJECT}`), WAIT); }); }); From e9cf6567da3a22a28e371a0a9152ad924c73d864 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:14:50 +0000 Subject: [PATCH 13/18] test(app-shell): the chart door reads the routed app's package; the ask is a package-create door The Save as view chart case stubbed the authenticated fetch as a no-op, so the create's package read failed and the create asked instead of saving. The resource list's create-package door now lives in the create ask. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .../src/views/CreateViewDialog.chartBinding-11576.test.tsx | 4 +++- .../PackageFormDialog.newAppStep-36748.test.tsx | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/ui/packages/app-shell/src/views/CreateViewDialog.chartBinding-11576.test.tsx b/ui/packages/app-shell/src/views/CreateViewDialog.chartBinding-11576.test.tsx index e3d538f438f..9cdd0b89a14 100644 --- a/ui/packages/app-shell/src/views/CreateViewDialog.chartBinding-11576.test.tsx +++ b/ui/packages/app-shell/src/views/CreateViewDialog.chartBinding-11576.test.tsx @@ -139,7 +139,9 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }), useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), - createAuthenticatedFetch: () => vi.fn(), + // objectstack#38149 — the package list a create reads goes through the + // page's `fetch`, so the routed app's writable package answers it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, init), })); vi.mock('@object-ui/plugin-list', async (importOriginal) => ({ ...(await importOriginal()), diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx index 879f06e79d4..10cf7ace8f4 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageFormDialog.newAppStep-36748.test.tsx @@ -465,11 +465,13 @@ function mounts(component: string): string[] { } describe('every create-package door offers 「同时创建应用」 (objectstack#37134)', () => { - it('Setup → Packages (its button and the `?new=package` door), the resource list and Studio’s package switcher (objectstack#37456) mount CreatePackageDialog', () => { + // The resource list's door moved into the create ask's "New package…" + // (objectstack#38149), which the list, the editor and the app creates mount. + it('Setup → Packages (its button and the `?new=package` door), the create ask (objectstack#38149) and Studio’s package switcher (objectstack#37456) mount CreatePackageDialog', () => { const doors = mounts('CreatePackageDialog').map((m) => m.split(':')[0]); expect(doors.sort()).toEqual([ + 'views/metadata-admin/PackageCreateAsk.tsx', 'views/metadata-admin/PackagesPage.tsx', - 'views/metadata-admin/ResourceListPage.tsx', 'views/studio-design/StudioPackageSwitcher.tsx', ]); }); From dca301308005b5e4a07446825bc1c8d0a0ff8b2f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:25:10 +0000 Subject: [PATCH 14/18] test(app-shell): pin the create-ask paths the in-app creates now take The Create View refusal cases and the new-dataset seed cases created with no readable package, so the create asked instead of saving: the routed app's package answers the first, the address names one for the second. The create-app route's lazy boundary is the console wrapper now, so the two route tests pay its load at collection as they pay the designer's. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .../__tests__/AppContent.noAppsCta.test.tsx | 5 +++++ .../AppContent.pseudoRouteSegments.test.tsx | 5 +++++ .../ObjectView.createViewRefusal-11578.test.tsx | 15 +++++++++++++-- ...ltInspector.firstPickKeepsCount-12848.test.tsx | 4 ++++ 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.noAppsCta.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.noAppsCta.test.tsx index b6d54a076ff..7bbe0351dda 100644 --- a/ui/packages/app-shell/src/console/__tests__/AppContent.noAppsCta.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.noAppsCta.test.tsx @@ -93,6 +93,11 @@ vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({ // identical to the component's own, so ESM hands the lazy factory this // already-resolved module. import '@object-ui/plugin-designer'; +// objectstack#38149 — the route's lazy boundary is now the console's wrapper +// (`React.lazy(() => import('./ConsoleCreateAppPage.js'))`), whose own graph +// (the package ask, the Packages page's create dialog) was a second unbounded +// load inside the same `findByTestId` budget. Paid here too, for the same reason. +import '../ConsoleCreateAppPage'; vi.mock('@object-ui/i18n', async (importOriginal) => ({ ...(await importOriginal>()), diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.pseudoRouteSegments.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.pseudoRouteSegments.test.tsx index bdbbffe2c6b..f7ef242fe1c 100644 --- a/ui/packages/app-shell/src/console/__tests__/AppContent.pseudoRouteSegments.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.pseudoRouteSegments.test.tsx @@ -191,6 +191,11 @@ vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({ // identical to the component's own, so ESM hands the lazy factory this // already-resolved module. import '@object-ui/plugin-designer'; +// objectstack#38149 — the route's lazy boundary is now the console's wrapper +// (`React.lazy(() => import('./ConsoleCreateAppPage.js'))`), whose own graph +// (the package ask, the Packages page's create dialog) was a second unbounded +// load inside the same `findByTestId` budget. Paid here too, for the same reason. +import '../ConsoleCreateAppPage'; /** * The probe that makes the bug visible: it reports WHICH app's shell rendered. diff --git a/ui/packages/app-shell/src/views/ObjectView.createViewRefusal-11578.test.tsx b/ui/packages/app-shell/src/views/ObjectView.createViewRefusal-11578.test.tsx index ac3d7e6a927..946ba225cf9 100644 --- a/ui/packages/app-shell/src/views/ObjectView.createViewRefusal-11578.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.createViewRefusal-11578.test.tsx @@ -62,7 +62,9 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({ useAuth: () => ({ user: { id: 'u1', name: 'Ada' }, activeOrganization: null }), // The add-view button and the dialog are admin-only. useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), - createAuthenticatedFetch: () => vi.fn(), + // objectstack#38149 — the package list a create reads goes through the + // page's `fetch`, so the routed app's writable package answers it. + createAuthenticatedFetch: () => (input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, init), })); vi.mock('@object-ui/collaboration', async (importOriginal) => ({ @@ -211,7 +213,16 @@ beforeEach(() => { cleanup(); puts.length = 0; client = new MetadataClient({ baseUrl: 'http://localhost', fetch: wire() as unknown as typeof fetch }); - vi.stubGlobal('fetch', vi.fn(async () => json({ data: [] }, 200))); + // objectstack#38149 — the routed app `demo` is a writable package, so the + // create saves into it; every other page read answers empty, as before. + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => + String(input) === '/api/v1/packages' + ? json({ success: true, data: { packages: [{ manifest: { id: 'demo', name: 'Demo' }, writable: true }] } }, 200) + : json({ data: [] }, 200), + ), + ); vi.spyOn(console, 'error').mockImplementation(() => {}); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DatasetDefaultInspector.firstPickKeepsCount-12848.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DatasetDefaultInspector.firstPickKeepsCount-12848.test.tsx index 45bee268d88..1256866490b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DatasetDefaultInspector.firstPickKeepsCount-12848.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DatasetDefaultInspector.firstPickKeepsCount-12848.test.tsx @@ -100,11 +100,15 @@ registerBuiltinPreviews(); registerBuiltinInspectors(); beforeEach(() => { + // objectstack#38149 — a create whose address names no package asks for one + // first; this create's address names its package, as Setup's list now writes. + window.history.replaceState(null, '', '/?package=app.test'); server.puts = []; window.localStorage.setItem('metadata-admin:autosave', '0'); }); afterEach(() => { cleanup(); + window.history.replaceState(null, '', '/'); window.localStorage.removeItem('metadata-admin:autosave'); }); From 958d1c111fa5bcec97e85a070d8891a8a2b0bbbb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 07:27:52 +0000 Subject: [PATCH 15/18] test(app-shell): pay the lint load at collection in the retargeted create tests Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .../src/console/__tests__/AppContent.noAppsCta.test.tsx | 3 +++ .../DatasetDefaultInspector.firstPickKeepsCount-12848.test.tsx | 3 +++ .../studio-design/StudioMetadataArea.allList-29566.test.tsx | 3 +++ 3 files changed, 9 insertions(+) diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.noAppsCta.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.noAppsCta.test.tsx index 7bbe0351dda..aef6fe41724 100644 --- a/ui/packages/app-shell/src/console/__tests__/AppContent.noAppsCta.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.noAppsCta.test.tsx @@ -60,6 +60,9 @@ */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches a dynamic `@objectstack/lint` import; its first +// load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { describe, it, expect, vi, beforeEach } from 'vitest'; import React from 'react'; import { render, screen, fireEvent, waitFor } from '@testing-library/react'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DatasetDefaultInspector.firstPickKeepsCount-12848.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DatasetDefaultInspector.firstPickKeepsCount-12848.test.tsx index 1256866490b..fc0e93bcc16 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DatasetDefaultInspector.firstPickKeepsCount-12848.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DatasetDefaultInspector.firstPickKeepsCount-12848.test.tsx @@ -21,6 +21,9 @@ */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches a dynamic `@objectstack/lint` import; its first +// load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.allList-29566.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.allList-29566.test.tsx index 86cd79ab615..5be560ff22d 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.allList-29566.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioMetadataArea.allList-29566.test.tsx @@ -16,6 +16,9 @@ */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches a dynamic `@objectstack/lint` import; its first +// load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; import * as React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, cleanup, waitFor, fireEvent, within } from '@testing-library/react'; From 6b589fc6a9e58efcd5e0fdb44761873fe25b9ed7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:07:03 +0000 Subject: [PATCH 16/18] fix(app-shell): Setup's catalog asks for a new item's package once, at Save The catalog's New asked and wrote the answer into the create's address, but Studio's area drops ?package= under the environment scope, so the editor's Save asked a second time. New now opens the create in the scope and the editor's Save asks. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- ...rceListPage.catalogAsksOnce-38149.test.tsx | 161 ++++++++++++++++++ .../ResourceListPage.createAsk-38149.test.tsx | 19 +-- .../views/metadata-admin/ResourceListPage.tsx | 19 ++- 3 files changed, 183 insertions(+), 16 deletions(-) create mode 100644 ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.catalogAsksOnce-38149.test.tsx diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.catalogAsksOnce-38149.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.catalogAsksOnce-38149.test.tsx new file mode 100644 index 00000000000..36767f94b4b --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.catalogAsksOnce-38149.test.tsx @@ -0,0 +1,161 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38149 — Setup's catalog (the environment scope, decisions Q-a of + * topic objectstack#37424) asks for a new item's package exactly once, at Save. + * + * The catalog's New used to ask too, and wrote the answer into the create's + * address. Studio's area drops `?package=` under the environment scope + * (`areaLocationRedirect`), where every catalog create of a position or a + * permission set lands, so the editor's Save asked a second time (measured + * live). New now opens the create in the scope, naming no package, and Save + * asks; the save names the chosen package. + * + * The REAL list and the REAL editor, mounted on Setup's two routes, over a + * REAL `MetadataClient` whose transport is an in-memory server recording each + * write; the permission set's registration is the real one. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// The source under test reaches `celAuthoring`'s dynamic `@objectstack/lint` +// import; its first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; +// …and `anchors.ts`'s dynamic `@object-ui/plugin-detail` import, the same way. +import '@object-ui/plugin-detail'; +import '@objectstack/spec/identity'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; +import { MetadataClient } from '@object-ui/data-objectstack'; + +type Write = { method: string; path: string; mode: string | null; packageId: string | null }; +const server = { writes: [] as Write[] }; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + +async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { + const method = (init?.method ?? 'GET').toUpperCase(); + const url = new URL(String(input), 'http://console.test'); + const meta = url.pathname.match(/^\/api\/v1\/meta\/(.+)$/); + if (!meta) return json(200, []); + const seg = meta[1].split('/').map(decodeURIComponent); + if (seg[0] === '_drafts') return json(200, { drafts: [] }); + if (seg.length === 1) return json(200, { items: [] }); + if (method === 'PUT' || method === 'POST') { + server.writes.push({ method, path: url.pathname, mode: url.searchParams.get('mode'), packageId: url.searchParams.get('package') }); + return json(200, { success: true, version: 'hmac-sha256:v1', seq: 1, state: method === 'PUT' ? 'draft' : 'active', message: 'Saved' }); + } + return json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); +} + +const client = vi.hoisted(() => ({ current: null as unknown })); + +const SCHEMA = { + type: 'object', + required: ['name'], + properties: { name: { type: 'string' }, label: { type: 'string' }, description: { type: 'string' } }, +}; + +vi.mock('./useMetadata', async (importOriginal) => ({ + ...(await importOriginal()), + useMetadataClient: () => client.current, + useMetadataTypes: () => ({ + loading: false, + error: null, + entries: [{ type: 'permission', label: 'Permission Set', domain: 'security', allowEnvironmentOverlay: false, allowRuntimeCreate: true, schema: SCHEMA }], + }), +})); + +vi.mock('./i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataLocale: () => 'en-US', +})); + +vi.mock('../../hooks/useCanAuthorMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useCanAuthorMetadata: () => true, +})); + +/** The server's package list the ask reads, with its `writable` verdict. */ +vi.mock('../studio-design/packages-io', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchPackages: async () => [ + { id: 'app.alpha', name: 'Alpha', writable: true, namespace: 'alpha' }, + { id: 'app.bravo', name: 'Bravo', writable: true, namespace: 'bravo' }, + ], +})); + +import { MetadataResourceListPage } from './ResourceListPage'; +import { MetadataResourceEditPage } from './ResourceEditPage'; +import { t } from './i18n'; +import './anchors'; +import '../../services/builtinComponents'; + +client.current = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch }); + +beforeEach(() => { + server.writes = []; + window.localStorage.setItem('metadata-admin:autosave', '0'); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify({ records: [], hasMore: false }), { status: 200, headers: { 'Content-Type': 'application/json' } })), + ); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + window.localStorage.removeItem('metadata-admin:autosave'); + window.history.replaceState(null, '', '/'); +}); + +function Where() { + const location = useLocation(); + return
{`${location.pathname}${location.search}`}
; +} + +describe('Setup catalog: a new permission set asks for its package once, at Save (objectstack#38149, Q-a)', () => { + it('New asks nothing; Save asks once; the save is a draft in the chosen package and its publish', async () => { + render( + + + + } /> + } /> + } /> + + , + ); + fireEvent.click(await screen.findByRole('button', { name: new RegExp(t('engine.list.create', 'en-US')) }, { timeout: 8000 })); + // New opens the create in the environment scope, naming no package, with no ask. + await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/apps/setup/metadata/permission/new?scope=environment')); + expect(screen.getByTestId('where')).not.toHaveTextContent('package='); + expect(screen.queryByTestId('package-create-ask')).toBeNull(); + + const input = await waitFor(() => { + const el = document.getElementById('mdf-name') as HTMLInputElement | null; + expect(el).not.toBeNull(); + return el!; + }, { timeout: 8000 }); + fireEvent.change(input, { target: { value: 'regional_set' } }); + await waitFor(() => expect((document.getElementById('mdf-name') as HTMLInputElement).value).toBe('regional_set')); + fireEvent.click(screen.getByRole('button', { name: /Save \(⌘S\)/ })); + + // Save asks, once, with nothing pre-selected. + const dialog = await screen.findByTestId('package-create-ask', {}, { timeout: 8000 }); + expect(screen.getAllByTestId('package-create-ask')).toHaveLength(1); + const alpha = await within(dialog).findByTestId('package-create-ask-option-app.alpha'); + expect(alpha).toHaveAttribute('data-state', 'unchecked'); + expect(server.writes).toEqual([]); + fireEvent.click(alpha); + fireEvent.click(within(dialog).getByTestId('package-create-ask-continue')); + + await waitFor(() => expect(server.writes).toHaveLength(2), { timeout: 8000 }); + expect(server.writes).toEqual([ + { method: 'PUT', path: '/api/v1/meta/permission/regional_set', mode: 'draft', packageId: 'app.alpha' }, + { method: 'POST', path: '/api/v1/meta/permission/regional_set/publish', mode: null, packageId: 'app.alpha' }, + ]); + await waitFor(() => expect(screen.queryByTestId('package-create-ask')).toBeNull()); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx index 1dad707d1c4..18fdfbfeca1 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx @@ -15,7 +15,8 @@ * no ask, the create opens there; * - while the packages load: New is disabled; * - Setup's catalog (the environment scope, decisions Q-a of topic - * objectstack#37424): New asks, and the create keeps the scope; + * objectstack#37424): New opens the create in the scope with no ask; the + * editor's Save asks, once (`ResourceListPage.catalogAsksOnce-38149`); * - Studio's cross-package leg (`/studio/~all/metadata/TYPE`): New asks; * - Cancel opens nothing. */ @@ -185,17 +186,15 @@ describe('Setup list: New waits for the packages (objectstack#38149)', () => { }); }); -describe('Setup catalog: a new permission set asks for its package (objectstack#38149, Q-a)', () => { - it('New asks with nothing pre-selected, and the create keeps the environment scope', async () => { +describe('Setup catalog: a new permission set opens in the environment scope (objectstack#38149, Q-a)', () => { + // The environment scope binds no package, and Studio's area drops a + // `?package=` under it: an answer asked here was lost, and Save asked again. + it('New asks nothing and opens the create in the scope, naming no package', async () => { mount('?scope=environment'); fireEvent.click(await screen.findByRole('button', { name: new RegExp(t('engine.list.create', 'en-US')) })); - const dialog = await ask(); - const alpha = await within(dialog).findByTestId(`package-create-ask-option-${PKG_A}`); - expect(alpha).toHaveAttribute('data-state', 'unchecked'); - expect(within(dialog).getByTestId('package-create-ask-continue')).toBeDisabled(); - fireEvent.click(alpha); - fireEvent.click(within(dialog).getByTestId('package-create-ask-continue')); - expect(await screen.findByTestId('create-opened')).toHaveTextContent(`?scope=environment&package=${PKG_A}`); + expect(await screen.findByTestId('create-opened')).toHaveTextContent('?scope=environment'); + expect(screen.getByTestId('create-opened')).not.toHaveTextContent('package='); + expect(screen.queryByTestId('package-create-ask')).toBeNull(); }); }); 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 c969ff8f0f6..92135175a98 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx @@ -527,21 +527,28 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string navigate(`./new${pkgSuffix}`); return; } + // Setup's catalog (positions and permission sets, decisions Q-a of topic + // objectstack#37424): the create opens in the environment scope, which + // binds no package, and the editor's Save asks for one, once. An answer + // asked here would not survive: Studio's area drops `?package=` under the + // environment scope (`areaLocationRedirect`), so Save asked a second time. + if (envScope) { + navigate(`./new?${ENVIRONMENT_SCOPE_QUERY}`); + return; + } if (packagesPending) return; // Setup's list, scoped to a package the person named. - if (!envScope && !allLeg && packageNamed && activePackage) { + if (!allLeg && packageNamed && activePackage) { navigate(`./new?package=${encodeURIComponent(activePackage)}`); return; } - // Setup's catalog (positions and permission sets, decisions Q-a of topic - // objectstack#37424), the cross-package leg, and a Setup list on a - // heuristic pick: ask. The environment scope keeps its own address. + // The cross-package leg, and a Setup list on a heuristic pick: ask. const chosen = await askPackage({ - preselect: envScope ? null : pickedPackage, + preselect: pickedPackage, typeLabel: translateMetadataType(type, locale, entry?.label ?? type), }); if (!chosen) return; - navigate(`./new?${envScope ? `${ENVIRONMENT_SCOPE_QUERY}&` : ''}package=${encodeURIComponent(chosen)}`); + navigate(`./new?package=${encodeURIComponent(chosen)}`); }, [activePackage, pickedPackage, pkgSuffix, navigate, envScope, host?.packageId, allLeg, createInDialog, packagesPending, packageNamed, askPackage, type, locale, entry?.label]); // objectui#7611 — the activation state the switch column shows. Re-read on From 75fbb8d7de063f1b3eaef918dd4bfbb4c0426c65 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:09:19 +0000 Subject: [PATCH 17/18] chore(changeset): the catalog's create asks at Save Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .changeset/38149-create-asks-for-package.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/38149-create-asks-for-package.md b/.changeset/38149-create-asks-for-package.md index 45ccbd0b453..968cec8ea11 100644 --- a/.changeset/38149-create-asks-for-package.md +++ b/.changeset/38149-create-asks-for-package.md @@ -12,7 +12,7 @@ Metadata-protocol: none The console no longer saves a new item naming no package. Where a create's package is not named, the person is asked to choose one of the packages the server says they may write (`writable: true` on `GET /api/v1/packages`, kernel packages left out), or to create a new one with the Packages page's create dialog. Nothing is written until they answer, and Cancel writes nothing. - Setup's metadata lists: New on a list scoped by the list's own heuristic pick (no `?package=` in the address, or the one the list wrote itself) asks, with that pick pre-selected. A `?package=` the person put in the address, by a link or by the scope selector, opens the create there with no ask, as before. New waits while the package list loads. -- Setup's catalog (`?scope=environment`) and Studio's cross-package leg (`/studio/~all/metadata/TYPE`): New asks, with nothing pre-selected. +- Setup's catalog (`?scope=environment`): New opens the create in the environment scope, and the editor's Save asks for the package, once. Studio's cross-package leg (`/studio/~all/metadata/TYPE`): New asks, with nothing pre-selected. - The item editor at a create address naming no package (a deep link to `/new`): Save asks first; the item is saved as a draft in the chosen package and published at once, and the editor opens it under that package. A position or a permission set takes this path too, instead of the live package-less create. - A new view or report in an app: saved into the app's writable package or its customization package, as before; where neither can be had the person is asked. In a system app the create is refused with the reason (a view: save it to My views or add it in a business app; a report: create it in a business app). Where the customization package's door refuses the caller (`403`), the create is refused with the door's reason. The "saved outside this app" notice no longer runs. - The console's create-app route asks for the package, then saves the wizard's app as a draft there and publishes it. `CreateAppPage` (plugin-designer) takes an optional `saveApp(name, app)` that replaces its own save; answering `false` keeps the wizard open with nothing done. From 65a8b199aaecec73ea927ba13ccd5faa1581871b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:15:57 +0000 Subject: [PATCH 18/18] fix(app-shell): the cross-package leg's ask pre-selects nothing The leg fell through to the heuristic pick, so the ask opened with a package checked. Pin it with the heuristic fixture, and say where the datasource import door lands an object as the page's comment does. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibzywxH36FPH6ayWMUe --- .changeset/38149-create-asks-for-package.md | 2 +- .../ResourceListPage.createAsk-38149.test.tsx | 33 +++++++++++++++++++ .../views/metadata-admin/ResourceListPage.tsx | 6 ++-- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/.changeset/38149-create-asks-for-package.md b/.changeset/38149-create-asks-for-package.md index 968cec8ea11..f6f33a19d89 100644 --- a/.changeset/38149-create-asks-for-package.md +++ b/.changeset/38149-create-asks-for-package.md @@ -16,7 +16,7 @@ The console no longer saves a new item naming no package. Where a create's packa - The item editor at a create address naming no package (a deep link to `/new`): Save asks first; the item is saved as a draft in the chosen package and published at once, and the editor opens it under that package. A position or a permission set takes this path too, instead of the live package-less create. - A new view or report in an app: saved into the app's writable package or its customization package, as before; where neither can be had the person is asked. In a system app the create is refused with the reason (a view: save it to My views or add it in a business app; a report: create it in a business app). Where the customization package's door refuses the caller (`403`), the create is refused with the door's reason. The "saved outside this app" notice no longer runs. - The console's create-app route asks for the package, then saves the wizard's app as a draft there and publishes it. `CreateAppPage` (plugin-designer) takes an optional `saveApp(name, app)` that replaces its own save; answering `false` keeps the wizard open with nothing done. -- Datasource Sync lands each object through the server's import door (`POST /api/v1/datasources/:name/external/tables/:remote/import`), which places it in the datasource's package, instead of a client save naming none. +- Datasource Sync lands each object through the server's import door (`POST /api/v1/datasources/:name/external/tables/:remote/import`), which lands it in the datasource's own package, its read-only base's `.custom` pair, or no package for a datasource that has none, instead of a client save naming none. - Setup → Access control → Positions and permissions reads its own sub-path at the address the shell serves Setup at (`/apps/com.objectstack.setup/...`) as well as at the `setup` alias, so New on a position or a permission set opens the editor in Studio instead of a blank page, and a list gets the environment scope on both addresses (objectstack#38206). - New `studio` catalogue keys `engine.packageAsk.*` (English and Chinese). diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx index 18fdfbfeca1..bff2be25908 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.createAsk-38149.test.tsx @@ -201,6 +201,39 @@ describe('Setup catalog: a new permission set opens in the environment scope (ob describe("Studio's cross-package leg: New asks for its package (objectstack#38149)", () => { const ALL: MetadataAreaHost = { packageId: null, readOnly: false, basePath: '/studio/~all/metadata' }; + it('the ask opens with nothing pre-selected, though the heuristic would pick a package, and Continue is disabled', async () => { + // The fixture's heuristic picks Bravo (it owns the rows); Setup's list + // pre-selects it (above). The case waits until the list holds the packages, so + // the pick exists when New is pressed. + let packagesRead = false; + const served = packageList; + packageList = async () => { + const list = await served(); + packagesRead = true; + return list; + }; + render( + + + + } /> + } /> + + + , + ); + await waitFor(() => expect(packagesRead).toBe(true)); + await waitFor(() => expect(screen.getByText('bravo_set')).toBeInTheDocument()); + await new Promise((r) => setTimeout(r, 50)); + fireEvent.click(await newButton()); + const dialog = await ask(); + const bravo = await within(dialog).findByTestId(`package-create-ask-option-${PKG_B}`); + expect(bravo).toHaveAttribute('data-state', 'unchecked'); + expect(within(dialog).getByTestId(`package-create-ask-option-${PKG_A}`)).toHaveAttribute('data-state', 'unchecked'); + expect(within(dialog).getByTestId('package-create-ask-continue')).toBeDisabled(); + expect(screen.queryByTestId('create-opened')).toBeNull(); + }); + it('New asks, and the create opens in the leg under the chosen package', async () => { render( 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 92135175a98..e6af4c1e3cb 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx @@ -542,9 +542,11 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string navigate(`./new?package=${encodeURIComponent(activePackage)}`); return; } - // The cross-package leg, and a Setup list on a heuristic pick: ask. + // The cross-package leg, and a Setup list on a heuristic pick: ask. The + // leg lists across packages, so nothing is pre-selected there; a Setup + // list offers its heuristic pick. const chosen = await askPackage({ - preselect: pickedPackage, + preselect: allLeg ? null : pickedPackage, typeLabel: translateMetadataType(type, locale, entry?.label ?? type), }); if (!chosen) return;