diff --git a/.changeset/28784-dashboard-route-bundle-first.md b/.changeset/28784-dashboard-route-bundle-first.md new file mode 100644 index 00000000000..4f6763afe95 --- /dev/null +++ b/.changeset/28784-dashboard-route-bundle-first.md @@ -0,0 +1,15 @@ +--- +'@object-ui/app-shell': patch +--- + +perf(app-shell): a dashboard opens from the app bundle and asks only its widgets' objects by name + +Clause-②: no +Metadata-protocol: none + +Every open of `/apps/APP/dashboard/NAME` read the `GET /api/v1/meta/dashboard` list, the whole object registry (`GET /api/v1/meta/object`) and the `GET /api/v1/meta/view` list, and the widgets' dataset queries waited for all three, though the app bundle already held the dashboard. Now: + +- The dashboard route reads its dashboard from the app bundle when the bundle holds the one the app's package owns, and the `/meta/dashboard` list (prefer-local) only for a dashboard outside it, as the page route does. +- It reads the app's object scope instead of the whole registry: the objects its widgets require (`requiresObject`), asked by name, beside the app's package list. A widget whose object the server answers absent is left out, as before. A dashboard whose widgets require no object does not wait for any object read. + +What the dashboard shows is unchanged. diff --git a/ui/packages/app-shell/src/console/AppContent.tsx b/ui/packages/app-shell/src/console/AppContent.tsx index 1b1da927362..bda9b86e7c4 100644 --- a/ui/packages/app-shell/src/console/AppContent.tsx +++ b/ui/packages/app-shell/src/console/AppContent.tsx @@ -500,6 +500,19 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = settled: status === undefined || status === 'ready' || status === 'error', }; }, + // objectstack#28784 — a dashboard route reads the objects its widgets + // require: the bundle's dashboard when it holds this package's; the + // `/meta/dashboard` list, prefer-local, for one it does not hold. + (dashboardName) => { + const bundled = bundledReads?.item('dashboard', dashboardName, (activeApp as any)?._packageId); + if (bundled?.state === 'hit') return { dashboard: bundled.value, settled: true }; + if (bundled?.state === 'pending') return { dashboard: undefined, settled: false }; + const status = getTypeStatus?.('dashboard'); + return { + dashboard: preferLocal(metadata.dashboards as any[], dashboardName, (activeApp as any)?._packageId), + settled: status === undefined || status === 'ready' || status === 'error', + }; + }, ); // Until the app list has loaded, a scope candidate does not know its package // yet, and reads nothing (the splash is up). @@ -525,11 +538,16 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps = // objectstack#28645 — a page route reads its page bundle-first (`PageView`, // the page scope above), so it does not wait for the `/meta/page` list: a // page outside the bundle is read from the list by those readers, which - // wait for it themselves. + // wait for it themselves. objectstack#28784 — a dashboard route reads its + // dashboard the same way (`DashboardView`, the dashboard scope above). const pageRouteReadsBundle = !!bundledReads && /^page\/[^/]+$/.test(appSubPath); + const dashboardRouteReadsBundle = !!bundledReads && /^dashboard\/[^/]+$/.test(appSubPath); const routeReadsKey = [ ...routeReads.filter( - (type) => (type !== 'object' || readsWholeRegistry) && !(type === 'page' && pageRouteReadsBundle), + (type) => + (type !== 'object' || readsWholeRegistry) && + !(type === 'page' && pageRouteReadsBundle) && + !(type === 'dashboard' && dashboardRouteReadsBundle), ), ...(searchParamsHasRecordForm(location.search) && !routeReads.includes('object') ? ['object'] : []), ].join(','); diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.dashboardRouteReads-28784.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.dashboardRouteReads-28784.test.tsx new file mode 100644 index 00000000000..7cb9afaffee --- /dev/null +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.dashboardRouteReads-28784.test.tsx @@ -0,0 +1,278 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#28784 — a dashboard route reads its dashboard from the app + * bundle, and the objects its widgets require by name, never the + * `/meta/dashboard` list or the whole object registry. + * + * Measured on the card: every open of `/apps/APP/dashboard/NAME` read + * `GET /api/v1/meta/dashboard`, the whole `GET /api/v1/meta/object` and + * `GET /api/v1/meta/view`, and the widgets' dataset queries waited for all + * three, though the app bundle already held the dashboard. + * + * The harness is the REAL `MetadataProvider` under the real `AppContent` and + * the real `DashboardView`, with a client double that records each read as its + * URL would read and an app bundle the test controls (`peekAppBundle`, entered + * through `loadAppBundle` as the real adapter is). `DashboardRenderer` is a + * stand-in that lists the widgets it was handed. + * + * Pins: (a) a bundled dashboard opens with no `dashboard` list, no whole + * `object` list and no `view` list; (b) the objects its widgets require are + * asked by name, and a widget whose object the server answered absent is left + * out; (c) CONTROL: a dashboard the bundle does not hold is read from the + * `dashboard` list, prefer-local, still without the whole object list. + */ + +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 widgets the view hands the renderer, by id. +vi.mock('@object-ui/plugin-dashboard', async (importOriginal) => ({ + ...(await importOriginal>()), + DashboardRenderer: ({ schema }: { schema: { name: string; widgets?: Array<{ id: string }> } }) => ( +
+ {(schema.widgets ?? []).map((w) => w.id).join(',')} +
+ ), +})); +vi.mock('../../layout/ConsoleLayout', () => ({ + ConsoleLayout: ({ children }: { children?: React.ReactNode }) =>
{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 })); +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: () => '' }), +})); + +type Items = Map }>>; +interface Bundle { + state: { status: 'none' } | { status: 'pending'; settled: Promise } | { status: 'ready'; items: Items }; +} +const bundle: Bundle = { state: { status: 'none' } }; + +// `AppContent` enters the app's bundle through the console's adapter; the +// provider reads it through its own (`peekAppBundle`), as the real adapter is one. +const dataSourceStub = { + onConnectionStateChange: () => () => {}, + getConnectionState: () => 'connected', + loadAppBundle: () => { + if (bundle.state.status !== 'none') return; + let land: () => void = () => {}; + bundle.state = { status: 'pending', settled: new Promise((r) => { land = r; }) }; + queueMicrotask(() => { + bundle.state = { status: 'ready', items: server.bundleItems() }; + land(); + }); + }, +}; +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: () => {}, + }; +}); + +import { AppContent } from '../AppContent'; +// The route's lazy element, loaded at import so the first open does not race its chunk. +import '../../views/DashboardView'; +import { MetadataProvider } from '../../providers/MetadataProvider'; + +const CRM = 'app.crm'; +const OBJECTS = [ + { name: 'crm_account', _packageId: CRM, fields: {} }, + { name: 'crm_case', _packageId: 'app.service', fields: {} }, +]; + +/** Widgets bound to datasets only: they name no object. */ +const SALES = { + name: 'sales', + label: 'Sales', + _packageId: CRM, + widgets: [ + { id: 'pipeline', type: 'bar', dataset: 'pipeline_by_stage' }, + { id: 'won', type: 'metric', dataset: 'won_this_month' }, + ], +}; +/** A widget gated on an object outside the package, and one on an object this runtime lacks. */ +const SERVICE = { + name: 'service', + label: 'Service', + _packageId: CRM, + widgets: [ + { id: 'cases', type: 'bar', dataset: 'cases_by_status', requiresObject: 'crm_case' }, + { id: 'cloud', type: 'metric', dataset: 'cloud_usage', requiresObject: 'cloud_only' }, + { id: 'plain', type: 'metric', dataset: 'won_this_month' }, + ], +}; +/** Not in the bundle; two packages ship it, and the app's own wins. */ +const SHARED = [ + { name: 'shared', label: 'Theirs', _packageId: 'app.other', widgets: [{ id: 'theirs', type: 'metric', dataset: 'x' }] }, + { name: 'shared', label: 'Ours', _packageId: CRM, widgets: [{ id: 'ours', type: 'metric', dataset: 'x' }] }, +]; + +interface Server { + calls: string[]; + apps: unknown[]; + bundleItems: () => Items; +} +const server: Server = { calls: [], apps: [], bundleItems: () => new Map() }; + +function itemsOf(byType: Record): Items { + const items: Items = new Map(); + for (const [type, docs] of Object.entries(byType)) { + const byName = new Map(); + for (const doc of docs as Array<{ name: string }>) { + byName.set(doc.name, { item: structuredClone(doc), envelope: { type, name: doc.name, item: doc } }); + } + items.set(type, byName); + } + return items; +} + +function makeAdapter() { + return { + clearCache: vi.fn(), + invalidateCache: vi.fn(), + peekAppBundle: () => bundle.state, + 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 = type === 'object' ? OBJECTS : type === 'app' ? server.apps : type === 'dashboard' ? [SALES, SERVICE, ...SHARED] : []; + const items = options?.packageId ? all.filter((o: any) => o._packageId === options.packageId) : all; + return Promise.resolve({ type, items: structuredClone(items) }); + }, + getItem: (type: string, name: string) => { + server.calls.push(`${type}/${name}`); + const item = (type === 'object' ? OBJECTS : []).find((o) => o.name === name); + return item + ? Promise.resolve({ type, name, item: structuredClone(item) }) + : Promise.reject(Object.assign(new Error('not found'), { httpStatus: 404, code: 'RESOURCE_NOT_FOUND' })); + }, + }, + }), + } as unknown as Parameters[0]['adapter']; +} + +const USER = 'u_28784'; +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-28784', 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; +} + +function boot(url: string) { + render( + + + + + } /> + + + + , + ); +} + +const objectCalls = () => server.calls.filter((c) => c === 'object' || c.startsWith('object?') || c.startsWith('object/')); + +beforeEach(() => { + server.calls = []; + server.apps = [ + { + name: 'crm', + label: 'CRM', + _packageId: CRM, + navigation: [ + { id: 'n1', type: 'object', label: 'Accounts', objectName: 'crm_account' }, + { id: 'n2', type: 'dashboard', label: 'Sales', dashboardName: 'sales' }, + { id: 'n3', type: 'dashboard', label: 'Service', dashboardName: 'service' }, + ], + }, + ]; + server.bundleItems = () => itemsOf({ object: [OBJECTS[0]], dashboard: [SALES, SERVICE] }); + bundle.state = { status: 'none' }; + localStorage.clear(); + sessionStorage.clear(); + ActiveOrganizationStorage.clear(); +}); + +afterEach(() => { + cleanup(); + ActiveOrganizationStorage.clear(); +}); + +describe('a dashboard route reads from the app bundle and asks its widgets\' objects by name (objectstack#28784)', () => { + it('(a) a bundled dashboard opens with no dashboard list, no whole object list and no view list', async () => { + boot(`/apps/${CRM}/dashboard/sales`); + await waitFor(() => expect(screen.getByTestId('dashboard-widgets')).toHaveTextContent('pipeline,won')); + + expect(server.calls).not.toContain('dashboard'); + expect(server.calls).not.toContain('view'); + expect(objectCalls()).not.toContain('object'); + // Its widgets name no object: nothing is asked by name. + expect(objectCalls().filter((c) => c.startsWith('object/'))).toEqual([]); + }); + + it('(b) asks the widgets\' objects by name and leaves out a widget whose object is absent', async () => { + boot(`/apps/${CRM}/dashboard/service`); + await waitFor(() => expect(screen.getByTestId('dashboard-widgets')).toHaveTextContent('cases,plain')); + + expect(screen.getByTestId('dashboard-widgets')).not.toHaveTextContent('cloud'); + expect(objectCalls()).toContain('object/crm_case'); + expect(objectCalls()).toContain('object/cloud_only'); + expect(objectCalls()).not.toContain('object'); + expect(server.calls).not.toContain('dashboard'); + }); + + it('(c) CONTROL: a dashboard the bundle does not hold is read from the list, prefer-local, still without the whole object list', async () => { + boot(`/apps/${CRM}/dashboard/shared`); + await waitFor(() => expect(screen.getByTestId('dashboard-widgets')).toHaveTextContent('ours')); + + expect(server.calls).toContain('dashboard'); + expect(objectCalls()).not.toContain('object'); + }); +}); 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 bcae8d26998..d1fc85ac634 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 @@ -88,7 +88,10 @@ const OBJECTS_READERS: Record = { 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/DashboardView.tsx': { + kind: 'scope', + why: "a dashboard route asks its widgets' objects by name (readDashboardWidgetObjects); a context without readObjectScope reads objects", + }, 'packages/app-shell/src/views/ReportView.tsx': { kind: 'off', why: "a report route: its columns' objects" }, 'packages/app-shell/src/views/PageView.tsx': { kind: 'scope', diff --git a/ui/packages/app-shell/src/console/appObjectScope.ts b/ui/packages/app-shell/src/console/appObjectScope.ts index 1a75ed3b061..8244cee32ee 100644 --- a/ui/packages/app-shell/src/console/appObjectScope.ts +++ b/ui/packages/app-shell/src/console/appObjectScope.ts @@ -18,6 +18,11 @@ * a block names outside that set is read by name when the block asks for it * (`PageView`). * + * A dashboard (`dashboard/:dashboardName`, objectstack#28784) reads only the + * objects its widgets require ({@link dashboardObjectNames}), by name, the + * way a page reads the ones it binds; its widgets' dataset queries wait for + * those names alone, and for nothing when it names none. + * * An object's list in an app whose package holds no objects of its own * (objectui#13046: cloud's control-plane app, whose package ships only the * app, and Setup, whose every entry opens another package's object) reads the @@ -65,6 +70,7 @@ import { defaultRecordPageObject } from '@objectstack/spec/ui'; import { APP_ROUTE_METADATA_READS } from './appRouteMetadataReads.js'; import { matchAppBySegment } from '../utils/appRoute.js'; import { COMMAND_PALETTE_PARAM, RECORD_FORM_OBJECT_PARAM, RECORD_FORM_PARAM } from '../urlParams.js'; +import type { ReadNamesWithoutViews } from '../hooks/useObjectPresence.js'; type ReadObjectScope = NonNullable; export type AppObjectScope = ReturnType; @@ -118,17 +124,23 @@ export const APP_OBJECT_SCOPE_ROUTES: readonly string[] = [ 'page/:pageName', ':objectName/record/:recordId', ':objectName/record/:recordId/page/:pageName', + 'dashboard/:dashboardName', ]; function matchObjectScopeRoute( subPath: string, hostPaths: readonly string[], -): { objectName?: string; pageName?: string; recordId?: string } | null { +): { objectName?: string; pageName?: string; recordId?: string; dashboardName?: string } | null { const routes = [...APP_ROUTE_METADATA_READS.map(({ path }) => ({ path })), ...hostPaths.map((path) => ({ path }))]; const matches = matchRoutes(routes, `/${subPath.replace(/^\/+/, '')}`); const match = matches?.[matches.length - 1]; if (!match || !APP_OBJECT_SCOPE_ROUTES.includes(match.route.path)) return null; - return { objectName: match.params.objectName, pageName: match.params.pageName, recordId: match.params.recordId }; + return { + objectName: match.params.objectName, + pageName: match.params.pageName, + recordId: match.params.recordId, + dashboardName: match.params.dashboardName, + }; } function isRecord(value: unknown): value is Record { @@ -250,6 +262,77 @@ export function readPageObjectScope( }; } +/** + * objectstack#28784 — the objects a dashboard definition names: each widget's + * `requiresObject`, else its `object` (the pre-ADR-0021 inline arm), which is + * what `DashboardView`'s capability gate reads to hide a widget whose object + * this runtime does not register. Nothing else on a dashboard reads an object + * definition off the metadata context: a dataset-bound widget learns its base + * object from its query's answer, never from the registry. + */ +export function dashboardObjectNames(dashboard: unknown): string[] { + const widgets = isRecord(dashboard) && Array.isArray(dashboard.widgets) ? dashboard.widgets : []; + const out = new Set(); + for (const widget of widgets) { + if (!isRecord(widget)) continue; + const required = widget.requiresObject ?? widget.object; + if (typeof required === 'string' && required) out.add(required); + } + return [...out]; +} + +/** + * objectstack#28784 — whether this runtime registers the objects a + * dashboard's widgets require ({@link dashboardObjectNames}): those names + * alone, by name, riding the app's package scope when the app names a + * package, and without views (a presence answer: `missing` lists the names + * the server answered without a definition). No name asks nothing and is + * settled at once, so a dashboard that names none never waits for the + * package list. + */ +export function readDashboardWidgetObjects( + readObjectScope: ReadObjectScope, + app: Record | undefined, + dashboard: unknown, +): AppObjectScope { + const packageId = typeof app?._packageId === 'string' && app._packageId ? app._packageId : undefined; + const names = dashboardObjectNames(dashboard); + if (names.length === 0) return NO_OBJECT_SCOPE; + const read = readObjectScope as ReadNamesWithoutViews; + return packageId ? read({ packageId, names, views: false }) : read({ names, views: false }); +} + +/** + * objectstack#28784 — the objects a dashboard route reads: the names its + * widgets require plus `extraNames` (the chrome's), by name, riding the app's + * package scope when the app names a package, as a page route's do. `ready` + * is true once the widgets' names have answered ({@link + * readDashboardWidgetObjects}): the widgets' dataset queries wait for nothing + * else. No lookup targets are asked: no widget reads them. + */ +export function readDashboardObjectScope( + readObjectScope: ReadObjectScope, + app: Record | undefined, + dashboard: unknown, + extraNames: readonly string[] = [], +): { scope: AppObjectScope; ready: boolean; failedNames: readonly string[] } { + const packageId = typeof app?._packageId === 'string' && app._packageId ? app._packageId : undefined; + const widgetRead = readDashboardWidgetObjects(readObjectScope, app, dashboard); + const names = [...new Set([...dashboardObjectNames(dashboard), ...extraNames])]; + const scope = packageId + ? readObjectScope({ packageId, names }) + : names.length > 0 + ? readObjectScope({ names }) + : NO_OBJECT_SCOPE; + return { scope, ready: routeReadDone(widgetRead), failedNames: failedNamesOf(widgetRead) }; +} + +/** The dashboard a dashboard route resolves to, and whether it is known yet (objectstack#28784). */ +export interface DashboardRead { + dashboard: unknown; + settled: boolean; +} + /** The page list, and whether the `page` type has answered (objectui#13046). */ export interface PagesRead { pages: readonly unknown[]; @@ -370,10 +453,29 @@ export function readAppObjectScope( hostPaths: readonly string[] = [], readPage?: (pageName: string) => PageRead, readPages?: () => PagesRead, + readDashboard?: (dashboardName: string) => DashboardRead, ): AppObjectScopeRead { const route = matchObjectScopeRoute(subPath, hostPaths); const candidate = !!route && !!readObjectScope && !hasRecordFormOverlay(search); const packageId = typeof app?._packageId === 'string' && app._packageId ? app._packageId : undefined; + if (candidate && readObjectScope && route && route.dashboardName !== undefined) { + // objectstack#28784 — a dashboard route: the app list, then the dashboard + // (bundle-first), then the objects its widgets require, by name. Never + // the whole registry. + if (!app) return { candidate, scope: null, ready: false, ...NOT_READ }; + const dashboardRead = readDashboard?.(route.dashboardName); + if (!dashboardRead?.dashboard) { + // Not known yet: the package list starts beside it. Known absent: + // `DashboardView` draws its not-found or its refusal, and reads no object. + if (dashboardRead?.settled) return { candidate, scope: NO_OBJECT_SCOPE, ready: true, ...NOT_READ }; + return { candidate, scope: packageId ? readObjectScope({ packageId }) : PENDING_OBJECT_SCOPE, ready: false, ...NOT_READ }; + } + const extra = appRequiredObjectNames(app); + if (new URLSearchParams(search).has(COMMAND_PALETTE_PARAM)) { + extra.push(...navigationNames(app.navigation, (item) => (item.type === 'object' ? item.objectName : undefined))); + } + return { candidate, ...readDashboardObjectScope(readObjectScope, app, dashboardRead.dashboard, extra), routeObjectRefusal: null }; + } if (candidate && readObjectScope && route && route.recordId !== undefined && route.objectName) { // objectui#13046 — a record route: the app list, then the page list, then // either the objects the record's declared page binds, by name, or the diff --git a/ui/packages/app-shell/src/console/appRouteMetadataReads.ts b/ui/packages/app-shell/src/console/appRouteMetadataReads.ts index be99b3c6c7d..c643467fff0 100644 --- a/ui/packages/app-shell/src/console/appRouteMetadataReads.ts +++ b/ui/packages/app-shell/src/console/appRouteMetadataReads.ts @@ -57,7 +57,10 @@ export const APP_ROUTE_METADATA_READS: ReadonlyArray<{ path: string; reads: read { path: ':objectName/record/:recordId', reads: ['object', 'page'] }, { path: ':objectName/record/:recordId/page/:pageName', reads: ['object', 'page'] }, // DashboardView, ReportView, PageView: their own bucket and the objects - // their widgets, columns and record actions resolve against. + // their widgets, columns and record actions resolve against. A dashboard + // reads its dashboard bundle-first and the objects its widgets require by + // name (`appObjectScope.ts`, objectstack#28784); both buckets stay for an + // adapter without the bundle or the scope. { path: 'dashboard/:dashboardName', reads: ['dashboard', 'object'] }, { path: 'report/:reportName', reads: ['report', 'object'] }, // AppReportIndexView (objectui#13020): the report list, and the dataset diff --git a/ui/packages/app-shell/src/views/DashboardView.tsx b/ui/packages/app-shell/src/views/DashboardView.tsx index 3ed41184753..382934df81e 100644 --- a/ui/packages/app-shell/src/views/DashboardView.tsx +++ b/ui/packages/app-shell/src/views/DashboardView.tsx @@ -34,6 +34,8 @@ import { useMetadata } from '../providers/MetadataProvider.js'; import { useExpressionContext } from '../providers/ExpressionProvider.js'; import { resolveKeyedI18nLabel, preferLocal } from '../utils/index.js'; import { useAdapter } from '../providers/AdapterProvider.js'; +import { useBundledItem } from '../providers/bundledReads.js'; +import { readDashboardWidgetObjects } from '../console/appObjectScope.js'; import { useObjectTranslation, useSafeTranslate } from '@object-ui/i18n'; /** @@ -174,12 +176,25 @@ export function DashboardView({ dataSource }: { dataSource?: any }) { queueMicrotask(() => setIsLoading(false)); }, [dashboardName]); - // `dashboards` is read first: its getter starts the list's fetch, and the - // status read after it is that fetch's. - const { dashboards, objects: metadataObjects, getTypeStatus } = useMetadata(); + // ⛔ Neither `dashboards` nor `objects` is destructured: reading `dashboards` + // loads the `/meta/dashboard` list, which the app bundle spares, and reading + // `objects` loads the whole object registry, which this view needs only to + // ask whether its widgets' objects are registered (objectstack#28784). + const metadata = useMetadata(); + const { getTypeStatus, readObjectScope } = metadata; // ADR-0048 Phase 2 — prefer the dashboard owned by the current app's package. const { app: activeApp } = useExpressionContext(); - const dashboard = preferLocal(dashboards as any[], dashboardName, (activeApp as any)?._packageId); + // objectstack#28784 — the dashboard the app bundle holds, when it holds the + // one this app's package owns; else the `/meta/dashboard` list, + // prefer-local, as before. While the bundle is on the wire the dashboard is + // not yet known. + const bundledDashboard = useBundledItem('dashboard', dashboardName, (activeApp as any)?._packageId); + const dashboard = + bundledDashboard.state === 'hit' + ? bundledDashboard.value + : bundledDashboard.state === 'miss' + ? preferLocal(metadata.dashboards as any[], dashboardName, (activeApp as any)?._packageId) + : undefined; // ---- A miss: refused, or not there? (objectui#12112) --------------------- // The server lists only the dashboards this caller may open @@ -190,7 +205,8 @@ export function DashboardView({ dataSource }: { dataSource?: any }) { // preview: the probe reads the published world, and this page reads the // draft one — `AppContent` skips its app probe there for the same reason. const previewDrafts = usePreviewDrafts(); - const dashboardsStatus = getTypeStatus?.('dashboard') ?? 'ready'; + const dashboardsStatus = + bundledDashboard.state === 'pending' ? 'loading' : bundledDashboard.state === 'hit' ? 'ready' : getTypeStatus?.('dashboard') ?? 'ready'; const dashboardsSettled = dashboardsStatus === 'ready' || dashboardsStatus === 'error'; const missedName = !dashboard && dashboardsSettled && !previewDrafts && dashboardName ? dashboardName : null; const access = useMetaItemRefusal('dashboard', missedName); @@ -201,25 +217,37 @@ export function DashboardView({ dataSource }: { dataSource?: any }) { // when not set, so any object-bound widget disappears gracefully when its // backing object isn't in this runtime (e.g. cloud-only // `sys_package_installation` on system_overview). - const registeredObjectNamesForFilter = useMemo( - () => new Set((metadataObjects || []).map((o: any) => o?.name).filter(Boolean)), - [metadataObjects], - ); - const previewSchema = useMemo(() => { - if (!dashboard) return dashboard; + // + // objectstack#28784 — asked by name (`readDashboardWidgetObjects`): a widget + // is hidden once the server answered its object absent. A hand-rolled + // metadata context has no scope to offer, and its `objects` is what it holds. + const widgetObjects = readObjectScope && dashboard ? readDashboardWidgetObjects(readObjectScope, activeApp as Record | undefined, dashboard) : null; + const absentObjectNames = widgetObjects ? widgetObjects.missing : null; + const listedObjects = readObjectScope ? null : metadata.objects; + const unregistered = useMemo((): ((name: string) => boolean) | null => { + if (absentObjectNames) { + if (absentObjectNames.length === 0) return null; + const absent = new Set(absentObjectNames); + return (name) => absent.has(name); + } + const registered = new Set((listedObjects || []).map((o: any) => o?.name).filter(Boolean)); // Defer pruning until metadata has actually loaded — otherwise the // empty Set would hide every object-bound widget on first render. - if (registeredObjectNamesForFilter.size === 0) return dashboard; + if (registered.size === 0) return null; + return (name) => !registered.has(name); + }, [absentObjectNames, listedObjects]); + const previewSchema = useMemo(() => { + if (!dashboard || !unregistered) return dashboard; const widgets = (dashboard as any).widgets; if (!Array.isArray(widgets) || widgets.length === 0) return dashboard; const filtered = widgets.filter((w: any) => { const required = w?.requiresObject ?? w?.object; if (!required) return true; - return registeredObjectNamesForFilter.has(required); + return !unregistered(required); }); if (filtered.length === widgets.length) return dashboard; return { ...dashboard, widgets: filtered }; - }, [dashboard, registeredObjectNamesForFilter]); + }, [dashboard, unregistered]); // ---- Loading / not-found guards ----------------------------------------- if (isLoading) {