Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/38150-move-loose-items-console.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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<string, unknown[] | Error> = {};
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<Record<string, unknown>>()),
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(
<MemoryRouter>
<LooseItemsBanner locale="en-US" />
</MemoryRouter>,
);

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();
});
});
135 changes: 135 additions & 0 deletions ui/packages/app-shell/src/views/metadata-admin/LooseItemsBanner.tsx
Original file line number Diff line number Diff line change
@@ -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<LooseCounts | null>(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<any>(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 (
<div
className="mb-4 flex items-start gap-2 rounded-md border border-amber-300/70 bg-amber-50/70 px-3 py-2.5 text-sm dark:border-amber-700/40 dark:bg-amber-950/20"
data-testid="loose-items-banner"
>
<Inbox className="mt-0.5 h-4 w-4 shrink-0 text-amber-700 dark:text-amber-300" aria-hidden="true" />
<div className="min-w-0 space-y-1">
<p className="font-medium">
{counts.total === 1
? t('engine.looseItems.bannerOne', locale)
: tFormat('engine.looseItems.banner', locale, { count: counts.total })}
</p>
<p className="text-xs text-muted-foreground">{t('engine.looseItems.bannerHint', locale)}</p>
<ul className="flex flex-wrap gap-x-3 gap-y-1 text-xs" data-testid="loose-items-banner-types">
{counts.byType.map(({ type, count }) => (
<li key={type}>
<Link
to={looseListPath(type)}
className="text-primary hover:underline"
data-testid={`loose-items-banner-${type}`}
>
{tFormat('engine.looseItems.typeCount', locale, { type: translateMetadataType(type, locale), count })}
</Link>
</li>
))}
</ul>
{counts.unread.length > 0 && (
<p className="text-xs text-muted-foreground" data-testid="loose-items-banner-unread">
{tFormat('engine.looseItems.unread', locale, { types: counts.unread.join(', ') })}
</p>
)}
</div>
</div>
);
}
Loading
Loading