Skip to content
Merged
16 changes: 16 additions & 0 deletions .changeset/36726-studio-pinned-publish.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@object-ui/app-shell': patch
---

fix(studio): the object extension, hook, action and flow Saves no longer publish over another admin's live change

Clause-②: no
Metadata-protocol: none

Studio's top-bar Save writes an item's draft and then publishes that one item. The object page pinned that publish to the published row it was loaded at, but the other editors that save this way did not: two admins who opened the same object extension, hook, pair action or flow each passed the draft check, and the later Save replaced the earlier one's live change without a word.

Each of those editors now reads the published version at the address its publish writes (the `/layers` read's `overlayVersion`) where its buffer is loaded, and its Save's publish sends it as `If-Match` (`If-None-Match: *` where nothing is published there yet). When another writer published since, the Save opens the same dialog the object page shows for a live change: reload re-reads the live item, overwrite (after a confirmation) publishes over the version the refusal names, and keep editing leaves the edits on the page, unsaved. The flow's on/off switch is pinned the same way. Creating a new hook, pair action or flow publishes with `If-None-Match: *`, so a same-named item another writer published first is refused instead of replaced. No dialog wording or locale key changes.

A reload over a draft that was pending before the Save (a copilot's) now keeps the publish pinned to the version the conflict was raised on: the reload re-reads that draft, which carries the page's edits, and the next Save is asked again instead of publishing it over the row that moved. An overwrite, a publish that lands, or a load that finds no pending draft ends that hold. This applies to the object page too.

A server that serves no `overlayVersion` gets an unpinned publish, as before. Nothing to migrate.
Original file line number Diff line number Diff line change
Expand Up @@ -626,3 +626,95 @@ describe('DraftVersionGuard — the Save\'s publish is pinned to the published r
expect(unpinned.state.sent).toEqual([[null, null]]);
});
});

describe('DraftVersionGuard — a reload that keeps a pending draft keeps the publish pinned until the author re-confirms (objectstack#36726)', () => {
const NAME = 'acme_task';

/** A publish door over one live row, the refusal parsed by the real client. */
function liveDoor(live: string) {
const state = { live, sent: [] as Array<string | null> };
const fetchImpl = (async (_input: RequestInfo | URL, init?: RequestInit) => {
const ifMatch = new Headers(init?.headers).get('If-Match');
state.sent.push(ifMatch);
if (ifMatch !== null && ifMatch !== state.live) {
return json(409, { error: 'The published row moved.', code: 'METADATA_CONFLICT', currentVersion: state.live });
}
state.live = v(200 + state.sent.length);
return json(200, { success: true, version: state.live, seq: 1 });
}) as typeof fetch;
return { state, client: new MetadataClient({ baseUrl: 'http://localhost:3000', fetch: fetchImpl }) };
}

function guardAnswering(...answers: DraftConflictChoice[]) {
const queue = [...answers];
const ask = vi.fn(async () => queue.shift() ?? 'cancel');
const guard = new DraftVersionGuard({
client: () => measuredDoor().client,
ask,
reload: vi.fn(),
notSaved: (c) => new Error(`not saved: ${c.type}/${c.name}`),
});
return { guard, ask };
}

/** The conflict, answered "reload", then the reload's load: its draft read and its fresh `/layers` read. */
async function reloadOverPendingDraft(
left: 'kept' | 'discarded',
order: 'read-first' | 'layers-first' = 'read-first',
...later: DraftConflictChoice[]
) {
const door = liveDoor(v(2));
const { guard, ask } = guardAnswering('reload', ...later);
guard.recordPublished('object', NAME, PKG, { ifMatch: v(1) });
expect(await guard.publish(door.client, 'object', NAME, { packageId: PKG }, async () => left)).toBe('reloaded');
const draftPin = left === 'kept' ? { ifMatch: v(9) } : ({ ifNoneMatch: '*' } as const);
if (order === 'read-first') guard.recordRead('object', NAME, PKG, draftPin);
guard.recordPublished('object', NAME, PKG, { ifMatch: v(2) });
if (order === 'layers-first') guard.recordRead('object', NAME, PKG, draftPin);
return { door, guard, ask };
}

it('kept: the fresh read does not replace the pin the conflict was raised on, and the next publish is asked again', async () => {
const { door, guard, ask } = await reloadOverPendingDraft('kept');
expect(guard.publishedFor('object', NAME, PKG)).toEqual({ ifMatch: v(1) });
await expect(guard.publish(door.client, 'object', NAME, { packageId: PKG })).rejects.toThrow(/not saved/);
expect(ask).toHaveBeenCalledTimes(2);
expect(door.state.sent).toEqual([v(1), v(1)]);
expect(door.state.live).toBe(v(2));
});

it('discarded: the reload re-read the live row, and is pinned to it at once', async () => {
const { door, guard } = await reloadOverPendingDraft('discarded');
expect(guard.publishedFor('object', NAME, PKG)).toEqual({ ifMatch: v(2) });
expect(await guard.publish(door.client, 'object', NAME, { packageId: PKG })).toBe('published');
expect(door.state.sent).toEqual([v(1), v(2)]);
});

it('kept, then the author overwrites: re-sent pinned to the refusal\'s currentVersion, and the receipt pins the next', async () => {
const { door, guard } = await reloadOverPendingDraft('kept', 'read-first', 'overwrite');
expect(await guard.publish(door.client, 'object', NAME, { packageId: PKG })).toBe('published');
expect(door.state.sent).toEqual([v(1), v(1), v(2)]);
expect(guard.publishedFor('object', NAME, PKG)).toEqual({ ifMatch: door.state.live });
});

it('a load that reads no pending draft ends it: the fresh pin is taken, whichever read is recorded first', async () => {
for (const order of ['read-first', 'layers-first'] as const) {
const { guard } = await reloadOverPendingDraft('kept', order);
expect(guard.publishedFor('object', NAME, PKG)).toEqual({ ifMatch: v(1) });
guard.recordRead('object', NAME, PKG, { ifNoneMatch: '*' });
// Recorded before the release: taken now. Recorded after: taken as usual.
guard.recordPublished('object', NAME, PKG, { ifMatch: v(2) });
expect(guard.publishedFor('object', NAME, PKG)).toEqual({ ifMatch: v(2) });
}
});

it('`forget` ends it too, and the pin it held for another item survives a reload of this one', async () => {
const { guard } = await reloadOverPendingDraft('kept', 'read-first', 'reload');
const other = liveDoor(v(5));
guard.recordPublished('object', 'acme_other', PKG, { ifMatch: v(4) });
expect(await guard.publish(other.client, 'object', 'acme_other', { packageId: PKG }, async () => 'discarded')).toBe('reloaded');
expect(guard.publishedFor('object', NAME, PKG)).toEqual({ ifMatch: v(1) });
guard.forget();
expect(guard.publishedFor('object', NAME, PKG)).toBeNull();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,15 @@
* draft the Save just wrote is taken back before the buffer is re-read),
* overwrite after the confirmation (re-sent pinned to the refusal's
* `currentVersion`), or keep editing (nothing goes live).
* 9. objectstack#36726 — a reload whose `beforeReload` leaves a draft pending
* (`'kept'`: one that was there before the Save, a copilot's, which the
* Save wrote into and never discards) re-reads THAT draft, now carrying
* the page's edits. Its publish stays pinned to the version the conflict
* was raised on until the author re-confirms: the next Save is refused and
* asked again, and only an overwrite, a publish that lands, or a load that
* 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.
*/

import * as React from 'react';
Expand All @@ -112,6 +121,14 @@ import { GetMetaItemLayeredResponseSchema, GetMetaItemResponseSchema, MetadataCo
import { errorCodeIs } from '@object-ui/types';
import { t, tFormat, translateMetadataType, useMetadataLocale } from './i18n.js';

/**
* objectstack#36726 — what a publish conflict's `beforeReload` left at the
* item: `'discarded'`, the draft the Save wrote was taken back, so the reload
* re-reads the live row; `'kept'`, a draft pending before the Save stays (it
* carries the page's edits), so the reload re-reads that draft (rule 9).
*/
export type BeforeReloadOutcome = 'discarded' | 'kept';

/** What a guarded save ended in, when it did not throw. */
export type DraftSaveOutcome = 'saved' | 'reloaded';

Expand Down Expand Up @@ -306,6 +323,13 @@ export class DraftVersionGuard {
private readonly held = new Map<string, DraftPin>();
/** objectstack#36601 — the published layer's pin per item, for the Save's publish (rules 6–8). */
private readonly published = new Map<string, DraftPin>();
/**
* objectstack#36726 — rule 9: per item, the published pin a conflict was
* raised on, held over a reload that re-read a pending draft until the
* author re-confirms; `fresh` is what the reload's load recorded meanwhile
* (absent until it has), taken once the item is confirmed.
*/
private readonly unconfirmed = new Map<string, { pin: DraftPin; fresh?: DraftPin | null }>();
private tail: Promise<void> | null = null;
/** Bumped by a reload: a save queued before it carries the replaced buffer. */
private epoch = 0;
Expand All @@ -324,46 +348,70 @@ export class DraftVersionGuard {

/** The published pin held, for the item `publish` would address (tests read it). */
publishedFor(type: string, name: string, packageId?: string | null): DraftPin | null {
return this.published.get(itemKey(type, name, packageId)) ?? null;
const key = itemKey(type, name, packageId);
return this.unconfirmed.get(key)?.pin ?? this.published.get(key) ?? null;
}

/** The buffer was installed with no draft read behind it: nothing describes it. */
forget = (): void => {
this.held.clear();
this.published.clear();
this.unconfirmed.clear();
};

/**
* objectstack#36726 — rule 9 ends for the item: its publish takes the pin
* the last load recorded, if one has since the reload.
*/
private confirm(key: string): void {
const entry = this.unconfirmed.get(key);
if (!entry) return;
this.unconfirmed.delete(key);
if (entry.fresh) this.published.set(key, entry.fresh);
else if (entry.fresh === null) this.published.delete(key);
}

/**
* objectstack#36601 — the buffer was installed from a load whose `/layers`
* read, at the address the buffer's publish writes, served `pin`
* ({@link publishedPinOf}). `null` pins nothing.
*/
recordPublished = (type: string, name: string, packageId: string | null | undefined, pin: DraftPin | null): void => {
const key = itemKey(type, name, packageId);
// objectstack#36726 — a reload that re-read a pending draft is not the
// author's answer to the conflict: the pin it was raised on stays (rule 9).
const entry = this.unconfirmed.get(key);
if (entry) {
entry.fresh = pin;
return;
}
if (pin) this.published.set(key, pin);
else this.published.delete(key);
};

/**
* objectstack#36601 — the Save's publish of the draft it just wrote, pinned
* to the published version this buffer holds (rules 6–8 above). Resolves
* to the published version this buffer holds (rules 6–9 above). Resolves
* `'published'`, or `'reloaded'` when the author chose to reload after a
* conflict (`beforeReload` has run, then the caller's reload); throws the
* client's error otherwise, and the guard's "not saved" error when the
* author kept editing.
* author kept editing. `beforeReload` answers what it left at the item
* ({@link BeforeReloadOutcome}); one that answers nothing is `'discarded'`.
*/
publish = async (
client: Pick<MetadataClient, 'publish'>,
type: string,
name: string,
options: { packageId?: string; member?: string } = {},
beforeReload?: () => Promise<void>,
beforeReload?: () => Promise<BeforeReloadOutcome | void>,
): Promise<'published' | 'reloaded'> => {
const key = itemKey(type, name, options.packageId);
let pin = this.published.get(key) ?? null;
let pin = this.unconfirmed.get(key)?.pin ?? this.published.get(key) ?? null;
for (;;) {
try {
const receipt = await client.publish(type, name, { ...options, ...(pin ?? {}) });
// The publish the author's buffer was built for landed: rule 9 is over for it.
this.unconfirmed.delete(key);
const version = receiptVersion(receipt);
if (version) this.published.set(key, { ifMatch: version });
else this.published.delete(key);
Expand All @@ -376,10 +424,14 @@ export class DraftVersionGuard {
// A `beforeReload` that throws (its draft could not be taken back)
// stops the reload here: nothing is re-read and the pins stay, so
// the next Save is asked about again (contract review S2).
await beforeReload?.();
const left = await beforeReload?.();
this.held.clear();
this.published.clear();
this.epoch += 1;
// objectstack#36726 — the reload re-reads the pending draft it kept,
// which carries the page's edits: never pinned to the fresh read's
// version, so its next Save is refused and asked again (rule 9).
if (left === 'kept' && pin) this.unconfirmed.set(key, { pin });
this.deps.reload();
return 'reloaded';
}
Expand All @@ -389,7 +441,10 @@ export class DraftVersionGuard {
throw kept;
}
// As for a draft: the re-send is pinned to the version the refusal
// names, so a publish landing in between is asked about again.
// names, so a publish landing in between is asked about again. The
// author has seen the live row move and chose this buffer over it:
// that is the re-confirmation rule 9 waits for.
this.unconfirmed.delete(key);
pin = pinOfConflict(err);
if (pin) this.published.set(key, pin);
else this.published.delete(key);
Expand All @@ -403,7 +458,11 @@ export class DraftVersionGuard {
* {@link readDraftForSave} returned. `null` pins nothing, as `forget()`.
*/
recordRead = (type: string, name: string, packageId: string | null | undefined, pin: DraftPin | null): void => {
this.pin(itemKey(type, name, packageId), pin);
const key = itemKey(type, name, packageId);
this.pin(key, pin);
// objectstack#36726 — no draft is pending at the address: the buffer is
// the live row, which the load's published read describes (rule 9 ends).
if (pin && 'ifNoneMatch' in pin) this.confirm(key);
};

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -352,8 +352,10 @@ describe('Customize a read-only base’s flow into its pair (objectstack#28570)'
expect(srv.saves, 'nothing is written before Save (objectstack#36511)').toEqual([]);
await pressStudioSave();
await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 });
// Then that one flow is published at the pair: the override is live.
await waitFor(() => expect(srv.publishes).toEqual([{ name: FLOW_NAME, opts: { packageId: PAIR } }]));
// 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: '*' } }]));
expect(srv.ensure).toEqual([201]);
const [saved] = srv.saves;
expect(saved!.name).toBe(FLOW_NAME);
Expand Down
Loading
Loading