Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/33826-deleted-record-leaves-recents.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/app-shell': patch
---

fix(app-shell): a deleted record leaves the recently-accessed list that the command palette and Home show

Clause-②: no
Metadata-protocol: none

Deleting a record left its entry in the recents, so the ⌘K palette's "Recent" group and Home's "recently accessed" still offered it, and opening it landed on a record that no longer exists. The connected shell now listens to the data source's delete events once and drops the deleted record's entry from the list, from localStorage and from the saved `ui.recent` preference. One listener covers every delete that reports its record: the record page's header, a list row, an action. Undoing the delete brings the record back, and the visit that follows lists it again. A bulk delete reports only its object, not its records, so it drops nothing.
14 changes: 13 additions & 1 deletion ui/packages/app-shell/src/console/ConsoleShell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import { AiUnavailable } from './ai/AiUnavailable.js';
import { PreviewModeProvider } from '../preview/PreviewModeContext.js';
import { NavigationProvider } from '../context/NavigationContext.js';
import { FavoritesProvider } from '../context/FavoritesProvider.js';
import { RecentItemsProvider } from '../context/RecentItemsProvider.js';
import { RecentItemsProvider, useDropDeletedRecordsFromRecents } from '../context/RecentItemsProvider.js';
import { FlowPaletteRecentsProvider } from '../context/FlowPaletteRecentsProvider.js';
import {
UserStateAdaptersProvider,
Expand Down Expand Up @@ -339,6 +339,7 @@ function ConnectedShellInner({ children }: { children: ReactNode }) {
switch of language reads again. */}
<ConsoleElementApiOpen>
<UserStateBridge />
<DeletedRecordsLeaveRecents />
<GlobalActionRuntimeProvider dataSource={adapter}>
{children}
</GlobalActionRuntimeProvider>
Expand Down Expand Up @@ -436,6 +437,17 @@ function UserStateBridge() {
return null;
}

/**
* DeletedRecordsLeaveRecents — a record this session deletes leaves the
* recently-accessed list at once, whichever page deleted it, so the command
* palette and Home never offer a record that is gone. The one subscriber, to
* the connected adapter's mutation events. Renders nothing.
*/
function DeletedRecordsLeaveRecents() {
useDropDeletedRecordsFromRecents(useAdapter());
return null;
}

/**
* RequireOrganization — redirects to /organizations when the multi-tenant
* feature is enabled (user has orgs but no active one). Single-tenant
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/**
* objectstack#33826 — a record deleted in the console leaves the
* recently-accessed list that the command palette and Home read.
*
* The one subscriber that drops it, `useDropDeletedRecordsFromRecents`, is
* mounted once, in `ConnectedShellInner`, on the connected adapter's mutation
* events. This pins that mount: the console's provider stack holds the
* recents above the shell (`ConsoleShell` wraps every `ConnectedShell`), the
* adapter reports a delete the way `ObjectStackAdapter.delete` does, and the
* probe stands where the palette and Home read the list.
*
* What is real: `ConnectedShell` and everything it mounts, the recents
* provider and its storage. The adapter is a fake that serves the shell's
* metadata reads and reports mutations; the session is resolved, signed out,
* so no preference row is attached.
*/

import '@testing-library/jest-dom/vitest';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { act, cleanup, render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import type { DataSourceMutationEvent } from '@object-ui/types';

const listeners = vi.hoisted(() => new Set<(e: { type: string; resource: string; id?: string }) => void>());

const fakeAdapter = vi.hoisted(() => ({
clearCache: () => {},
getObjectSchema: async () => null,
getClient: () => ({
meta: {
getItems: (type: string) => Promise.resolve({ type, items: [] }),
getItem: () => Promise.resolve({ item: null }),
},
}),
onMutation: (cb: (e: { type: string; resource: string; id?: string }) => void) => {
listeners.add(cb);
return () => {
listeners.delete(cb);
};
},
}));

vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => ({
user: null,
session: null,
isAuthenticated: false,
isLoading: false,
isAuthEnabled: true,
error: null,
}),
createAuthenticatedFetch: () => globalThis.fetch,
}));

// The adapter is not under test: the shell hands the fake to every
// `useAdapter()` reader.
vi.mock('../../providers/AdapterProvider', () => ({
AdapterProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
useAdapter: () => fakeAdapter,
}));

import { ConnectedShell } from '../ConsoleShell';
import { RecentItemsProvider, useRecentItems, type RecentItem } from '../../context/RecentItemsProvider';
import { UserStateAdaptersProvider } from '../../context/UserStateAdapters';

const KEY = 'objectui-recent-items';

/** Stands where the palette and Home read the list. */
function RecentsProbe() {
const { recentItems } = useRecentItems();
return <ul data-testid="recents">{recentItems.map((r) => <li key={r.id}>{r.id}</li>)}</ul>;
}

function emit(e: DataSourceMutationEvent) {
listeners.forEach((cb) => cb(e as never));
}

const seeded: RecentItem[] = [
{ id: 'record:crm_account:a1', type: 'record', label: 'Browser Test Co', href: '/apps/crm/crm_account/record/a1', visitedAt: '2026-11-15T00:00:02Z' },
{ id: 'record:crm_account:b2', type: 'record', label: 'Globex', href: '/apps/crm/crm_account/record/b2', visitedAt: '2026-11-15T00:00:01Z' },
];

function renderConsole() {
return render(
<UserStateAdaptersProvider>
<RecentItemsProvider>
<MemoryRouter>
<ConnectedShell>
<RecentsProbe />
</ConnectedShell>
</MemoryRouter>
</RecentItemsProvider>
</UserStateAdaptersProvider>,
);
}

function listed(): string[] {
return Array.from(screen.getByTestId('recents').querySelectorAll('li')).map((li) => li.textContent ?? '');
}

describe('ConnectedShell — a deleted record leaves the recents (objectstack#33826)', () => {
beforeEach(() => {
localStorage.clear();
localStorage.setItem(KEY, JSON.stringify(seeded));
});
afterEach(() => {
cleanup();
listeners.clear();
});

it('the delete the adapter reports drops that record, and only that one', async () => {
renderConsole();
await screen.findByTestId('recents');
expect(listed()).toEqual(['record:crm_account:a1', 'record:crm_account:b2']);

act(() => emit({ type: 'delete', resource: 'crm_account', id: 'a1' }));

expect(listed()).toEqual(['record:crm_account:b2']);
expect(JSON.parse(localStorage.getItem(KEY)!).map((r: RecentItem) => r.id)).toEqual(['record:crm_account:b2']);
});

it('control: with the shell unmounted, nothing listens', async () => {
const view = renderConsole();
await screen.findByTestId('recents');
expect(listeners.size).toBeGreaterThan(0);
view.unmount();
expect(listeners.size).toBe(0);
});
});
36 changes: 36 additions & 0 deletions ui/packages/app-shell/src/context/RecentItemsProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
type ReactNode,
} from 'react';
import { useAuth } from '@object-ui/auth';
import type { DataSource } from '@object-ui/types';
import {
createDebouncedFlush,
scopedKey,
Expand Down Expand Up @@ -380,3 +381,38 @@ export function useRecentItems(): RecentItemsContextValue {
}
return ctx;
}

/**
* The id a record's recent entry is kept under — the one the record page
* writes: `record:OBJECT:RECORD_ID`, by the object's machine name.
*/
function recordRecentItemId(objectName: string, recordId: string): string {
return `record:${objectName}:${recordId}`;
}

/** The part of a data source this module reads: its mutation events. */
type MutationSource = Pick<DataSource, 'onMutation'>;

/**
* Drops a record from the recents the moment `dataSource` reports it deleted,
* so neither the command palette nor Home's "recently accessed" offers a
* record that is gone. One subscription, to the data source's mutation bus,
* covers every delete door that reports its record — the record page's
* header, a list row, an action — with no call at each of them.
*
* Undoing the delete restores the record; the visit that follows records it
* again, the way any visit does. A delete event that names no record (a bulk
* delete reports only its object) drops nothing: nothing in it says which.
*
* Mount it once, under the data source and inside a {@link RecentItemsProvider}.
*/
export function useDropDeletedRecordsFromRecents(dataSource: MutationSource | null | undefined): void {
const { removeRecentItem } = useRecentItems();
useEffect(() => {
if (typeof dataSource?.onMutation !== 'function') return;
return dataSource.onMutation(event => {
if (event.type !== 'delete' || event.id == null || !event.resource) return;
removeRecentItem(recordRecentItemId(event.resource, event.id));
});
}, [dataSource, removeRecentItem]);
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({

import {
RecentItemsProvider,
useDropDeletedRecordsFromRecents,
useRecentItems,
type RecentItem,
} from '../RecentItemsProvider';
import type { DataSourceMutationEvent } from '@object-ui/types';
import { recentViewId } from '../../hooks/useTrackRouteAsRecent';
import {
UserStateAdaptersProvider,
Expand Down Expand Up @@ -485,3 +487,108 @@ describe('RecentItemsProvider — one entry per target (objectui#12604)', () =>
expect(result.current.recentItems.map((r) => r.id)).toEqual(['view:z']);
});
});

/**
* objectstack#33826 — a deleted record leaves the recents. The data source's
* mutation bus reports the delete; one subscriber drops the record's entry, so
* neither the command palette nor Home offers a record that is gone.
*/
describe('RecentItemsProvider — a deleted record leaves the recents (objectstack#33826)', () => {
const KEY = 'objectui-recent-items:u:user-1';

beforeEach(() => {
localStorage.clear();
mockUser.current = { id: 'user-1', name: 'Alice', email: 'a@x' };
});

/** A data source that only reports mutations, and the means to report one. */
function makeMutationSource() {
const listeners = new Set<(e: DataSourceMutationEvent) => void>();
return {
onMutation: (cb: (e: DataSourceMutationEvent) => void) => {
listeners.add(cb);
return () => {
listeners.delete(cb);
};
},
emit: (e: DataSourceMutationEvent) => listeners.forEach((cb) => cb(e)),
};
}

const record = (object: string, id: string, label: string) =>
({ id: `record:${object}:${id}`, type: 'record', label, href: `/apps/crm/${object}/record/${id}` }) as const;

async function mount() {
const source = makeMutationSource();
const adapter = makeAdapter([]);
const view = renderHook(
() => {
useDropDeletedRecordsFromRecents(source);
return useHarness();
},
{ wrapper },
);
act(() => view.result.current.attach('recent', adapter));
await waitFor(() => expect(adapter.loadMock).toHaveBeenCalled());
await act(async () => {
await Promise.resolve();
});
act(() => view.result.current.recent.addRecentItem({ id: 'object:crm_account', type: 'object', name: 'crm_account', href: '/apps/crm/crm_account' }));
act(() => view.result.current.recent.addRecentItem(record('crm_account', 'a1', 'Browser Test Co')));
act(() => view.result.current.recent.addRecentItem(record('crm_account', 'b2', 'Globex')));
// The visits' own debounced save lands first, so the counts below start at zero.
await waitFor(() => expect(adapter.saveMock).toHaveBeenCalled(), { timeout: 1500 });
adapter.saveMock.mockClear();
return { ...view, source, adapter };
}

const ids = (items: RecentItem[]) => items.map((r) => r.id);

it('the deleted record is gone from the list, localStorage and the saved row', async () => {
const { result, source, adapter } = await mount();
act(() => source.emit({ type: 'delete', resource: 'crm_account', id: 'a1' }));

expect(ids(result.current.recent.recentItems)).toEqual(['record:crm_account:b2', 'object:crm_account']);
expect(ids(JSON.parse(localStorage.getItem(KEY)!))).toEqual(['record:crm_account:b2', 'object:crm_account']);
await waitFor(() => expect(adapter.saveMock).toHaveBeenCalledTimes(1), { timeout: 1500 });
expect(ids(adapter.saveMock.mock.calls[0][0])).toEqual(['record:crm_account:b2', 'object:crm_account']);
});

it('control: deleting another record leaves this one listed, and writes nothing', async () => {
const { result, source, adapter } = await mount();
const before = ids(result.current.recent.recentItems);
act(() => source.emit({ type: 'delete', resource: 'crm_account', id: 'zz9' }));
act(() => source.emit({ type: 'delete', resource: 'crm_contact', id: 'a1' }));

expect(ids(result.current.recent.recentItems)).toEqual(before);
await new Promise((r) => setTimeout(r, 700));
expect(adapter.saveMock).not.toHaveBeenCalled();
});

it('control: an update of the record, or a delete that names no record (a bulk delete), drops nothing', async () => {
const { result, source } = await mount();
const before = ids(result.current.recent.recentItems);
act(() => source.emit({ type: 'update', resource: 'crm_account', id: 'a1' }));
act(() => source.emit({ type: 'delete', resource: 'crm_account' }));

expect(ids(result.current.recent.recentItems)).toEqual(before);
});

it('after an undo, the visit to the restored record lists it again', async () => {
const { result, source } = await mount();
act(() => source.emit({ type: 'delete', resource: 'crm_account', id: 'a1' }));
expect(ids(result.current.recent.recentItems)).not.toContain('record:crm_account:a1');

// The record page's Undo restores the record and returns to it; that visit records it.
act(() => result.current.recent.addRecentItem(record('crm_account', 'a1', 'Browser Test Co')));
expect(ids(result.current.recent.recentItems)[0]).toBe('record:crm_account:a1');
});

it('unsubscribes when unmounted', async () => {
const { result, source, unmount } = await mount();
const before = ids(result.current.recent.recentItems);
unmount();
act(() => source.emit({ type: 'delete', resource: 'crm_account', id: 'a1' }));
expect(ids(JSON.parse(localStorage.getItem(KEY)!))).toEqual(before);
});
});
Loading