From 871f186df890122fed130c95057d8103f97adb7a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:17:05 +0000 Subject: [PATCH 1/3] wip: OWD draft save through the guard --- .../studio-design/PackageOwdOverviewPanel.tsx | 269 ++++++++++++++---- 1 file changed, 213 insertions(+), 56 deletions(-) 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 f3046b31b11..0ff32a1047a 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx @@ -25,6 +25,10 @@ * (objectstack#36962, as objectstack#36726 pins the Studio editors): a * publish over a row another writer published since is refused and the * author is asked (reload, overwrite, keep editing), never replaced. + * • Each row's draft save goes through the same guard, pinned to the draft + * read of the load the edit was made on (objectstack#37515): a draft + * written since, or one that appeared after the page loaded, is refused + * and asked about, never overwritten or published unseen. * • `controlled_by_parent` rows show the master link (read-only) under the * row's dial. * • There is no external column: `externalSharingModel` is retired by @@ -67,7 +71,12 @@ import { readFields } from '../metadata-admin/previews/object-fields-io.js'; import { t, tFormat, type SupportedLocale } from '../metadata-admin/i18n.js'; import { cbpMasterDetailDefaultsRequired, deriveMasterObject, requireCbpMasterDetails } from './owd-sharing.js'; import { toast } from 'sonner'; -import { type DraftPin, useDraftSaveGuard } from '../metadata-admin/DraftConflictDialog.js'; +import { + type DraftPin, + type DraftReadForSave, + readDraftForSave, + useDraftSaveGuard, +} from '../metadata-admin/DraftConflictDialog.js'; import { STUDIO_SAVE_TOAST_ID, publishSavedItem, @@ -102,6 +111,18 @@ interface OwdRow { hasDraft: boolean; /** True when the package's published list held this object at load (objectui#11799). */ saved: boolean; + /** What this load read, for an edit made on this row ({@link RowBasis}). */ + basis: RowBasis; +} + +/** + * objectstack#37515 — what a row's edit was made against: the reads of the + * load the author saw. A Save writes the edit over THIS, never over a read + * taken at Save time, so a draft another writer saved since, or one that + * appeared after the page loaded, is refused at the draft door and asked + * about, never overwritten and never published under the author's Save. + */ +interface RowBasis { /** * objectstack#36962 — the published row this row was loaded at, the pin its * Save's publish sends (`publishedPinOfLayers` of the row's layers read). A @@ -110,6 +131,60 @@ interface OwdRow { * failed pins nothing. */ published: DraftPin | null; + /** + * The pin its draft save sends (`readDraftForSave` at the package the save + * writes): `If-Match` the draft read, `If-None-Match: *` when the load read + * none. A draft read that failed pins nothing. + */ + draft: DraftPin | null; + /** The pending draft the load read, as-is; `null` when it read none. */ + draftBody: Record | null; + /** + * True when a draft was pending before this edit's first Save: a refused + * publish then takes back nothing (`publishSavedItem`'s `hadDraft`). + */ + hadDraft: boolean; + /** True when the draft read neither served a draft nor said there is none: a failure. */ + draftUnread: boolean; + /** The server's refusal, when the draft read was refused `403` (`readDraftForSave`). */ + draftRefused?: unknown; +} + +/** One draft read, as the basis of an edit made over it. */ +function draftBasisOf(read: DraftReadForSave>): Omit { + const draftBody = extractDraftBody(read.answer) ?? null; + return { + draft: read.pin, + draftBody, + hadDraft: !!draftBody, + // `pin` is `If-None-Match: *` for an answer of "no draft"; a read that + // failed answers nothing and pins nothing. + draftUnread: !draftBody && read.pin === null && !('refused' in read), + ...('refused' in read ? { draftRefused: read.refused } : {}), + }; +} + +/** The key a row's {@link RowBasis} is held under: the package and the object, never the name alone. */ +function basisKey(packageId: string, name: string): string { + return JSON.stringify([packageId, name]); +} + +/** An object's layers at the package this table lists and saves; a read that fails answers `null`. */ +function readLayeredAt( + client: MetadataClient, + packageId: string, + name: string, +): Promise> | null> { + // ADR-0048 — the layers at the package this table lists and saves, the + // object's owner here: a layered read naming no package is refused for a + // name two packages hold. + return client.layered>('object', name, { packageId }).catch(() => null); +} + +/** The published baseline a layers read serves, `{}` for none. */ +function baselineOf(layered: unknown): Record { + const lay = (layered ?? {}) as { effective?: Record; code?: Record }; + return (lay.effective ?? lay.code ?? {}) as Record; } /** @@ -128,21 +203,20 @@ async function readObjectBodies( packageId: string, name: string, saved: boolean, -): Promise<[MetadataLayered> | null, unknown]> { - // ADR-0048 — the layers at the package this table lists and saves, the - // object's owner here: a layered read naming no package is refused for a - // name two packages hold. - const readLayered = () => client.layered>('object', name, { packageId }).catch(() => null); - const readDraft = () => client.getDraft>('object', name).catch(() => null); +): Promise<[MetadataLayered> | null, DraftReadForSave>]> { + const readLayered = () => readLayeredAt(client, packageId, name); + // objectstack#37515 — the draft is read at the address the row's draft save + // writes (`?package=`), so the version it serves pins that save. + const readDraft = () => readDraftForSave>(client, 'object', name, packageId); if (saved) return Promise.all([readLayered(), readDraft()]); - const draftResp = await readDraft(); - if (extractDraftBody(draftResp)) return [null, draftResp]; - return [await readLayered(), draftResp]; + const draftRead = await readDraft(); + if (extractDraftBody(draftRead.answer)) return [null, draftRead]; + return [await readLayered(), draftRead]; } /** * objectstack#36962 — the pin a row's Save publishes with, from the load's - * reads ({@link OwdRow.published}): the layers it read, else, for a row the + * reads ({@link RowBasis.published}): the layers it read, else, for a row the * published list does not hold (its layers not asked while its draft is in * hand), no published row. A saved row whose layers read failed pins nothing. */ @@ -290,17 +364,32 @@ export function PackageOwdOverviewPanel({ const [prereq, setPrereq] = React.useState(null); // objectstack#36962 — each row's publish is pinned to the published row its // load read (`recordPublished`), so a Save over a row another writer - // published since opens the conflict dialog instead of replacing it. The - // guard's own reload is not used: the Save that met the conflict re-reads - // the table itself once its pass ends (`reloadKeeping`), keeping the edits - // of the rows it did not save, which a reload of the whole table would drop. - const { recordPublished, publish: publishPinned, dialog: conflictDialog } = useDraftSaveGuard(client, keepPageOnReload); - // The pin each row's edit was made against: a load that keeps a row's edit - // keeps that row pinned to the read the edit was made on, never the fresh one. - // It is the panel's own record, sent to the guard again before each row's - // publish: a conflict's reload clears every pin the guard holds, for every - // row, while this pass goes on with the rows after it. - const editPinsRef = React.useRef(new Map()); + // published since opens the conflict dialog instead of replacing it. + // objectstack#37515 — and each row's draft save to the draft its load read + // (`recordRead`, `save`), so a draft another writer saved since, or one that + // appeared after the load, opens the same dialog. The guard's own reload is + // not used: the Save that met the conflict re-reads the table itself once + // its pass ends (`reloadKeeping`), keeping the edits of the rows it did not + // save, which a reload of the whole table would drop. + const { + save: saveDraftGuarded, + recordRead, + recordPublished, + publish: publishPinned, + heldDraftVersion, + dialog: conflictDialog, + } = useDraftSaveGuard(client, keepPageOnReload); + // What each row's edit was made against ({@link RowBasis}), keyed by package + // and name: a load that keeps a row's edit keeps the basis the edit was made + // on, never the fresh read. It is the panel's own record, sent to the guard + // again before each row's save: a conflict's reload clears every pin the + // guard holds, for every row, while this pass goes on with the rows after + // it. Each installed load rebuilds it from its own rows, and a row's entry + // goes once its publish lands: the guard then holds the receipt's pin. + const editPinsRef = React.useRef(new Map()); + // Loads are sequenced: only the last one started installs its rows and pins, + // so an earlier load finishing late never re-pins a kept edit to its read. + const loadSeqRef = React.useRef(0); // The master a `controlled_by_parent` row derives under is named by its // label (`ux-conventions.labels-over-machine-names`): this package's own // object as this table reads it (its pending draft included), else the @@ -318,7 +407,10 @@ export function PackageOwdOverviewPanel({ master; // `keep` names the rows whose edits the caller puts back over this load. - const load = React.useCallback(async (keep?: ReadonlySet) => { + // Resolves `false` when a later load superseded this one: it installed nothing. + const load = React.useCallback(async (keep?: ReadonlySet): Promise => { + const seq = ++loadSeqRef.current; + const current = () => seq === loadSeqRef.current; setLoaded(false); setLoadError(null); try { @@ -356,10 +448,10 @@ export function PackageOwdOverviewPanel({ names.map(async (name): Promise => { // objectui#11799 — saved = held by the published list read above. const saved = publishedLabel.has(name); - const [layRaw, draftResp] = await readObjectBodies(client, packageId, name, saved); - const lay = (layRaw ?? {}) as { effective?: Record; code?: Record }; - const baseline = (lay.effective ?? lay.code ?? {}) as Record; - const draftBody = extractDraftBody(draftResp); + const [layRaw, draftRead] = await readObjectBodies(client, packageId, name, saved); + const baseline = baselineOf(layRaw); + const draftBasis = draftBasisOf(draftRead); + const draftBody = draftBasis.draftBody; // The pending draft is the whole document: read it as-is, and the // published baseline only when no draft exists (objectui#10765). A // spread over `effective` showed a model the draft had cleared as @@ -375,28 +467,35 @@ export function PackageOwdOverviewPanel({ ), hasDraft: !!draftBody, saved, - published: publishedPinOfRow(layRaw, saved), + basis: { ...draftBasis, published: publishedPinOfRow(layRaw, saved) }, }; }), ); + if (!current()) return false; built.sort((a, b) => a.label.localeCompare(b.label) || a.name.localeCompare(b.name)); - // objectstack#36962 — each row's publish is pinned to what this load read; - // a kept edit stays pinned to the read it was made on. + // objectstack#36962, objectstack#37515 — each row's save is pinned to + // what this load read; a kept edit stays pinned to the reads it was made on. + const bases = new Map(); for (const r of built) { - const kept = keep?.has(r.name) && editPinsRef.current.has(r.name); - const pin = kept ? (editPinsRef.current.get(r.name) ?? null) : r.published; - editPinsRef.current.set(r.name, pin); - recordPublished('object', r.name, packageId, pin); + const key = basisKey(packageId, r.name); + const prior = keep?.has(r.name) ? editPinsRef.current.get(key) : undefined; + const basis = prior ?? r.basis; + bases.set(key, basis); + recordRead('object', r.name, packageId, basis.draft); + recordPublished('object', r.name, packageId, basis.published); } + editPinsRef.current = bases; setRows(built); // Reset working edits to the freshly loaded baseline. setEdits(Object.fromEntries(built.map((r) => [r.name, { internal: r.internal }]))); + return true; } catch (e) { - setLoadError(formatMetadataError(e)); + if (current()) setLoadError(formatMetadataError(e)); + return current(); } finally { - setLoaded(true); + if (current()) setLoaded(true); } - }, [client, packageId, recordPublished]); + }, [client, packageId, recordPublished, recordRead]); React.useEffect(() => { void load(); @@ -470,28 +569,57 @@ export function PackageOwdOverviewPanel({ // Read the rows back from the server, then put back the edits of the rows // this pass did not save. const reloadKeeping = async (unsaved: ReadonlyArray<{ row: { name: string }; edit: OwdEdit }>) => { - await load(new Set(unsaved.map((u) => u.row.name))); + // A later load (the package was published meanwhile) superseded this + // one: it reset every row, as a plain load does, so no edit is put back. + if (!(await load(new Set(unsaved.map((u) => u.row.name))))) return; if (unsaved.length > 0) { setEdits((prev) => ({ ...prev, ...Object.fromEntries(unsaved.map((u) => [u.row.name, u.edit])) })); } }; try { - // Each changed row lands as that object's package-scoped DRAFT: read the - // fresh body (below), apply just `sharingModel` (unset → drop the key), - // save, and publish that one object. Identical to the per-object - // Settings write, N times. + // Each changed row lands as that object's package-scoped DRAFT: the edit + // applied to just `sharingModel` (unset → drop the key) of the body the + // edit was made over (below), saved through the guard, then that one + // object published. Identical to the per-object Settings write, N times. for (const s of changed) { - // objectui#11799 — the row's saved state from the load decides whether - // the baseline is asked before the draft is in hand. - const [layRaw, draftResp] = await readObjectBodies(client, packageId, s.row.name, s.row.saved); - const lay = (layRaw ?? {}) as { effective?: Record; code?: Record }; - const baseline = (lay.effective ?? lay.code ?? {}) as Record; - const draftBody = extractDraftBody(draftResp); + const key = basisKey(packageId, s.row.name); + const held = editPinsRef.current.get(key); + let basis: Omit; + let baseline: Record = {}; + if (held && !held.draftUnread) { + // objectstack#37515 — the draft the load read is the body the edit + // was made over, and its version pins the save: a draft another + // writer saved since, or one that appeared after the load (`If-None- + // Match: *`), is refused at the door and asked about. With no draft + // read, the published baseline is read now; its publish pin holds it. + basis = held; + if (!held.draftBody) baseline = baselineOf(await readLayeredAt(client, packageId, s.row.name)); + } else { + // No load read says what the draft is: the load's draft read failed, + // or this row went live earlier and has not been read back since. + // The body is read now, at the address the save writes, and that + // read pins the save. objectui#11799 — the row's saved state from the + // load decides whether the baseline is asked before the draft is in hand. + const [layRaw, draftRead] = await readObjectBodies(client, packageId, s.row.name, s.row.saved); + basis = draftBasisOf(draftRead); + baseline = baselineOf(layRaw); + } + // objectstack#29148 — a draft the server refused to read is no absence: + // a body seeded from the published layer would be saved over it. + if (basis.draftRefused !== undefined) { + refused.push({ + name: s.row.name, + label: s.row.label, + reason: t('engine.studio.refusal.draftUnreadable', locale), + edit: s.edit, + }); + continue; + } // The pending draft is the whole document — the edit lands on it as-is, // and on the published baseline only when no draft exists // (objectui#10765): a spread over `effective` would put back every key // the draft had deleted and save them again as this object's draft. - const next: Record = { ...(draftBody ?? baseline) }; + const next: Record = { ...(basis.draftBody ?? baseline) }; if (s.edit.internal) next.sharingModel = s.edit.internal; else delete next.sharingModel; // objectui#12326 — switching to `controlled_by_parent` sets @@ -509,8 +637,12 @@ export function PackageOwdOverviewPanel({ // runtime resolved from the list; the authoring door refuses the two // together, for the whole object. So the resolved `options` stay out of // the body, on every bound field and on nothing else. + const body = dropServedPicklistOptions(next); + // Sent to the guard again before each row's save: an earlier row's + // reload in this pass cleared the guard's pins. + recordRead('object', s.row.name, packageId, basis.draft); try { - await client.save('object', s.row.name, dropServedPicklistOptions(next), { + const wrote = await saveDraftGuarded('object', s.row.name, body, { mode: 'draft', packageId, surface: 'studio', @@ -518,6 +650,12 @@ export function PackageOwdOverviewPanel({ // prerequisite below, and only on the rows that carry one. ...(force && relations.length > 0 ? { force: true } : {}), }); + // The draft moved and the author chose to reload: nothing was + // written, and the row is read back once the pass ends. + if (wrote === 'reloaded') { + reloadedNames.add(s.row.name); + continue; + } } catch (e) { // objectstack#27458 — making the relationship required is a change // the server's destructive-change guard asks to confirm (409). Name @@ -543,18 +681,35 @@ export function PackageOwdOverviewPanel({ refused.push({ name: s.row.name, label: s.row.label, reason: formatMetadataError(e), edit: s.edit }); continue; } - // A draft that was pending before this save (a copilot's) is published - // with it; a refused publish takes back only the draft this save wrote. + // The draft now holds this save: the next save of the row's edit is + // pinned to the version it left (the guard's receipt), over this body. + const token = heldDraftVersion('object', s.row.name, packageId); + const written: RowBasis = { + ...basis, + published: held?.published ?? null, + draft: token ? { ifMatch: token } : null, + draftBody: body, + draftUnread: false, + }; + if (held) editPinsRef.current.set(key, written); + // A draft that was pending when the edit was made over it is published + // with it, the author having seen it; a refused publish takes back only + // the draft this save wrote. // objectstack#36962 — pinned to the published row this row was loaded at, // sent again here because an earlier row's reload in this pass cleared - // the guard's pins (and a re-read that failed sent none back). - recordPublished('object', s.row.name, packageId, editPinsRef.current.get(s.row.name) ?? null); + // the guard's pins. A row with no entry went live earlier in this + // session: the guard holds that publish's receipt, and nothing is re-sent. + if (held) recordPublished('object', s.row.name, packageId, held.published); const live = await publishSavedItem( client, { type: 'object', name: s.row.name, packageId }, - s.row.hasDraft, + basis.hadDraft, publishPinned, ); + // The draft this save wrote was taken back: the row holds no draft again. + if (!live.ok && live.draftDiscarded && held) { + editPinsRef.current.set(key, { ...written, draft: { ifNoneMatch: '*' }, draftBody: null }); + } // The published row moved and the author chose to reload it: the row // is read back once the pass ends, and the pass goes on with the other // rows, each still pinned to its own load. The draft this Save wrote is @@ -571,6 +726,8 @@ export function PackageOwdOverviewPanel({ } saved += 1; savedNames.add(s.row.name); + // Live: no draft is left, and the guard holds the publish's receipt. + editPinsRef.current.delete(key); } // A Save leaves no draft: the publish told the ledger behind Changes. // The reload puts every dial back at what the server holds: a refused @@ -586,7 +743,7 @@ export function PackageOwdOverviewPanel({ } finally { setSaving(false); } - }, [rowState, client, packageId, load, locale, publishPinned, recordPublished]); + }, [rowState, client, packageId, load, locale, publishPinned, recordPublished, recordRead, saveDraftGuarded, heldDraftVersion]); // Cancel: every dial back at what the server holds, nothing sent. const doCancel = React.useCallback(() => { From 7b0a3b7a5ebd43236bcd8d021bf89e5bad1b593e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:26:59 +0000 Subject: [PATCH 2/3] fix(ui): OWD overview draft save goes through the draft guard Each row's draft save is pinned to the draft read of the load the edit was made on, so a draft written since, or one that appeared after the load, is refused and asked about instead of overwritten or published unseen. The per-row basis is keyed by package and name, dropped once the row's publish lands, and loads are sequenced. Claude-Session: https://claude.ai/code/session_01L6bhgUnCu5Y93VusJhmEVm Co-authored-by: Claude --- ...wdOverviewPanel.draftPinned-37515.test.tsx | 470 ++++++++++++++++++ ...dOverviewPanel.sharedSelect-11865.test.tsx | 4 +- 2 files changed, 473 insertions(+), 1 deletion(-) create mode 100644 ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.draftPinned-37515.test.tsx 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 new file mode 100644 index 00000000000..478a1a89941 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.draftPinned-37515.test.tsx @@ -0,0 +1,470 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37515 — the OWD overview's Save writes each row's draft through + * the draft guard, pinned to the draft read of the load the author saw. + * + * The publish was already pinned (objectstack#36962); the draft write before + * it was a whole-document PUT over a read taken a moment earlier, so: + * + * 1. a draft another writer saved since the read was replaced entirely; + * 2. a draft that appeared after the page loaded was picked up by the + * Save-time re-read and published live with the row, never shown. + * + * Neither moves the live row, so the published pin catches neither. Now the + * draft save sends `If-Match` the load's draft version, or `If-None-Match: *` + * when the load read none, and the door's `409 METADATA_CONFLICT` opens the + * draft conflict dialog (objectstack#36601) instead. + * + * The other writer is the server double's own move of the draft row. Its + * refusals are parsed by the REAL `MetadataClient`, so the error the guard + * reads is production's. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { MetadataClient, type MetadataError } from '@object-ui/data-objectstack'; +import { t } from '../metadata-admin/i18n'; +import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; + +const PACKAGE = 'com.qa.owd'; +const L = (key: string) => t(key, 'en-US'); +const PUBLIC_READ = L('engine.studio.settings.sharingPublicRead'); +const PUBLIC_READ_WRITE = L('engine.studio.settings.sharingPublicReadWrite'); +const UNPUBLISHED_DRAFT = L('engine.studio.unpublishedDraft'); +const WAIT = { timeout: 4000 }; + +type Body = Record; + +interface Write { + name: string; + ifMatch: string | undefined; + ifNoneMatch: string | undefined; +} + +interface Deferred { + promise: Promise; + release: () => void; +} + +function deferred(): Deferred { + let release!: () => void; + const promise = new Promise((resolve) => { + release = resolve; + }); + return { promise, release }; +} + +interface Server { + published: Map; + publishedVersions: Map; + drafts: Map; + draftVersions: Map; + /** Whether the draft read serves `version` (a server from before it did serves none: the control). */ + servesDraftVersion: boolean; + saves: Write[]; + publishes: Write[]; + resets: string[]; + /** The package each draft read named. */ + draftReadPackages: Array; + /** Run once when the Save reads `name`'s layers: another writer acting in the Save's own window. */ + onSaveLayers: Map void>; + /** Held list reads, released by the test (the load-sequencing case). */ + listGates: Deferred[]; + seq: number; +} + +/** The 409 the door answers, run through the real client's error parser. */ +async function conflictRefusal(name: string, head: string | null): Promise { + const client = new MetadataClient({ + baseUrl: 'http://localhost:3000', + fetch: (async () => + new Response( + JSON.stringify({ + error: `object/${name} has been modified since you loaded it.`, + code: 'METADATA_CONFLICT', + currentVersion: head, + }), + { status: 409, headers: { 'content-type': 'application/json' } }, + )) as unknown as typeof fetch, + }); + return client.publish('object', name).then( + () => { + throw new Error('the stub door accepted the write'); + }, + (e: unknown) => e as MetadataError, + ); +} + +const copy = (v: T): T => JSON.parse(JSON.stringify(v)) as T; + +function newServer(): Server { + const server: Server = { + published: new Map(), + publishedVersions: new Map(), + drafts: new Map(), + draftVersions: new Map(), + servesDraftVersion: true, + saves: [], + publishes: [], + resets: [], + draftReadPackages: [], + onSaveLayers: new Map(), + listGates: [], + seq: 0, + }; + server.published.set('a_alpha', { name: 'a_alpha', label: 'Alpha', sharingModel: 'private', fields: {} }); + server.publishedVersions.set('a_alpha', 'pub:alpha0'); + server.published.set('b_beta', { name: 'b_beta', label: 'Beta', sharingModel: 'private', fields: {} }); + server.publishedVersions.set('b_beta', 'pub:beta0'); + return server; +} + +function makeClient(server: Server, saving: { on: boolean }) { + return { + list: async () => { + const gate = server.listGates.shift(); + if (gate) await gate.promise; + return [...server.published.values()].map((b) => ({ name: b.name, label: b.label })); + }, + listDrafts: async () => [...server.drafts.keys()].map((name) => ({ name })), + layered: async (_t: string, name: string) => { + if (saving.on) { + const act = server.onSaveLayers.get(name); + server.onSaveLayers.delete(name); + act?.(); + } + const live = server.published.get(name) ?? null; + return { + code: null, + overlay: live && copy(live), + effective: live && copy(live), + overlayVersion: live ? (server.publishedVersions.get(name) ?? null) : null, + }; + }, + getDraft: async (_t: string, name: string, opts?: { packageId?: string }) => { + server.draftReadPackages.push(opts?.packageId); + const draft = server.drafts.get(name); + if (!draft) return null; + const version = server.servesDraftVersion ? { version: server.draftVersions.get(name) ?? null } : {}; + return { type: 'object', name, item: copy(draft), ...version }; + }, + save: async (_t: string, name: string, body: Body, opts?: { ifMatch?: string; ifNoneMatch?: '*' }) => { + server.saves.push({ name, ifMatch: opts?.ifMatch, ifNoneMatch: opts?.ifNoneMatch }); + const head = server.drafts.has(name) ? (server.draftVersions.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); + server.seq += 1; + const version = `draft:mine${server.seq}`; + server.drafts.set(name, copy(body)); + server.draftVersions.set(name, version); + return { success: true, version, state: 'draft' }; + }, + publish: async (_t: string, name: string, opts?: { ifMatch?: string; ifNoneMatch?: '*' }) => { + server.publishes.push({ name, ifMatch: opts?.ifMatch, ifNoneMatch: opts?.ifNoneMatch }); + 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); + server.seq += 1; + const version = `pub:mine${server.seq}`; + const draft = server.drafts.get(name); + if (draft) { + server.published.set(name, draft); + server.publishedVersions.set(name, version); + } + server.drafts.delete(name); + server.draftVersions.delete(name); + return { success: true, version }; + }, + reset: async (_t: string, name: string, opts?: { state?: string }) => { + if (opts?.state === 'draft') { + server.resets.push(name); + server.drafts.delete(name); + server.draftVersions.delete(name); + } + return { success: true }; + }, + } as unknown as React.ComponentProps['client']; +} + +/** The panel, and a way to bump its publish nonce (a package publish elsewhere re-reads the table). */ +function renderPanel(server: Server): { saving: { on: boolean }; bumpNonce: () => void } { + const saving = { on: false }; + const client = makeClient(server, saving); + const tree = (nonce: number) => ( + + + + ); + let nonce = 0; + const { rerender } = render(tree(nonce)); + return { saving, bumpNonce: () => rerender(tree(++nonce)) }; +} + +/** Another writer (a copilot, another tab) saves `name`'s draft: the draft row and its version move. */ +function anotherWriterSavesDraft(server: Server, name: string, patch: Body): string { + server.seq += 1; + const version = `draft:theirs${server.seq}`; + const base = server.drafts.get(name) ?? server.published.get(name)!; + server.drafts.set(name, { ...copy(base), ...patch }); + server.draftVersions.set(name, version); + return version; +} + +/** Another admin publishes `name`: the live row and its version move. */ +function anotherAdminPublishes(server: Server, name: string, sharingModel: string): void { + server.seq += 1; + server.published.set(name, { ...server.published.get(name)!, sharingModel }); + server.publishedVersions.set(name, `pub:theirs${server.seq}`); +} + +async function pick(name: string, option: string): Promise { + await screen.findByTestId(`owd-row-${name}`, undefined, WAIT); + fireEvent.keyDown(screen.getByTestId(`owd-internal-${name}`), { key: 'ArrowDown' }); + fireEvent.click(within(await screen.findByRole('listbox')).getByRole('option', { name: option })); + await screen.findByTestId(`owd-dirty-${name}`); +} + +async function save(saving: { on: boolean }): Promise { + saving.on = true; + await pressStudioSave({ settle: false }); +} + +async function nextDialog(): Promise { + return screen.findByTestId('draft-conflict-dialog', undefined, WAIT); +} + +async function answer(choice: 'reload' | 'cancel'): Promise { + fireEvent.click(screen.getByTestId(`draft-conflict-${choice}`)); + await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), WAIT); +} + +/** Let every queued read run to its end. */ +async function settle(): Promise { + for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0)); +} + +const pins = (writes: Write[]) => writes.map((w) => [w.name, w.ifMatch, w.ifNoneMatch]); +const liveSharing = (server: Server, name: string) => server.published.get(name)?.sharingModel; + +let server: Server; +beforeEach(() => { + Element.prototype.scrollIntoView = vi.fn(); + server = newServer(); +}); +afterEach(cleanup); + +describe('the OWD overview — a draft replaced since the load is refused, not overwritten (objectstack#37515)', () => { + it('a pending draft another writer re-saved after the load: the draft save is refused and asked about; nothing is written or published', async () => { + server.drafts.set('a_alpha', { ...server.published.get('a_alpha')!, description: 'the copilot draft' }); + server.draftVersions.set('a_alpha', 'draft:v1'); + const { saving } = renderPanel(server); + await pick('a_alpha', PUBLIC_READ_WRITE); + const theirs = anotherWriterSavesDraft(server, 'a_alpha', { description: 'saved elsewhere' }); + + await save(saving); + const dialog = await nextDialog(); + // The draft dialog, not the live-change one: it is the draft that moved. + expect(dialog).toHaveTextContent(L('engine.draftConflict.title')); + expect(pins(server.saves)).toEqual([['a_alpha', 'draft:v1', undefined]]); + expect(server.publishes).toEqual([]); + + await answer('cancel'); + expect(await screen.findByText(/Alpha: Not saved:/, undefined, WAIT)).toBeInTheDocument(); + // The other writer's draft stands as they saved it; the edit stays on the page. + expect(server.draftVersions.get('a_alpha')).toBe(theirs); + expect(server.drafts.get('a_alpha')).toMatchObject({ description: 'saved elsewhere', sharingModel: 'private' }); + expect(liveSharing(server, 'a_alpha')).toBe('private'); + expect(server.resets).toEqual([]); + expect(screen.getByTestId('owd-dirty-a_alpha')).toBeInTheDocument(); + }); + + it('a draft written in the Save\'s own window, after the Save read the row: refused, not replaced', async () => { + const { saving } = renderPanel(server); + await pick('b_beta', PUBLIC_READ); + let theirs = ''; + server.onSaveLayers.set('b_beta', () => { + theirs = anotherWriterSavesDraft(server, 'b_beta', { description: 'in between' }); + }); + + await save(saving); + await nextDialog(); + expect(pins(server.saves)).toEqual([['b_beta', undefined, '*']]); + await answer('cancel'); + expect(server.draftVersions.get('b_beta')).toBe(theirs); + expect(server.drafts.get('b_beta')).toMatchObject({ description: 'in between', sharingModel: 'private' }); + expect(server.publishes).toEqual([]); + }); + + it('"overwrite" asks again, then the author\'s version replaces the draft and goes live', async () => { + server.drafts.set('a_alpha', { ...server.published.get('a_alpha')!, description: 'the copilot draft' }); + server.draftVersions.set('a_alpha', 'draft:v1'); + const { saving } = renderPanel(server); + await pick('a_alpha', PUBLIC_READ_WRITE); + const theirs = anotherWriterSavesDraft(server, 'a_alpha', { description: 'saved elsewhere' }); + + await save(saving); + await nextDialog(); + fireEvent.click(screen.getByTestId('draft-conflict-overwrite')); + await screen.findByTestId('draft-conflict-overwrite-confirm'); + expect(server.saves).toHaveLength(1); + await act(async () => { + fireEvent.click(screen.getByTestId('draft-conflict-overwrite-confirm')); + }); + await waitFor(() => expect(liveSharing(server, 'a_alpha')).toBe('public_read_write'), WAIT); + // Re-sent pinned to the version the refusal named; what went live is the + // draft the author loaded and edited, not the one saved elsewhere. + expect(pins(server.saves)).toEqual([ + ['a_alpha', 'draft:v1', undefined], + ['a_alpha', theirs, undefined], + ]); + expect(server.published.get('a_alpha')).toMatchObject({ description: 'the copilot draft' }); + }); +}); + +describe('the OWD overview — a draft that appeared after the load is never published unseen (objectstack#37515)', () => { + it('the row loaded with no draft: its save asserts none, is refused, and nothing goes live', async () => { + const { saving } = renderPanel(server); + await pick('a_alpha', PUBLIC_READ_WRITE); + const theirs = anotherWriterSavesDraft(server, 'a_alpha', { sharingModel: 'public_read', description: 'the copilot draft' }); + + await save(saving); + await nextDialog(); + expect(pins(server.saves)).toEqual([['a_alpha', undefined, '*']]); + await answer('cancel'); + expect(await screen.findByText(/Alpha: Not saved:/, undefined, WAIT)).toBeInTheDocument(); + // Nothing the author never saw went live, and the copilot's draft is not taken back as if this Save wrote it. + expect(server.publishes).toEqual([]); + expect(liveSharing(server, 'a_alpha')).toBe('private'); + expect(server.resets).toEqual([]); + expect(server.draftVersions.get('a_alpha')).toBe(theirs); + }); + + it('"reload" shows the draft under its mark; the next Save, made over it, goes live', async () => { + const { saving } = renderPanel(server); + await pick('a_alpha', PUBLIC_READ_WRITE); + const theirs = anotherWriterSavesDraft(server, 'a_alpha', { sharingModel: 'public_read', description: 'the copilot draft' }); + + await save(saving); + await nextDialog(); + await answer('reload'); + await waitFor(() => expect(screen.queryByTestId('owd-dirty-a_alpha')).toBeNull(), WAIT); + expect(screen.getByTestId('owd-internal-a_alpha')).toHaveTextContent(PUBLIC_READ); + expect(within(screen.getByTestId('owd-row-a_alpha')).getByText(UNPUBLISHED_DRAFT)).toBeInTheDocument(); + expect(server.publishes).toEqual([]); + + await pick('a_alpha', PUBLIC_READ_WRITE); + await save(saving); + await waitFor(() => expect(liveSharing(server, 'a_alpha')).toBe('public_read_write'), WAIT); + expect(server.saves[server.saves.length - 1]).toMatchObject({ name: 'a_alpha', ifMatch: theirs }); + expect(server.published.get('a_alpha')).toMatchObject({ description: 'the copilot draft' }); + expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(); + }); +}); + +describe('the OWD overview — the draft pin, with no other writer (objectstack#37515)', () => { + it('control: the draft is read at the package; each save is pinned to its load and lands; no dialog', async () => { + server.drafts.set('a_alpha', { ...server.published.get('a_alpha')!, description: 'the copilot draft' }); + server.draftVersions.set('a_alpha', 'draft:v1'); + const { saving } = renderPanel(server); + await pick('a_alpha', PUBLIC_READ); + await pick('b_beta', PUBLIC_READ_WRITE); + await save(saving); + await waitFor(() => expect(liveSharing(server, 'b_beta')).toBe('public_read_write'), WAIT); + expect(liveSharing(server, 'a_alpha')).toBe('public_read'); + expect(pins(server.saves)).toEqual([ + ['a_alpha', 'draft:v1', undefined], + ['b_beta', undefined, '*'], + ]); + expect(new Set(server.draftReadPackages)).toEqual(new Set([PACKAGE])); + expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(); + }); + + it('control: one editor saving one row twice never conflicts with its own Save (the entry goes on publish)', async () => { + const { saving } = renderPanel(server); + await pick('a_alpha', PUBLIC_READ); + await save(saving); + await waitFor(() => expect(screen.queryByTestId('owd-dirty-a_alpha')).toBeNull(), WAIT); + await pick('a_alpha', PUBLIC_READ_WRITE); + await save(saving); + await waitFor(() => expect(liveSharing(server, 'a_alpha')).toBe('public_read_write'), WAIT); + expect(pins(server.saves)).toEqual([ + ['a_alpha', undefined, '*'], + ['a_alpha', undefined, '*'], + ]); + expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(); + }); + + it('control: a server whose draft read serves no `version` gets an unpinned draft save, as before', async () => { + server.servesDraftVersion = false; + server.drafts.set('a_alpha', { ...server.published.get('a_alpha')!, description: 'the copilot draft' }); + server.draftVersions.set('a_alpha', 'draft:v1'); + const { saving } = renderPanel(server); + await pick('a_alpha', PUBLIC_READ); + await save(saving); + await waitFor(() => expect(liveSharing(server, 'a_alpha')).toBe('public_read'), WAIT); + expect(pins(server.saves)).toEqual([['a_alpha', undefined, undefined]]); + }); + + it('a row refused at its draft save keeps its edit over a re-read, still pinned to the load it was made on', async () => { + const { saving } = renderPanel(server); + await pick('a_alpha', PUBLIC_READ_WRITE); + await pick('b_beta', PUBLIC_READ); + anotherWriterSavesDraft(server, 'a_alpha', { description: 'the copilot draft' }); + await save(saving); + await nextDialog(); + await answer('cancel'); + // Beta went live and the table was read back, Alpha's edit kept. + await waitFor(() => expect(liveSharing(server, 'b_beta')).toBe('public_read'), WAIT); + await waitFor(() => expect(screen.queryByTestId('owd-dirty-b_beta')).toBeNull(), WAIT); + expect(screen.getByTestId('owd-dirty-a_alpha')).toBeInTheDocument(); + + // That re-read served the copilot's draft; the kept edit is still the one made with none: asked again. + const before = server.saves.length; + await save(saving); + await nextDialog(); + expect(pins(server.saves.slice(before))).toEqual([['a_alpha', undefined, '*']]); + expect(liveSharing(server, 'a_alpha')).toBe('private'); + }); +}); + +describe('the OWD overview — loads are sequenced (objectstack#37515)', () => { + it('a plain load finishing before the kept-edit re-read it overlapped does not re-pin the kept edit to its read', async () => { + const { saving, bumpNonce } = renderPanel(server); + await pick('a_alpha', PUBLIC_READ_WRITE); + await pick('b_beta', PUBLIC_READ); + anotherAdminPublishes(server, 'a_alpha', 'public_read'); + // Hold the next two loads: the package-publish re-read, then the Save's kept-edit re-read. + const plain = deferred(); + const keep = deferred(); + server.listGates.push(plain, keep); + + await save(saving); + await nextDialog(); + bumpNonce(); + await answer('cancel'); + // Beta goes live; the pass's re-read (keeping Alpha's edit) waits behind the plain one. + await waitFor(() => expect(liveSharing(server, 'b_beta')).toBe('public_read'), WAIT); + // The plain load runs to its end first, then the kept-edit re-read. + await act(async () => { + plain.release(); + await settle(); + }); + await act(async () => { + keep.release(); + await settle(); + }); + await waitFor(() => expect(screen.queryByTestId('owd-dirty-b_beta')).toBeNull(), WAIT); + expect(screen.getByTestId('owd-dirty-a_alpha')).toBeInTheDocument(); + + // Alpha's next publish is still pinned to the row its edit was made on: asked, never published over theirs. + const before = server.publishes.length; + await save(saving); + await nextDialog(); + expect(pins(server.publishes.slice(before))).toEqual([['a_alpha', 'pub:alpha0', undefined]]); + expect(liveSharing(server, 'a_alpha')).toBe('public_read'); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.sharedSelect-11865.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.sharedSelect-11865.test.tsx index 17a029ea3f4..bee8371cd36 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.sharedSelect-11865.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.sharedSelect-11865.test.tsx @@ -130,8 +130,10 @@ describe('the OWD overview dials are the shared Select (objectui#11865)', () => }); }); +// objectstack#37515 — the draft save is pinned to the load's draft read; these +// rows loaded with no draft, so it asserts none (`If-None-Match: *`). const SAVED = (name: string, body: Body) => - JSON.stringify([{ name, body, opts: { mode: 'draft', packageId: 'pkg.a', surface: 'studio' } }]); + JSON.stringify([{ name, body, opts: { mode: 'draft', packageId: 'pkg.a', surface: 'studio', ifNoneMatch: '*' } }]); /** * [dial, option label, the JSON text of the saves Save sent]. `null`: the From f0bb20d447a5b7527320fa65eae33726abb8553d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:32:00 +0000 Subject: [PATCH 3/3] chore: changeset for the OWD overview's guarded draft save Claude-Session: https://claude.ai/code/session_01L6bhgUnCu5Y93VusJhmEVm Co-authored-by: Claude --- .changeset/37515-owd-overview-guarded-draft-save.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .changeset/37515-owd-overview-guarded-draft-save.md diff --git a/.changeset/37515-owd-overview-guarded-draft-save.md b/.changeset/37515-owd-overview-guarded-draft-save.md new file mode 100644 index 00000000000..24628c52fe5 --- /dev/null +++ b/.changeset/37515-owd-overview-guarded-draft-save.md @@ -0,0 +1,10 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(app-shell): the Studio sharing-defaults overview's Save no longer overwrites, or publishes unseen, a draft saved elsewhere since the page loaded + +Clause-②: no +Metadata-protocol: none + +The overview of every object's org-wide sharing default (Studio → Access) now writes each changed object's draft the way the Studio editors do: pinned to the draft its load read, at the package the save writes. A draft another writer (a copilot, another admin, another tab) saved after the load is no longer replaced by the Save, and a draft that appeared after the load is no longer published live under the author's Save without the unpublished-draft mark ever being shown: the draft save is refused and the conflict dialog asks to reload the saved draft, overwrite it with the author's version after a confirmation, or keep editing. An object whose draft the server will not let this session read is not saved over that draft; the Save names it. An object kept unsaved stays pinned to the reads its edit was made on, and a re-read of the table that a later one overtakes installs nothing. Against a server that serves no draft version, the draft save goes unpinned, as before.