diff --git a/.changeset/36137-pinned-view-draft-writes.md b/.changeset/36137-pinned-view-draft-writes.md new file mode 100644 index 00000000000..52bfbd396cb --- /dev/null +++ b/.changeset/36137-pinned-view-draft-writes.md @@ -0,0 +1,16 @@ +--- +'@object-ui/app-shell': patch +--- + +fix(console): a view settings save is pinned to the draft it opened, so it can no longer be published by someone else's Save to this view + +Clause-②: yes (widening) — `ViewConfigPanel`'s `onSave` host prop gains an optional second parameter, the panel's draft-version guard (`saveDraft`), which the panel always passes; a host that takes one argument is called as before; nothing removed or renamed +Metadata-protocol: none + +**Save to this view** on a shared view writes a draft and then publishes it. A save from the view settings panel that landed between the two used to overwrite that draft unpinned, and the publish then made the settings panel's unreviewed change live for everyone. + +- The view settings panel now sends its draft save pinned to the draft it opened: `If-Match` with the version its load read, or `If-None-Match: *` when the view had no draft. After a save lands, the next one is pinned to that save's receipt. A save over a draft that changed since (another admin's settings save, or a Save to this view in flight) is refused by the server, and the panel opens the Studio editors' draft conflict dialog: reload the saved version, overwrite it after a second confirmation, or keep editing. The edit stays in the panel until the author chooses. +- Creating a view (the Create View dialog, the panel's create mode, Save as view) sends the first-write pin, `If-None-Match: *`, so a create over a name that already holds a pending draft is refused instead of writing over it. +- A host of `ViewConfigPanel` that writes through the guard it receives gets the pin and the dialog; a host that ignores it saves unpinned, as before. + +No metadata key, value or default changes. diff --git a/content/docs/ui/views.mdx b/content/docs/ui/views.mdx index 4c612f4e703..a5fa0800361 100644 --- a/content/docs/ui/views.mdx +++ b/content/docs/ui/views.mdx @@ -641,7 +641,10 @@ also holds Discard on a narrow list or a phone). widths into the view. When the view already has unpublished changes (a draft saved from the view settings, by anyone), nothing is saved: the Console says so and points to the view settings to publish or discard that draft first. Every other change to a shared view still - goes to a draft that the view settings publish. + goes to a draft that the view settings publish. A view settings save is pinned to the draft + the settings opened, so one that lands while a Save to this view is between its save and its + publish is refused, never published with it: the settings say the draft changed and offer + to reload it, overwrite it or keep editing. - A footer calculation is offered on every column the saved view would carry: the columns the list draws and the fields the user added. Picking the view's own calculation again takes that column out of the draft. diff --git a/ui/packages/app-shell/src/views/ObjectView.createChartView-11576.test.tsx b/ui/packages/app-shell/src/views/ObjectView.createChartView-11576.test.tsx index 2267a26c0e2..7cd3267cbcc 100644 --- a/ui/packages/app-shell/src/views/ObjectView.createChartView-11576.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.createChartView-11576.test.tsx @@ -205,7 +205,7 @@ async function createChartViewThroughTheSwitcher() { await waitFor(() => expect(metadataClient.save).toHaveBeenCalledTimes(1)); const [type, , body, opts] = metadataClient.save.mock.calls[0] as unknown as [string, string, any, any]; expect(type).toBe('view'); - expect(opts).toEqual({ mode: 'draft' }); + expect(opts).toEqual({ mode: 'draft', ifNoneMatch: '*' }); return body; } diff --git a/ui/packages/app-shell/src/views/ObjectView.createKanbanView-11581.test.tsx b/ui/packages/app-shell/src/views/ObjectView.createKanbanView-11581.test.tsx index 6feec9671cc..afd223f7694 100644 --- a/ui/packages/app-shell/src/views/ObjectView.createKanbanView-11581.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.createKanbanView-11581.test.tsx @@ -164,7 +164,7 @@ describe('ObjectView.handleViewCreate persists a kanban through the one builder await waitFor(() => expect(metadataClient.save).toHaveBeenCalledTimes(1)); const [type, , body, opts] = metadataClient.save.mock.calls[0] as unknown as [string, string, any, any]; expect(type).toBe('view'); - expect(opts).toEqual({ mode: 'draft' }); + expect(opts).toEqual({ mode: 'draft', ifNoneMatch: '*' }); // The spec's verdict first: it is the claim this pin exists for. const listView = ListViewSchema.safeParse(body.config); expect(listView.success, JSON.stringify(listView.error?.issues)).toBe(true); diff --git a/ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx b/ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx index 58543ac6eed..de66d7dfa6f 100644 --- a/ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.viewConfigSaveWiring-10210.test.tsx @@ -81,29 +81,42 @@ vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({ useMetadataClient: () => metadataClient, })); +// objectstack#36137 — the panel's draft-version guard, as the real panel hands it over. +const panelGuardSave = vi.fn(async () => 'saved' as const); + // The panel, reduced to its Save: it hands the host the draft the real panel -// produced for a label edit (live capture, objectui#10210). -vi.mock('./ViewConfigPanel', () => ({ - ViewConfigPanel: ({ activeView, onSave }: any) => ( - - ), -})); +// produced for a label edit (live capture, objectui#10210), with or without +// its guard. +vi.mock('./ViewConfigPanel', () => { + const editedDraft = (activeView: any) => ({ + label: 'Everything EDITED', + type: activeView.type, + columns: activeView.columns, + name: activeView.name, + isDefault: !!activeView.isDefault, + id: activeView.id, + }); + return { + ViewConfigPanel: ({ activeView, onSave }: any) => ( + <> + + + + ), + }; +}); +// The view's source reaches a dynamic import of `@objectstack/lint`: pay its +// load at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; import { ObjectView } from './ObjectView'; import { ExpressionProvider } from '../providers/ExpressionProvider'; @@ -154,8 +167,7 @@ afterEach(() => { vi.clearAllMocks(); }); -describe('ObjectView — Edit view config → Save (objectui#10210)', () => { - it('stages a spec-valid ViewItem envelope on the row the tab is keyed by', async () => { +function mountObjectView() { render( @@ -168,6 +180,11 @@ describe('ObjectView — Edit view config → Save (objectui#10210)', () => { , ); +} + +describe('ObjectView — Edit view config → Save (objectui#10210)', () => { + it('stages a spec-valid ViewItem envelope on the row the tab is keyed by', async () => { + mountObjectView(); await settle(); await act(async () => { @@ -186,3 +203,20 @@ describe('ObjectView — Edit view config → Save (objectui#10210)', () => { expect(verdict.success, JSON.stringify(verdict.error?.issues)).toBe(true); }); }); + +describe('ObjectView — the view settings save writes through the panel\'s guard (objectstack#36137)', () => { + it('sends the envelope through the guard the panel hands it, never straight to the client', async () => { + mountObjectView(); + await settle(); + + await act(async () => { + fireEvent.click(screen.getByTestId('stub-view-config-guarded-save')); + }); + + expect(metadataClient.save).not.toHaveBeenCalled(); + expect(panelGuardSave).toHaveBeenCalledTimes(1); + const [type, name, body, opts] = panelGuardSave.mock.calls[0] as unknown as [string, string, any, any]; + expect([type, name, opts]).toEqual(['view', VIEW_ID, { mode: 'draft' }]); + expect(body).toMatchObject({ name: VIEW_ID, object: OBJECT_NAME, viewKind: 'list', label: 'Everything EDITED' }); + }); +}); diff --git a/ui/packages/app-shell/src/views/ViewConfigPanel.pinnedDraftSave-36137.test.tsx b/ui/packages/app-shell/src/views/ViewConfigPanel.pinnedDraftSave-36137.test.tsx new file mode 100644 index 00000000000..8379d13981c --- /dev/null +++ b/ui/packages/app-shell/src/views/ViewConfigPanel.pinnedDraftSave-36137.test.tsx @@ -0,0 +1,426 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36137 — the view settings save and the view create are pinned, + * so a view settings save that lands between 「Save to this view」's draft write + * and its publish is refused instead of being published with it (ruling record + * 7058616478 on objectstack#35955: a pending draft is never published on + * someone else's behalf). The draft half of `ObjectStackAdapter.updateView` + * (rename, pin, set as default) is not pinned and is not pinned here. + * + * The door is a `fetch` double of the `/meta` draft door, answering the way + * `DraftConflictDialog.test.tsx` records it was measured to answer (a draft + * save's receipt `version`, the draft read's `version`, `409 + * METADATA_CONFLICT` with `currentVersion` for a stale `If-Match` or for + * `If-None-Match: *` over a draft), plus a publish that promotes the draft and + * drops it. Every address names no package, as these Console writers do. The + * client is the REAL `MetadataClient`, so the headers on the wire are + * production's. + * + * The panel's host is the body of `handleViewConfigSave`: the panel's buffer + * through `buildViewConfigSaveBody`, written by `persistRuntimeMetadata` with + * the guard the panel hands it. That `ObjectView`'s handler forwards the guard + * is pinned in `ObjectView.viewConfigSaveWiring-10210.test.tsx`. + */ + +import { useState } from 'react'; +import { describe, it, expect, vi } from 'vitest'; +import { render, screen, fireEvent, act, waitFor, cleanup } from '@testing-library/react'; +import { MetadataClient } from '@object-ui/data-objectstack'; + +vi.mock('./RuntimeDraftBar', () => ({ RuntimeDraftBar: () => null })); + +// One control: an edit of the view's label, as the real inspector's label field patches it. +vi.mock('./metadata-admin/inspectors/ViewVariantInspector', () => ({ + ViewVariantInspector: ({ draft, onPatch }: any) => ( +
+ {String(draft?.label)} + +
+ ), +})); + +// Paid at collection, never inside a case's clocked window (`check:test-source-alias`). +import '@objectstack/lint'; +import '@objectstack/formula'; +import { ViewConfigPanel } from './ViewConfigPanel'; +import { buildViewConfigSaveBody } from './objectViewTabs'; +import { + createRuntimeMetadata, + persistRuntimeMetadata, + saveAndPublishRuntimeMetadata, + viewEnvelope, +} from './runtime-metadata-persistence'; +import type { DraftVersionGuard } from './metadata-admin/DraftConflictDialog'; + +const OBJECT = 'crm_lead'; +const VIEW_ID = `${OBJECT}.all`; +const PUBLISHED = { + name: VIEW_ID, + object: OBJECT, + viewKind: 'list', + label: 'Everything', + config: { type: 'grid', columns: [{ field: 'name' }], data: { provider: 'object', object: OBJECT } }, +}; + +function json(status: number, body: unknown): Response { + return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); +} + +const token = (seq: number) => `hmac-sha256:${seq.toString(16).padStart(64, '0')}`; + +interface SentPut { + name: string; + ifMatch: string | null; + ifNoneMatch: string | null; + label: unknown; + status: number; +} + +/** The `/meta` view doors for package-less addresses; `holdPublish` parks the next publish. */ +function viewDoor(start: { draft?: Record } = {}) { + let seq = 0; + const published = new Map>([[VIEW_ID, PUBLISHED]]); + const drafts = new Map; version: string }>(); + if (start.draft) drafts.set(VIEW_ID, { body: start.draft, version: token(++seq) }); + const puts: SentPut[] = []; + const publishes: Array> = []; + let parked: { release: () => void } | null = null; + let parkNext = false; + let parkedPut: { release: () => void } | null = null; + let parkNextPut = false; + let putArrived: () => void = () => {}; + const putArrival = new Promise((resolve) => { putArrived = resolve; }); + let publishArrived: () => void = () => {}; + const arrived = new Promise((resolve) => { publishArrived = resolve; }); + + const fetchImpl = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(input)); + const method = init?.method ?? 'GET'; + if (url.pathname.endsWith('/meta/_drafts')) { + return json(200, { drafts: [...drafts.keys()].map((name) => ({ type: 'view', name })) }); + } + const m = /\/meta\/view\/([^/]+)(\/layers|\/publish)?$/.exec(url.pathname); + if (!m) return json(404, { error: 'not modelled' }); + const name = decodeURIComponent(m[1]!); + const tail = m[2]; + if (method === 'GET' && tail === '/layers') { + const effective = published.get(name) ?? null; + return json(200, { + code: null, + overlay: effective, + overlayScope: effective ? 'env' : null, + effective, + draft: drafts.get(name)?.body ?? null, + }); + } + if (method === 'GET' && url.searchParams.get('state') === 'draft') { + const row = drafts.get(name); + if (!row) return json(404, { error: `No pending draft exists for view/${name}.`, code: 'NO_DRAFT' }); + return json(200, { type: 'view', name, item: row.body, version: row.version }); + } + if (method === 'POST' && tail === '/publish') { + if (parkNext) { + parkNext = false; + publishArrived(); + await new Promise((resolve) => { parked = { release: resolve }; }); + } + const row = drafts.get(name); + if (!row) return json(404, { error: `No pending draft exists for view/${name}.`, code: 'NO_DRAFT' }); + published.set(name, row.body); + drafts.delete(name); + publishes.push(row.body); + return json(200, { success: true, version: token(++seq), seq, message: 'published' }); + } + if (method === 'DELETE') { + drafts.delete(name); + return json(200, { success: true }); + } + if (method !== 'PUT' || url.searchParams.get('mode') !== 'draft') return json(404, { error: 'not modelled' }); + if (parkNextPut) { + parkNextPut = false; + putArrived(); + await new Promise((resolve) => { parkedPut = { release: resolve }; }); + } + const headers = new Headers(init?.headers); + const ifMatch = headers.get('If-Match'); + const ifNoneMatch = headers.get('If-None-Match'); + const body = JSON.parse(String(init?.body)) as Record; + const head = drafts.get(name)?.version ?? null; + const refused = + (ifMatch !== null && (head === null || ifMatch.replace(/^"|"$/g, '') !== head)) || + (ifNoneMatch !== null && head !== null); + puts.push({ name, ifMatch, ifNoneMatch, label: body.label, status: refused ? 409 : 200 }); + if (refused) { + return json(409, { + error: `view/${name} has been modified since you loaded it.`, + code: 'METADATA_CONFLICT', + currentVersion: head, + }); + } + const version = token(++seq); + drafts.set(name, { body, version }); + return json(200, { success: true, version, seq, state: 'draft', message: `Saved view '${name}'` }); + }) as typeof fetch; + + return { + client: new MetadataClient({ baseUrl: 'http://localhost:3000', fetch: fetchImpl }), + puts, + publishes, + draftOf: (name: string) => drafts.get(name), + publishedOf: (name: string) => published.get(name), + /** Park the next publish once it arrives; resolves when it has. */ + holdNextPublish(): Promise { + parkNext = true; + return arrived; + }, + releasePublish(): void { + parked?.release(); + }, + /** Park the next draft save once it arrives, before the door judges it; resolves when it has. */ + holdNextPut(): Promise { + parkNextPut = true; + return putArrival; + }, + releasePut(): void { + parkedPut?.release(); + }, + }; +} + +type Door = ReturnType; + +/** + * The panel, hosted the way `handleViewConfigSave` hosts it, by a host that + * closes it on Discard the way `ObjectView` does. + */ +function mountPanel(door: Door) { + const outcomes: string[] = []; + const onSave = vi.fn(async (draft: Record, saveDraft?: DraftVersionGuard['save']) => { + try { + const outcome = await persistRuntimeMetadata( + 'view', + String(draft.id), + buildViewConfigSaveBody(OBJECT, draft), + { metadataClient: door.client }, + saveDraft, + ); + outcomes.push(outcome); + return outcome === 'saved'; + } catch (err) { + outcomes.push(`refused: ${(err as Error).message}`); + return false; + } + }); + const host: { reopen: () => void } = { reopen: () => {} }; + function Host() { + const [open, setOpen] = useState(true); + host.reopen = () => setOpen(true); + return ( + setOpen(false)} + activeView={{ id: VIEW_ID, label: 'Everything', type: 'grid', columns: ['name'], filter: [], sort: [] }} + objectDef={{ name: OBJECT, fields: { name: { label: 'Name', type: 'text' } } }} + onViewUpdate={vi.fn()} + onSave={onSave} + metadataClient={door.client} + /> + ); + } + render(); + return { onSave, outcomes, reopen: () => act(() => host.reopen()) }; +} + +const saveButton = () => screen.getByTestId('view-config-save') as HTMLButtonElement; + +async function loadedAndEdited() { + await waitFor(() => expect(screen.getByTestId('mock-inspector-shown-label')).toBeTruthy()); + fireEvent.click(screen.getByTestId('mock-inspector-label')); + expect(saveButton().disabled).toBe(false); +} + +/** 「Save to this view」's body: the view with another sort, as the reader saves it. */ +const SAVE_TO_VIEW_BODY = { ...PUBLISHED, label: 'Everything', config: { ...PUBLISHED.config, sort: [{ field: 'name', order: 'desc' }] } }; + +describe('a view settings save between 「Save to this view」\'s draft write and its publish (objectstack#36137)', () => { + it('is refused, and the publish publishes only the Save\'s own draft', async () => { + const door = viewDoor(); + const { outcomes } = mountPanel(door); + await loadedAndEdited(); + + // Another admin's confirmed Save: its pinned draft write lands, its publish is parked. + const parked = door.holdNextPublish(); + const saveToView = saveAndPublishRuntimeMetadata('view', VIEW_ID, SAVE_TO_VIEW_BODY, { metadataClient: door.client }); + await parked; + expect(door.draftOf(VIEW_ID)?.body).toEqual(SAVE_TO_VIEW_BODY); + + // The settings save crosses it: pinned to "no draft", as the panel loaded the view. + await act(async () => { + fireEvent.click(saveButton()); + }); + await waitFor(() => expect(screen.getByTestId('draft-conflict-dialog')).toBeTruthy()); + const settingsPut = door.puts[door.puts.length - 1]!; + expect(settingsPut).toMatchObject({ ifNoneMatch: '*', ifMatch: null, label: 'Settings edit', status: 409 }); + // The Save's draft is untouched by it. + expect(door.draftOf(VIEW_ID)?.body).toEqual(SAVE_TO_VIEW_BODY); + + door.releasePublish(); + await expect(saveToView).resolves.toBe('published'); + expect(door.publishes).toEqual([SAVE_TO_VIEW_BODY]); + expect(door.publishedOf(VIEW_ID)).toEqual(SAVE_TO_VIEW_BODY); + + // Keep editing: nothing is saved, and the edit stays on screen, unsaved. + await act(async () => { + fireEvent.click(screen.getByTestId('draft-conflict-cancel')); + }); + await waitFor(() => expect(outcomes).toHaveLength(1)); + expect(outcomes[0]).toMatch(/^refused: /); + expect(screen.getByTestId('mock-inspector-shown-label').textContent).toBe('Settings edit'); + expect(saveButton().disabled).toBe(false); + expect(door.draftOf(VIEW_ID)).toBeUndefined(); + cleanup(); + }); + + it('Reload takes the published view into the panel, and nothing is written', async () => { + const door = viewDoor(); + const { outcomes } = mountPanel(door); + await loadedAndEdited(); + const parked = door.holdNextPublish(); + const saveToView = saveAndPublishRuntimeMetadata('view', VIEW_ID, SAVE_TO_VIEW_BODY, { metadataClient: door.client }); + await parked; + await act(async () => { + fireEvent.click(saveButton()); + }); + await waitFor(() => expect(screen.getByTestId('draft-conflict-dialog')).toBeTruthy()); + door.releasePublish(); + await saveToView; + + await act(async () => { + fireEvent.click(screen.getByTestId('draft-conflict-reload')); + }); + await waitFor(() => expect(outcomes).toEqual(['reloaded'])); + expect(door.puts.filter((p) => p.status === 200)).toHaveLength(1); + expect(door.publishes).toEqual([SAVE_TO_VIEW_BODY]); + // The buffer is the view as now stored, and the next save is pinned to "no draft". + await waitFor(() => expect(saveButton().disabled).toBe(true)); + fireEvent.click(screen.getByTestId('mock-inspector-label')); + await act(async () => { + fireEvent.click(saveButton()); + }); + await waitFor(() => expect(outcomes).toEqual(['reloaded', 'saved'])); + expect(door.puts[door.puts.length - 1]).toMatchObject({ ifNoneMatch: '*', status: 200 }); + cleanup(); + }); + + it('refused after the panel closed, still asks, and Save is live again once answered', async () => { + const door = viewDoor(); + const { outcomes, reopen } = mountPanel(door); + await loadedAndEdited(); + const parked = door.holdNextPublish(); + const saveToView = saveAndPublishRuntimeMetadata('view', VIEW_ID, SAVE_TO_VIEW_BODY, { metadataClient: door.client }); + await parked; + + // The settings save is sent, and the panel closes (Discard) before the door answers it. + const putParked = door.holdNextPut(); + await act(async () => { + fireEvent.click(saveButton()); + }); + await putParked; + await act(async () => { + fireEvent.click(screen.getByTestId('view-config-discard')); + }); + expect(screen.queryByTestId('view-config-save')).toBeNull(); + + // The refusal lands on the closed panel: the dialog is still shown. + await act(async () => { + door.releasePut(); + }); + await waitFor(() => expect(screen.getByTestId('draft-conflict-dialog')).toBeTruthy()); + expect(door.puts[door.puts.length - 1]).toMatchObject({ ifNoneMatch: '*', label: 'Settings edit', status: 409 }); + door.releasePublish(); + await expect(saveToView).resolves.toBe('published'); + expect(door.publishes).toEqual([SAVE_TO_VIEW_BODY]); + + // Keep editing: the host hears the refusal, and the save is no longer in flight. + await act(async () => { + fireEvent.click(screen.getByTestId('draft-conflict-cancel')); + }); + await waitFor(() => expect(outcomes).toHaveLength(1)); + expect(outcomes[0]).toMatch(/^refused: /); + await reopen(); + await waitFor(() => expect(screen.getByTestId('mock-inspector-shown-label').textContent).toBe('Everything')); + fireEvent.click(screen.getByTestId('mock-inspector-label')); + expect(saveButton().disabled).toBe(false); + cleanup(); + }); +}); + +describe('the view settings save is pinned to the draft it loaded (objectstack#36137)', () => { + it('over no draft: If-None-Match: *, and the next save If-Match on the receipt', async () => { + const door = viewDoor(); + const { outcomes } = mountPanel(door); + await loadedAndEdited(); + await act(async () => { + fireEvent.click(saveButton()); + }); + await waitFor(() => expect(outcomes).toEqual(['saved'])); + const first = door.draftOf(VIEW_ID)!; + expect(door.puts[0]).toMatchObject({ ifNoneMatch: '*', ifMatch: null, status: 200 }); + + fireEvent.click(screen.getByTestId('mock-inspector-label')); + await act(async () => { + fireEvent.click(saveButton()); + }); + await waitFor(() => expect(outcomes).toEqual(['saved', 'saved'])); + expect(door.puts[1]).toMatchObject({ ifMatch: first.version, ifNoneMatch: null, status: 200 }); + expect(door.publishes).toEqual([]); + cleanup(); + }); + + it('over its own loaded draft: If-Match on the version the load read', async () => { + const pending = { ...PUBLISHED, label: 'Pending' }; + const door = viewDoor({ draft: pending }); + const loaded = door.draftOf(VIEW_ID)!.version; + const { outcomes } = mountPanel(door); + await waitFor(() => expect(screen.getByTestId('mock-inspector-shown-label').textContent).toBe('Pending')); + fireEvent.click(screen.getByTestId('mock-inspector-label')); + await act(async () => { + fireEvent.click(saveButton()); + }); + await waitFor(() => expect(outcomes).toEqual(['saved'])); + expect(door.puts).toEqual([ + expect.objectContaining({ ifMatch: loaded, ifNoneMatch: null, label: 'Settings edit', status: 200 }), + ]); + cleanup(); + }); +}); + +describe('a view create carries the first-write pin (objectstack#36137)', () => { + it('is refused over a name that holds a pending draft, which it leaves as it was', async () => { + const pending = { ...PUBLISHED, label: 'Pending' }; + const door = viewDoor({ draft: pending }); + const env = viewEnvelope(OBJECT, { type: 'grid', columns: ['name'] }, { name: 'all', label: 'All' }); + expect(env.name).toBe(VIEW_ID); + await expect(createRuntimeMetadata('view', env.name, env, { metadataClient: door.client })).rejects.toMatchObject({ + status: 409, + code: 'METADATA_CONFLICT', + }); + expect(door.puts).toEqual([expect.objectContaining({ ifNoneMatch: '*', status: 409 })]); + expect(door.draftOf(VIEW_ID)?.body).toEqual(pending); + }); + + it('writes a new name (control)', async () => { + const door = viewDoor(); + const env = viewEnvelope(OBJECT, { type: 'grid', columns: ['name'] }, { name: 'mine', label: 'Mine' }); + await expect(createRuntimeMetadata('view', env.name, env, { metadataClient: door.client })).resolves.toBe(env.name); + expect(door.puts).toEqual([expect.objectContaining({ name: `${OBJECT}.mine`, ifNoneMatch: '*', status: 200 })]); + }); +}); diff --git a/ui/packages/app-shell/src/views/ViewConfigPanel.resumeEnvelope-10210.test.tsx b/ui/packages/app-shell/src/views/ViewConfigPanel.resumeEnvelope-10210.test.tsx index 59592dd722a..cfa4ba8a231 100644 --- a/ui/packages/app-shell/src/views/ViewConfigPanel.resumeEnvelope-10210.test.tsx +++ b/ui/packages/app-shell/src/views/ViewConfigPanel.resumeEnvelope-10210.test.tsx @@ -82,7 +82,7 @@ function served(doc: T): T & { _packageId: string } } /** - * A metadata client whose served draft read (`get(..., { state: 'draft' })`) + * A metadata client whose served draft read (`getDraft`, objectstack#36137) * answers the translated envelope, and whose layered read serves the stored * view: `draft` the pending draft as stored (`undefined`: no `draft` key at all). */ @@ -92,7 +92,7 @@ function makeClient(opts: { draft: Record | null | undefined; s const pending = opts.servedDraft ?? !!opts.draft; return { layered: vi.fn(async () => layers), - get: vi.fn(async () => + getDraft: vi.fn(async () => pending ? { type: 'view', name: VIEW_ID, item: served((opts.draft ?? SOURCE) as typeof SOURCE) } : null, ), }; diff --git a/ui/packages/app-shell/src/views/ViewConfigPanel.tsx b/ui/packages/app-shell/src/views/ViewConfigPanel.tsx index aa23127fcee..d5040af285d 100644 --- a/ui/packages/app-shell/src/views/ViewConfigPanel.tsx +++ b/ui/packages/app-shell/src/views/ViewConfigPanel.tsx @@ -40,7 +40,8 @@ import { RuntimeDraftBar } from './RuntimeDraftBar.js'; import { isFormFamilyKey } from './metadata-admin/view-variant-model.js'; import { useMetadataLocale, t as tStudio, tFormat } from './metadata-admin/i18n.js'; import { authoredBuffer, formatMetadataError, type AuthoredLayers } from '@object-ui/data-objectstack'; -import { readRuntimeDraft } from './runtime-metadata-persistence.js'; +import { unwrapDraftBody } from './runtime-metadata-persistence.js'; +import { draftPinOf, useDraftSaveGuard, type DraftPin, type DraftVersionGuard } from './metadata-admin/DraftConflictDialog.js'; import { isSameOptionsValue } from './objectViewOptions.js'; import type { ObjectFieldInfo } from './metadata-admin/previews/useObjectFields.js'; import { @@ -98,8 +99,15 @@ export interface ViewConfigPanelProps { * prop admitted (an `async` host that returns nothing, one resolving to a * record, a sync non-void return). The contract review of objectui#11583 * measured that; `ViewConfigPanel.onSaveHosts-11583.test.ts` pins it. + * + * objectstack#36137 — `saveDraft` is this panel's draft-version guard, + * holding the pin of the draft the panel loaded (`If-Match`, or + * `If-None-Match: *` over no draft): a host that writes through it gets a + * refused save asked about in the panel (reload the saved version, + * overwrite it, or keep editing) instead of overwriting a draft saved + * since. It resolves `'reloaded'` when the author chose the saved version. */ - onSave?: (draft: Record) => unknown; + onSave?: (draft: Record, saveDraft?: DraftVersionGuard['save']) => unknown; /** Called when create-mode view is created */ onCreate?: (config: Record) => void; /** @@ -132,7 +140,7 @@ export interface ViewConfigPanelProps { */ type AuthoredSeed = | { for: string; state: 'loading' } - | { for: string; state: 'ready'; view: RuntimeView } + | { for: string; state: 'ready'; view: RuntimeView; pin: DraftPin | null } | { for: string; state: 'refused'; message: string }; /** @@ -186,6 +194,22 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje const readsAuthored = mode === 'edit' && !!metadataClient && !!activeView.id; const [seed, setSeed] = useState(null); const [authoredReads, setAuthoredReads] = useState(0); + // A publish or a discard from the draft bar changes what is stored, and so + // does a conflict the author resolves by taking the saved version: the + // buffer is read again (objectstack#35054), then the host refreshes. + const handleAfterChange = useCallback(() => { + setAuthoredReads((n) => n + 1); + onAfterChange?.(); + }, [onAfterChange]); + // objectstack#36137 — the draft-version guard of this panel's buffer + // (`useDraftSaveGuard`): the pin of the draft it was loaded from, then of + // each save it sent, and the conflict dialog a refused save opens. + const { + save: saveDraftVersioned, + recordRead: recordDraftRead, + forget: forgetDraftVersion, + dialog: draftConflictDialog, + } = useDraftSaveGuard(metadataClient, handleAfterChange); useEffect(() => { if (!open || !readsAuthored) return; const id = activeView.id; @@ -194,10 +218,14 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje (async () => { let next: AuthoredSeed; try { - const [layers, servedDraft] = await Promise.all([ + // objectstack#36137 — the served draft read is the envelope, so + // its `version` pins this buffer's saves (`draftPinOf`), at the + // address they write: no package, as the save names none. + const [layers, draftAnswer] = await Promise.all([ metadataClient.layered('view', id), - readRuntimeDraft>('view', id, { metadataClient }), + metadataClient.getDraft('view', id), ]); + const servedDraft = unwrapDraftBody(draftAnswer); const authored = authoredBuffer('view', layers as AuthoredLayers, servedDraft); if (authored.kind === 'unserved') { next = { for: id, state: 'refused', message: tStudio('engine.studio.refusal.draftUnreadable', locale) }; @@ -214,7 +242,12 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje } else { // The stored body is a ViewItem envelope or a flat view; // its identity is the view the panel was opened on. - next = { for: id, state: 'ready', view: { ...storedViewToRuntimeView(authored.body), id } }; + next = { + for: id, + state: 'ready', + view: { ...storedViewToRuntimeView(authored.body), id }, + pin: draftPinOf(draftAnswer), + }; } } catch (err) { next = { @@ -223,7 +256,12 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje message: tFormat('engine.edit.loadFailed', locale, { type: 'view', name: id, message: formatMetadataError(err) }), }; } - if (!cancelled) setSeed(next); + if (cancelled) return; + // The buffer is installed from this read: its pin is the one the + // next save sends; a read that installs none leaves nothing held. + if (next.state === 'ready') recordDraftRead('view', id, null, next.pin); + else forgetDraftVersion(); + setSeed(next); })(); return () => { cancelled = true; }; }, [open, readsAuthored, activeView.id, metadataClient, authoredReads]); // eslint-disable-line react-hooks/exhaustive-deps @@ -338,7 +376,7 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje setSaving(true); let landed: boolean; try { - landed = (await onSave?.(flat)) !== false; + landed = (await onSave?.(flat, saveDraftVersioned)) !== false; } catch { landed = false; } finally { @@ -347,7 +385,7 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje if (!landed) return; setSavedSignal((s) => s + 1); if (draftRef.current === savedDraft) setIsDirty(false); - }, [draft, onSave, onCreate, mode]); + }, [draft, onSave, onCreate, mode, saveDraftVersioned]); // Discard = revert any unsaved edits AND close the panel, in both modes // (objectui#2320). Create mode has no committed view to preview against, so @@ -388,13 +426,6 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje if (turnedReadOnly && mode === 'edit' && (isDirty || relayedRef.current.size > 0)) revertEdits(); }, [readOnly, mode, isDirty, revertEdits]); - // A publish or a discard from the draft bar changes what is stored: the - // buffer is read again (objectstack#35054), then the host refreshes. - const handleAfterChange = useCallback(() => { - setAuthoredReads((n) => n + 1); - onAfterChange?.(); - }, [onAfterChange]); - const panelTitle = mode === 'create' ? t('console.objectView.createView') : t('console.objectView.configureView'); @@ -402,7 +433,17 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje if (!open) { // Keep the slide container (owned by ObjectView) able to collapse to // zero width without rendering inspector internals while hidden. - return
; + // + // objectstack#36137 — the conflict dialog is rendered here too: a + // save still in flight when the panel closes (Discard, another view + // tab) can be refused after it closed, and the guard then waits on + // the author's choice. Without the dialog nothing would answer it, + // and Save would stay disabled. It portals out of this hidden div. + return ( +
+ {draftConflictDialog} +
+ ); } return ( @@ -486,6 +527,7 @@ export function ViewConfigPanel({ open, onClose, mode = 'edit', activeView, obje )}
+ {draftConflictDialog} ); } diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index d56f33116b4..e1a948b95c2 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -22,6 +22,7 @@ import type { useConsoleActionRuntime } from '../hooks/useConsoleActionRuntime.j import type { useMetadataClient } from './metadata-admin/useMetadata.js'; import { persistRuntimeMetadata, createRuntimeMetadata, saveAndPublishRuntimeMetadata, viewEnvelope } from './runtime-metadata-persistence.js'; import type { RuntimeCreateApp, SaveAndPublishOutcome } from './runtime-metadata-persistence.js'; +import type { DraftVersionGuard } from './metadata-admin/DraftConflictDialog.js'; import { draftBarPackageOf } from '../preview/DraftPreviewBar.js'; import { useMetadata } from '../providers/MetadataProvider.js'; import { buildAddViewSpec, setDefaultViewPatches, buildViewConfigSaveBody } from './objectViewTabs.js'; @@ -137,8 +138,16 @@ export function useObjectViewViewCrud({ * The view-config panel's edit Save. Resolves whether the draft was staged, * so the panel stays dirty, and announces no draft, on anything but `true` * (objectui#11583). + * + * objectstack#36137 — `saveDraft` is the panel's draft-version guard: the + * write is pinned to the draft the panel loaded, so a save that would + * cross another admin's 「Save to this view」 between its draft write and + * its publish is refused and asked about, never published with it. */ - const handleViewConfigSave = useCallback(async (draft: Record): Promise => { + const handleViewConfigSave = useCallback(async ( + draft: Record, + saveDraft?: DraftVersionGuard['save'], + ): Promise => { setViewDraft(draft); setRefreshKey(k => k + 1); @@ -152,12 +161,13 @@ export function useObjectViewViewCrud({ try { // `dataSource` + `objectName` let the seam drop this object's view // cache keys (#4373) — the adapter owns which keys those are. - await persistRuntimeMetadata('view', vid, buildViewConfigSaveBody(objectName, draft), { + const outcome = await persistRuntimeMetadata('view', vid, buildViewConfigSaveBody(objectName, draft), { metadataClient, dataSource, objectName, - }); - return true; + }, saveDraft); + // `'reloaded'`: the author chose the saved version, and the panel reads it again. + return outcome === 'saved'; } catch (err) { console.error('[ViewConfigPanel] Failed to persist view config:', err); // objectui#11583: a refused save is SAID, as the Create View doors diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.otherTypesUntouched-35624.test.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.otherTypesUntouched-35624.test.ts index 066af0ef84e..9966ba014fd 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.otherTypesUntouched-35624.test.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.otherTypesUntouched-35624.test.ts @@ -31,7 +31,7 @@ describe('report, dashboard and page creates are untouched by the app destinatio }); expect(metadataClient.save).toHaveBeenCalledTimes(1); - expect(metadataClient.save).toHaveBeenCalledWith(type, `crm_${type}`, { label: type }, { mode: 'draft' }); + expect(metadataClient.save).toHaveBeenCalledWith(type, `crm_${type}`, { label: type }, { mode: 'draft', ifNoneMatch: '*' }); expect(pageFetch).not.toHaveBeenCalled(); expect(onSavedOutsideApp).not.toHaveBeenCalled(); }); diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.pendingDraftsPulse-13139.test.tsx b/ui/packages/app-shell/src/views/runtime-metadata-persistence.pendingDraftsPulse-13139.test.tsx index 7c6f52c9c76..ccc9ad04aa1 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.pendingDraftsPulse-13139.test.tsx +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.pendingDraftsPulse-13139.test.tsx @@ -198,7 +198,7 @@ describe('a runtime draft write moves the draft preview bar (objectui#13139)', ( try { await expect( persistRuntimeMetadata('view', VIEW, { label: 'x' }, { metadataClient, objectName: OBJECT }), - ).resolves.toBeUndefined(); + ).resolves.toBe('saved'); expect(metadataClient.save).toHaveBeenCalledTimes(1); expect(warn).toHaveBeenCalledTimes(1); expect(warn.mock.calls[0]?.[1]).toBeInstanceOf(Error); diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts index 05b7f592b82..b845699c8ad 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.test.ts @@ -114,6 +114,7 @@ describe('runtime-metadata-persistence seam (ADR-0034)', () => { expect(metadataClient.save).toHaveBeenCalledWith('view', 'view_123', body, { mode: 'draft', + ifNoneMatch: '*', }); expect(id).toBe('view_123'); }); @@ -243,7 +244,7 @@ describe('runtime-metadata-persistence seam (ADR-0034)', () => { const id = await createRuntimeMetadata('view', env.name, env, { metadataClient }); // Row key (URL segment), returned id, and body.name are the SAME value. expect(id).toBe('acct.mine'); - expect(metadataClient.save).toHaveBeenCalledWith('view', 'acct.mine', env, { mode: 'draft' }); + expect(metadataClient.save).toHaveBeenCalledWith('view', 'acct.mine', env, { mode: 'draft', ifNoneMatch: '*' }); expect(env.name).toBe('acct.mine'); }); }); diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index b61a26a2c44..254168a0436 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -41,7 +41,11 @@ import { stripReadDecorations } from '@objectstack/spec/kernel'; import { emitMetadataRefresh } from '../assistant/assistantBus.js'; import { slugify } from './metadata-admin/createDerive.js'; -import { isDraftVersionConflict } from './metadata-admin/DraftConflictDialog.js'; +import { + isDraftVersionConflict, + type DraftSaveOutcome, + type DraftVersionGuard, +} from './metadata-admin/DraftConflictDialog.js'; import { ensureCustomizationPackage, fetchListedPackageManifests } from './studio-design/packages-io.js'; /** The runtime-editable artifact types ADR-0034 unifies. `page` (a record @@ -322,16 +326,29 @@ export function unwrapDraftBody( /** * Persist a runtime edit of a view / report / dashboard as a per-item DRAFT * (invisible to other users until {@link publishRuntimeMetadata}). + * + * objectstack#36137 — `saveDraft` is the editing buffer's draft-version guard + * (`useDraftSaveGuard`'s `save`): the write is sent pinned to the draft the + * buffer was loaded from (`If-Match`, or `If-None-Match: *` over no draft), + * and a `409 METADATA_CONFLICT` is asked about instead of overwriting. Without + * one the write goes unpinned, as a report's still does. Resolves + * `'reloaded'` when the author chose the saved version: nothing was written. */ export async function persistRuntimeMetadata( type: RuntimeArtifactType, name: string, body: any, ctx: RuntimePersistCtx, -): Promise { - await ctx.metadataClient.save(type, name, body, { mode: 'draft' }); + saveDraft?: DraftVersionGuard['save'], +): Promise { + if (saveDraft) { + if ((await saveDraft(type, name, body, { mode: 'draft' })) === 'reloaded') return 'reloaded'; + } else { + await ctx.metadataClient.save(type, name, body, { mode: 'draft' }); + } invalidateViewCaches(type, name, ctx); announceDraftLedgerWrite(); + return 'saved'; } /** @@ -451,7 +468,14 @@ export async function createRuntimeMetadata( } const app = type === 'view' ? ctx.app : null; const packageId = app?.packageId ? await resolveRuntimeCreatePackage(app.packageId) : null; - await ctx.metadataClient.save(type, name, body, packageId ? { mode: 'draft', packageId } : { mode: 'draft' }); + // objectstack#36137 — the first-write pin: a create over a name that already + // holds a pending draft is refused `409 METADATA_CONFLICT`, never written over it. + await ctx.metadataClient.save( + type, + name, + body, + packageId ? { mode: 'draft', packageId, ifNoneMatch: '*' } : { mode: 'draft', ifNoneMatch: '*' }, + ); invalidateViewCaches(type, name, ctx); announceDraftLedgerWrite(); if (app?.packageId && !packageId) {