diff --git a/.changeset/29121-home-reads-objects-by-name.md b/.changeset/29121-home-reads-objects-by-name.md new file mode 100644 index 00000000000..99924b44638 --- /dev/null +++ b/.changeset/29121-home-reads-objects-by-name.md @@ -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. diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.recentReadsByName-29121.test.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.recentReadsByName-29121.test.tsx new file mode 100644 index 00000000000..65ac32f5153 --- /dev/null +++ b/ui/packages/app-shell/src/chrome/CommandPalette.recentReadsByName-29121.test.tsx @@ -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>()), + useAuth: () => ({ user: { id: 'u1' }, activeOrganization: null }), +})); + +const recent = vi.hoisted(() => ({ items: [] as unknown[] })); +vi.mock('../context/RecentItemsProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useRecentItems: () => ({ recentItems: recent.items, addRecentItem: () => {}, clearRecentItems: () => {} }), +})); + +vi.mock('../utils/getIcon', () => ({ + getIcon: (name: string) => + function StubIcon(props: { className?: string }) { + return ; + }, +})); + +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[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( + + + + + {}} /> + + + + , + ); + 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']); + }); +}); diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.tsx index 6a5136aeb56..7180b52437e 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.tsx @@ -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'; @@ -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. */ @@ -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, }; }; diff --git a/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts b/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts index 6a61ea5adef..bcae8d26998 100644 --- a/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts +++ b/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts @@ -12,8 +12,9 @@ * 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: * @@ -21,6 +22,8 @@ * 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). * @@ -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 = { @@ -53,7 +56,7 @@ const OBJECTS_READERS: Record = { }, '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', @@ -61,7 +64,7 @@ const OBJECTS_READERS: Record = { }, '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', @@ -73,12 +76,18 @@ const OBJECTS_READERS: Record = { }, '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': { @@ -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(); let found = false; @@ -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); @@ -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'); } }); }); diff --git a/ui/packages/app-shell/src/console/home/HomeLayout.tsx b/ui/packages/app-shell/src/console/home/HomeLayout.tsx index 3c56c454e8c..59f635a0ad8 100644 --- a/ui/packages/app-shell/src/console/home/HomeLayout.tsx +++ b/ui/packages/app-shell/src/console/home/HomeLayout.tsx @@ -29,13 +29,24 @@ * `current_user.positions` answers here as it does in the sidebar. `features` * is not bound: Home reads no deployment config, as the scope it replaces did. * + * The palette is mounted from the first time it opens, never while Home is + * merely shown (objectstack#29121). Mounted closed, it read the whole object + * registry (`useMetadata().objects`, the largest metadata payload of the page) + * and its host app's package scope for its gates, on every visit, for a dialog + * nobody had opened. Opened, it is handed the host app's object scope over the + * objects its navigation lists, read without views: those are the objects its + * record search reads (`useRecordSearch` searches the navigation's objects and + * names their groups from these definitions), which is what the palette is + * handed inside an app as well. Once mounted it stays, so it closes as it + * always has. + * * @module */ -import React, { useCallback, useEffect, useMemo } from 'react'; +import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; import { useNavigationContext } from '../../context/NavigationContext.js'; -import { CommandPaletteProvider } from '../../context/CommandPaletteProvider.js'; +import { CommandPaletteProvider, useCommandPalette } from '../../context/CommandPaletteProvider.js'; import { CommandPalette } from '../../chrome/CommandPalette.js'; import { AppHeader } from '../../layout/AppHeader.js'; import { CONSOLE_TOP_BAR } from '../../layout/consoleTopBar.js'; @@ -44,6 +55,8 @@ import { useAdapter } from '../../providers/AdapterProvider.js'; import { filterActiveApps, matchAppBySegment, resolveHostAppSegment } from '../../utils/index.js'; import { useAiSurfaceEnabled } from '../../hooks/useAiSurface.js'; import { ExpressionProvider } from '../../providers/ExpressionProvider.js'; +import { navigationNames } from '../appObjectScope.js'; +import type { ReadNamesWithoutViews } from '../../hooks/useObjectPresence.js'; import { buildExpressionUser } from '../../providers/expressionUser.js'; import { useAuth } from '@object-ui/auth'; import { useObjectTranslation } from '@object-ui/i18n'; @@ -59,6 +72,58 @@ import { rememberDockReturnLocation } from '../../layout/chatDockState.js'; */ const NO_SCOPE_INPUT: Record = {}; +const NO_OBJECTS: any[] = []; + +/** + * The objects the palette searches, while it is open: the host app's object + * scope over the objects its navigation lists, without views + * (objectstack#29121) — its package's list plus, by name, a listed object the + * package does not hold; by name alone for an app bound to no package. Once + * the whole registry is loaded, or on its way, it is that list, and nothing + * more is asked. A provider without scope reads answers its `objects`. + */ +function useHostAppPaletteObjects(hostApp: Record): any[] { + const metadata = useMetadata(); + const names = navigationNames(hostApp.navigation, (item) => (item.type === 'object' ? item.objectName : undefined)); + const packageId = typeof hostApp._packageId === 'string' && hostApp._packageId ? hostApp._packageId : undefined; + const { readObjectScope, getTypeStatus } = metadata; + if (readObjectScope && getTypeStatus?.('object') === 'idle') { + const read = readObjectScope as ReadNamesWithoutViews; + if (packageId) return read({ packageId, names, views: false }).objects; + return names.length > 0 ? read({ names, views: false }).objects : NO_OBJECTS; + } + return metadata.objects ?? NO_OBJECTS; +} + +interface HomeCommandPaletteProps { + apps: any[]; + hostApp: Record; + onAppChange: (segment: string) => void; + dataSource?: any; +} + +/** The palette once opened, with the objects it searches. */ +function OpenedHomeCommandPalette({ apps, hostApp, onAppChange, dataSource }: HomeCommandPaletteProps) { + const objects = useHostAppPaletteObjects(hostApp); + return ( + + ); +} + +/** Home's palette: mounted from its first open (see the module doc). */ +function HomeCommandPalette(props: HomeCommandPaletteProps) { + const { open } = useCommandPalette(); + const [opened, setOpened] = useState(open); + if (open && !opened) setOpened(true); + return opened || open ? : null; +} + interface HomeLayoutProps { children: React.ReactNode; /** @@ -73,7 +138,7 @@ export function HomeLayout({ children }: HomeLayoutProps) { const { user } = useAuth(); // The shared `current_user` normaliser, keyed on the session user (objectui#6515). const expressionUser = useMemo(() => buildExpressionUser(user), [user]); - const { apps, objects } = useMetadata(); + const { apps } = useMetadata(); const dataSource = useAdapter(); const { t } = useObjectTranslation(); const navigate = useNavigate(); @@ -116,10 +181,9 @@ export function HomeLayout({ children }: HomeLayoutProps) { {hostApp ? ( {header} - navigate(`/apps/${segment}`)} dataSource={dataSource} /> diff --git a/ui/packages/app-shell/src/console/home/HomePage.tsx b/ui/packages/app-shell/src/console/home/HomePage.tsx index 07e099a3c06..e733fbcfb6c 100644 --- a/ui/packages/app-shell/src/console/home/HomePage.tsx +++ b/ui/packages/app-shell/src/console/home/HomePage.tsx @@ -20,7 +20,8 @@ import { useNavigate } from 'react-router-dom'; import { useMetadata } from '../../providers/MetadataProvider.js'; import { useRecentItems, type RecentItem } from '../../hooks/useRecentItems.js'; import { useRecentItemLabel } from '../../hooks/useRecentItemLabel.js'; -import { useNavTargetLabel } from '../../hooks/useNavTargetLabel.js'; +import { useNavTargetLabel, type NavTargetLabelOptions } from '../../hooks/useNavTargetLabel.js'; +import { readObjectsByName } from '../../hooks/useObjectPresence.js'; import { useFavorites } from '../../hooks/useFavorites.js'; import { useObjectTranslation } from '@object-ui/i18n'; // Its own line: the line above is the pack-hook binding `perm-home-namespace-3546.test.tsx` reads. @@ -343,10 +344,14 @@ function usePendingDraftsRow(t: (key: string, opts?: any) => string, language: s ); } +/** Home's labels read each object they name by name (objectstack#29121). */ +const BY_NAME: NavTargetLabelOptions = { byName: true }; + export function HomePage() { const navigate = useNavigate(); const { t, language } = useObjectTranslation(); - const { apps, objects, loading } = useMetadata(); + const metadata = useMetadata(); + const { apps, loading } = metadata; const { recentItems } = useRecentItems(); // A recent entry stores identity; the rail labels it with this, on the // render, in the current language (objectui#11678). @@ -354,7 +359,10 @@ export function HomePage() { // A record row's trail names its object as the sidebar names an unlabelled // navigation entry for it, and the app as its launcher tile does // (objectui#12604). - const targetLabel = useNavTargetLabel(); + // + // objectstack#29121 — by name: the object a row names is read alone (as its + // icon below is), so Home never loads the whole registry for its rows. + const targetLabel = useNavTargetLabel(BY_NAME); const { appLabel } = useObjectLabel(); const { favorites } = useFavorites(); const { user } = useAuth(); @@ -491,7 +499,9 @@ export function HomePage() { const app = segment ? matchAppBySegment(activeApps, segment) : undefined; const objectIcon = item.type === 'record' && objectName - ? (objects ?? []).find((o: { name?: unknown }) => o?.name === objectName)?.icon + ? (readObjectsByName(metadata, [objectName]) as Array<{ name?: unknown; icon?: unknown } | null | undefined>).find( + (o) => o?.name === objectName, + )?.icon : undefined; return { context: diff --git a/ui/packages/app-shell/src/console/home/__tests__/HomeLayout.paletteReads-29121.test.tsx b/ui/packages/app-shell/src/console/home/__tests__/HomeLayout.paletteReads-29121.test.tsx new file mode 100644 index 00000000000..5aaccb602e0 --- /dev/null +++ b/ui/packages/app-shell/src/console/home/__tests__/HomeLayout.paletteReads-29121.test.tsx @@ -0,0 +1,182 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#29121 — Home's command palette reads no object until it opens. + * + * `HomeLayout` mounted the palette closed and handed it `useMetadata().objects`, + * so every visit to `/home` read the whole object registry (and the view list) + * for a dialog nobody had opened. Now the palette is mounted from its first + * open, and handed the host app's object scope over the objects its navigation + * lists, read without views: what its record search reads. + * + * Real subjects: `HomeLayout`, `CommandPaletteProvider`, `MetadataProvider` + * over a fake adapter that records each read, and a `MemoryRouter`. The bar is + * a stub with an open button, and the palette a probe that records the objects + * it was handed (what the palette lists is its own files' pins). + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import React from 'react'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { MetadataProvider } from '../../../providers/MetadataProvider'; + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ language: 'en', t: (key: string, o?: { defaultValue?: string }) => o?.defaultValue ?? key }), +})); +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u1', name: 'Dev Admin', email: 'dev.admin@example.com' } }), +})); +vi.mock('../../../hooks/useAiSurface', () => ({ + useAiSurfaceEnabled: () => ({ enabled: false, isLoading: false }), +})); +vi.mock('../../../providers/AdapterProvider', () => ({ useAdapter: () => undefined })); +vi.mock('../../../context/NavigationContext', () => ({ + useNavigationContext: () => ({ setContext: () => {}, currentAppName: undefined, recordTitle: undefined }), +})); +// The bar: one button that opens the palette, as the search field does. +vi.mock('../../../layout/AppHeader', async () => { + const { useCommandPalette, useCommandPaletteProviderMounted } = await import('../../../context/CommandPaletteProvider'); + return { + // Drawn once a palette provider is above it (the app list has landed), as + // the real bar draws its search field. + AppHeader: () => { + const { openCommandPalette } = useCommandPalette(); + const mounted = useCommandPaletteProviderMounted(); + return mounted ?