Skip to content

Commit 6cb7440

Browse files
fix(client, app-shell): every draft-then-publish Save publishes only the draft it wrote (#37637)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuBUGgrNWoBUQKbyS4GaX5vM)_ Fixes #37440 Clause-②: yes (widening: `@objectstack/client` `meta.publishItem` accepts `draftVersion` and `parentVersion` beside `message` and `packageId`) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:管理员在设计器、记录页和导航编辑里点保存时,只会发布自己刚写下的那份草稿;如果有人恰好在这一刻改了同一份草稿,这次保存不会发布,也不会删掉别人的草稿,而是提示草稿待处理。没有冲突时保存和以前完全一样。 - 为什么做:属于「草稿并发写入保护」这条线(替先保存草稿、再立即发布的所有保存入口补上最后一个缺口):服务端早已支持按草稿版本拦截,前端各个保存入口却一直没把自己的版本带上。 - 出错会怎样:最坏情况是某个保存在没有冲突时也被拒,作者看到「草稿待处理」需要再存一次;旧服务端不返回版本号时一切照旧不带锁;整笔可以直接撤回。 - 要你做什么:无。 ## What changes `client.meta.publishItem` takes the two optimistic-concurrency pins the per-item publish door already judges (ADR-0008, `PublishMetaItemRequestSchema`). `draftVersion` goes in the body beside `message` and names the pending draft the publish promotes. `parentVersion` is sent as `If-Match`, and `null` is sent as `If-None-Match: *`; it names the live row the publish replaces. With neither set, the request is byte-identical to before. Every console Save that writes a draft and publishes it at once now passes `draftVersion`. The value is the version its OWN draft write returned: `draftReceiptVersion(receipt)`, or `heldDraftVersion(...)` right after a guarded save. It is never a fresh re-read, which would pin another writer's draft. The callers: - **Studio top-bar Save.** `publishSavedItem` in `studioSaveBar.tsx` takes `SavedItem.draftVersion`. It is forwarded by DataPillar (objects and object extensions), AutomationsPillar (flows and the on/off switch), `objectHooksBuffer`, `pairObjectActions`, PermissionMatrixEditor, `newAppDoor`, and MetadataListCreateDialog (new object and new flow). - **Item page Save:** `detailSaveAtOnce` via ResourceEditPage. - **Sharing-defaults table:** each row of PackageOwdOverviewPanel. This was deferred in round 1 behind #37554 and is added now that #37554 has landed. - **Record page:** 「Configure tabs」 (`recordTabsConfigSave`) and an installed object's field arrangement (`objectExtensionArrangementSave`). - **Design mode:** the header pins (`designModeHeaderPinsSave`) and the menu plus menu labels (`designModeMenuSave`). A door refusal under the draft pin is `409 METADATA_CONFLICT`, the same code the live-row pin gets, and the body does not say which pin refused. The draft-version guard (`draftVersionGuard.ts`, new rule 10 in the `DraftConflictDialog.tsx` header) tells the two apart with one draft read after the refusal: - If the draft is still at the pinned version, the live row moved, and the existing reload-or-overwrite dialog asks (rule 8). - If the draft moved, is gone, or cannot be read, the refusal is the draft's. Nothing is asked, and the error is thrown marked `isPublishDraftMoved`. Every caller treats a moved draft the same way: nothing is published and the draft is **kept**, because it now holds the other writer's change. The Save reads as refused or says a draft is pending. Every take-back of the Save's own draft is pinned `If-Match` to that same receipt, so a refused Save never deletes a draft someone else changed. ## Why #36350 added `draftVersion` to the publish door, but no caller sent it. In the window between a Save's draft write and its publish, another writer's draft write (another tab, the copilot) is promoted live under the first author's Save. The client test reproduces this at the real door: the unpinned publish promotes `theirs`. Read first (risk order): 1. `ui/packages/app-shell/src/views/metadata-admin/draftVersionGuard.ts`: the `publish` catch and `draftStillAt`. This is where a refusal is classified; a misclassification either asks the wrong question or keeps a draft that should be discarded. 2. `ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx`: `publishSavedItem`, which holds `draftMoved`, `discardScope`, and the skipped discard. 3. `ui/packages/app-shell/src/layout/designModeMenuSave.ts`: `discardOwnDraft`, the pinned take-back whose `409` means "moved, keep it". Two-minute verification: run `pnpm --dir ui exec vitest run packages/app-shell/src/views/studio-design/studioSaveBar.draftPin-37440.test.ts`. Expect 5 passed. The PIN case shows the other writer's draft still pending and the live row unchanged. ## Tests Each caller got one PIN (another writer's draft lands between the Save's draft write and its publish: nothing goes live, their draft is kept, no reset) and one CONTROL (no interleave: the Save's draft goes live), in that caller's existing harness. The PIN asserts `draftVersion` is the caller's own receipt; the CONTROLs assert the outcome only. - `packages/client/src/meta-publish-item-package.test.ts`, Part 3, on the real per-item publish door: the reproduction, PIN, CONTROL, the wire shape (body `draftVersion`, `If-Match`, `If-None-Match: *` for `null`, nothing when unset), and `parentVersion` stale or `null` refused. - New `studioSaveBar.draftPin-37440.test.ts` and `detailSaveAtOnce-37440.test.ts`, over a stateful door double, `views/__tests__/draftPublishDoor-37440.ts`. - Added describes in `recordTabsConfigSave-36499`, `objectExtensionArrangementSave-36499`, `designModeHeaderPinsSave-36366`, `designModeMenuSave-36538` (menu and translation, plus the published-moved distinction), `DraftConflictDialog.test.tsx` (guard rule 10: PIN, live-row-moved still asks, overwrite keeps the draft pin, CONTROL), and `PackageOwdOverviewPanel.draftPinned-37515`. - Updated exact-argument asserts to carry `draftVersion: expect.any(String)`: `AutomationsPillar.customizeFlow-28570`, `DataPillar.pairActions-30088`, `StudioDesignSurface.draftVersionConflict-11773`. Ablation: one per pin (rebuild, on-disk mutation via `scripts/ablation-replace.mjs`, restore). Every PIN went red with its CONTROL green, and `git diff HEAD` was empty after each restore. <details><summary>Local test readings at head 046abbb (each under scripts/pm/os-verify-lock.sh)</summary> - Client, `pnpm --filter @objectstack/client exec vitest run --maxWorkers=2 src/meta-publish-item-package.test.ts`: Test Files 1 passed (1), Tests 15 passed (15), VERDICT command-exit 0. - UI pins, 9 files (the 8 harnesses above plus `firstScreenStudioCatalogue-37444`): Test Files 9 passed (9), Tests 112 passed (112), VERDICT command-exit 0. - Affected app-shell set, 346 files: every test file that imports a changed module, plus the OWD panel suites and the importers of `draftVersionGuard.ts` / `customizeOverride.ts`. Result: Test Files 346 passed (346), Tests 2658 passed (2658), VERDICT command-exit 0. This ran at 8192a73; the only later commit is the changeset. - `pnpm --filter @object-ui/app-shell type-check`: VERDICT command-exit 0. - The full app-shell suite was not run locally (it runs over 70 min on the shared box). It is CI's. </details> <details><summary>Ablation readings (every PIN red, CONTROL green, restored)</summary> | Ablation | Result | |---|---| | client | 2 failed, 13 passed | | studioSaveBar | 2 failed, 3 passed | | detailSaveAtOnce | 2 failed, 1 passed | | recordTabs | 1 failed, 6 passed | | extension arrangement | 1 failed, 7 passed | | header pins | 1 failed, 14 passed | | menu | 1 failed, 16 passed | | menu labels | 1 failed, 16 passed | | OWD row | 1 failed, 11 passed | | guard draft pin forwarded | 2 failed, 37 passed | | guard classification | 1 failed, 38 passed | After every restore, `git diff HEAD` was empty. </details> ## Acceptance notes - **Re-checked and out of scope (not draft-then-publish of an own draft):** - `StudioDesignSurface` `publishDraft('flow')` (about line 655), `usePublishAllDrafts` and PackagesPage `publishDrafts`. These are publish-all doors with no draft write of their own, so there is no receipt to pin. - `runtime-metadata-persistence` `boundToPackage`, which is already pinned. - **Nit N6 does not ride.** Its fix site is ViewConfigPanel / RuntimeDraftBar, outside this card's surface. - **Merged with #37589.** #37589 moved the guard's pure half into `draftVersionGuard.ts`. Rule 10, `draftStillAt`, `isPublishDraftMoved` and `draftReceiptVersion` now live there; `DraftConflictDialog.tsx` re-exports them and keeps the header rule and the hook's stable `heldDraftVersion`. The #37444 first-screen import walk (`firstScreenStudioCatalogue-37444`) stays green: the list and record save paths import the new names from `draftVersionGuard.ts`, never from the dialog. - **Classification read.** The read happens only after a refusal under both pins, and it is never itself a pin. An unreadable draft is treated as moved, which fails safe: nothing is asked and nothing is discarded. - **Forwarders.** Forwarders that only pass a receipt through (DataPillar, AutomationsPillar, objectHooksBuffer, pairObjectActions, PermissionMatrixEditor, newAppDoor, MetadataListCreateDialog, ResourceEditPage) are covered through the door they forward to (`publishSavedItem` or `detailSaveAtOnce`) and the updated exact-argument asserts above, not each by its own PIN. - **Older servers.** Against a server whose draft save returns no `version`, every caller publishes unpinned, as before. ## Verification <details><summary>Derived gate families at head 046abbb</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 74 families. 73 exited 0, including `pnpm --dir ui exec vitest run scripts/`, `check:type-check-debt` and `check:skill-examples`, each after building their prerequisite dist. `pnpm check:dual-build-cjs-loads` exited 3, PREREQUISITE NOT MET: not every package has a dist in this container. NOT MEASURED locally; it is read from this PR's checks. `--ran` reconciliation: 74 derived, 74 run, 0 UNRUN. `node scripts/check-nul-bytes.mjs`: OK. `node scripts/pm/overlap-check.mjs`: VERDICT clean exit 0, against origin/main 54d6726 and 0 open PR heads. </details> Merge, not rebase: origin/main (including #37589 and #37554) was merged into the branch in 6f1e735. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (`packages/spec` untouched.) - [x] 2. Every name I added uses the casing for its kind. - [ ] 3. No formatter ran; `pnpm lint` passes. (No formatter ran; `pnpm lint` is the CI-owned repo scan, read from this PR's checks.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched: n/a.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. (Except the fleet's required maintainer brief, 维护者速读.) - [ ] The *Before Submitting* list in CONTRIBUTING.md is done. (Local targeted subset only; the full farm is CI's, see Verification.) 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgWAbKPqt7vTgX5qgUn --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9ed54cb commit 6cb7440

32 files changed

Lines changed: 1217 additions & 91 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/client': patch
3+
'@object-ui/app-shell': patch
4+
---
5+
6+
fix(client, app-shell): every draft-then-publish Save publishes only the draft it wrote
7+
8+
Clause-②: yes (widening: `@objectstack/client` `meta.publishItem` accepts `draftVersion` and `parentVersion` beside `message` and `packageId`)
9+
Metadata-protocol: none
10+
11+
`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.
12+
13+
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.

‎packages/client/src/index.ts‎

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1284,6 +1284,22 @@ function metaDeleteHeaders(options?: DeleteMetaItemOptions): Record<string, stri
12841284
return { 'If-Match': String(options.ifMatch) };
12851285
}
12861286

1287+
/**
1288+
* [#37440] The live-row pin of `meta.publishItem`
1289+
* (`PublishMetaItemRequestSchema.parentVersion`) as the publish door reads it:
1290+
* a token as `If-Match`, verbatim and unquoted as {@link metaSaveHeaders}
1291+
* sends it, and `null` ("no live row is stored") as `If-None-Match: *`. The
1292+
* door takes `*` alone and never beside `If-Match`, which one argument cannot
1293+
* produce. `undefined` (never `{}`) when unset or empty, so the call site
1294+
* omits the `headers` key and an unpinned publish is byte-identical to what
1295+
* it sent before.
1296+
*/
1297+
function metaPublishHeaders(parentVersion: string | null | undefined): Record<string, string> | undefined {
1298+
if (parentVersion === null) return { 'If-None-Match': '*' };
1299+
if (!parentVersion) return undefined;
1300+
return { 'If-Match': String(parentVersion) };
1301+
}
1302+
12871303
/**
12881304
* An OAuth client application exactly as `@better-auth/oauth-provider` puts it
12891305
* on the wire: RFC 7591 §2 client metadata, snake_case, served BARE — these
@@ -2725,6 +2741,15 @@ export class ObjectStackClient {
27252741
* holds no draft and another package's draft is stored. Pass the package
27262742
* whose draft you mean as `opts.packageId` (`?package=` on the wire), as
27272743
* `saveItem` and `deleteItem` name the row they act on.
2744+
*
2745+
* PIN WHAT YOU PUBLISH when you wrote or read the draft first
2746+
* (`PublishMetaItemRequestSchema`'s two ADR-0008 pins): `draftVersion`
2747+
* names the draft you mean to promote, so a draft another writer changed
2748+
* after you wrote or read it is refused `409 METADATA_CONFLICT` and
2749+
* nothing is published on their behalf; `parentVersion` names the live
2750+
* row you mean to replace. Pass your own draft save's receipt `version`
2751+
* (or the draft read's) as `draftVersion` — never a fresh re-read, which
2752+
* would pin whatever draft is pending now, someone else's included.
27282753
*/
27292754
publishItem: async (
27302755
type: string,
@@ -2751,6 +2776,31 @@ export class ObjectStackClient {
27512776
* it.
27522777
*/
27532778
packageId?: string;
2779+
/**
2780+
* `PublishMetaItemRequestSchema.draftVersion` — the version token
2781+
* of the pending draft this publish means to promote: a draft
2782+
* save's receipt `version` (`saveItem` in draft mode) or the
2783+
* draft read's `version`. Sent as the `draftVersion` member of
2784+
* the publish body, beside `message`. A draft that moved since is
2785+
* refused `409 METADATA_CONFLICT`, its `currentVersion` naming the
2786+
* draft's current token (`null` when no draft is pending any
2787+
* more), and nothing is promoted. Omitted, whichever draft is
2788+
* pending is promoted, as before. An empty string pins nothing and
2789+
* is not sent.
2790+
*/
2791+
draftVersion?: string;
2792+
/**
2793+
* `PublishMetaItemRequestSchema.parentVersion` — the version token
2794+
* of the LIVE row this publish means to replace (a publish
2795+
* receipt's `version`, a read's `version`), sent as `If-Match`.
2796+
* `null` asserts that no live row is stored, sent as
2797+
* `If-None-Match: *`. A live row that does not match is refused
2798+
* `409 METADATA_CONFLICT` and nothing is promoted. Omitted, the
2799+
* publish replaces whatever is live, as before. It pins the live
2800+
* row only; the draft's own pin is `draftVersion`, and the two
2801+
* may be sent together (the door judges the draft first).
2802+
*/
2803+
parentVersion?: string | null;
27542804
},
27552805
): Promise<PublishMetaItemResponse> => {
27562806
const route = this.getRoute('metadata');
@@ -2764,9 +2814,20 @@ export class ObjectStackClient {
27642814
// `query`, not `qs` — it carries its own `?`; see `saveItem`'s note on
27652815
// the three meanings `qs` holds in this file.
27662816
const query = search ? `?${search}` : '';
2817+
// [#37440] The two ADR-0008 pins. `draftVersion` rides the BODY,
2818+
// beside `message` (the REST door reads it there); `parentVersion`
2819+
// rides a HEADER, as on the save and delete doors: a token as
2820+
// `If-Match`, `null` as `If-None-Match: *`. Each is omitted when
2821+
// unset, so an unpinned publish hands `fetch` the same `init` it
2822+
// always did.
2823+
const headers = metaPublishHeaders(opts?.parentVersion);
27672824
const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/publish${query}`, {
27682825
method: 'POST',
2769-
body: JSON.stringify(opts?.message ? { message: opts.message } : {}),
2826+
...(headers ? { headers } : {}),
2827+
body: JSON.stringify({
2828+
...(opts?.message ? { message: opts.message } : {}),
2829+
...(opts?.draftVersion ? { draftVersion: opts.draftVersion } : {}),
2830+
}),
27702831
});
27712832
return this.unwrapResponse<PublishMetaItemResponse>(res);
27722833
},

‎packages/client/src/meta-publish-item-package.test.ts‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,3 +409,112 @@ describe('[#23658] the real publish door: the only draft is another package\'s',
409409
expect(publishRequests[1].packageId).toBe(OTHER_PKG);
410410
}, 60_000);
411411
});
412+
413+
// ---------------------------------------------------------------------------
414+
// Part 3 — [#37440] the two pins: `draftVersion` (the draft) and
415+
// `parentVersion` (the live row)
416+
// ---------------------------------------------------------------------------
417+
418+
describe('[#37440] meta.publishItem pins — what reaches the wire', () => {
419+
it('`draftVersion` rides the body beside `message`; `parentVersion` rides `If-Match`', async () => {
420+
const { client, fetchMock } = createMockClient(PUBLISH_OK);
421+
await client.meta.publishItem('view', 'shared_grid', {
422+
message: 'ship it',
423+
packageId: PKG,
424+
draftVersion: 'draft-token',
425+
parentVersion: 'live-token',
426+
});
427+
expect(bodyOfCall(fetchMock)).toEqual({ message: 'ship it', draftVersion: 'draft-token' });
428+
const headers = fetchMock.mock.calls[0][1].headers as Record<string, string>;
429+
expect(headers['If-Match']).toBe('live-token');
430+
expect(headers).not.toHaveProperty('If-None-Match');
431+
// A body member and a header: neither is put on the query string.
432+
expect(new URL(String(fetchMock.mock.calls[0][0])).search).toBe(`?package=${PKG}`);
433+
});
434+
435+
it('`parentVersion: null` asserts no live row: `If-None-Match: *`, never beside `If-Match`', async () => {
436+
const { client, fetchMock } = createMockClient(PUBLISH_OK);
437+
await client.meta.publishItem('view', 'shared_grid', { parentVersion: null });
438+
const headers = fetchMock.mock.calls[0][1].headers as Record<string, string>;
439+
expect(headers['If-None-Match']).toBe('*');
440+
expect(headers).not.toHaveProperty('If-Match');
441+
expect(bodyOfCall(fetchMock)).toEqual({});
442+
});
443+
444+
it('CONTROL: unset (or empty) pins send nothing — the request an unpinned publish always sent', async () => {
445+
const { client, fetchMock } = createMockClient(PUBLISH_OK);
446+
await client.meta.publishItem('view', 'shared_grid', { draftVersion: '', parentVersion: '' });
447+
await client.meta.publishItem('view', 'shared_grid', { draftVersion: undefined, parentVersion: undefined });
448+
for (let i = 0; i < 2; i++) {
449+
expect(String(fetchMock.mock.calls[i][0])).toBe(PUBLISH_URL);
450+
expect(bodyOfCall(fetchMock, i)).toEqual({});
451+
const headers = fetchMock.mock.calls[i][1].headers as Record<string, string>;
452+
expect(headers).not.toHaveProperty('If-Match');
453+
expect(headers).not.toHaveProperty('If-None-Match');
454+
}
455+
});
456+
});
457+
458+
describe('[#37440] the real publish door: a draft another writer changed in between is never published', () => {
459+
/**
460+
* The caller's draft write (its receipt is its pin), then ANOTHER writer's
461+
* draft write to the same address, landing before the caller's publish.
462+
*/
463+
async function interleaved(client: ObjectStackClient, name: string) {
464+
await client.meta.saveItem('view', name, VIEW(name, 'live'), { packageId: PKG });
465+
const mine = await client.meta.saveItem('view', name, VIEW(name, 'mine'), { packageId: PKG, mode: 'draft' });
466+
await client.meta.saveItem('view', name, VIEW(name, 'theirs'), { packageId: PKG, mode: 'draft' });
467+
return (mine as { version?: string }).version;
468+
}
469+
470+
it('REPRODUCTION — unpinned (all the SDK could send before): the other writer\'s draft goes live', async () => {
471+
const { engine, client } = await bootDoor();
472+
await interleaved(client, 'interleaved_unpinned');
473+
await client.meta.publishItem('view', 'interleaved_unpinned', { packageId: PKG });
474+
expect(await rowsOf(engine, 'interleaved_unpinned')).toEqual([`${PKG}:active:theirs`]);
475+
}, 60_000);
476+
477+
it('PIN — `draftVersion` = the caller\'s own receipt: refused 409 METADATA_CONFLICT, nothing promoted', async () => {
478+
const { engine, client, publishRequests } = await bootDoor();
479+
const mine = await interleaved(client, 'interleaved_pinned');
480+
expect(typeof mine).toBe('string');
481+
const err = await refusalOf(client.meta.publishItem('view', 'interleaved_pinned', { packageId: PKG, draftVersion: mine }));
482+
expect(err.code).toBe('METADATA_CONFLICT');
483+
expect(err.httpStatus).toBe(409);
484+
// The live row stands; the moved draft (the other writer's) stays pending, unpublished.
485+
expect(await rowsOf(engine, 'interleaved_pinned')).toEqual([`${PKG}:active:live`, `${PKG}:draft:theirs`].sort());
486+
expect(publishRequests[0].draftVersion).toBe(mine);
487+
}, 60_000);
488+
489+
it('CONTROL — no interleave: the same pinned publish promotes the caller\'s draft', async () => {
490+
const { engine, client } = await bootDoor();
491+
await client.meta.saveItem('view', 'uninterleaved', VIEW('uninterleaved', 'live'), { packageId: PKG });
492+
const mine = await client.meta.saveItem('view', 'uninterleaved', VIEW('uninterleaved', 'mine'), {
493+
packageId: PKG,
494+
mode: 'draft',
495+
});
496+
const published = await client.meta.publishItem('view', 'uninterleaved', {
497+
packageId: PKG,
498+
draftVersion: (mine as { version?: string }).version,
499+
});
500+
expect(published.success).toBe(true);
501+
expect(await rowsOf(engine, 'uninterleaved')).toEqual([`${PKG}:active:mine`]);
502+
}, 60_000);
503+
504+
it('`parentVersion` pins the live row: a stale token is refused 409, the live token promotes', async () => {
505+
const { engine, client, publishRequests } = await bootDoor();
506+
const first = await client.meta.saveItem('view', 'live_pinned', VIEW('live_pinned', 'live'), { packageId: PKG });
507+
const liveToken = (first as { version?: string }).version;
508+
await client.meta.saveItem('view', 'live_pinned', VIEW('live_pinned', 'mine'), { packageId: PKG, mode: 'draft' });
509+
// `null` asserts no live row — one is stored, so it is refused.
510+
const err = await refusalOf(client.meta.publishItem('view', 'live_pinned', { packageId: PKG, parentVersion: null }));
511+
expect(err.code).toBe('METADATA_CONFLICT');
512+
expect(err.httpStatus).toBe(409);
513+
expect(await rowsOf(engine, 'live_pinned')).toEqual([`${PKG}:active:live`, `${PKG}:draft:mine`].sort());
514+
expect(publishRequests[0].parentVersion).toBeNull();
515+
const published = await client.meta.publishItem('view', 'live_pinned', { packageId: PKG, parentVersion: liveToken });
516+
expect(published.success).toBe(true);
517+
expect(await rowsOf(engine, 'live_pinned')).toEqual([`${PKG}:active:mine`]);
518+
expect(publishRequests[1].parentVersion).toBe(liveToken);
519+
}, 60_000);
520+
});

‎ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ vi.mock('../../assistant/assistantBus', async (importOriginal) => ({
1818

1919
import { saveObjectPins, type ObjectPinsSaveDoors } from '../designModeHeaderPinsSave';
2020
import type { ObjectPins } from '../designModeHeaderPinsModel';
21+
import { draftPublishDoor } from '../../views/__tests__/draftPublishDoor-37440';
2122

2223
const TEXTS = {
2324
notListed: 'not listed',
@@ -234,3 +235,35 @@ describe('saving the header pins (objectstack#36366)', () => {
234235
expect(calls.at(-1)).toEqual(['reset', 'object', 'crm_lead', { state: 'draft', packageId: 'com.acme.crm' }]);
235236
});
236237
});
238+
239+
describe('the header pins Save publishes only the draft it wrote (objectstack#37440)', () => {
240+
const authored = { name: 'crm_lead', label: 'Lead', actions: [{ name: 'convert', locations: ['record_header'] }] };
241+
function doorDoors() {
242+
const door = draftPublishDoor();
243+
door.seedLive('object', 'crm_lead', 'com.acme.crm', authored);
244+
const d: ObjectPinsSaveDoors = {
245+
listPackages: async () =>
246+
new Map([['com.acme.crm', { id: 'com.acme.crm', name: 'CRM', writable: true, manifest: { version: '1.0.0' } }]]),
247+
ensureCustomization: async (base) => ({ basePackageId: base, packageId: `${base}.custom`, namespace: 'crm_custom', created: false, writable: true }),
248+
client: { ...door.client, get: async () => null, layered: async () => ({ code: authored }) },
249+
};
250+
return { door, d };
251+
}
252+
const pins = { record: { pinned: ['log_call', 'convert'] } };
253+
254+
it("PIN: another writer's draft write between the save and its publish is refused, published by nobody, and kept", async () => {
255+
const { door, d } = doorDoors();
256+
door.interleave('object', 'crm_lead', 'com.acme.crm', { name: 'crm_lead', label: 'theirs' });
257+
await expect(saveObjectPins(input(pins), TEXTS, d)).rejects.toThrow('pending draft');
258+
expect(door.liveOf('object', 'crm_lead', 'com.acme.crm')).toEqual(authored);
259+
expect(door.draftOf('object', 'crm_lead', 'com.acme.crm')).toEqual({ name: 'crm_lead', label: 'theirs' });
260+
expect(door.calls.find(([c]) => c === 'publish')?.[3]).toMatchObject({ draftVersion: expect.any(String) });
261+
});
262+
263+
it('CONTROL: with no write in between, the same pinned publish takes the pins live', async () => {
264+
const { door, d } = doorDoors();
265+
await saveObjectPins(input(pins), TEXTS, d);
266+
expect(door.liveOf('object', 'crm_lead', 'com.acme.crm')).toEqual({ ...authored, actionLayout: pins });
267+
expect(door.draftOf('object', 'crm_lead', 'com.acme.crm')).toBeUndefined();
268+
});
269+
});

0 commit comments

Comments
 (0)