Skip to content

Commit 1e96009

Browse files
feat(studio): the generic item page's Save takes effect at once; an AI draft gets the designers' notice and discard (#37026)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBTuMGhLAZx29zwDrayDGZZF)_ Fixes #36902 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:管理员在 Studio 的通用详情页(钩子、选项集、视图等)改完点「保存」,改动立刻生效;不再有自动保存开关,也不用再点一次「发布」。 - 为什么做:Studio 重构专题里「通用详情保存即生效」这一项,让通用详情和各个设计器的保存方式一致。 - 出错会怎样:发布被拒时,页面上方写明原因,什么都不生效,页面上的修改保留可以再存;AI 留下的草稿保留并有提示,可以一键放弃;本改动可以直接撤回。 - 要你做什么:无 ## What changes Studio's generic item page (`ResourceEditPage`, every type without its own designer: hook, picklist, view, page, app, doc…) now saves the way the designers do (#36511, epic decisions 1, 12, 14). 1. **Save = draft + this one item's publish.** Save writes the draft (`PUT /meta/:type/:name?mode=draft`, If-Match / If-None-Match pin and conflict dialog unchanged), then publishes that one item (`POST /meta/:type/:name/publish`) at the same `?package=` and bundle `member`. The publish is pinned to the published version the page loaded, through the existing `DraftSaveGuard.publish` (#36601), so a Save over a row another editor published since opens the same conflict dialog (reload, overwrite, keep editing). The auto-save switch, its 1.5 s debounce and the `metadata-admin:autosave` browser setting are gone; the header's Publish and discard-draft buttons are gone. 2. **Create publishes after its first save** (If-None-Match `*`, then the publish). 3. **AI draft** (`draftChanges[].by` is `copilot` or `mcp`): the page shows the AI's version under the designers' `StudioAiDraftNotice`; a person's Save makes it live together with their edits; "Discard the AI's changes" drops that one item's draft at its package and member, and asks first (in the page's own dialog, objectui#13333) when the page holds unsaved edits. 4. **A person's pending draft** from before this change is marked "This item has unpublished changes" with its own Publish (pinned) and Discard for that one item. 5. **Leave guard**: ×, ‹ ›, the side menu, in-app links, reload and close ask first when the page holds unsaved edits; browser Back is not intercepted (decision 12). The seam was already in place (`chrome/unsavedEdits.ts`); this PR pins it on this page. 6. **A refused publish** shows its reason above the editor in the designers' words (`publishRefusal`, server text under Details). Nothing goes live; the draft the Save wrote is taken back when no draft was pending before, and the edits stay on the page, unsaved. A draft that was pending before (the AI's or a person's) is kept. 7. **`@object-ui/data-objectstack`: `MetadataClient.layered()` now forwards `overlayVersion`.** The client rebuilt its answer field by field and dropped it, so a publish pin read off `layered()` was always `null`. This is why the Save's publish could not be pinned; it also made the object page's #36601 publish pin a no-op on a server that serves the field. Fixed in place (bounded fix: same defect class as the card's pin, mechanical, the file had no other claim, no new gate surface) and pinned in `metadata-client.layeredDraft-29793.test.ts`. **Clause-② yes (widening):** the published package's exported `MetadataLayered` type gains the optional member `overlayVersion?: string | null` (claim amendment on #36902, 7137741670; L1-b (3) S1, 7137721696). New shared piece: `detailSaveAtOnce.ts` (`publishDetailSave`, `isAiDraft`). The designers' `publishSavedItem` (`studioSaveBar.tsx`) names no bundle member, so this page carries its own instead of changing that file. `StudioDesignSurface.tsx`, `DraftConflictDialog.tsx` and `studioSaveBar.tsx` are unchanged (reused as they are). ### How this relates to #36726 and #36350 - **#36726** (open PR #36958 pins the designers' publish): no shared files, either PR can land first. This card pins the generic page's own publish with the same #36601 `DraftSaveGuard` API, used as it is on main. The `overlayVersion` client fix (item 7) is what makes a pin read off `layered()` effective at all, the object page's included. One sequencing item: #36958 adds rule 9 to the guard (a reload over a draft that was pending before the Save keeps the conflict's pin until the author re-confirms), answered by a `beforeReload` that returns `'kept'`. On main that callback is typed to resolve to nothing (a void promise) and refuses that answer (tsc TS2345, measured), so it cannot be written here without editing `DraftConflictDialog.tsx`, which this card must not touch. Today this page is at parity with main's guard. Whichever PR lands second adds the one-line `beforeReload` for the `hadDraft` case in `publishDetailSave`. - **#36350** (view-draft publish takes a draft-version precondition): left to #36350. That is a change to the publish door (server / protocol), outside this card's boundary (Metadata-protocol: none). This page's publish is pinned on the published version, not on the draft version, so the window #36350 describes (another writer's draft write between this Save's draft save and its publish, then published by this Save) is still open for views until #36350 lands. When it does, the Save's publish can send the draft version it just received; the call site is `publishDetailSave`. ### Read first (by risk) 1. `ResourceEditPage.tsx` `doSave`: the draft save → `publishDetailSave` → refresh sequence, and the refused branch (take-back only when `hadDraft` is false). 2. `detailSaveAtOnce.ts`: the take-back on a refused or conflicted publish. 3. `metadata-client.ts` `layered()`: the two `overlayVersion` forwards. ### Two-minute check Open Studio → All metadata → any view, change its label, press Save. Expected: one `PUT …?mode=draft` and one `POST …/publish` in the network panel, the Unsaved chip clears, no "unpublished changes" line, and `GET /api/v1/meta/view/NAME` already serves the new label. ## Tests ### Acceptance run (the card's 验收 scenario, real browser, self-built stack) Backend `examples/app-showcase` (`objectstack dev --seed-admin --fresh`) and the console dev server, both built from this branch, on per-agent ports. The items are my own, authored into the showcase's customization package (`com.example.showcase.custom`): a hook, a shared option set (picklist) and two views. The backend ran with `OS_METADATA_WRITABLE=picklist`: the picklist type is not runtime-creatable by default (`NOT_CREATABLE`, its registry entry), so the option-set leg needs that operator setting. Each leg edits the label and presses Save once; the network log is the page's own requests. | Item | Before Save | Writes after Save | Live read after Save | |---|---|---|---| | hook `s36902_stamp_title` | chip `unsaved`, no request in 2.5 s | `PUT …?mode=draft&package=…custom` then `POST …/publish?package=…custom` (200) | new label served; no unpublished-changes line | | picklist `s36902_priority` | same | same pair (200) | same | | view `showcase_task.s36902_triage` | same | same pair (200) | same | <details><summary>Screenshots: hook, option set, view (unsaved, then saved and live)</summary> ![hook, unsaved](https://github.com/objectstack-ai/objectstack/raw/566b916797d827170f5e073c774c1759f02c223e/1-hook-unsaved.png) ![hook, saved and live](https://github.com/objectstack-ai/objectstack/raw/566b916797d827170f5e073c774c1759f02c223e/1-hook-saved.png) ![option set, unsaved](https://github.com/objectstack-ai/objectstack/raw/566b916797d827170f5e073c774c1759f02c223e/2-picklist-unsaved.png) ![option set, saved and live](https://github.com/objectstack-ai/objectstack/raw/566b916797d827170f5e073c774c1759f02c223e/2-picklist-saved.png) ![view, unsaved](https://github.com/objectstack-ai/objectstack/raw/566b916797d827170f5e073c774c1759f02c223e/3-view-unsaved.png) ![view, saved and live](https://github.com/objectstack-ai/objectstack/raw/566b916797d827170f5e073c774c1759f02c223e/3-view-saved.png) </details> **AI draft.** Written through the real MCP door, not faked: an OAuth client (dynamic registration, PKCE, consent, `metadata:write`) called `save_metadata_draft` on `showcase_task.s36902_ai`; the draft read then carried `draftChanges: [{path: ["label"], by: "mcp", …}]`. - The page shows the AI's version under the notice (4). An edit then "Discard the AI's changes" asks in the page's own dialog (5); confirming sends one `DELETE …?state=draft&package=…custom`, the draft read answers 404 and the live version is back (6). - A second MCP draft, then an edit and Save: `PUT` draft + `POST …/publish` (200), the draft read answers 404, the live label is the AI's change plus the person's edit (7). - Leave guard: with an unsaved edit, × asked "You have unsaved changes. Leave this page anyway?", and Cancel stayed on the item. <details><summary>Screenshots: AI draft notice, discard, save</summary> ![AI draft notice](https://github.com/objectstack-ai/objectstack/raw/566b916797d827170f5e073c774c1759f02c223e/4-ai-draft-notice.png) ![discard asks first with unsaved edits](https://github.com/objectstack-ai/objectstack/raw/566b916797d827170f5e073c774c1759f02c223e/5-ai-discard-asks.png) ![AI draft discarded, live version back](https://github.com/objectstack-ai/objectstack/raw/566b916797d827170f5e073c774c1759f02c223e/6-ai-discarded.png) ![AI draft saved live with the person edit](https://github.com/objectstack-ai/objectstack/raw/566b916797d827170f5e073c774c1759f02c223e/7-ai-draft-saved-live.png) </details> Images: orphan branch `claude/issue-36902-screenshots` at `566b916`. ### Live e2e `LIVE_APP_URL=… LIVE_API_URL=… pnpm exec playwright test -c playwright.live.config.ts e2e/live/studio-detail-save-at-once.spec.ts e2e/live/studio-editor.spec.ts`: 3 passed (the new spec: no auto-save in 2.5 s, × asks, Save sends exactly `PUT` + `POST …/publish`, the live page has the added block, the draft read is 404, browser Back is not intercepted; `studio-editor.spec.ts`'s Add-block round trip now reads the published item after Save). ### Unit At head `09693db5c`, under the shared verify lock, one run: every test file under `metadata-admin/` plus every other ui test file that mentions publish, draft, auto-save or the detail page (338 files), then `type-check` (which compiles the test files too) of `@object-ui/data-objectstack`, `@object-ui/i18n` and `@object-ui/app-shell`. <details><summary>Readings</summary> ```text Test Files 338 passed (338) Tests 2918 passed (2918) packages/data-objectstack type-check: Done packages/i18n type-check: Done packages/app-shell type-check: Done os-verify-lock: VERDICT command-exit 0 ``` New: `ResourceEditPage.saveAtOnce-36902.test.tsx` (19 cases over the real `MetadataClient` and an in-memory server that honours If-Match / If-None-Match on the draft door and on the publish door: items 1–6, the leave guard on ×, ‹ ›, links, beforeunload, Back unguarded, create publishes, refused create). `metadata-client.layeredDraft-29793.test.ts` gains the `overlayVersion` forward on both answer shapes (served value, served null, absent). </details> ## Acceptance notes - 'Changes 1' in shots 1–3 is the AI draft of `showcase_task.s36902_ai`, written through MCP before the save leg for shots 4–7; it clears in shot 6 once that draft is discarded (not the hook: its Save sent `PUT ?mode=draft` then `POST /publish` 200). - Existing detail-page suites that waited out the auto-save or clicked the header's Publish / Discard draft now press Save and read the Save's own publish, or use the unpublished-changes line's buttons (14 files). Their doubles gained a publish that drains the draft, as the real door does; assertions that only held because a draft stayed pending after Save were rewritten to the live result. `layersUnsaved-11799`'s SAVE case now expects one `/layers` re-read: a Save publishes, so the item has a layer afterwards. - Leftover `localStorage.setItem('metadata-admin:autosave', '0')` lines in suites this PR does not otherwise touch are now no-ops; left as they are to keep the diff to the card. - The platform checklist step that says the ResourceEditPage draft auto-saves and is then published (`docs/qa/platform-checklist/areas/studio-authoring.json`, the page Add-block item) is now stale. carrier: #36910 (the epic's checklist-and-docs card). - The designers' own auto-save (Data / Automations / Access pillars) is unchanged: out of this card. ## Verification <details><summary>Local gates (derived for this diff) and reconciliation</summary> - `node scripts/pm/dispatch-gates.mjs --commands`: 39 families. All 39 run locally: 38 exit 0 (`check:*` and the node scripts, re-run after the last code commit), and `pnpm --dir ui exec vitest run scripts/` under the lock at `c8a49c900` (the one later commit changes only a live e2e spec): `Test Files 172 passed | 2 skipped (174)`, VERDICT command-exit 0. - `node scripts/pm/dispatch-gates.mjs --ran FILE` (each line with its exit code): `39 derived famil(ies) accounted for — 39 run, 0 NOT-MEASURED (a DERIVED zero)`. - `node scripts/check-test-source-alias.mjs`: OK, 34 changed test files judged (the touched suites now load `@objectstack/lint` at collection, as the gate asks). - `node scripts/pm/overlap-check.mjs` before every push: `VERDICT clean exit 0` (shares only the i18n catalogues and `metadata-client.ts` with #36983, #36985, #36784; each merges cleanly). - The rest of the farm (lint, the CI test shards, `test:repo`) is CI's; its check-runs are read on the PR. </details> Changed lines: 1,650 over 24 files (1,317 added, 333 removed), one PR. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufziBCAytAzzCu3iPBFR --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0e3187e commit 1e96009

24 files changed

Lines changed: 1317 additions & 333 deletions
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/i18n': patch
4+
'@object-ui/data-objectstack': patch
5+
---
6+
7+
feat(studio): the generic item page's Save takes effect at once; an AI draft gets the designers' notice and discard
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: none
11+
12+
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.
13+
14+
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.
15+
16+
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.
17+
18+
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.
19+
20+
`@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.
21+
22+
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.
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import { test, expect, type APIRequestContext, type Dialog } from '@playwright/test';
2+
3+
/**
4+
* Live e2e for the generic Studio item page's save model (objectstack#36902,
5+
* epic objectstack#36890 decisions 1 and 12): Save makes the item live at once
6+
* (its draft, then that one item's publish), with no auto-save and no second
7+
* Publish step, and leaving with unsaved edits asks first through × and ‹ ›
8+
* while the browser's Back is not intercepted.
9+
*
10+
* The item under edit is a page the test authors in the environment (a copy of
11+
* the showcase's `showcase_project_workspace`), removed again at the end, as
12+
* `studio-editor.spec.ts` does.
13+
*/
14+
const API = process.env.LIVE_API_URL || 'http://localhost:3000';
15+
const SHIPPED_PAGE = 'showcase_project_workspace';
16+
17+
async function authorEditablePage(request: APIRequestContext): Promise<{ name: string; firstRegionBlocks: number }> {
18+
const res = await request.get(`${API}/api/v1/meta/page/${SHIPPED_PAGE}`);
19+
expect(res.ok(), await res.text()).toBeTruthy();
20+
const shipped = (await res.json()).item as Record<string, unknown>;
21+
const body = Object.fromEntries(Object.entries(shipped).filter(([k]) => !k.startsWith('_')));
22+
const firstRegionBlocks = ((body.regions as { components?: unknown[] }[])[0].components ?? []).length;
23+
const name = `e2e_save_at_once_${Date.now()}`;
24+
const put = await request.put(`${API}/api/v1/meta/page/${name}`, {
25+
data: { ...body, name, label: `E2E Save At Once ${name.slice(-6)}` },
26+
});
27+
expect(put.ok(), await put.text()).toBeTruthy();
28+
return { name, firstRegionBlocks };
29+
}
30+
31+
test('Save makes the edit live at once, and an unsaved edit is guarded on × but not on Back', async ({ page, request }) => {
32+
const { name, firstRegionBlocks } = await authorEditablePage(request);
33+
const writes: string[] = [];
34+
page.on('request', (r) => {
35+
if (r.url().includes(`/api/v1/meta/page/${name}`) && ['PUT', 'POST'].includes(r.method())) {
36+
writes.push(`${r.method()} ${new URL(r.url()).pathname}`);
37+
}
38+
});
39+
try {
40+
// The list first, then the item by its row: an in-app navigation, so the
41+
// browser's Back below is the app's own history entry (a full page load
42+
// would make Back a cross-document unload, which the reload guard asks about).
43+
await page.goto('/studio/~all/metadata/page');
44+
await page.getByText(name, { exact: true }).first().click();
45+
await expect(page).toHaveURL(new RegExp(`/metadata/page/${name}`));
46+
await expect(page.getByTestId('metadata-edit-page')).toBeVisible();
47+
48+
await test.step('an edit stays on the page: no auto-save sends it', async () => {
49+
await page.getByRole('button', { name: /Add block/i }).first().click();
50+
await page.getByRole('dialog').getByRole('button', { name: /Card/i }).first().click();
51+
await expect(page.getByTestId('save-status')).toHaveAttribute('data-state', 'unsaved');
52+
await page.waitForTimeout(2500);
53+
expect(writes).toEqual([]);
54+
});
55+
56+
await test.step('× asks before dropping the edit; Cancel stays', async () => {
57+
const asked: string[] = [];
58+
const dismiss = (d: Dialog) => {
59+
asked.push(d.type());
60+
void d.dismiss();
61+
};
62+
page.on('dialog', dismiss);
63+
await page.getByTestId('studio-detail-close').click();
64+
await expect.poll(() => asked).toEqual(['confirm']);
65+
page.off('dialog', dismiss);
66+
await expect(page).toHaveURL(new RegExp(`/metadata/page/${name}`));
67+
});
68+
69+
await test.step('Save writes the draft, then publishes the one item; nothing is left to publish', async () => {
70+
const published = page.waitForResponse(
71+
(r) => r.request().method() === 'POST' && r.url().includes(`/api/v1/meta/page/${name}/publish`),
72+
);
73+
await page.getByTestId('resource-save').click();
74+
const publish = await published;
75+
expect(publish.ok(), await publish.text()).toBeTruthy();
76+
expect(writes).toEqual([`PUT /api/v1/meta/page/${name}`, `POST /api/v1/meta/page/${name}/publish`]);
77+
await expect(page.getByTestId('save-status')).toHaveAttribute('data-state', 'saved');
78+
await expect(page.getByTestId('resource-unpublished-changes')).toHaveCount(0);
79+
const live = await request.get(`${API}/api/v1/meta/page/${name}`, { headers: { 'Cache-Control': 'no-cache' } });
80+
const blocks = (await live.json()).item.regions[0].components as unknown[];
81+
expect(blocks).toHaveLength(firstRegionBlocks + 1);
82+
const draft = await request.get(`${API}/api/v1/meta/page/${name}?state=draft`);
83+
expect(draft.status()).toBe(404);
84+
});
85+
86+
await test.step('browser Back is not intercepted, even with an unsaved edit', async () => {
87+
await page.getByRole('button', { name: /Add block/i }).first().click();
88+
await page.getByRole('dialog').getByRole('button', { name: /Card/i }).first().click();
89+
await expect(page.getByTestId('save-status')).toHaveAttribute('data-state', 'unsaved');
90+
const asked: string[] = [];
91+
const accept = (d: Dialog) => {
92+
asked.push(d.type());
93+
void d.accept();
94+
};
95+
page.on('dialog', accept);
96+
await page.goBack();
97+
await expect(page).toHaveURL(/\/metadata\/page(\?|$)/);
98+
page.off('dialog', accept);
99+
expect(asked).toEqual([]);
100+
});
101+
} finally {
102+
await request.delete(`${API}/api/v1/meta/page/${name}`);
103+
}
104+
});

‎ui/e2e/live/studio-editor.spec.ts‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -86,16 +86,18 @@ test('Add block opens a block-type picker with configurable block kinds, and the
8686
await expect(dialog.getByRole('button', { name: /Section/i })).toBeVisible();
8787
await expect(dialog.getByRole('button', { name: /Record details/i })).toBeVisible();
8888

89-
// The save round trip, not only the canvas: picking a kind autosaves a
90-
// draft, and the draft read back through /meta holds the new block at the
91-
// end of the first region.
92-
const saved = page.waitForResponse(
93-
(r) => r.request().method() === 'PUT' && r.url().includes(`/api/v1/meta/page/${name}?mode=draft`),
94-
);
89+
// The save round trip, not only the canvas: picking a kind is an unsaved
90+
// edit, and Save makes it live at once (objectstack#36902): the item's
91+
// draft, then that one item's publish. The page read back through /meta
92+
// holds the new block at the end of the first region.
9593
await dialog.getByRole('button', { name: /Card/i }).first().click();
96-
const save = await saved;
97-
expect(save.ok(), await save.text()).toBeTruthy();
98-
const stored = await request.get(`${API}/api/v1/meta/page/${name}?state=draft`);
94+
const published = page.waitForResponse(
95+
(r) => r.request().method() === 'POST' && r.url().includes(`/api/v1/meta/page/${name}/publish`),
96+
);
97+
await page.getByTestId('resource-save').click();
98+
const publish = await published;
99+
expect(publish.ok(), await publish.text()).toBeTruthy();
100+
const stored = await request.get(`${API}/api/v1/meta/page/${name}`);
99101
expect(stored.ok(), await stored.text()).toBeTruthy();
100102
const blocks = (await stored.json()).item.regions[0].components as { type?: string }[];
101103
expect(blocks).toHaveLength(firstRegionBlocks + 1);

‎ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.authoredObjectBuffer-29793.test.tsx‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
*/
2525

2626
import '@testing-library/jest-dom/vitest';
27+
// 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`).
28+
import '@objectstack/lint';
2729
import * as React from 'react';
2830
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2931
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
@@ -183,6 +185,12 @@ function renderZh() {
183185
);
184186
}
185187

188+
/** Save is explicit (objectstack#36902): wait for the unsaved edit, then press Save. */
189+
async function pressSave() {
190+
await waitFor(() => expect(screen.getByTestId('save-status').getAttribute('data-state')).toBe('unsaved'), { timeout: 8000 });
191+
fireEvent.click(screen.getByTestId('resource-save'));
192+
}
193+
186194
const editorDraft = (): Row => JSON.parse(screen.getByTestId('editor-draft').textContent ?? '{}') as Row;
187195

188196
function expectAuthored(doc: Row, severityLabel: string) {
@@ -196,28 +204,22 @@ function expectAuthored(doc: Row, severityLabel: string) {
196204
}
197205

198206
describe('MetadataResourceEditPage in a zh-CN console — an object buffer is the authored document (objectstack#29793)', () => {
199-
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 () => {
207+
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 () => {
200208
srv.draft = wire({ ...AUTHORED, description: 'draft only' });
201209
renderZh();
202210

203211
await waitFor(() => expect(editorDraft().name).toBe(OBJECT), { timeout: 8000 });
204212
expect(editorDraft()).toStrictEqual(wire({ ...AUTHORED, description: 'draft only' }));
205213

206214
fireEvent.click(screen.getByRole('button', { name: 'relabel severity' }));
215+
await pressSave();
207216
await waitFor(() => expect(srv.saves.length).toBeGreaterThan(0), { timeout: 8000 });
208217
const { body, opts } = srv.saves.at(-1)!;
209218
expect(opts).toMatchObject({ mode: 'draft' });
210219
expectAuthored(body, 'Level');
211220
expect(body.description).toBe('draft only');
212221

213-
// The refresh after the save installs the stored draft again, not the served one.
214-
await waitFor(() => expect((editorDraft().fields as Record<string, Row>).severity.label).toBe('Level'), { timeout: 8000 });
215-
expectAuthored(editorDraft(), 'Level');
216-
217-
// Publish: the refresh installs the promoted body as authored (`overlay`).
218-
const publish = await screen.findAllByRole('button', { name: new RegExp(`^${t('engine.edit.publish', 'zh-CN')}$`) }, { timeout: 8000 });
219-
await waitFor(() => expect(publish[0]).toBeEnabled(), { timeout: 8000 });
220-
fireEvent.click(publish[0]!);
222+
// The Save publishes the item, and the refresh installs the promoted body as authored (`overlay`).
221223
await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(1), { timeout: 8000 });
222224
await waitFor(() => expect(srv.draft).toBeNull(), { timeout: 8000 });
223225
await act(async () => {
@@ -233,6 +235,7 @@ describe('MetadataResourceEditPage in a zh-CN console — an object buffer is th
233235
expect(editorDraft()).toStrictEqual(wire(AUTHORED));
234236

235237
fireEvent.click(screen.getByRole('button', { name: 'relabel severity' }));
238+
await pressSave();
236239
await waitFor(() => expect(srv.saves.length).toBeGreaterThan(0), { timeout: 8000 });
237240
expectAuthored(srv.saves.at(-1)!.body, 'Level');
238241
});
@@ -401,27 +404,31 @@ describe.each(TRANSLATED_TYPES)(
401404
if (realTypePreview) registerMetadataPreview(spec.type, realTypePreview);
402405
});
403406

404-
it('no pending draft: two edits in a row each PUT source text, the second after the save refresh re-read the draft', async () => {
407+
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 () => {
405408
renderTypeZh(spec);
406409
await waitFor(() => expect(editorDraft().name).toBe(spec.name), { timeout: 8000 });
407410
expect(spec.sourceText(editorDraft())).toStrictEqual(SOURCE_TEXT[spec.type]);
408411

409412
fireEvent.click(screen.getByRole('button', { name: 'edit once' }));
413+
await pressSave();
410414
await waitFor(() => expect(srv.saves.length).toBe(1), { timeout: 8000 });
411415
expect(srv.saves[0]!.opts).toMatchObject({ mode: 'draft' });
412416
expect(spec.sourceText(srv.saves[0]!.body)).toStrictEqual(SOURCE_TEXT[spec.type]);
413417

414-
// The save refresh: the served draft is now the zh-CN one, the layers' the stored one.
418+
// The Save published the draft; the refresh re-reads the stored row, in source text.
419+
await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(1), { timeout: 8000 });
415420
await waitFor(() => expect(mockClient.getDraft.mock.calls.length).toBeGreaterThan(1), { timeout: 8000 });
416421
await act(async () => {
417422
await new Promise((resolve) => setTimeout(resolve, 50));
418423
});
419424
expect(spec.sourceText(editorDraft())).toStrictEqual(SOURCE_TEXT[spec.type]);
420425

421426
fireEvent.click(screen.getByRole('button', { name: 'edit once' }));
427+
await pressSave();
422428
await waitFor(() => expect(srv.saves.length).toBe(2), { timeout: 8000 });
423429
expect(spec.sourceText(srv.saves[1]!.body)).toStrictEqual(SOURCE_TEXT[spec.type]);
424-
expect(spec.sourceText(srv.draft!)).toStrictEqual(SOURCE_TEXT[spec.type]);
430+
await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(2), { timeout: 8000 });
431+
expect(spec.sourceText(srv.overlay!)).toStrictEqual(SOURCE_TEXT[spec.type]);
425432
});
426433

427434
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)(
431438
expect(spec.sourceText(editorDraft())).toStrictEqual(SOURCE_TEXT[spec.type]);
432439

433440
fireEvent.click(screen.getByRole('button', { name: 'edit once' }));
441+
await pressSave();
434442
await waitFor(() => expect(srv.saves.length).toBeGreaterThan(0), { timeout: 8000 });
435443
expect(spec.sourceText(srv.saves.at(-1)!.body)).toStrictEqual(SOURCE_TEXT[spec.type]);
436444
});

‎ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.bundleMember-26649.test.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
*/
1919

2020
import '@testing-library/jest-dom/vitest';
21+
// 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`).
22+
import '@objectstack/lint';
2123
import * as React from 'react';
2224
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2325
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
@@ -193,7 +195,7 @@ describe('MetadataResourceEditPage — ?member= opens that bundle member (object
193195
await screen.findByDisplayValue('逾期了,请处理', undefined, { timeout: 8000 });
194196
await settle();
195197

196-
fireEvent.click(screen.getByTitle('Publish'));
198+
fireEvent.click(screen.getByTestId('resource-draft-publish'));
197199
await waitFor(() => expect(server.members.get('zh-CN')!.draft).toBeNull());
198200
await settle();
199201

@@ -208,7 +210,7 @@ describe('MetadataResourceEditPage — ?member= opens that bundle member (object
208210
await screen.findByDisplayValue('逾期了,请处理', undefined, { timeout: 8000 });
209211
await settle();
210212

211-
fireEvent.click(screen.getAllByTitle('Discard draft')[0]!);
213+
fireEvent.click(screen.getByTestId('resource-draft-discard'));
212214
await confirmDialog();
213215
await waitFor(() => expect(server.members.get('zh-CN')!.draft).toBeNull());
214216

‎ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.celGate.test.tsx‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -165,17 +165,17 @@ describe('MetadataResourceEditPage — Save is gated on the block inspector’s
165165
});
166166
});
167167

168-
describe('MetadataResourceEditPage — the save-status chip while the inspector holds auto-save (#29901)', () => {
169-
// `inspectorBlocking` returns the auto-save effect early exactly as a server
170-
// refusal does, so the chip must not promise an auto-save then either.
168+
describe('MetadataResourceEditPage — the save-status chip while the inspector holds Save (#29901)', () => {
169+
// `inspectorBlocking` holds Save exactly as a server refusal does, so the
170+
// chip must not read as a plain unsaved edit then either.
171171
const chipState = () => screen.queryByTestId('save-status')?.getAttribute('data-state') ?? null;
172172

173-
it('reads the held state on a dangling operator, and the auto-save state once it parses', async () => {
173+
it('reads the held state on a dangling operator, and the unsaved state once it parses', async () => {
174174
const box = await openBlockCel();
175175

176-
// CONTROL first: a good predicate dirties the draft and reads auto-save.
176+
// CONTROL first: a good predicate dirties the draft and reads unsaved.
177177
fireEvent.change(box, { target: { value: 'record.amount > 20' } });
178-
await waitFor(() => expect(chipState()).toBe('autosave-pending'), { timeout: 4000 });
178+
await waitFor(() => expect(chipState()).toBe('unsaved'), { timeout: 4000 });
179179

180180
fireEvent.change(box, { target: { value: 'record.amount >' } });
181181
await waitFor(() => expect(chipState()).toBe('held'), { timeout: 4000 });
@@ -185,6 +185,6 @@ describe('MetadataResourceEditPage — the save-status chip while the inspector
185185
);
186186

187187
fireEvent.change(box, { target: { value: 'record.amount > 21' } });
188-
await waitFor(() => expect(chipState()).toBe('autosave-pending'), { timeout: 4000 });
188+
await waitFor(() => expect(chipState()).toBe('unsaved'), { timeout: 4000 });
189189
});
190190
});

0 commit comments

Comments
 (0)