Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .changeset/36902-detail-save-at-once.md
Original file line number Diff line number Diff line change
@@ -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.
104 changes: 104 additions & 0 deletions ui/e2e/live/studio-detail-save-at-once.spec.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>;
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}`);
}
});
20 changes: 11 additions & 9 deletions ui/e2e/live/studio-editor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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) {
Expand All @@ -196,28 +204,22 @@ 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();

await waitFor(() => expect(editorDraft().name).toBe(OBJECT), { timeout: 8000 });
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<string, Row>).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 () => {
Expand All @@ -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');
});
Expand Down Expand Up @@ -401,27 +404,31 @@ 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));
});
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 () => {
Expand All @@ -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]);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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();

Expand All @@ -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());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand All @@ -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 });
});
});
Loading
Loading