diff --git a/.changeset/37440-draft-publish-pins.md b/.changeset/37440-draft-publish-pins.md new file mode 100644 index 00000000000..a8663de6bfe --- /dev/null +++ b/.changeset/37440-draft-publish-pins.md @@ -0,0 +1,13 @@ +--- +'@objectstack/client': patch +'@object-ui/app-shell': patch +--- + +fix(client, app-shell): every draft-then-publish Save publishes only the draft it wrote + +Clause-②: yes (widening: `@objectstack/client` `meta.publishItem` accepts `draftVersion` and `parentVersion` beside `message` and `packageId`) +Metadata-protocol: none + +`client.meta.publishItem(type, name, opts)` takes two optional pins. `draftVersion` (sent in the publish body beside `message`) names the pending draft the publish means to promote: pass your own draft save's receipt `version`, and a draft another writer changed after it is refused `409 METADATA_CONFLICT` with nothing published. `parentVersion` names the live row the publish means to replace (sent as `If-Match`; `null` asserts that no live row is stored, sent as `If-None-Match: *`). Omitted, the request is byte-identical to before and the publish is unpinned. + +In the console, every Save that writes a draft and publishes it at once now pins that publish to the draft its own write returned: the Studio top bar's Save (objects, object extensions, flows and their on/off switch, hooks, an installed object's actions, permission sets, a new app, a new object or flow), the item page's Save, each row of the package's sharing-defaults table, 「Configure tabs」, an installed object's field arrangement, the design mode's header pins, menu and menu labels. When someone else's draft write lands on the same item between that draft write and the publish, nothing is published and the draft, which now holds their change, is kept pending instead of discarded; the Save says a draft is pending (the next Studio Save asks to reload or overwrite). The take-back of a refused Save's own draft is pinned to the same version, so it never removes a draft someone else changed. Against a server whose draft save returns no version, all of these publish unpinned, as before. diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 6d9368259b5..fb8506eaea4 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -1284,6 +1284,22 @@ function metaDeleteHeaders(options?: DeleteMetaItemOptions): Record | undefined { + if (parentVersion === null) return { 'If-None-Match': '*' }; + if (!parentVersion) return undefined; + return { 'If-Match': String(parentVersion) }; +} + /** * An OAuth client application exactly as `@better-auth/oauth-provider` puts it * on the wire: RFC 7591 §2 client metadata, snake_case, served BARE — these @@ -2725,6 +2741,15 @@ export class ObjectStackClient { * holds no draft and another package's draft is stored. Pass the package * whose draft you mean as `opts.packageId` (`?package=` on the wire), as * `saveItem` and `deleteItem` name the row they act on. + * + * PIN WHAT YOU PUBLISH when you wrote or read the draft first + * (`PublishMetaItemRequestSchema`'s two ADR-0008 pins): `draftVersion` + * names the draft you mean to promote, so a draft another writer changed + * after you wrote or read it is refused `409 METADATA_CONFLICT` and + * nothing is published on their behalf; `parentVersion` names the live + * row you mean to replace. Pass your own draft save's receipt `version` + * (or the draft read's) as `draftVersion` — never a fresh re-read, which + * would pin whatever draft is pending now, someone else's included. */ publishItem: async ( type: string, @@ -2751,6 +2776,31 @@ export class ObjectStackClient { * it. */ packageId?: string; + /** + * `PublishMetaItemRequestSchema.draftVersion` — the version token + * of the pending draft this publish means to promote: a draft + * save's receipt `version` (`saveItem` in draft mode) or the + * draft read's `version`. Sent as the `draftVersion` member of + * the publish body, beside `message`. A draft that moved since is + * refused `409 METADATA_CONFLICT`, its `currentVersion` naming the + * draft's current token (`null` when no draft is pending any + * more), and nothing is promoted. Omitted, whichever draft is + * pending is promoted, as before. An empty string pins nothing and + * is not sent. + */ + draftVersion?: string; + /** + * `PublishMetaItemRequestSchema.parentVersion` — the version token + * of the LIVE row this publish means to replace (a publish + * receipt's `version`, a read's `version`), sent as `If-Match`. + * `null` asserts that no live row is stored, sent as + * `If-None-Match: *`. A live row that does not match is refused + * `409 METADATA_CONFLICT` and nothing is promoted. Omitted, the + * publish replaces whatever is live, as before. It pins the live + * row only; the draft's own pin is `draftVersion`, and the two + * may be sent together (the door judges the draft first). + */ + parentVersion?: string | null; }, ): Promise => { const route = this.getRoute('metadata'); @@ -2764,9 +2814,20 @@ export class ObjectStackClient { // `query`, not `qs` — it carries its own `?`; see `saveItem`'s note on // the three meanings `qs` holds in this file. const query = search ? `?${search}` : ''; + // [#37440] The two ADR-0008 pins. `draftVersion` rides the BODY, + // beside `message` (the REST door reads it there); `parentVersion` + // rides a HEADER, as on the save and delete doors: a token as + // `If-Match`, `null` as `If-None-Match: *`. Each is omitted when + // unset, so an unpinned publish hands `fetch` the same `init` it + // always did. + const headers = metaPublishHeaders(opts?.parentVersion); const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/publish${query}`, { method: 'POST', - body: JSON.stringify(opts?.message ? { message: opts.message } : {}), + ...(headers ? { headers } : {}), + body: JSON.stringify({ + ...(opts?.message ? { message: opts.message } : {}), + ...(opts?.draftVersion ? { draftVersion: opts.draftVersion } : {}), + }), }); return this.unwrapResponse(res); }, diff --git a/packages/client/src/meta-publish-item-package.test.ts b/packages/client/src/meta-publish-item-package.test.ts index 66f3808286e..71d60c4873b 100644 --- a/packages/client/src/meta-publish-item-package.test.ts +++ b/packages/client/src/meta-publish-item-package.test.ts @@ -409,3 +409,112 @@ describe('[#23658] the real publish door: the only draft is another package\'s', expect(publishRequests[1].packageId).toBe(OTHER_PKG); }, 60_000); }); + +// --------------------------------------------------------------------------- +// Part 3 — [#37440] the two pins: `draftVersion` (the draft) and +// `parentVersion` (the live row) +// --------------------------------------------------------------------------- + +describe('[#37440] meta.publishItem pins — what reaches the wire', () => { + it('`draftVersion` rides the body beside `message`; `parentVersion` rides `If-Match`', async () => { + const { client, fetchMock } = createMockClient(PUBLISH_OK); + await client.meta.publishItem('view', 'shared_grid', { + message: 'ship it', + packageId: PKG, + draftVersion: 'draft-token', + parentVersion: 'live-token', + }); + expect(bodyOfCall(fetchMock)).toEqual({ message: 'ship it', draftVersion: 'draft-token' }); + const headers = fetchMock.mock.calls[0][1].headers as Record; + expect(headers['If-Match']).toBe('live-token'); + expect(headers).not.toHaveProperty('If-None-Match'); + // A body member and a header: neither is put on the query string. + expect(new URL(String(fetchMock.mock.calls[0][0])).search).toBe(`?package=${PKG}`); + }); + + it('`parentVersion: null` asserts no live row: `If-None-Match: *`, never beside `If-Match`', async () => { + const { client, fetchMock } = createMockClient(PUBLISH_OK); + await client.meta.publishItem('view', 'shared_grid', { parentVersion: null }); + const headers = fetchMock.mock.calls[0][1].headers as Record; + expect(headers['If-None-Match']).toBe('*'); + expect(headers).not.toHaveProperty('If-Match'); + expect(bodyOfCall(fetchMock)).toEqual({}); + }); + + it('CONTROL: unset (or empty) pins send nothing — the request an unpinned publish always sent', async () => { + const { client, fetchMock } = createMockClient(PUBLISH_OK); + await client.meta.publishItem('view', 'shared_grid', { draftVersion: '', parentVersion: '' }); + await client.meta.publishItem('view', 'shared_grid', { draftVersion: undefined, parentVersion: undefined }); + for (let i = 0; i < 2; i++) { + expect(String(fetchMock.mock.calls[i][0])).toBe(PUBLISH_URL); + expect(bodyOfCall(fetchMock, i)).toEqual({}); + const headers = fetchMock.mock.calls[i][1].headers as Record; + expect(headers).not.toHaveProperty('If-Match'); + expect(headers).not.toHaveProperty('If-None-Match'); + } + }); +}); + +describe('[#37440] the real publish door: a draft another writer changed in between is never published', () => { + /** + * The caller's draft write (its receipt is its pin), then ANOTHER writer's + * draft write to the same address, landing before the caller's publish. + */ + async function interleaved(client: ObjectStackClient, name: string) { + await client.meta.saveItem('view', name, VIEW(name, 'live'), { packageId: PKG }); + const mine = await client.meta.saveItem('view', name, VIEW(name, 'mine'), { packageId: PKG, mode: 'draft' }); + await client.meta.saveItem('view', name, VIEW(name, 'theirs'), { packageId: PKG, mode: 'draft' }); + return (mine as { version?: string }).version; + } + + it('REPRODUCTION — unpinned (all the SDK could send before): the other writer\'s draft goes live', async () => { + const { engine, client } = await bootDoor(); + await interleaved(client, 'interleaved_unpinned'); + await client.meta.publishItem('view', 'interleaved_unpinned', { packageId: PKG }); + expect(await rowsOf(engine, 'interleaved_unpinned')).toEqual([`${PKG}:active:theirs`]); + }, 60_000); + + it('PIN — `draftVersion` = the caller\'s own receipt: refused 409 METADATA_CONFLICT, nothing promoted', async () => { + const { engine, client, publishRequests } = await bootDoor(); + const mine = await interleaved(client, 'interleaved_pinned'); + expect(typeof mine).toBe('string'); + const err = await refusalOf(client.meta.publishItem('view', 'interleaved_pinned', { packageId: PKG, draftVersion: mine })); + expect(err.code).toBe('METADATA_CONFLICT'); + expect(err.httpStatus).toBe(409); + // The live row stands; the moved draft (the other writer's) stays pending, unpublished. + expect(await rowsOf(engine, 'interleaved_pinned')).toEqual([`${PKG}:active:live`, `${PKG}:draft:theirs`].sort()); + expect(publishRequests[0].draftVersion).toBe(mine); + }, 60_000); + + it('CONTROL — no interleave: the same pinned publish promotes the caller\'s draft', async () => { + const { engine, client } = await bootDoor(); + await client.meta.saveItem('view', 'uninterleaved', VIEW('uninterleaved', 'live'), { packageId: PKG }); + const mine = await client.meta.saveItem('view', 'uninterleaved', VIEW('uninterleaved', 'mine'), { + packageId: PKG, + mode: 'draft', + }); + const published = await client.meta.publishItem('view', 'uninterleaved', { + packageId: PKG, + draftVersion: (mine as { version?: string }).version, + }); + expect(published.success).toBe(true); + expect(await rowsOf(engine, 'uninterleaved')).toEqual([`${PKG}:active:mine`]); + }, 60_000); + + it('`parentVersion` pins the live row: a stale token is refused 409, the live token promotes', async () => { + const { engine, client, publishRequests } = await bootDoor(); + const first = await client.meta.saveItem('view', 'live_pinned', VIEW('live_pinned', 'live'), { packageId: PKG }); + const liveToken = (first as { version?: string }).version; + await client.meta.saveItem('view', 'live_pinned', VIEW('live_pinned', 'mine'), { packageId: PKG, mode: 'draft' }); + // `null` asserts no live row — one is stored, so it is refused. + const err = await refusalOf(client.meta.publishItem('view', 'live_pinned', { packageId: PKG, parentVersion: null })); + expect(err.code).toBe('METADATA_CONFLICT'); + expect(err.httpStatus).toBe(409); + expect(await rowsOf(engine, 'live_pinned')).toEqual([`${PKG}:active:live`, `${PKG}:draft:mine`].sort()); + expect(publishRequests[0].parentVersion).toBeNull(); + const published = await client.meta.publishItem('view', 'live_pinned', { packageId: PKG, parentVersion: liveToken }); + expect(published.success).toBe(true); + expect(await rowsOf(engine, 'live_pinned')).toEqual([`${PKG}:active:mine`]); + expect(publishRequests[1].parentVersion).toBe(liveToken); + }, 60_000); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts index 82963e8baf4..55ea50bf5c6 100644 --- a/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts +++ b/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts @@ -18,6 +18,7 @@ vi.mock('../../assistant/assistantBus', async (importOriginal) => ({ import { saveObjectPins, type ObjectPinsSaveDoors } from '../designModeHeaderPinsSave'; import type { ObjectPins } from '../designModeHeaderPinsModel'; +import { draftPublishDoor } from '../../views/__tests__/draftPublishDoor-37440'; const TEXTS = { notListed: 'not listed', @@ -234,3 +235,35 @@ describe('saving the header pins (objectstack#36366)', () => { expect(calls.at(-1)).toEqual(['reset', 'object', 'crm_lead', { state: 'draft', packageId: 'com.acme.crm' }]); }); }); + +describe('the header pins Save publishes only the draft it wrote (objectstack#37440)', () => { + const authored = { name: 'crm_lead', label: 'Lead', actions: [{ name: 'convert', locations: ['record_header'] }] }; + function doorDoors() { + const door = draftPublishDoor(); + door.seedLive('object', 'crm_lead', 'com.acme.crm', authored); + const d: ObjectPinsSaveDoors = { + listPackages: async () => + new Map([['com.acme.crm', { id: 'com.acme.crm', name: 'CRM', writable: true, manifest: { version: '1.0.0' } }]]), + ensureCustomization: async (base) => ({ basePackageId: base, packageId: `${base}.custom`, namespace: 'crm_custom', created: false, writable: true }), + client: { ...door.client, get: async () => null, layered: async () => ({ code: authored }) }, + }; + return { door, d }; + } + const pins = { record: { pinned: ['log_call', 'convert'] } }; + + it("PIN: another writer's draft write between the save and its publish is refused, published by nobody, and kept", async () => { + const { door, d } = doorDoors(); + door.interleave('object', 'crm_lead', 'com.acme.crm', { name: 'crm_lead', label: 'theirs' }); + await expect(saveObjectPins(input(pins), TEXTS, d)).rejects.toThrow('pending draft'); + expect(door.liveOf('object', 'crm_lead', 'com.acme.crm')).toEqual(authored); + expect(door.draftOf('object', 'crm_lead', 'com.acme.crm')).toEqual({ name: 'crm_lead', label: 'theirs' }); + expect(door.calls.find(([c]) => c === 'publish')?.[3]).toMatchObject({ draftVersion: expect.any(String) }); + }); + + it('CONTROL: with no write in between, the same pinned publish takes the pins live', async () => { + const { door, d } = doorDoors(); + await saveObjectPins(input(pins), TEXTS, d); + expect(door.liveOf('object', 'crm_lead', 'com.acme.crm')).toEqual({ ...authored, actionLayout: pins }); + expect(door.draftOf('object', 'crm_lead', 'com.acme.crm')).toBeUndefined(); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36538.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36538.test.ts index 76a29c572cc..50244cb6daf 100644 --- a/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36538.test.ts +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36538.test.ts @@ -15,7 +15,15 @@ vi.mock('../../assistant/assistantBus', async (importOriginal) => ({ emitMetadataRefresh, })); -import { readStoredMenu, saveAppMenu, type AppMenuSaveDoors, type AppMenuSaveTexts } from '../designModeMenuSave'; +import { + menuTranslationName, + readStoredMenu, + saveAppMenu, + writeAppMenu, + type AppMenuSaveDoors, + type AppMenuSaveTexts, +} from '../designModeMenuSave'; +import { draftPublishDoor } from '../../views/__tests__/draftPublishDoor-37440'; const TEXTS: AppMenuSaveTexts = { notListed: 'not listed', @@ -181,3 +189,65 @@ describe('the publish is pinned to the published row the save read (objectstack# expect(publishOf(found.calls)).toEqual(['publish', 'app', 'crm', { packageId: 'com.acme.crm.custom' }]); }); }); + +describe('the menu Save publishes only the drafts it wrote (objectstack#37440)', () => { + const PKG = 'com.acme.crm'; + const BODY = { ...APP, navigation: NAV }; + const TRANSLATION = menuTranslationName('crm', 'zh-CN'); + function doorDoors() { + const door = draftPublishDoor(); + const liveVersion = door.seedLive('app', 'crm', PKG, APP); + const d: Pick = { client: { ...door.client, layered: async () => NOT_FOUND } }; + const prepared = { appName: 'crm', target: PKG, body: BODY, publishPin: { ifMatch: liveVersion } }; + return { door, d, prepared, liveVersion }; + } + + it("PIN (menu): another writer's draft write before the publish is refused, published by nobody, and kept", async () => { + const { door, d, prepared } = doorDoors(); + door.interleave('app', 'crm', PKG, { ...APP, label: 'theirs' }); + await expect(writeAppMenu(prepared, TEXTS, d)).rejects.toThrow(TEXTS.pendingDraft); + expect(door.liveOf('app', 'crm', PKG)).toEqual(APP); + expect(door.draftOf('app', 'crm', PKG)).toEqual({ ...APP, label: 'theirs' }); + expect(door.calls.find(([c]) => c === 'publish')?.[3]).toMatchObject({ ifMatch: prepared.publishPin.ifMatch, draftVersion: expect.any(String) }); + }); + + it('the published row moved instead: still said as a live change, and the draft this save wrote is taken back', async () => { + const { door, d, prepared } = doorDoors(); + door.seedLive('app', 'crm', PKG, { ...APP, label: 'published since' }); + await expect(writeAppMenu(prepared, TEXTS, d)).rejects.toThrow(TEXTS.publishedMoved); + expect(door.liveOf('app', 'crm', PKG)).toEqual({ ...APP, label: 'published since' }); + expect(door.draftOf('app', 'crm', PKG)).toBeUndefined(); + }); + + it('CONTROL (menu): with no write in between, the same pinned publish takes the menu live', async () => { + const { door, d, prepared } = doorDoors(); + await writeAppMenu(prepared, TEXTS, d); + expect(door.liveOf('app', 'crm', PKG)).toEqual(BODY); + expect(door.draftOf('app', 'crm', PKG)).toBeUndefined(); + }); + + const translated = (prepared: ReturnType['prepared']) => ({ + ...prepared, + writesMenu: false, + translation: { name: TRANSLATION, locale: 'zh-CN', labels: { leads: '线索' } }, + }); + + it("PIN (translation): another writer's draft write before its publish is refused, published by nobody, and kept", async () => { + const { door, d, prepared } = doorDoors(); + door.interleave('translation', TRANSLATION, PKG, { name: TRANSLATION, label: 'theirs' }); + await expect(writeAppMenu(translated(prepared), TEXTS, d)).rejects.toThrow(TEXTS.pendingDraft); + expect(door.liveOf('translation', TRANSLATION, PKG)).toBeUndefined(); + expect(door.draftOf('translation', TRANSLATION, PKG)).toEqual({ name: TRANSLATION, label: 'theirs' }); + }); + + it('CONTROL (translation): with no write in between, the labels go live', async () => { + const { door, d, prepared } = doorDoors(); + await writeAppMenu(translated(prepared), TEXTS, d); + expect(door.liveOf('translation', TRANSLATION, PKG)).toMatchObject({ + name: TRANSLATION, + locale: 'zh-CN', + apps: { crm: { navigation: { leads: { label: '线索' } } } }, + }); + expect(door.draftOf('translation', TRANSLATION, PKG)).toBeUndefined(); + }); +}); diff --git a/ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts b/ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts index 76cca8c1fa3..56a5c5930a0 100644 --- a/ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts +++ b/ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts @@ -49,7 +49,7 @@ import type { ObjectActionLayout } from '@objectstack/spec/data'; import { emitMetadataRefresh } from '../assistant/assistantBus.js'; -import { isDraftVersionConflict } from '../views/metadata-admin/draftVersionGuard.js'; +import { draftReceiptVersion, isDraftVersionConflict } from '../views/metadata-admin/draftVersionGuard.js'; import { authoredPublished, type AuthoredLayers } from '../views/metadata-admin/authoredObjectBuffer.js'; import { saveObjectExtensionArrangement } from '../views/objectExtensionArrangementSave.js'; import { @@ -68,7 +68,7 @@ export interface ObjectPinsSaveDoors { layered: (type: string, name: string, options: { packageId?: string }) => Promise; get: (type: string, name: string, options?: Record) => Promise; save: (type: string, name: string, body: unknown, options: Record) => Promise; - publish: (type: string, name: string, options: { packageId?: string }) => Promise; + publish: (type: string, name: string, options: { packageId?: string; draftVersion?: string }) => Promise; reset: (type: string, name: string, options: Record) => Promise; }; } @@ -161,21 +161,37 @@ export async function saveObjectPins( if (layers && 'draft' in layers && layers.draft) throw new Error(texts.pendingDraft); const authored = authoredPublished('object', layers) as Record; const body = withActionLayout({ ...authored, name: objectName }, actionLayoutValue(authored.actionLayout, pins, changed)); + let draftVersion: string | undefined; try { - await doors.client.save('object', objectName, body, { mode: 'draft', packageId, ifNoneMatch: '*' }); + draftVersion = draftReceiptVersion( + await doors.client.save('object', objectName, body, { mode: 'draft', packageId, ifNoneMatch: '*' }), + ); } catch (err) { if (isDraftVersionConflict(err)) throw Object.assign(new Error(texts.pendingDraft), { cause: err }); throw err; } + // objectstack#37440 — the publish is pinned to the draft this save wrote + // (its receipt's version): a draft another writer changed in between is + // refused, and nothing is published on their behalf. + const pin = draftVersion ? { draftVersion } : {}; try { - await doors.client.publish('object', objectName, { packageId }); + await doors.client.publish('object', objectName, { packageId, ...pin }); } catch (err) { + // The discard is pinned to the same draft: one that moved holds the + // other writer's change, is refused, and stays pending, said as such. + let moved = false; try { - await doors.client.reset('object', objectName, { state: 'draft', packageId }); + await doors.client.reset('object', objectName, { + state: 'draft', + packageId, + ...(draftVersion ? { ifMatch: draftVersion } : {}), + }); } catch (discardErr) { - console.error('[design-mode] a refused publish left the action layout draft pending:', discardErr); + moved = !!draftVersion && isDraftVersionConflict(discardErr); + if (!moved) console.error('[design-mode] a refused publish left the action layout draft pending:', discardErr); } emitMetadataRefresh(); + if (moved) throw Object.assign(new Error(texts.pendingDraft), { cause: err }); throw err; } emitMetadataRefresh(); diff --git a/ui/packages/app-shell/src/layout/designModeMenuSave.ts b/ui/packages/app-shell/src/layout/designModeMenuSave.ts index e91b084eb7b..d4c4b1c167d 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuSave.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuSave.ts @@ -75,7 +75,7 @@ import { stripReadDecorations } from '@objectstack/spec/kernel'; import { emitMetadataRefresh } from '../assistant/assistantBus.js'; -import { isDraftVersionConflict, publishedPinOf, type DraftPin } from '../views/metadata-admin/draftVersionGuard.js'; +import { draftReceiptVersion, isDraftVersionConflict, publishedPinOf, type DraftPin } from '../views/metadata-admin/draftVersionGuard.js'; import { overrideDraftBody } from '../views/studio-design/customizeOverride.js'; import { ensureCustomizationPackage, @@ -115,7 +115,11 @@ export interface AppMenuSaveDoors { readonly client: { layered: (type: string, name: string, options: { packageId?: string }) => Promise; save: (type: string, name: string, body: unknown, options: Record) => Promise; - publish: (type: string, name: string, options: { packageId?: string; ifMatch?: string; ifNoneMatch?: '*' }) => Promise; + publish: ( + type: string, + name: string, + options: { packageId?: string; ifMatch?: string; ifNoneMatch?: '*'; draftVersion?: string }, + ) => Promise; reset: (type: string, name: string, options: Record) => Promise; }; } @@ -328,21 +332,30 @@ export async function writeAppMenu( return; } } + let draftVersion: string | undefined; try { - await doors.client.save('app', appName, body, { mode: 'draft', packageId: target, ifNoneMatch: '*' }); + draftVersion = draftReceiptVersion( + await doors.client.save('app', appName, body, { mode: 'draft', packageId: target, ifNoneMatch: '*' }), + ); } catch (err) { if (isDraftVersionConflict(err)) throw Object.assign(new Error(texts.pendingDraft), { cause: err }); throw err; } try { - await doors.client.publish('app', appName, { packageId: target, ...(publishPin ?? {}) }); + // objectstack#37440 — pinned to the draft this save wrote (its receipt's + // version) beside the published row it was composed over. + await doors.client.publish('app', appName, { + packageId: target, + ...(publishPin ?? {}), + ...(draftVersion ? { draftVersion } : {}), + }); } catch (err) { - try { - await doors.client.reset('app', appName, { state: 'draft', packageId: target }); - } catch (discardErr) { - console.error('[design-mode] a refused publish left the menu draft pending:', discardErr); - } + // objectstack#37440 — the discard is pinned to the same draft, which is + // also what tells the two refusals apart: a draft that moved (another + // writer's change is in it) refuses the discard and stays pending. + const moved = await discardOwnDraft(doors, 'app', appName, target, draftVersion, 'the menu draft'); emitMetadataRefresh(); + if (moved) throw Object.assign(new Error(texts.pendingDraft), { cause: err }); // A publish somebody landed since the read: nothing went live. if (texts.publishedMoved && isDraftVersionConflict(err)) throw Object.assign(new Error(texts.publishedMoved), { cause: err }); throw err; @@ -421,8 +434,11 @@ async function writeMenuTranslation( } const body = { ...stored, name: write.name, locale: write.locale, apps: { ...apps, [appName]: { ...app, navigation } } }; const pin = publishPinAt(layers); + let draftVersion: string | undefined; try { - await doors.client.save('translation', write.name, body, { mode: 'draft', packageId: target, ifNoneMatch: '*' }); + draftVersion = draftReceiptVersion( + await doors.client.save('translation', write.name, body, { mode: 'draft', packageId: target, ifNoneMatch: '*' }), + ); } catch (err) { if (isDraftVersionConflict(err)) { throw Object.assign(new Error(texts.translationPendingDraft ?? texts.pendingDraft), { cause: err }); @@ -430,18 +446,47 @@ async function writeMenuTranslation( throw err; } try { - await doors.client.publish('translation', write.name, { packageId: target, ...(pin ?? {}) }); + // objectstack#37440 — pinned to the draft this save wrote, as the menu's is. + await doors.client.publish('translation', write.name, { + packageId: target, + ...(pin ?? {}), + ...(draftVersion ? { draftVersion } : {}), + }); } catch (err) { - try { - await doors.client.reset('translation', write.name, { state: 'draft', packageId: target }); - } catch (discardErr) { - console.error('[design-mode] a refused publish left the menu translation draft pending:', discardErr); - } + const moved = await discardOwnDraft(doors, 'translation', write.name, target, draftVersion, 'the menu translation draft'); + if (moved) throw Object.assign(new Error(texts.translationPendingDraft ?? texts.pendingDraft), { cause: err }); if (texts.publishedMoved && isDraftVersionConflict(err)) throw Object.assign(new Error(texts.publishedMoved), { cause: err }); throw err; } } +/** + * objectstack#37440 — take back the draft a refused publish leaves, pinned + * (`If-Match`) to the version this save's own draft write returned, so the + * server removes that draft only. Answers whether the draft MOVED: another + * writer's change is in it, the discard is refused `409 METADATA_CONFLICT`, + * and it stays pending — which also says the publish's refusal was the draft + * pin's, not the published row's. Any other failure is logged and the draft + * stays pending, as before. + */ +async function discardOwnDraft( + doors: Pick, + type: string, + name: string, + packageId: string, + draftVersion: string | undefined, + what: string, +): Promise { + try { + await doors.client.reset(type, name, { state: 'draft', packageId, ...(draftVersion ? { ifMatch: draftVersion } : {}) }); + return false; + } catch (discardErr) { + if (draftVersion && isDraftVersionConflict(discardErr)) return true; + console.error(`[design-mode] a refused publish left ${what} pending:`, discardErr); + return false; + } +} + /** * The stored menu of the app `appName` of the package `packageId`: the * navigation of its layered read (`storedApp`), `null` when the read fails diff --git a/ui/packages/app-shell/src/views/__tests__/draftPublishDoor-37440.ts b/ui/packages/app-shell/src/views/__tests__/draftPublishDoor-37440.ts new file mode 100644 index 00000000000..428d984cbcf --- /dev/null +++ b/ui/packages/app-shell/src/views/__tests__/draftPublishDoor-37440.ts @@ -0,0 +1,153 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37440 — a stateful double of the `/meta` item doors a + * draft-then-publish caller goes through, holding one draft row and one live + * row per address (type, name, package), with the two ADR-0008 pins of the + * per-item publish as the real door judges them + * (`PublishMetaItemRequestSchema`, measured on the real door in + * `packages/client/src/meta-publish-item-package.test.ts`): + * + * - a draft save answers its receipt `version`; `If-None-Match: *` over a + * pending draft, and an `If-Match` that is not the draft's version, are + * refused `409 METADATA_CONFLICT`; + * - the publish judges `draftVersion` FIRST (against the draft row), then + * `If-Match` / `If-None-Match: *` (against the live row), each refused + * `409 METADATA_CONFLICT` with `currentVersion`; with no pin, whichever + * draft is pending goes live — the window the card closes; + * - a draft discard (`reset` with `state: 'draft'`) pinned `If-Match` removes + * that draft only, and is refused `409` when the draft moved; + * - the draft read answers the envelope with its `version`, `null` when none. + * + * `interleave` runs ANOTHER writer's draft write right before the next + * publish reaches the door: the race the pins are for. + */ + +import type { MetadataClient } from '@object-ui/data-objectstack'; + +type Options = Record; + +interface Row { + body: unknown; + version: string; +} + +export interface DraftPublishDoor { + client: { + save: (type: string, name: string, body: unknown, options?: Options) => Promise; + publish: (type: string, name: string, options?: Options) => Promise; + reset: (type: string, name: string, options?: Options) => Promise; + getDraft: (type: string, name: string, options?: Options) => Promise; + }; + /** The same doors, typed as the console's client for callers that take one. */ + metadataClient: Pick; + /** The pending draft body at the address, or `undefined`. */ + draftOf: (type: string, name: string, packageId?: string | null) => unknown; + /** The live body at the address, or `undefined`. */ + liveOf: (type: string, name: string, packageId?: string | null) => unknown; + /** Store a live row at the address (the state before the Save), answering its version. */ + seedLive: (type: string, name: string, packageId: string | null | undefined, body: unknown) => string; + /** Another writer's draft write to the address, landing right before the next publish. */ + interleave: (type: string, name: string, packageId: string | null | undefined, body: unknown) => void; + /** Every request, in order: `[door, type, name, options]`. */ + calls: Array<[string, string, string, Options]>; +} + +const key = (type: string, name: string, packageId: unknown): string => + JSON.stringify([type, name, typeof packageId === 'string' && packageId ? packageId : null]); + +function conflict(currentVersion: string | null): Error { + return Object.assign(new Error('the version token sent is not the current version'), { + status: 409, + code: 'METADATA_CONFLICT', + body: { error: 'conflict', code: 'METADATA_CONFLICT', currentVersion }, + }); +} + +export function draftPublishDoor(): DraftPublishDoor { + let seq = 0; + const drafts = new Map(); + const live = new Map(); + const calls: DraftPublishDoor['calls'] = []; + let pendingInterleave: (() => void) | null = null; + const writeDraft = (k: string, body: unknown): Row => { + const row = { body, version: `draft-${++seq}` }; + drafts.set(k, row); + return row; + }; + const client: DraftPublishDoor['client'] = { + async save(type, name, body, options = {}) { + calls.push(['save', type, name, options]); + const k = key(type, name, options.packageId); + if (options.mode !== 'draft') { + const row = { body, version: `live-${++seq}` }; + live.set(k, row); + return { success: true, version: row.version }; + } + const current = drafts.get(k); + if (options.ifNoneMatch === '*' && current) throw conflict(current.version); + if (typeof options.ifMatch === 'string' && options.ifMatch !== current?.version) { + throw conflict(current?.version ?? null); + } + const row = writeDraft(k, body); + return { success: true, version: row.version, state: 'draft' }; + }, + async publish(type, name, options = {}) { + calls.push(['publish', type, name, options]); + if (pendingInterleave) { + const run = pendingInterleave; + pendingInterleave = null; + run(); + } + const k = key(type, name, options.packageId); + const draft = drafts.get(k); + if (options.draftVersion !== undefined && options.draftVersion !== draft?.version) { + throw conflict(draft?.version ?? null); + } + const active = live.get(k); + if (typeof options.ifMatch === 'string' && options.ifMatch !== active?.version) throw conflict(active?.version ?? null); + if (options.ifNoneMatch === '*' && active) throw conflict(active.version); + if (!draft) throw Object.assign(new Error('no draft'), { status: 404, code: 'NO_DRAFT' }); + const row = { body: draft.body, version: `live-${++seq}` }; + live.set(k, row); + drafts.delete(k); + return { success: true, version: row.version }; + }, + async reset(type, name, options = {}) { + calls.push(['reset', type, name, options]); + const k = key(type, name, options.packageId); + if (options.state === 'draft') { + const draft = drafts.get(k); + if (typeof options.ifMatch === 'string' && options.ifMatch !== draft?.version) throw conflict(draft?.version ?? null); + drafts.delete(k); + } else { + live.delete(k); + } + return { success: true }; + }, + async getDraft(type, name, options = {}) { + calls.push(['getDraft', type, name, options]); + const draft = drafts.get(key(type, name, options.packageId)); + return draft ? { type, name, item: draft.body, version: draft.version } : null; + }, + }; + return { + client, + // The doors answer what the console's client answers for these calls; its + // generic signatures are what the cast stands in for. + metadataClient: client as unknown as DraftPublishDoor['metadataClient'], + draftOf: (type, name, packageId) => drafts.get(key(type, name, packageId))?.body, + liveOf: (type, name, packageId) => live.get(key(type, name, packageId))?.body, + seedLive: (type, name, packageId, body) => { + const row = { body, version: `live-${++seq}` }; + live.set(key(type, name, packageId), row); + return row.version; + }, + interleave: (type, name, packageId, body) => { + pendingInterleave = () => { + writeDraft(key(type, name, packageId), body); + }; + }, + calls, + }; +} diff --git a/ui/packages/app-shell/src/views/__tests__/objectExtensionArrangementSave-36499.test.ts b/ui/packages/app-shell/src/views/__tests__/objectExtensionArrangementSave-36499.test.ts index 89a7e887601..93157f4ae8b 100644 --- a/ui/packages/app-shell/src/views/__tests__/objectExtensionArrangementSave-36499.test.ts +++ b/ui/packages/app-shell/src/views/__tests__/objectExtensionArrangementSave-36499.test.ts @@ -15,6 +15,7 @@ import { saveObjectExtensionArrangement, type ExtensionArrangementDoors, } from '../objectExtensionArrangementSave'; +import { draftPublishDoor } from './draftPublishDoor-37440'; const BASE = 'app.hotcrm'; const PAIR = 'app.hotcrm.custom'; @@ -176,3 +177,39 @@ describe("writing an installed object's arrangement into its pair (objectstack#3 expect(refused.refreshed).toHaveBeenCalledTimes(1); }); }); + +describe('the arrangement Save publishes only the draft it wrote (objectstack#37440)', () => { + const TYPE = 'object_extension'; + function doorDoors() { + const door = draftPublishDoor(); + const refreshed = vi.fn(); + const d: ExtensionArrangementDoors = { + listPackages: async () => new Map([[BASE, { writable: false }]]), + ensureCustomization: async () => ({ packageId: PAIR, writable: true }), + client: { + ...door.client, + get: async () => null, + layered: async () => ({ code: { name: 'lead' }, effective: { name: 'lead' } }), + }, + refreshed, + }; + return { door, d }; + } + const input = { objectName: 'lead', basePackageId: BASE, arrange: () => ({ relatedLists: ['task'] }) }; + + it("PIN: another writer's draft write between the save and its publish is refused, published by nobody, and kept", async () => { + const { door, d } = doorDoors(); + door.interleave(TYPE, 'lead', PAIR, { extend: 'lead', label: 'theirs' }); + await expect(saveObjectExtensionArrangement(input, TEXTS, d)).rejects.toThrow('pending draft'); + expect(door.liveOf(TYPE, 'lead', PAIR)).toBeUndefined(); + expect(door.draftOf(TYPE, 'lead', PAIR)).toEqual({ extend: 'lead', label: 'theirs' }); + expect(door.calls.find(([c]) => c === 'publish')?.[3]).toMatchObject({ packageId: PAIR, draftVersion: expect.any(String) }); + }); + + it('CONTROL: with no write in between, the same pinned publish takes the arrangement live', async () => { + const { door, d } = doorDoors(); + await saveObjectExtensionArrangement(input, TEXTS, d); + expect(door.liveOf(TYPE, 'lead', PAIR)).toEqual({ extend: 'lead', relatedLists: ['task'] }); + expect(door.draftOf(TYPE, 'lead', PAIR)).toBeUndefined(); + }); +}); diff --git a/ui/packages/app-shell/src/views/__tests__/recordTabsConfigSave-36499.test.ts b/ui/packages/app-shell/src/views/__tests__/recordTabsConfigSave-36499.test.ts index 4c292a6c575..5257dd1c2d3 100644 --- a/ui/packages/app-shell/src/views/__tests__/recordTabsConfigSave-36499.test.ts +++ b/ui/packages/app-shell/src/views/__tests__/recordTabsConfigSave-36499.test.ts @@ -18,6 +18,7 @@ const emitMetadataRefresh = vi.fn(); import { recordTabsCatalog, type RecordTabsDraft } from '../recordTabsConfigModel'; import { resolveRecordTabsSaveTarget, saveRecordTabs, type RecordTabsSaveDoors } from '../recordTabsConfigSave'; +import { draftPublishDoor } from './draftPublishDoor-37440'; const TEXTS = { notListed: 'not listed', pendingDraft: 'pending draft', notWritable: 'not writable', pairNotWritable: 'pair not writable' }; const PKG = 'app.crm'; @@ -127,3 +128,38 @@ describe("saving the record page's tabs (objectstack#36499)", () => { expect(resolveRecordTabsSaveTarget(PKG, new Map())).toBeNull(); }); }); + +describe('the tabs Save publishes only the draft it wrote (objectstack#37440)', () => { + function doorDoors() { + const door = draftPublishDoor(); + door.seedLive('object', 'account', PKG, { name: 'account', label: 'Account (live)' }); + const code = { name: 'account', label: 'Account', fields: {}, relatedLists: [{ list: 'contact', columns: ['name'] }], _packageId: PKG }; + const d: RecordTabsSaveDoors = { + listPackages: async () => new Map([[PKG, { writable: true }]]), + ensureCustomization: async (base) => ({ packageId: `${base}.custom`, writable: false }), + client: { ...door.client, get: async () => null, layered: async () => ({ code, effective: code }) }, + refreshed: emitMetadataRefresh, + }; + return { door, d }; + } + + it("PIN: another writer's draft write between the save and its publish is refused, published by nobody, and kept", async () => { + const { door, d } = doorDoors(); + door.interleave('object', 'account', PKG, { name: 'account', label: 'theirs' }); + await expect(saveRecordTabs({ objectName: 'account', packageId: PKG, draft: DRAFT, catalog }, TEXTS, d)).rejects.toThrow( + 'pending draft', + ); + // Nothing unreviewed went live, and the other writer's draft is not discarded. + expect(door.liveOf('object', 'account', PKG)).toEqual({ name: 'account', label: 'Account (live)' }); + expect(door.draftOf('object', 'account', PKG)).toEqual({ name: 'account', label: 'theirs' }); + const publish = door.calls.find(([c]) => c === 'publish'); + expect(publish?.[3]).toMatchObject({ packageId: PKG, draftVersion: expect.any(String) }); + }); + + it('CONTROL: with no write in between, the same pinned publish takes the saved tabs live', async () => { + const { door, d } = doorDoors(); + await saveRecordTabs({ objectName: 'account', packageId: PKG, draft: DRAFT, catalog }, TEXTS, d); + expect(door.liveOf('object', 'account', PKG)).toMatchObject({ relatedLists: ['task', { list: 'contact', columns: ['name'] }] }); + expect(door.draftOf('object', 'account', PKG)).toBeUndefined(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.test.tsx index a91331de548..668d9db228f 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.test.tsx @@ -30,11 +30,14 @@ import { draftPinOf, publishedPinOf, isPublishConflictKeptEditing, + isPublishDraftMoved, + heldDraftVersionOf, isDraftVersionConflict, isDraftReadRefused, readDraftForSave, type DraftConflictChoice, } from './DraftConflictDialog'; +import { draftPublishDoor } from '../__tests__/draftPublishDoor-37440'; interface SentPut { type: string; @@ -718,3 +721,67 @@ describe('DraftVersionGuard — a reload that keeps a pending draft keeps the pu expect(guard.publishedFor('object', NAME, PKG)).toBeNull(); }); }); + +describe("DraftVersionGuard — the Save's publish is pinned to the draft it wrote (objectstack#37440, rule 10)", () => { + const PIN_PKG = 'com.acme.crm'; + /** One buffer loaded over a live row, then its Save's guarded draft write. */ + async function savedBuffer(...answers: DraftConflictChoice[]) { + const door = draftPublishDoor(); + const live = door.seedLive('object', 'acme_task', PIN_PKG, { label: 'live' }); + const queue = [...answers]; + const ask = vi.fn(async () => queue.shift() ?? 'cancel'); + const guard = new DraftVersionGuard({ + client: () => door.client as never, + ask, + reload: vi.fn(), + notSaved: (c) => new Error(`not saved: ${c.type}/${c.name}`), + }); + guard.recordRead('object', 'acme_task', PIN_PKG, { ifNoneMatch: '*' }); + guard.recordPublished('object', 'acme_task', PIN_PKG, { ifMatch: live }); + expect(await guard.save('object', 'acme_task', { label: 'mine' }, { mode: 'draft', packageId: PIN_PKG })).toBe('saved'); + // The Save's own receipt, read right after its save, never a re-read. + const draftVersion = heldDraftVersionOf(guard)('object', 'acme_task', PIN_PKG); + expect(draftVersion).toEqual(expect.any(String)); + const publish = () => guard.publish(door.client as never, 'object', 'acme_task', { packageId: PIN_PKG, draftVersion }); + return { door, guard, ask, publish, draftVersion }; + } + + it("PIN: another writer's draft write before the publish is refused, nothing is asked, and the refusal is marked the draft's", async () => { + const { door, ask, publish } = await savedBuffer(); + door.interleave('object', 'acme_task', PIN_PKG, { label: 'theirs' }); + const err = await publish().catch((e: unknown) => e); + expect(isDraftVersionConflict(err)).toBe(true); + expect(isPublishDraftMoved(err)).toBe(true); + // Not a live change: the published-row dialog is not opened for it. + expect(ask).not.toHaveBeenCalled(); + expect(door.liveOf('object', 'acme_task', PIN_PKG)).toEqual({ label: 'live' }); + expect(door.draftOf('object', 'acme_task', PIN_PKG)).toEqual({ label: 'theirs' }); + }); + + it('the published row moved and the draft did not: still asked as a live change (rule 8), never marked the draft\'s', async () => { + const { door, ask, publish } = await savedBuffer('cancel'); + door.seedLive('object', 'acme_task', PIN_PKG, { label: 'published since' }); + const err = await publish().catch((e: unknown) => e); + expect(ask).toHaveBeenCalledWith({ type: 'object', name: 'acme_task', layer: 'published' }); + expect(isPublishDraftMoved(err)).toBe(false); + expect(isPublishConflictKeptEditing(err)).toBe(true); + expect(door.draftOf('object', 'acme_task', PIN_PKG)).toEqual({ label: 'mine' }); + }); + + it("an overwrite after a live change keeps the draft pin: the buffer's own draft goes live over the moved row", async () => { + const { door, publish, draftVersion } = await savedBuffer('overwrite'); + door.seedLive('object', 'acme_task', PIN_PKG, { label: 'published since' }); + expect(await publish()).toBe('published'); + expect(door.liveOf('object', 'acme_task', PIN_PKG)).toEqual({ label: 'mine' }); + const sent = door.calls.filter(([c]) => c === 'publish').map(([, , , o]) => o.draftVersion); + expect(sent).toEqual([draftVersion, draftVersion]); + }); + + it('CONTROL: with no write in between, the same pinned publish takes the buffer live', async () => { + const { door, ask, publish } = await savedBuffer(); + expect(await publish()).toBe('published'); + expect(ask).not.toHaveBeenCalled(); + expect(door.liveOf('object', 'acme_task', PIN_PKG)).toEqual({ label: 'mine' }); + expect(door.draftOf('object', 'acme_task', PIN_PKG)).toBeUndefined(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx b/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx index 84c84bb4356..eb8eba04b9c 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/DraftConflictDialog.tsx @@ -102,6 +102,20 @@ * reads no pending draft (the buffer is then the live row) takes the * fresh read's pin. A reload over a discarded draft re-reads the live row * and is pinned to it at once, as before. + * 10. objectstack#37440 — the Save's publish is also pinned to the DRAFT it + * promotes when its caller passes `draftVersion`: the version its own + * draft save's receipt returned (`heldDraftVersion` right after a guarded + * save), ⛔ never a fresh re-read, which would pin another writer's draft. + * A draft another writer changed in between is refused + * `409 METADATA_CONFLICT` and nothing is published. That refusal carries + * the same code as the published row's (rule 8) and does not say which + * pin refused, so the guard reads the draft at the address once: still + * the pinned version, the live row moved and rule 8 asks; moved, gone, or + * unreadable, the refusal is the draft's, nothing is asked, and it is + * thrown marked ({@link isPublishDraftMoved}): the caller ⛔ never + * discards that draft — it now holds the other writer's change — and the + * next Save's draft write, still pinned to the old receipt, is refused and + * asked about by rule 4. */ import * as React from 'react'; @@ -121,7 +135,9 @@ import { t, tFormat, translateMetadataType, useMetadataLocale } from './i18n.js' export { isPublishConflictKeptEditing, + isPublishDraftMoved, isDraftVersionConflict, + draftReceiptVersion, draftPinOf, publishedPinOf, isDraftReadRefused, @@ -174,6 +190,9 @@ export function useDraftSaveGuard(client: Pick, onReload React.useLayoutEffect(() => { guard.bind({ client: () => client, reload: onReload, notSaved: notSavedIn(locale) }); }); + // objectstack#37440 — one function for the guard's life, as the guard's own + // members are: a Save callback may name it among its dependencies. + const [heldDraftVersion] = React.useState(() => heldDraftVersionOf(guard)); // A dialog left open by an unmount answers "keep editing": nothing is sent. const pendingRef = React.useRef(pending); React.useLayoutEffect(() => { @@ -191,7 +210,7 @@ export function useDraftSaveGuard(client: Pick, onReload forget: guard.forget, recordPublished: guard.recordPublished, publish: guard.publish, - heldDraftVersion: heldDraftVersionOf(guard), + heldDraftVersion, dialog: , }; } diff --git a/ui/packages/app-shell/src/views/metadata-admin/MetadataListCreateDialog.tsx b/ui/packages/app-shell/src/views/metadata-admin/MetadataListCreateDialog.tsx index 6a14777a27f..7736e345e35 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/MetadataListCreateDialog.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/MetadataListCreateDialog.tsx @@ -32,6 +32,7 @@ import { OWD_OPTION_DESC_KEY, OWD_OPTION_LABEL_KEY } from '../studio-design/Data import { buildFlowSkeleton, buildObjectSkeleton } from '../studio-design/skeletons.js'; import { ensureCustomizationPackage, fetchPackages, prefixObjectName } from '../studio-design/packages-io.js'; import { publishCreated, publishSavedItem } from '../studio-design/studioSaveBar.js'; +import { draftReceiptVersion } from './DraftConflictDialog.js'; import { loadPackageSurfaces } from '../studio-design/packageSurfaces.js'; import { studioItemPath } from '../studio-design/studioAddress.js'; import { plainRefusal, type StudioRefusal } from '../studio-design/metadataError.js'; @@ -137,11 +138,22 @@ function ObjectCreate({ open, onOpenChange, packageId, inPair, locale, onCreated return; } const body = buildObjectSkeleton(name, label, t('engine.studio.data.nameFieldLabel', locale), owd); - await client.save('object', name, body, { mode: 'draft', packageId: target.packageId, ifNoneMatch: '*', surface: 'studio' }); + const receipt = await client.save('object', name, body, { + mode: 'draft', + packageId: target.packageId, + ifNoneMatch: '*', + surface: 'studio', + }); // objectstack#36726 — pinned `If-None-Match: *`, as the flow create is: // an object another writer published under the name since the check - // above is refused, not replaced. - const live = await publishSavedItem(client, { type: 'object', name, packageId: target.packageId }, false, publishCreated); + // above is refused, not replaced. objectstack#37440 — and to the draft + // this create wrote (its receipt). + const live = await publishSavedItem( + client, + { type: 'object', name, packageId: target.packageId, draftVersion: draftReceiptVersion(receipt) }, + false, + publishCreated, + ); if (!live.ok) { if ('error' in live) setError(plainRefusal(live.error)); return; @@ -277,12 +289,23 @@ function FlowCreate({ open, onOpenChange, packageId, inPair, locale, onCreated, start, ); const target = await createTarget(packageId, inPair, null); - await client.save('flow', name, skeleton, { mode: 'draft', packageId: target.packageId, ifNoneMatch: '*', surface: 'studio' }); + const receipt = await client.save('flow', name, skeleton, { + mode: 'draft', + packageId: target.packageId, + ifNoneMatch: '*', + surface: 'studio', + }); // objectstack#36726 — pinned `If-None-Match: *`, as the Automations // pillar's create was (objectstack#36903 moved every flow create here): // a flow another writer published under the name since the check above - // is refused, not replaced. - const live = await publishSavedItem(client, { type: 'flow', name, packageId: target.packageId }, false, publishCreated); + // is refused, not replaced. objectstack#37440 — and to the draft this + // create wrote (its receipt). + const live = await publishSavedItem( + client, + { type: 'flow', name, packageId: target.packageId, draftVersion: draftReceiptVersion(receipt) }, + false, + publishCreated, + ); if (!live.ok) { if ('error' in live) setError(plainRefusal(live.error)); return; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.tsx b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.tsx index eaa04cdb317..2453e196625 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.tsx @@ -1013,6 +1013,8 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, save: saveVersioned, recordRead: recordSetRead, forget: forgetSetVersion, + // objectstack#37440 — the version the set's own Save wrote, which pins its publish. + heldDraftVersion: heldSetDraftVersion, dialog: draftConflictDialog, } = useDraftSaveGuard(client, reloadSet); // The header's label as the published list serves it: that read is @@ -1784,7 +1786,12 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, // objectstack#36511 — the draft just written is published alone, so // the set is live; a refused publish drops the draft this Save wrote // (one that was pending before stays, listed under Changes). - const live = await publishSavedItem(client, { type, name: payload.name, packageId }, hadDraftRef.current); + // objectstack#37440 — pinned to the draft this Save just wrote (its receipt). + const live = await publishSavedItem( + client, + { type, name: payload.name, packageId, draftVersion: heldSetDraftVersion(type, payload.name, packageId) }, + hadDraftRef.current, + ); if (!live.ok) { hadDraftRef.current = !live.draftDiscarded; if (live.draftDiscarded) recordSetRead(type, payload.name, packageId, { ifNoneMatch: '*' }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index e7d48dbac20..685b5b1251e 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -117,7 +117,13 @@ import { type RichMetadataTypeEntry, } from './useMetadata.js'; // objectui#11773 — the draft save's optimistic-concurrency guard and its dialog. -import { isPublishConflictKeptEditing, publishedPinOf, readDraftForSave, useDraftSaveGuard } from './DraftConflictDialog.js'; +import { + draftReceiptVersion, + isPublishConflictKeptEditing, + publishedPinOf, + readDraftForSave, + useDraftSaveGuard, +} from './DraftConflictDialog.js'; // objectstack#36902 — Save takes effect at once; the AI draft's notice is the designers'. import { isAiDraft, publishDetailSave } from './detailSaveAtOnce.js'; import { StudioAiDraftNotice } from '../studio-design/StudioAiDraftNotice.js'; @@ -1070,6 +1076,8 @@ function MetadataResourceEditPageImpl({ forget: forgetDraftVersion, recordPublished: recordPublishedVersion, publish: publishPinned, + // objectstack#37440 — the version the page's own Save wrote, which pins its publish. + heldDraftVersion, dialog: draftConflictDialog, } = useDraftSaveGuard(client, reloadFromServer); // objectstack#36902 — the pending draft's per-key provenance (`draftChanges`), @@ -2115,15 +2123,20 @@ function MetadataResourceEditPageImpl({ // a draft instead of writing over it, and reads it as a create. A save of // the item this editor loaded sends the pin its load or last save held. let wroteDraft = true; + // objectstack#37440 — the version this Save's own draft write returned, which pins its publish. + let draftVersion: string | undefined; if (createMode) { // objectui#7611 — a type whose edit page writes the live item creates // it live too (`createLive`): nothing is left in the draft to publish. const live = !!config.createLive && !activePackage; - await client.save(type, savedName, itemToSave, { ...(live ? { force } : saveOptions), ifNoneMatch: '*' }); + const receipt = await client.save(type, savedName, itemToSave, { ...(live ? { force } : saveOptions), ifNoneMatch: '*' }); wroteDraft = !live; + draftVersion = draftReceiptVersion(receipt); } else if ((await saveDraftVersioned(type, savedName, itemToSave, saveOptions)) === 'reloaded') { // The author chose the saved version; the load effect replaces the draft. return; + } else { + draftVersion = heldDraftVersion(type, savedName, activePackage); } if (wroteDraft) { // objectstack#34818 — a flow whose Problems tab lists the draft's @@ -2134,7 +2147,13 @@ function MetadataResourceEditPageImpl({ try { live = await publishDetailSave( client, - { type, name: savedName, ...(activePackage ? { packageId: activePackage } : {}), ...memberScope }, + { + type, + name: savedName, + ...(activePackage ? { packageId: activePackage } : {}), + ...memberScope, + ...(draftVersion ? { draftVersion } : {}), + }, hadDraft, // objectstack#36601 — pinned to the published row the load read; a // create read nothing, and its draft's first-write pin stands. diff --git a/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce-37440.test.ts b/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce-37440.test.ts new file mode 100644 index 00000000000..d2390a98f0b --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce-37440.test.ts @@ -0,0 +1,69 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37440 — the generic item page's Save (`publishDetailSave`) + * pins its publish to the draft the Save itself wrote (`target.draftVersion`, + * its receipt), guarded or not. A draft another writer changed in between is + * refused and kept pending, never published and never taken back; with no + * write in between, the Save goes live as before. + */ + +import { describe, expect, it, vi } from 'vitest'; +import { publishDetailSave } from './detailSaveAtOnce'; +import { DraftVersionGuard, draftReceiptVersion, isPublishDraftMoved } from './DraftConflictDialog'; +import { draftPublishDoor } from '../__tests__/draftPublishDoor-37440'; + +const PKG = 'com.acme.crm'; +const TARGET = { type: 'flow', name: 'acme_flow', packageId: PKG }; + +async function savedDraft(door: ReturnType): Promise { + return draftReceiptVersion(await door.client.save(TARGET.type, TARGET.name, { label: 'mine' }, { mode: 'draft', packageId: PKG })); +} + +function guardOver(door: ReturnType) { + const ask = vi.fn(async () => 'cancel' as const); + const guard = new DraftVersionGuard({ + client: () => door.client as never, + ask, + reload: vi.fn(), + notSaved: () => new Error('not saved'), + }); + return { guard, ask }; +} + +describe("the item page's Save publishes only the draft it wrote (objectstack#37440)", () => { + it("PIN (unguarded): another writer's draft write before the publish is refused, published by nobody, and kept", async () => { + const door = draftPublishDoor(); + const draftVersion = await savedDraft(door); + door.interleave(TARGET.type, TARGET.name, PKG, { label: 'theirs' }); + const outcome = await publishDetailSave(door.metadataClient, { ...TARGET, draftVersion }, false); + expect(outcome).toMatchObject({ kind: 'refused', draftDiscarded: false }); + expect(door.liveOf(TARGET.type, TARGET.name, PKG)).toBeUndefined(); + expect(door.draftOf(TARGET.type, TARGET.name, PKG)).toEqual({ label: 'theirs' }); + expect(door.calls.some(([c]) => c === 'reset')).toBe(false); + expect(door.calls.find(([c]) => c === 'publish')?.[3]).toEqual({ packageId: PKG, draftVersion }); + }); + + it("PIN (guarded): the same, with nothing asked — the refusal is the draft's, not a live change", async () => { + const door = draftPublishDoor(); + const draftVersion = await savedDraft(door); + const { guard, ask } = guardOver(door); + door.interleave(TARGET.type, TARGET.name, PKG, { label: 'theirs' }); + const outcome = await publishDetailSave(door.metadataClient, { ...TARGET, draftVersion }, false, guard.publish); + expect(outcome.kind).toBe('refused'); + expect(outcome.kind === 'refused' && isPublishDraftMoved(outcome.error)).toBe(true); + expect(ask).not.toHaveBeenCalled(); + expect(door.draftOf(TARGET.type, TARGET.name, PKG)).toEqual({ label: 'theirs' }); + expect(door.calls.some(([c]) => c === 'reset')).toBe(false); + }); + + it('CONTROL: with no write in between, the same pinned publish takes the Save live, guarded and not', async () => { + for (const guarded of [false, true]) { + const door = draftPublishDoor(); + const draftVersion = await savedDraft(door); + const pinned = guarded ? guardOver(door).guard.publish : undefined; + expect(await publishDetailSave(door.metadataClient, { ...TARGET, draftVersion }, false, pinned)).toEqual({ kind: 'published' }); + expect(door.liveOf(TARGET.type, TARGET.name, PKG)).toEqual({ label: 'mine' }); + } + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts b/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts index ff799e26d45..df7504f66b8 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts @@ -25,12 +25,18 @@ * would be re-read as the buffer and published by the next Save. * - Every path tells the ledger (`emitMetadataRefresh`), so Changes and the * app re-read what went live. + * - objectstack#37440 — `draftVersion`, the version the Save's OWN draft + * write returned, pins the publish to that draft: a draft another writer + * changed in between is refused and nothing is published on their behalf. + * That draft now holds the other writer's change and is ⛔ never taken + * back; every take-back of the Save's own draft is pinned to the same + * version (`If-Match`), so the server removes only that draft. */ import type { DraftChange, MetadataClient } from '@object-ui/data-objectstack'; import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; import { isAgentDraftSurface } from '../studio-design/StudioDraftMark.js'; -import type { DraftSaveGuard } from './draftVersionGuard.js'; +import { isDraftVersionConflict, isPublishDraftMoved, type DraftSaveGuard } from './draftVersionGuard.js'; /** The item a Save wrote, at the address its draft save wrote it. */ export interface DetailPublishTarget { @@ -40,6 +46,12 @@ export interface DetailPublishTarget { packageId?: string; /** The bundle member the draft belongs to; absent for the canonical one. */ member?: string; + /** + * objectstack#37440 — the version the Save's own draft write returned (its + * receipt's `version`), which pins the publish to that draft. Absent, the + * publish goes unpinned, as before. + */ + draftVersion?: string; } /** What {@link publishDetailSave} did. */ @@ -53,7 +65,7 @@ export type DetailPublishOutcome = /** Make the draft a Save just wrote live (see the module docblock). */ export async function publishDetailSave( - client: Pick, + client: Pick, target: DetailPublishTarget, hadDraft: boolean, pinned?: DraftSaveGuard['publish'], @@ -62,23 +74,33 @@ export async function publishDetailSave( ...(target.packageId ? { packageId: target.packageId } : {}), ...(target.member ? { member: target.member } : {}), }; + const { draftVersion } = target; + const publishScope = draftVersion ? { ...scope, draftVersion } : scope; + // The refusal is the draft pin's: the guard said so, or no other pin was sent. + const draftMoved = (error: unknown): boolean => + isPublishDraftMoved(error) || (!pinned && !!draftVersion && isDraftVersionConflict(error)); let draftDiscarded = false; const takeBack = async (): Promise => { - await client.reset(target.type, target.name, { state: 'draft', ...scope }); + await client.reset(target.type, target.name, { + state: 'draft', + ...scope, + ...(draftVersion ? { ifMatch: draftVersion } : {}), + }); draftDiscarded = true; }; try { if (pinned) { - const outcome = await pinned(client, target.type, target.name, scope, hadDraft ? undefined : takeBack); + const outcome = await pinned(client, target.type, target.name, publishScope, hadDraft ? undefined : takeBack); if (outcome === 'reloaded') { emitMetadataRefresh(); return { kind: 'reloaded', draftDiscarded }; } } else { - await client.publish(target.type, target.name, scope); + await client.publish(target.type, target.name, publishScope); } } catch (error) { - if (!hadDraft && !draftDiscarded) { + // objectstack#37440 — another writer's change is in the draft now: kept. + if (!hadDraft && !draftDiscarded && !draftMoved(error)) { try { await takeBack(); } catch (discardError) { diff --git a/ui/packages/app-shell/src/views/metadata-admin/draftVersionGuard.ts b/ui/packages/app-shell/src/views/metadata-admin/draftVersionGuard.ts index 5f682e8b393..83d1c6b0fe6 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/draftVersionGuard.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/draftVersionGuard.ts @@ -58,6 +58,18 @@ export function isPublishConflictKeptEditing(err: unknown): boolean { return typeof err === 'object' && err !== null && KEPT_EDITING.has(err); } +const DRAFT_MOVED = new WeakSet(); + +/** + * objectstack#37440 — `err` is a guarded publish's refusal of the DRAFT pin + * (rule 10): the draft the Save wrote was changed by another writer before + * its publish, so nothing went live and the draft now holds that writer's + * change. The caller keeps it pending, ⛔ never discards it. + */ +export function isPublishDraftMoved(err: unknown): boolean { + return typeof err === 'object' && err !== null && DRAFT_MOVED.has(err); +} + /** * The version-conflict refusal of the `/meta` draft door, told apart from the * door's OTHER 409 (`DESTRUCTIVE_CHANGE`) by its code, never by its prose. @@ -191,6 +203,44 @@ function receiptVersion(receipt: unknown): string | null { return typeof version === 'string' && version.length > 0 ? version : null; } +/** + * objectstack#37440 — the version a draft save's receipt returned, as the + * `draftVersion` its publish is pinned to (and the `If-Match` a take-back of + * that draft is pinned to); `undefined` when the receipt carries none, and + * both then go unpinned, as before. + */ +export function draftReceiptVersion(receipt: unknown): string | undefined { + return receiptVersion(receipt) ?? undefined; +} + +/** + * objectstack#37440 — whether the draft at the publish's address still is the + * version `draftVersion` names (rule 10). Read once, after a refusal, only to + * tell which pin refused; ⛔ never a pin. A draft that moved, a draft no longer + * pending and a read that fails all answer `false`: a refusal that cannot be + * told apart is treated as the draft's, so nothing is asked and nothing is + * discarded. + */ +async function draftStillAt( + client: Pick, + type: string, + name: string, + options: { packageId?: string; member?: string }, + draftVersion: string, +): Promise { + try { + const pin = draftPinOf( + await client.getDraft(type, name, { + ...(options.packageId ? { packageId: options.packageId } : {}), + ...(options.member ? { member: options.member } : {}), + }), + ); + return !!pin && 'ifMatch' in pin && pin.ifMatch === draftVersion; + } catch { + return false; + } +} + /** `options` sent with `pin` in place of whatever precondition they carried. */ function pinned(options: MetadataClientSaveOptions, pin: DraftPin | null): MetadataClientSaveOptions { if (!pin) return options; @@ -299,10 +349,11 @@ export class DraftVersionGuard { * ({@link BeforeReloadOutcome}); one that answers nothing is `'discarded'`. */ publish = async ( - client: Pick, + client: Pick, type: string, name: string, - options: { packageId?: string; member?: string } = {}, + // objectstack#37440 — `draftVersion`: the draft the caller's own save wrote (rule 10). + options: { packageId?: string; member?: string; draftVersion?: string } = {}, beforeReload?: () => Promise, ): Promise<'published' | 'reloaded'> => { const key = itemKey(type, name, options.packageId); @@ -318,6 +369,11 @@ export class DraftVersionGuard { return 'published'; } catch (err) { if (!isDraftVersionConflict(err)) throw err; + // objectstack#37440 — rule 10: the draft pin refused, not the live row's. + if (options.draftVersion && !(await draftStillAt(client, type, name, options, options.draftVersion))) { + DRAFT_MOVED.add(err as object); + throw err; + } const conflict: DraftConflict = { type, name, layer: 'published' }; const choice = await this.deps.ask(conflict); if (choice === 'reload') { diff --git a/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts b/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts index 5256e87b9cd..7feb1145711 100644 --- a/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts +++ b/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts @@ -45,7 +45,7 @@ import { stripReadDecorations } from '@objectstack/spec/kernel'; import type { CustomArrangementKey, ObjectActionLayout } from '@objectstack/spec/data'; -import { isDraftVersionConflict } from './metadata-admin/draftVersionGuard.js'; +import { draftReceiptVersion, isDraftVersionConflict } from './metadata-admin/draftVersionGuard.js'; import { OBJECT_EXTENSION_TYPE, objectExtensionBodyOf, type ObjectExtensionBody } from './studio-design/customizeOverride.js'; import type { EnsuredCustomizationPackage, ListedPackageManifest } from './studio-design/packages-io.js'; @@ -57,7 +57,7 @@ export interface ExtensionArrangementDoors { get: (type: string, name: string, options: { packageId?: string }) => Promise; layered: (type: string, name: string, options: { packageId?: string }) => Promise; save: (type: string, name: string, body: unknown, options: Record) => Promise; - publish: (type: string, name: string, options: { packageId?: string }) => Promise; + publish: (type: string, name: string, options: { packageId?: string; draftVersion?: string }) => Promise; reset: (type: string, name: string, options: Record) => Promise; }; /** Announces the object changed, so the console reads it again. */ @@ -151,21 +151,37 @@ export async function saveObjectExtensionArrangement( objectName, arrange({ extension, object: storedObjectOf(objectRead) }), ); + let draftVersion: string | undefined; try { - await doors.client.save(OBJECT_EXTENSION_TYPE, objectName, body, { mode: 'draft', packageId: target, ifNoneMatch: '*' }); + draftVersion = draftReceiptVersion( + await doors.client.save(OBJECT_EXTENSION_TYPE, objectName, body, { mode: 'draft', packageId: target, ifNoneMatch: '*' }), + ); } catch (err) { if (isDraftVersionConflict(err)) throw Object.assign(new Error(texts.pendingDraft), { cause: err }); throw err; } + // objectstack#37440 — the publish is pinned to the draft this save wrote + // (its receipt's version): a draft another writer changed in between is + // refused, and nothing is published on their behalf. + const pin = draftVersion ? { draftVersion } : {}; try { - await doors.client.publish(OBJECT_EXTENSION_TYPE, objectName, { packageId: target }); + await doors.client.publish(OBJECT_EXTENSION_TYPE, objectName, { packageId: target, ...pin }); } catch (err) { + // The discard is pinned to the same draft: one that moved holds the + // other writer's change, is refused, and stays pending, said as such. + let moved = false; try { - await doors.client.reset(OBJECT_EXTENSION_TYPE, objectName, { state: 'draft', packageId: target }); + await doors.client.reset(OBJECT_EXTENSION_TYPE, objectName, { + state: 'draft', + packageId: target, + ...(draftVersion ? { ifMatch: draftVersion } : {}), + }); } catch (discardErr) { - console.error('[object-extension] a refused publish left the extension draft pending:', discardErr); + moved = !!draftVersion && isDraftVersionConflict(discardErr); + if (!moved) console.error('[object-extension] a refused publish left the extension draft pending:', discardErr); } doors.refreshed(); + if (moved) throw Object.assign(new Error(texts.pendingDraft), { cause: err }); throw err; } doors.refreshed(); diff --git a/ui/packages/app-shell/src/views/recordTabsConfigSave.ts b/ui/packages/app-shell/src/views/recordTabsConfigSave.ts index 9b101db38fb..730873966c9 100644 --- a/ui/packages/app-shell/src/views/recordTabsConfigSave.ts +++ b/ui/packages/app-shell/src/views/recordTabsConfigSave.ts @@ -33,7 +33,7 @@ import { stripReadDecorations } from '@objectstack/spec/kernel'; import { emitMetadataRefresh } from '../assistant/assistantBus.js'; -import { isDraftVersionConflict } from './metadata-admin/draftVersionGuard.js'; +import { draftReceiptVersion, isDraftVersionConflict } from './metadata-admin/draftVersionGuard.js'; import { ensureCustomizationPackage, fetchListedPackageManifests, @@ -53,7 +53,7 @@ export interface RecordTabsSaveDoors { get: (type: string, name: string, options: { packageId?: string }) => Promise; layered: (type: string, name: string, options: { packageId?: string }) => Promise; save: (type: string, name: string, body: unknown, options: Record) => Promise; - publish: (type: string, name: string, options: { packageId?: string }) => Promise; + publish: (type: string, name: string, options: { packageId?: string; draftVersion?: string }) => Promise; reset: (type: string, name: string, options: Record) => Promise; }; /** Announces the object changed, so the console reads it again (`emitMetadataRefresh`). */ @@ -156,21 +156,37 @@ export async function saveRecordTabs( const entries = recordTabsEntries(draft, base, catalog, initial); const { relatedLists: _previous, ...rest } = stored; const body: Record = { ...rest, name: objectName, ...(entries ? { relatedLists: entries } : {}) }; + let draftVersion: string | undefined; try { - await doors.client.save('object', objectName, body, { mode: 'draft', packageId: target.packageId, ifNoneMatch: '*' }); + draftVersion = draftReceiptVersion( + await doors.client.save('object', objectName, body, { mode: 'draft', packageId: target.packageId, ifNoneMatch: '*' }), + ); } catch (err) { if (isDraftVersionConflict(err)) throw Object.assign(new Error(texts.pendingDraft), { cause: err }); throw err; } + // objectstack#37440 — the publish is pinned to the draft this save wrote + // (its receipt's version): a draft another writer changed in between is + // refused, and nothing is published on their behalf. + const pin = draftVersion ? { draftVersion } : {}; try { - await doors.client.publish('object', objectName, { packageId: target.packageId }); + await doors.client.publish('object', objectName, { packageId: target.packageId, ...pin }); } catch (err) { + // The discard is pinned to the same draft: one that moved holds the + // other writer's change, is refused, and stays pending, said as such. + let moved = false; try { - await doors.client.reset('object', objectName, { state: 'draft', packageId: target.packageId }); + await doors.client.reset('object', objectName, { + state: 'draft', + packageId: target.packageId, + ...(draftVersion ? { ifMatch: draftVersion } : {}), + }); } catch (discardErr) { - console.error('[record-tabs] a refused publish left the object draft pending:', discardErr); + moved = !!draftVersion && isDraftVersionConflict(discardErr); + if (!moved) console.error('[record-tabs] a refused publish left the object draft pending:', discardErr); } doors.refreshed(); + if (moved) throw Object.assign(new Error(texts.pendingDraft), { cause: err }); throw err; } doors.refreshed(); diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.customizeFlow-28570.test.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.customizeFlow-28570.test.tsx index 9955c93c2db..8d175f3a885 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.customizeFlow-28570.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.customizeFlow-28570.test.tsx @@ -359,7 +359,10 @@ describe('Customize a read-only base’s flow into its pair (objectstack#28570)' // Then that one flow is published at the pair: the override is live. Read // at the base, the Save takes the pair to hold no live flow of the name, // and its publish asserts so (objectstack#36726). - await waitFor(() => expect(srv.publishes).toEqual([{ name: FLOW_NAME, opts: { packageId: PAIR, ifNoneMatch: '*' } }])); + await waitFor(() => expect(srv.publishes).toEqual([ + // objectstack#37440 — and to the draft this Save wrote (its receipt). + { name: FLOW_NAME, opts: { packageId: PAIR, ifNoneMatch: '*', draftVersion: expect.any(String) } }, + ])); expect(srv.ensure).toEqual([201]); const [saved] = srv.saves; expect(saved!.name).toBe(FLOW_NAME); diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx index 79885d93a7c..4bdc2189bd1 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.tsx @@ -338,6 +338,8 @@ export function AutomationsPillar({ // objectstack#36726 — and the published flow the buffer was loaded at, for the Save's publish. recordPublished: recordFlowPublished, publish: publishFlow, + // objectstack#37440 — the version the buffer's own Save wrote, which pins its publish. + heldDraftVersion: heldFlowDraftVersion, dialog: flowConflictDialog, } = useDraftSaveGuard(client, reloadFlowDraft); const [selection, setSelection] = React.useState(null); @@ -747,7 +749,13 @@ export function AutomationsPillar({ // objectstack#36726 — pinned to the published flow this buffer was loaded at. const live = await publishSavedItem( client, - { type: 'flow', name: current.name, packageId: target.packageId ?? null }, + { + type: 'flow', + name: current.name, + packageId: target.packageId ?? null, + // objectstack#37440 — and to the draft this Save just wrote (its receipt). + draftVersion: heldFlowDraftVersion('flow', current.name, target.packageId), + }, hadDraft, publishFlow, ); @@ -785,7 +793,7 @@ export function AutomationsPillar({ } finally { setSaving(false); } - }, [saveFlowDraft, publishFlow, client, current, draft, hasDraft, draftPackageId, locale, rereadFlowVerdict, readOnly, pairForFlow, recordFlowRead, recordFlowPublished]); + }, [saveFlowDraft, publishFlow, heldFlowDraftVersion, client, current, draft, hasDraft, draftPackageId, locale, rereadFlowVerdict, readOnly, pairForFlow, recordFlowRead, recordFlowPublished]); // objectui#11786 — an edit that leaves a step's required input out (a step // just added, before it is filled in) is held, not sent: the server would // refuse the flow with a 422 naming that input. The step's inspector hints the @@ -899,7 +907,13 @@ export function AutomationsPillar({ // objectstack#36726 — pinned to the published flow this buffer was loaded at, as the Save is. const live = await publishSavedItem( client, - { type: 'flow', name: flowName, packageId: draftPackageId ?? null }, + { + type: 'flow', + name: flowName, + packageId: draftPackageId ?? null, + // objectstack#37440 — and to the draft the flip just wrote (its receipt). + draftVersion: heldFlowDraftVersion('flow', flowName, draftPackageId), + }, hadDraft, publishFlow, ); @@ -928,7 +942,7 @@ export function AutomationsPillar({ } finally { setSaving(false); } - }, [saveFlowDraft, publishFlow, client, current, draft, draftFor, hasDraft, draftPackageId, locale, readOnly, recordFlowRead, rereadFlowVerdict]); + }, [saveFlowDraft, publishFlow, heldFlowDraftVersion, client, current, draft, draftFor, hasDraft, draftPackageId, locale, readOnly, recordFlowRead, rereadFlowVerdict]); // #27356 row 19 — Delete flow (`FlowItemMoreMenu`): the autosave disarmed, // the draft (so none is left to publish the flow back) and then the flow diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActions-30088.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActions-30088.test.tsx index 9f7c05f5bab..1fa07580efb 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActions-30088.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActions-30088.test.tsx @@ -284,7 +284,8 @@ describe('Studio adds an action to an installed app’s object, in its customiza expect(opts).toMatchObject({ mode: 'draft', packageId: PAIR, ifNoneMatch: '*' }); // Then that one action is published at the pair: live at once, asserting // no published action of its name (objectstack#36726). - expect(mockClient.publish).toHaveBeenCalledWith('action', name, { packageId: PAIR, ifNoneMatch: '*' }); + // objectstack#37440 — pinned to the draft this Save wrote (its receipt), too. + expect(mockClient.publish).toHaveBeenCalledWith('action', name, { packageId: PAIR, ifNoneMatch: '*', draftVersion: expect.any(String) }); expect(mockClient.save.mock.invocationCallOrder[0]).toBeLessThan(mockClient.publish.mock.invocationCallOrder[0]); expect(ensure).toHaveBeenCalledTimes(1); expect(saves().filter(([type]) => type === 'object')).toHaveLength(0); @@ -323,7 +324,7 @@ describe('Studio adds an action to an installed app’s object, in its customiza // The read's decorations are not written back. expect(body).not.toHaveProperty('_packageId'); expect(opts).toMatchObject({ mode: 'draft', packageId: PAIR }); - expect(mockClient.publish).toHaveBeenCalledWith('action', KEPT.name, { packageId: PAIR }); + expect(mockClient.publish).toHaveBeenCalledWith('action', KEPT.name, { packageId: PAIR, draftVersion: expect.any(String) }); expect(saves().filter(([type]) => type === 'object')).toHaveLength(0); fireEvent.click(screen.getByRole('button', { name: L('engine.studio.actions.delete') })); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.tsx index 45b057d9acc..e9924602f60 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.tsx @@ -695,6 +695,8 @@ export function DataPillar({ // objectstack#36601 — and the published row the buffer was loaded at, for the Save's publish. recordPublished: recordObjPublished, publish: publishObj, + // objectstack#37440 — the version the buffer's own Save wrote, which pins its publish. + heldDraftVersion: heldObjDraftVersion, dialog: objConflictDialog, } = useDraftSaveGuard(client, reloadObjDraft); // objectstack#28575 — the extension buffer's own guard, pinned by its draft read at the pair. @@ -705,6 +707,7 @@ export function DataPillar({ // objectstack#36726 — and the pair's published extension row, for the Save's publish. recordPublished: recordExtPublished, publish: publishExt, + heldDraftVersion: heldExtDraftVersion, dialog: extConflictDialog, } = useDraftSaveGuard(client, reloadExt); // The pair a READ names is the surface's (`StudioBaseCustomization.pairId`), @@ -1192,8 +1195,14 @@ export function DataPillar({ objStoredRef.current = draft; setHasDraft(true); setSaving('publish'); - // objectstack#36601 — pinned to the published row this buffer was loaded at. - const live = await publishSavedItem(client, { type: 'object', name, packageId: to }, hadDraft, publishObj); + // objectstack#36601 — pinned to the published row this buffer was loaded at; + // objectstack#37440 — and to the draft this Save just wrote (its receipt). + const live = await publishSavedItem( + client, + { type: 'object', name, packageId: to, draftVersion: heldObjDraftVersion('object', name, to) }, + hadDraft, + publishObj, + ); // The published row moved and the author chose to reload: the load replaces the buffer. if (!live.ok && 'reloaded' in live) return { kind: 'declined' }; if (!live.ok) { @@ -1229,7 +1238,7 @@ export function DataPillar({ } finally { setSaving(false); } - }, [saveObjDraft, recordObjRead, publishObj, client, current, objDraft, hasDraft, publishedFieldNames, packageId, locale]); + }, [saveObjDraft, recordObjRead, publishObj, heldObjDraftVersion, client, current, objDraft, hasDraft, publishedFieldNames, packageId, locale]); // objectstack#34931 — Cancel keeps what the refused save would have lost: // each field a finding names goes back as the server holds it, and nothing @@ -1321,7 +1330,8 @@ export function DataPillar({ // objectstack#36726 — pinned to the published extension row this buffer was loaded at. const live = await publishSavedItem( client, - { type: OBJECT_EXTENSION_TYPE, name, packageId: pair }, + // objectstack#37440 — pinned to the draft this Save just wrote (its receipt). + { type: OBJECT_EXTENSION_TYPE, name, packageId: pair, draftVersion: heldExtDraftVersion(OBJECT_EXTENSION_TYPE, name, pair) }, hadDraft, publishExt, ); @@ -1355,7 +1365,7 @@ export function DataPillar({ } finally { setSaving(false); } - }, [extOpen, customization, extPairFor, saveExtDraft, recordExtRead, recordExtPublished, publishExt, client, extHasDraft, locale]); + }, [extOpen, customization, extPairFor, saveExtDraft, recordExtRead, recordExtPublished, publishExt, heldExtDraftVersion, client, extHasDraft, locale]); // An edit of the folded object's fields, written into the extension: an // extension field whole, a base field's whitelisted change as its patch. const onExtFieldsPatch = React.useCallback( diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.draftPinned-37515.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.draftPinned-37515.test.tsx index 478a1a89941..ca060c4e86d 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.draftPinned-37515.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.draftPinned-37515.test.tsx @@ -72,6 +72,10 @@ interface Server { draftReadPackages: Array; /** Run once when the Save reads `name`'s layers: another writer acting in the Save's own window. */ onSaveLayers: Map void>; + /** objectstack#37440 — run once right before `name`'s next publish reaches the door: another writer in between. */ + onPublish: Map void>; + /** objectstack#37440 — the `draftVersion` each publish named, in order. */ + publishDraftPins: Array; /** Held list reads, released by the test (the load-sequencing case). */ listGates: Deferred[]; seq: number; @@ -113,6 +117,8 @@ function newServer(): Server { resets: [], draftReadPackages: [], onSaveLayers: new Map(), + onPublish: new Map(), + publishDraftPins: [], listGates: [], seq: 0, }; @@ -163,8 +169,16 @@ function makeClient(server: Server, saving: { on: boolean }) { server.draftVersions.set(name, version); return { success: true, version, state: 'draft' }; }, - publish: async (_t: string, name: string, opts?: { ifMatch?: string; ifNoneMatch?: '*' }) => { + publish: async (_t: string, name: string, opts?: { ifMatch?: string; ifNoneMatch?: '*'; draftVersion?: string }) => { server.publishes.push({ name, ifMatch: opts?.ifMatch, ifNoneMatch: opts?.ifNoneMatch }); + server.publishDraftPins.push(opts?.draftVersion); + const between = server.onPublish.get(name); + server.onPublish.delete(name); + between?.(); + // objectstack#37440 — the door judges the draft pin first, against the draft row. + if (opts?.draftVersion !== undefined && opts.draftVersion !== (server.draftVersions.get(name) ?? null)) { + throw await conflictRefusal(name, server.draftVersions.get(name) ?? null); + } const head = server.published.has(name) ? (server.publishedVersions.get(name) ?? null) : null; if (opts?.ifMatch !== undefined && opts.ifMatch !== head) throw await conflictRefusal(name, head); if (opts?.ifNoneMatch !== undefined && head !== null) throw await conflictRefusal(name, head); @@ -179,8 +193,10 @@ function makeClient(server: Server, saving: { on: boolean }) { server.draftVersions.delete(name); return { success: true, version }; }, - reset: async (_t: string, name: string, opts?: { state?: string }) => { + reset: async (_t: string, name: string, opts?: { state?: string; ifMatch?: string }) => { if (opts?.state === 'draft') { + const head = server.draftVersions.get(name) ?? null; + if (opts.ifMatch !== undefined && opts.ifMatch !== head) throw await conflictRefusal(name, head); server.resets.push(name); server.drafts.delete(name); server.draftVersions.delete(name); @@ -468,3 +484,37 @@ describe('the OWD overview — loads are sequenced (objectstack#37515)', () => { expect(liveSharing(server, 'a_alpha')).toBe('public_read'); }); }); + +describe('the OWD overview — a row\'s publish promotes only the draft its own save wrote (objectstack#37440)', () => { + it('PIN: another writer\'s draft lands between the row\'s draft save and its publish: nothing goes live, their draft is kept, nothing is asked', async () => { + const { saving } = renderPanel(server); + await pick('b_beta', PUBLIC_READ); + let theirs = ''; + server.onPublish.set('b_beta', () => { + theirs = anotherWriterSavesDraft(server, 'b_beta', { description: 'in between' }); + }); + + await save(saving); + // The row reads as refused (the door's own refusal), edits on the page. + expect(await screen.findByText(/^Beta: /, undefined, WAIT)).toBeInTheDocument(); + // The publish named the draft this Save wrote: its own receipt. + expect(server.publishDraftPins).toEqual(['draft:mine1']); + expect(liveSharing(server, 'b_beta')).toBe('private'); + // Their draft stands, never taken back as if it were this Save's. + expect(server.draftVersions.get('b_beta')).toBe(theirs); + expect(server.drafts.get('b_beta')).toMatchObject({ description: 'in between' }); + expect(server.resets).toEqual([]); + expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(); + expect(screen.getByTestId('owd-dirty-b_beta')).toBeInTheDocument(); + }); + + it('CONTROL: with no other writer in between, the row\'s draft goes live', async () => { + const { saving } = renderPanel(server); + await pick('b_beta', PUBLIC_READ); + + await save(saving); + await waitFor(() => expect(liveSharing(server, 'b_beta')).toBe('public_read'), WAIT); + expect(server.drafts.has('b_beta')).toBe(false); + expect(server.resets).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx index 0ff32a1047a..b5b15b56a65 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx @@ -702,7 +702,9 @@ export function PackageOwdOverviewPanel({ if (held) recordPublished('object', s.row.name, packageId, held.published); const live = await publishSavedItem( client, - { type: 'object', name: s.row.name, packageId }, + // objectstack#37440 — and to the draft this save wrote (`token`, its + // receipt): a draft another writer changed in between is not published. + { type: 'object', name: s.row.name, packageId, ...(token ? { draftVersion: token } : {}) }, basis.hadDraft, publishPinned, ); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftVersionConflict-11773.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftVersionConflict-11773.test.tsx index ff5e39dd9f8..a7d838a5874 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftVersionConflict-11773.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftVersionConflict-11773.test.tsx @@ -336,7 +336,8 @@ describe('Data pillar — a draft saved elsewhere is not overwritten in silence // The draft was read at the package the saves write. expect(mockClient.getDraft).toHaveBeenCalledWith('object', OBJECT.name, { packageId: PKG }); expect(server.saves.every((s) => s.packageId === PKG)).toBe(true); - expect(mockClient.publish).toHaveBeenCalledWith('object', OBJECT.name, { packageId: PKG }); + // objectstack#37440 — each publish is pinned to the draft its own Save wrote (its receipt). + expect(mockClient.publish).toHaveBeenCalledWith('object', OBJECT.name, { packageId: PKG, draftVersion: expect.any(String) }); expect(liveFields()).toEqual(['title', 'status', 'new_field', 'second_field']); expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(); }); diff --git a/ui/packages/app-shell/src/views/studio-design/newAppDoor.ts b/ui/packages/app-shell/src/views/studio-design/newAppDoor.ts index c3588bb2a2d..dbe75e6e1d8 100644 --- a/ui/packages/app-shell/src/views/studio-design/newAppDoor.ts +++ b/ui/packages/app-shell/src/views/studio-design/newAppDoor.ts @@ -29,6 +29,7 @@ import type { MetadataClient } from '@object-ui/data-objectstack'; import { findTakenIdentifier } from './StudioPillarKit.js'; import { buildAppSkeleton } from './skeletons.js'; import { publishSavedItem } from './studioSaveBar.js'; +import { draftReceiptVersion } from '../metadata-admin/DraftConflictDialog.js'; /** What `reserve` answers: a free app name, or the app holding the first candidate. */ export type AppNameReservation = { name: string } | { taken: { name: string; label: string } }; @@ -63,13 +64,18 @@ export function newAppStep( }, async create(packageId, name, label) { // The first-write pin refuses a draft that landed since `reserve`. - await client.save('app', name, buildAppSkeleton(name, label), { + const receipt = await client.save('app', name, buildAppSkeleton(name, label), { mode: 'draft', packageId, ifNoneMatch: '*', surface: 'studio', }); - const live = await publishSavedItem(client, { type: 'app', name, packageId }, false); + // objectstack#37440 — the publish is pinned to the draft this create wrote (its receipt). + const live = await publishSavedItem( + client, + { type: 'app', name, packageId, draftVersion: draftReceiptVersion(receipt) }, + false, + ); if (!live.ok) throw live.error; }, }; diff --git a/ui/packages/app-shell/src/views/studio-design/objectHooksBuffer.ts b/ui/packages/app-shell/src/views/studio-design/objectHooksBuffer.ts index db3ba9e8b7c..915276dd08e 100644 --- a/ui/packages/app-shell/src/views/studio-design/objectHooksBuffer.ts +++ b/ui/packages/app-shell/src/views/studio-design/objectHooksBuffer.ts @@ -35,7 +35,13 @@ import * as React from 'react'; import { authoredPublished, extractDraftBody, formatMetadataError } from '@object-ui/data-objectstack'; import { useMetadataClient } from '../metadata-admin/useMetadata.js'; -import { publishedPinOf, readDraftForSave, useDraftSaveGuard, type DraftPin } from '../metadata-admin/DraftConflictDialog.js'; +import { + draftReceiptVersion, + publishedPinOf, + readDraftForSave, + useDraftSaveGuard, + type DraftPin, +} from '../metadata-admin/DraftConflictDialog.js'; import type { HookTargetScope } from '../metadata-admin/inspectors/HookDefaultInspector.js'; import { t, tFormat, useMetadataLocale } from '../metadata-admin/i18n.js'; import { loadPackageSurfaces } from './packageSurfaces.js'; @@ -155,6 +161,8 @@ export function useObjectHooksBuffer({ // objectstack#36726 — the published hook each buffer was loaded at, for the Save's publish. recordPublished: recordHookPublished, publish: publishHook, + // objectstack#37440 — the version the buffer's own Save wrote, which pins its publish. + heldDraftVersion: heldHookDraftVersion, dialog, } = useDraftSaveGuard(client, reloadHooks); React.useEffect(() => { @@ -390,20 +398,26 @@ export function useObjectHooksBuffer({ setSaving(true); setError(null); try { + // objectstack#37440 — the version this Save's own draft write returned, which pins its publish. + let draftVersion: string | undefined; if (isNew) { // objectui#11773 — a create is the first-write pin: refused where the // name already holds a draft, instead of written over it. - await client.save('hook', name, body, { mode: 'draft', packageId, ifNoneMatch: '*', surface: 'studio' }); + draftVersion = draftReceiptVersion( + await client.save('hook', name, body, { mode: 'draft', packageId, ifNoneMatch: '*', surface: 'studio' }), + ); } else if ( (await saveHookDraft('hook', name, body, { mode: 'draft', packageId, surface: 'studio' })) === 'reloaded' ) { // The author chose the saved version: the list re-read installs it. setEdited(false); return { kind: 'declined' }; + } else { + draftVersion = heldHookDraftVersion('hook', name, packageId); } // objectstack#36726 — a new hook's publish asserts no published row of its name. if (isNew) recordHookPublished('hook', name, packageId, { ifNoneMatch: '*' }); - const outcome = await publishSavedItem(client, { type: 'hook', name, packageId }, hadDraft, publishHook); + const outcome = await publishSavedItem(client, { type: 'hook', name, packageId, draftVersion }, hadDraft, publishHook); // The published hook moved and the author chose to reload: the list re-read installs it. if (!outcome.ok && 'reloaded' in outcome) { if (isNew) setCreated(null); @@ -450,7 +464,7 @@ export function useObjectHooksBuffer({ } finally { setSaving(false); } - }, [client, draft, draftFor, created, drafted, packageId, objectName, saveHookDraft, recordHookRead, recordHookPublished, publishHook]); + }, [client, draft, draftFor, created, drafted, packageId, objectName, saveHookDraft, recordHookRead, recordHookPublished, publishHook, heldHookDraftVersion]); const cancel = React.useCallback(() => { setError(null); diff --git a/ui/packages/app-shell/src/views/studio-design/pairObjectActions.ts b/ui/packages/app-shell/src/views/studio-design/pairObjectActions.ts index 33942a0554a..7123e76985d 100644 --- a/ui/packages/app-shell/src/views/studio-design/pairObjectActions.ts +++ b/ui/packages/app-shell/src/views/studio-design/pairObjectActions.ts @@ -55,6 +55,7 @@ import { authoredBuffer, extractDraftBody, formatMetadataError, type AuthoredLay import { useMetadataClient } from '../metadata-admin/useMetadata.js'; import { t as tStudio, tFormat, useMetadataLocale } from '../metadata-admin/i18n.js'; import { + draftReceiptVersion, publishedPinOf, readDraftForSave, useDraftSaveGuard, @@ -181,6 +182,8 @@ export function usePairObjectActions( // objectstack#36726 — the published action each row was loaded at, for the Save's publish. recordPublished, publish: publishGuarded, + // objectstack#37440 — the version a row's own Save wrote, which pins its publish. + heldDraftVersion, dialog, } = useDraftSaveGuard(client, reload); React.useEffect(() => { @@ -416,19 +419,30 @@ export function usePairObjectActions( if (!row) continue; const isNew = created.has(name); try { + // objectstack#37440 — the version this row's own draft write returned, which pins its publish. + let draftVersion: string | undefined; if (isNew) { // objectui#11773 — a create is the first-write pin. - await client.save('action', name, row.body, { mode: 'draft', packageId: pair, ifNoneMatch: '*', surface: 'studio' }); + draftVersion = draftReceiptVersion( + await client.save('action', name, row.body, { mode: 'draft', packageId: pair, ifNoneMatch: '*', surface: 'studio' }), + ); } else if ( (await saveGuarded('action', name, row.body, { mode: 'draft', packageId: pair, surface: 'studio' })) === 'reloaded' ) { reloaded = true; setEdited(new Set()); continue; + } else { + draftVersion = heldDraftVersion('action', name, pair); } // objectstack#36726 — a new row's publish asserts no published action of its name. if (isNew) recordPublished('action', name, pair, { ifNoneMatch: '*' }); - const outcome = await publishSavedItem(client, { type: 'action', name, packageId: pair }, row.draft, publishGuarded); + const outcome = await publishSavedItem( + client, + { type: 'action', name, packageId: pair, draftVersion }, + row.draft, + publishGuarded, + ); // The published action moved and the author chose to reload: the pair's read installs it. if (!outcome.ok && 'reloaded' in outcome) { reloaded = true; @@ -486,7 +500,7 @@ export function usePairObjectActions( return { kind: 'refused', reason }; } return reloaded ? { kind: 'declined' } : { kind: 'saved' }; - }, [client, created, edited, removed, pairForWrite, saveGuarded, publishGuarded, recordRead, recordPublished, reload]); + }, [client, created, edited, removed, pairForWrite, saveGuarded, publishGuarded, heldDraftVersion, recordRead, recordPublished, reload]); const cancel = React.useCallback(() => { setError(null); diff --git a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.draftPin-37440.test.ts b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.draftPin-37440.test.ts new file mode 100644 index 00000000000..34bdc041e3b --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.draftPin-37440.test.ts @@ -0,0 +1,79 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37440 — the Studio Save's publish (`publishSavedItem`) is + * pinned to the draft the Save itself wrote (`item.draftVersion`, its + * receipt), on both of its publish doors: the unpinned door (no buffer + * guard) and a create's `publishCreated`. A draft another writer changed in + * between is refused and kept pending, never published and never discarded; + * with no write in between, the Save goes live as before. The guarded door + * (`DraftSaveGuard.publish`) is pinned in `DraftConflictDialog.test.tsx`. + */ + +import { describe, expect, it } from 'vitest'; +import { publishCreated, publishSavedItem } from './studioSaveBar'; +import { draftReceiptVersion, isDraftVersionConflict } from '../metadata-admin/DraftConflictDialog'; +import { draftPublishDoor } from '../__tests__/draftPublishDoor-37440'; + +const PKG = 'com.acme.crm'; +const ITEM = { type: 'app', name: 'acme_app', packageId: PKG }; + +/** The Save's own draft write, through the door, answering its receipt's version. */ +async function savedDraft(door: ReturnType, body: unknown): Promise { + return draftReceiptVersion(await door.client.save(ITEM.type, ITEM.name, body, { mode: 'draft', packageId: PKG, ifNoneMatch: '*' })); +} + +describe('publishSavedItem, unpinned door: the publish names the draft the Save wrote (objectstack#37440)', () => { + it("PIN: another writer's draft write before the publish is refused; nothing goes live, and their draft is kept", async () => { + const door = draftPublishDoor(); + const draftVersion = await savedDraft(door, { label: 'mine' }); + door.interleave(ITEM.type, ITEM.name, PKG, { label: 'theirs' }); + const live = await publishSavedItem(door.metadataClient, { ...ITEM, draftVersion }, false); + expect(live.ok).toBe(false); + expect(!live.ok && isDraftVersionConflict(live.error)).toBe(true); + expect(!live.ok && live.draftDiscarded).toBe(false); + expect(door.liveOf(ITEM.type, ITEM.name, PKG)).toBeUndefined(); + expect(door.draftOf(ITEM.type, ITEM.name, PKG)).toEqual({ label: 'theirs' }); + expect(door.calls.some(([c]) => c === 'reset')).toBe(false); + expect(door.calls.find(([c]) => c === 'publish')?.[3]).toEqual({ packageId: PKG, draftVersion }); + }); + + it('a refusal for another reason takes back only the draft this Save wrote, pinned to its receipt', async () => { + const door = draftPublishDoor(); + const draftVersion = await savedDraft(door, { label: 'mine' }); + const refusing = { ...door.metadataClient, publish: async () => Promise.reject(Object.assign(new Error('rule'), { status: 422 })) }; + const live = await publishSavedItem(refusing, { ...ITEM, draftVersion }, false); + expect(!live.ok && live.draftDiscarded).toBe(true); + expect(door.calls.find(([c]) => c === 'reset')?.[3]).toEqual({ state: 'draft', packageId: PKG, ifMatch: draftVersion }); + expect(door.draftOf(ITEM.type, ITEM.name, PKG)).toBeUndefined(); + }); + + it('CONTROL: with no write in between, the same pinned publish takes the Save live', async () => { + const door = draftPublishDoor(); + const draftVersion = await savedDraft(door, { label: 'mine' }); + expect(await publishSavedItem(door.metadataClient, { ...ITEM, draftVersion }, false)).toEqual({ ok: true }); + expect(door.liveOf(ITEM.type, ITEM.name, PKG)).toEqual({ label: 'mine' }); + }); +}); + +describe('publishSavedItem, a create (`publishCreated`): the publish names the draft the create wrote (objectstack#37440)', () => { + it("PIN: another writer's draft write before the publish is refused; nothing goes live, and their draft is kept", async () => { + const door = draftPublishDoor(); + const draftVersion = await savedDraft(door, { label: 'mine' }); + door.interleave(ITEM.type, ITEM.name, PKG, { label: 'theirs' }); + const live = await publishSavedItem(door.metadataClient, { ...ITEM, draftVersion }, false, publishCreated); + expect(live.ok).toBe(false); + expect(!live.ok && 'draftDiscarded' in live && live.draftDiscarded).toBe(false); + expect(door.liveOf(ITEM.type, ITEM.name, PKG)).toBeUndefined(); + // The pinned take-back was refused by the door: the moved draft is not the create's. + expect(door.draftOf(ITEM.type, ITEM.name, PKG)).toEqual({ label: 'theirs' }); + expect(door.calls.find(([c]) => c === 'publish')?.[3]).toEqual({ packageId: PKG, draftVersion, ifNoneMatch: '*' }); + }); + + it('CONTROL: with no write in between, the create goes live', async () => { + const door = draftPublishDoor(); + const draftVersion = await savedDraft(door, { label: 'mine' }); + expect(await publishSavedItem(door.metadataClient, { ...ITEM, draftVersion }, false, publishCreated)).toEqual({ ok: true }); + expect(door.liveOf(ITEM.type, ITEM.name, PKG)).toEqual({ label: 'mine' }); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx index 5575b4597cd..9e3a736c244 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx @@ -45,6 +45,8 @@ import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; import { t, tFormat } from '../metadata-admin/i18n.js'; import { LINT_DEBOUNCE_MS } from '../metadata-admin/celLintDebounce.js'; import { + isDraftVersionConflict, + isPublishDraftMoved, publishedPinOf, type BeforeReloadOutcome, type DraftPin, @@ -253,6 +255,19 @@ export function useStudioSaveCoordinator(locale: string): StudioSaveCoordinator return { registry, dirty, saving, save, cancel }; } +/** The item a Save wrote, at the address its draft save wrote it. */ +export interface SavedItem { + type: string; + name: string; + packageId: string | null; + /** + * objectstack#37440 — the version the Save's own draft write returned (its + * receipt's `version`), which pins the publish to that draft. Absent, the + * publish goes unpinned, as before. + */ + draftVersion?: string; +} + /** What an unpinned {@link publishSavedItem} did. */ export type UnpinnedPublishOutcome = | { ok: true } @@ -318,7 +333,11 @@ export function publishedPinOfLayers(layered: unknown): DraftPin | null { * `If-None-Match: *`: no live row was there when the create checked, so a row * another writer published under the name since is refused `409` instead of * replaced. For a create with no loaded buffer to reload (a new flow), the - * refusal is the create's own: no dialog is asked. + * refusal is the create's own: no dialog is asked. objectstack#37440 — the + * create's own draft pin (`options.draftVersion`, its receipt) rides beside + * it; a refusal by either pin is the create's, and the discard + * {@link publishSavedItem} pins to the same receipt removes the create's + * draft only while it is still the create's own. */ export const publishCreated: PinnedPublish = async (client, type, name, options = {}) => { await client.publish(type, name, { ...options, ifNoneMatch: '*' }); @@ -341,30 +360,48 @@ export const publishCreated: PinnedPublish = async (client, type, name, options * instead of replacing it. Omitted, the publish is unpinned, as before. * objectstack#36726 — every Studio editor that saves this way passes it; a * create passes {@link publishCreated} where no buffer is loaded behind it. + * + * objectstack#37440 — `item.draftVersion`, the version the Save's OWN draft + * write returned (its receipt's `version`; `heldDraftVersion` right after a + * guarded save), pins the publish to that draft: a draft another writer + * changed in between is refused `409 METADATA_CONFLICT` and nothing is + * published on their behalf. That draft now holds the other writer's change, + * so it is ⛔ never discarded: the outcome is a refusal with the draft kept. + * Every discard of the Save's own draft is pinned to the same version + * (`If-Match`), so the server removes only that draft, never one that moved. + * Absent (a receipt without a version), both go unpinned, as before. */ export async function publishSavedItem( client: Pick, - item: { type: string; name: string; packageId: string | null }, + item: SavedItem, hadDraft: boolean, ): Promise; export async function publishSavedItem( - client: Pick, - item: { type: string; name: string; packageId: string | null }, + client: Pick, + item: SavedItem, hadDraft: boolean, pinned: PinnedPublish, ): Promise; export async function publishSavedItem( - client: Pick, - item: { type: string; name: string; packageId: string | null }, + client: Pick & Partial>, + item: SavedItem, hadDraft: boolean, pinned?: PinnedPublish, ): Promise { const scope = item.packageId ? { packageId: item.packageId } : {}; + const { draftVersion } = item; + // objectstack#37440 — the publish names the draft the Save wrote; a discard removes only that draft. + const publishScope = draftVersion ? { ...scope, draftVersion } : scope; + const discardScope = { state: 'draft' as const, ...scope, ...(draftVersion ? { ifMatch: draftVersion } : {}) }; + // The refusal is the draft pin's: the guard said so (rule 10), or no other + // pin was sent that a `409 METADATA_CONFLICT` could be. + const draftMoved = (error: unknown): boolean => + isPublishDraftMoved(error) || (!pinned && !!draftVersion && isDraftVersionConflict(error)); let draftDiscarded = false; const discardSavedDraft = async (): Promise => { if (hadDraft) return; try { - await client.reset(item.type, item.name, { state: 'draft', ...scope }); + await client.reset(item.type, item.name, discardScope); draftDiscarded = true; } catch (discardError) { // The draft stays pending, listed under Changes, where it can be discarded. @@ -382,7 +419,7 @@ export async function publishSavedItem( // pinned to the published version the conflict was raised on. const discardBeforeReload = async (): Promise => { if (hadDraft) return 'kept'; - await client.reset(item.type, item.name, { state: 'draft', ...scope }); + await client.reset(item.type, item.name, discardScope); draftDiscarded = true; return 'discarded'; }; @@ -390,16 +427,24 @@ export async function publishSavedItem( if (pinned) { // A reload takes the saved draft back BEFORE the buffer is re-read, so // the re-read installs the live row, never the draft that lost. - const outcome = await pinned(client, item.type, item.name, scope, discardBeforeReload); + // The pinned overload's client carries `getDraft` (the guard's rule 10). + const outcome = await pinned( + client as Pick, + item.type, + item.name, + publishScope, + discardBeforeReload, + ); if (outcome === 'reloaded') { emitMetadataRefresh(); return { ok: false, reloaded: true, draftDiscarded }; } } else { - await client.publish(item.type, item.name, scope); + await client.publish(item.type, item.name, publishScope); } } catch (error) { - await discardSavedDraft(); + // objectstack#37440 — another writer's change is in the draft now: kept. + if (!draftMoved(error)) await discardSavedDraft(); emitMetadataRefresh(); return { ok: false, error, draftDiscarded }; }