Skip to content

Commit c1c86a3

Browse files
fix(app-shell): a deleted record leaves the recently-accessed list (#34108)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi97evQ69Yx3njz2MqoYASHxL)_ Fixes #33826 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:删除记录成功后,该记录立刻从「最近访问」里移除(⌘K 命令面板、环境首页、本地缓存与服务端 `ui.recent` 偏好同步)。 - 为什么改:删掉的记录还挂在最近访问第一条,点进去落到一条不存在的记录,最近访问越用越不可信。 - 风险与回滚:只加了一个订阅数据源删除事件的监听,只删 `record:对象:ID` 这一条;回滚即 revert 本 PR,无数据迁移。 - 先看:`ui/packages/app-shell/src/context/RecentItemsProvider.tsx`(`useDropDeletedRecordsFromRecents`)→ `ui/packages/app-shell/src/console/ConsoleShell.tsx`(唯一挂载点)。 - 两分钟验证:打开一条客户记录 → 更多 → 删除 → 确认,然后按 ⌘K:「最近访问」里不再有它;点 Toast 上的撤销回到该记录后再按 ⌘K,它重新出现在第一条。 - 需要你做的:无,席位落地。 ## What changes - `useDropDeletedRecordsFromRecents(dataSource)` (new, module-internal to `@object-ui/app-shell`, not exported from the package index): subscribes to the data source's `onMutation` and, on a `delete` event that names its record (`resource` + `id`), calls the provider's existing `removeRecentItem` with the record entry's id, `record:OBJECT:RECORD_ID` (the id the record page writes). `removeRecentItem` already writes the list, localStorage and the debounced `ui.recent` save, and writes nothing when the entry is absent. - `ConnectedShellInner` mounts it once (`DeletedRecordsLeaveRecents`, beside `UserStateBridge`), on the connected adapter. The console's `ConsoleShell` holds `RecentItemsProvider` above every `ConnectedShell`, so the palette (`CommandPalette`), Home and the sidebar read the trimmed list. One subscriber covers every delete door that reports its record (record header, list row, action) with no call at each door, and `RecordDetailView.tsx` is untouched. - Undo: the record page's Undo restores the record and navigates back to it; that visit records it again through the record page's existing `addRecentItem` effect. A restore emits no mutation event by design (`restoreRecycleBinEntry`: "a restore is never a create"), so nothing re-inserts the entry before the visit. - No public surface changes: the `useRecentItems()` value and the package exports are unchanged, so `Clause-②: no` holds. ## Tests - `ui/packages/app-shell/src/context/__tests__/RecentItemsProvider.test.tsx` gains one top-level `describe` (the shared harness file): the deleted record leaves the list, localStorage and the saved row; CONTROL another record's delete (same object, other object) leaves it listed and saves nothing; CONTROL an `update` event and an id-less `delete` (bulk) drop nothing; after an undo the revisit lists it again at the head; the listener unsubscribes on unmount. - `ui/packages/app-shell/src/console/__tests__/ConnectedShell.deletedRecordLeavesRecents-33826.test.tsx` (new): the real `ConnectedShell` under the real recents provider; a delete reported by the adapter drops that record only; the subscription goes away with the shell. - No forced test edits. <details><summary>Test runs (head a6cbed1)</summary> - `pnpm --dir ui exec vitest run packages/app-shell/src/context/__tests__/RecentItemsProvider.test.tsx packages/app-shell/src/console/__tests__/ConnectedShell.deletedRecordLeavesRecents-33826.test.tsx`: Test Files 2 passed (2), Tests 28 passed (28), lock VERDICT command-exit 0. - Ablation 1 (`scripts/ablation-replace.mjs`, mutation landed anchor 1 to 0, restored blob == HEAD): `DeletedRecordsLeaveRecents` mount deleted from `ConsoleShell.tsx` turns the shell pin red, Tests 2 failed (2). - Ablation 2: the `removeRecentItem(recordRecentItemId(...))` call in the hook replaced by a no-op turns 3 pins red (deleted record gone; undo revisit; shell drop), Tests 3 failed / 25 passed (28); restored, `git diff HEAD` empty. - No build between legs: ui vitest resolves `@object-ui/*` to `src/` through `ui/vitest.config.mts` aliases. </details> ## Acceptance notes - A bulk delete (`bulkDelete`, `bulk('delete')`) emits one resource-level `delete` with no `id`, so its records stay in the recents until opened. Closing it needs the mutation event to carry the deleted ids (`DataSourceMutationEvent` in `@object-ui/types`), a public-type widening outside this card's surface. carrier: seat (named in the report's open_questions). - A record deleted elsewhere (another session or user) is not reported to this tab's data source, so it stays listed until opened. The card's optional route ("opening a recent whose record answers 404 drops it") lives in the record page's load path (`RecordDetailView.tsx`), which this card's claim fenced off; not done here. carrier: seat. ## Verification <details><summary>Local gates (head a6cbed1)</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 37 commands, each run, all exit 0 (including `pnpm --dir ui exec vitest run scripts/` under the lock, `pnpm check:test-source-alias`, `pnpm check:cross-package-test-inputs`, `pnpm check:nul-bytes`, `pnpm check:published-files`). - `--ran` reconciliation: 37 derived, 37 run, 0 NOT-MEASURED, 0 UNRUN. - `pnpm --filter @object-ui/app-shell type-check` (after `turbo run build --filter='@object-ui/app-shell^...'`): both `tsc --noEmit` and `tsc -p tsconfig.test.json`, lock VERDICT command-exit 0. - `pnpm --dir ui run check:new-line-citations`: 0 new citations. - Every other family (lint, Test UI shards, Build and E2E UI, the required set): this PR's CI check-runs. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmTS7jKcrSq1mgNofuy)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8ce138a commit c1c86a3

5 files changed

Lines changed: 296 additions & 1 deletion

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
fix(app-shell): a deleted record leaves the recently-accessed list that the command palette and Home show
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.

‎ui/packages/app-shell/src/console/ConsoleShell.tsx‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ import { AiUnavailable } from './ai/AiUnavailable.js';
3636
import { PreviewModeProvider } from '../preview/PreviewModeContext.js';
3737
import { NavigationProvider } from '../context/NavigationContext.js';
3838
import { FavoritesProvider } from '../context/FavoritesProvider.js';
39-
import { RecentItemsProvider } from '../context/RecentItemsProvider.js';
39+
import { RecentItemsProvider, useDropDeletedRecordsFromRecents } from '../context/RecentItemsProvider.js';
4040
import { FlowPaletteRecentsProvider } from '../context/FlowPaletteRecentsProvider.js';
4141
import {
4242
UserStateAdaptersProvider,
@@ -339,6 +339,7 @@ function ConnectedShellInner({ children }: { children: ReactNode }) {
339339
switch of language reads again. */}
340340
<ConsoleElementApiOpen>
341341
<UserStateBridge />
342+
<DeletedRecordsLeaveRecents />
342343
<GlobalActionRuntimeProvider dataSource={adapter}>
343344
{children}
344345
</GlobalActionRuntimeProvider>
@@ -436,6 +437,17 @@ function UserStateBridge() {
436437
return null;
437438
}
438439

440+
/**
441+
* DeletedRecordsLeaveRecents — a record this session deletes leaves the
442+
* recently-accessed list at once, whichever page deleted it, so the command
443+
* palette and Home never offer a record that is gone. The one subscriber, to
444+
* the connected adapter's mutation events. Renders nothing.
445+
*/
446+
function DeletedRecordsLeaveRecents() {
447+
useDropDeletedRecordsFromRecents(useAdapter());
448+
return null;
449+
}
450+
439451
/**
440452
* RequireOrganization — redirects to /organizations when the multi-tenant
441453
* feature is enabled (user has orgs but no active one). Single-tenant
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
/**
2+
* objectstack#33826 — a record deleted in the console leaves the
3+
* recently-accessed list that the command palette and Home read.
4+
*
5+
* The one subscriber that drops it, `useDropDeletedRecordsFromRecents`, is
6+
* mounted once, in `ConnectedShellInner`, on the connected adapter's mutation
7+
* events. This pins that mount: the console's provider stack holds the
8+
* recents above the shell (`ConsoleShell` wraps every `ConnectedShell`), the
9+
* adapter reports a delete the way `ObjectStackAdapter.delete` does, and the
10+
* probe stands where the palette and Home read the list.
11+
*
12+
* What is real: `ConnectedShell` and everything it mounts, the recents
13+
* provider and its storage. The adapter is a fake that serves the shell's
14+
* metadata reads and reports mutations; the session is resolved, signed out,
15+
* so no preference row is attached.
16+
*/
17+
18+
import '@testing-library/jest-dom/vitest';
19+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
20+
import { act, cleanup, render, screen } from '@testing-library/react';
21+
import { MemoryRouter } from 'react-router-dom';
22+
import type { DataSourceMutationEvent } from '@object-ui/types';
23+
24+
const listeners = vi.hoisted(() => new Set<(e: { type: string; resource: string; id?: string }) => void>());
25+
26+
const fakeAdapter = vi.hoisted(() => ({
27+
clearCache: () => {},
28+
getObjectSchema: async () => null,
29+
getClient: () => ({
30+
meta: {
31+
getItems: (type: string) => Promise.resolve({ type, items: [] }),
32+
getItem: () => Promise.resolve({ item: null }),
33+
},
34+
}),
35+
onMutation: (cb: (e: { type: string; resource: string; id?: string }) => void) => {
36+
listeners.add(cb);
37+
return () => {
38+
listeners.delete(cb);
39+
};
40+
},
41+
}));
42+
43+
vi.mock('@object-ui/auth', async (importOriginal) => ({
44+
...(await importOriginal<Record<string, unknown>>()),
45+
useAuth: () => ({
46+
user: null,
47+
session: null,
48+
isAuthenticated: false,
49+
isLoading: false,
50+
isAuthEnabled: true,
51+
error: null,
52+
}),
53+
createAuthenticatedFetch: () => globalThis.fetch,
54+
}));
55+
56+
// The adapter is not under test: the shell hands the fake to every
57+
// `useAdapter()` reader.
58+
vi.mock('../../providers/AdapterProvider', () => ({
59+
AdapterProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
60+
useAdapter: () => fakeAdapter,
61+
}));
62+
63+
import { ConnectedShell } from '../ConsoleShell';
64+
import { RecentItemsProvider, useRecentItems, type RecentItem } from '../../context/RecentItemsProvider';
65+
import { UserStateAdaptersProvider } from '../../context/UserStateAdapters';
66+
67+
const KEY = 'objectui-recent-items';
68+
69+
/** Stands where the palette and Home read the list. */
70+
function RecentsProbe() {
71+
const { recentItems } = useRecentItems();
72+
return <ul data-testid="recents">{recentItems.map((r) => <li key={r.id}>{r.id}</li>)}</ul>;
73+
}
74+
75+
function emit(e: DataSourceMutationEvent) {
76+
listeners.forEach((cb) => cb(e as never));
77+
}
78+
79+
const seeded: RecentItem[] = [
80+
{ id: 'record:crm_account:a1', type: 'record', label: 'Browser Test Co', href: '/apps/crm/crm_account/record/a1', visitedAt: '2026-11-15T00:00:02Z' },
81+
{ id: 'record:crm_account:b2', type: 'record', label: 'Globex', href: '/apps/crm/crm_account/record/b2', visitedAt: '2026-11-15T00:00:01Z' },
82+
];
83+
84+
function renderConsole() {
85+
return render(
86+
<UserStateAdaptersProvider>
87+
<RecentItemsProvider>
88+
<MemoryRouter>
89+
<ConnectedShell>
90+
<RecentsProbe />
91+
</ConnectedShell>
92+
</MemoryRouter>
93+
</RecentItemsProvider>
94+
</UserStateAdaptersProvider>,
95+
);
96+
}
97+
98+
function listed(): string[] {
99+
return Array.from(screen.getByTestId('recents').querySelectorAll('li')).map((li) => li.textContent ?? '');
100+
}
101+
102+
describe('ConnectedShell — a deleted record leaves the recents (objectstack#33826)', () => {
103+
beforeEach(() => {
104+
localStorage.clear();
105+
localStorage.setItem(KEY, JSON.stringify(seeded));
106+
});
107+
afterEach(() => {
108+
cleanup();
109+
listeners.clear();
110+
});
111+
112+
it('the delete the adapter reports drops that record, and only that one', async () => {
113+
renderConsole();
114+
await screen.findByTestId('recents');
115+
expect(listed()).toEqual(['record:crm_account:a1', 'record:crm_account:b2']);
116+
117+
act(() => emit({ type: 'delete', resource: 'crm_account', id: 'a1' }));
118+
119+
expect(listed()).toEqual(['record:crm_account:b2']);
120+
expect(JSON.parse(localStorage.getItem(KEY)!).map((r: RecentItem) => r.id)).toEqual(['record:crm_account:b2']);
121+
});
122+
123+
it('control: with the shell unmounted, nothing listens', async () => {
124+
const view = renderConsole();
125+
await screen.findByTestId('recents');
126+
expect(listeners.size).toBeGreaterThan(0);
127+
view.unmount();
128+
expect(listeners.size).toBe(0);
129+
});
130+
});

‎ui/packages/app-shell/src/context/RecentItemsProvider.tsx‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
type ReactNode,
3939
} from 'react';
4040
import { useAuth } from '@object-ui/auth';
41+
import type { DataSource } from '@object-ui/types';
4142
import {
4243
createDebouncedFlush,
4344
scopedKey,
@@ -380,3 +381,38 @@ export function useRecentItems(): RecentItemsContextValue {
380381
}
381382
return ctx;
382383
}
384+
385+
/**
386+
* The id a record's recent entry is kept under — the one the record page
387+
* writes: `record:OBJECT:RECORD_ID`, by the object's machine name.
388+
*/
389+
function recordRecentItemId(objectName: string, recordId: string): string {
390+
return `record:${objectName}:${recordId}`;
391+
}
392+
393+
/** The part of a data source this module reads: its mutation events. */
394+
type MutationSource = Pick<DataSource, 'onMutation'>;
395+
396+
/**
397+
* Drops a record from the recents the moment `dataSource` reports it deleted,
398+
* so neither the command palette nor Home's "recently accessed" offers a
399+
* record that is gone. One subscription, to the data source's mutation bus,
400+
* covers every delete door that reports its record — the record page's
401+
* header, a list row, an action — with no call at each of them.
402+
*
403+
* Undoing the delete restores the record; the visit that follows records it
404+
* again, the way any visit does. A delete event that names no record (a bulk
405+
* delete reports only its object) drops nothing: nothing in it says which.
406+
*
407+
* Mount it once, under the data source and inside a {@link RecentItemsProvider}.
408+
*/
409+
export function useDropDeletedRecordsFromRecents(dataSource: MutationSource | null | undefined): void {
410+
const { removeRecentItem } = useRecentItems();
411+
useEffect(() => {
412+
if (typeof dataSource?.onMutation !== 'function') return;
413+
return dataSource.onMutation(event => {
414+
if (event.type !== 'delete' || event.id == null || !event.resource) return;
415+
removeRecentItem(recordRecentItemId(event.resource, event.id));
416+
});
417+
}, [dataSource, removeRecentItem]);
418+
}

‎ui/packages/app-shell/src/context/__tests__/RecentItemsProvider.test.tsx‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@ vi.mock('@object-ui/auth', async (importOriginal) => ({
1818

1919
import {
2020
RecentItemsProvider,
21+
useDropDeletedRecordsFromRecents,
2122
useRecentItems,
2223
type RecentItem,
2324
} from '../RecentItemsProvider';
25+
import type { DataSourceMutationEvent } from '@object-ui/types';
2426
import { recentViewId } from '../../hooks/useTrackRouteAsRecent';
2527
import {
2628
UserStateAdaptersProvider,
@@ -485,3 +487,108 @@ describe('RecentItemsProvider — one entry per target (objectui#12604)', () =>
485487
expect(result.current.recentItems.map((r) => r.id)).toEqual(['view:z']);
486488
});
487489
});
490+
491+
/**
492+
* objectstack#33826 — a deleted record leaves the recents. The data source's
493+
* mutation bus reports the delete; one subscriber drops the record's entry, so
494+
* neither the command palette nor Home offers a record that is gone.
495+
*/
496+
describe('RecentItemsProvider — a deleted record leaves the recents (objectstack#33826)', () => {
497+
const KEY = 'objectui-recent-items:u:user-1';
498+
499+
beforeEach(() => {
500+
localStorage.clear();
501+
mockUser.current = { id: 'user-1', name: 'Alice', email: 'a@x' };
502+
});
503+
504+
/** A data source that only reports mutations, and the means to report one. */
505+
function makeMutationSource() {
506+
const listeners = new Set<(e: DataSourceMutationEvent) => void>();
507+
return {
508+
onMutation: (cb: (e: DataSourceMutationEvent) => void) => {
509+
listeners.add(cb);
510+
return () => {
511+
listeners.delete(cb);
512+
};
513+
},
514+
emit: (e: DataSourceMutationEvent) => listeners.forEach((cb) => cb(e)),
515+
};
516+
}
517+
518+
const record = (object: string, id: string, label: string) =>
519+
({ id: `record:${object}:${id}`, type: 'record', label, href: `/apps/crm/${object}/record/${id}` }) as const;
520+
521+
async function mount() {
522+
const source = makeMutationSource();
523+
const adapter = makeAdapter([]);
524+
const view = renderHook(
525+
() => {
526+
useDropDeletedRecordsFromRecents(source);
527+
return useHarness();
528+
},
529+
{ wrapper },
530+
);
531+
act(() => view.result.current.attach('recent', adapter));
532+
await waitFor(() => expect(adapter.loadMock).toHaveBeenCalled());
533+
await act(async () => {
534+
await Promise.resolve();
535+
});
536+
act(() => view.result.current.recent.addRecentItem({ id: 'object:crm_account', type: 'object', name: 'crm_account', href: '/apps/crm/crm_account' }));
537+
act(() => view.result.current.recent.addRecentItem(record('crm_account', 'a1', 'Browser Test Co')));
538+
act(() => view.result.current.recent.addRecentItem(record('crm_account', 'b2', 'Globex')));
539+
// The visits' own debounced save lands first, so the counts below start at zero.
540+
await waitFor(() => expect(adapter.saveMock).toHaveBeenCalled(), { timeout: 1500 });
541+
adapter.saveMock.mockClear();
542+
return { ...view, source, adapter };
543+
}
544+
545+
const ids = (items: RecentItem[]) => items.map((r) => r.id);
546+
547+
it('the deleted record is gone from the list, localStorage and the saved row', async () => {
548+
const { result, source, adapter } = await mount();
549+
act(() => source.emit({ type: 'delete', resource: 'crm_account', id: 'a1' }));
550+
551+
expect(ids(result.current.recent.recentItems)).toEqual(['record:crm_account:b2', 'object:crm_account']);
552+
expect(ids(JSON.parse(localStorage.getItem(KEY)!))).toEqual(['record:crm_account:b2', 'object:crm_account']);
553+
await waitFor(() => expect(adapter.saveMock).toHaveBeenCalledTimes(1), { timeout: 1500 });
554+
expect(ids(adapter.saveMock.mock.calls[0][0])).toEqual(['record:crm_account:b2', 'object:crm_account']);
555+
});
556+
557+
it('control: deleting another record leaves this one listed, and writes nothing', async () => {
558+
const { result, source, adapter } = await mount();
559+
const before = ids(result.current.recent.recentItems);
560+
act(() => source.emit({ type: 'delete', resource: 'crm_account', id: 'zz9' }));
561+
act(() => source.emit({ type: 'delete', resource: 'crm_contact', id: 'a1' }));
562+
563+
expect(ids(result.current.recent.recentItems)).toEqual(before);
564+
await new Promise((r) => setTimeout(r, 700));
565+
expect(adapter.saveMock).not.toHaveBeenCalled();
566+
});
567+
568+
it('control: an update of the record, or a delete that names no record (a bulk delete), drops nothing', async () => {
569+
const { result, source } = await mount();
570+
const before = ids(result.current.recent.recentItems);
571+
act(() => source.emit({ type: 'update', resource: 'crm_account', id: 'a1' }));
572+
act(() => source.emit({ type: 'delete', resource: 'crm_account' }));
573+
574+
expect(ids(result.current.recent.recentItems)).toEqual(before);
575+
});
576+
577+
it('after an undo, the visit to the restored record lists it again', async () => {
578+
const { result, source } = await mount();
579+
act(() => source.emit({ type: 'delete', resource: 'crm_account', id: 'a1' }));
580+
expect(ids(result.current.recent.recentItems)).not.toContain('record:crm_account:a1');
581+
582+
// The record page's Undo restores the record and returns to it; that visit records it.
583+
act(() => result.current.recent.addRecentItem(record('crm_account', 'a1', 'Browser Test Co')));
584+
expect(ids(result.current.recent.recentItems)[0]).toBe('record:crm_account:a1');
585+
});
586+
587+
it('unsubscribes when unmounted', async () => {
588+
const { result, source, unmount } = await mount();
589+
const before = ids(result.current.recent.recentItems);
590+
unmount();
591+
act(() => source.emit({ type: 'delete', resource: 'crm_account', id: 'a1' }));
592+
expect(ids(JSON.parse(localStorage.getItem(KEY)!))).toEqual(before);
593+
});
594+
});

0 commit comments

Comments
 (0)