diff --git a/.changeset/38150-move-loose-items-console.md b/.changeset/38150-move-loose-items-console.md new file mode 100644 index 00000000000..c7d2e36a84f --- /dev/null +++ b/.changeset/38150-move-loose-items-console.md @@ -0,0 +1,16 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(app-shell): select loose items on Studio's cross-package list and move them into a package; the Packages page counts them + +Clause-②: yes (widening) +Metadata-protocol: none + +The console's half of the move door (`POST /api/v1/packages/:id/move-in`, ADR-0084's amendment of 2026-11-26: "Loose items stay where they are, and one door moves them"). + +- Studio's cross-package list of a type (`/studio/~all/metadata/TYPE`) offers a "Loose" source value (`?source=loose`): the items bound to no package, and only those. An item of a package's `.custom` pair and an overlay of a shipped item are not loose, though the list's "Modified and new" value holds them. +- Under "Loose", a person who may author metadata gets a select box per row, "Select all", and "Move into package…". The package is picked in the create's ask (the packages the server says they may write, or a new one), with nothing pre-selected. +- The confirm step reads the door's dry run. It shows each item and what its addresses become (`_env/NAME` → `NAMESPACE/NAME`, the name AI clients list it under), or each refused item with the door's own code and sentence. When a moved item uses a loose item the selection leaves behind, it offers to add that item and check again. Move makes the move, whole or nothing. The confirm says that a save check that runs only on the real move can still refuse an item, and that reverting the move's package commit takes the items out of the package rather than making them loose again. +- The Packages page (Setup → Packages, and its development face) shows "N items belong to no package" while there are any, counted per type, each count a link to that type's "Loose" list. It is drawn for a person who may author metadata. diff --git a/ui/packages/app-shell/src/views/metadata-admin/LooseItemsBanner-38150.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/LooseItemsBanner-38150.test.tsx new file mode 100644 index 00000000000..9cc159f571b --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/LooseItemsBanner-38150.test.tsx @@ -0,0 +1,113 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38150 PR-A2 — the Packages page's "N loose items" banner. Pinned, + * each with its control: + * + * - it counts the package-less rows of each type that takes a runtime write, + * one list read per such type, and links each count to that type's "Loose" + * list on Studio's cross-package leg (`?source=loose`), so the list is + * reached with no typed address; + * - a type that takes no runtime write is not read; + * - a type whose read fails is named as not counted, never folded into a + * smaller total; + * - nothing is drawn, and nothing read, for a reader who may not author; and + * nothing is drawn while no item is loose. + */ +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, cleanup, screen, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import * as React from 'react'; +import { MemoryRouter } from 'react-router-dom'; +// The source reaches `celAuthoring`'s dynamic `@objectstack/lint` import; its +// first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; + +let canAuthor = true; +let rows: Record = {}; +const listCalls: string[] = []; + +const CLIENT = { + list: async (type: string) => { + listCalls.push(type); + const r = rows[type]; + if (r instanceof Error) throw r; + return r ?? []; + }, +}; +const ENTRIES = [ + { type: 'flow', allowRuntimeCreate: true }, + { type: 'dataset', allowEnvironmentOverlay: true }, + { type: 'report', allowRuntimeCreate: true }, + { type: 'agent', allowRuntimeCreate: false, allowEnvironmentOverlay: false }, + { type: 'package', allowRuntimeCreate: true }, +]; + +vi.mock('./useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => CLIENT, + useMetadataTypes: () => ({ loading: false, error: null, entries: ENTRIES }), +})); +vi.mock('../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => canAuthor })); + +import { LooseItemsBanner } from './LooseItemsBanner'; + +beforeEach(() => { + canAuthor = true; + listCalls.length = 0; + rows = { + flow: [{ name: 'f1' }, { name: 'f2', _packageId: 'sys_metadata' }, { name: 'f3', _packageId: 'app.alpha' }], + dataset: [{ item: { name: 'ds1', _packageId: '' } }, { name: 'ds2', _packageId: 'app.alpha.custom' }], + report: new Error('read failed'), + agent: [{ name: 'a1' }], + package: [{ name: 'p1' }], + }; +}); +afterEach(cleanup); + +const mount = () => + render( + + + , + ); + +describe('the Packages page banner (objectstack#38150)', () => { + it('counts the loose rows per writable type and links each to its Loose list', async () => { + mount(); + const banner = await screen.findByTestId('loose-items-banner'); + expect(banner).toHaveTextContent('3 items belong to no package'); + const flow = within(banner).getByTestId('loose-items-banner-flow'); + expect(flow).toHaveTextContent('(2)'); + expect(flow).toHaveAttribute('href', '/studio/~all/metadata/flow?source=loose'); + expect(within(banner).getByTestId('loose-items-banner-dataset')).toHaveTextContent('(1)'); + }); + + it('control: a type that takes no runtime write, and the package type, are not read', async () => { + mount(); + await screen.findByTestId('loose-items-banner'); + expect([...listCalls].sort()).toEqual(['dataset', 'flow', 'report']); + expect(screen.queryByTestId('loose-items-banner-agent')).toBeNull(); + }); + + it('names a type whose read failed as not counted', async () => { + mount(); + expect(await screen.findByTestId('loose-items-banner-unread')).toHaveTextContent('report'); + }); + + it('control: draws nothing and reads nothing for a reader who may not author', async () => { + canAuthor = false; + mount(); + await new Promise((r) => setTimeout(r, 20)); + expect(screen.queryByTestId('loose-items-banner')).toBeNull(); + expect(listCalls).toEqual([]); + }); + + it('control: draws nothing while no item is loose', async () => { + rows = { flow: [{ name: 'f3', _packageId: 'app.alpha' }], dataset: [], report: [] }; + mount(); + await waitFor(() => expect(listCalls.length).toBe(3)); + await new Promise((r) => setTimeout(r, 20)); + expect(screen.queryByTestId('loose-items-banner')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/LooseItemsBanner.tsx b/ui/packages/app-shell/src/views/metadata-admin/LooseItemsBanner.tsx new file mode 100644 index 00000000000..e00c85bc41d --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/LooseItemsBanner.tsx @@ -0,0 +1,135 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38150 — the Packages page's "N loose items" banner (ADR-0084's + * amendment of 2026-11-26; decision 12's placement, kept for the move door): + * how many items of this environment belong to no package, counted per type, + * each count a link to that type's "Loose" list on Studio's cross-package leg, + * where they are selected and moved into a package. + * + * - Drawn only for a person who may author metadata, and only while the count + * is above zero. + * - The count is the list's own reading: one `GET /meta/:type` per type that + * takes runtime writes (a type that takes none holds no loose item), the + * type's own hide hook applied, `isPackageLessItem` on each row. No new + * server read: the list the link opens counts the same rows. + * - A type whose read fails is left out of the count, and the banner says + * some types could not be counted, never a smaller number as if it were all. + */ + +import * as React from 'react'; +import { Link } from 'react-router-dom'; +import { Inbox } from 'lucide-react'; +import { useCanAuthorMetadata } from '../../hooks/useCanAuthorMetadata.js'; +import { useMetadataClient, useMetadataTypes, type RichMetadataTypeEntry } from './useMetadata.js'; +import { resolveResourceConfig } from './registry.js'; +import { t, tFormat, translateMetadataType } from './i18n.js'; +import { isLooseRow } from './looseMove.js'; +import { LIST_LOOSE_SOURCE, LIST_SOURCE_PARAM } from './metadataListState.js'; +import { STUDIO_ALL_PACKAGES_SEGMENT, studioMetadataAreaAddress } from '../studio-design/studioAddress.js'; + +/** The types whose loose rows are counted: those that take a runtime write. */ +export function looseCountTypes(entries: readonly RichMetadataTypeEntry[]): RichMetadataTypeEntry[] { + return entries.filter((e) => e.type !== 'package' && (e.allowRuntimeCreate || e.allowEnvironmentOverlay)); +} + +/** A type's "Loose" list on Studio's cross-package leg. */ +export function looseListPath(type: string): string { + return studioMetadataAreaAddress(STUDIO_ALL_PACKAGES_SEGMENT, encodeURIComponent(type), { + query: `${LIST_SOURCE_PARAM}=${LIST_LOOSE_SOURCE}`, + }); +} + +export interface LooseCounts { + /** Loose rows per type, types with none left out. */ + byType: Array<{ type: string; count: number }>; + total: number; + /** Types whose list could not be read. */ + unread: string[]; +} + +export function useLooseItemCounts(enabled: boolean, refreshKey: unknown = 0): LooseCounts | null { + const client = useMetadataClient(); + const { entries, loading } = useMetadataTypes(client); + const [counts, setCounts] = React.useState(null); + // Read through a ref: the count is keyed on the types it reads, never on the + // client's identity, which a host may hand out fresh on each render. + const clientRef = React.useRef(client); + clientRef.current = client; + const typesKey = looseCountTypes(entries) + .map((e) => e.type) + .join(','); + React.useEffect(() => { + if (!enabled || loading) return; + let cancelled = false; + const types = looseCountTypes(entries); + Promise.allSettled( + types.map(async (entry) => { + const list = await clientRef.current.list(entry.type); + const listFilter = resolveResourceConfig(entry.type, entry).listFilter; + let count = 0; + for (const raw of list ?? []) { + const item = (raw && typeof raw === 'object' && 'item' in raw ? raw.item : raw) ?? {}; + if (listFilter && !listFilter(item)) continue; + if (isLooseRow(item)) count++; + } + return count; + }), + ).then((results) => { + if (cancelled) return; + const byType: LooseCounts['byType'] = []; + const unread: string[] = []; + results.forEach((r, i) => { + if (r.status === 'rejected') unread.push(types[i].type); + else if (r.value > 0) byType.push({ type: types[i].type, count: r.value }); + }); + setCounts({ byType, total: byType.reduce((sum, b) => sum + b.count, 0), unread }); + }); + return () => { + cancelled = true; + }; + // Keyed on the types read, never on `entries`' or the client's identity. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [enabled, loading, typesKey, refreshKey]); + return enabled ? counts : null; +} + +export function LooseItemsBanner({ locale, refreshKey }: { locale: string; refreshKey?: unknown }) { + const canAuthor = useCanAuthorMetadata(); + const counts = useLooseItemCounts(canAuthor, refreshKey); + if (!counts || counts.total === 0) return null; + return ( +
+
+ ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/LooseMoveDialog-38150.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/LooseMoveDialog-38150.test.tsx new file mode 100644 index 00000000000..219a4dfe3bd --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/LooseMoveDialog-38150.test.tsx @@ -0,0 +1,163 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38150 PR-A2 — the move's confirm step (`LooseMoveDialog`). The + * door is handed in, so each answer is the door's own shape. Pinned, each with + * its control: + * + * - a dry run that passes draws each item and what its addresses become, the + * dry-run caveat and what undoing the move means; Move is offered; + * - a refused dry run draws each refused item with the door's code and + * sentence, offers no Move, and for `REFERENCE_LEFT_BEHIND` offers to add + * the loose items left behind: the next check carries them (another type + * included) and, when it passes, Move moves them all; + * - control: a refusal with no `references` offers nothing to add; + * - a refusal on the real move (a save-door judge the dry run does not run) + * is drawn as nothing moved, and `onMoved` is not called; + * - a failure that is not an answer is drawn with the door's sentence and a + * retry. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, cleanup, screen, fireEvent, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import * as React from 'react'; +// The source reaches `celAuthoring`'s dynamic `@objectstack/lint` import; its +// first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; +import type { MoveIntoPackageResponse } from '@objectstack/spec/api'; +import { LooseMoveDialog } from './LooseMoveDialog'; +import type { LooseItem } from './looseMove'; + +afterEach(cleanup); + +const TARGET = { id: 'app.alpha', label: 'Alpha' }; +const FLOW: LooseItem = { type: 'flow', name: 'probe_loose_flow' }; +const DATASET: LooseItem = { type: 'dataset', name: 'probe_env_ds' }; + +const wouldMove = (items: readonly LooseItem[]): MoveIntoPackageResponse => ({ + outcome: 'would_move', + targetPackageId: TARGET.id, + moved: items.map((i) => ({ type: i.type, name: i.name, states: ['active'] })), + refused: [], +}); + +function mount(move: (id: string, items: readonly LooseItem[], dryRun: boolean) => Promise, onMoved = vi.fn()) { + render(); + return { onMoved }; +} + +describe('the confirm step (objectstack#38150)', () => { + it('a dry run that passes draws the address change, the caveat and the undo note, and Move moves', async () => { + const move = vi.fn(async (_id: string, items: readonly LooseItem[], dryRun: boolean): Promise => + dryRun + ? { + ...wouldMove(items), + moved: [ + { + type: 'flow', + name: FLOW.name, + states: ['active', 'draft'], + environmentAddress: `_env/${FLOW.name}`, + qualifiedAddress: `zeta/${FLOW.name}`, + }, + ], + } + : { ...wouldMove(items), outcome: 'moved', commitId: 'c1' }, + ); + const { onMoved } = mount(move); + const items = await screen.findByTestId('loose-move-items'); + expect(within(items).getByText(`_env/${FLOW.name}`)).toBeInTheDocument(); + expect(within(items).getByText(`zeta/${FLOW.name}`)).toBeInTheDocument(); + const notes = screen.getByTestId('loose-move-notes'); + expect(notes).toHaveTextContent('This is a check, not the move'); + expect(notes).toHaveTextContent('reverting its package commit takes these items out of the package'); + expect(move).toHaveBeenCalledWith(TARGET.id, [FLOW], true); + + fireEvent.click(screen.getByTestId('loose-move-confirm')); + await waitFor(() => expect(onMoved).toHaveBeenCalledTimes(1)); + expect(move).toHaveBeenLastCalledWith(TARGET.id, [FLOW], false); + expect(onMoved.mock.calls[0][0].outcome).toBe('moved'); + }); + + it('a set refused for a loose item left behind offers to add it; the next check carries it and Move moves both', async () => { + const move = vi.fn(async (_id: string, items: readonly LooseItem[], dryRun: boolean): Promise => { + const holdsDataset = items.some((i) => i.name === DATASET.name); + if (!holdsDataset) { + return { + outcome: 'refused', + targetPackageId: TARGET.id, + moved: [], + refused: [ + { + type: 'flow', + name: FLOW.name, + code: 'REFERENCE_LEFT_BEHIND', + error: `flow '${FLOW.name}' names dataset '${DATASET.name}', a loose item this move leaves behind.`, + references: [{ type: DATASET.type, name: DATASET.name }], + }, + ], + }; + } + return dryRun ? wouldMove(items) : { ...wouldMove(items), outcome: 'moved' }; + }); + const { onMoved } = mount(move); + const refused = await screen.findByTestId('loose-move-refused'); + expect(within(refused).getByText('REFERENCE_LEFT_BEHIND')).toBeInTheDocument(); + expect(within(refused).getByText(/a loose item this move leaves behind/)).toBeInTheDocument(); + expect(screen.getByTestId('loose-move-confirm')).toBeDisabled(); + + fireEvent.click(screen.getByTestId('loose-move-add-references')); + await screen.findByTestId('loose-move-items'); + expect(move).toHaveBeenLastCalledWith(TARGET.id, [FLOW, DATASET], true); + fireEvent.click(screen.getByTestId('loose-move-confirm')); + await waitFor(() => expect(onMoved).toHaveBeenCalledTimes(1)); + expect(move).toHaveBeenLastCalledWith(TARGET.id, [FLOW, DATASET], false); + }); + + it('control: a refusal naming no references offers nothing to add', async () => { + mount(async () => ({ + outcome: 'refused', + targetPackageId: TARGET.id, + moved: [], + refused: [{ type: 'object', name: 'probe_widget', code: 'NAMESPACE_PREFIX', error: "Object 'probe_widget' needs the prefix 'zeta__'." }], + })); + const refused = await screen.findByTestId('loose-move-refused'); + expect(within(refused).getByText('NAMESPACE_PREFIX')).toBeInTheDocument(); + expect(screen.queryByTestId('loose-move-add-references')).toBeNull(); + expect(screen.getByTestId('loose-move-confirm')).toBeDisabled(); + }); + + it('a refusal on the real move is drawn as nothing moved, and onMoved is not called', async () => { + const move = vi.fn(async (_id: string, items: readonly LooseItem[], dryRun: boolean): Promise => + dryRun + ? wouldMove(items) + : { + outcome: 'refused', + targetPackageId: TARGET.id, + moved: [], + refused: [{ type: 'flow', name: FLOW.name, code: 'NOT_OVERRIDABLE', error: 'The save door refused it.' }], + }, + ); + const { onMoved } = mount(move); + await screen.findByTestId('loose-move-items'); + fireEvent.click(screen.getByTestId('loose-move-confirm')); + const refused = await screen.findByTestId('loose-move-refused'); + expect(refused).toHaveTextContent('The move was refused, and nothing moved'); + expect(within(refused).getByText('The save door refused it.')).toBeInTheDocument(); + expect(onMoved).not.toHaveBeenCalled(); + }); + + it('a failure that is not an answer is drawn with its sentence, and Try again checks again', async () => { + let fail = true; + const move = vi.fn(async (_id: string, items: readonly LooseItem[]) => { + if (fail) throw new Error('Moving loose metadata into package "app.alpha" is the platform operator\'s.'); + return wouldMove(items); + }); + mount(move); + expect(await screen.findByTestId('loose-move-failed')).toHaveTextContent("is the platform operator's"); + fail = false; + fireEvent.click(screen.getByTestId('loose-move-retry')); + await screen.findByTestId('loose-move-items'); + expect(move).toHaveBeenCalledTimes(2); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/LooseMoveDialog.tsx b/ui/packages/app-shell/src/views/metadata-admin/LooseMoveDialog.tsx new file mode 100644 index 00000000000..fbe71557f17 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/LooseMoveDialog.tsx @@ -0,0 +1,243 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38150 — the move's confirm step: what moving a selection of + * loose items into one package would do, read from the move door's dry run, + * then the move itself (`looseMove.ts`). + * + * - Opened with the target the person picked and the selection, it asks the + * door at once for a dry run and draws its answer: each item and what its + * addresses become, or each refused item with the door's own sentence. + * - A set refused because a moved item names a loose item left behind + * (`REFERENCE_LEFT_BEHIND`, ADR-0150 D3 (a)) offers to add those items and + * check again: the selection may then hold items of other types. + * - Move makes the real call. A save-door judge runs only there, so it can + * refuse what the dry run passed; that refusal is drawn the same way, with + * nothing moved (the door is whole or nothing). + * - The text says what undoing the move means: reverting its package commit + * takes the items out of the package, it does not make them loose again. + */ + +import * as React from 'react'; +import { AlertTriangle, ArrowRight, Loader2 } from 'lucide-react'; +import { + Button, + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@object-ui/components'; +import type { MoveIntoPackageResponse } from '@objectstack/spec/api'; +import { t, tFormat, translateMetadataType } from './i18n.js'; +import { moveLooseItems, referencesLeftBehind, withLooseItems, type LooseItem } from './looseMove.js'; + +type Step = + | { kind: 'checking' } + | { kind: 'checked'; answer: MoveIntoPackageResponse; fromMove: boolean } + | { kind: 'moving'; answer: MoveIntoPackageResponse } + | { kind: 'failed'; error: string }; + +function itemText(item: { type: string; name: string; member?: string }, locale: string): string { + const kind = translateMetadataType(item.type, locale); + return item.member ? `${kind} ${item.name} (${item.member})` : `${kind} ${item.name}`; +} + +export interface LooseMoveDialogProps { + /** The package picked; `null` keeps the dialog closed. */ + target: { id: string; label: string } | null; + /** The selection the person made. */ + items: readonly LooseItem[]; + locale: string; + onClose: () => void; + /** The move was made: the door's answer. */ + onMoved: (answer: MoveIntoPackageResponse) => void; + /** The door; a test hands its own. */ + move?: typeof moveLooseItems; +} + +export function LooseMoveDialog({ target, items, locale, onClose, onMoved, move = moveLooseItems }: LooseMoveDialogProps) { + const [working, setWorking] = React.useState([...items]); + const [step, setStep] = React.useState({ kind: 'checking' }); + const runRef = React.useRef(0); + + const check = React.useCallback( + (selection: LooseItem[]) => { + if (!target) return; + const run = ++runRef.current; + setStep({ kind: 'checking' }); + move(target.id, selection, true).then( + (answer) => { + if (runRef.current === run) setStep({ kind: 'checked', answer, fromMove: false }); + }, + (err: unknown) => { + if (runRef.current === run) setStep({ kind: 'failed', error: err instanceof Error ? err.message : String(err) }); + }, + ); + }, + [target, move], + ); + + // A new target or selection starts over from the person's selection. + const itemsKey = JSON.stringify(items); + React.useEffect(() => { + if (!target) { + runRef.current++; + return; + } + const selection = [...items]; + setWorking(selection); + check(selection); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [target?.id, itemsKey, check]); + + const close = () => { + if (step.kind === 'moving') return; + runRef.current++; + onClose(); + }; + + const runMove = (answer: MoveIntoPackageResponse) => { + if (!target) return; + const run = ++runRef.current; + setStep({ kind: 'moving', answer }); + move(target.id, working, false).then( + (moved) => { + if (runRef.current !== run) return; + if (moved.outcome === 'moved') onMoved(moved); + else setStep({ kind: 'checked', answer: moved, fromMove: true }); + }, + (err: unknown) => { + if (runRef.current === run) setStep({ kind: 'failed', error: err instanceof Error ? err.message : String(err) }); + }, + ); + }; + + const answer = step.kind === 'checked' || step.kind === 'moving' ? step.answer : null; + const refused = answer?.outcome === 'refused' ? answer.refused : []; + const toAdd = answer ? referencesLeftBehind(working, refused) : []; + const passes = answer?.outcome === 'would_move'; + + return ( + !next && close()}> + + + + {tFormat('engine.looseMove.confirm.title', locale, { count: working.length, package: target?.label ?? '' })} + + {t('engine.looseMove.confirm.description', locale)} + + + {step.kind === 'checking' && ( +

+

+ )} + + {step.kind === 'failed' && ( +

+

+ )} + + {answer && answer.outcome !== 'refused' && ( +
    + {answer.moved.map((m) => ( +
  • + {itemText(m, locale)} + {m.states.length === 1 && m.states[0] === 'draft' && ( + {t('engine.looseMove.confirm.draftOnly', locale)} + )} + {m.environmentAddress && m.qualifiedAddress && ( + + {t('engine.looseMove.confirm.address', locale)} + {m.environmentAddress} + + )} + {m.aiFaceName && ( + + {t('engine.looseMove.confirm.aiFace', locale)} + {m.aiFaceName.before} + + )} +
  • + ))} +
+ )} + + {refused.length > 0 && ( +
+

+ {step.kind === 'checked' && step.fromMove + ? t('engine.looseMove.confirm.refusedOnMove', locale) + : t('engine.looseMove.confirm.refused', locale)} +

+
    + {refused.map((r) => ( +
  • + {itemText(r, locale)} + {r.code} + {r.error} +
  • + ))} +
+ {toAdd.length > 0 && ( + + )} +
+ )} + + {passes && ( +
+

{t('engine.looseMove.confirm.dryRunNote', locale)}

+

{t('engine.looseMove.confirm.undoNote', locale)}

+
+ )} + + + + {step.kind === 'failed' ? ( + + ) : ( + + )} + +
+
+ ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx index d1b4e25de11..e0e25e348f3 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackageCreateAsk.tsx @@ -58,6 +58,12 @@ export interface PackageAskRequest { preselect?: string | null; /** The type being created, as the reader reads it; names the question. */ typeLabel?: string; + /** + * The question and its explanation, for an ask that is not a create + * (objectstack#38150: where loose items move to). Absent, the create's own. + */ + title?: string; + description?: string; } /** The packages the ask offers: the server's writable verdict, kernel packages out, by name. */ @@ -73,6 +79,8 @@ export function PackageCreateAskDialog({ open, preselect, typeLabel, + title: askTitle, + description: askDescription, onAnswer, readPackages = fetchPackages, }: PackageAskRequest & { @@ -117,7 +125,9 @@ export function PackageCreateAskDialog({ }; const options = list.status === 'read' ? list.options : []; - const title = typeLabel + const title = askTitle + ? askTitle + : typeLabel ? tFormat('engine.packageAsk.titleNamed', locale, { type: typeLabel }) : t('engine.packageAsk.title', locale); @@ -132,7 +142,7 @@ export function PackageCreateAskDialog({ {title} - {t('engine.packageAsk.description', locale)} + {askDescription ?? t('engine.packageAsk.description', locale)} {list.status === 'loading' && (

@@ -244,6 +254,8 @@ export function usePackageCreateAsk(): { open={!!pending} preselect={pending?.preselect ?? null} typeLabel={pending?.typeLabel} + title={pending?.title} + description={pending?.description} onAnswer={onAnswer} /> ); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx index 6f52037de24..1eac052a20f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx @@ -139,6 +139,7 @@ import { ProtocolCheckSkippedNote } from '../../console/marketplace/ProtocolChec import type { InstalledPackageAtEitherStage } from '@objectstack/spec/api-assembled'; import type { PackagePublishResult } from '@objectstack/spec/system'; import { studioHomePath } from '../studio-design/studioAddress.js'; +import { LooseItemsBanner } from './LooseItemsBanner.js'; import { PackageCustomizationsPanel } from '../studio-design/PackageCustomizationsPanel.js'; import { isCustomizationPackage } from '@objectstack/spec/kernel'; import { @@ -2054,6 +2055,10 @@ export function PackagesPage() {

)} + {/* objectstack#38150 — the items of this environment that belong to no + package, counted per type, each a link to its "Loose" list. */} + + {importMsg && (
[] = [ + { name: 'loose_none', label: 'No package' }, + { name: 'loose_empty', label: 'Empty package', _packageId: '' }, + { name: 'loose_sentinel', label: 'Sentinel', _packageId: 'sys_metadata' }, + { name: 'packaged_flow', label: 'Packaged', _packageId: PKG }, + { name: 'pair_flow', label: 'Pair item', _packageId: `${PKG}.custom` }, + { name: 'overlay_flow', label: 'Overlay', _packageId: 'com.shipped' }, +]; +const RAW: unknown[] = ITEMS.map((item) => (item.name === 'overlay_flow' ? { item, source: 'overlay' } : item)); +const LOOSE = ['loose_none', 'loose_empty', 'loose_sentinel']; +const NOT_LOOSE = ['packaged_flow', 'pair_flow', 'overlay_flow']; + +const CLIENT = { + list: async (type: string) => (type === TYPE ? RAW : []), +}; +const ENTRY = { type: TYPE, label: 'Flow', allowEnvironmentOverlay: false, allowRuntimeCreate: true }; + +let canAuthor = 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: () => canAuthor })); +vi.mock('../studio-design/packages-io', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchPackages: async () => [{ id: PKG, name: 'Alpha', writable: true, namespace: 'alpha' }], +})); + +import { MetadataResourceListPage } from './ResourceListPage'; +import { MetadataAreaHostContext, type MetadataAreaHost } from './metadataAreaHost'; + +const ALL: MetadataAreaHost = { packageId: null, readOnly: false, basePath: '/studio/~all/metadata' }; +const ON_PKG: MetadataAreaHost = { packageId: PKG, readOnly: false, basePath: `/studio/${PKG}/metadata` }; + +/** Every move-in call the page made: its package and body. */ +let moveCalls: Array<{ url: string; body: any }> = []; + +beforeEach(() => { + canAuthor = true; + moveCalls = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + if (url.includes('/move-in')) { + const body = JSON.parse(String(init?.body ?? '{}')); + moveCalls.push({ url, body }); + const moved = body.items.map((i: { type: string; name: string }) => ({ + type: i.type, + name: i.name, + states: ['active'], + environmentAddress: `_env/${i.name}`, + qualifiedAddress: `alpha/${i.name}`, + })); + return new Response( + JSON.stringify({ + success: true, + data: { outcome: body.dryRun ? 'would_move' : 'moved', targetPackageId: PKG, moved, refused: [] }, + }), + { status: 200, headers: { 'Content-Type': 'application/json' } }, + ); + } + return new Response(JSON.stringify({ object: 'x', records: [], hasMore: false }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + }), + ); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +function mount(host: MetadataAreaHost, search: string) { + return render( + + + + } /> + + + , + ); +} + +const shown = (names: readonly string[]) => names.filter((n) => screen.queryByText(n) !== null); + +describe('the cross-package list: "Loose" (objectstack#38150)', () => { + it('?source=loose lists exactly the package-less rows, never a .custom pair item or an overlay', async () => { + mount(ALL, '?source=loose'); + await waitFor(() => expect(shown(LOOSE)).toEqual(LOOSE)); + expect(shown(NOT_LOOSE)).toEqual([]); + }); + + it('control: with no source filter the list holds every row', async () => { + mount(ALL, ''); + await waitFor(() => expect(shown([...LOOSE, ...NOT_LOOSE])).toEqual([...LOOSE, ...NOT_LOOSE])); + expect(screen.queryByTestId('loose-selection-bar')).toBeNull(); + }); + + it('draws a select box per row and the selection bar for an author', async () => { + mount(ALL, '?source=loose'); + await screen.findByTestId('loose-selection-bar'); + for (const name of LOOSE) expect(await screen.findByTestId(`loose-select-${name}`)).toBeInTheDocument(); + expect(screen.getByTestId('loose-move-start')).toBeDisabled(); + }); + + it('control: a reader who may not author sees the loose rows, with no select box and no bar', async () => { + canAuthor = false; + mount(ALL, '?source=loose'); + await waitFor(() => expect(shown(LOOSE)).toEqual(LOOSE)); + expect(screen.queryByTestId('loose-selection-bar')).toBeNull(); + expect(screen.queryByTestId('loose-select-loose_none')).toBeNull(); + }); + + it('select all, Move into package…: the ask opens with nothing picked, the confirm reads a dry run, and Move moves the selection', async () => { + mount(ALL, '?source=loose'); + fireEvent.click(await screen.findByTestId('loose-select-all')); + expect(screen.getByTestId('loose-selected-count')).toHaveTextContent('3'); + fireEvent.click(screen.getByTestId('loose-move-start')); + + const ask = await screen.findByTestId('package-create-ask'); + const option = await within(ask).findByTestId(`package-create-ask-option-${PKG}`); + expect(option).toHaveAttribute('data-state', 'unchecked'); + expect(within(ask).getByText('Which package should the selected items move into?')).toBeInTheDocument(); + fireEvent.click(option); + fireEvent.click(within(ask).getByTestId('package-create-ask-continue')); + + const dialog = await screen.findByTestId('loose-move-dialog'); + await within(dialog).findByTestId('loose-move-items'); + expect(moveCalls).toHaveLength(1); + expect(moveCalls[0].url).toContain(`/packages/${encodeURIComponent(PKG)}/move-in`); + expect(moveCalls[0].body.dryRun).toBe(true); + expect(moveCalls[0].body.items.map((i: { name: string }) => i.name).sort()).toEqual([...LOOSE].sort()); + expect(moveCalls[0].body.items.every((i: { type: string }) => i.type === TYPE)).toBe(true); + expect(within(dialog).getByText('_env/loose_none')).toBeInTheDocument(); + expect(within(dialog).getByText('alpha/loose_none')).toBeInTheDocument(); + expect(within(dialog).getByTestId('loose-move-notes')).toBeInTheDocument(); + expect(within(dialog).getByText('Move into Alpha')).toBeInTheDocument(); + + fireEvent.click(within(dialog).getByTestId('loose-move-confirm')); + await waitFor(() => expect(moveCalls).toHaveLength(2)); + expect(moveCalls[1].body.dryRun).toBeUndefined(); + expect(moveCalls[1].body.items).toEqual(moveCalls[0].body.items); + await waitFor(() => expect(screen.queryByTestId('loose-move-dialog')).toBeNull()); + }); + + it('one row selected moves that row alone', async () => { + mount(ALL, '?source=loose'); + fireEvent.click(await screen.findByTestId('loose-select-loose_sentinel')); + expect(screen.getByTestId('loose-selected-count')).toHaveTextContent('1'); + fireEvent.click(screen.getByTestId('loose-move-start')); + const ask = await screen.findByTestId('package-create-ask'); + fireEvent.click(await within(ask).findByTestId(`package-create-ask-option-${PKG}`)); + fireEvent.click(within(ask).getByTestId('package-create-ask-continue')); + await screen.findByTestId('loose-move-items'); + expect(moveCalls[0].body.items).toEqual([{ type: TYPE, name: 'loose_sentinel' }]); + }); + + it("control: a package's own leg offers no \"Loose\": ?source=loose is ignored and draws no selection", async () => { + mount(ON_PKG, '?source=loose'); + await waitFor(() => expect(shown(['packaged_flow', 'pair_flow'])).toEqual(['packaged_flow', 'pair_flow'])); + expect(screen.queryByTestId('loose-selection-bar')).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 8496b81b667..6188e1050da 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx @@ -13,7 +13,7 @@ import * as React from 'react'; import { Link, Navigate, useLocation, useNavigate, useNavigationType, useParams, useSearchParams } from 'react-router-dom'; -import { Plus, Search, RefreshCw, AlertTriangle, Lock, Copy, X } from 'lucide-react'; +import { Plus, Search, RefreshCw, AlertTriangle, Lock, Copy, PackagePlus, X } from 'lucide-react'; import { Button, NeutralIconTile, @@ -26,6 +26,7 @@ import { } from '@object-ui/components'; import { Input } from '@object-ui/components'; import { Badge } from '@object-ui/components'; +import { Checkbox } from '@object-ui/components'; import { toast } from 'sonner'; import { Select, @@ -44,6 +45,9 @@ import { navEntryTitle } from './navEntryTitle.js'; import { getIcon } from '../../utils/getIcon.js'; import { MetadataTypeActions } from './MetadataTypeActions.js'; import { PACKAGE_PICKED_STATE, usePackageCreateAsk } from './PackageCreateAsk.js'; +import { LooseMoveDialog } from './LooseMoveDialog.js'; +import { isLooseRow, looseItemKey, type LooseItem } from './looseMove.js'; +import { fetchPackages } from '../studio-design/packages-io.js'; import { useMetadataClient, useMetadataTypes, @@ -303,6 +307,14 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string // names no package and never repairs one into the URL (`?package=X` would // move it onto X's leg, `areaLocationRedirect`); only create picks one. const allLeg = !!host && host.packageId === null && !envScope; + // objectstack#38150 (ADR-0084's amendment of 2026-11-26) — the cross-package + // leg offers a "Loose" source value: the rows bound to no package, read by + // `isPackageLessItem` exactly (never `classifyProvenance`, which files a + // `.custom` pair item and a served overlay as runtime too). Under it a person + // who may author selects loose items and moves them into a package. + const looseOffered = allLeg; + const [looseSelected, setLooseSelected] = React.useState>(() => new Map()); + const [looseMove, setLooseMove] = React.useState<{ target: { id: string; label: string }; items: LooseItem[] } | null>(null); // objectstack ADR-0146 D3 (#28568) — "On top, one surface": with a base open // in the area, its list holds the base's items and its paired // `.custom` package's items together, each item of the pair marked @@ -794,6 +806,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string label: (row) => (typeof row.item.label === 'string' ? row.item.label : undefined), matches: (row, q) => matchesQuery(row.item, q, searchableFields), source: sourceOf, + ...(looseOffered ? { loose: (row: ItemRow) => isLooseRow(row.item) } : {}), ...(showCustomizedFilter && !studioList ? { customized: (row: ItemRow) => markOf(row) !== null } : {}), // objectstack#37359 — a type whose rows name the object they serve is // narrowed to one object by `?targetObject=` (the import wizard's Manage). @@ -838,9 +851,10 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string // Compute source + invalid counts for filter / header stats. const sourceCounts = React.useMemo(() => { - const c = { all: scopedItems.length, artifact: 0, runtime: 0 }; + const c = { all: scopedItems.length, artifact: 0, runtime: 0, loose: 0 }; for (const r of scopedItems) { c[sourceOf(r)]++; + if (isLooseRow(r.item)) c.loose++; } return c; }, [scopedItems, sourceOf]); @@ -917,6 +931,61 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string }; const refresh = () => setRefreshKey((k) => k + 1); + + // objectstack#38150 — under "Loose", a person who may author selects rows + // and moves them: the picker (#38149's ask, nothing pre-selected), then the + // confirm step, which reads the door's dry run (`LooseMoveDialog`). + const looseSelecting = looseOffered && sourceFilter === 'loose' && canAuthor && !walled; + const looseItemOf = React.useCallback( + (row: ItemRow): LooseItem => { + const member = bundleMemberOf(row.item, config.bundleMemberField); + return { type, name: String(row.item[primaryKey] ?? ''), ...(member ? { member } : {}) }; + }, + [type, primaryKey, config.bundleMemberField], + ); + // A selection belongs to one type's loose list; leaving it drops it. + React.useEffect(() => { + setLooseSelected(new Map()); + }, [type, looseSelecting]); + const looseRows = looseSelecting ? filtered : []; + const looseAllSelected = looseRows.length > 0 && looseRows.every((row) => looseSelected.has(looseItemKey(looseItemOf(row)))); + const looseSomeSelected = !looseAllSelected && looseRows.some((row) => looseSelected.has(looseItemKey(looseItemOf(row)))); + const toggleLoose = (item: LooseItem, on: boolean) => { + setLooseSelected((prev) => { + const next = new Map(prev); + if (on) next.set(looseItemKey(item), item); + else next.delete(looseItemKey(item)); + return next; + }); + }; + const toggleAllLoose = (on: boolean) => { + setLooseSelected((prev) => { + const next = new Map(prev); + for (const row of looseRows) { + const item = looseItemOf(row); + if (on) next.set(looseItemKey(item), item); + else next.delete(looseItemKey(item)); + } + return next; + }); + }; + const startLooseMove = async () => { + const items = [...looseSelected.values()]; + if (items.length === 0) return; + const target = await askPackage({ + preselect: null, + title: tFormat('engine.looseMove.pick.title', locale, { count: items.length }), + description: t('engine.looseMove.pick.description', locale), + }); + if (!target) return; + // The confirm names the package as the ask listed it (the list read is the + // ask's own, already held); its id when the name cannot be read. + const label = await fetchPackages().then( + (entries) => entries.find((p) => p.id === target)?.name ?? target, + () => target, + ); + setLooseMove({ target: { id: target, label }, items }); + }; // objectstack#36896 — × / Back from a detail lands where the list was: the // position is kept per list address and restored once the rows are drawn. const scrollAnchorRef = useListScrollRestore( @@ -1020,12 +1089,14 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string // its package, lock and diagnostics are looked up here, never carried on // the grid's row. const rowInfos = new Map(); + // objectstack#38150 — under "Loose" the table leads with the select column. + const leadColumns = looseSelecting ? 1 : 0; const gridRowsAll = filtered.map((row, i) => { const info = metadataRowInfo(row, i); rowInfos.set(info.id, info); const values: Record = { id: info.id }; shownColumns.forEach((c, ci) => { - values[metadataGridField(ci)] = gridValue(valueAtPath(row.item, c.key)); + values[metadataGridField(ci + leadColumns)] = gridValue(valueAtPath(row.item, c.key)); }); return values; }); @@ -1107,6 +1178,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string return seen; }; const gridColumns: MetadataGridColumn[] = [ + ...(looseSelecting ? [{ key: SELECT_COLUMN, label: t('engine.looseMove.col.select', locale), width: '64px' }] : []), ...shownColumns.map((c, ci) => ({ key: c.key, // The Studio list heads its label-first column by the identity it @@ -1332,8 +1404,25 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string ); }; const cellDraws: Record React.ReactNode> = {}; + if (looseSelecting) cellDraws[metadataGridField(0)] = (_value, rec) => { + const info = rowInfoOf(rec); + if (!info) return null; + const item = looseItemOf(info.row); + return ( + + toggleLoose(item, on === true)} + // The row's click opens the item; the box only selects it. + onClick={(e) => e.stopPropagation()} + aria-label={tFormat('engine.looseMove.select', locale, { name: info.name })} + data-testid={`loose-select-${info.name}`} + /> + + ); + }; shownColumns.forEach((c, ci) => { - cellDraws[metadataGridField(ci)] = (_value, rec) => { + cellDraws[metadataGridField(ci + leadColumns)] = (_value, rec) => { const info = rowInfoOf(rec); if (!info) return null; if (ci === 0) return firstCell(info, c); @@ -1490,6 +1579,11 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string {tFormat('engine.list.sourceFilter.system', locale, { count: sourceCounts.artifact })} + {looseOffered && ( + + {tFormat('engine.list.sourceFilter.loose', locale, { count: sourceCounts.loose })} + + )}
@@ -1573,6 +1667,11 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string {t('engine.list.allSources', locale)} ({sourceCounts.all}) {t('engine.list.source.artifact', locale)} ({sourceCounts.artifact}) {t('engine.list.source.runtime', locale)} ({sourceCounts.runtime}) + {looseOffered && ( + + {tFormat('engine.list.sourceFilter.loose', locale, { count: sourceCounts.loose })} + + )} {activation && ( @@ -1771,6 +1870,50 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string )} )} + {/* objectstack#38150 — the "Loose" list's selection bar: select every + row the filter shows, and move the selection into a package. */} + {!loading && looseSelecting && filtered.length > 0 && ( +
+ + + {tFormat('engine.looseMove.selected', locale, { count: looseSelected.size })} + + +
+ )} + setLooseMove(null)} + onMoved={(answer) => { + setLooseMove(null); + setLooseSelected(new Map()); + toast.success( + tFormat('engine.looseMove.moved', locale, { count: answer.moved.length, package: answer.targetPackageId }), + ); + refresh(); + }} + /> {!loading && filtered.length > 0 && ( // objectstack#36897 — every type's list is the same table: the // record list's `ObjectGrid`, fed the rows above in their order @@ -1937,6 +2080,9 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string /** The page columns after the list's own (`metadataListGrid.ts` keys none of them as a field). */ const CHANGED_COLUMN = '__changed'; +/** objectstack#38150 — the select column of the "Loose" list, first when drawn. */ +const SELECT_COLUMN = '__select'; +const EMPTY_LOOSE_ITEMS: readonly LooseItem[] = []; const SOURCE_COLUMN = '__source'; const CONTROLS_COLUMN = '__controls'; diff --git a/ui/packages/app-shell/src/views/metadata-admin/looseMove-38150.test.ts b/ui/packages/app-shell/src/views/metadata-admin/looseMove-38150.test.ts new file mode 100644 index 00000000000..d102781ef55 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/looseMove-38150.test.ts @@ -0,0 +1,127 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38150 PR-A2 — the "Loose" source value in the list's address + * state, and the console's call to the move door (`looseMove.ts`). Pinned, + * each with its control: + * + * - `source=loose` round-trips through the codec; an unknown value reads as + * every source; + * - under `loose` the list keeps the rows the reader's `loose` member keeps; + * with no such member the filter is not offered and keeps every row; + * - the move door's 422 refusal resolves as the door's own answer; any other + * failure throws with the server's sentence; + * - the references a refusal names are added once, the selection's own items + * never twice. + */ +import { describe, it, expect, vi, afterEach } from 'vitest'; +// The source reaches `celAuthoring`'s dynamic `@objectstack/lint` import; its +// first load is paid here, at collection (`check:test-source-alias`). +import '@objectstack/lint'; +import { + applyListState, + decodeListState, + DEFAULT_LIST_STATE, + writeListState, + type ListRowReader, +} from './metadataListState'; +import { isLooseRow, moveLooseItems, referencesLeftBehind, withLooseItems } from './looseMove'; + +afterEach(() => vi.unstubAllGlobals()); + +interface Row { + item: Record; +} +const ROWS: Row[] = [ + { item: { name: 'a' } }, + { item: { name: 'b', _packageId: 'sys_metadata' } }, + { item: { name: 'c', _packageId: 'app.alpha' } }, + { item: { name: 'd', _packageId: 'app.alpha.custom' } }, +]; +const base: ListRowReader = { + name: (r) => String(r.item.name), + label: () => undefined, + matches: () => true, + source: (r) => (r.item._packageId === 'app.alpha' ? 'artifact' : 'runtime'), +}; + +describe('the list state: "loose" (objectstack#38150)', () => { + it('round-trips source=loose', () => { + const state = decodeListState(new URLSearchParams('source=loose')); + expect(state.source).toBe('loose'); + expect(writeListState(new URLSearchParams(), state).toString()).toBe('source=loose'); + }); + + it('control: an unknown source reads as every source', () => { + expect(decodeListState(new URLSearchParams('source=org')).source).toBe('all'); + }); + + it('keeps the rows the reader reads as loose, never a .custom pair row the runtime source would keep', () => { + const state = { ...DEFAULT_LIST_STATE, source: 'loose' as const }; + const kept = applyListState(ROWS, state, { ...base, loose: (r) => isLooseRow(r.item) }, 'en-US'); + expect(kept.map((r) => r.item.name)).toEqual(['a', 'b']); + const runtime = applyListState(ROWS, { ...DEFAULT_LIST_STATE, source: 'runtime' }, base, 'en-US'); + expect(runtime.map((r) => r.item.name)).toEqual(['a', 'b', 'd']); + }); + + it('control: with no loose member the filter is not offered and keeps every row', () => { + const kept = applyListState(ROWS, { ...DEFAULT_LIST_STATE, source: 'loose' }, base, 'en-US'); + expect(kept).toHaveLength(ROWS.length); + }); +}); + +function answer(status: number, payload: unknown) { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify(payload), { status, headers: { 'Content-Type': 'application/json' } })), + ); +} + +describe('the move door call (objectstack#38150)', () => { + const ITEMS = [{ type: 'flow', name: 'f1' }]; + + it('a 422 refusal resolves as the door answer, every item with its own code', async () => { + const refused = { + outcome: 'refused', + targetPackageId: 'com.probe.ghost', + moved: [], + refused: [{ type: 'flow', name: 'f1', code: 'WRITABLE_PACKAGE_REQUIRED', error: 'Not installed.' }], + }; + answer(422, { success: false, error: { code: 'WRITABLE_PACKAGE_REQUIRED', message: 'Not installed.', details: refused } }); + await expect(moveLooseItems('com.probe.ghost', ITEMS, true)).resolves.toEqual(refused); + }); + + it('control: a failure that is not an answer throws with the server sentence', async () => { + answer(403, { success: false, error: { code: 'FORBIDDEN', message: 'Moving loose metadata is refused here.' } }); + await expect(moveLooseItems('app.alpha', ITEMS, true)).rejects.toThrow('Moving loose metadata is refused here.'); + }); + + it('sends the selection, with dryRun only on a dry run', async () => { + const fetchMock = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response(JSON.stringify({ success: true, data: { outcome: 'moved', targetPackageId: 'app.alpha', moved: [], refused: [] } }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }), + ); + vi.stubGlobal('fetch', fetchMock); + await moveLooseItems('app.alpha', ITEMS, true); + await moveLooseItems('app.alpha', ITEMS, false); + const bodies = fetchMock.mock.calls.map((c) => JSON.parse(String(c[1]?.body))); + expect(String(fetchMock.mock.calls[0][0])).toContain('/api/v1/packages/app.alpha/move-in'); + expect(bodies).toEqual([{ items: ITEMS, dryRun: true }, { items: ITEMS }]); + }); +}); + +describe('the selection (objectstack#38150)', () => { + it('adds what a refusal names as left behind once, never an item the selection holds', () => { + const items = [{ type: 'flow', name: 'f1' }, { type: 'dataset', name: 'ds1' }]; + const more = referencesLeftBehind(items, [ + { type: 'flow', name: 'f1', code: 'REFERENCE_LEFT_BEHIND', error: 'x', references: [{ type: 'dataset', name: 'ds1' }, { type: 'dataset', name: 'ds2' }] }, + { type: 'flow', name: 'f2', code: 'REFERENCE_LEFT_BEHIND', error: 'y', references: [{ type: 'dataset', name: 'ds2' }] }, + ]); + expect(more).toEqual([{ type: 'dataset', name: 'ds2' }]); + expect(withLooseItems(items, more)).toEqual([...items, { type: 'dataset', name: 'ds2' }]); + expect(withLooseItems(items, items)).toEqual(items); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/looseMove.ts b/ui/packages/app-shell/src/views/metadata-admin/looseMove.ts new file mode 100644 index 00000000000..890b6a9caaf --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/looseMove.ts @@ -0,0 +1,111 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38150 — the console's half of the move door (ADR-0084's + * amendment of 2026-11-26, "Loose items stay where they are, and one door + * moves them"; ruling 7184753035, question 3): a selection of loose items, + * one, several or every loose item of a type, moved into one package through + * `POST /api/v1/packages/:id/move-in`. + * + * Invariants: + * - What is loose is `isPackageLessItem` on the served `_packageId`, the one + * reading; never `classifyProvenance`, which also files a `.custom` pair + * item and a served overlay as "runtime". + * - The answer is the server's. A refusal arrives as a 422 whose details are + * the whole answer (`outcome: 'refused'`, every item's own code and + * sentence), and is returned as that answer, never re-worded here. Any + * other failure throws. + * - The confirm step reads a dry run, which runs the judgement made before any + * door (loose, target, the object judges, the set) and writes nothing, so a + * save-door judge can still refuse the real move. The confirm says so. + */ + +import type { + MoveIntoPackageItem, + MoveIntoPackageRefusedItem, + MoveIntoPackageResponse, +} from '@objectstack/spec/api'; +import { PACKAGES_API, packagesApiJson } from './packageActions.js'; +import { isPackageLessItem } from '../studio-design/studioScope.js'; + +export type LooseItem = MoveIntoPackageItem; + +/** One loose item's key in a selection: its type, name and bundle member. */ +export function looseItemKey(item: { type: string; name: string; member?: string | null }): string { + return `${item.type}\u0000${item.name}\u0000${item.member ?? ''}`; +} + +/** Whether a served row is loose: bound to no package (`isPackageLessItem`). */ +export function isLooseRow(item: { _packageId?: unknown } | null | undefined): boolean { + return isPackageLessItem(item); +} + +/** `items` with `more` added, each once, in the order first named. */ +export function withLooseItems(items: readonly LooseItem[], more: readonly LooseItem[]): LooseItem[] { + const seen = new Set(items.map(looseItemKey)); + const out = [...items]; + for (const item of more) { + const key = looseItemKey(item); + if (seen.has(key)) continue; + seen.add(key); + out.push(item); + } + return out; +} + +/** + * The loose items a refused answer names as left behind + * (`REFERENCE_LEFT_BEHIND`'s `references`) that the selection does not hold + * yet: what "add them and check again" adds. + */ +export function referencesLeftBehind(items: readonly LooseItem[], refused: readonly MoveIntoPackageRefusedItem[]): LooseItem[] { + const held = new Set(items.map(looseItemKey)); + const out: LooseItem[] = []; + for (const r of refused) { + for (const ref of r.references ?? []) { + const item = { type: ref.type, name: ref.name }; + const key = looseItemKey(item); + if (held.has(key)) continue; + held.add(key); + out.push(item); + } + } + return out; +} + +function isMoveAnswer(value: unknown): value is MoveIntoPackageResponse { + const v = value as Partial | null | undefined; + return ( + !!v && + typeof v === 'object' && + (v.outcome === 'moved' || v.outcome === 'would_move' || v.outcome === 'refused') && + Array.isArray(v.moved) && + Array.isArray(v.refused) + ); +} + +/** + * Ask the move door: `dryRun` answers what the move would do and writes + * nothing. Resolves with the door's answer, a refusal included; throws on any + * other failure (the gates' refusals, a fault), with the server's sentence. + */ +export async function moveLooseItems( + targetPackageId: string, + items: readonly LooseItem[], + dryRun: boolean, +): Promise { + try { + return await packagesApiJson( + `${PACKAGES_API}/${encodeURIComponent(targetPackageId)}/move-in`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ items, ...(dryRun ? { dryRun: true } : {}) }), + }, + ); + } catch (err) { + const details = (err as { details?: unknown } | null)?.details; + if (isMoveAnswer(details) && details.outcome === 'refused') return details; + throw err; + } +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts b/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts index 5c0386b4f3d..69a03b5b472 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts @@ -31,7 +31,11 @@ import { compareChangedAt } from './listChangedAt.js'; /** The search text. */ export const LIST_QUERY_PARAM = 'q'; -/** The source filter: `artifact` or `runtime`; absent = every source. */ +/** + * The source filter: `artifact`, `runtime` or `loose`; absent = every source. + * `loose` (objectstack#38150) is offered on the cross-package leg only: the + * rows bound to no package, read by `isPackageLessItem` exactly. + */ export const LIST_SOURCE_PARAM = 'source'; /** "Only customizations": `1`; absent = off. */ export const LIST_CUSTOMIZED_PARAM = 'customized'; @@ -57,7 +61,10 @@ export const LIST_STATE_PARAMS: readonly string[] = [ LIST_TARGET_OBJECT_PARAM, ]; -export type ListSourceFilter = 'all' | 'artifact' | 'runtime'; +export type ListSourceFilter = 'all' | 'artifact' | 'runtime' | 'loose'; + +/** The source filter's value for the loose rows (objectstack#38150). */ +export const LIST_LOOSE_SOURCE = 'loose'; export type ListStatusFilter = 'all' | 'active' | 'inactive'; /** @@ -127,7 +134,7 @@ export function decodeListState(params: URLSearchParams): MetadataListState { const targetObject = params.get(LIST_TARGET_OBJECT_PARAM)?.trim(); return { query: params.get(LIST_QUERY_PARAM) ?? '', - source: source === 'artifact' || source === 'runtime' ? source : 'all', + source: source === 'artifact' || source === 'runtime' || source === LIST_LOOSE_SOURCE ? source : 'all', customizedOnly: params.get(LIST_CUSTOMIZED_PARAM) === '1', status: status === 'active' || status === 'inactive' ? status : 'all', sort: decodeListSort(params.get(LIST_SORT_PARAM)), @@ -180,6 +187,12 @@ export interface ListRowReader { matches(row: R, query: string): boolean; /** Where the row comes from. */ source(row: R): 'artifact' | 'runtime'; + /** + * The "Loose" source value is offered (objectstack#38150, the cross-package + * leg): is the row bound to no package? Absent, `source=loose` is not + * offered and reads as every source, as an unoffered filter does. + */ + loose?: (row: R) => boolean; /** "Only customizations" is offered: is the row a customization? */ customized?: (row: R) => boolean; /** @@ -238,7 +251,9 @@ export function applyListState( const collator = collatorFor(locale); const kept = rows.filter((row) => { if (state.query && !read.matches(row, state.query)) return false; - if (state.source !== 'all' && read.source(row) !== state.source) return false; + if (state.source === LIST_LOOSE_SOURCE) { + if (read.loose && !read.loose(row)) return false; + } else if (state.source !== 'all' && read.source(row) !== state.source) return false; if (state.targetObject && read.targetObject && read.targetObject(row) !== state.targetObject) return false; if (state.customizedOnly && read.customized && !read.customized(row)) return false; if (state.status !== 'all' && read.active) { diff --git a/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts b/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts index a6e41f4d4f7..172f911b891 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/useListOrderedNames.ts @@ -34,6 +34,7 @@ import { holdersOfName, servedHolderOf } from './permission-set-holder.js'; import { usePackageCustomizations } from '../studio-design/CustomizationMark.js'; import { customizationMarkOf, customizationTotal } from '../studio-design/customizationMarks.js'; import { classifyProvenance } from './ResourceListPage.js'; +import { isPackageLessItem } from '../studio-design/studioScope.js'; import { useListChangedAt } from './listChangedAt.js'; import { useInSetupApp } from '../../console/setupApp.js'; import { studioListSource, studioSourceKind } from './studioListSource.js'; @@ -101,6 +102,8 @@ export function useListOrderedNames(type: string): ListOrderedNames { const locale = useMetadataLocale(); const activePackage = envScope ? null : host ? host.packageId : urlPackage; const unscoped = envScope || activePackage === null; + // objectstack#38150 — the cross-package leg (`ResourceListPage`'s `allLeg`) offers "Loose". + const looseOffered = !!host && host.packageId === null && !envScope; const pairId = React.useMemo(() => { if (!host?.packageId || envScope) return null; const pair = customizationPackageId(host.packageId); @@ -185,6 +188,8 @@ export function useListOrderedNames(type: string): ListOrderedNames { label: (row) => (typeof row.item.label === 'string' ? row.item.label : undefined), matches: (row, query) => matchesQuery(row.item, query, searchKey.split('\n')), source: (row) => (studioList ? studioListSource(studioSourceKind(row.source, markOf(row))) : row.source), + // objectstack#38150 — the list offers "Loose" on the area's cross-package leg alone. + ...(looseOffered ? { loose: (row: Row) => isPackageLessItem(row.item) } : {}), changedAt: (row) => changedAt?.[String(row.item[primaryKey] ?? '')], ...(customizedOffered && !studioList ? { customized: (row: Row) => markOf(row) !== null } : {}), ...(envScope && hasCatalogActivation(type) @@ -201,5 +206,5 @@ export function useListOrderedNames(type: string): ListOrderedNames { }; return { status: 'ready', names: orderedListNames(scoped, state, read, locale), fromList }; // Keyed on the config members read, never on `config`, rebuilt every render. - }, [rows, changedAt, type, locale, state, fromList, customizations, needsLedger, ledger, envScope, unscoped, activePackage, pairId, primaryKey, listFilter, bundleMemberField, searchKey, studioList]); + }, [rows, changedAt, type, locale, state, fromList, customizations, needsLedger, ledger, envScope, unscoped, activePackage, pairId, primaryKey, listFilter, bundleMemberField, searchKey, studioList, looseOffered]); } diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 65d128872ee..81da86a60c8 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -4092,6 +4092,36 @@ const STUDIO_EN: Record = { '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}', + // objectstack#38150 — the move door's console half: the "Loose" list's selection, the confirm step, the Packages page banner. + 'engine.looseMove.col.select': 'Select', + 'engine.looseMove.select': 'Select {name}', + 'engine.looseMove.selectAll': 'Select all ({count})', + 'engine.looseMove.selected': 'Selected: {count}', + 'engine.looseMove.start': 'Move into package…', + 'engine.looseMove.pick.title': 'Which package should the selected items move into?', + 'engine.looseMove.pick.description': 'Loose items belong to no package. Moving puts each one in the package you choose, checked as a save into that package is. Choose one of your packages, or create a new one.', + 'engine.looseMove.confirm.title': 'Move into {package}', + 'engine.looseMove.confirm.description': 'Each item is checked as a save into the package is. The move is whole or nothing: if any item is refused, nothing moves.', + 'engine.looseMove.confirm.checking': 'Checking what the move would do…', + 'engine.looseMove.confirm.failed': 'The move could not be checked: {error}', + 'engine.looseMove.confirm.draftOnly': '(draft only)', + 'engine.looseMove.confirm.address': 'Address:', + 'engine.looseMove.confirm.aiFace': 'Name AI clients see:', + 'engine.looseMove.confirm.refused': 'These items can’t move, so nothing will move:', + 'engine.looseMove.confirm.refusedOnMove': 'The move was refused, and nothing moved:', + 'engine.looseMove.confirm.addReferences': 'Add the loose items they use and check again: {items}', + 'engine.looseMove.confirm.dryRunNote': 'This is a check, not the move. Some save checks run only when the move is made, so an item can still be refused then; if one is, nothing moves.', + 'engine.looseMove.confirm.undoNote': 'To undo the move later: reverting its package commit takes these items out of the package. It does not make them loose again.', + 'engine.looseMove.confirm.cancel': 'Cancel', + 'engine.looseMove.confirm.retry': 'Try again', + 'engine.looseMove.confirm.moving': 'Moving…', + 'engine.looseMove.confirm.move': 'Move', + 'engine.looseMove.moved': 'Moved into {package}: {count}.', + 'engine.looseItems.banner': '{count} items belong to no package', + 'engine.looseItems.bannerOne': '1 item belongs to no package', + 'engine.looseItems.bannerHint': 'Open a type to select its loose items and move them into a package.', + 'engine.looseItems.typeCount': '{type} ({count})', + 'engine.looseItems.unread': 'These types could not be counted: {types}', 'engine.list.refresh': 'Refresh', 'engine.list.search': 'Search name, label, description…', 'engine.list.empty': 'No items yet.', @@ -4129,6 +4159,7 @@ const STUDIO_EN: Record = { 'engine.list.sourceFilter.all': 'All sources ({count})', 'engine.list.sourceFilter.changed': 'Modified and new ({count})', 'engine.list.sourceFilter.system': 'System-shipped ({count})', + 'engine.list.sourceFilter.loose': 'Loose ({count})', 'engine.list.col.name': 'Name', 'engine.list.col.label': 'Label', 'engine.list.col.source': 'Source', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index b3789db1378..1053f58e27b 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -3622,6 +3622,36 @@ const STUDIO_ZH: Record = { 'engine.packageAsk.systemApp.view': '系统应用里不能保存共享视图:系统应用随平台提供,没有存放你改动的软件包。请改存到「我的视图」,或者到你的业务应用里添加这个视图。', 'engine.packageAsk.systemApp.report': '系统应用里不能保存报表:系统应用随平台提供,没有存放你改动的软件包。请到你的业务应用里新建这份报表。', 'engine.packageAsk.callerRefused': '无法替你存进这个应用的软件包:{reason}', + // objectstack#38150 — the move door's console half: the "Loose" list's selection, the confirm step, the Packages page banner. + 'engine.looseMove.col.select': '选择', + 'engine.looseMove.select': '选择 {name}', + 'engine.looseMove.selectAll': '全选({count})', + 'engine.looseMove.selected': '已选:{count}', + 'engine.looseMove.start': '移入软件包…', + 'engine.looseMove.pick.title': '选中的项移入哪个软件包?', + 'engine.looseMove.pick.description': '散落项不属于任何软件包。移入后,每一项都放进你选的软件包,并像保存进这个软件包一样接受检查。请选择一个软件包,或新建一个。', + 'engine.looseMove.confirm.title': '移入 {package}', + 'engine.looseMove.confirm.description': '每一项都像保存进这个软件包一样接受检查。移入是整批的:只要有一项被拒,就一项都不移。', + 'engine.looseMove.confirm.checking': '正在检查移入后会怎样…', + 'engine.looseMove.confirm.failed': '无法检查这次移入:{error}', + 'engine.looseMove.confirm.draftOnly': '(仅草稿)', + 'engine.looseMove.confirm.address': '地址:', + 'engine.looseMove.confirm.aiFace': 'AI 看到的名称:', + 'engine.looseMove.confirm.refused': '以下各项不能移入,所以这次一项都不会移:', + 'engine.looseMove.confirm.refusedOnMove': '移入被拒,一项都没有移:', + 'engine.looseMove.confirm.addReferences': '把它们用到的散落项一起加上,再检查一次:{items}', + 'engine.looseMove.confirm.dryRunNote': '这只是检查,还没有移入。有些保存检查要真正移入时才做,所以那时某一项仍可能被拒;一旦被拒,一项都不移。', + 'engine.looseMove.confirm.undoNote': '以后要撤销:回退这次移入的软件包提交,会把这些项从软件包里删掉,不会让它们重新变回散落项。', + 'engine.looseMove.confirm.cancel': '取消', + 'engine.looseMove.confirm.retry': '重试', + 'engine.looseMove.confirm.moving': '正在移入…', + 'engine.looseMove.confirm.move': '移入', + 'engine.looseMove.moved': '已移入 {package}:{count} 项。', + 'engine.looseItems.banner': '有 {count} 个散落项,不属于任何软件包', + 'engine.looseItems.bannerOne': '有 1 个散落项,不属于任何软件包', + 'engine.looseItems.bannerHint': '打开一种类型,勾选它的散落项,再移入软件包。', + 'engine.looseItems.typeCount': '{type}({count})', + 'engine.looseItems.unread': '以下类型没能计数:{types}', 'engine.list.refresh': '刷新', 'engine.list.search': '搜索名称、显示名或描述…', 'engine.list.empty': '暂无数据。', @@ -3658,6 +3688,7 @@ const STUDIO_ZH: Record = { 'engine.list.sourceFilter.all': '全部来源({count})', 'engine.list.sourceFilter.changed': '已修改和新建({count})', 'engine.list.sourceFilter.system': '系统自带({count})', + 'engine.list.sourceFilter.loose': '散落项({count})', 'engine.list.col.name': '名称', 'engine.list.col.label': '显示名', 'engine.list.col.source': '来源',