diff --git a/.changeset/35932-draft-save-keeps-list.md b/.changeset/35932-draft-save-keeps-list.md new file mode 100644 index 00000000000..b7d3a4018bf --- /dev/null +++ b/.changeset/35932-draft-save-keeps-list.md @@ -0,0 +1,14 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(console): saving a shared view's draft keeps the list on screen, and a second change builds on the first + +Clause-②: no +Metadata-protocol: none + +An admin who saved a draft of a shared view (a footer calculation pick, or a view settings change) saw the list redraw on the published view about half a second later, and the change came back only after Publish. A second change before Publish was then built on the published view, so its draft replaced the first: pick Sum, then Latest, then Publish, and only Latest was kept. + +Every draft save announces itself on the metadata-refresh pulse, so the pending-drafts surfaces re-read, and every mounted metadata provider refetches its loaded types on that pulse. While the refetched view list was on the wire, the route's object scope read as unanswered, so the console dropped the route to its loading skeleton and mounted the list again, on the published view. A type that is refetching over an answer it still holds now counts as answered: the scope stays settled on the views in hand, the route stays mounted, and the list keeps the draft on screen. This holds for every refresh pulse (a publish, a package install, a change noticed in another tab), not only a draft save. On an app with a metadata bundle, the pulse also drops the bundle, and it answers nothing until it is downloaded again; meanwhile the scope's views now come from the bundle that last answered, when it holds every object the route asked for, so the route stays mounted there too. A type the provider drops (an invalidation, an organization switch) still waits for its new answer, and an organization or session switch forgets the last bundle. + +Publish and Discard in view settings now drop the list's local copy of the draft once the saved views have been read again, so the list then shows what is stored. A reader who is not an admin still sees the published view until Publish. No props, exports or locale keys change. diff --git a/ui/packages/app-shell/src/console/__tests__/AppContent.draftSaveKeepsList-35932.test.tsx b/ui/packages/app-shell/src/console/__tests__/AppContent.draftSaveKeepsList-35932.test.tsx new file mode 100644 index 00000000000..485a01b0003 --- /dev/null +++ b/ui/packages/app-shell/src/console/__tests__/AppContent.draftSaveKeepsList-35932.test.tsx @@ -0,0 +1,558 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#35932 — saving a shared view's draft keeps the list on screen. + * + * Every write of the runtime persistence seam announces itself on the + * assistant bus (`emitMetadataRefresh`, so the pending-drafts surfaces + * re-read), and every mounted `MetadataProvider` refetches its loaded types on + * that pulse. While the refetched `/meta/view` list was on the wire, the + * route's object scope read as unsettled, so `AppContent` dropped the route to + * its skeleton and mounted `ObjectView` again. The new mount read the + * PUBLISHED view: the admin's draft was gone from the screen until Publish, + * and a second footer pick was built on the published view, so the draft it + * wrote replaced the first pick. + * + * What runs: the real `AuthProvider`, `MetadataProvider`, `AppContent` and + * `ObjectView`, and the real persistence seam. Only the network is stubbed: + * the provider's adapter (with the refetched view list held open, as a real + * request is), the list's data source, and the metadata client's `save`. + * `ListView` is a stand-in that records the props it is handed and counts its + * mounts, so a remount of the route is read as a second mount. + * + * Pinned: + * - an admin's footer pick on a shared view: no skeleton, no remount, the + * list keeps the picked calculation while the refresh is on the wire and + * after it lands; + * - two successive picks: the second draft carries both; + * - the writes are draft saves; a reader (not an admin) served the published + * view draws it, without the admin's calculations. + * CONTROL: a whole-type invalidation of `view` (the provider dropping its + * items, not refetching in place) still sends the route back to waiting. + * + * The same, on an app with a bundle (the showcase's path): the provider's + * adapter has `peekAppBundle`, and the refresh pulse's `clearCache()` drops + * the bundle, as `AppBundleStore.clear()` does, so the bundle answers + * `pending` while its reload is on the wire (held here). The cases above read + * an adapter without one, which is why they missed it. Pinned: the pick, two + * picks, and Publish keep one mount and no skeleton. CONTROLS: a first entry + * held on the wire (no bundle has answered yet) still waits, and a whole-type + * `object` invalidation still sends the drawn route back to its skeleton. + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import React, { useEffect } from 'react'; +import { act, 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, +})); +vi.mock('../../layout/ConsoleLayout', () => ({ + ConsoleLayout: ({ children }: { children?: React.ReactNode }) =>
{children}
, +})); +vi.mock('../../chrome/CommandPalette', () => ({ CommandPalette: () => null })); +vi.mock('../../chrome/KeyboardShortcutsDialog', () => ({ KeyboardShortcutsDialog: () => null })); +vi.mock('../../chrome/OnboardingWalkthrough', () => ({ OnboardingWalkthrough: () => null })); + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + // Stable identities: `ListView` names `perms` in its fetch dependencies. + const perms = { + check: () => ({ allowed: true }), + checkField: () => true, + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + isLoaded: false, + hasCapabilities: () => true, + can: () => true, + cannot: () => false, + }; + const fieldPerms = { canRead: () => true, canWrite: () => true, permissions: [] }; + return { ...actual, usePermissions: () => perms, useFieldPermissions: () => fieldPerms }; +}); +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRealtimeSubscription: () => ({ lastMessage: null }), + useConflictResolution: () => ({ hasConflicts: false, resolveAllConflicts: () => {} }), +})); +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), error: vi.fn(), info: vi.fn(), + warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), + }), +})); +vi.mock('../../views/MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); +vi.mock('../../views/RecordDetailView', () => ({ RecordDetailView: () => null })); + +/** The props the list was last handed, and how many times it mounted. */ +const list = vi.hoisted(() => ({ props: null as Record | null, mounts: 0 })); +vi.mock('@object-ui/plugin-list', async (importOriginal) => { + const { useEffect: useMountEffect } = await import('react'); + return { + ...(await importOriginal()), + ListView: (props: any) => { + list.props = props; + useMountEffect(() => { + list.mounts++; + }, []); + return null; + }, + }; +}); +vi.mock('../../views/studio-design/packages-io', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchSessionPackages: vi.fn(async () => []), +})); + +/** The metadata client's writes: the network half of the persistence seam. */ +const saves = vi.hoisted(() => [] as Array<{ type: string; name: string; body: any; options: any }>); +const client = vi.hoisted(() => ({ + save: async (type: string, name: string, body: any, options: any) => { + saves.push({ type, name, body: structuredClone(body), options }); + return {}; + }, + publish: async () => ({}), + reset: async () => ({}), + get: async () => null, + layered: async () => ({}), +})); +vi.mock('../../views/metadata-admin/useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => client, +})); + +const OBJECT = 'crm_account'; +const CRM = 'app.crm'; +const VIEW = `${OBJECT}.team`; +/** The shared view as the server publishes it: no calculation on any column. */ +const PUBLISHED_VIEW = { name: VIEW, object: OBJECT, label: 'Team', type: 'grid', columns: ['name', 'amount', 'closed_at'] }; +const OBJECTS = [{ + name: OBJECT, + label: 'Account', + _packageId: CRM, + fields: { + name: { type: 'text', label: 'Name' }, + amount: { type: 'number', label: 'Amount' }, + closed_at: { type: 'date', label: 'Closed' }, + }, +}]; + +/** The list's data source (`useAdapter()`): the saved views are served published. */ +const dataSourceStub = vi.hoisted(() => ({}) as Record); +vi.mock('../../providers/AdapterProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useAdapter: () => dataSourceStub, +})); +function resetDataSource() { + Object.assign(dataSourceStub, { + onConnectionStateChange: () => () => {}, + getConnectionState: () => 'connected', + find: vi.fn(async () => ({ data: [], total: 0 })), + findOne: vi.fn(async () => null), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + getObjectSchema: vi.fn(async () => OBJECTS[0]), + listViews: vi.fn(async () => [structuredClone(PUBLISHED_VIEW)]), + updateView: vi.fn(async () => ({})), + invalidateViewKeys: vi.fn(), + // `AppContent` enters the app's bundle through the list's data source, as the console does. + ...(appBundle.on + ? { + loadAppBundle: () => { + appBundle.entered = true; + if (!appBundle.items) askBundle(); + return appBundle.settled ?? Promise.resolve(); + }, + } + : {}), + }); +} + +const actionRunnerStub = { registerHandler: vi.fn(), getContext: () => ({}) }; +vi.mock('@object-ui/react', async (importOriginal) => ({ + ...(await importOriginal>()), + useActionRunner: () => ({ execute: vi.fn(), runner: actionRunnerStub }), + useGlobalUndo: () => {}, + useMutationInvalidationBridge: () => {}, +})); + +// `AppContent` and `ObjectView` reach a dynamic `import('@objectstack/lint')`: +// pay its load at collection, never inside a case's clocked window +// (`check:test-source-alias`). +import '@objectstack/lint'; +// The route element `AppContent` loads lazily (`routeChunk.lazy`), loaded at +// collection so its factory resolves at once. +import '../../views/ObjectView.js'; +import { AppContent } from '../AppContent'; +import { MetadataProvider, useMetadata } from '../../providers/MetadataProvider'; +import { publishRuntimeMetadata } from '../../views/runtime-metadata-persistence.js'; + +interface Server { + /** Hold every `/meta/view` list read until `releaseViews`, as a request on the wire. */ + holdViews: boolean; + releaseViews: () => void; +} +const server: Server = { holdViews: false, releaseViews: () => {} }; + +type BundleItems = Map }>>; +/** + * The adapter's app bundle, as `AppBundleStore` holds it: `items` is the + * answer in hand (`null` before the first one and after `clearCache()`), and + * a load while `hold` is set stays on the wire until `releaseBundle`. + */ +const appBundle = { + /** Whether this boot's adapter has a bundle at all. */ + on: false, + entered: false, + hold: false, + items: null as BundleItems | null, + settled: null as Promise | null, + waiting: [] as Array<() => void>, + loads: 0, +}; +const APPS = [{ name: 'crm', label: 'CRM', _packageId: CRM, navigation: [{ id: 'n1', type: 'object', label: 'Accounts', objectName: OBJECT }] }]; +function bundleItems(): BundleItems { + const entry = (item: unknown) => ({ item: structuredClone(item), envelope: {} }); + return new Map([ + ['app', new Map([['crm', entry(APPS[0])]])], + ['object', new Map(OBJECTS.map((o) => [o.name, entry(o)]))], + ['view', new Map([[VIEW, entry(PUBLISHED_VIEW)]])], + ]); +} +function askBundle() { + if (appBundle.settled) return; + appBundle.loads++; + let land: () => void = () => {}; + appBundle.settled = new Promise((resolve) => { land = resolve; }); + const go = () => { + appBundle.items = bundleItems(); + appBundle.settled = null; + land(); + }; + if (appBundle.hold) appBundle.waiting.push(go); + else queueMicrotask(go); +} +const releaseBundle = () => appBundle.waiting.splice(0).forEach((go) => go()); +function resetBundle(on: boolean) { + Object.assign(appBundle, { on, entered: false, hold: false, items: null, settled: null, waiting: [], loads: 0 }); +} + +function makeAdapter() { + const heldViews: Array<() => void> = []; + server.releaseViews = () => heldViews.splice(0).forEach((go) => go()); + const bundleHost = appBundle.on + ? { + peekAppBundle: () => { + if (!appBundle.entered) return { status: 'none' }; + if (!appBundle.items) { + askBundle(); + return { status: 'pending', settled: appBundle.settled! }; + } + return { status: 'ready', items: appBundle.items }; + }, + } + : {}; + return { + ...bundleHost, + // `AppBundleStore.clear()`: the bundle's answer is dropped, the app stays entered. + clearCache: vi.fn(() => { + appBundle.items = null; + }), + invalidateCache: vi.fn(), + getObjectSchema(this: { getClient(): any }, name: string) { + return this.getClient() + .meta.getItem('object', name) + .then((res: any) => (res && typeof res === 'object' && 'item' in res ? res.item : res)); + }, + getClient: () => ({ + meta: { + getItems: (type: string, options?: { packageId?: string; names?: readonly string[] }) => { + if (options?.names) { + const named = type === 'object' ? OBJECTS.filter((o) => options.names!.includes(o.name)) : []; + return Promise.resolve({ type, items: structuredClone(named) }); + } + const all: any[] = type === 'object' ? OBJECTS : type === 'app' ? APPS : type === 'view' ? [PUBLISHED_VIEW] : []; + const items = options?.packageId ? all.filter((o: any) => o._packageId === options.packageId) : all; + const answer = { type, items: structuredClone(items) }; + if (type === 'view' && server.holdViews) return new Promise((resolve) => heldViews.push(() => resolve(answer))); + return Promise.resolve(answer); + }, + getItem: (type: string, name: string) => { + 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 ORG: AuthOrganization = { id: 'org_a', name: 'Org A', slug: 'a' }; + +function authClient(admin: boolean): AuthClient { + const user = admin + ? { id: 'u_admin', name: 'Ada', email: 'ada@test.com', role: 'admin', positions: ['admin'] } + : { id: 'u_reader', name: 'Rey', email: 'rey@test.com', role: 'user', positions: [] }; + return { + getSession: vi.fn(async () => ({ user, session: { token: `tok-${user.id}`, 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: `m_${user.id}`, organizationId: ORG.id, userId: user.id, role: admin ? 'owner' : 'member' })), + } as unknown as AuthClient; +} + +const metadata: { current: ReturnType | null } = { current: null }; +function MetadataProbe() { + const ctx = useMetadata(); + useEffect(() => { + metadata.current = ctx; + }); + return null; +} + +function boot(admin: boolean, options: { bundle?: boolean; holdFirstLoad?: boolean } = {}) { + if (options.bundle) { + resetBundle(true); + resetDataSource(); + appBundle.hold = options.holdFirstLoad === true; + } + render( + + + + + + } /> + + + + , + ); +} + +/** Forget what the list was handed (a function, so the read after it is not narrowed to `null`). */ +function forgetList() { + list.props = null; +} +const skeletonUp = () => screen.queryByTestId('route-metadata-skeleton') !== null; +/** The calculation the list draws under `field`, as the list's schema carries it. */ +const summaryOf = (field: string) => { + const columns = (list.props?.schema?.columns ?? []) as Array; + const column = columns.find((c) => (typeof c === 'string' ? c : c.field) === field); + return column && typeof column === 'object' ? column.summary : undefined; +}; +const pick = (field: string, summary: string) => + act(async () => { + await list.props!.onColumnSummaryPick(field, summary); + }); +const storedSummaries = (body: any) => + Object.fromEntries( + ((body?.config?.columns ?? body?.columns ?? []) as Array) + .filter((c): c is { field: string; summary?: unknown } => typeof c === 'object' && c.summary !== undefined) + .map((c) => [c.field, c.summary]), + ); + +beforeEach(() => { + server.holdViews = false; + saves.length = 0; + forgetList(); + list.mounts = 0; + metadata.current = null; + resetBundle(false); + resetDataSource(); + localStorage.clear(); + sessionStorage.clear(); + ActiveOrganizationStorage.clear(); +}); + +afterEach(() => { + server.releaseViews(); + appBundle.hold = false; + releaseBundle(); + cleanup(); + ActiveOrganizationStorage.clear(); +}); + +describe('objectstack#35932 — a shared view\'s draft save keeps the list on screen', () => { + it('an admin\'s footer pick: no skeleton, no remount, the pick stays drawn through the refresh', async () => { + boot(true); + await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 }); + expect(list.mounts).toBe(1); + expect(summaryOf('amount')).toBeUndefined(); + + // The refresh the save announces re-reads `/meta/view`; held, as a request on the wire. + server.holdViews = true; + await pick('amount', 'sum'); + expect(saves).toHaveLength(1); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + expect(skeletonUp()).toBe(false); + expect(list.mounts).toBe(1); + expect(summaryOf('amount')).toBe('sum'); + + server.holdViews = false; + act(() => server.releaseViews()); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + expect(list.mounts).toBe(1); + expect(summaryOf('amount')).toBe('sum'); + }); + + it('two successive picks: the second draft carries both', async () => { + boot(true); + await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 }); + + server.holdViews = true; + await pick('amount', 'sum'); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + await pick('closed_at', 'latest'); + server.holdViews = false; + act(() => server.releaseViews()); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + + expect(saves.map((s) => [s.type, s.name, s.options?.mode])).toEqual([ + ['view', VIEW, 'draft'], + ['view', VIEW, 'draft'], + ]); + expect(storedSummaries(saves[0].body)).toEqual({ amount: 'sum' }); + expect(storedSummaries(saves[1].body)).toEqual({ amount: 'sum', closed_at: 'latest' }); + expect(list.mounts).toBe(1); + expect(summaryOf('amount')).toBe('sum'); + expect(summaryOf('closed_at')).toBe('latest'); + }); + + it('a reader is served the published view and draws it, without the admin\'s draft', async () => { + boot(true); + await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 }); + await pick('amount', 'sum'); + expect(saves.map((s) => s.options?.mode)).toEqual(['draft']); + cleanup(); + + forgetList(); + boot(false); + await waitFor(() => expect(list.props?.schema?.columns).toBeDefined(), { timeout: 5000 }); + expect(summaryOf('amount')).toBeUndefined(); + // Offered to an admin only. + expect(list.props?.onColumnSummaryPick).toBeUndefined(); + }); + + it('CONTROL: a whole-type invalidation of `view` still sends the route back to waiting', async () => { + boot(true); + await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 }); + server.holdViews = true; + act(() => metadata.current!.invalidate('view')); + await waitFor(() => expect(skeletonUp()).toBe(true)); + server.holdViews = false; + act(() => server.releaseViews()); + await waitFor(() => expect(skeletonUp()).toBe(false)); + }); +}); + +describe('objectstack#35932 — the same, on an app with a bundle', () => { + /** Let the pulse run: the save's refresh, the bundle reload put on the wire. */ + const settle = () => + act(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + + it('an admin\'s footer pick: the bundle reloading keeps the list, one mount, the pick drawn', async () => { + boot(true, { bundle: true }); + await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 }); + expect(list.mounts).toBe(1); + const loadsBefore = appBundle.loads; + + appBundle.hold = true; + await pick('amount', 'sum'); + await settle(); + // The pulse dropped the bundle and its reload is on the wire. + expect(appBundle.items).toBeNull(); + expect(appBundle.loads).toBe(loadsBefore + 1); + expect(skeletonUp()).toBe(false); + expect(list.mounts).toBe(1); + expect(summaryOf('amount')).toBe('sum'); + + appBundle.hold = false; + act(() => releaseBundle()); + await settle(); + expect(skeletonUp()).toBe(false); + expect(list.mounts).toBe(1); + expect(summaryOf('amount')).toBe('sum'); + }); + + it('two successive picks, then Publish: both picks in the second draft, one mount throughout', async () => { + boot(true, { bundle: true }); + await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 }); + + appBundle.hold = true; + await pick('amount', 'sum'); + await settle(); + await pick('closed_at', 'latest'); + await settle(); + expect(skeletonUp()).toBe(false); + expect(storedSummaries(saves[0].body)).toEqual({ amount: 'sum' }); + expect(storedSummaries(saves[1].body)).toEqual({ amount: 'sum', closed_at: 'latest' }); + + appBundle.hold = false; + act(() => releaseBundle()); + await settle(); + + // Publish, through the seam the draft bar calls: its pulse drops the bundle again. + appBundle.hold = true; + await act(async () => { + await publishRuntimeMetadata('view', VIEW, { metadataClient: client as any, dataSource: dataSourceStub as any, objectName: OBJECT }); + }); + await settle(); + expect(appBundle.items).toBeNull(); + expect(skeletonUp()).toBe(false); + expect(list.mounts).toBe(1); + + appBundle.hold = false; + act(() => releaseBundle()); + await settle(); + expect(skeletonUp()).toBe(false); + expect(list.mounts).toBe(1); + }); + + it('CONTROL: a first entry on the wire (no bundle has answered) still waits, the list not drawn', async () => { + boot(true, { bundle: true, holdFirstLoad: true }); + await waitFor(() => expect(appBundle.waiting.length).toBeGreaterThan(0), { timeout: 5000 }); + await settle(); + expect(list.mounts).toBe(0); + appBundle.hold = false; + act(() => releaseBundle()); + await waitFor(() => expect(list.mounts).toBe(1), { timeout: 5000 }); + }); + + it('CONTROL: a whole-type invalidation of `object` on the bundle route still shows the skeleton', async () => { + boot(true, { bundle: true }); + await waitFor(() => expect(typeof list.props?.onColumnSummaryPick).toBe('function'), { timeout: 5000 }); + act(() => { + metadata.current!.invalidate('object'); + }); + await waitFor(() => expect(skeletonUp()).toBe(true)); + await waitFor(() => expect(skeletonUp()).toBe(false)); + }); +}); diff --git a/ui/packages/app-shell/src/providers/MetadataProvider.tsx b/ui/packages/app-shell/src/providers/MetadataProvider.tsx index 5e64e9b6840..00739af7ccc 100644 --- a/ui/packages/app-shell/src/providers/MetadataProvider.tsx +++ b/ui/packages/app-shell/src/providers/MetadataProvider.tsx @@ -61,6 +61,22 @@ interface TypeCacheEntry { error: Error | null; fetchedAt: number; promise: Promise | null; + /** + * An answer (a list or a failure) has landed and is still held: set when a + * fetch settles, cleared only when the entry drops its items (`invalidate`). + * A refetch in place (`refresh()`, a lapsed TTL) keeps it, so a reader that + * already drew the old answer is not sent back to waiting while the new one + * is on the wire (objectstack#35932). + */ + answered: boolean; +} + +/** + * Whether a type's answer is in hand: ready, failed, or refetching in place + * over an answer it still holds (`TypeCacheEntry.answered`). + */ +function typeAnswered(entry: TypeCacheEntry): boolean { + return entry.status === 'ready' || entry.status === 'error' || (entry.status === 'loading' && entry.answered); } /** @@ -954,6 +970,7 @@ function emptyEntry(): TypeCacheEntry { error: null, fetchedAt: 0, promise: null, + answered: false, }; } @@ -1079,8 +1096,17 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: */ const dropAdapterWorld = useCallback((): void => { adapterObjectNamesRef.current.clear(); + answeredBundleRef.current = null; try { adapterRef.current?.clearCache?.(); } catch { /* adapter mid-swap */ } }, []); + /** + * objectstack#35932 — the items of the last app bundle that answered in this + * world. A refresh pulse drops the adapter's bundle, which then answers + * `pending` until its reload lands; the scope's views keep answering from + * these meanwhile (`viewsForObjects`), as a `/meta/view` list refetching in + * place does. A world switch forgets them (`dropAdapterWorld`). + */ + const answeredBundleRef = useRef(null); const [version, setVersion] = useState(0); // Defer state bumps so they never occur synchronously during a consumer's @@ -1128,6 +1154,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: watchedBundleLoadsRef.current.add(peek.settled); void peek.settled.then(bump, bump); } + if (peek.status === 'ready') answeredBundleRef.current = peek.items; return peek; }, [bump]); useEffect(() => { @@ -1287,6 +1314,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: if (type === 'object') ingestObjectList(items, res); entry.items = items; entry.status = 'ready'; + entry.answered = true; entry.error = null; entry.fetchedAt = Date.now(); entry.promise = null; @@ -1320,6 +1348,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: .catch((err: unknown) => { const error = err instanceof Error ? err : new Error(String(err)); entry.status = 'error'; + entry.answered = true; entry.error = error; entry.promise = null; // Stamped on failure too, so ERROR_RETRY_COOLDOWN_MS has a clock to @@ -1669,6 +1698,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: dropAdapterObjectReads(); } entry.status = 'idle'; + entry.answered = false; entry.items = []; entry.byName.clear(); entry.error = null; @@ -1840,6 +1870,7 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: const entry = getEntry('app'); entry.items = cached; entry.status = 'ready'; + entry.answered = true; entry.fetchedAt = 0; for (const it of cached) { if (isNamedItem(it)) { @@ -1893,32 +1924,46 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: * list already in hand, and asks for none: a reader of its views names it. * - The bundle still loading, or the app about to be entered in this * commit: a list already in hand answers, so a scope never unsettles - * because an app was entered after it; otherwise the scope waits. + * because an app was entered after it; so does the bundle that last + * answered, when it holds every asked name (a reload after a refresh + * pulse, objectstack#35932); otherwise the scope waits. * - No bundle (no app entered, or a host without one): the list, as before. */ const viewsForObjects = useCallback( (asked: readonly string[]): { views: unknown[]; settled: boolean } => { const listed = getEntry('view'); const peek = peekBundle(); - if (peek?.status === 'ready') { - const bundledObjects = peek.items.get('object'); - const fromBundle = (bundledViews(peek.items) as { value: unknown[] }).value; + // objectstack#35932 — a bundle reloading after a refresh pulse still + // answers with the items it last answered (`answeredBundleRef`), so the + // pulse never sends a drawn route back to its skeleton (which remounts it). + // Only when those items hold every asked object: one outside them waits + // for the reload, as before, rather than asking the `/meta/view` list. + const answered = peek?.status === 'pending' ? answeredBundleRef.current : null; + const items = peek?.status === 'ready' + ? peek.items + : answered && asked.every((name) => answered.get('object')?.has(name)) ? answered : null; + if (items) { + const bundledObjects = items.get('object'); + const fromBundle = (bundledViews(items) as { value: unknown[] }).value; const outside = asked.some((name) => !bundledObjects?.has(name)); if (!outside) { - const views = listed.status === 'ready' ? bundledWithListed(fromBundle, bundledObjects, listed.items) : fromBundle; + const views = listed.status === 'ready' || (listed.status === 'loading' && listed.answered) + ? bundledWithListed(fromBundle, bundledObjects, listed.items) + : fromBundle; return { views, settled: true }; } const list = readType('view'); - const status = getEntry('view').status; - return { views: bundledWithListed(fromBundle, bundledObjects, list), settled: status === 'ready' || status === 'error' }; + return { views: bundledWithListed(fromBundle, bundledObjects, list), settled: typeAnswered(getEntry('view')) }; } - if (listed.status === 'ready') return { views: listed.items, settled: true }; + // objectstack#35932 — a list refetching in place still answers: the + // scope stays settled on the views it holds, so a refresh pulse never + // sends a drawn route back to its skeleton (which remounts it). + if (listed.status === 'ready' || (listed.status === 'loading' && listed.answered)) return { views: listed.items, settled: true }; // `none` here is an app not entered YET: `peekBundle` answers null once // the commit has settled without one. if (peek) return { views: NO_VIEWS, settled: false }; const views = readType('view'); - const status = getEntry('view').status; - return { views, settled: status === 'ready' || status === 'error' }; + return { views, settled: typeAnswered(getEntry('view')) }; }, [getEntry, peekBundle, readType], ); @@ -1943,14 +1988,13 @@ export function MetadataProvider({ children, adapter, ttlMs = DEFAULT_TTL_MS }: ? NAMES_BATCH_SCOPE : scope.packageId || (namesOnly ? NAMES_ONLY_SCOPE : undefined); if (packageId === undefined) { - const status = getEntry('object').status; const served = readType('object'); const views = readType('view'); return { objects: composeObjects(served, views) as any[], served, missing: NO_NAMES, - settled: (status === 'ready' || status === 'error') && getEntry('view').status !== 'loading', + settled: typeAnswered(getEntry('object')) && (getEntry('view').status !== 'loading' || getEntry('view').answered), views, }; } diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 18e53fbec4e..d5e44eb86c3 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -798,6 +798,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co // switcher it also registered retired with objectstack#27058). const { handleViewConfigSave, + handleDraftBarChange, handleViewCreate, handleViewUpdate, handleViewChange, @@ -1445,7 +1446,7 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co onCreate={handleViewCreate} metadataClient={metadataClient} dataSource={dataSource} - onAfterChange={() => setRefreshKey(k => k + 1)} + onAfterChange={handleDraftBarChange} /> diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.draftBarChange-35932.test.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.draftBarChange-35932.test.tsx new file mode 100644 index 00000000000..640dcfc1f67 --- /dev/null +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.draftBarChange-35932.test.tsx @@ -0,0 +1,86 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#35932 — the draft bar's Publish or Discard drops the list's + * local copy of the draft once the saved views have been read again. + * + * A draft save keeps the list mounted, so the copy a save put on screen + * (`viewDraft`) is no longer dropped by a remount. After Publish or Discard the + * stored view is what the list must show: the handler bumps the refresh + * counter (the saved views are read again) and drops the copy in the commit + * that installs that read, never before it, so the list does not fall back to + * the read from before the publish. + */ + +import * as React from 'react'; +import { describe, it, expect, vi } from 'vitest'; +import { act, renderHook } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +vi.mock('../providers/MetadataProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadata: () => ({ apps: [] }), +})); + +// The module reaches a dynamic `import('@objectstack/lint')`: pay its load at +// collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; +import { useObjectViewViewCrud } from './objectViewViewCrud'; + +type Args = Parameters[0]; + +function mount() { + const setViewDraft = vi.fn(); + const setRefreshKey = vi.fn(); + const base = { + dataSource: {} as Args['dataSource'], + objects: [], + navigate: vi.fn() as unknown as Args['navigate'], + objectName: 'crm_account', + viewId: 'crm_account.team', + t: ((key: string) => key) as unknown as Args['t'], + metadataClient: {} as Args['metadataClient'], + previewDrafts: false as Args['previewDrafts'], + setShowViewConfigPanel: vi.fn(), + setViewConfigPanelMode: vi.fn(), + setShowCreateViewDialog: vi.fn(), + setViewDraft, + setRefreshKey, + confirmHandler: vi.fn() as unknown as Args['confirmHandler'], + listPrefs: { setViewOrder: vi.fn() } as unknown as Args['listPrefs'], + views: [], + activeViewId: 'crm_account.team', + baseView: { id: 'crm_account.team' } as Args['baseView'], + }; + const hook = renderHook( + ({ savedViews }: { savedViews: Args['savedViews'] }) => useObjectViewViewCrud({ ...base, savedViews }), + { + initialProps: { savedViews: [{ name: 'crm_account.team' }] as Args['savedViews'] }, + wrapper: ({ children }) => {children}, + }, + ); + return { hook, setViewDraft, setRefreshKey }; +} + +describe('objectstack#35932 — Publish or Discard drops the local draft once the views are read again', () => { + it('reads the views again, and drops the copy when that read lands', () => { + const { hook, setViewDraft, setRefreshKey } = mount(); + act(() => hook.result.current.handleDraftBarChange()); + expect(setRefreshKey).toHaveBeenCalledTimes(1); + expect(setViewDraft).not.toHaveBeenCalled(); + + hook.rerender({ savedViews: [{ name: 'crm_account.team', columns: ['name'] }] as Args['savedViews'] }); + expect(setViewDraft).toHaveBeenCalledTimes(1); + expect(setViewDraft).toHaveBeenCalledWith(null); + + // Only that read: a later one leaves a later draft alone. + hook.rerender({ savedViews: [{ name: 'crm_account.team' }] as Args['savedViews'] }); + expect(setViewDraft).toHaveBeenCalledTimes(1); + }); + + it('CONTROL: a saved-views read with no Publish or Discard before it keeps the copy', () => { + const { hook, setViewDraft } = mount(); + hook.rerender({ savedViews: [{ name: 'crm_account.team', columns: ['name'] }] as Args['savedViews'] }); + expect(setViewDraft).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index 49ec1d752e8..bac5e656520 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -8,7 +8,7 @@ * component reads the returned handlers. */ -import { useCallback, useMemo, type Dispatch, type SetStateAction } from 'react'; +import { useCallback, useEffect, useMemo, useRef, type Dispatch, type SetStateAction } from 'react'; import { useParams, type useNavigate } from 'react-router-dom'; import { formatMetadataError } from '@object-ui/data-objectstack'; import { toast } from 'sonner'; @@ -169,6 +169,25 @@ export function useObjectViewViewCrud({ } }, [metadataClient, dataSource, objectName, t]); + /** + * objectstack#35932 — the draft bar's Publish or Discard changed what is + * stored. The saved views are read again, and the local copy of the draft + * (`viewDraft`, what a save put on screen) goes once that read has landed, + * so the list shows what is now stored without first falling back to the + * read from before. The list stays mounted across a draft save, so this + * copy is not dropped by anything else. + */ + const dropViewDraftOnRead = useRef(false); + const handleDraftBarChange = useCallback(() => { + dropViewDraftOnRead.current = true; + setRefreshKey(k => k + 1); + }, [setRefreshKey]); + useEffect(() => { + if (!dropViewDraftOnRead.current) return; + dropViewDraftOnRead.current = false; + setViewDraft(null); + }, [savedViews, setViewDraft]); + /** * Create a new view: the Create View dialog's door and the view-config * panel's create mode. Resolves whether the view was saved, so the dialog @@ -446,6 +465,7 @@ export function useObjectViewViewCrud({ return { handleViewConfigSave, + handleDraftBarChange, handleViewCreate, handleViewUpdate, handleViewChange,