diff --git a/.changeset/29416-packageless-app-reads-by-name.md b/.changeset/29416-packageless-app-reads-by-name.md new file mode 100644 index 00000000000..00376d59dd8 --- /dev/null +++ b/.changeset/29416-packageless-app-reads-by-name.md @@ -0,0 +1,16 @@ +--- +'@object-ui/app-shell': patch +--- + +perf(app-shell): an app built in the console and a page outside the app bundle read what they name by name + +Clause-②: no +Metadata-protocol: none + +An app created in the console has no package, and three of its reads still downloaded a whole metadata list: + +- Every route of such an app read the whole `/meta/view` list: the sidebar's capability gate composed its union of `requiresObject` names, which names other apps' objects outside this app's bundle, with their views. It now asks those names without views, as it already did outside an app, and a names-only object read composes only the views of the names its reader asked. +- An object's route read the whole object registry. It now reads the route's object, the app's `requiresObject` entries and the object's lookup targets by name; the lookup targets are asked without views. The view tabs and the view crumb keep reading their served labels from the same documents, so labels are unchanged. +- A page the app bundle does not hold (in any app) read the whole `/meta/page` list in the route, the page view and the phone title. It is now read by name, and the list is read only when the by-name answer cannot be the prefer-local pick (ADR-0048): another package's page in a packaged app, or no page at all. + +Once something else has loaded a list, these readers read it and ask nothing more. diff --git a/ui/packages/app-shell/src/console/AppContent.tsx b/ui/packages/app-shell/src/console/AppContent.tsx index bda9b86e7c4..074489843e4 100644 --- a/ui/packages/app-shell/src/console/AppContent.tsx +++ b/ui/packages/app-shell/src/console/AppContent.tsx @@ -34,6 +34,7 @@ import { import { buildExpressionUser } from '../providers/expressionUser.js'; import { useTrackRouteAsRecent } from '../hooks/useTrackRouteAsRecent.js'; import { useHomePath } from '../hooks/useHomePath.js'; +import { readItemPreferLocal, useReadItemsByName } from '../hooks/useObjectPresence.js'; import { useLauncherApps } from '../hooks/useLauncherApps.js'; import { useSignedInUserLocale } from '../hooks/useUserLocale.js'; import { resolveRecordFormTarget, resolveRecordFormModalLayout, resolveFormViewChrome, selectRecordFormView, resolveNavigateCreateUrl, resolveNavigateEditUrl, resolvePostCreateTarget, recordFormCreateValues, readRecordFormCreateValues, RECORD_FORM_CREATE_VALUES_STATE } from '../utils/recordFormNavigation.js'; @@ -343,6 +344,8 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = // objectstack#28645 — what the app bundle answers in render (null outside a // `MetadataProvider`): the page a page route opens is read there first. const bundledReads = useBundledReads(); + // objectstack#29416 — a page the bundle does not hold is asked by name. + const readItemsByName = useReadItemsByName(metadata); // objectui#7373 — where this file's two "you cannot be here" exits land. Both // sit BELOW the readiness gate further down (`metadataLoading` &c), so the // list they resolve against has settled; an app list that failed to load is @@ -481,15 +484,20 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = hostRoutePaths, (pageName) => { // objectstack#28645 — the bundle's page when it holds this package's; - // the `/meta/page` list, prefer-local, for a page it does not hold. + // objectstack#29416 — else the page by name, prefer-local, and the + // `/meta/page` list only when the by-name answer cannot be the pick. const bundled = bundledReads?.item('page', pageName, (activeApp as any)?._packageId); if (bundled?.state === 'hit') return { page: bundled.value, settled: true }; if (bundled?.state === 'pending') return { page: undefined, settled: false }; - const status = getTypeStatus?.('page'); - return { - page: preferLocal(metadata.pages as any[], pageName, (activeApp as any)?._packageId), - settled: status === undefined || status === 'ready' || status === 'error', - }; + const { item, settled } = readItemPreferLocal( + readItemsByName, + 'page', + pageName, + (activeApp as any)?._packageId, + () => metadata.pages, + getTypeStatus?.('page'), + ); + return { page: item, settled }; }, // objectui#13046 — a record route reads the objects its declared record // page binds, picked from the page list as `RecordDetailView` picks it. diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.objectScope-12811.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.objectScope-12811.test.tsx index aff3802a469..72ae756f3c1 100644 --- a/ui/packages/app-shell/src/console/__tests__/AppContent.objectScope-12811.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.objectScope-12811.test.tsx @@ -18,10 +18,12 @@ * one `requiresObject` entry, and `useActionModal` is mounted beside it, as * `ConsoleShell` mounts it. * - * CONTROLs: an app item with no package id asks the whole registry, as before, - * and so does the root of an app whose package holds no objects of its own (a - * platform app such as Setup; its object routes read by name, objectui#13046); - * a record overlay (`?recordId=`) reads the whole registry, because a record's + * An app item with no package id asks its route's names by name instead + * (objectstack#29416; it read the whole registry). + * + * CONTROLs: the root of an app whose package holds no objects of its own (a + * platform app such as Setup; its object routes read by name, objectui#13046) + * asks the whole registry, as before; a record overlay (`?recordId=`) reads the whole registry, because a record's * related lists come from every object that points at it (since * objectstack#27626 the drawer reads it beside the list's scope, and the list * does not wait for it: `AppContent.recordDrawerKeepsScope-27626.test.tsx`). @@ -231,14 +233,15 @@ describe('one console open asks for the app\'s objects, not the whole registry ( expect(screen.getByTestId('console-layout').getAttribute('data-chrome-objects')).toBe('crm_account,crm_contact,sys_user'); }); - it('CONTROL: an app item with no package id asks the whole registry, as before', async () => { + it('an app item with no package id asks the route object and its lookup target by name, never the whole registry (objectstack#29416)', async () => { server.apps = [{ name: 'crm', label: 'CRM', navigation: NAVIGATION }]; boot('/apps/crm/crm_account'); - await waitFor(() => expect(screen.getByTestId('object-view')).toBeInTheDocument()); + await waitFor(() => expect(screen.getByTestId('object-view')).toHaveTextContent('sys_user')); - expect(objectCalls()).toContain('object'); + expect(objectCalls()).not.toContain('object'); expect(objectCalls().some((c) => c.startsWith('object?'))).toBe(false); - expect(screen.getByTestId('object-view')).toHaveTextContent('crm_account,crm_contact,crm_case,sys_user'); + expect(objectCalls()).toEqual(expect.arrayContaining(['object/crm_account', 'object/sys_user'])); + expect(screen.getByTestId('object-view')).toHaveTextContent('crm_account'); }); it("CONTROL: the root of an app whose package holds no objects of its own reads the whole registry, and asks none by name", async () => { diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.packagelessReads-29416.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.packagelessReads-29416.test.tsx new file mode 100644 index 00000000000..a0255962c44 --- /dev/null +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.packagelessReads-29416.test.tsx @@ -0,0 +1,315 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#29416 — the routes of an app created in the console (its served + * item names no package), and a page the app bundle does not hold, read the + * items they name by name, never a whole `/meta/object`, `/meta/view` or + * `/meta/page` list. + * + * The harness is the REAL `MetadataProvider` under the real `AppContent`, the + * real `PageView` and the sidebar's real capability gate (`useNavMemberGates`), + * with a client double that records each call as its URL would read and an app + * bundle that is already in hand (`peekAppBundle`, as the adapter answers it + * once the app was entered). The bundle holds what the app's navigation + * reaches: the `note` object, its view and the `notes_home` page. + * + * Pins: + * (a) a package-less app's object route reads its object by name, composes + * it with the bundle's views, and asks no list: not the registry, not + * the `/meta/view` list (the gate's union names another app's object, + * outside this bundle), not the page list; + * (b) a page the bundle does not hold is read by name, and no list is asked; + * (c) CONTROL: with the lists already loaded, both routes ask nothing by name; + * (d) prefer-local (ADR-0048): in a packaged app, a by-name answer owned by + * another package cannot be the pick, so the `/meta/page` list is read + * and the app's own page is drawn; the app's own answer is taken as is; + * in a package-less app the by-name answer is the first match, as the + * list's pick is. + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import React from 'react'; +import { cleanup, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter, Routes, Route } from 'react-router-dom'; +import { AuthProvider, ActiveOrganizationStorage } from '@object-ui/auth'; +import type { AuthClient, AuthOrganization } from '@object-ui/auth'; + +vi.mock('@object-ui/plugin-designer', async (importOriginal) => ({ + ...(await importOriginal()), + CreateAppPage: () => null, + EditAppPage: () => null, + DashboardDesignPage: () => null, +})); +// The chrome: the sidebar's capability gate, over the app list's union. +vi.mock('../../layout/ConsoleLayout', async () => { + const { useNavMemberGates } = await import('../../hooks/useNavMemberGates'); + return { + ConsoleLayout: ({ children }: { children?: React.ReactNode }) => { + const gates = useNavMemberGates(); + return ( +
+ {String(gates.checkCapability('object', 'gone_obj'))} + {children} +
+ ); + }, + }; +}); +vi.mock('../../chrome/CommandPalette', () => ({ CommandPalette: () => null })); +vi.mock('../../hooks/useStudioDesignGate', () => ({ useStudioDesignGate: () => null })); +vi.mock('../../chrome/KeyboardShortcutsDialog', () => ({ KeyboardShortcutsDialog: () => null })); +vi.mock('../../chrome/OnboardingWalkthrough', () => ({ OnboardingWalkthrough: () => null })); +// The object list: the object documents it is handed, and the route object's view keys. +vi.mock('../../views/ObjectView', () => ({ + ObjectView: ({ objects }: { objects: Array<{ name: string; listViews?: Record }> }) => ( +
o.name === 'note')?.listViews ?? {}).join(',')} + > + {objects.map((o) => o.name).join(',')} +
+ ), +})); +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ + t: (key: string, options?: Record) => String(options?.defaultValue ?? key), + }), + useObjectLabel: () => ({ objectLabel: ({ label }: { label?: string }) => label, objectPluralLabel: () => '' }), +})); + +const dataSourceStub = { + onConnectionStateChange: () => () => {}, + getConnectionState: () => 'connected', +}; +vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useAdapter: () => dataSourceStub, +})); + +const actionRunnerStub = { registerHandler: vi.fn(), getContext: () => ({}) }; +vi.mock('@object-ui/react', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useActionRunner: () => ({ execute: vi.fn(), runner: actionRunnerStub }), + useGlobalUndo: () => {}, + useMutationInvalidationBridge: () => {}, + // Stands in for the page's blocks: it names the page it was handed. + SchemaRenderer: ({ schema }: { schema: { label?: string } }) =>
{schema.label}
, + }; +}); + +import { AppContent } from '../AppContent'; +import { MetadataProvider, useMetadata } from '../../providers/MetadataProvider'; + +type Doc = { name: string; [key: string]: unknown }; + +const OBJECTS: Doc[] = [ + { name: 'note', label: 'Note', fields: { owner: { type: 'lookup', reference: 'sys_user' } } }, + { name: 'crm_account', _packageId: 'app.crm', label: 'Account', fields: {} }, + { name: 'sys_user', _packageId: 'plugin.auth', label: 'User', fields: {} }, +]; +const VIEWS: Doc[] = [ + { name: 'note.all', object: 'note', viewKind: 'list', label: 'All notes', isDefault: true, config: { type: 'grid', columns: [] } }, + { name: 'crm_account.all', object: 'crm_account', viewKind: 'list', label: 'All accounts', isDefault: true, config: { type: 'grid', columns: [] } }, +]; +const PAGES: Doc[] = [ + { name: 'notes_home', label: 'Notes home', type: 'app', regions: [] }, + { name: 'outside_page', label: 'Outside page', type: 'app', regions: [] }, + // Two packages ship `home`; the server's by-name read answers the first. + { name: 'home', _packageId: 'app.other', label: 'Other home', type: 'app', regions: [] }, + { name: 'home', _packageId: 'app.crm', label: 'CRM home', type: 'app', regions: [] }, + { name: 'crm_only', _packageId: 'app.crm', label: 'CRM only', type: 'app', regions: [] }, +]; + +const objectEntry = (name: string, requires?: string) => ({ + id: `nav_${name}`, type: 'object', label: name, objectName: name, ...(requires ? { requiresObject: requires } : {}), +}); + +/** The console-created app: no `_packageId`. */ +const NOTES_APP = { + name: 'notes', + label: 'Notes', + navigation: [objectEntry('note'), { id: 'nav_home', type: 'page', label: 'Home', pageName: 'notes_home' }, objectEntry('gone_obj', 'gone_obj')], +}; +/** Another app the list carries: it requires an object outside the notes bundle. */ +const CRM_APP = { name: 'crm', label: 'CRM', _packageId: 'app.crm', navigation: [objectEntry('crm_account', 'crm_account')] }; + +/** The notes app's bundle, keyed as the adapter's `AppBundleItems` keys it. */ +function bundleItems() { + const items = new Map }>>(); + const put = (type: string, docs: Doc[]) => { + const byName = new Map(); + for (const doc of docs) byName.set(doc.name, { item: structuredClone(doc), envelope: { type, name: doc.name, item: doc } }); + items.set(type, byName); + }; + put('object', [OBJECTS[0]]); + put('view', [VIEWS[0]]); + put('page', [PAGES[0]]); + put('dashboard', []); + return items; +} + +const server = { calls: [] as string[] }; + +const notFound = () => Promise.reject(Object.assign(new Error('not found'), { httpStatus: 404, code: 'RESOURCE_NOT_FOUND' })); + +function makeAdapter() { + const bundle = { status: 'ready', items: bundleItems() }; + return { + clearCache: vi.fn(), + invalidateCache: vi.fn(), + peekAppBundle: () => bundle, + 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 }) => { + server.calls.push(options?.packageId ? `${type}?package=${options.packageId}` : type); + const all: Doc[] = + type === 'object' ? OBJECTS : type === 'view' ? VIEWS : type === 'page' ? PAGES : type === 'app' ? [NOTES_APP, CRM_APP] : []; + const items = options?.packageId ? all.filter((o) => o._packageId === options.packageId) : all; + return Promise.resolve({ type, items: structuredClone(items) }); + }, + getItem: (type: string, name: string) => { + server.calls.push(`${type}/${name}`); + const all = type === 'object' ? OBJECTS : type === 'page' ? PAGES : []; + // ADR-0048 §3.3: a context-free by-name read answers the first match. + const item = all.find((o) => o.name === name); + return item ? Promise.resolve({ type, name, item: structuredClone(item) }) : notFound(); + }, + }, + }), + } as unknown as Parameters[0]['adapter']; +} + +const USER = 'u_29416'; +const ORG: AuthOrganization = { id: 'org_a', name: 'Org A', slug: 'a' }; + +function authClient(): AuthClient { + return { + getSession: vi.fn(async () => ({ + user: { id: USER, name: 'Ada', email: 'ada@test.com', role: 'admin', positions: ['admin'] }, + session: { token: 'tok-29416', activeOrganizationId: ORG.id }, + })), + signOut: vi.fn(async () => undefined), + getConfig: vi.fn(async () => ({ features: {} })), + listOrganizations: vi.fn(async () => [ORG]), + getActiveOrganization: vi.fn(async () => ORG), + setActiveOrganization: vi.fn(async () => ORG), + getActiveMember: vi.fn(async () => ({ id: 'm1', organizationId: ORG.id, userId: USER, role: 'owner' })), + } as unknown as AuthClient; +} + +/** Reads the whole object, view and page lists at mount, as Studio would have. */ +function LoadLists() { + const metadata = useMetadata(); + void metadata.objects; + void metadata.pages; + return null; +} + +function boot(url: string, options: { listsLoaded?: boolean } = {}) { + render( + + + {options.listsLoaded ? : null} + + + } /> + + + + , + ); +} + +/** The calls that read a whole list of one of the three types. */ +const listCalls = () => server.calls.filter((c) => c === 'object' || c === 'view' || c === 'page'); +const byNameCalls = () => server.calls.filter((c) => c.startsWith('object/') || c.startsWith('page/')); + +beforeEach(() => { + server.calls = []; + localStorage.clear(); + sessionStorage.clear(); + ActiveOrganizationStorage.clear(); +}); + +afterEach(() => { + cleanup(); + ActiveOrganizationStorage.clear(); +}); + +describe('a package-less app reads what its routes name, by name (objectstack#29416)', () => { + it('(a) its object route reads the object and its lookup target by name, with the bundle’s views, and no list', async () => { + boot('/apps/notes/note'); + await waitFor(() => expect(screen.getByTestId('object-view')).toHaveTextContent('sys_user')); + await waitFor(() => expect(screen.getByTestId('gone-entry')).toHaveTextContent('false')); + + expect(screen.getByTestId('object-view')).toHaveTextContent('note'); + expect(screen.getByTestId('object-view').getAttribute('data-views')).toContain('note.all'); + expect(byNameCalls()).toEqual(expect.arrayContaining(['object/note', 'object/sys_user', 'object/crm_account', 'object/gone_obj'])); + expect(listCalls()).toEqual([]); + }); + + it('(b) a page the bundle does not hold is read by name, and no list is asked', async () => { + boot('/apps/notes/page/outside_page'); + await waitFor(() => expect(screen.getByTestId('page-blocks')).toHaveTextContent('Outside page')); + await waitFor(() => expect(screen.getByTestId('gone-entry')).toHaveTextContent('false')); + + expect(byNameCalls()).toContain('page/outside_page'); + expect(listCalls()).toEqual([]); + }); + + it('(b) a page the bundle holds is read from it: nothing is asked for it', async () => { + boot('/apps/notes/page/notes_home'); + await waitFor(() => expect(screen.getByTestId('page-blocks')).toHaveTextContent('Notes home')); + + expect(byNameCalls()).not.toContain('page/notes_home'); + expect(listCalls()).toEqual([]); + }); + + it('(c) CONTROL: with the lists already loaded, the object route and the page route ask nothing by name', async () => { + boot('/apps/notes/note', { listsLoaded: true }); + await waitFor(() => expect(screen.getByTestId('object-view')).toHaveTextContent('note')); + await waitFor(() => expect(screen.getByTestId('gone-entry')).toHaveTextContent('false')); + expect(byNameCalls()).toEqual([]); + cleanup(); + + server.calls = []; + boot('/apps/notes/page/outside_page', { listsLoaded: true }); + await waitFor(() => expect(screen.getByTestId('page-blocks')).toHaveTextContent('Outside page')); + expect(byNameCalls()).toEqual([]); + expect(listCalls()).toContain('page'); + }); +}); + +describe('prefer-local holds for a page read by name (ADR-0048, objectstack#29416)', () => { + it('(d) a packaged app whose by-name answer is another package’s reads the list, and draws its own page', async () => { + boot('/apps/app.crm/page/home'); + await waitFor(() => expect(screen.getByTestId('page-blocks')).toHaveTextContent('CRM home')); + + expect(byNameCalls()).toContain('page/home'); + expect(listCalls()).toContain('page'); + }); + + it('(d) a packaged app whose by-name answer is its own page takes it, and reads no list', async () => { + boot('/apps/app.crm/page/crm_only'); + await waitFor(() => expect(screen.getByTestId('page-blocks')).toHaveTextContent('CRM only')); + + expect(byNameCalls()).toContain('page/crm_only'); + expect(listCalls()).not.toContain('page'); + }); + + it('(d) a package-less app takes the by-name answer, the first match, as the list’s pick is', async () => { + boot('/apps/notes/page/home'); + await waitFor(() => expect(screen.getByTestId('page-blocks')).toHaveTextContent('Other home')); + + expect(listCalls()).not.toContain('page'); + }); +}); diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.pageRouteObjects-12980.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.pageRouteObjects-12980.test.tsx index 8e463ecfdc3..eb5cc815d9b 100644 --- a/ui/packages/app-shell/src/console/__tests__/AppContent.pageRouteObjects-12980.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.pageRouteObjects-12980.test.tsx @@ -176,10 +176,12 @@ function makeAdapter() { }, getItem: (type: string, name: string) => { server.calls.push(`${type}/${name}`); - const item = (type === 'object' ? OBJECTS : []).find((o) => o.name === name); + // objectstack#29416 — a page outside the app bundle is read by name + // first, as the server answers it; only object reads are held. + const item = (type === 'object' ? OBJECTS : type === 'page' ? (server.pages as Array<{ name: string }>) : []).find((o) => o.name === name); const answer = () => item ? Promise.resolve({ type, name, item: structuredClone(item) }) : Promise.reject(Object.assign(new Error('not found'), { httpStatus: 404, code: 'RESOURCE_NOT_FOUND' })); - if (!server.holdByName) return answer(); + if (!server.holdByName || type !== 'object') return answer(); return new Promise((resolve, reject) => held.push(() => answer().then(resolve, reject))); }, }, diff --git a/ui/packages/app-shell/src/console/__tests__/appObjectScope-12811.test.tsx b/ui/packages/app-shell/src/console/__tests__/appObjectScope-12811.test.tsx index 9d205a9b25c..a19f134c50d 100644 --- a/ui/packages/app-shell/src/console/__tests__/appObjectScope-12811.test.tsx +++ b/ui/packages/app-shell/src/console/__tests__/appObjectScope-12811.test.tsx @@ -11,9 +11,10 @@ * asks the scope as soon as the app list names the app: the package list, * then by name the route object's lookup targets outside the package. * - * CONTROLs: a route outside an app, a record form overlay and an app item - * with no package id ask nothing here (`AppContent` reads the whole registry - * there). A record drawer (`?recordId=`) asks the scope of the list under it, + * CONTROLs: a route outside an app and a record form overlay ask nothing here + * (`AppContent` reads the whole registry there). An app item with no package + * id asks the route's object and its lookup targets by name, never the whole + * registry (objectstack#29416). A record drawer (`?recordId=`) asks the scope of the list under it, * as `AppContent` does (objectstack#27626). */ @@ -129,7 +130,7 @@ describe('the console root starts the app object scope (objectui#12811)', () => expect(entered).toEqual(['crm', 'hr', 'crm']); }); - it('CONTROL: outside an app, on a record form overlay, or for an app without a package id, it asks nothing', async () => { + it('CONTROL: outside an app, or on a record form overlay, it asks nothing; an app without a package id asks by name (objectstack#29416)', async () => { const outside = mount('/home', APPS); const overlay = mount('/apps/crm/crm_account?form=new', APPS); const noPackage = mount('/apps/crm/crm_account', [{ name: 'crm', navigation: [] }]); @@ -139,6 +140,6 @@ describe('the console root starts the app object scope (objectui#12811)', () => await new Promise((resolve) => setTimeout(resolve, 50)); expect(objectCalls(outside)).toEqual([]); expect(objectCalls(overlay)).toEqual([]); - expect(objectCalls(noPackage)).toEqual([]); + expect([...objectCalls(noPackage)].sort()).toEqual(['object/crm_account', 'object/sys_user']); }); }); diff --git a/ui/packages/app-shell/src/console/appObjectScope.ts b/ui/packages/app-shell/src/console/appObjectScope.ts index 8244cee32ee..04c9abe19a0 100644 --- a/ui/packages/app-shell/src/console/appObjectScope.ts +++ b/ui/packages/app-shell/src/console/appObjectScope.ts @@ -54,8 +54,12 @@ * landed. Dropping the scope for the registry had swapped the list for the * route skeleton on every first open (remounting it, and re-reading its * rows), and handed it new object documents on every open and close. The - * record form overlay still reads the whole registry instead. An app item - * without a package id has no package to scope by. + * record form overlay still reads the whole registry instead. + * + * An app item without a package id (an app created in the console) has no + * package to scope by: an object's route reads the same names by name through + * the names-only scope (objectstack#29416), and its root keeps the whole + * registry. * * Two readers ask the same question with the same answer: `AppContent`, which * renders the route, and the console root (`ConsoleShell`), which asks it as @@ -509,7 +513,16 @@ export function readAppObjectScope( } return { candidate, ...readPageObjectScope(readObjectScope, app, pageRead.page, extra), routeObjectRefusal: null }; } - if (!candidate || !packageId || !readObjectScope || !route) return { candidate, scope: null, ready: false, ...NOT_READ }; + if (!candidate || !readObjectScope || !route) return { candidate, scope: null, ready: false, ...NOT_READ }; + if (!packageId) { + // objectstack#29416 — an app with no package: an object's route reads its + // names by name through the names-only scope (the route's object, its + // lookup targets and the app's `requiresObject` entries), as an app whose + // package holds no objects does below. The app's root keeps the whole + // registry, as there. Until the app list names the app, nothing is read. + if (!app || !route.objectName) return { candidate, scope: null, ready: false, ...NOT_READ }; + return { candidate, ...readObjectRouteNames(readObjectScope, app, route.objectName, search, undefined) }; + } // The package list first: no name is asked until it has answered. const own = readObjectScope({ packageId }); if (!own.settled) return { candidate, scope: own, ready: false, ...NOT_READ }; @@ -519,25 +532,47 @@ export function readAppObjectScope( if (!route.objectName && !own.served.some((o: any) => o?._packageId === packageId)) { return { candidate, scope: null, ready: false, ...NOT_READ }; } - const routeRead = readObjectScope({ packageId, names: route.objectName ? [route.objectName] : [] }); + return { candidate, ...readObjectRouteNames(readObjectScope, app, route.objectName, search, packageId) }; +} + +/** + * An app route's object names, read through the app's package scope + * (`packageId`) or, in an app with no package, the names-only scope + * (objectstack#29416): the route's object (`objectName`, none on the app's + * root), the objects the app's own navigation and area entries require (the + * sidebar's capability gate answers from this scope), the navigation's objects + * while the command palette is open, and the route object's lookup targets. + * Only the route's object holds the route. + */ +function readObjectRouteNames( + readObjectScope: ReadObjectScope, + app: Record | undefined, + objectName: string | undefined, + search: string, + packageId: string | undefined, +): Omit { + const read = (names: readonly string[]): AppObjectScope => + packageId ? readObjectScope({ packageId, names }) : readObjectScope({ names }); + const routeRead = read(objectName ? [objectName] : []); const ready = routeReadDone(routeRead); - const routeOutcome = { failedNames: failedNamesOf(routeRead), routeObjectRefusal: refusalOf(routeRead, route.objectName) }; - // The objects the app's own navigation entries require, in its `navigation` - // and its `areas`: the sidebar's capability gate answers from this scope. + const routeOutcome = { failedNames: failedNamesOf(routeRead), routeObjectRefusal: refusalOf(routeRead, objectName) }; const names = appRequiredObjectNames(app); - if (route.objectName) names.push(route.objectName); + if (objectName) names.push(objectName); if (new URLSearchParams(search).has(COMMAND_PALETTE_PARAM)) { names.push(...navigationNames(app?.navigation, (item) => (item.type === 'object' ? item.objectName : undefined))); } - const first = readObjectScope({ packageId, names }); - const routeDef = route.objectName ? first.objects.find((o: any) => o?.name === route.objectName) : undefined; + const first = read(names); + const routeDef = objectName ? first.objects.find((o: any) => o?.name === objectName) : undefined; const lookups = routeDef ? lookupTargetNames(routeDef) : []; - return { - candidate, - scope: lookups.length > 0 ? readObjectScope({ packageId, names: [...names, ...lookups] }) : first, - ready, - ...routeOutcome, - }; + if (lookups.length === 0) return { scope: first, ready, ...routeOutcome }; + if (packageId) return { scope: read([...names, ...lookups]), ready, ...routeOutcome }; + // In an app with no package the lookup targets are asked without views: a + // lookup cell links and names its target and reads none of its views, and a + // target outside the app bundle (`sys_user`) composed with them read the + // whole `/meta/view` list. They join the names-only scope's objects as they + // land. + (readObjectScope as ReadNamesWithoutViews)({ names: lookups, views: false }); + return { scope: first, ready, ...routeOutcome }; } /** An adapter that loads app metadata bundles (`ObjectStackAdapter.loadAppBundle`). */ diff --git a/ui/packages/app-shell/src/hooks/__tests__/packagelessServedViews-29416.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/packagelessServedViews-29416.test.tsx new file mode 100644 index 00000000000..2068eabf1fa --- /dev/null +++ b/ui/packages/app-shell/src/hooks/__tests__/packagelessServedViews-29416.test.tsx @@ -0,0 +1,196 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#29416 — an object route of an app created in the console (no + * `_packageId`) reads its object by name now, not the whole registry, so the + * object type stays idle and the label sites' served reads + * (`useServedViewItems`) answer from the names-only scope. + * + * Harness: the REAL `MetadataProvider` with an app bundle already in hand + * (`peekAppBundle`), the route's reads as `AppContent` makes them + * (`readAppObjectScope`), the sidebar's gate (`useNavMemberGates`) and the + * served reads, under the app's expression context. The app's entries name no + * `requiresObject` for the route's object (the usual console-built app). + * + * Pins: + * - the route object's views stay served, and the tab and crumb labels + * (`viewTabLabel`, which both read) are byte-identical to the labels the + * whole lists give, which is what this route read before (CONTROL, in the + * same tree once the registry is loaded); + * - no `/meta/view` list is read on the way, though the gate's cross-app + * union names another app's object outside the bundle; + * - the provider: a names-only read with views composes the views of the + * names its reader asked, never of every name the shared entry holds. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { act, cleanup, render, waitFor } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { MetadataProvider, useMetadata } from '../../providers/MetadataProvider'; +import { ExpressionProvider } from '../../providers/ExpressionProvider'; +import { readAppObjectScope } from '../../console/appObjectScope'; +import { useNavMemberGates } from '../useNavMemberGates'; +import { useServedViewItems, isServedView } from '../useServedViewItems'; +import { viewTabLabel } from '../../views/viewTabLabel'; + +type Doc = { name: string; [key: string]: unknown }; + +const OBJECTS: Doc[] = [ + // `mine` is a view the object document embeds; `note.all` a `/meta/view` document. + { name: 'note', label: 'Note', fields: {}, listViews: { mine: { type: 'grid', label: 'My notes (served)' } } }, + { name: 'crm_account', _packageId: 'app.crm', label: 'Account', fields: {} }, +]; +const VIEWS: Doc[] = [ + { name: 'note.all', object: 'note', viewKind: 'list', label: 'All notes (served)', isDefault: true, config: { type: 'grid', columns: [] } }, + { name: 'crm_account.all', object: 'crm_account', viewKind: 'list', label: 'All accounts', isDefault: true, config: { type: 'grid', columns: [] } }, +]; + +const NOTES_APP = { + name: 'notes', + navigation: [{ id: 'nav_note', type: 'object', label: 'Notes', objectName: 'note' }], +}; +const CRM_APP = { + name: 'crm', + _packageId: 'app.crm', + navigation: [{ id: 'nav_acc', type: 'object', label: 'Accounts', objectName: 'crm_account', requiresObject: 'crm_account' }], +}; + +function bundleItems() { + const items = new Map }>>(); + const put = (type: string, docs: Doc[]) => { + const byName = new Map(); + for (const doc of docs) byName.set(doc.name, { item: structuredClone(doc), envelope: { type, name: doc.name, item: doc } }); + items.set(type, byName); + }; + put('object', [OBJECTS[0]]); + put('view', [VIEWS[0]]); + put('page', []); + put('dashboard', []); + return items; +} + +function makeAdapter(calls: string[]) { + const bundle = { status: 'ready', items: bundleItems() }; + return { + clearCache: () => {}, + invalidateCache: () => {}, + peekAppBundle: () => bundle, + getObjectSchema: (name: string) => { + calls.push(`object/${name}`); + const item = OBJECTS.find((o) => o.name === name); + return item ? Promise.resolve(structuredClone(item)) : Promise.reject(Object.assign(new Error('nf'), { httpStatus: 404 })); + }, + getClient: () => ({ + meta: { + getItems: (type: string) => { + calls.push(type); + const all = type === 'object' ? OBJECTS : type === 'view' ? VIEWS : type === 'app' ? [NOTES_APP, CRM_APP] : []; + return Promise.resolve({ type, items: structuredClone(all) }); + }, + getItem: (type: string, name: string) => { + calls.push(`${type}/${name}`); + return Promise.reject(Object.assign(new Error('nf'), { httpStatus: 404 })); + }, + }, + }), + } as unknown as Parameters[0]['adapter']; +} + +type Reading = { + ctx: ReturnType; + served: ReturnType; + routeObject: { listViews?: Record } | undefined; +}; + +/** The note route, read as `AppContent` reads it, with the gate and the served reads beside it. */ +function mountRoute(calls: string[]): () => Reading { + sessionStorage.clear(); + let latest: Reading | null = null; + function Route() { + const ctx = useMetadata(); + useNavMemberGates(); + const read = readAppObjectScope(ctx.readObjectScope, NOTES_APP, 'note', ''); + const objects = (read.scope ? read.scope.objects : ctx.objects) as Array<{ name: string }>; + latest = { + ctx, + served: useServedViewItems(), + routeObject: objects.find((o) => o.name === 'note') as Reading['routeObject'], + }; + return null; + } + render( + + + + + + + , + ); + return () => latest as unknown as Reading; +} + +/** A bundle pass that changes the text, so a served view drawn through it would read differently. */ +const throughBundle = (_object: string, _view: string, text: string) => `bundle(${text})`; + +/** The tab and crumb labels of the route object's views, as `viewTabLabel` draws them. */ +function labels(read: Reading): Record { + const views = read.routeObject?.listViews ?? {}; + return Object.fromEntries( + Object.entries(views).map(([id, view]) => [ + id, + viewTabLabel({ id, name: id, label: view.label }, 'note', read.served, throughBundle, 'Unlabelled', 'en'), + ]), + ); +} + +afterEach(() => cleanup()); + +describe('a package-less app’s object route keeps its views served (objectstack#29416)', () => { + it('the route object’s views are served and labelled as the whole lists label them, with no list read', async () => { + const calls: string[] = []; + const read = mountRoute(calls); + await waitFor(() => expect(Object.keys(read().routeObject?.listViews ?? {}).sort()).toEqual(['mine', 'note.all'])); + await waitFor(() => expect(isServedView(read().served, 'note', 'note.all')).toBe(true)); + + expect(isServedView(read().served, 'note', 'mine')).toBe(true); + const scoped = labels(read()); + expect(scoped).toEqual({ mine: 'My notes (served)', 'note.all': 'All notes (served)' }); + expect(calls.filter((c) => !c.includes('/'))).toEqual(['app']); + expect(read().ctx.getTypeStatus!('object')).toBe('idle'); + + // CONTROL: the same tree once the whole registry is loaded, which is what + // this route read before: byte-identical labels. + act(() => { + void read().ctx.objects; + }); + await waitFor(() => expect(read().ctx.getTypeStatus!('object')).toBe('ready')); + expect(calls).toContain('object'); + expect(labels(read())).toEqual(scoped); + }); + + it('the provider composes a names-only read’s views for the names its reader asked, not the whole shared entry', async () => { + const calls: string[] = []; + let ctx: ReturnType | null = null; + function Probe() { + ctx = useMetadata(); + return null; + } + render( + + + , + ); + const metadata = () => ctx as unknown as ReturnType; + await waitFor(() => expect(calls).toContain('app')); + type ReadNoViews = (scope: { names: string[]; views: false }) => { settled: boolean }; + const union = () => (metadata().readObjectScope as unknown as ReadNoViews)({ names: ['note', 'crm_account'], views: false }); + act(() => { + union(); + }); + await waitFor(() => expect(union().settled).toBe(true)); + await waitFor(() => expect(metadata().readObjectScope!({ names: ['note'] }).settled).toBe(true)); + + expect(calls).not.toContain('view'); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/useNavMemberGates.ts b/ui/packages/app-shell/src/hooks/useNavMemberGates.ts index 85bcc96e627..77709959ca9 100644 --- a/ui/packages/app-shell/src/hooks/useNavMemberGates.ts +++ b/ui/packages/app-shell/src/hooks/useNavMemberGates.ts @@ -376,9 +376,15 @@ export function useNavMemberGates(forApp?: Record): NavMemberGa // package leg asks without views too: inside an app the bundle answers them // anyway, and on Home (the palette's gates for its host app) nothing does, // so composing them read the whole `/meta/view` list. + // + // objectstack#29416 — inside an app with no package the union is asked + // without views as well: the gate reads only which objects there are, and + // the union names other apps' objects, which the app's bundle does not + // hold, so composing them read the whole `/meta/view` list on every route + // of such an app. The route's own objects are composed with their views by + // the route's reader (`AppContent`), not here. const metadata = useMetadata(); const packageId = typeof app?._packageId === 'string' && app._packageId ? app._packageId : undefined; - const inApp = typeof app?.name === 'string' && app.name !== ''; const readObjectScope = metadata.getTypeStatus?.('object') === 'idle' ? metadata.readObjectScope : undefined; const unionNames = readObjectScope && !packageId ? requiredObjectUnion(metadata.apps, app) : NO_MISSING; const scope: { objects: readonly unknown[]; missing: readonly string[] } | null = !readObjectScope @@ -387,9 +393,7 @@ export function useNavMemberGates(forApp?: Record): NavMemberGa ? (readObjectScope as ReadNamesWithoutViews)({ packageId, views: false }) : unionNames.length === 0 ? NO_REQUIRED_OBJECTS - : inApp - ? readObjectScope({ names: unionNames }) - : (readObjectScope as ReadNamesWithoutViews)({ names: unionNames, views: false }); + : (readObjectScope as ReadNamesWithoutViews)({ names: unionNames, views: false }); const metadataObjects = scope ? scope.objects : metadata.objects; const missingObjects = scope ? scope.missing : NO_MISSING; const registeredObjectNames = useMemo( diff --git a/ui/packages/app-shell/src/hooks/useObjectPresence.ts b/ui/packages/app-shell/src/hooks/useObjectPresence.ts index dd858c37938..3b4decf0109 100644 --- a/ui/packages/app-shell/src/hooks/useObjectPresence.ts +++ b/ui/packages/app-shell/src/hooks/useObjectPresence.ts @@ -56,6 +56,7 @@ import { useCallback, useRef, useState } from 'react'; import { useMetadata, type MetadataContextValue, type MetadataTypeStatus } from '@object-ui/react'; import { useExpressionContext } from '../providers/ExpressionProvider.js'; +import { preferLocal } from '../utils/preferLocal.js'; type ReadObjectScope = NonNullable; @@ -107,6 +108,8 @@ export type ReadItemsByName = ( type: string, names: readonly string[], list: () => readonly unknown[] | undefined, + /** Called with each asked name whose by-name read has not answered yet (objectstack#29416). */ + pending?: (name: string) => void, ) => readonly unknown[]; const NO_ANSWERS: ReadonlyMap = new Map(); @@ -139,7 +142,7 @@ export function useReadItemsByName( // `getTypeStatus` is rebuilt with it) starts a new set. const askedRef = useRef<{ of: unknown; keys: Set }>({ of: undefined, keys: new Set() }); return useCallback( - (type, names, list) => { + (type, names, list, pending) => { if (typeof getItem !== 'function' || getTypeStatus?.(type) !== 'idle') return list() ?? NO_OBJECTS; if (askedRef.current.of !== getTypeStatus) askedRef.current = { of: getTypeStatus, keys: new Set() }; const asked = askedRef.current.keys; @@ -155,6 +158,7 @@ export function useReadItemsByName( } const item = answers.get(key); if (item) found.push(item); + else if (!answers.has(key)) pending?.(name); } return found; }, @@ -162,6 +166,50 @@ export function useReadItemsByName( ); } +/** One item a route resolves by name, and whether its read has settled. */ +export interface ItemByNameRead { + item: any; + settled: boolean; +} + +/** + * The `type` item named `name` as the prefer-local pick over the type's list + * resolves it (`preferLocal`, ADR-0048), without reading that list while the + * by-name read can answer it (objectstack#29416): a route that names one item + * (a page the app bundle does not hold) asked the whole `/meta/` list. + * + * The by-name read (`GET /meta//`) takes no package and answers + * the first match (ADR-0048 §3.3), so its answer is the pick only when it + * cannot differ from it: in an app with no package (`ownerPackageId` unset, + * where the pick is the first match too), or when it is the app's own + * package's item, which the pick prefers. Otherwise, another package's item + * while the app's own may exist, or no item at all (absent, or a failed read), + * the list is read and picked from, as before. Once the list is loaded, or on + * its way, the pick reads it and nothing is asked by name. + */ +export function readItemPreferLocal( + readItemsByName: ReadItemsByName, + type: string, + name: string, + ownerPackageId: unknown, + list: () => readonly unknown[] | undefined, + status: MetadataTypeStatus | undefined, +): ItemByNameRead { + const fromList = (): ItemByNameRead => { + const listed = list(); + const now = status === 'idle' ? 'loading' : status; + return { item: preferLocal(listed as any[] | undefined, name, ownerPackageId), settled: metadataTypeSettled(now) }; + }; + if (status !== 'idle') return fromList(); + let waiting = false; + const [answer] = readItemsByName(type, [name], () => undefined, () => { + waiting = true; + }) as Array<{ _packageId?: unknown } | undefined>; + if (waiting) return { item: undefined, settled: false }; + if (answer && (!ownerPackageId || answer._packageId === ownerPackageId)) return { item: answer, settled: true }; + return fromList(); +} + /** What the metadata registry can say about one object name. */ export type ObjectPresence = 'present' | 'absent' | 'unknown'; diff --git a/ui/packages/app-shell/src/hooks/useServedViewItems.ts b/ui/packages/app-shell/src/hooks/useServedViewItems.ts index 6824922fafa..b7741b2f5dc 100644 --- a/ui/packages/app-shell/src/hooks/useServedViewItems.ts +++ b/ui/packages/app-shell/src/hooks/useServedViewItems.ts @@ -132,13 +132,17 @@ export function useServedViewItems(read = true): ServedViewReads { // objectui#12980 — inside an app whose served item names NO package, on the // same condition, the served object documents are the names-only scope's: // the objects the app's route asked for by name (`AppContent` names the - // objects the app's entries require, and a page route the objects its page - // binds). Its handle is the app's `requiresObject` names, which `AppContent` - // asks on every scoped route, so this read asks nothing new. An app that - // names none reads nothing, as `readPageObjectScope` reads nothing for a - // page that binds no object. Such an app reads the whole registry on an - // object route anyway (`appObjectScope.ts`), so the condition is false - // there and the label sites keep the whole list. + // objects the app's entries require, an object route its object and that + // object's lookup targets, and a page route the objects its page binds). + // + // objectstack#29416 — its handle is the app's navigation objects and its + // `requiresObject` names, in `navigation` and `areas[].navigation`: an + // object route of such an app reads the names-only scope now, not the whole + // registry, and the route's object is one of the navigation's. The app + // bundle answers each of them by name, so this read asks nothing new, and + // the views it composes are the bundle's, which hold the route object's. + // An app that names none reads nothing, as `readPageObjectScope` reads + // nothing for a page that binds no object. const { app } = useExpressionContext(); if (!read) return NOTHING_READ; const packageId = typeof app?._packageId === 'string' && app._packageId ? app._packageId : undefined; @@ -154,7 +158,7 @@ export function useServedViewItems(read = true): ServedViewReads { objects = scope.served; views = scope.views; } else if (scoped && isPackagelessApp(app)) { - const names = navigationNames(app.navigation, (item) => item.requiresObject); + const names = packagelessAppObjectNames(app); if (names.length > 0) { const scope = metadata.readObjectScope!({ names }) as { served: unknown; views?: unknown }; objects = scope.served; @@ -170,6 +174,20 @@ export function useServedViewItems(read = true): ServedViewReads { return servedViewReads(payloadOf(views), payloadOf(objects)); } +/** + * The objects a package-less app's entries open or require, in its + * `navigation` and every `areas[].navigation`, once each (objectstack#29416). + */ +function packagelessAppObjectNames(app: Record): string[] { + const pick = (item: Record) => (item.type === 'object' ? item.objectName : undefined); + const trees = [app.navigation, ...(Array.isArray(app.areas) ? app.areas : []).map((area) => (isRecord(area) ? area.navigation : undefined))]; + const names = trees.flatMap((tree) => [ + ...navigationNames(tree, pick), + ...navigationNames(tree, (item) => item.requiresObject), + ]); + return [...new Set(names)]; +} + /** * An app item the console renders that names no package (an app created in * the console is stored bound to none, and served without `_packageId`). diff --git a/ui/packages/app-shell/src/layout/AppHeader.tsx b/ui/packages/app-shell/src/layout/AppHeader.tsx index c31a43efaf5..e75c1645d84 100644 --- a/ui/packages/app-shell/src/layout/AppHeader.tsx +++ b/ui/packages/app-shell/src/layout/AppHeader.tsx @@ -89,6 +89,7 @@ import type { BreadcrumbItem as BreadcrumbItemType } from '@object-ui/types'; import { useAuth, getUserInitials } from '@object-ui/auth'; import { useMetadata } from '../providers/MetadataProvider.js'; import { useBundledReads } from '../providers/bundledReads.js'; +import { readItemPreferLocal, useReadItemsByName } from '../hooks/useObjectPresence.js'; import { resolveKeyedI18nLabel, preferLocal, matchAppBySegment, appStudioRoutePath } from '../utils/index.js'; import { appAddressSegment } from '../utils/appRoute.js'; import { getIcon } from '../utils/getIcon.js'; @@ -488,6 +489,7 @@ export function AppHeader({ // objectstack#28645 — the dashboard or page the phone title names, read from // the app bundle first; the list below only for one the bundle does not hold. const bundledReads = useBundledReads(); + const readItemsByName = useReadItemsByName(metadata); const { currentAppName, recordTitle } = useNavigationContext(); /** @@ -715,12 +717,22 @@ export function AppHeader({ if (pathParts[3]) { const pageName = pathParts[3]; const bundledPage = bundledReads?.item('page', pageName, (currentApp as any)?._packageId); + // objectstack#29416 — a page the bundle does not hold is read by name, + // and from the `/meta/page` list only when that answer cannot be the + // prefer-local pick (`readItemPreferLocal`). const pageDef = bundledPage?.state === 'hit' ? bundledPage.value : bundledPage?.state === 'pending' ? undefined - : preferLocal(metadata.pages as any[], pageName, (currentApp as any)?._packageId); + : readItemPreferLocal( + readItemsByName, + 'page', + pageName, + (currentApp as any)?._packageId, + () => metadata.pages, + metadata.getTypeStatus?.('page'), + ).item; // A page's `label` may be an inline locale map; drawn raw, the phone // bar's title blanked the page (objectui#13488). const fallback = metadataText(pageDef?.label, language) ?? humanizeSlug(pageName); diff --git a/ui/packages/app-shell/src/layout/__tests__/AppHeader.pageTitleByName-29416.test.tsx b/ui/packages/app-shell/src/layout/__tests__/AppHeader.pageTitleByName-29416.test.tsx new file mode 100644 index 00000000000..09976642dd3 --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/AppHeader.pageTitleByName-29416.test.tsx @@ -0,0 +1,185 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#29416 — the phone bar's title on a page route names a page the + * app bundle does not hold by reading that page by name, never the whole + * `/meta/page` list, in an app with no package (the by-name answer is the + * prefer-local pick there, ADR-0048 §3.3). Harness: `AppHeader`'s, from + * `AppHeader.dashboardPageNoCrumb-12526`, over a metadata context that records + * which of the two reads the bar makes. + * + * CONTROL: once the page list is loaded the bar reads it, and asks nothing by + * name, and names the page by its served label. + */ +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen, within } from '@testing-library/react'; +import React from 'react'; +import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; + +const route = vi.hoisted(() => ({ pathname: '/apps/crm/page/welcome' })); +const served = vi.hoisted(() => ({ + pages: [{ name: 'welcome', type: 'home', label: 'Welcome (served-29416)' }] as Array<{ name: string; type: string; label: string }>, + status: 'idle' as 'idle' | 'ready', + listReads: 0, + byName: [] as string[], +})); + +vi.mock('react-router-dom', () => ({ + useLocation: () => ({ pathname: route.pathname, search: '', hash: '', state: null, key: 't' }), + useParams: () => ({ appName: 'crm' }), + useNavigate: () => vi.fn(), + useSearchParams: () => [new URLSearchParams(), vi.fn()] as const, + Link: ({ children, to, ...p }: Record & { children?: React.ReactNode }) => ( + {children} + ), +})); + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ + language: 'en', + t: (key: string, options?: Record) => String(options?.defaultValue ?? key), + }), + // Pass-through: each label read answers the label it is handed, so a phone + // title reads as the served label, or as the humanized slug the header hands + // the bundle when nothing was served. + useObjectLabel: () => { + const label = (x: { name?: string; label?: string } | string) => + typeof x === 'string' ? x : String(x?.label ?? x?.name ?? ''); + return { + objectLabel: label, + objectPluralLabel: label, + dashboardLabel: label, + pageLabel: label, + reportLabel: label, + viewLabel: (_o: string, _v: string, fallback?: string) => fallback ?? '', + appLabel: label, + }; + }, +})); +vi.mock('@object-ui/react', async (importOriginal) => ({ + ...(await importOriginal>()), + useOffline: () => ({ isOnline: true }), +})); +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + PresenceAvatars: () => null, + useTenantPresence: () => [], +})); +vi.mock('../ModeToggle', () => ({ ModeToggle: () => null })); +vi.mock('../WorkspaceSwitcher', () => ({ WorkspaceSwitcher: () => null })); +vi.mock('../CurrentOrganizationIndicator', () => ({ CurrentOrganizationIndicator: () => null })); +vi.mock('../LocaleSwitcher', () => ({ LocaleSwitcher: () => null })); +vi.mock('../ConnectionStatus', () => ({ ConnectionStatus: () => null })); +vi.mock('../LocalizedSidebarTrigger', () => ({ LocalizedSidebarTrigger: () => null })); +vi.mock('../InboxPopover', () => ({ InboxPopover: () => })); +vi.mock('../../hooks/useAiSurface', () => ({ + useAiSurfaceEnabled: () => ({ enabled: false, isLoading: false }), +})); +// The pill is a recorder: its own rendering is `AppSwitcher.appIdentity-12201`'s. +vi.mock('../AppSwitcher', () => ({ + AppSwitcher: (p: { activeAppName: string }) => ( +
+ ), +})); +vi.mock('../../context/NavigationContext.js', () => ({ + useNavigationContext: () => ({ currentAppName: 'crm', recordTitle: undefined }), +})); +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ + user: { id: 'u1', name: 'Lin Yue', email: 'linyue@example.com' }, + signOut: vi.fn(), + isAuthEnabled: true, + organizations: [], + activeOrganization: null, + isOrganizationsLoading: false, + getAuthConfig: undefined, + }), + getUserInitials: () => 'LY', + useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }), +})); +// The metadata context records what the bar reads: the `/meta/page` list (the +// `pages` getter) or one page by name (`getItem`). +vi.mock('../../providers/MetadataProvider', () => { + const ctx = { + apps: [{ name: 'crm', label: 'CRM' }], + dashboards: [], + reports: [], + get pages() { + served.listReads += 1; + return served.pages; + }, + // Only the page type is in question; every other answers as loaded. + getTypeStatus: (type: string) => (type === 'page' ? served.status : 'ready'), + getItem: async (type: string, name: string) => { + served.byName.push(`${type}/${name}`); + return served.pages.find((p) => p.name === name) ?? null; + }, + }; + return { useMetadata: () => ctx }; +}); +vi.mock('../../providers/AdapterProvider', () => ({ + useAdapter: () => ({ find: () => Promise.resolve({ data: [] }), getClient: () => undefined }), +})); + +import { AppHeader } from '../AppHeader'; + +const MEMBER: MePermissionsAuthenticatedResponse = { + authenticated: true, + userId: 'u1', + tenantId: 'org_1', + positions: [], + hasAnyQueue: false, + permissionSets: [], + systemPermissions: [], + objects: {}, + fields: {}, +}; + +function mountAt(pathname: string) { + route.pathname = pathname; + return render( + + + , + ); +} + +/** The phone bar's compact title: the one `sm:hidden` element in the left group reading `text`. */ +function phoneTitle(text: string): HTMLElement { + const leftGroup = screen.getByTestId('app-switcher-stub').parentElement!.parentElement!; + const hits = within(leftGroup).getAllByText(text); + expect(hits).toHaveLength(1); + expect(hits[0].className.split(' ')).toEqual(expect.arrayContaining(['sm:hidden'])); + return hits[0]; +} + +beforeEach(() => { + served.status = 'idle'; + served.listReads = 0; + served.byName = []; + vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ data: [] }) }))); +}); + +describe('the phone title reads a page outside the bundle by name (objectstack#29416)', () => { + // The harness's bar is drawn synchronously and torn down at once (its feeds + // do not survive an awaited tick here), so this pins what the render asks; + // that the answer is drawn is `AppContent.packagelessReads-29416`'s pin of + // the same reader (`readItemPreferLocal`). + it('asks the page by name, never the page list, and names it by its slug until the answer lands', () => { + mountAt('/apps/crm/page/welcome'); + phoneTitle('Welcome'); + expect(served.byName).toEqual(['page/welcome']); + expect(served.listReads).toBe(0); + }); + + it('CONTROL: with the page list loaded it reads the list, and asks nothing by name', () => { + served.status = 'ready'; + mountAt('/apps/crm/page/welcome'); + phoneTitle('Welcome (served-29416)'); + expect(served.byName).toEqual([]); + expect(served.listReads).toBeGreaterThan(0); + }); +}); diff --git a/ui/packages/app-shell/src/providers/MetadataProvider.tsx b/ui/packages/app-shell/src/providers/MetadataProvider.tsx index e667647fb38..e4def23e12d 100644 --- a/ui/packages/app-shell/src/providers/MetadataProvider.tsx +++ b/ui/packages/app-shell/src/providers/MetadataProvider.tsx @@ -1594,7 +1594,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: /** * The views to compose a scope's objects with (objectstack#28645), and * whether they are in hand. `asked` are the names the scope's reader asked - * for (a names-only scope: every object in it). + * for (a names-only scope: those of them it holds). * * - The app bundle in hand: an object it holds composes with its views (it * carries every view of every object it holds). When an asked name is @@ -1735,7 +1735,13 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: views: NO_VIEWS, }; } - const scopeViews = viewsForObjects(namesOnly ? itemNames(entry.items) : (scope.names ?? NO_NAMES)); + // objectstack#29416 — a names-only scope composes the views of the names + // THIS reader asked, never of every name in the shared entry: the nav + // gate's cross-app `requiresObject` union lands there too (`views: + // false`), and an object of another app outside the bundle read the whole + // `/meta/view` list for a reader that never asked about it. + const asked = scope.names ?? NO_NAMES; + const scopeViews = viewsForObjects(namesOnly ? itemNames(entry.items).filter((name) => asked.includes(name)) : asked); return { objects: composeObjects(entry.items, scopeViews.views) as any[], served: entry.items, diff --git a/ui/packages/app-shell/src/views/PageView.tsx b/ui/packages/app-shell/src/views/PageView.tsx index 1285c53ec7e..7f33b447352 100644 --- a/ui/packages/app-shell/src/views/PageView.tsx +++ b/ui/packages/app-shell/src/views/PageView.tsx @@ -36,7 +36,7 @@ import { MetadataPanel, useMetadataInspector } from './MetadataInspector.js'; import { useMetadata } from '../providers/MetadataProvider.js'; import { useBundledItem } from '../providers/bundledReads.js'; import { PageRecordScope, useExpressionContext } from '../providers/ExpressionProvider.js'; -import { preferLocal } from '../utils/preferLocal.js'; +import { readItemPreferLocal, useReadItemsByName } from '../hooks/useObjectPresence.js'; import { appStudioRoutePath } from '../utils/appRoute.js'; import { ConsoleActionRuntimeProvider } from '../hooks/useConsoleActionRuntime.js'; import { useStudioDesignGate } from '../hooks/useStudioDesignGate.js'; @@ -323,12 +323,14 @@ export function PageView() { // this app's package owns; else the `/meta/page` list, prefer-local, as // before. While the bundle is on the wire the page is not yet known. const bundledPage = useBundledItem('page', pageName, (activeApp as any)?._packageId); - const page = - bundledPage.state === 'hit' - ? bundledPage.value - : bundledPage.state === 'miss' - ? preferLocal(metadata.pages as any[], pageName, (activeApp as any)?._packageId) - : undefined; + // objectstack#29416 — a page the bundle does not hold is read by name, and + // from the list only when that answer cannot be the prefer-local pick. + const readItemsByName = useReadItemsByName(metadata); + const pageRead = + bundledPage.state === 'miss' && pageName + ? readItemPreferLocal(readItemsByName, 'page', pageName, (activeApp as any)?._packageId, () => metadata.pages, getTypeStatus?.('page')) + : undefined; + const page = bundledPage.state === 'hit' ? bundledPage.value : pageRead?.item; // Where "Edit in studio" goes: the page's surface in Studio's Interfaces // pillar, through the one derivation the app bar's pencil, the app @@ -355,8 +357,7 @@ export function PageView() { // race where the app's home page is the first thing rendered. Show a // loading state until the `page` type is actually resolved, then trust the // not-found. (getTypeStatus absent = hand-rolled context = always ready.) - const pageStatus = bundledPage.state === 'pending' ? 'loading' : getTypeStatus?.('page'); - if (pageStatus === 'idle' || pageStatus === 'loading') { + if (bundledPage.state === 'pending' || (pageRead && !pageRead.settled)) { return (