Skip to content

Commit ed0edb1

Browse files
feat(studio): the object page saves with Cancel and Save in the top bar, live at once (#36597)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi96kzyjcbK53dPTb3U2Eb422)_ Part of #36511 Clause-②: no Metadata-protocol: none This is the first of three PRs for the card. It covers the object page. Still to come: - PR 2: flows, the enable switch, permissions, and the object page's hooks and an installed app's own actions. - PR 3: field layout, the AI-draft notice with its 「放弃 AI 的改动」 button, and the card's closing line. ## 维护者速读 - 用户能看到什么变化:在 Studio 的对象页(字段、校验规则、动作、设置)改完后,顶栏右侧原来「发布」的位置出现「取消」「保存」。点保存后改动立刻生效,不再每隔一秒半自动存草稿。「变更」「发布」只在有待发布草稿时出现。 - 为什么做:维护者裁定,人类改一项就确认一项、点保存直接生效。本单是「保存即生效」这一系列的第一步,先做对象页。 - 出错会怎样:保存被服务器拒绝时,改动留在页面上,并写明原因;同一次保存里成功的项会被列出来。删掉或改类型已生效的字段前会先问一句。出问题可以直接撤回本单,回到原来的自动存草稿。 - 要你做什么:无。两人同时改同一对象时后保存的人可能覆盖先生效的改动,这件事已交席位按决策卡流程处理。 ## What changes **Mechanism.** A new top-bar coordinator in `studioSaveBar.tsx` does the following: - Editors register their buffers with `useStudioSaveEntry`. - The surface draws Cancel and Save at the right of the top bar, where Publish was, and only while a registered buffer is dirty. They are the column's last actions; only the right-slot icon follows them, as it followed Publish. - One Save sends every dirty buffer in order. A refused buffer does not stop the others. - When something is refused, the toast names each refused item with its reason, then lists the items that were saved. - If any buffer holds an edit it cannot send yet, Save refuses before anything is written. - Save first waits out the editors' expression check of the last keystroke. That is `LINT_DEBOUNCE_MS`, now in its own module `celLintDebounce.ts` (which `CelPredicateField` imports), plus 50 ms. Without the wait, a formula or rule guard typed and saved at once could be sent before its check had judged it (the objectui#4306 rule). **Save = draft + that item's publish.** `publishSavedItem` calls `MetadataClient.publish(type, name, { packageId })`, which is `POST /api/v1/meta/:type/:name/publish?package=` at the package the draft was written to. It is never the package batch. If the publish is refused: - The draft the Save wrote is discarded, unless a draft was already pending before the Save (a copilot's). A pending draft is kept: it now carries the page's edits too. - The edits stay on the page, unsaved, and the reason is shown in the refusal strip. **Editors moved to explicit save in this PR.** All of them are on the object page, as one buffer with one Save: - Fields: - Add, from the Records grid's plus column and from the Form toolbar. - Edit in the field inspector. - Remove. - Column reorder. This is now a buffer edit, not a save of its own. - Validation rules. - The object's own actions. - Settings. - Field groups. - An installed app's object: base-field patches and added `__c` fields. These are saved into its `.custom` pair as an `object_extension` and published there, so they take effect at once. **Editors not changed here** (they keep their draft autosave): - Hooks. The hooks buffer lives in `ObjectHooksPanel` and unmounts on a tab switch, so it has to be lifted into the pillar first. - An installed app's own actions in the pair (`pairObjectActions`). - List and form views, navigation, flows and permissions. **Top bar.** - Changes and Publish are drawn only while drafts are pending. The "No drafts pending publish" disabled state is gone, because nothing is drawn in its place. - Publish refuses, with a toast, while the page holds edits Save has not sent: its re-read would drop them. - The surface's comment saying there is no per-item publish is corrected. **Confirmations.** Save asks before it sends a change that removes or retypes a published field (`objectSaveConfirm.ts`). The field-remove dialog at edit time stays, and its body now says the field leaves once the change is saved and live. Studio has no delete-object affordance (measured: none in the Data pillar or its item tools), so no dialog was added for that. **Leaving.** Opening another object with unsaved edits asks through `confirmDropUnsavedWork`. The switch sends nothing. The unsaved-edit registry the console's leave prompt reads now includes the Save bar's dirty state. **i18n** (`namespaces/studio`, en + zh): - New keys: `engine.studio.save.{save,saving,cancel,title,cancelTitle,done,refused,refusedLine,savedLine,itemSeparator,held,publishFirst,confirmIrreversible,confirmRemoveField,confirmRetypeField}` and `engine.studio.held.lineExplicit`. - `designer.field.removeConfirmBody` is reworded. - Alternatives considered: `engine.studio.saveBar.*` and `engine.studio.commit.*`. The name `save` matches the button's word. ## Tests New files, named for this card: - `DataPillar.saveCancel-36511.test.tsx`. Covers: - Nothing is sent before Save. Save sends a PUT of the draft with `?package=`, then a POST to publish with `?package=`. - Cancel re-reads the object with no writes. - A refused publish discards the draft. A refusal strip appears, the edit is kept, and Save is still offered. - A held picklist blocks Save. - Removing a published field asks at Save. Declined, nothing is sent; accepted, PUT then publish. - `studioSaveBar.partialSave-36511.test.tsx`. Covers ordering, a partial refusal naming the item and its reason, the saved list, a held buffer, and Cancel. - `StudioDesignSurface.saveBar-36511.test.tsx`. Covers: - With no draft, the top bar has no Changes or Publish, and Cancel then Save are the last actions. - With a draft, the order is Changes, Publish, Cancel, Save, and Publish waits for Save. - `__tests__/studioSaveHarness.tsx`. A harness so a pillar mounted alone gets the same coordinator and buttons. **Retired, with the reason:** - `DataPillar.savedAtDisplayLocale-10232.test.tsx` (3 tests). The "Saved HH:MM" hint they pinned is gone: there is no autosave left to time. - `StudioDesignSurface.draftVersionConflict-11773`, the case where two editors each load and save once with no draft pending. A Save now publishes, so no draft is left for the second editor's `If-None-Match: *` to collide with. See Acceptance notes. - `StudioDesignSurface.publishReadOnlyReason-12303`, the objectstack#31495 "nothing pending" block (3 tests). Replaced by one case: no Publish and no reason are drawn. - `StudioDesignSurface.interfacePolish`, "no draft: disabled Publish with visible reason". Replaced by: no Publish at all. **Rewritten to the new semantics.** Each flipped pin asserts nothing sent before Save, then the draft write and the item's publish after Save, or that Cancel or a declined question leaves the page as it was: - DataPillar, Save-gate suites: `celGate`, `panelGate`, `panelHold-27629`, `heldIncomplete-11786`, `choiceWithoutOptions-11253`, `summaryHeld-27461`, `authorRefusal-11785`, `actionRefusal-26736`, `showMeFocus-26730`, `picklistServedOptions-10202`. - DataPillar, other suites: - `hiddenSystemFields-11780`, `recordsTab-34794`, `addFieldPopover-12516`, `copilotDraftMarks-12725`. - `destructiveChange-34931`, `draftSavedNamed-28984` (the toast is now "Saved, live now: Task" under one sonner id), `draftUnreadable-29148`. - `authoredBuffer-29793`, `pairActions-30088` (only its writable control), `baseObjectExtension-28575` (its double now publishes the pair's extension). - `validationVerdictHold-27644` (its double's publish refuses the guard the door refuses), `railSwitchFlush-27511` (the switch asks and sends nothing; a saved edit leaves nothing to ask about). - StudioDesignSurface suites: `autosaveInFlight-11204` (Data block: an edit taken during a Save is the next Save's), `autosaveSwitch-11232` (Data cases), `draftVersionConflict-11773` (the race over a pending draft is refused, with reload and overwrite), `customizePublish-28562`, `narrowHeader-12509`, `packageListErrorPosture`, `publishPosture-12517`. - `DataPillar.internalFormRetired-36425`, added on main by #36543 while this branch was open, now presses Save before its two Add group saves. `DataPillar.formViewLayout-30057` was deleted on main by that PR, and its one Data-page edit went with it. - 17 edited suites gained a module-top `import '@objectstack/lint'`, as `check:test-source-alias` asks of an edited file that reaches the linter. <details><summary>Studio-design suite after the last commit</summary> Final head `1d6c0845`, same tree as the run except the registry method rename, which the scripts run below covered. ``` cd ui && pnpm exec vitest run --maxWorkers=2 packages/app-shell/src/views/studio-design \ (+ CelPredicateField, ObjectFieldInspector.celGate, ResourceEditPage.celGate, PermissionMatrixEditor.saveSurface-12725, i18n studio-namespace, studio-namespace-lazy) Test Files 359 passed (359) Tests 2774 passed (2774) cd ui && pnpm exec vitest run --maxWorkers=2 scripts/ (+ the three new 36511 suites) Test Files 175 passed | 2 skipped (177) Tests 5138 passed | 2 skipped (5140) os-verify-lock: VERDICT command-exit 0 ``` Before the pins were rewritten, the same studio-design run read: 33 failed files and 89 failed tests out of 2733. Those are the pins this PR flips. </details> <details><summary>Type-check (both configs) and dependency build</summary> ``` pnpm --filter @object-ui/app-shell type-check (tsc --noEmit && tsc -p tsconfig.test.json) os-verify-lock: VERDICT command-exit 0 · held the lock 119s pnpm --workspace-concurrency=2 --filter '@object-ui/app-shell^...' build (after merging origin/main) os-verify-lock: VERDICT command-exit 0 · held the lock 433s ``` </details> <details><summary>Gates (dispatch-gates --ran)</summary> Head `1d6c0845`. `node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack --ran FILE`: ``` Run reconciliation — 39 derived, 39 run, 0 NOT-MEASURED, 0 UNRUN. ✓ dispatch-gates --ran: 39 derived famil(ies) accounted for — 39 run, 0 NOT-MEASURED ``` ``` node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-sdui-manifest.mjs :: exit 0 node scripts/check-sdui-manifest.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/pm/check-governed-queue-guard.mjs --self-test :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm --filter @objectstack/spec run check:error-code-provenance :: exit 0 pnpm check:adr-anchors :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:skill-identifier-liveness :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 pnpm --dir ui exec vitest run scripts/ :: exit 0 ``` `node scripts/check-nul-bytes.mjs`: OK. `node scripts/pm/overlap-check.mjs`: VERDICT clean exit 0 (against #36580 and #36579, which share the studio namespace files). </details> ## Acceptance notes - **Concurrent editors over a published object** (seat ruling 7089589821 on #36511: accepted as a transitional window; the server guard is tracked on #36601, not awaited here). The draft-version guard pins drafts only. After a Save publishes, no draft is left, so the second editor's next Save asserts no draft and succeeds over the first editor's live change. The server serves no published-layer version a save could pin. When a draft was pending at open, the race is still refused with the conflict dialog; that case is pinned in `draftVersionConflict-11773`. Until #36601 lands, the second editor's Save overwrites the first editor's live change. - **AI and a human on one item.** While the page holds unsaved edits, the refresh pulse is held, so a copilot draft written meanwhile is not shown over them. Save is pinned to the draft read: if the copilot wrote a draft in between, the conflict dialog offers reload or overwrite, so neither side is lost silently. If the publish is refused, a pending copilot draft is kept and carries the page's edits. - **A rule guard refused by the publish.** The object publish locator does not place a `validations.N.condition` path, so the strip reads "Not published: the server refused this draft. Details say why." and the rule's reason is under Details. This is the locator's existing reach, not new here. - **The served-verdict hold** (objectstack#27644) still holds a rule whose stored draft the door refused, when that draft was pending at open. A Save the publish refuses now shows the reason at once instead of leaving a draft whose re-read holds the next edit. - **Removing a published field** asks twice: once in the remove dialog at edit time, and once at Save. The card names a confirmation for both removal and type changes. Folding them into one is a product call left to the card. - **ADR sentences the new behaviour contradicts**, for objectstack#36086: - ADR-0027 M2, "explicit, batched publish". - ADR-0037, "Publish remains the single commit gate". - The surface comment "There is no per-item publish". This one is corrected in code. - **Not measured.** - The single-item publish was not run against a live server in this run. The route `POST /api/v1/meta/:type/:name/publish` (`publishMetaItem`) and the existing caller `saveAndPublishRuntimeMetadata` are cited. - The full-farm CI families were not run locally (local scope rule). ## Verification Read first: 1. `ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx`. The coordinator's held and settle check, and `publishSavedItem`'s discard rule. 2. `StudioDesignSurface.tsx`, the DataPillar `doSave` and `doSaveExt` hunk. Riskiest: the refused-publish restore of `objStoredRef` and `hasDraft`. 3. `DataPillar.saveCancel-36511.test.tsx`. Two-minute check: `cd ui && pnpm exec vitest run packages/app-shell/src/views/studio-design/DataPillar.saveCancel-36511.test.tsx`. Expected: 5 passed, including the case where nothing is sent before Save, then a PUT with `mode=draft&package=` followed by a POST to `/publish?package=`. Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmPsv99YG2tCHoSe8Nb --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent ceaa70e commit ed0edb1

48 files changed

Lines changed: 1903 additions & 847 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/i18n': patch
4+
---
5+
6+
feat(studio): the object page saves with Cancel and Save in the top bar, and a Save is live at once
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
Studio's object page (fields, validation rules, actions, settings and field groups) no longer autosaves a draft 1.5 s after each edit. Edits stay on the page until the author presses Save, which sits at the right of the Studio top bar where Publish was; Cancel beside it puts the page back as the server holds it. Save writes the object's draft and then publishes that one object at the package it was written to, so the change is live at once. An installed app's object takes its edits into the paired `.custom` package and publishes them there.
12+
13+
Changes and Publish are drawn only while drafts are pending (a copilot's, or another editor's), and a publish waits while the page holds edits Save has not sent. A Save refused by the server keeps the edits on the page with the reason, and its toast names each refused item with its reason and lists the items that were saved. Removing or retyping a published field asks first. Save waits out the expression checks of the last keystroke, so a formula or rule guard that does not parse is never sent. Leaving the page, or opening another object, with unsaved edits asks, as every departure does.
14+
15+
Other Studio editors (flows, hooks, list and form views, navigation, permissions) keep their draft autosave for now.

‎ui/e2e/live/studio-customize-journey.spec.ts‎

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { test as base, expect, type APIRequestContext, type Page, type Response } from '@playwright/test';
1+
import { test as base, expect, type APIRequestContext, type Page, type Request, type Response } from '@playwright/test';
22

33
/**
44
* Live e2e for the ADR-0146 customization journey, walked through the Studio
@@ -12,9 +12,10 @@ import { test as base, expect, type APIRequestContext, type Page, type Response
1212
* type's list) — not what the canvas draws.
1313
* 2. Restore package original: the pair's draft and row are deleted at the
1414
* pair, and the three reads serve the shipped column set again.
15-
* 3. Add `region__c`: Add field on the base object's Form writes an
16-
* `object_extension` into the pair; once published, the base object is
17-
* served with the field and the pair's own read and export carry it.
15+
* 3. Add `region__c`: Add field on the base object's Form, then the top
16+
* bar's Save (objectstack#36511), writes an `object_extension` into the
17+
* pair and publishes that one item there, so the base object is served
18+
* with the field at once and the pair's own read and export carry it.
1819
* 4. Uninstall the base: the uninstall door refuses the read-only showcase
1920
* with 422 `WRITABLE_PACKAGE_REQUIRED` and removes nothing. This is the
2021
* refusal `main` answers here, and the one asserted: `DELETE
@@ -230,19 +231,45 @@ test('a read-only base is customized, restored and extended through Studio, and
230231
await page.getByTestId('add-field-label-input').fill(FIELD.label);
231232
await expect(page.getByTestId('add-field-api-name-preview')).toContainText(FIELD.name);
232233

234+
// objectstack#36511 — the add stays on the page until the top bar's
235+
// Save: no write of the extension leaves before it is pressed.
236+
const extensionWrites: string[] = [];
237+
const onRequest = (r: Request) => {
238+
if (r.method() !== 'GET' && r.url().includes(`/api/v1/meta/object_extension/${OBJECT}`)) {
239+
extensionWrites.push(`${r.method()} ${r.url()}`);
240+
}
241+
};
242+
page.on('request', onRequest);
243+
await page.getByTestId('add-field-create').click();
244+
await expect(page.getByTestId('studio-save')).toBeVisible();
245+
expect(extensionWrites).toEqual([]);
246+
247+
// Save writes the extension's draft into the pair, then publishes that
248+
// one item there: live at once, with no package publish.
233249
const drafted = page.waitForResponse(
234250
(r) => r.request().method() === 'PUT' && r.url().includes(`/api/v1/meta/object_extension/${OBJECT}?`),
235251
);
236-
await page.getByTestId('add-field-create').click();
252+
const published = page.waitForResponse(
253+
(r) => r.request().method() === 'POST' && r.url().includes(`/api/v1/meta/object_extension/${OBJECT}/publish`),
254+
);
255+
await page.getByTestId('studio-save').click();
237256
const draft = await drafted;
238257
expect(draft.ok(), await draft.text()).toBeTruthy();
239258
expect(new URL(draft.url()).searchParams.get('package')).toBe(PAIR);
259+
expect(new URL(draft.url()).searchParams.get('mode')).toBe('draft');
240260
expect(draft.request().postDataJSON()).toEqual({
241261
extend: OBJECT,
242262
fields: { [FIELD.name]: { type: 'text', label: FIELD.label } },
243263
});
244-
245-
await publishPair(page);
264+
const publish = await published;
265+
expect(publish.ok(), await publish.text()).toBeTruthy();
266+
expect(new URL(publish.url()).searchParams.get('package')).toBe(PAIR);
267+
// The Save left nothing to save, and no draft for the package publish.
268+
await expect(page.getByTestId('studio-save')).toHaveCount(0);
269+
page.off('request', onRequest);
270+
expect(extensionWrites.map((w) => w.split(' ')[0])).toEqual(['PUT', 'POST']);
271+
const pending = await request.get(`${API}/api/v1/meta/object_extension/${OBJECT}?state=draft&package=${PAIR}`);
272+
expect(pending.status(), await pending.text()).toBe(404);
246273
const object = await request.get(`${API}/api/v1/meta/object/${OBJECT}`);
247274
expect(object.ok(), await object.text()).toBeTruthy();
248275
const objectBody = await object.json();

‎ui/packages/app-shell/src/views/metadata-admin/CelPredicateField.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ import { useServerHoldAt, type ServerDiagnosticEntry } from './draftVerdict.js';
7979
// fields as lists (`celAuthoring.ts` stays free of any import at load).
8080
import { multiValueFieldsOf, type CelFieldDef } from './clientValidation.js';
8181

82-
const LINT_DEBOUNCE_MS = 250;
82+
import { LINT_DEBOUNCE_MS } from './celLintDebounce.js';
8383

8484
const KIND_TAG: Record<CelSuggestionKind, string> = {
8585
field: 'field',
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/** The CEL editors lint this long after the last keystroke; Studio's Save waits it out (objectstack#36511). */
4+
export const LINT_DEBOUNCE_MS = 250;

‎ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx‎

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
import '@testing-library/jest-dom/vitest';
2828
import * as React from 'react';
2929
import { afterEach, describe, expect, it, vi } from 'vitest';
30-
import { render, screen, fireEvent, cleanup, act, waitFor, within } from '@testing-library/react';
30+
import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react';
3131
import { MemoryRouter } from 'react-router-dom';
3232
import { MetadataClient } from '@object-ui/data-objectstack';
3333
import { ActionSchema } from '@objectstack/spec/ui';
@@ -63,6 +63,8 @@ function serverIssues(body: Record<string, unknown>): Array<{ path: string; mess
6363
}
6464

6565
const fetchImpl = vi.fn(async (_url: string, init?: RequestInit) => {
66+
// objectstack#36511 — the Save's own publish of the item, and a refused one's discard.
67+
if (init?.method === 'POST' || init?.method === 'DELETE') return new Response('{"success":true}', { status: 200 });
6668
if (init?.method === 'PUT') {
6769
const body = JSON.parse(String(init.body)) as Record<string, unknown>;
6870
puts.push(body);
@@ -128,7 +130,10 @@ vi.mock('@object-ui/react', async (importOriginal) => {
128130
return { ...mod, useAdapter: () => dataSource };
129131
});
130132

133+
// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`).
134+
import '@objectstack/lint';
131135
import { DataPillar } from './StudioDesignSurface';
136+
import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness';
132137
import { createEmptyDataSource } from './__tests__/emptyDataSource';
133138
import { registerBuiltinInspectors } from '../metadata-admin/inspectors';
134139
import { t, tFormat } from '../metadata-admin/i18n';
@@ -144,19 +149,12 @@ afterEach(() => {
144149

145150
const L = (key: string) => t(key, 'en');
146151

147-
/** Past the autosave's 1.5 s debounce. */
148-
async function outlastDebounce(): Promise<void> {
149-
await act(async () => {
150-
await new Promise((r) => setTimeout(r, 2300));
151-
});
152-
}
153-
154152
async function mountOnView(def: Record<string, unknown>, tabKey: string): Promise<void> {
155153
objectDef = def;
156154
render(
157-
<MemoryRouter initialEntries={['/studio/com.example.showcase/data']}>
155+
<StudioSaveHarness><MemoryRouter initialEntries={['/studio/com.example.showcase/data']}>
158156
<DataPillar packageId="com.example.showcase" />
159-
</MemoryRouter>,
157+
</MemoryRouter></StudioSaveHarness>,
160158
);
161159
// The first match is the flat tab (the passthrough menu draws a second).
162160
fireEvent.click((await screen.findAllByRole('button', { name: L(tabKey) }))[0]);
@@ -179,7 +177,7 @@ describe('Studio data page — a refused action save is shown at the action, and
179177
// Any edit: the label of the first action, which the list selects.
180178
const labelInput = (await screen.findByText(L('engine.inspector.action.label'), { selector: 'label' })).parentElement!.querySelector('input')!;
181179
fireEvent.change(labelInput, { target: { value: 'Archive now' } });
182-
await outlastDebounce();
180+
await pressStudioSave();
183181
expect(puts).toHaveLength(1);
184182

185183
// The refusal names the action, not "the server refused this draft".
@@ -198,7 +196,7 @@ describe('Studio data page — a refused action save is shown at the action, and
198196
// and clear the flat key; the next autosave is accepted, the strip goes.
199197
fireEvent.click(expose);
200198
fireEvent.click(expose);
201-
await outlastDebounce();
199+
await pressStudioSave();
202200
expect(puts).toHaveLength(2);
203201
expect(lastSentAction('showcase_task_send')).not.toHaveProperty('aiExposed');
204202
expect(serverIssues(puts[1])).toEqual([]);
@@ -211,11 +209,11 @@ describe('Studio data page — a Type switch is held until its input is filled (
211209
await mountOnView({ name: 'showcase_task', label: 'Task', fields: [{ name: 'title', label: 'Title', type: 'text' }], actions: [SEND] }, 'engine.studio.data.tab.actions');
212210

213211
await pick(L('engine.inspector.action.type'), L('engine.inspector.action.type.api'));
214-
await outlastDebounce();
212+
await pressStudioSave();
215213
expect(puts, 'an api action with no endpoint is held, not sent').toEqual([]);
216214
expect(screen.queryByTestId('studio-refusal')).toBeNull();
217215
expect(within(await screen.findByTestId('studio-held')).getByTestId('studio-held-message')).toHaveTextContent(
218-
tFormat('engine.studio.held.line', 'en', {
216+
tFormat('engine.studio.held.lineExplicit', 'en', {
219217
clause: tFormat('engine.studio.held.actionNeedsInput', 'en', {
220218
input: L('engine.inspector.action.target.api.label'),
221219
action: 'Send',
@@ -225,7 +223,7 @@ describe('Studio data page — a Type switch is held until its input is filled (
225223

226224
const endpoint = screen.getByText(`${L('engine.inspector.action.target.api.label')} *`, { selector: 'label' }).parentElement!.querySelector('input')!;
227225
fireEvent.change(endpoint, { target: { value: '/api/v1/send' } });
228-
await outlastDebounce();
226+
await pressStudioSave();
229227
expect(puts).toHaveLength(1);
230228
// The body the script had is gone with the switch, so the server accepts it.
231229
expect(lastSentAction('showcase_task_send')).not.toHaveProperty('body');

‎ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ const mockClient = {
3232
listDrafts: vi.fn(async () => []),
3333
layered: vi.fn(async () => ({ effective: servedObject, code: servedObject })),
3434
getDraft: vi.fn(async () => null),
35+
publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})),
3536
save: vi.fn(async () => ({ ok: true })),
3637
};
3738

@@ -68,7 +69,10 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => {
6869
return { ...mod, ObjectView: GridDouble };
6970
});
7071

72+
// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`).
73+
import '@objectstack/lint';
7174
import { DataPillar } from './StudioDesignSurface';
75+
import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness';
7276
import { t } from '../metadata-admin/i18n';
7377
import { readFields } from '../metadata-admin/previews/object-fields-io';
7478
import { addFieldFromFormToolbar, addFieldFromGrid } from './__tests__/dataPillarAddField';
@@ -98,9 +102,9 @@ afterEach(() => {
98102

99103
async function renderPillar(props: { readOnly?: boolean } = {}) {
100104
render(
101-
<MemoryRouter initialEntries={['/studio/com.example.showcase/data']}>
105+
<StudioSaveHarness><MemoryRouter initialEntries={['/studio/com.example.showcase/data']}>
102106
<DataPillar packageId="com.example.showcase" readOnly={props.readOnly} />
103-
</MemoryRouter>,
107+
</MemoryRouter></StudioSaveHarness>,
104108
);
105109
await waitFor(() => expect(screen.getByTestId('records-panel')).toBeInTheDocument(), { timeout: 8000 });
106110
}
@@ -115,6 +119,7 @@ const toolbarAddField = () => within(screen.getByTestId('form-toolbar')).getByRo
115119

116120
/** The fields of the latest object draft the pillar saved. */
117121
async function savedFields(): Promise<Record<string, Record<string, unknown>>> {
122+
await pressStudioSave();
118123
await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 8000 });
119124
const calls = mockClient.save.mock.calls as unknown as Array<[string, string, Record<string, unknown>]>;
120125
const body = calls[calls.length - 1][2];
@@ -205,11 +210,8 @@ describe('Data pillar — Add field asks for the label and type first (objectui#
205210
expect(within(inspector).getByText('full_name')).toBeInTheDocument();
206211
await addFieldFromFormToolbar(undefined, { label: 'ヘルススコア', apiName: 'health_score' });
207212
await waitFor(() => expect(within(screen.getByTestId('data-field-inspector')).getByText('health_score')).toBeInTheDocument());
208-
const fields = await waitFor(async () => {
209-
const f = await savedFields();
210-
expect(Object.keys(f)).toEqual(['name', 'full_name', 'health_score']);
211-
return f;
212-
}, { timeout: 8000 });
213+
const fields = await savedFields();
214+
expect(Object.keys(fields)).toEqual(['name', 'full_name', 'health_score']);
213215
expect(fields.full_name).toMatchObject({ type: 'text', label: 'Name' });
214216
expect(fields.health_score).toMatchObject({ type: 'text', label: 'ヘルススコア' });
215217
});

‎ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx‎

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
import '@testing-library/jest-dom/vitest';
2828
import * as React from 'react';
2929
import { afterEach, describe, expect, it, vi } from 'vitest';
30-
import { render, screen, fireEvent, cleanup, act, within } from '@testing-library/react';
30+
import { render, screen, fireEvent, cleanup, within } from '@testing-library/react';
3131
import userEvent from '@testing-library/user-event';
3232
import { MemoryRouter } from 'react-router-dom';
3333
import { MetadataClient } from '@object-ui/data-objectstack';
@@ -41,6 +41,8 @@ const objectDef = {
4141
const puts: unknown[] = [];
4242

4343
const fetchImpl = vi.fn(async (_url: string, init?: RequestInit) => {
44+
// objectstack#36511 — the Save's own publish of the item, and a refused one's discard.
45+
if (init?.method === 'POST' || init?.method === 'DELETE') return new Response('{"success":true}', { status: 200 });
4446
if (init?.method === 'PUT') {
4547
puts.push(JSON.parse(String(init.body)));
4648
return new Response(JSON.stringify({ success: true }), {
@@ -74,7 +76,10 @@ vi.mock('@object-ui/react', async (importOriginal) => {
7476
return { ...mod, useAdapter: () => dataSource };
7577
});
7678

79+
// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`).
80+
import '@objectstack/lint';
7781
import { DataPillar } from './StudioDesignSurface';
82+
import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness';
7883
import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField';
7984
import { createEmptyDataSource } from './__tests__/emptyDataSource';
8085
import { registerBuiltinInspectors } from '../metadata-admin/inspectors';
@@ -98,9 +103,9 @@ function controlUnder(label: string): HTMLElement {
98103
describe('Studio data page — a held Picklist reads as a sentence (objectui#11785, held since objectui#11786)', () => {
99104
it('names the field by its label and shows no developer text', async () => {
100105
render(
101-
<MemoryRouter initialEntries={['/studio/com.example.showcase/data']}>
106+
<StudioSaveHarness><MemoryRouter initialEntries={['/studio/com.example.showcase/data']}>
102107
<DataPillar packageId="com.example.showcase" />
103-
</MemoryRouter>,
108+
</MemoryRouter></StudioSaveHarness>,
104109
);
105110
fireEvent.click(await screen.findByRole('button', { name: 'Form' }));
106111
await addFieldFromFormToolbar();
@@ -112,17 +117,15 @@ describe('Studio data page — a held Picklist reads as a sentence (objectui#117
112117
await userEvent.click(controlUnder('Type'));
113118
await userEvent.click(await screen.findByRole('option', { name: /^Picklist$/ }));
114119

115-
// Past the autosave's 1.5 s debounce: the guard holds the save.
116-
await act(async () => {
117-
await new Promise((r) => setTimeout(r, 2300));
118-
});
120+
// Save pressed (objectstack#36511): the guard holds it.
121+
await pressStudioSave();
119122
expect(puts, 'the guard must hold this save').toEqual([]);
120123

121124
expect(screen.queryByTestId('studio-refusal'), 'held, not refused (objectui#11786)').toBeNull();
122125
const held = await screen.findByTestId('studio-held');
123126
const message = within(held).getByTestId('studio-held-message');
124127
expect(message).toHaveTextContent(
125-
tFormat('engine.studio.held.line', 'en', {
128+
tFormat('engine.studio.held.lineExplicit', 'en', {
126129
clause: tFormat('engine.studio.held.needsOptions', 'en', { field: label }),
127130
}),
128131
);
@@ -134,19 +137,17 @@ describe('Studio data page — a held Picklist reads as a sentence (objectui#117
134137

135138
it('"Show me" opens the named field\'s inspector after it was closed', async () => {
136139
render(
137-
<MemoryRouter initialEntries={['/studio/com.example.showcase/data']}>
140+
<StudioSaveHarness><MemoryRouter initialEntries={['/studio/com.example.showcase/data']}>
138141
<DataPillar packageId="com.example.showcase" />
139-
</MemoryRouter>,
142+
</MemoryRouter></StudioSaveHarness>,
140143
);
141144
fireEvent.click(await screen.findByRole('button', { name: 'Form' }));
142145
await addFieldFromFormToolbar();
143146
await screen.findByText('Type', { selector: 'label' }, { timeout: 4000 });
144147
const apiName = (controlUnder('API name') as HTMLInputElement).value;
145148
await userEvent.click(controlUnder('Type'));
146149
await userEvent.click(await screen.findByRole('option', { name: /^Picklist$/ }));
147-
await act(async () => {
148-
await new Promise((r) => setTimeout(r, 2300));
149-
});
150+
await pressStudioSave();
150151
const strip = await screen.findByTestId('studio-held');
151152

152153
// The rail's own header close (the field inspector inside carries another).

0 commit comments

Comments
 (0)