Skip to content
Merged
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/29121-home-reads-objects-by-name.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@object-ui/app-shell': patch
---

fix(app-shell): Home asks for the objects it names instead of loading the whole object registry

Clause-②: no
Metadata-protocol: none

Every visit to `/home` read `GET /api/v1/meta/object` (the whole registry, the largest metadata payload of the page) and `GET /api/v1/meta/view`, for a few object names. Now:

- The command palette is mounted from its first open. Opened, it reads its host app's object scope over the objects its navigation lists, without views: the objects its record search reads.
- Outside an app, the activity feeds' `sys_activity` check (`useObjectPresence`) and their roster's capability gate (`useNavMemberGates`) ask their names by name, without views.
- Recent rows (Home's and the palette's) and activity rows read the object each one names, by name (`readObjectsByName`, `useNavTargetLabel({ byName: true })`, `useRecentItemLabel`, `ActivityObjectLabel`). A list-view row reads its object with its views.

Once something has loaded the whole list (inside an app, say), every one of these reads it and asks nothing more. What Home and the palette show is unchanged.
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#29121 — the palette's recent rows read the objects they name, by
* name.
*
* A recent record row draws its object's label and icon (objectui#12852). It
* read them off `useMetadata().objects`, so opening the palette with a recent
* record in the list loaded the whole object registry (and the view list) — on
* Home, where nothing else had loaded it, that was the registry the page no
* longer reads. Now each row's object is read by name.
*
* Real subjects: `CommandPalette`, `CommandPaletteProvider` and
* `MetadataProvider` over a fake adapter that records each read; what the rows
* print is pinned by `CommandPalette.recentItemType-12852`.
*/

import * as React from 'react';
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { render, cleanup, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { createI18n, I18nProvider } from '@object-ui/i18n';
import type { RecentItem } from '../context/RecentItemsProvider';
import { MetadataProvider } from '../providers/MetadataProvider';

vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => ({ user: { id: 'u1' }, activeOrganization: null }),
}));

const recent = vi.hoisted(() => ({ items: [] as unknown[] }));
vi.mock('../context/RecentItemsProvider', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useRecentItems: () => ({ recentItems: recent.items, addRecentItem: () => {}, clearRecentItems: () => {} }),
}));

vi.mock('../utils/getIcon', () => ({
getIcon: (name: string) =>
function StubIcon(props: { className?: string }) {
return <svg data-testid="stub-icon" data-glyph={name} className={props.className} />;
},
}));

import { CommandPalette } from './CommandPalette';
import { CommandPaletteProvider } from '../context/CommandPaletteProvider';

const APP = { name: 'cloud', label: 'Cloud', navigation: [] };

const OBJECTS = [
{ name: 'sys_organization', label: 'Organization', icon: 'Building2', fields: {} },
{ name: 'sys_environment', label: 'Environment', icon: 'Server', fields: {} },
{ name: 'sys_user', label: 'User', icon: 'User', fields: {} },
];

function makeAdapter(calls: string[]) {
return {
clearCache: vi.fn(),
invalidateCache: vi.fn(),
getObjectSchema(this: { getClient(): any }, name: string) {
return this.getClient()
.meta.getItem('object', name)
.then((res: any) => (res && typeof res === 'object' && 'item' in res ? res.item : res));
},
getClient: () => ({
meta: {
getItems: (type: string, options?: { packageId?: string }) => {
calls.push(options?.packageId ? `${type}?package=${options.packageId}` : type);
const items = type === 'object' ? OBJECTS : type === 'app' ? [APP] : [];
return Promise.resolve({ type, items: structuredClone(items) });
},
getItem: (type: string, name: string) => {
calls.push(`${type}/${name}`);
const item = (type === 'object' ? OBJECTS : []).find((o) => o.name === name) ?? null;
return Promise.resolve({ item: structuredClone(item) });
},
},
}),
} as unknown as Parameters<typeof MetadataProvider>[0]['adapter'];
}

const metaReads = (calls: string[]) =>
calls.filter((c) => c === 'object' || c === 'view' || c.startsWith('object?') || c.startsWith('object/'));

const VISITED = '2026-10-17T00:00:00.000Z';
const record = (id: string, href: string, label: string): RecentItem => ({ id, type: 'record', href, label, visitedAt: VISITED });

function mount(items: RecentItem[]): string[] {
recent.items = items;
const calls: string[] = [];
render(
<I18nProvider instance={createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false })} persistLanguage={false}>
<MemoryRouter initialEntries={['/home?palette=1']}>
<MetadataProvider adapter={makeAdapter(calls)}>
<CommandPaletteProvider>
<CommandPalette apps={[APP]} activeApp={APP} objects={[]} onAppChange={() => {}} />
</CommandPaletteProvider>
</MetadataProvider>
</MemoryRouter>
</I18nProvider>,
);
return calls;
}

function recentRows() {
return Array.from(document.querySelectorAll('[cmdk-item][data-value^="recent "]')).map((el) => ({
type: el.querySelector('[data-testid="palette-recent-type"]')?.textContent ?? null,
icon: el.querySelector('svg')?.getAttribute('data-glyph') ?? null,
}));
}

const settle = () => new Promise((resolve) => setTimeout(resolve, 50));

beforeEach(() => sessionStorage.clear());
afterEach(() => {
cleanup();
recent.items = [];
});

describe('objectstack#29121 — the palette’s recent rows read their objects by name', () => {
it('each recent record row’s object is read by name, for its type and its icon; the whole list is never read', async () => {
const calls = mount([
record('record:sys_organization:o1', '/apps/cloud/sys_organization/record/o1', 'Objectstack'),
record('record:sys_environment:e1', '/apps/cloud/sys_environment/record/e1', 'Objectstack'),
]);
await waitFor(() =>
expect(recentRows()).toEqual([
{ type: 'Organization', icon: 'Building2' },
{ type: 'Environment', icon: 'Server' },
]),
);
await settle();
expect([...metaReads(calls)].sort()).toEqual(['object/sys_environment', 'object/sys_organization']);
});
});
19 changes: 13 additions & 6 deletions ui/packages/app-shell/src/chrome/CommandPalette.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ import { confirmUnsavedLeave } from './unsavedEdits.js';
import { useMetadata } from '../providers/MetadataProvider.js';
import { resolveHref, resolveNavItemLabel } from '@object-ui/layout';
import type { NavigationItem } from '@object-ui/types';
import { findByName, useNavTargetLabel } from '../hooks/useNavTargetLabel.js';
import { findByName, useNavTargetLabel, type NavTargetLabelOptions } from '../hooks/useNavTargetLabel.js';
import { readObjectsByName } from '../hooks/useObjectPresence.js';

import { useAuth } from '@object-ui/auth';
import { matchesPaletteQuery } from './paletteMatch.js';
import { fetchPackages, type PkgEntry } from '../views/studio-design/packages-io.js';
Expand All @@ -77,6 +79,9 @@ import { DESIGNER_SURFACE_PARAM, formatSurfaceParam } from '../views/metadata-ad
import { flattenNavigation, useAppReportEntries } from '../views/appReportIndex.js';
import { useServedApps } from '../hooks/useLauncherApps.js';

/** A recent row names its object by name (objectstack#29121). */
const RECENT_ROW_LABELS: NavTargetLabelOptions = { byName: true };

/** The palette of the active app: the frame `ConsoleLayout` draws for `/apps/APP`. */
interface AppCommandPaletteProps {
/** Omitted inside an app; `'studio'` is the other scope. */
Expand Down Expand Up @@ -389,17 +394,19 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates
* address names no object, so its row shows no type and keeps the neutral
* glyph — ⛔ never a type guessed from the title.
*
* `objects` is read inside the function, never at render: the metadata
* cache loads the object list when it is first read, and a closed palette
* reads nothing (objectui#11863).
* The object is read inside the function, never at render, so a closed
* palette reads nothing (objectui#11863); and it is read by name
* (`readObjectsByName`, objectstack#29121), so a few recent rows never load
* the whole object registry — on Home nothing else has.
*/
const metadata = useMetadata();
const recentTargetLabel = useNavTargetLabel(RECENT_ROW_LABELS);
const recentContext = (item: RecentItem): { type?: string; icon?: string } => {
const objectName = recentItemObject(item);
if (!objectName) return {};
const def = findByName(metadata.objects, objectName) as { icon?: unknown } | undefined;
const def = findByName(readObjectsByName(metadata, [objectName]), objectName) as { icon?: unknown } | undefined;
return {
type: targetLabel({ kind: 'object', objectName }) ?? objectName,
type: recentTargetLabel({ kind: 'object', objectName }) ?? objectName,
icon: typeof def?.icon === 'string' && def.icon !== '' ? def.icon : undefined,
};
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,18 @@
* This file finds every reader of the whole object list off the metadata
* context in the packages' and the console's source (a `{ objects }`
* destructured from `useMetadata()`, `useMetadata().objects`, `.objects` on a
* binding of `useMetadata()`, or `getItemsByType('object')`, which holds the
* same list as served), and fails on a reader the table below does not
* binding of `useMetadata()`, `getItemsByType('object')`, which holds the
* same list as served, or `readObjectsByName(…)`, which reads it once it is
* loaded), and fails on a reader the table below does not
* classify, and on a row that names no reader. Each row says where the reader
* runs:
*
* - `scope`: on the open path, it reads `readObjectScope`, and `objects`
* only where no package scopes the read;
* - `action`: it reads `objects` only when an action needs it, after
* `ensureType('object')`;
* - `byName`: it reads the objects it names by name (`readObjectsByName`,
* objectstack#29121), and `objects` only once something else loaded it;
* - `off`: it is not mounted on an app's object-list open, and keeps the
* whole registry (the control: its own pins stay unchanged).
*
Expand All @@ -43,7 +46,7 @@ import ts from 'typescript';
const HERE = dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = join(HERE, '..', '..', '..', '..', '..');

type Kind = 'scope' | 'action' | 'off';
type Kind = 'scope' | 'action' | 'byName' | 'off';

/** Every reader of `objects` off the metadata context, and where it runs. */
const OBJECTS_READERS: Record<string, { kind: Kind; why: string }> = {
Expand All @@ -53,15 +56,15 @@ const OBJECTS_READERS: Record<string, { kind: Kind; why: string }> = {
},
'packages/app-shell/src/hooks/useNavMemberGates.ts': {
kind: 'scope',
why: "the capability gate reads the app's scope; with no app package (the home feeds) it reads objects",
why: "the capability gate reads the app's scope; outside an app (the home feeds) the app list's required objects by name (objectstack#29121)",
},
'packages/app-shell/src/hooks/useServedViewItems.ts': {
kind: 'scope',
why: "the served object documents behind the view-tab labels (AppHeader, ObjectView) are the app scope's, until something loads the whole registry",
},
'packages/app-shell/src/hooks/useObjectPresence.ts': {
kind: 'scope',
why: "an object's presence (the bell's sys_activity feed) is asked by name through the app scope, until something loads the whole registry",
why: "an object's presence (the bell's and Home's sys_activity feed) is asked by name, through the app scope inside an app, until something loads the whole registry; it also holds readObjectsByName",
},
'packages/app-shell/src/views/appReportIndex.ts': {
kind: 'scope',
Expand All @@ -73,12 +76,18 @@ const OBJECTS_READERS: Record<string, { kind: Kind; why: string }> = {
},
'packages/app-shell/src/hooks/useConsoleActionRuntime.tsx': { kind: 'off', why: 'read inside action handlers, when an action runs' },
'packages/plugin-grid/src/ObjectGrid.tsx': { kind: 'off', why: 'read inside an action handler, when an action runs' },
'packages/app-shell/src/hooks/useNavTargetLabel.ts': { kind: 'off', why: 'read when a label is resolved for a nav entry without its own label, or a view entry' },
'packages/app-shell/src/hooks/useRecentItemLabel.ts': { kind: 'off', why: 'read when a recent object or view entry is labelled' },
'packages/app-shell/src/layout/ActivityObjectLabel.tsx': { kind: 'off', why: "the inbox and the home rail's activity rows" },
'packages/app-shell/src/hooks/useNavTargetLabel.ts': {
kind: 'off',
why: 'read when a label is resolved for a nav entry without its own label, or a view entry; with { byName: true } (Home, recent rows) the object is read by name',
},
'packages/app-shell/src/hooks/useRecentItemLabel.ts': { kind: 'byName', why: "a recent object or view entry's object, by name (objectstack#29121)" },
'packages/app-shell/src/layout/ActivityObjectLabel.tsx': { kind: 'byName', why: "the inbox's and the home rail's activity rows, each row's object by name (objectstack#29121)" },
'packages/app-shell/src/chrome/CommandPalette.tsx': { kind: 'off', why: "the Studio scope's object list, read while the palette lists Studio entries" },
'packages/app-shell/src/console/home/HomeLayout.tsx': { kind: 'off', why: 'the home page, outside any app' },
'packages/app-shell/src/console/home/HomePage.tsx': { kind: 'off', why: 'the home page, outside any app' },
'packages/app-shell/src/console/home/HomeLayout.tsx': {
kind: 'scope',
why: "Home's command palette, mounted from its first open: the host app's scope over its navigation's objects (objectstack#29121)",
},
'packages/app-shell/src/console/home/HomePage.tsx': { kind: 'byName', why: "Home's recent record rows, each row's object by name (objectstack#29121)" },
'packages/app-shell/src/views/DashboardView.tsx': { kind: 'off', why: "a dashboard route: its widgets' objects" },
'packages/app-shell/src/views/ReportView.tsx': { kind: 'off', why: "a report route: its columns' objects" },
'packages/app-shell/src/views/PageView.tsx': {
Expand Down Expand Up @@ -133,7 +142,7 @@ const isUseMetadataCall = (node: ts.Node | undefined): boolean =>
/** Whether the module reads `objects` off the metadata context, by any of the three spellings. */
function readsObjects(path: string): boolean {
const source = readFileSync(path, 'utf8');
if (!source.includes('useMetadata(')) return false;
if (!source.includes('useMetadata(') && !source.includes('readObjectsByName(')) return false;
const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true, path.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
const bindings = new Set<string>();
let found = false;
Expand Down Expand Up @@ -165,6 +174,8 @@ function readsObjects(path: string): boolean {
(ts.isIdentifier(callee) && bindings.has(`fn:${callee.text}`))
) found = true;
}
// objectstack#29121 — `readObjectsByName(…)` reads the whole list once it is loaded.
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'readObjectsByName') found = true;
ts.forEachChild(node, access);
};
access(file);
Expand Down Expand Up @@ -201,11 +212,12 @@ describe('the readers of `useMetadata().objects`, each classified (objectui#1281
expect(found).toEqual(Object.keys(OBJECTS_READERS).sort());
});

it('an open-path reader reads the scope, and an action-time reader waits for the list', () => {
it('an open-path reader reads the scope, an action-time reader waits for the list, and a by-name reader reads by name', () => {
for (const [path, { kind }] of Object.entries(OBJECTS_READERS)) {
const source = readFileSync(join(REPO_ROOT, path), 'utf8');
if (kind === 'scope') expect(source, path).toContain('readObjectScope');
if (kind === 'action') expect(source, path).toContain("ensureType('object')");
if (kind === 'byName') expect(source, path).toContain('readObjectsByName');
}
});
});
Loading
Loading