Skip to content

Commit 9fa05c6

Browse files
os-warrenclaude
andauthored
feat(studio): every human editor saves live; an item's unpublished AI changes can be dropped on its page (#36511, PR 3 of 3) (#36652)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8TmfMWT7ctTvEhPrKWGwWUe)_ Fixes #36511 Clause-②: no Metadata-protocol: none ## 维护者速读 - 这是「改完直接点保存」专题的最后一个 PR:权限集、对象的访问总览、字段布局也改成右上角「取消/保存」,保存即生效,不再留草稿。 - 新建对象、流程、权限集时按钮写「创建」,建好就生效;其余仍存草稿的新建照旧写「存为草稿」。 - 对象和流程上有 AI 没发布的改动时,页面提示「这一项有 AI 未发布的改动,保存会一并生效」,并可「放弃 AI 的改动」,顶上「变更」数随之减少。 - 要你做的:无产品问题待裁;本卡全部验收条目在下表,PR 1 #36597、PR 2 #36634 已合并。 ## What changes PR 3 of 3 for the card. PR 1 (#36597) moved an object's fields, validations, actions and settings to the Studio top-bar Cancel/Save; PR 2 (#36634) moved hooks, an installed app's added actions, and flows. This PR finishes the list: - **Permission sets** (`PermissionMatrixEditor`, inside Studio's Access pillar). Grants stay on the page until Save; Save writes the draft and publishes that one set at its package. A refused publish keeps the grant unsaved, says why, and takes back the draft it wrote. The full-metadata item page keeps its own buttons, as the card says. - **OWD overview** (`PackageOwdOverviewPanel`). Its own "Save" button is gone; its rows register with the top-bar Save. Each changed object is saved as a draft and published at once. The controlled-by-parent prerequisite confirm still applies. Rows the server refuses stay edited and are named in the refusal; the rest are saved. When a later row asks the prerequisite, the rows already published are read back first, so none shows as unsaved and Cancel never restores a value the server no longer holds. - **Field layout.** The form designer writes through the object's buffer that PR 1 put on Save/Cancel, so no code changed. A new suite pins it: moving a section sends nothing; Cancel restores the order; Save sends one draft PUT, then the publish. - **Creates.** Creating an object, a flow or a permission set now publishes the new item right away, and those three dialogs say "Create" / 「创建」 (`engine.studio.createLive`). Every other create dialog still writes a draft and still says "Save as draft". `CreateItemDialog.oneLabel-11787` pins which is which. - **Item 6: an item with the AI's unpublished changes** (objects and flows). The page opens on the AI's version, as before. A line says 「这一项有 AI 未发布的改动,保存会一并生效」, with a 「放弃 AI 的改动」 button. The button discards that one item's draft at its package (`DELETE /meta/:type/:name?state=draft&package=`), never the package's batch discard. It asks first if the page has unsaved edits. The page goes back to the live version, and the Changes count re-reads the ledger, so it drops by that item. A draft a person wrote draws neither the line nor the button. - **Changes count.** Live saves and the AI discard no longer report a "draft saved". That report held the count at one or more. They send the metadata refresh pulse instead, so the count reads the ledger again. ## Why The maintainer ruled on 2026-11-22 that a human edit is saved and confirmed one item at a time. Drafts plus the batch publish stay for the AI. This PR moves the last human editors off the draft autosave and adds the card's item 6. ## Acceptance | Card acceptance line | Where | Test | |---|---|---| | Add a field to an object: nothing is written before Save; after Save it is live, no publish needed | #36597 | `DataPillar.saveCancel-36511` › an edit sends nothing until Save; Save writes the draft, then publishes | | Cancel/Save sit at the top-bar right where Publish was; hidden with no edit | #36597 | `StudioDesignSurface.saveBar-36511`, `studioSaveBar.partialSave-36511` › is drawn only while a buffer is dirty | | A field, the display name in Settings and a validation, one Save: all three live | #36597 | `studioSaveBar.partialSave-36511` › sends every dirty buffer in order; `DataPillar.saveCancel-36511` | | Drag a field in the field layout: nothing written before Save; Cancel puts the canvas back | this PR | `DataPillar.layoutSaveCancel-36511` (2 tests) | | Validations, actions, settings, hooks, permissions: each edit saved is live; no Draft chip, no Changes/Publish | #36597, #36634, this PR | `DataPillar.saveCancel-36511`, `ObjectHooksPanel.saveCancel-36511`, `PermissionMatrixEditor.studioSave-36511`, `PackageOwdOverviewPanel*`, `StudioDesignSurface.saveBar-36511` › with no draft pending | | Create a flow and save; switch it on: live with no publish | #36634, this PR | `AutomationsPillar.saveCancel-36511` › the switch is live at once; a new flow is published as it is created | | Delete a field and save: a confirm names the consequence | #36597 | `DataPillar.saveCancel-36511` › removing a published field asks at Save; `DataPillar.destructiveChange-34931` | | Save something that uses an unsaved new field: refused, says which item to save first, edits kept | #36597 | `DataPillar.saveCancel-36511` › an edit that cannot be sent yet holds the whole Save and names what it needs; a refused publish keeps the edits unsaved | | AI left a draft: notice shows; 「放弃 AI 的改动」 goes back to live; Changes count drops | this PR | `DataPillar.aiDraftDiscard-36511` (4 tests), `AutomationsPillar.saveCancel-36511` › flow AI block (2 tests) | | HotCRM object: an edit is saved and live; visible in `/customizations` | #36597, #36634 | `DataPillar.baseObjectExtension-28575`, `DataPillar.pairActions-30088` (writes the `.custom` pair, then publishes there) | | A person mid-edit while the AI edits the same item: say what happens | this PR (below) | `StudioDesignSurface.draftVersionConflict-11773` | | The PR body lists every editor changed and every test retired or rewritten | each PR | lists below | **A person and the AI edit the same item at once.** Neither side's change is dropped silently: - The page keeps the person's edits in its buffer until Save. The AI's write goes to the item's draft on the server. - On Save, the draft write carries the version the page read (`If-Match`, or `If-None-Match: *` when the page read no draft). If the AI wrote in between, the server refuses with a version conflict, and the existing draft-conflict dialog opens. - The dialog offers **overwrite**. It asks once more, then sends the page's version pinned to the version the refusal served, and that version goes live. - It also offers **reload**: the page takes what the AI saved, and the next Save is built on it. - Nothing is written until the person picks one. - `StudioDesignSurface.draftVersionConflict-11773` pins the refusal and both choices (the "two editors", "reload" and "overwrite" cases). ## Editors changed in this PR - `metadata-admin/PermissionMatrixEditor.tsx`: permission sets in Studio. - `studio-design/PackageOwdOverviewPanel.tsx`: org-wide default overview. - `studio-design/StudioDesignSurface.tsx`: object / flow / permission creates; the object and flow AI notice and discard. - New `studio-design/StudioAiDraftNotice.tsx`: the flow page's notice line. - Field layout: no code change; pinned by a test. ## Tests added, rewritten or retired Added: - `DataPillar.aiDraftDiscard-36511` - `DataPillar.layoutSaveCancel-36511` - `PermissionMatrixEditor.studioSave-36511` - `PackageOwdOverviewPanel.partialSave-36511`: a refused row keeps its edit and is named while the other goes live, with the draft taken back; the controlled-by-parent prerequisite asked after an earlier row went live - `AutomationsPillar.saveCancel-36511`: the flow AI block Rewritten: - `CreateItemDialog.oneLabel-11787`. The three live creates must say Create; every other dialog must say Save as draft. Two CONTROL tests are included. - All nine `PackageOwdOverviewPanel*` suites. "owd-save" becomes the top-bar `studio-save`, and the fake clients gain `publish`/`reset`. - `layersUnsaved-11799`: its FRESH layers count goes from 0 to 1, the publish. - `sharedSelect-11865` and `refusalClearsOnRevert-26846`: a "disabled Save" now reads as "no Save drawn". - `StudioDesignSurface.changesCount-11787` now drives Create app, which still writes a draft. A permission set no longer leaves one. - `StudioDesignSurface.draftVersionConflict-11773`: it asserts the publish, and its save pins now read `If-None-Match: *` three times. - `StudioDesignSurface.accessCreateTaken-26836` and `accessGuard`: the client gains `publish`, and the create is asserted to publish. Label-only (Save as draft → Create): - `CreateItemDialog.storedName-11792` - `createObjectOwd` - `flowPresets-11861` - `flowStatusTruth-11779` - `heldDataCreate-26845` - `newFlowTrigger-11788` - `sharedSelect-11865` - `createTaken-26917` - `PermissionMatrixEditor.recordScope-26187` and `saveSurface-12725`: the Studio save harness Retired: none. ## Verification Rework at head `a4ee300c4` (contract review 7096256689). Two things changed: the OWD prerequisite path, and three comments. ``` cd ui && pnpm exec vitest run packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel Test Files 11 passed (11) Tests 49 passed (49) # the new partialSave-36511 suite against the previous PackageOwdOverviewPanel.tsx: 2 of 3 fail (the prerequisite cases); with the fix: 3 passed pnpm exec turbo run type-check --filter=@object-ui/app-shell :: 69 tasks successful pnpm check:test-source-alias :: exit 0 ``` Run at head `f9e6bada7` (main merged at `f590f3eb3`): ``` cd ui && pnpm exec vitest run packages/app-shell/src/views/studio-design packages/app-shell/src/views/metadata-admin/PermissionMatrix* scripts/__tests__/check-i18n-en-drift.test.ts packages/i18n Test Files 511 passed (511) Tests 5100 passed | 13 skipped (5113) (the ten suites given warm imports in the last commit, re-run after it: 10 files, 145 tests passed) pnpm --dir ui run check:i18n-drift :: exit 0 (every changed designer en value followed by its zh row) pnpm check:test-source-alias :: exit 0 pnpm exec turbo run type-check --filter=...[merge-base] (affected UI packages) :: 105 tasks successful pnpm --dir ui exec eslint <changed .ts/.tsx> :: 0 errors ``` Permission-set work after the merge from main: a file-by-file check confirmed it is all still there. - For the permission-only files, each file's added/removed line counts are the exact reverse of PR 2's split commit: - `PermissionMatrixEditor.tsx` +97/-7 - `studioSave-36511` +201 - `recordScope-26187` +15/-7 - `saveSurface-12725` +10/-3 - `accessPairCopy-29674` +3 - In the shared files (`StudioDesignSurface.tsx`, `en.ts`, `zh.ts`), every permission line the split took out is back. - The split commit itself is not in this branch's history. ## Acceptance notes - Item 6 is wired for **objects and flows**: the pages that read the draft's per-change provenance (`draftChanges[].by`). Hooks, actions and permission sets do not read it, so they show no AI line. Their draft still opens and is saved live as the AI's version plus the person's edit. Adding that read is a separate change if wanted. - The merge from `main` (1371428) also carries one changeset wording edit. `.changeset/36511-studio-save-cancel.md` now says permission sets moved to Save in a later change. - `DataPillar.panelHold-27629` failed once in an earlier full local run of the studio-design tests. It passes when run alone, and it passed in the final full run above. It looks like a timing flake under load, in code this PR does not touch. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (Not touched.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English (the maintainer brief is the allowed Chinese channel). - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbWaN9FFV8GYdeZHvuB --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3cf6a44 commit 9fa05c6

38 files changed

Lines changed: 1430 additions & 177 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/i18n': patch
4+
---
5+
6+
feat(studio): every human editor in Studio saves live; an item's unpublished AI changes can be dropped on its page
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
Every editor a person uses in Studio's object, automation and access pages now saves with the top bar's Save and Cancel, and a Save is live at once: an object's fields, field layout, validation rules, actions, settings and hooks, flows, and now permission sets and the Access pillar's record-sharing overview, which no longer has a Save of its own. A permission set no longer autosaves a draft 1.5 s after each edit, and the access banners say that Save makes a change live. Creating an object, a flow or a permission set makes it live at once too, so those create dialogs say Create instead of Save as draft; apps, pages, dashboards, reports and datasets are still created as drafts.
12+
13+
Changes and Publish are left for the AI assistant's drafts. When an object or a flow holds an unpublished draft the assistant wrote, its page says that saving makes those changes live too and offers to discard them: that one item's draft is dropped, the page goes back to the live version, and Changes counts one item fewer. Unsaved edits on the page go with the discard, after a confirm.

‎.changeset/36511-studio-save-cancel.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@ Studio's object page (fields, validation rules, actions, settings and field grou
1212

1313
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.
1414

15-
Other Studio editors (flows, hooks, list and form views, navigation, permissions) keep their draft autosave for now.
15+
Hooks, flows and permission sets moved to the same Save in later changes; list views and navigation keep their draft autosave for now.

‎ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.recordScope-26187.test.tsx‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@
2424
* bulk arms, in `PermissionMatrixEditor.bulkMergeKeys.test.tsx`.
2525
*/
2626

27+
// Warmed at module top so the first load of the console's lazily loaded
28+
// authoring code is paid during collection, not inside a test's clock.
29+
import '@objectstack/formula';
30+
import '@objectstack/lint';
2731
import '@testing-library/jest-dom/vitest';
2832
import { describe, it, expect, vi, afterEach } from 'vitest';
2933
import { render, screen, cleanup, fireEvent, waitFor, within } from '@testing-library/react';
@@ -53,6 +57,9 @@ function makeClient(server: FakeServer) {
5357
server.set = payload; // the reopen reads what was saved
5458
return payload;
5559
},
60+
// objectstack#36511 — the Studio's Save publishes the set it wrote.
61+
publish: async () => ({ success: true }),
62+
reset: async () => ({ success: true }),
5663
} as any;
5764
}
5865

@@ -74,6 +81,7 @@ vi.mock('@object-ui/fields', async (importOriginal) => ({
7481
}));
7582

7683
import { PermissionMatrixEditPage } from './PermissionMatrixEditor';
84+
import { StudioSaveHarness, pressStudioSave } from '../studio-design/__tests__/studioSaveHarness';
7785

7886
afterEach(cleanup);
7987

@@ -93,13 +101,15 @@ async function mount(server: FakeServer, site: Site, packageId?: string) {
93101
const utils = render(
94102
<MemoryRouter>
95103
{site === 'studio' ? (
96-
<PermissionMatrixEditPage
97-
type="permission"
98-
name="sales_perms"
99-
packageId={packageId}
100-
embedded
101-
studio={{ tab: 'objects', onTabChange: () => {} }}
102-
/>
104+
<StudioSaveHarness>
105+
<PermissionMatrixEditPage
106+
type="permission"
107+
name="sales_perms"
108+
packageId={packageId}
109+
embedded
110+
studio={{ tab: 'objects', onTabChange: () => {} }}
111+
/>
112+
</StudioSaveHarness>
103113
) : (
104114
<PermissionMatrixEditPage type="permission" name="sales_perms" packageId={packageId} />
105115
)}
@@ -220,6 +230,8 @@ describe.each<Site>(['page', 'studio'])('record scope pickers (%s renderer)', (s
220230
await mount(server, site, 'app.a');
221231

222232
await pick(readPicker('a_account'), 'Own and reports');
233+
// objectstack#36511 — in the Studio the top bar's Save sends it; the page autosaves.
234+
if (site === 'studio') await pressStudioSave();
223235
const payload = await autosaved(server);
224236
expect(payload.objects.a_account).toEqual({ allowRead: true, readScope: 'own_and_reports' });
225237
expect(payload.objects.b_order).toEqual({ allowRead: true, readScope: 'unit' });

‎ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717
* query string the server would read.
1818
*/
1919

20+
// Warmed at module top so the first load of the console's lazily loaded
21+
// authoring code is paid during collection, not inside a test's clock.
22+
import '@objectstack/lint';
2023
import '@testing-library/jest-dom/vitest';
2124
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2225
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
@@ -63,6 +66,8 @@ const client = {
6366
getDraft: async () => null,
6467
get: async () => null,
6568
save: (...args: Parameters<MetadataClient['save']>) => wire.save(...args),
69+
publish: (...args: Parameters<MetadataClient['publish']>) => wire.publish(...args),
70+
reset: (...args: Parameters<MetadataClient['reset']>) => wire.reset(...args),
6671
};
6772

6873
vi.mock('./useMetadata', async (importOriginal) => {
@@ -85,6 +90,7 @@ vi.mock('../studio-design/StudioAiCopilot', () => ({ StudioChatDock: () => null
8590
import '../../services/builtinComponents.js';
8691
import { MetadataResourceEditPage } from './ResourceEditPage';
8792
import { AccessPillar } from '../studio-design/StudioDesignSurface';
93+
import { StudioSaveHarness, pressStudioSave } from '../studio-design/__tests__/studioSaveHarness';
8894

8995
window.matchMedia = ((query: string) => ({
9096
matches: false,
@@ -111,13 +117,17 @@ afterEach(cleanup);
111117
describe('the permission matrix states `surface` only under the Studio host (objectui#12725)', () => {
112118
it('Studio’s Access pillar: the draft save sends `?surface=studio`, once', async () => {
113119
render(
114-
<MemoryRouter>
115-
<AccessPillar packageId={PKG} />
116-
</MemoryRouter>,
120+
<StudioSaveHarness>
121+
<MemoryRouter>
122+
<AccessPillar packageId={PKG} />
123+
</MemoryRouter>
124+
</StudioSaveHarness>,
117125
);
118126
await waitFor(() => expect(readBox()).toBeInTheDocument(), AUTOSAVE);
119127

120128
fireEvent.click(readBox());
129+
// objectstack#36511 — sent by the top bar's Save.
130+
await pressStudioSave();
121131
await waitFor(() => expect(puts).toHaveLength(1), AUTOSAVE);
122132
expect(puts[0]!.get('mode')).toBe('draft');
123133
expect(puts[0]!.get('package')).toBe(PKG);
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#36511 — a permission set in the Studio's Access pillar saves with
5+
* the top bar's Save and Cancel, and a Save is live at once.
6+
*
7+
* - A grant clicked sends nothing: no draft write leaves before Save is
8+
* pressed, however long the page waits (the set's 1.5 s autosave is gone
9+
* from the Studio).
10+
* - Save writes the set's draft at its package, then publishes that one set at
11+
* the same package (`POST /meta/permission/NAME/publish?package=`).
12+
* - Cancel sends nothing and puts the matrix back as the server holds it.
13+
* - A refused publish keeps the grant unsaved, says why on the page, and takes
14+
* back the draft the Save wrote.
15+
*
16+
* The REAL `AccessPillar` inside the top bar's coordinator; the writes go
17+
* through a REAL `MetadataClient` whose transport records each one, so the pins
18+
* read the URL the server would read. The environment door (metadata-admin,
19+
* no package) keeps its own Save and live write: pinned in
20+
* `PermissionMatrixEditor.saveSurface-12725.test.tsx`.
21+
*/
22+
23+
// Warmed at module top so the first load of the console's lazily loaded
24+
// authoring code is paid during collection, not inside a test's clock.
25+
import '@objectstack/lint';
26+
import '@testing-library/jest-dom/vitest';
27+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
28+
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
29+
import { MemoryRouter } from 'react-router-dom';
30+
import { MetadataClient } from '@object-ui/data-objectstack';
31+
32+
const PKG = 'com.acme.crm';
33+
34+
const SET = {
35+
name: 'sales_perms',
36+
label: 'Sales',
37+
objects: { a_account: { allowRead: false, allowCreate: true } },
38+
fields: {},
39+
};
40+
41+
interface Write {
42+
method: string;
43+
url: URL;
44+
body: Record<string, unknown> | null;
45+
}
46+
const writes: Write[] = [];
47+
const door = { refusePublish: false };
48+
49+
const json = (status: number, body: unknown) =>
50+
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
51+
52+
async function serve(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
53+
const url = new URL(String(input), 'http://console.test');
54+
const method = (init?.method ?? 'GET').toUpperCase();
55+
if (method === 'GET') return json(404, { error: { code: 'NOT_FOUND', message: 'absent' } });
56+
writes.push({ method, url, body: init?.body ? JSON.parse(String(init.body)) : null });
57+
if (method === 'POST' && door.refusePublish) {
58+
return json(422, { success: false, error: { code: 'INVALID_METADATA', message: 'The set grants on an object that is not live.' } });
59+
}
60+
return json(200, { success: true, version: 'v2', state: url.searchParams.get('mode') ?? 'active' });
61+
}
62+
63+
const wire = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch });
64+
65+
/** The reads the pillar makes, answered in memory; the writes are the real client's. */
66+
const client = {
67+
withPreviewDrafts() { return this; },
68+
list: async (type: string) => {
69+
if (type === 'permission') return [{ name: SET.name, label: SET.label }];
70+
if (type === 'object') return [{ name: 'a_account', label: 'Account' }];
71+
return [];
72+
},
73+
listDrafts: async () => [],
74+
layered: async () => ({ effective: SET, code: null, overlay: null, overlayScope: null }),
75+
getDraft: async () => null,
76+
get: async () => null,
77+
save: (...args: Parameters<MetadataClient['save']>) => wire.save(...args),
78+
publish: (...args: Parameters<MetadataClient['publish']>) => wire.publish(...args),
79+
reset: (...args: Parameters<MetadataClient['reset']>) => wire.reset(...args),
80+
};
81+
82+
vi.mock('./useMetadata', async (importOriginal) => {
83+
const actual = await importOriginal<Record<string, unknown>>();
84+
return {
85+
...actual,
86+
useMetadataClient: () => client,
87+
useMetadataTypes: () => ({
88+
loading: false,
89+
error: null,
90+
entries: [{ type: 'permission', label: 'Permission', allowEnvironmentOverlay: true }],
91+
}),
92+
};
93+
});
94+
vi.mock('sonner', () => ({
95+
toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn(), message: vi.fn(), dismiss: vi.fn() },
96+
Toaster: () => null,
97+
}));
98+
vi.mock('./AssignedUsersSection', () => ({ AssignedUsersSection: () => null }));
99+
vi.mock('./AccessExplainPanel', () => ({ AccessExplainPanel: () => null }));
100+
vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null }));
101+
vi.mock('../studio-design/StudioAiCopilot', () => ({ StudioChatDock: () => null }));
102+
103+
import { toast } from 'sonner';
104+
import { AccessPillar } from '../studio-design/StudioDesignSurface';
105+
import { StudioSaveHarness, pressStudioCancel, pressStudioSave } from '../studio-design/__tests__/studioSaveHarness';
106+
import { tFormat } from './i18n';
107+
108+
window.matchMedia = ((query: string) => ({
109+
matches: false,
110+
media: query,
111+
onchange: null,
112+
addEventListener: () => {},
113+
removeEventListener: () => {},
114+
addListener: () => {},
115+
removeListener: () => {},
116+
dispatchEvent: () => false,
117+
})) as unknown as typeof window.matchMedia;
118+
119+
const readBox = () => screen.getByRole('checkbox', { name: 'a_account Read' });
120+
const describeWrite = (w: Write) => `${w.method} ${w.url.pathname}${w.url.search}`;
121+
122+
/** Past the retired autosave's 1.5 s debounce and a round trip. */
123+
async function waitPastTheOldAutosave(): Promise<void> {
124+
await act(async () => {
125+
await new Promise((r) => setTimeout(r, 2300));
126+
});
127+
}
128+
129+
async function mount(): Promise<void> {
130+
render(
131+
<StudioSaveHarness>
132+
<MemoryRouter>
133+
<AccessPillar packageId={PKG} />
134+
</MemoryRouter>
135+
</StudioSaveHarness>,
136+
);
137+
await waitFor(() => expect(readBox()).toBeInTheDocument(), { timeout: 8000 });
138+
expect(readBox()).not.toBeChecked();
139+
}
140+
141+
beforeEach(() => {
142+
window.confirm = vi.fn(() => true) as unknown as typeof window.confirm;
143+
});
144+
afterEach(() => {
145+
cleanup();
146+
writes.length = 0;
147+
door.refusePublish = false;
148+
vi.mocked(toast.success).mockClear();
149+
vi.mocked(toast.error).mockClear();
150+
});
151+
152+
describe('Access — a permission set saves with the top bar, live at once (objectstack#36511)', () => {
153+
it('a grant sends nothing until Save; Save writes the draft, then publishes that set at its package', async () => {
154+
await mount();
155+
expect(screen.queryByTestId('studio-save')).toBeNull();
156+
fireEvent.click(readBox());
157+
expect(await screen.findByTestId('studio-save')).toBeInTheDocument();
158+
await waitPastTheOldAutosave();
159+
expect(writes.map(describeWrite), 'no write before Save').toEqual([]);
160+
161+
await pressStudioSave();
162+
await waitFor(() => expect(writes).toHaveLength(2), { timeout: 4000 });
163+
const [draft, publish] = writes;
164+
expect(draft.method).toBe('PUT');
165+
expect(draft.url.pathname).toBe('/api/v1/meta/permission/sales_perms');
166+
expect(draft.url.searchParams.get('mode')).toBe('draft');
167+
expect(draft.url.searchParams.get('package')).toBe(PKG);
168+
expect((draft.body?.objects as Record<string, { allowRead?: boolean }>).a_account.allowRead).toBe(true);
169+
expect(publish.method).toBe('POST');
170+
expect(publish.url.pathname).toBe('/api/v1/meta/permission/sales_perms/publish');
171+
expect(publish.url.searchParams.get('package')).toBe(PKG);
172+
173+
await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull());
174+
expect(readBox()).toBeChecked();
175+
expect(toast.success).toHaveBeenCalledWith(tFormat('engine.studio.save.done', 'en', { items: 'Sales' }), { id: 'studio-save' });
176+
});
177+
178+
it('Cancel sends nothing and puts the matrix back as the server holds it', async () => {
179+
await mount();
180+
fireEvent.click(readBox());
181+
expect(readBox()).toBeChecked();
182+
await pressStudioCancel();
183+
await waitFor(() => expect(readBox()).not.toBeChecked());
184+
expect(screen.queryByTestId('studio-save')).toBeNull();
185+
await waitPastTheOldAutosave();
186+
expect(writes.map(describeWrite)).toEqual([]);
187+
});
188+
189+
it('a refused publish keeps the grant unsaved, says why, and takes back the draft it wrote', async () => {
190+
door.refusePublish = true;
191+
await mount();
192+
fireEvent.click(readBox());
193+
await pressStudioSave();
194+
await waitFor(() => expect(writes.map((w) => w.method)).toEqual(['PUT', 'POST', 'DELETE']), { timeout: 4000 });
195+
const discard = writes[2];
196+
expect(discard.url.pathname).toBe('/api/v1/meta/permission/sales_perms');
197+
expect(discard.url.searchParams.get('state')).toBe('draft');
198+
expect(discard.url.searchParams.get('package')).toBe(PKG);
199+
expect(readBox(), 'the grant is still on the page').toBeChecked();
200+
expect(screen.getByTestId('studio-save'), 'and still offered to Save').toBeInTheDocument();
201+
expect(await screen.findByText(/The set grants on an object that is not live\./)).toBeInTheDocument();
202+
expect(toast.success).not.toHaveBeenCalled();
203+
});
204+
});

0 commit comments

Comments
 (0)