diff --git a/.changeset/36902-detail-save-at-once.md b/.changeset/36902-detail-save-at-once.md new file mode 100644 index 00000000000..8f81b0752c1 --- /dev/null +++ b/.changeset/36902-detail-save-at-once.md @@ -0,0 +1,22 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +'@object-ui/data-objectstack': patch +--- + +feat(studio): the generic item page's Save takes effect at once; an AI draft gets the designers' notice and discard + +Clause-②: yes (widening) +Metadata-protocol: none + +Studio's generic item page saves the way the designers do. Save writes the item's draft and then publishes that one item (`POST /meta/:type/:name/publish`, at the same package and bundle member), so the change is live at once and there is no second Publish step. The draft save keeps its version pin and conflict dialog, and the publish is now pinned to the published version the page loaded: when another editor published the item in between, the same dialog asks to reload, overwrite or keep editing. A create publishes right after its first save. The auto-save switch is gone, and edits wait for Save, ⌘S or the destructive-change confirmation. + +A refused publish shows its reason above the editor in the designers' words, with the server's text under Details. Nothing goes live, the draft the Save wrote is taken back, and the edits stay on the page, unsaved. + +A pending draft written by the AI assistant (the copilot or an MCP client) is the version on screen, under the designers' line: saving makes it live too, and "Discard AI changes" drops that one item's draft, asking first when the page holds unsaved edits. A pending draft a person wrote before this change is marked "This item has unpublished changes", with its own Publish and Discard for that item. The header's Publish and discard buttons are gone. + +Leaving the page with unsaved edits still asks first through ×, ‹ ›, the side menu, in-app links, reload and close. The browser's Back is not intercepted. + +`@object-ui/data-objectstack`: the exported `MetadataLayered` type gains an optional `overlayVersion` member (`string | null`), and `MetadataClient.layered()` now forwards the served `overlayVersion` into it. The client used to rebuild its answer field by field and drop it, so a Studio Save's publish was never pinned on a server that serves it. + +Locale keys `engine.edit.unpublishedChanges` and `engine.edit.unpublishedPublishDirty` are new, and `engine.edit.autoSaveOn`, `engine.edit.autoSaveOff` and `engine.edit.autoSavingShortly` are removed (en, zh). The per-browser `metadata-admin:autosave` setting is no longer read. No metadata changes; nothing to migrate. diff --git a/ui/e2e/live/studio-detail-save-at-once.spec.ts b/ui/e2e/live/studio-detail-save-at-once.spec.ts new file mode 100644 index 00000000000..b5c897c2151 --- /dev/null +++ b/ui/e2e/live/studio-detail-save-at-once.spec.ts @@ -0,0 +1,104 @@ +import { test, expect, type APIRequestContext, type Dialog } from '@playwright/test'; + +/** + * Live e2e for the generic Studio item page's save model (objectstack#36902, + * epic objectstack#36890 decisions 1 and 12): Save makes the item live at once + * (its draft, then that one item's publish), with no auto-save and no second + * Publish step, and leaving with unsaved edits asks first through × and ‹ › + * while the browser's Back is not intercepted. + * + * The item under edit is a page the test authors in the environment (a copy of + * the showcase's `showcase_project_workspace`), removed again at the end, as + * `studio-editor.spec.ts` does. + */ +const API = process.env.LIVE_API_URL || 'http://localhost:3000'; +const SHIPPED_PAGE = 'showcase_project_workspace'; + +async function authorEditablePage(request: APIRequestContext): Promise<{ name: string; firstRegionBlocks: number }> { + const res = await request.get(`${API}/api/v1/meta/page/${SHIPPED_PAGE}`); + expect(res.ok(), await res.text()).toBeTruthy(); + const shipped = (await res.json()).item as Record; + const body = Object.fromEntries(Object.entries(shipped).filter(([k]) => !k.startsWith('_'))); + const firstRegionBlocks = ((body.regions as { components?: unknown[] }[])[0].components ?? []).length; + const name = `e2e_save_at_once_${Date.now()}`; + const put = await request.put(`${API}/api/v1/meta/page/${name}`, { + data: { ...body, name, label: `E2E Save At Once ${name.slice(-6)}` }, + }); + expect(put.ok(), await put.text()).toBeTruthy(); + return { name, firstRegionBlocks }; +} + +test('Save makes the edit live at once, and an unsaved edit is guarded on × but not on Back', async ({ page, request }) => { + const { name, firstRegionBlocks } = await authorEditablePage(request); + const writes: string[] = []; + page.on('request', (r) => { + if (r.url().includes(`/api/v1/meta/page/${name}`) && ['PUT', 'POST'].includes(r.method())) { + writes.push(`${r.method()} ${new URL(r.url()).pathname}`); + } + }); + try { + // The list first, then the item by its row: an in-app navigation, so the + // browser's Back below is the app's own history entry (a full page load + // would make Back a cross-document unload, which the reload guard asks about). + await page.goto('/studio/~all/metadata/page'); + await page.getByText(name, { exact: true }).first().click(); + await expect(page).toHaveURL(new RegExp(`/metadata/page/${name}`)); + await expect(page.getByTestId('metadata-edit-page')).toBeVisible(); + + await test.step('an edit stays on the page: no auto-save sends it', async () => { + await page.getByRole('button', { name: /Add block/i }).first().click(); + await page.getByRole('dialog').getByRole('button', { name: /Card/i }).first().click(); + await expect(page.getByTestId('save-status')).toHaveAttribute('data-state', 'unsaved'); + await page.waitForTimeout(2500); + expect(writes).toEqual([]); + }); + + await test.step('× asks before dropping the edit; Cancel stays', async () => { + const asked: string[] = []; + const dismiss = (d: Dialog) => { + asked.push(d.type()); + void d.dismiss(); + }; + page.on('dialog', dismiss); + await page.getByTestId('studio-detail-close').click(); + await expect.poll(() => asked).toEqual(['confirm']); + page.off('dialog', dismiss); + await expect(page).toHaveURL(new RegExp(`/metadata/page/${name}`)); + }); + + await test.step('Save writes the draft, then publishes the one item; nothing is left to publish', async () => { + const published = page.waitForResponse( + (r) => r.request().method() === 'POST' && r.url().includes(`/api/v1/meta/page/${name}/publish`), + ); + await page.getByTestId('resource-save').click(); + const publish = await published; + expect(publish.ok(), await publish.text()).toBeTruthy(); + expect(writes).toEqual([`PUT /api/v1/meta/page/${name}`, `POST /api/v1/meta/page/${name}/publish`]); + await expect(page.getByTestId('save-status')).toHaveAttribute('data-state', 'saved'); + await expect(page.getByTestId('resource-unpublished-changes')).toHaveCount(0); + const live = await request.get(`${API}/api/v1/meta/page/${name}`, { headers: { 'Cache-Control': 'no-cache' } }); + const blocks = (await live.json()).item.regions[0].components as unknown[]; + expect(blocks).toHaveLength(firstRegionBlocks + 1); + const draft = await request.get(`${API}/api/v1/meta/page/${name}?state=draft`); + expect(draft.status()).toBe(404); + }); + + await test.step('browser Back is not intercepted, even with an unsaved edit', async () => { + await page.getByRole('button', { name: /Add block/i }).first().click(); + await page.getByRole('dialog').getByRole('button', { name: /Card/i }).first().click(); + await expect(page.getByTestId('save-status')).toHaveAttribute('data-state', 'unsaved'); + const asked: string[] = []; + const accept = (d: Dialog) => { + asked.push(d.type()); + void d.accept(); + }; + page.on('dialog', accept); + await page.goBack(); + await expect(page).toHaveURL(/\/metadata\/page(\?|$)/); + page.off('dialog', accept); + expect(asked).toEqual([]); + }); + } finally { + await request.delete(`${API}/api/v1/meta/page/${name}`); + } +}); diff --git a/ui/e2e/live/studio-editor.spec.ts b/ui/e2e/live/studio-editor.spec.ts index 8d4df2a4a74..832afdeed62 100644 --- a/ui/e2e/live/studio-editor.spec.ts +++ b/ui/e2e/live/studio-editor.spec.ts @@ -86,16 +86,18 @@ test('Add block opens a block-type picker with configurable block kinds, and the await expect(dialog.getByRole('button', { name: /Section/i })).toBeVisible(); await expect(dialog.getByRole('button', { name: /Record details/i })).toBeVisible(); - // The save round trip, not only the canvas: picking a kind autosaves a - // draft, and the draft read back through /meta holds the new block at the - // end of the first region. - const saved = page.waitForResponse( - (r) => r.request().method() === 'PUT' && r.url().includes(`/api/v1/meta/page/${name}?mode=draft`), - ); + // The save round trip, not only the canvas: picking a kind is an unsaved + // edit, and Save makes it live at once (objectstack#36902): the item's + // draft, then that one item's publish. The page read back through /meta + // holds the new block at the end of the first region. await dialog.getByRole('button', { name: /Card/i }).first().click(); - const save = await saved; - expect(save.ok(), await save.text()).toBeTruthy(); - const stored = await request.get(`${API}/api/v1/meta/page/${name}?state=draft`); + const published = page.waitForResponse( + (r) => r.request().method() === 'POST' && r.url().includes(`/api/v1/meta/page/${name}/publish`), + ); + await page.getByTestId('resource-save').click(); + const publish = await published; + expect(publish.ok(), await publish.text()).toBeTruthy(); + const stored = await request.get(`${API}/api/v1/meta/page/${name}`); expect(stored.ok(), await stored.text()).toBeTruthy(); const blocks = (await stored.json()).item.regions[0].components as { type?: string }[]; expect(blocks).toHaveLength(firstRegionBlocks + 1); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.authoredObjectBuffer-29793.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.authoredObjectBuffer-29793.test.tsx index 1027982f25a..c6685899ad8 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.authoredObjectBuffer-29793.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.authoredObjectBuffer-29793.test.tsx @@ -24,6 +24,8 @@ */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches a dynamic import of this module: its first load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; @@ -183,6 +185,12 @@ function renderZh() { ); } +/** Save is explicit (objectstack#36902): wait for the unsaved edit, then press Save. */ +async function pressSave() { + await waitFor(() => expect(screen.getByTestId('save-status').getAttribute('data-state')).toBe('unsaved'), { timeout: 8000 }); + fireEvent.click(screen.getByTestId('resource-save')); +} + const editorDraft = (): Row => JSON.parse(screen.getByTestId('editor-draft').textContent ?? '{}') as Row; function expectAuthored(doc: Row, severityLabel: string) { @@ -196,7 +204,7 @@ function expectAuthored(doc: Row, severityLabel: string) { } describe('MetadataResourceEditPage in a zh-CN console — an object buffer is the authored document (objectstack#29793)', () => { - it('a pending draft: the buffer is the stored draft, one edit PUTs it in source labels with no injected column, and the publish refresh stays authored', async () => { + it('a pending draft: the buffer is the stored draft, one Save PUTs it in source labels with no injected column and publishes it, and the refresh stays authored', async () => { srv.draft = wire({ ...AUTHORED, description: 'draft only' }); renderZh(); @@ -204,20 +212,14 @@ describe('MetadataResourceEditPage in a zh-CN console — an object buffer is th expect(editorDraft()).toStrictEqual(wire({ ...AUTHORED, description: 'draft only' })); fireEvent.click(screen.getByRole('button', { name: 'relabel severity' })); + await pressSave(); await waitFor(() => expect(srv.saves.length).toBeGreaterThan(0), { timeout: 8000 }); const { body, opts } = srv.saves.at(-1)!; expect(opts).toMatchObject({ mode: 'draft' }); expectAuthored(body, 'Level'); expect(body.description).toBe('draft only'); - // The refresh after the save installs the stored draft again, not the served one. - await waitFor(() => expect((editorDraft().fields as Record).severity.label).toBe('Level'), { timeout: 8000 }); - expectAuthored(editorDraft(), 'Level'); - - // Publish: the refresh installs the promoted body as authored (`overlay`). - const publish = await screen.findAllByRole('button', { name: new RegExp(`^${t('engine.edit.publish', 'zh-CN')}$`) }, { timeout: 8000 }); - await waitFor(() => expect(publish[0]).toBeEnabled(), { timeout: 8000 }); - fireEvent.click(publish[0]!); + // The Save publishes the item, and the refresh installs the promoted body as authored (`overlay`). await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(1), { timeout: 8000 }); await waitFor(() => expect(srv.draft).toBeNull(), { timeout: 8000 }); await act(async () => { @@ -233,6 +235,7 @@ describe('MetadataResourceEditPage in a zh-CN console — an object buffer is th expect(editorDraft()).toStrictEqual(wire(AUTHORED)); fireEvent.click(screen.getByRole('button', { name: 'relabel severity' })); + await pressSave(); await waitFor(() => expect(srv.saves.length).toBeGreaterThan(0), { timeout: 8000 }); expectAuthored(srv.saves.at(-1)!.body, 'Level'); }); @@ -401,17 +404,19 @@ describe.each(TRANSLATED_TYPES)( if (realTypePreview) registerMetadataPreview(spec.type, realTypePreview); }); - it('no pending draft: two edits in a row each PUT source text, the second after the save refresh re-read the draft', async () => { + it('no pending draft: two Saves in a row each PUT source text, the second after the save refresh re-read the published item', async () => { renderTypeZh(spec); await waitFor(() => expect(editorDraft().name).toBe(spec.name), { timeout: 8000 }); expect(spec.sourceText(editorDraft())).toStrictEqual(SOURCE_TEXT[spec.type]); fireEvent.click(screen.getByRole('button', { name: 'edit once' })); + await pressSave(); await waitFor(() => expect(srv.saves.length).toBe(1), { timeout: 8000 }); expect(srv.saves[0]!.opts).toMatchObject({ mode: 'draft' }); expect(spec.sourceText(srv.saves[0]!.body)).toStrictEqual(SOURCE_TEXT[spec.type]); - // The save refresh: the served draft is now the zh-CN one, the layers' the stored one. + // The Save published the draft; the refresh re-reads the stored row, in source text. + await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(1), { timeout: 8000 }); await waitFor(() => expect(mockClient.getDraft.mock.calls.length).toBeGreaterThan(1), { timeout: 8000 }); await act(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); @@ -419,9 +424,11 @@ describe.each(TRANSLATED_TYPES)( expect(spec.sourceText(editorDraft())).toStrictEqual(SOURCE_TEXT[spec.type]); fireEvent.click(screen.getByRole('button', { name: 'edit once' })); + await pressSave(); await waitFor(() => expect(srv.saves.length).toBe(2), { timeout: 8000 }); expect(spec.sourceText(srv.saves[1]!.body)).toStrictEqual(SOURCE_TEXT[spec.type]); - expect(spec.sourceText(srv.draft!)).toStrictEqual(SOURCE_TEXT[spec.type]); + await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(2), { timeout: 8000 }); + expect(spec.sourceText(srv.overlay!)).toStrictEqual(SOURCE_TEXT[spec.type]); }); it('a pending draft: the buffer is the stored draft, and one edit PUTs it in source text', async () => { @@ -431,6 +438,7 @@ describe.each(TRANSLATED_TYPES)( expect(spec.sourceText(editorDraft())).toStrictEqual(SOURCE_TEXT[spec.type]); fireEvent.click(screen.getByRole('button', { name: 'edit once' })); + await pressSave(); await waitFor(() => expect(srv.saves.length).toBeGreaterThan(0), { timeout: 8000 }); expect(spec.sourceText(srv.saves.at(-1)!.body)).toStrictEqual(SOURCE_TEXT[spec.type]); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.bundleMember-26649.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.bundleMember-26649.test.tsx index 1e8e3c01270..e420bb59931 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.bundleMember-26649.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.bundleMember-26649.test.tsx @@ -18,6 +18,8 @@ */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches a dynamic import of this module: its first load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; 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'; @@ -193,7 +195,7 @@ describe('MetadataResourceEditPage — ?member= opens that bundle member (object await screen.findByDisplayValue('逾期了,请处理', undefined, { timeout: 8000 }); await settle(); - fireEvent.click(screen.getByTitle('Publish')); + fireEvent.click(screen.getByTestId('resource-draft-publish')); await waitFor(() => expect(server.members.get('zh-CN')!.draft).toBeNull()); await settle(); @@ -208,7 +210,7 @@ describe('MetadataResourceEditPage — ?member= opens that bundle member (object await screen.findByDisplayValue('逾期了,请处理', undefined, { timeout: 8000 }); await settle(); - fireEvent.click(screen.getAllByTitle('Discard draft')[0]!); + fireEvent.click(screen.getByTestId('resource-draft-discard')); await confirmDialog(); await waitFor(() => expect(server.members.get('zh-CN')!.draft).toBeNull()); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.celGate.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.celGate.test.tsx index 678ed543aaa..4f6c82cf734 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.celGate.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.celGate.test.tsx @@ -165,17 +165,17 @@ describe('MetadataResourceEditPage — Save is gated on the block inspector’s }); }); -describe('MetadataResourceEditPage — the save-status chip while the inspector holds auto-save (#29901)', () => { - // `inspectorBlocking` returns the auto-save effect early exactly as a server - // refusal does, so the chip must not promise an auto-save then either. +describe('MetadataResourceEditPage — the save-status chip while the inspector holds Save (#29901)', () => { + // `inspectorBlocking` holds Save exactly as a server refusal does, so the + // chip must not read as a plain unsaved edit then either. const chipState = () => screen.queryByTestId('save-status')?.getAttribute('data-state') ?? null; - it('reads the held state on a dangling operator, and the auto-save state once it parses', async () => { + it('reads the held state on a dangling operator, and the unsaved state once it parses', async () => { const box = await openBlockCel(); - // CONTROL first: a good predicate dirties the draft and reads auto-save. + // CONTROL first: a good predicate dirties the draft and reads unsaved. fireEvent.change(box, { target: { value: 'record.amount > 20' } }); - await waitFor(() => expect(chipState()).toBe('autosave-pending'), { timeout: 4000 }); + await waitFor(() => expect(chipState()).toBe('unsaved'), { timeout: 4000 }); fireEvent.change(box, { target: { value: 'record.amount >' } }); await waitFor(() => expect(chipState()).toBe('held'), { timeout: 4000 }); @@ -185,6 +185,6 @@ describe('MetadataResourceEditPage — the save-status chip while the inspector ); fireEvent.change(box, { target: { value: 'record.amount > 21' } }); - await waitFor(() => expect(chipState()).toBe('autosave-pending'), { timeout: 4000 }); + await waitFor(() => expect(chipState()).toBe('unsaved'), { timeout: 4000 }); }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.choiceWithoutOptions-11253.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.choiceWithoutOptions-11253.test.tsx index 9c8e1a8665e..46e32d4ea02 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.choiceWithoutOptions-11253.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.choiceWithoutOptions-11253.test.tsx @@ -15,11 +15,13 @@ * canvas and field inspector. The client is a real `MetadataClient`, whose * `save` is the door that runs the object write guard; only its transport and * the mount's reads are doubles. So the claim is read off the WIRE: no PUT - * carries a choice field without options, the held autosave says why and names - * the field, and one option lets the next autosave go (the control). + * carries a choice field without options, the held Save says why and names + * the field, and one option lets the next Save go (the control). */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches a dynamic import of this module: its first load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; import * as React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { render, screen, fireEvent, cleanup, waitFor, act } from '@testing-library/react'; @@ -46,6 +48,13 @@ const OBJECT_ENTRY = { const puts: Array<{ url: string; body: Record }> = []; const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => { + // The Save's own publish and a refused publish's take-back (objectstack#36902). + if (init?.method === 'POST' || init?.method === 'DELETE') { + return new Response(JSON.stringify({ success: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + } if (init?.method === 'PUT') { puts.push({ url, body: JSON.parse(String(init.body)) as Record }); return new Response(JSON.stringify({ success: true }), { @@ -125,10 +134,11 @@ function choiceWithoutOptions(): WireField[] { ); } -/** Past the autosave's 1.5 s debounce. */ -async function outlastDebounce(): Promise { +/** Press Save (a held Save is a disabled button, so the press sends nothing), and let any write leave. */ +async function pressSaveAndSettle(): Promise { + fireEvent.click(screen.getByTestId('resource-save')); await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); + await new Promise((r) => setTimeout(r, 300)); }); } @@ -137,7 +147,7 @@ describe('metadata-admin object editor — a new choice field is not sent withou ['select', 'Picklist', 'status'], ['radio', 'Radio', 'radio'], ] as const) { - it(`add a \`${type}\` from the palette, wait out the autosave: no request carries it without options`, async () => { + it(`add a \`${type}\` from the palette, press Save: no request carries it without options`, async () => { render( @@ -145,21 +155,23 @@ describe('metadata-admin object editor — a new choice field is not sent withou ); fireEvent.click(await screen.findByRole('button', { name: 'Add field' }, { timeout: 8000 })); fireEvent.click(await screen.findByRole('button', { name: paletteLabel })); - await outlastDebounce(); + await pressSaveAndSettle(); // Held: the seeded `options: []` never reached the wire. expect(choiceWithoutOptions()).toEqual([]); - const banner = await screen.findByText(new RegExp(`\`${seededName}\``)); - expect(banner).toHaveTextContent(/no options/); + const named = await screen.findAllByText(new RegExp(`\`${seededName}\``)); + expect(named.some((el) => /no options/.test(el.textContent ?? ''))).toBe(true); - // CONTROL: one option lets the next autosave go, and the banner clears. + // CONTROL: one option lets the next Save go, and the banner clears. fireEvent.change(await screen.findByPlaceholderText('value'), { target: { value: 'open' } }); + await waitFor(() => expect(screen.getByTestId('resource-save')).toBeEnabled(), { timeout: 4000 }); + fireEvent.click(screen.getByTestId('resource-save')); await waitFor(() => expect(puts.length).toBeGreaterThan(0), { timeout: 4000 }); const sent = wireFields(puts[puts.length - 1].body).find((f) => f.name === seededName); expect(sent?.type).toBe(type); expect(sent?.options).toEqual([expect.objectContaining({ value: 'open' })]); expect(choiceWithoutOptions()).toEqual([]); - await waitFor(() => expect(screen.queryByText(new RegExp(`\`${seededName}\``))).toBeNull()); + await waitFor(() => expect(screen.queryAllByText(new RegExp(`\`${seededName}\``))).toHaveLength(0)); }); } }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createFirstWritePin-11773.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createFirstWritePin-11773.test.tsx index fa9a6cd0783..ec32d81f330 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createFirstWritePin-11773.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.createFirstWritePin-11773.test.tsx @@ -19,6 +19,8 @@ */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches a dynamic import of this module: its first load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; import * as React from 'react'; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; @@ -30,6 +32,8 @@ import { MetadataClient } from '@object-ui/data-objectstack'; const server = { drafts: new Map; version: string }>(), + /** What a publish made live (objectstack#36902: a create's Save publishes it). */ + active: new Map>(), puts: [] as Array<{ name: string; ifMatch: string | null; ifNoneMatch: string | null; status: number }>, seq: 0, }; @@ -48,6 +52,13 @@ async function serve(input: RequestInfo | URL, init?: RequestInit): Promise ({ type: k.split('/')[0], name: k.split('/')[1] })) }); } if (seg.length === 1) return json(200, { items: [] }); + if (seg.length === 3 && seg[2] === 'publish' && method === 'POST') { + const row = server.drafts.get(key); + if (!row) return json(404, { error: { code: 'NO_DRAFT', message: 'absent' } }); + server.active.set(key, row.body); + server.drafts.delete(key); + return json(200, { success: true, version: `sha256:${key}`, message: 'published' }); + } if (seg.length === 3) return json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); if (method === 'PUT') { const headers = new Headers(init?.headers); @@ -115,13 +126,12 @@ afterAll(() => { beforeEach(() => { server.drafts.clear(); + server.active.clear(); server.puts = []; server.seq = 0; - window.localStorage.setItem('metadata-admin:autosave', '0'); }); afterEach(() => { cleanup(); - window.localStorage.removeItem('metadata-admin:autosave'); }); function Where() { @@ -161,11 +171,12 @@ async function createNewGuide() { } describe('MetadataResourceEditPage — a create sends If-None-Match: * (objectui#11773)', () => { - it('the create is sent with the first-write pin and no If-Match, and lands', async () => { + it('the create is sent with the first-write pin and no If-Match, and lands live', async () => { await createNewGuide(); await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/metadata/doc/new_guide'), { timeout: 8000 }); expect(server.puts).toEqual([{ name: 'new_guide', ifMatch: null, ifNoneMatch: '*', status: 200 }]); - expect(server.drafts.get('doc/new_guide')?.body).toMatchObject({ name: 'new_guide', content: '# New' }); + expect(server.active.get('doc/new_guide')).toMatchObject({ name: 'new_guide', content: '# New' }); + expect(server.drafts.has('doc/new_guide')).toBe(false); }); it('a create over a name that already holds a draft is refused, and that draft is not written over', async () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftPublishVerdict-26707.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftPublishVerdict-26707.test.tsx index d2eea563f23..db6ec0a5a7a 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftPublishVerdict-26707.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftPublishVerdict-26707.test.tsx @@ -22,6 +22,8 @@ */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches a dynamic import of this module: its first load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react'; @@ -175,13 +177,15 @@ describe('MetadataResourceEditPage — a pending draft is judged by its own serv ); }); - it('the verdict follows the draft: the refresh after an autosave of a fixed draft clears it', async () => { + it('the verdict follows the draft: the refresh after a Save of a fixed draft clears it', async () => { server.active.set('page/home', PAGE); server.drafts.set('page/home', { ...PAGE, label: 'broken' }); renderEditor(); await waitFor(() => expect(canvasDiagnostics().map((d) => d.message)).toContain(REFUSAL.message), { timeout: 8000 }); fireEvent.click(screen.getByRole('button', { name: 'fix the draft' })); + await waitFor(() => expect(screen.getByTestId('resource-save')).toBeEnabled(), { timeout: 8000 }); + fireEvent.click(screen.getByTestId('resource-save')); await waitFor(() => expect(server.saves).toBe(1), { timeout: 8000 }); await waitFor(() => expect(canvasDiagnostics().map((d) => d.message)).not.toContain(REFUSAL.message), { timeout: 8000 }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftUnreadable-29148.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftUnreadable-29148.test.tsx index d6d0b5140b2..8dde572d69b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftUnreadable-29148.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.draftUnreadable-29148.test.tsx @@ -21,6 +21,8 @@ */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches a dynamic import of this module: its first load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). +import '@objectstack/lint'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { act, render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; @@ -97,7 +99,7 @@ vi.mock('./useMetadata', async (importOriginal) => { import { MetadataResourceEditPage } from './ResourceEditPage'; import { registerMetadataPreview, getMetadataPreview } from './preview-registry'; -/** Canvas stand-in: its only job is to dirty the buffer, which arms the real autosave. */ +/** Canvas stand-in: its only job is to dirty the buffer, which arms the real Save. */ function StubPageCanvas({ onPatch }: { onPatch?: (patch: Record) => void }) { return ( - )} {canWrite && !createMode && editing && !PreviewComponent && ( - )} - {canWrite && !createMode && hasDraft && ( - - )} + {/* objectstack#36902 — no Publish here: Save makes the item live. A + draft that was already pending is published or discarded from its + own line above the editor (decision 14). */} ); // objectstack#36901 (decision 8) — the draft review is a status chip in the // header, not a sheet trigger among the tools: shown while a draft is // pending, it opens the review (ADR-0033 Phase B), as `?review=1` does. + // objectstack#36902 — a pending draft some key of which the AI assistant wrote. + const aiDraft = !createMode && hasDraft && isAiDraft(draftChanges); const draftChangeCount = hasDraft && !createMode ? computeDraftChangeCount(layered?.effective ?? null, draft) : 0; const reviewChip = !createMode && hasDraft ? ( @@ -3114,7 +3159,7 @@ function MetadataResourceEditPageImpl({ // objectstack#36901 (decision 8) — the body the open tab draws. The canvas // (Preview) and the details form edit the ONE draft this page holds, and the - // header's Save, ⌘S and autosave save it whichever tab is open (decision 4): + // header's Save and ⌘S save it whichever tab is open (decision 4): // a tab switch keeps every unsaved edit, so it asks nothing. A create draft // draws the canvas when its type authors there (`CREATE_MODE_CANVAS_TYPES`). const activeTab = itemTab.location.tab; @@ -3170,7 +3215,7 @@ function MetadataResourceEditPageImpl({ : 'p-6 space-y-6 max-w-7xl' } > - {(error || readOnly || hasDraft || isLocked || walledDeciding) && ( + {(error || publishRefused || readOnly || hasDraft || isLocked || walledDeciding) && (
)} - {hasDraft && !createMode && ( -
+ {/* objectstack#36902 item 6 — the item's own publish was refused: + nothing went live, and the reason says why. */} + {publishRefused && ( + + )} + {/* objectstack#36902 (decision 1) — the AI assistant's draft is the + version on screen: Save makes it live too, and its discard + drops that one item's draft, the designers' line. */} + {aiDraft && ( + + )} + {/* objectstack#36902 (decision 14) — a person's draft from before + Save took effect at once: marked as unpublished changes, and + published or discarded here, this one item. */} + {hasDraft && !createMode && !aiDraft && ( +
- {t('engine.edit.draftPending', locale)} + {t('engine.edit.unpublishedChanges', locale)} {canWrite && ( <> @@ -3245,7 +3313,9 @@ function MetadataResourceEditPageImpl({ size="sm" onClick={doPublish} disabled={saving || publishing || isDirty} + title={isDirty ? t('engine.edit.unpublishedPublishDirty', locale) : undefined} className="h-7 bg-emerald-600 hover:bg-emerald-700 text-emerald-50" + data-testid="resource-draft-publish" > {publishing ? ( @@ -3969,7 +4039,7 @@ function MetadataResourceEditPageImpl({ {/* objectui#11773 — the draft-version conflict, apart from the destructive-change confirmation above: two different 409s. */} {draftConflictDialog} - {/* objectui#13333 — reset / delete / discard-draft, asked in-app. */} + {/* objectui#13333 — reset / delete / discard-draft / discard the AI's draft, asked in-app. */} { @@ -3995,6 +4065,7 @@ function MetadataResourceEditPageImpl({ setPendingConfirm(null); if (!pending) return; if (pending.kind === 'discard') void runDiscardDraft(pending.item); + else if (pending.kind === 'discardAi') void runDiscardAiDraft(); else void runReset(pending.kind === 'reset'); }} > @@ -4023,26 +4094,21 @@ function MetadataResourceEditPageImpl({ } /** - * SaveStatusIndicator — small inline label next to the Save icon that - * communicates auto-save state so the icon-only button is not a black - * box. Six states, each stamped on `data-state`: + * SaveStatusIndicator — small inline label next to the Save button. Four + * states, each stamped on `data-state` (objectstack#36902: no auto-save, so + * an unsaved edit waits for Save): * - saving → "Saving…" with spinner * - dirty + held → "Not saved" (destructive): a save door is shut — the * server refused this draft or the inspector holds a - * fault — so neither the timer nor the button will save - * it; the reason rides on the chip's title - * - dirty + on → "Auto-saving…" (subtle, amber) - * - dirty + off → "Unsaved" (amber) - * - clean + ts → "Saved 14:32" (muted) + * fault — so the button will not save it; the reason + * rides on the chip's title + * - dirty → "Unsaved" (amber) + * - clean + ts → "Saved 14:32" (muted): the item is live * - createMode → hidden until first save - * - * `held` outranks the auto-save promise: the auto-save effect returns early on - * the same terms, so "Auto-saving…" there would promise a save that never comes. */ function SaveStatusIndicator({ saving, isDirty, - autoSaveEnabled, held, heldReason, lastSavedAt, @@ -4051,7 +4117,6 @@ function SaveStatusIndicator({ }: { saving: boolean; isDirty: boolean; - autoSaveEnabled: boolean; /** A save door is shut on this draft (server refusal or inspector fault). */ held: boolean; /** Why it is shut — the Save button's own explanation. */ @@ -4095,13 +4160,11 @@ function SaveStatusIndicator({ return ( - {autoSaveEnabled - ? t('engine.edit.autoSavingShortly', locale) - : t('engine.edit.unsaved', locale)} + {t('engine.edit.unsaved', locale)} ); } diff --git a/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts b/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts new file mode 100644 index 00000000000..3719b8b4ad6 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/detailSaveAtOnce.ts @@ -0,0 +1,104 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36902 (epic objectstack#36890 decisions 1 and 14) — the generic + * item page's Save takes effect at once, as the Studio designers' Save does + * (objectstack#36511): the item's draft, then that one item's own publish + * (`POST /meta/:type/:name/publish`), never the package's batch. + * + * Invariants: + * - The publish addresses what the draft save wrote: the same package + * (`?package=`) and, for a bundle, the same member. The designers' helper + * (`studioSaveBar.tsx` `publishSavedItem`) names no member, which is why + * this page carries its own. + * - Pinned (`pinned`, the buffer's `DraftSaveGuard.publish`), the publish + * sends the published version the buffer was loaded at, so a Save over a + * row another editor published since is asked about (reload, overwrite or + * keep editing) instead of replacing it. + * - Refused, the draft the save wrote is taken back when no other draft of + * the item was pending before it (`hadDraft` false): a refused Save leaves + * nothing behind and the edits stay on the page, unsaved. A draft that was + * pending before (the AI assistant's, or a person's from before Save took + * effect at once) is kept: it now carries the page's edits too. + * - A reload after a conflict takes the saved draft back BEFORE the buffer + * is re-read, and that discard is not best-effort: a draft left behind + * would be re-read as the buffer and published by the next Save. + * - Every path tells the ledger (`emitMetadataRefresh`), so Changes and the + * app re-read what went live. + */ + +import type { DraftChange, MetadataClient } from '@object-ui/data-objectstack'; +import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; +import { isAgentDraftSurface } from '../studio-design/StudioDraftMark.js'; +import type { DraftSaveGuard } from './DraftConflictDialog.js'; + +/** The item a Save wrote, at the address its draft save wrote it. */ +export interface DetailPublishTarget { + type: string; + name: string; + /** The folded `?package=` binding; absent when the page holds none. */ + packageId?: string; + /** The bundle member the draft belongs to; absent for the canonical one. */ + member?: string; +} + +/** What {@link publishDetailSave} did. */ +export type DetailPublishOutcome = + /** The item is live. */ + | { kind: 'published' } + /** The published row moved and the author chose to reload: the caller's load re-reads the buffer. */ + | { kind: 'reloaded'; draftDiscarded: boolean } + /** Refused, or the author kept editing after a conflict; `draftDiscarded` says the saved draft was taken back. */ + | { kind: 'refused'; error: unknown; draftDiscarded: boolean }; + +/** Make the draft a Save just wrote live (see the module docblock). */ +export async function publishDetailSave( + client: Pick, + target: DetailPublishTarget, + hadDraft: boolean, + pinned?: DraftSaveGuard['publish'], +): Promise { + const scope = { + ...(target.packageId ? { packageId: target.packageId } : {}), + ...(target.member ? { member: target.member } : {}), + }; + let draftDiscarded = false; + const takeBack = async (): Promise => { + await client.reset(target.type, target.name, { state: 'draft', ...scope }); + draftDiscarded = true; + }; + try { + if (pinned) { + const outcome = await pinned(client, target.type, target.name, scope, hadDraft ? undefined : takeBack); + if (outcome === 'reloaded') { + emitMetadataRefresh(); + return { kind: 'reloaded', draftDiscarded }; + } + } else { + await client.publish(target.type, target.name, scope); + } + } catch (error) { + if (!hadDraft && !draftDiscarded) { + try { + await takeBack(); + } catch (discardError) { + // The draft stays pending, listed under Changes, where it can be discarded. + console.error('[metadata] a refused publish left the saved draft pending:', discardError); + } + } + emitMetadataRefresh(); + return { kind: 'refused', error, draftDiscarded }; + } + emitMetadataRefresh(); + return { kind: 'published' }; +} + +/** + * Whether a pending draft is the AI assistant's: some key of it was last + * written by the copilot or an MCP client (`draftChanges[].by`), the rule the + * designers' notice reads (`StudioDraftMark.tsx`). A draft whose read recorded + * no provenance (`null`) is a person's. + */ +export function isAiDraft(changes: readonly DraftChange[] | null | undefined): boolean { + return (changes ?? []).some((change) => isAgentDraftSurface(change.by)); +} diff --git a/ui/packages/data-objectstack/src/metadata-client.layeredDraft-29793.test.ts b/ui/packages/data-objectstack/src/metadata-client.layeredDraft-29793.test.ts index 49952cc4946..4c757d4c65b 100644 --- a/ui/packages/data-objectstack/src/metadata-client.layeredDraft-29793.test.ts +++ b/ui/packages/data-objectstack/src/metadata-client.layeredDraft-29793.test.ts @@ -73,3 +73,29 @@ describe('MetadataClient.layered() forwards the stored draft layer (objectstack# }); } }); + +/** + * objectstack#36902 — the published row's version (`overlayVersion`) is + * forwarded the same way: the pinned publish of a Studio Save sends it as + * `If-Match` (objectstack#36601), and the client rebuilding its result field + * by field dropped it, so every such publish went unpinned. + */ +describe('MetadataClient.layered() forwards the published version (objectstack#36902)', () => { + it('the conforming fixture still parses with the version served', () => { + expect(GetMetaItemLayeredResponseSchema.safeParse({ ...CONFORMING, overlayVersion: 'v7' }).success).toBe(true); + }); + + for (const [branch, body] of [['conforming', CONFORMING], ['degraded', DEGRADED]] as const) { + it(`${branch}: a served version arrives as served, and a served null as null`, async () => { + expect((await clientAnswering({ ...body, overlayVersion: 'v7' }).layered('object', 'ticket')).overlayVersion).toBe('v7'); + const none = await clientAnswering({ ...body, overlayVersion: null }).layered('object', 'ticket'); + expect('overlayVersion' in none).toBe(true); + expect(none.overlayVersion).toBeNull(); + }); + + it(`${branch}: a version the server did not serve stays absent`, async () => { + const layered = await clientAnswering(body).layered('object', 'ticket'); + expect('overlayVersion' in layered).toBe(false); + }); + } +}); diff --git a/ui/packages/data-objectstack/src/metadata-client.ts b/ui/packages/data-objectstack/src/metadata-client.ts index 4c59689d35c..20d9707e6d0 100644 --- a/ui/packages/data-objectstack/src/metadata-client.ts +++ b/ui/packages/data-objectstack/src/metadata-client.ts @@ -635,6 +635,14 @@ export interface MetadataLayered { * key is forwarded only when the server sent it. */ draft?: T | null; + /** + * objectstack#36601 — the published row's version (spec + * `GetMetaItemLayeredResponseSchema.overlayVersion`): the token a pinned + * publish sends as `If-Match`, `null` when no published row is stored at the + * read's address. ABSENT when the server served none (a server from before + * the field): a caller then pins nothing. Forwarded only when served. + */ + overlayVersion?: string | null; /** * Load-time validation result for `effective` (server-computed via * the same Zod registry used at save time). Undefined for types @@ -1851,6 +1859,8 @@ export class MetadataClient { effective: (envelope.effective ?? null) as T | null, // objectstack#29793 — the draft layer, forwarded only when served. ...('draft' in body ? { draft: (body.draft ?? null) as T | null } : {}), + // objectstack#36601 — the published version a pinned publish sends, forwarded only when served. + ...(envelope.overlayVersion !== undefined ? { overlayVersion: envelope.overlayVersion } : {}), ...(body._diagnostics ? { _diagnostics: body._diagnostics as MetadataDiagnostics } : {}), lock: envelope.lock, ...(envelope.lockReason !== undefined ? { lockReason: envelope.lockReason } : {}), @@ -1884,6 +1894,7 @@ export class MetadataClient { overlayScope: body.overlayScope ?? null, effective: body.effective ?? null, ...('draft' in body ? { draft: (body.draft ?? null) as T | null } : {}), + ...(body.overlayVersion !== undefined ? { overlayVersion: body.overlayVersion as string | null } : {}), ...(body._diagnostics ? { _diagnostics: body._diagnostics as MetadataDiagnostics } : {}), ...(body.lock !== undefined ? { lock: body.lock as MetadataLayered['lock'] } : {}), ...(body.lockReason !== undefined ? { lockReason: body.lockReason as string } : {}), diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 1b3045e8e88..fce3b1420d1 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -1330,6 +1330,8 @@ const STUDIO_EN: Record = { 'engine.edit.discardDraftConfirmBody': 'The published version stays as it is; only the unpublished changes are removed.', 'engine.edit.draftDiscarded': 'Draft discarded: {item}', 'engine.edit.draftPending': 'Pending changes — save lives in a draft. Click Publish to release.', + 'engine.edit.unpublishedChanges': 'This item has unpublished changes. Publish or discard them here.', + 'engine.edit.unpublishedPublishDirty': 'Saving makes these changes live together with your edits.', 'engine.edit.rollback': 'Rollback to this version', 'engine.edit.rollbackConfirm': 'Restore version {version}? This writes the historical body back as the current published overlay.', 'engine.edit.rollbackConfirmTitle': 'Restore {item} to version {version}?', @@ -1753,9 +1755,6 @@ const STUDIO_EN: Record = { 'You have unsaved changes. Leave this page anyway?', 'engine.edit.saving': 'Saving…', 'engine.edit.savedAt': 'Saved {time}', - 'engine.edit.autoSaveOn': 'Auto-save is on — click to disable', - 'engine.edit.autoSaveOff': 'Auto-save is off — click to enable', - 'engine.edit.autoSavingShortly': 'Auto-saving…', 'engine.edit.notSavedHeld': 'Not saved — fix the errors to save', 'engine.edit.destructive': 'Destructive change', 'engine.edit.destructiveHint': diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index d54194135a6..8e23912a483 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -1183,6 +1183,8 @@ const STUDIO_ZH: Record = { 'engine.edit.discardDraftConfirmBody': '已发布的版本保持不变,仅移除未发布的更改。', 'engine.edit.draftDiscarded': '已丢弃 {item} 的待发布草稿', 'engine.edit.draftPending': '存在未发布的草稿 — 保存仅写入草稿,点击"发布"使其生效。', + 'engine.edit.unpublishedChanges': '这一项有未发布的改动,可以在这里发布或放弃。', + 'engine.edit.unpublishedPublishDirty': '保存会让这些改动和本页的修改一起生效。', 'engine.edit.rollback': '回滚到此版本', 'engine.edit.rollbackConfirm': '恢复版本 {version}?该历史内容将被写回作为当前已发布的覆盖层。', 'engine.edit.rollbackConfirmTitle': '将 {item} 恢复到版本 {version}?', @@ -1564,9 +1566,6 @@ const STUDIO_ZH: Record = { 'engine.edit.unsavedLeaveConfirm': '当前存在未保存的修改,确定离开此页面吗?', 'engine.edit.saving': '保存中…', 'engine.edit.savedAt': '已保存 {time}', - 'engine.edit.autoSaveOn': '自动保存已开启,点击关闭', - 'engine.edit.autoSaveOff': '自动保存已关闭,点击开启', - 'engine.edit.autoSavingShortly': '即将自动保存…', 'engine.edit.notSavedHeld': '未保存 — 修正错误后才能保存', 'engine.edit.destructive': '破坏性变更', 'engine.edit.destructiveHint': '该修改会破坏现有引用关系。请检查问题清单后确认强制保存。',