Skip to content
16 changes: 16 additions & 0 deletions .changeset/36309-embedded-stage-reread.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@object-ui/react': patch
'@object-ui/plugin-detail': patch
'@object-ui/app-shell': patch
---

fix(console): a stage move refused with a 409 in a record drawer re-reads the record, so the next Move sends the stored version

Clause-②: yes (widening) — `RecordContextValue` (and so `RecordContextProviderProps`) gains one optional member, `reread`; nothing is removed or renamed, and `refresh` keeps its type
Metadata-protocol: none

The record header's stage menu also draws in a record drawer (the list's drawer, and the drawer a record page opens over itself). Its save path answered a `409 CONCURRENT_UPDATE` by calling the record context's `refresh`, which the record view leaves out in a drawer so the header draws no Refresh entry there. In a drawer the record was therefore never read again: the dialog kept the old row, and a second Move sent the same stale version and was refused again.

`RecordContextValue` now keeps the two apart. `refresh` stays the host's opt-in to the header's Refresh entry and is still left out in a drawer. The new `reread` reads the record again with no affordance of its own; the record view provides it on the page and in a drawer alike, and the stage menu and `record:path`'s stage press call it after a move and after a 409. On the record page nothing changes: `reread` publishes the same `'*'` notice the Refresh entry does.

A host that mounts `RecordContextProvider` with only `refresh` keeps its behaviour: the stage surfaces call `reread` when the host provides it and `refresh` otherwise. Nothing to migrate; a host that wants the re-read without the Refresh entry passes `reread` alone.
162 changes: 161 additions & 1 deletion ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@

import * as React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
import { render, waitFor, cleanup, screen, act, fireEvent } from '@testing-library/react';
import { render, waitFor, cleanup, screen, act, fireEvent, within } from '@testing-library/react';
import { MemoryRouter, Route, Routes, BrowserRouter } from 'react-router-dom';
import { toast } from 'sonner';
import { RelatedCountStore } from '@object-ui/components';
Expand Down Expand Up @@ -3430,3 +3430,163 @@ describe('RecordDetailView.approvalSubjectTitle-35415', () => {
});
});
});

// ── RecordDetailView.embeddedStageReread-36309 ──────────────────────────────

/**
* objectstack#36309 — the header's stage menu draws in a drawer too (the list
* drawer, and the drawer a record page opens over itself, both mount this view
* `embedded`). A 409 on a Move there re-reads the record, so the next Move
* carries the version that is stored. The drawer still draws no Refresh entry:
* showing the entry and re-reading the record are two context members.
*/
describe('RecordDetailView.embeddedStageReread-36309', () => {
restoreAfterBlock();

const OBJECT = 'crm_deal_36309';
const ID = 'd1';
const DEF = {
name: OBJECT,
label: 'Deal',
nameField: 'name',
fields: {
id: { label: 'Id', type: 'text' },
name: { label: 'Name', type: 'text' },
stage: {
label: 'Stage',
type: 'select',
options: [
{ value: 'prospecting', label: 'Prospecting' },
{ value: 'negotiation', label: 'Negotiation' },
],
},
},
};
const versionAt = (read: number) => `2026-11-22T0${read}:00:00.000Z`;

function makeMetadata() {
const pages: any[] = [];
return {
objects: [DEF], pages, loading: false, error: null,
refresh: async () => {}, invalidate: () => {},
ensureType: async () => pages, getItem: async () => null,
getItemsByType: () => pages,
} as any;
}

/** Every read answers a newer version; the first Move is refused with a 409. */
function renderDeal(embedded: boolean) {
let reads = 0;
const conflict = Object.assign(new Error('CONCURRENT_UPDATE'), { code: 'CONCURRENT_UPDATE', status: 409 });
let writes = 0;
const ds = {
find: vi.fn(async () => ({ data: [], total: 0, hasMore: false, pageSize: 50 })),
findOne: vi.fn(async () => {
reads += 1;
return { id: ID, name: 'Wayne deal', stage: 'prospecting', updated_at: versionAt(reads) };
}),
create: vi.fn(async (_o: string, r: any) => r),
update: vi.fn(async () => {
writes += 1;
if (writes === 1) throw conflict;
return {};
}),
delete: vi.fn(async () => ({})),
getObjectSchema: async () => DEF,
} as Record<string, any>;
render(
<MemoryRouter initialEntries={[`/apps/demo/${OBJECT}/record/${ID}`]}>
<MetadataCtx.Provider value={makeMetadata()}>
<NavigationProvider>
<RecordDetailView
dataSource={ds as never}
objects={[DEF] as never}
onEdit={() => {}}
objectNameOverride={OBJECT}
recordIdOverride={ID}
embedded={embedded}
/>
</NavigationProvider>
</MetadataCtx.Provider>
</MemoryRouter>,
);
return { ds };
}

const stageMenu = () => document.querySelector('[data-record-stage-menu]') as HTMLElement | null;
const moreTrigger = () =>
document.querySelector('header [aria-label="More actions"], [data-record-top-bar-actions] [aria-label="More actions"]') as HTMLElement | null;

async function pickNegotiation() {
await waitFor(() => expect(stageMenu()).toBeTruthy());
fireEvent.pointerDown(stageMenu()!, { button: 0, ctrlKey: false, pointerType: 'mouse' });
const option = await waitFor(() => {
const el = document.querySelector('[data-record-stage-menu-list] [data-stage-value="negotiation"]') as HTMLElement | null;
expect(el).toBeTruthy();
return el!;
});
fireEvent.click(option);
return screen.findByRole('dialog');
}

beforeAll(() => {
Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 });
});

beforeEach(() => {
vi.stubGlobal('fetch', vi.fn(async () => ({
ok: true,
status: 200,
json: async () => ({ allowed: true, data: [] }),
text: async () => '{}',
})) as never);
});

afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});

it('in a drawer, a 409 on Move re-reads the record and the second Move carries the new version', async () => {
const { ds } = renderDeal(true);
const dialog = await pickNegotiation();
expect(ds.findOne).toHaveBeenCalledTimes(1);

fireEvent.click(within(dialog).getByRole('button', { name: 'Move' }));
await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1));
expect(ds.update).toHaveBeenLastCalledWith(OBJECT, ID, { stage: 'negotiation' }, { ifMatch: versionAt(1) });
// The refusal re-reads the record in place.
await waitFor(() => expect(ds.findOne).toHaveBeenCalledTimes(2));

fireEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Move' }));
await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(2));
expect(ds.update).toHaveBeenLastCalledWith(OBJECT, ID, { stage: 'negotiation' }, { ifMatch: versionAt(2) });
});

it('CONTROL — the drawer still draws no Refresh entry in the header', async () => {
const { ds } = renderDeal(true);
await waitFor(() => expect(ds.findOne).toHaveBeenCalled());
await waitFor(() => expect(stageMenu()).toBeTruthy());
const trigger = moreTrigger();
if (trigger) {
fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' });
await waitFor(() => expect(document.querySelector('[role="menu"]')).toBeTruthy());
}
expect(document.querySelector('[data-page-refresh]')).toBeNull();
});

it('CONTROL — on the record page the same 409 re-reads too, and the page keeps its Refresh entry', async () => {
const { ds } = renderDeal(false);
const dialog = await pickNegotiation();
fireEvent.click(within(dialog).getByRole('button', { name: 'Move' }));
await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1));
await waitFor(() => expect(ds.findOne).toHaveBeenCalledTimes(2));
fireEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Move' }));
await waitFor(() => expect(ds.update).toHaveBeenLastCalledWith(OBJECT, ID, { stage: 'negotiation' }, { ifMatch: versionAt(2) }));
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());

await waitFor(() => expect(moreTrigger()).toBeTruthy());
fireEvent.pointerDown(moreTrigger()!, { button: 0, ctrlKey: false, pointerType: 'mouse' });
await waitFor(() => expect(document.querySelector('[data-page-refresh]')).toBeTruthy());
});
});
6 changes: 6 additions & 0 deletions ui/packages/app-shell/src/views/RecordDetailView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1171,6 +1171,11 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
// keeps ⟳ off those surfaces for now. `undefined` is the opt-out
// `page:header` reads, so nothing renders there.
const headerRefresh = embedded ? undefined : handleManualRefresh;
// objectstack#36309 — the header's re-read (`RecordContext.reread`) is not
// the ⟳: the stage menu draws in a drawer too, and its 409 answer must read
// the record again there, so every host provides it. Same `'*'` scope as the
// ⟳: a 409 is exactly a write this client never saw.
const headerReread = handleManualRefresh;

// Record-scoped presence ("who else is viewing this record"). The default
// PresenceProvider source is a no-op, so this resolves to `[]` until a
Expand Down Expand Up @@ -5958,6 +5963,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
dataSource={dataSource}
embedded={embedded}
refresh={headerRefresh}
reread={headerReread}
headerSystemActions={synthSystemActions}
objectLabelNote={inSetupApp ? managedByNote ?? undefined : undefined}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ function mount(opts: MountOptions = {}) {
data={{ id: 'o1', name: 'Wayne deal', stage, loss_reason: null, updated_at: VERSION }}
objectSchema={opts.schema ?? OPPORTUNITY}
dataSource={dataSource as any}
refresh={refresh}
reread={refresh}
>
<InlineEditProvider canEdit={opts.canEdit ?? true}>
<RecordStageMenu field="stage" label={label} tag={tag} />
Expand Down Expand Up @@ -423,7 +423,7 @@ describe('#36036 after a 409 re-read, the stage dialog asks what the re-read rec
} as unknown as typeof OPPORTUNITY;

/**
* The page's refresh as the record page wires it: a notice that returns at
* The page's re-read as the record page wires it: a notice that returns at
* once, the re-read row landing in the record context afterwards.
*/
function mountReRead(reread: Record<string, unknown>, schema: typeof OPPORTUNITY = OPPORTUNITY) {
Expand All @@ -444,7 +444,7 @@ describe('#36036 after a 409 re-read, the stage dialog asks what the re-read rec
data={row}
objectSchema={schema}
dataSource={dataSource as any}
refresh={refresh}
reread={refresh}
>
<InlineEditProvider canEdit>
<RecordStageMenu field="stage" label="Prospecting" tag={<span>Prospecting</span>} />
Expand Down Expand Up @@ -540,6 +540,51 @@ describe('#35891 who sees the plain tag', () => {
});
});

describe('#36309 a host with only refresh still re-reads; reread wins where both are given', () => {
const conflict = () => Object.assign(new Error('CONCURRENT_UPDATE'), { code: 'CONCURRENT_UPDATE', status: 409 });

function mountWith(members: { refresh?: () => Promise<void>; reread?: () => Promise<void> }) {
const dataSource = makeDataSource(async () => { throw conflict(); });
render(
<RecordContextProvider
objectName="crm_opportunity"
recordId="o1"
data={{ id: 'o1', name: 'Wayne deal', stage: 'prospecting', loss_reason: null, updated_at: VERSION }}
objectSchema={OPPORTUNITY}
dataSource={dataSource as any}
{...members}
>
<InlineEditProvider canEdit>
<RecordStageMenu field="stage" label="Prospecting" tag={<span>Prospecting</span>} />
</InlineEditProvider>
</RecordContextProvider>,
);
return { dataSource };
}

it('a provider with only refresh: a 409 on Move calls refresh', async () => {
const refresh = vi.fn(async () => {});
const { dataSource } = mountWith({ refresh });
fireEvent.click(item(openMenu(), 'Negotiation'));
const dialog = await screen.findByRole('dialog');
fireEvent.click(within(dialog).getByRole('button', { name: 'Move' }));
await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1));
await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1));
});

it('CONTROL — a provider with both: a 409 on Move calls reread, not refresh', async () => {
const refresh = vi.fn(async () => {});
const reread = vi.fn(async () => {});
const { dataSource } = mountWith({ refresh, reread });
fireEvent.click(item(openMenu(), 'Negotiation'));
const dialog = await screen.findByRole('dialog');
fireEvent.click(within(dialog).getByRole('button', { name: 'Move' }));
await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1));
await waitFor(() => expect(reread).toHaveBeenCalledTimes(1));
expect(refresh).not.toHaveBeenCalled();
});
});

describe('#35891 the keyboard', () => {
it('Enter opens the menu; Escape closes it without a write', async () => {
const { dataSource } = mount();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ function mount(opts: MountOptions = {}) {
data={{ id: 'q1', status: 'draft', updated_at: VERSION }}
objectSchema={opts.objectSchema ?? OBJECT_SCHEMA}
dataSource={dataSource as any}
refresh={refresh}
reread={refresh}
>
<InlineEditProvider canEdit={opts.canEdit ?? true}>
{opts.editing && <EnterEditing />}
Expand Down Expand Up @@ -330,7 +330,7 @@ function mountNode(node: unknown, opts: Omit<MountOptions, 'allowStageChange'> =
data={{ id: 'q1', status: 'draft', updated_at: VERSION }}
objectSchema={opts.objectSchema ?? QUOTE_DEF}
dataSource={dataSource as any}
refresh={refresh}
reread={refresh}
>
<InlineEditProvider canEdit={opts.canEdit ?? true}>
<SchemaRenderer schema={node as never} />
Expand Down
16 changes: 10 additions & 6 deletions ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,9 @@
*
* The fields asked are judged against the record AS IT STANDS, on every
* render, not frozen at the pick (objectstack#36036). A 409 re-reads the
* record, and the re-read row reaches this hook later through the record
* context (the page's refresh is a bus notice, not a fetch it can await), so
* record (`RecordContextValue.reread`, else the host's `refresh`; the record
* view provides `reread` on the page and in a drawer alike), and the re-read row reaches this hook later through the record
* context (the page's re-read is a bus notice, not a fetch it can await), so
* the list follows that row when it lands: a field another writer filled in
* the meantime leaves the dialog, the move no longer sends it, and a value the
* reader typed for it stops counting toward the fields it would chain in. When
Expand Down Expand Up @@ -211,6 +212,9 @@ export function useStageChange(
): StageChange {
const collectFields = options.collectFields === true;
const ctx = useRecordContext();
// The record's re-read after a move or a 409: the host's `reread`, else its
// `refresh` (a host that provides only `refresh` keeps re-reading).
const rereadRecord = async () => { await (ctx?.reread ?? ctx?.refresh)?.(); };
const inline = useInlineEdit();
const perms = usePermissions();
const { t } = useDetailTranslation();
Expand Down Expand Up @@ -288,12 +292,12 @@ export function useStageChange(
setBusy(true);
try {
await updateVia(dataSource, objectName!, recordId!, { [statusField!]: stage.value }, ifMatchOf());
await ctx?.refresh?.();
await rereadRecord();
} catch (err) {
setRefusal(stageRefusalLines(err, statusField!, labelOf, t));
// A stale token means the reader is looking at an old record: show the
// current one, so a second press is judged against what is stored.
if (isConcurrentUpdateError(err)) await ctx?.refresh?.();
if (isConcurrentUpdateError(err)) await rereadRecord();
} finally {
setBusy(false);
}
Expand All @@ -314,7 +318,7 @@ export function useStageChange(
await updateVia(dataSource, objectName!, recordId!, { ...values, [statusField!]: stage.value }, ifMatchOf());
} catch (err) {
const concurrent = isConcurrentUpdateError(err);
if (concurrent) await ctx?.refresh?.();
if (concurrent) await rereadRecord();
const named = concurrent ? [] : (extractFieldErrors(err) ?? []).filter((e) => !!e.message);
if (named.length > 0 && !declaredUserMessage(err)) throw err;
const line = stageRefusalLines(err, statusField!, labelOf, t).join(' ');
Expand All @@ -323,7 +327,7 @@ export function useStageChange(
setBusy(false);
}
setTarget(null);
await ctx?.refresh?.();
await rereadRecord();
};

const dialog = collectFields
Expand Down
21 changes: 20 additions & 1 deletion ui/packages/react/src/context/RecordContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,26 @@ export interface RecordContextValue<TData = any, TObjectSchema = any> {
data?: TData;
/** Resolved object metadata schema (fields, label, etc.). */
objectSchema?: TObjectSchema;
/** Re-fetch the record from the source. */
/**
* The host's opt-in to the header's Refresh entry (the first item of its
* `⋯` menu): present, `page:header` draws the entry and calls this when it
* is picked; absent, the header draws none. A host that keeps the entry off
* a surface (a drawer) leaves it out. It also re-reads the record: a
* renderer that needs a re-read calls {@link RecordContextValue.reread}
* when the host provides one, and this otherwise.
*/
refresh?: () => void | Promise<void>;
/**
* Read the record again from the source, with no affordance of its own.
* A renderer that must judge its next write against what is stored calls
* it: after a write it made, and after a `409 CONCURRENT_UPDATE` refusal, so
* the next write carries the stored version. A host provides it wherever it
* reads the record, drawers included, whether or not it offers
* {@link RecordContextValue.refresh}; a renderer falls back to `refresh`
* when a host provides only that. It may be a notice that returns before
* the re-read row lands; the row reaches readers through `data` afterwards.
*/
reread?: () => void | Promise<void>;
/**
* Optional system-level header actions (Edit / Share / Delete) that the
* host (e.g. RecordDetailView) wants to inject into the page header
Expand Down Expand Up @@ -235,6 +253,7 @@ export const RecordContextProvider: React.FC<RecordContextProviderProps> = ({
value.data,
value.objectSchema,
value.refresh,
value.reread,
value.embedded,
value.headerSystemActions,
value.isFavorite,
Expand Down
Loading
Loading