diff --git a/.changeset/36511-studio-save-cancel-3.md b/.changeset/36511-studio-save-cancel-3.md new file mode 100644 index 00000000000..17cb8b40dc2 --- /dev/null +++ b/.changeset/36511-studio-save-cancel-3.md @@ -0,0 +1,13 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(studio): every human editor in Studio saves live; an item's unpublished AI changes can be dropped on its page + +Clause-②: no +Metadata-protocol: none + +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. + +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. diff --git a/.changeset/36511-studio-save-cancel.md b/.changeset/36511-studio-save-cancel.md index cffcd3e6a4b..2a1f30e54e8 100644 --- a/.changeset/36511-studio-save-cancel.md +++ b/.changeset/36511-studio-save-cancel.md @@ -12,4 +12,4 @@ Studio's object page (fields, validation rules, actions, settings and field grou 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. -Other Studio editors (flows, hooks, list and form views, navigation, permissions) keep their draft autosave for now. +Hooks, flows and permission sets moved to the same Save in later changes; list views and navigation keep their draft autosave for now. diff --git a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.recordScope-26187.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.recordScope-26187.test.tsx index ac2696b0edb..87ba08acd82 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.recordScope-26187.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.recordScope-26187.test.tsx @@ -24,6 +24,10 @@ * bulk arms, in `PermissionMatrixEditor.bulkMergeKeys.test.tsx`. */ +// Warmed at module top so the first load of the console's lazily loaded +// authoring code is paid during collection, not inside a test's clock. +import '@objectstack/formula'; +import '@objectstack/lint'; import '@testing-library/jest-dom/vitest'; import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, cleanup, fireEvent, waitFor, within } from '@testing-library/react'; @@ -53,6 +57,9 @@ function makeClient(server: FakeServer) { server.set = payload; // the reopen reads what was saved return payload; }, + // objectstack#36511 — the Studio's Save publishes the set it wrote. + publish: async () => ({ success: true }), + reset: async () => ({ success: true }), } as any; } @@ -74,6 +81,7 @@ vi.mock('@object-ui/fields', async (importOriginal) => ({ })); import { PermissionMatrixEditPage } from './PermissionMatrixEditor'; +import { StudioSaveHarness, pressStudioSave } from '../studio-design/__tests__/studioSaveHarness'; afterEach(cleanup); @@ -93,13 +101,15 @@ async function mount(server: FakeServer, site: Site, packageId?: string) { const utils = render( {site === 'studio' ? ( - {} }} - /> + + {} }} + /> + ) : ( )} @@ -220,6 +230,8 @@ describe.each(['page', 'studio'])('record scope pickers (%s renderer)', (s await mount(server, site, 'app.a'); await pick(readPicker('a_account'), 'Own and reports'); + // objectstack#36511 — in the Studio the top bar's Save sends it; the page autosaves. + if (site === 'studio') await pressStudioSave(); const payload = await autosaved(server); expect(payload.objects.a_account).toEqual({ allowRead: true, readScope: 'own_and_reports' }); expect(payload.objects.b_order).toEqual({ allowRead: true, readScope: 'unit' }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx index 0655a67b8c6..dd5dcb46810 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.saveSurface-12725.test.tsx @@ -17,6 +17,9 @@ * query string the server would read. */ +// Warmed at module top so the first load of the console's lazily loaded +// authoring code is paid during collection, not inside a test's clock. +import '@objectstack/lint'; import '@testing-library/jest-dom/vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; @@ -63,6 +66,8 @@ const client = { getDraft: async () => null, get: async () => null, save: (...args: Parameters) => wire.save(...args), + publish: (...args: Parameters) => wire.publish(...args), + reset: (...args: Parameters) => wire.reset(...args), }; vi.mock('./useMetadata', async (importOriginal) => { @@ -85,6 +90,7 @@ vi.mock('../studio-design/StudioAiCopilot', () => ({ StudioChatDock: () => null import '../../services/builtinComponents.js'; import { MetadataResourceEditPage } from './ResourceEditPage'; import { AccessPillar } from '../studio-design/StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from '../studio-design/__tests__/studioSaveHarness'; window.matchMedia = ((query: string) => ({ matches: false, @@ -111,13 +117,17 @@ afterEach(cleanup); describe('the permission matrix states `surface` only under the Studio host (objectui#12725)', () => { it('Studio’s Access pillar: the draft save sends `?surface=studio`, once', async () => { render( - - - , + + + + + , ); await waitFor(() => expect(readBox()).toBeInTheDocument(), AUTOSAVE); fireEvent.click(readBox()); + // objectstack#36511 — sent by the top bar's Save. + await pressStudioSave(); await waitFor(() => expect(puts).toHaveLength(1), AUTOSAVE); expect(puts[0]!.get('mode')).toBe('draft'); expect(puts[0]!.get('package')).toBe(PKG); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.studioSave-36511.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.studioSave-36511.test.tsx new file mode 100644 index 00000000000..71c97611dd7 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.studioSave-36511.test.tsx @@ -0,0 +1,204 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36511 — a permission set in the Studio's Access pillar saves with + * the top bar's Save and Cancel, and a Save is live at once. + * + * - A grant clicked sends nothing: no draft write leaves before Save is + * pressed, however long the page waits (the set's 1.5 s autosave is gone + * from the Studio). + * - Save writes the set's draft at its package, then publishes that one set at + * the same package (`POST /meta/permission/NAME/publish?package=`). + * - Cancel sends nothing and puts the matrix back as the server holds it. + * - A refused publish keeps the grant unsaved, says why on the page, and takes + * back the draft the Save wrote. + * + * The REAL `AccessPillar` inside the top bar's coordinator; the writes go + * through a REAL `MetadataClient` whose transport records each one, so the pins + * read the URL the server would read. The environment door (metadata-admin, + * no package) keeps its own Save and live write: pinned in + * `PermissionMatrixEditor.saveSurface-12725.test.tsx`. + */ + +// Warmed at module top so the first load of the console's lazily loaded +// authoring code is paid during collection, not inside a test's clock. +import '@objectstack/lint'; +import '@testing-library/jest-dom/vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { MetadataClient } from '@object-ui/data-objectstack'; + +const PKG = 'com.acme.crm'; + +const SET = { + name: 'sales_perms', + label: 'Sales', + objects: { a_account: { allowRead: false, allowCreate: true } }, + fields: {}, +}; + +interface Write { + method: string; + url: URL; + body: Record | null; +} +const writes: Write[] = []; +const door = { refusePublish: false }; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + +async function serve(input: RequestInfo | URL, init?: RequestInit): Promise { + const url = new URL(String(input), 'http://console.test'); + const method = (init?.method ?? 'GET').toUpperCase(); + if (method === 'GET') return json(404, { error: { code: 'NOT_FOUND', message: 'absent' } }); + writes.push({ method, url, body: init?.body ? JSON.parse(String(init.body)) : null }); + if (method === 'POST' && door.refusePublish) { + return json(422, { success: false, error: { code: 'INVALID_METADATA', message: 'The set grants on an object that is not live.' } }); + } + return json(200, { success: true, version: 'v2', state: url.searchParams.get('mode') ?? 'active' }); +} + +const wire = new MetadataClient({ baseUrl: '', fetch: vi.fn(serve) as unknown as typeof fetch }); + +/** The reads the pillar makes, answered in memory; the writes are the real client's. */ +const client = { + withPreviewDrafts() { return this; }, + list: async (type: string) => { + if (type === 'permission') return [{ name: SET.name, label: SET.label }]; + if (type === 'object') return [{ name: 'a_account', label: 'Account' }]; + return []; + }, + listDrafts: async () => [], + layered: async () => ({ effective: SET, code: null, overlay: null, overlayScope: null }), + getDraft: async () => null, + get: async () => null, + save: (...args: Parameters) => wire.save(...args), + publish: (...args: Parameters) => wire.publish(...args), + reset: (...args: Parameters) => wire.reset(...args), +}; + +vi.mock('./useMetadata', async (importOriginal) => { + const actual = await importOriginal>(); + return { + ...actual, + useMetadataClient: () => client, + useMetadataTypes: () => ({ + loading: false, + error: null, + entries: [{ type: 'permission', label: 'Permission', allowEnvironmentOverlay: true }], + }), + }; +}); +vi.mock('sonner', () => ({ + toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn(), message: vi.fn(), dismiss: vi.fn() }, + Toaster: () => null, +})); +vi.mock('./AssignedUsersSection', () => ({ AssignedUsersSection: () => null })); +vi.mock('./AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); +vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); +vi.mock('../studio-design/StudioAiCopilot', () => ({ StudioChatDock: () => null })); + +import { toast } from 'sonner'; +import { AccessPillar } from '../studio-design/StudioDesignSurface'; +import { StudioSaveHarness, pressStudioCancel, pressStudioSave } from '../studio-design/__tests__/studioSaveHarness'; +import { tFormat } from './i18n'; + +window.matchMedia = ((query: string) => ({ + matches: false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, +})) as unknown as typeof window.matchMedia; + +const readBox = () => screen.getByRole('checkbox', { name: 'a_account Read' }); +const describeWrite = (w: Write) => `${w.method} ${w.url.pathname}${w.url.search}`; + +/** Past the retired autosave's 1.5 s debounce and a round trip. */ +async function waitPastTheOldAutosave(): Promise { + await act(async () => { + await new Promise((r) => setTimeout(r, 2300)); + }); +} + +async function mount(): Promise { + render( + + + + + , + ); + await waitFor(() => expect(readBox()).toBeInTheDocument(), { timeout: 8000 }); + expect(readBox()).not.toBeChecked(); +} + +beforeEach(() => { + window.confirm = vi.fn(() => true) as unknown as typeof window.confirm; +}); +afterEach(() => { + cleanup(); + writes.length = 0; + door.refusePublish = false; + vi.mocked(toast.success).mockClear(); + vi.mocked(toast.error).mockClear(); +}); + +describe('Access — a permission set saves with the top bar, live at once (objectstack#36511)', () => { + it('a grant sends nothing until Save; Save writes the draft, then publishes that set at its package', async () => { + await mount(); + expect(screen.queryByTestId('studio-save')).toBeNull(); + fireEvent.click(readBox()); + expect(await screen.findByTestId('studio-save')).toBeInTheDocument(); + await waitPastTheOldAutosave(); + expect(writes.map(describeWrite), 'no write before Save').toEqual([]); + + await pressStudioSave(); + await waitFor(() => expect(writes).toHaveLength(2), { timeout: 4000 }); + const [draft, publish] = writes; + expect(draft.method).toBe('PUT'); + expect(draft.url.pathname).toBe('/api/v1/meta/permission/sales_perms'); + expect(draft.url.searchParams.get('mode')).toBe('draft'); + expect(draft.url.searchParams.get('package')).toBe(PKG); + expect((draft.body?.objects as Record).a_account.allowRead).toBe(true); + expect(publish.method).toBe('POST'); + expect(publish.url.pathname).toBe('/api/v1/meta/permission/sales_perms/publish'); + expect(publish.url.searchParams.get('package')).toBe(PKG); + + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull()); + expect(readBox()).toBeChecked(); + expect(toast.success).toHaveBeenCalledWith(tFormat('engine.studio.save.done', 'en', { items: 'Sales' }), { id: 'studio-save' }); + }); + + it('Cancel sends nothing and puts the matrix back as the server holds it', async () => { + await mount(); + fireEvent.click(readBox()); + expect(readBox()).toBeChecked(); + await pressStudioCancel(); + await waitFor(() => expect(readBox()).not.toBeChecked()); + expect(screen.queryByTestId('studio-save')).toBeNull(); + await waitPastTheOldAutosave(); + expect(writes.map(describeWrite)).toEqual([]); + }); + + it('a refused publish keeps the grant unsaved, says why, and takes back the draft it wrote', async () => { + door.refusePublish = true; + await mount(); + fireEvent.click(readBox()); + await pressStudioSave(); + await waitFor(() => expect(writes.map((w) => w.method)).toEqual(['PUT', 'POST', 'DELETE']), { timeout: 4000 }); + const discard = writes[2]; + expect(discard.url.pathname).toBe('/api/v1/meta/permission/sales_perms'); + expect(discard.url.searchParams.get('state')).toBe('draft'); + expect(discard.url.searchParams.get('package')).toBe(PKG); + expect(readBox(), 'the grant is still on the page').toBeChecked(); + expect(screen.getByTestId('studio-save'), 'and still offered to Save').toBeInTheDocument(); + expect(await screen.findByText(/The set grants on an object that is not live\./)).toBeInTheDocument(); + expect(toast.success).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.tsx b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.tsx index 304c41d6469..55c761de980 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PermissionMatrixEditor.tsx @@ -103,6 +103,9 @@ import { } from './draftVerdict.js'; // objectui#11787 — the package door autosaves through the pillars' own autosave. import { useDraftAutoSave, type DraftSend } from '../studio-design/useDraftAutoSave.js'; +// objectstack#36511 — in the Studio the set is sent by the top bar's Save, which makes it live. +import { publishSavedItem, useStudioSaveEntry, type StudioSaveResult } from '../studio-design/studioSaveBar.js'; +import { publishFailureOf, publishRefusal } from '../studio-design/metadataError.js'; // objectui#12456 — the Studio Access pillar's presentation draws the shared item header. import { StudioItemHeader, StudioTab } from '../studio-design/StudioItemHeader.js'; import type { CustomizationMarkKind } from '../studio-design/customizationMarks.js'; @@ -575,6 +578,14 @@ export interface PermissionMatrixEditPageProps { */ onDraftSaved?: () => void; publishNonce?: number; + /** + * objectstack#36511 — in the Studio (`studio` with a `packageId`) the set is + * not autosaved: the top bar's Save writes its draft and publishes that one + * set, so it is live at once, and Cancel puts back what the server holds. + * `onSaved` fires when such a Save made the set live (no draft is left); + * a refused publish that keeps the draft reports `onDraftSaved` instead. + */ + onSaved?: () => void; /** * objectui#2505 — when provided, the per-object OWD badge becomes a link that * opens the package-level Record Sharing Baseline (OWD) overview, scrolled to @@ -615,8 +626,10 @@ export interface PermissionMatrixEditPageProps { * name, Package chip, granted / override counts, History and a more menu * holding the name / label editor) instead of the PageShell breadcrumb, * badge row and collapsible set header, and splits its sections into five - * tabs, all kept mounted. Presentation only: every write, gate and autosave - * is the routed page's. Omitted (Setup's permission page): unchanged. + * tabs, all kept mounted. With a package, it also selects the save path: + * the grants are held until the Studio top bar's Save, which writes the + * draft and publishes that one set (objectstack#36511), instead of the + * routed page's autosave. Omitted (Setup's permission page): unchanged. */ studio?: PermissionStudioChrome; /** @@ -631,11 +644,14 @@ export interface PermissionMatrixEditPageProps { customizationMark?: CustomizationMarkKind | null; } +/** objectstack#36511 — a set is saved after the objects it grants on. */ +const PERMISSION_SET_SAVE_ORDER = 4; + /* ────────────────────────────────────────────────────────────────── */ /* Component */ /* ────────────────────────────────────────────────────────────────── */ -export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, publishNonce, onOpenOwd, onDirtyChange, readOnly: readOnlyProp = false, embedded = false, studio, customizationMark = null }: PermissionMatrixEditPageProps) { +export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, onSaved, publishNonce, onOpenOwd, onDirtyChange, readOnly: readOnlyProp = false, embedded = false, studio, customizationMark = null }: PermissionMatrixEditPageProps) { // objectstack ADR-0146 D1 (#28561) — Studio's "All metadata" area mounts this // editor through the routed item page, which hands it no `readOnly`: a // read-only package's area is the host gate here, as a pillar's prop is. @@ -924,6 +940,11 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, // objectui#11787 — when the package door's last draft save landed, for the // status line that replaces its Save button ("Saved 10:42"). const [savedAt, setSavedAt] = React.useState(null); + // objectstack#36511 — the Studio's Save sends this door's edit and publishes it. + const saveByTopBar = !!packageId && !!studio; + // Whether the set held a pending draft before this editor's Save wrote one: + // a refused publish discards only the draft the Save itself wrote. + const hadDraftRef = React.useRef(false); const displayLocale = useDisplayLocale(); const [error, setError] = React.useState(null); // objectstack#29148 — the server refused to read this set's pending package @@ -1097,6 +1118,7 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, return; } const pendingDraft = pendingRead?.answer ?? null; + hadDraftRef.current = !!pendingDraft; verdictReadSeq.current += 1; setServedVerdict( editedItemDiagnostics({ @@ -1574,9 +1596,11 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, /** * `sent` is the autosave's claim on the buffer it sent (objectui#11787, the * package door only); the environment door's Save and the destructive - * dialog's force-save pass none. + * dialog's force-save pass none. Under the Studio's Save (`saveByTopBar`) + * the draft is published at once (objectstack#36511); the answer is what the + * top bar reports. */ - async function doSave(force: boolean, pending?: PermissionSetDraft, sent?: DraftSend) { + async function doSave(force: boolean, pending?: PermissionSetDraft, sent?: DraftSend): Promise { const payload = pending ?? draft; setSaving(true); setError(null); @@ -1638,8 +1662,10 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, toSave = mergePermissionSlice(base, payload, scope); } // ADR-0086 P2 (D6/D7). Package door → the set is metadata: write a DRAFT - // (stamped with `packageId`) that the package's atomic Publish promotes, - // exactly like the Data/Interfaces pillars — NOT a live record write. + // (stamped with `packageId`), exactly like the Data/Interfaces pillars — + // NOT a live record write. Under the Studio's Save the set's own publish + // follows it at once (objectstack#36511); otherwise the package's Publish + // promotes it. // Environment door (no packageId) stays live (config). // objectui#11773 — the guard pins the package door's DRAFT save; the // environment door's live write passes through it unpinned, as before. @@ -1653,8 +1679,33 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, ...(packageId && embedded ? { surface: 'studio' as const } : {}), }); // The author chose the saved version; the load replaces the matrix. - if (outcome === 'reloaded') return; - if (packageId) { + if (outcome === 'reloaded') return { kind: 'declined' }; + if (packageId && saveByTopBar) { + // objectstack#36511 — the draft just written is published alone, so + // the set is live; a refused publish drops the draft this Save wrote + // (one that was pending before stays, listed under Changes). + const live = await publishSavedItem(client, { type, name: payload.name, packageId }, hadDraftRef.current); + if (!live.ok) { + hadDraftRef.current = !live.draftDiscarded; + if (live.draftDiscarded) recordSetRead(type, payload.name, packageId, { ifNoneMatch: '*' }); + else onDraftSaved?.(); + const refusal = publishRefusal( + publishFailureOf(type, payload.name, live.error), + type, + toSave as unknown as Record, + locale, + ); + setError(refusal.message); + return { kind: 'refused', reason: refusal.message }; + } + hadDraftRef.current = false; + recordSetRead(type, payload.name, packageId, { ifNoneMatch: '*' }); + resetDraftBaseline(toDisplayDraft(toSave)); + verdictReadSeq.current += 1; + setServedVerdict(undefined); + setServedVerdictBody(toSave); + onSaved?.(); + } else if (packageId) { setSavedAt(new Date()); if (sent && !sent.unmoved()) { // objectui#11787 (the objectui#11204 rule) — the author edited while @@ -1736,10 +1787,13 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, // key the editor on the server's prose. setCloned((c) => (c && c.name === payload.name ? null : c)); setDestructive(null); + return { kind: 'saved' }; } catch (err: any) { if (err?.status === 409 && errorCodeIs(err, 'DESTRUCTIVE_CHANGE')) { const issues = err?.body?.issues ?? []; setDestructive({ issues: Array.isArray(issues) ? issues : [], pending: payload }); + // The author is asked; the dialog's own button sends the set. + return { kind: 'declined' }; } else if (!packageId && err?.status === 403 && errorCodeIs(err, 'NOT_OVERRIDABLE')) { // objectui#5987 (the card's item 3) — the environment door refused the // write because a code package ships this set: the same condition the @@ -1755,6 +1809,7 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, // own issue messages, a policy's in the author's words. setError(refusalText(err, locale) ?? err?.message ?? String(err)); } + return { kind: 'refused', reason: refusalText(err, locale) ?? err?.message ?? String(err) }; } finally { setSaving(false); } @@ -1777,11 +1832,50 @@ export function PermissionMatrixEditPage({ type, name, packageId, onDraftSaved, target: autosaveTarget, loadedFor: loading || draftRefused ? '' : autosaveTarget, dirty: isDirty, - blocked: !packageId || !writable || saving || saveHeld || destructive !== null || draftRefused !== null, + blocked: saveByTopBar || !packageId || !writable || saving || saveHeld || destructive !== null || draftRefused !== null, snapshot: draft, - save: (sent) => doSave(false, undefined, sent), + save: async (sent) => { + await doSave(false, undefined, sent); + }, }); + /* ── The Studio's Save and Cancel (objectstack#36511) ──────────── */ + // The set is one buffer of the top bar's: nothing is written before Save, + // Save writes the draft and publishes this set alone, and Cancel puts back + // the body the editor last read or saved. Held while a finding the door + // would refuse is on the page, in the words the status line shows. + const heldClause = + celErrorTotal > 0 + ? t('perm.cel.saveBlocked') + : rlsUnnamedCount > 0 + ? t('perm.rls.nameNeeded') + : rlsClauseRefusedCount > 0 + ? t('perm.rls.clauseHeld') + : null; + const cancelEdits = () => { + const snap = baselineRef.current; + if (snap == null) return; + try { + setDraft(JSON.parse(snap) as PermissionSetDraft); + } catch { + return; + } + setError(null); + setDestructive(null); + }; + useStudioSaveEntry( + saveByTopBar && writable && !loading && draftRefused === null + ? { + label: typeof headerLabel === 'string' && headerLabel ? headerLabel : name, + order: PERMISSION_SET_SAVE_ORDER, + dirty: isDirty, + held: isDirty ? heldClause : null, + save: () => doSave(false), + cancel: cancelEdits, + } + : null, + ); + /* ── Clone to customize (objectui#5987, objectui#7611) ─────────── */ /** * The server accepted a clone of THIS set (`PermissionSetCloneDialog`, which diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.saveCancel-36511.test.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.saveCancel-36511.test.tsx index 1dbbd003d82..5cad7d7f672 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.saveCancel-36511.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.saveCancel-36511.test.tsx @@ -51,6 +51,8 @@ const server = vi.hoisted(() => ({ drafts: new Map>(), /** Every write, in order: `save TYPE/NAME`, `publish TYPE/NAME`, `reset TYPE/NAME`. */ log: [] as string[], + /** The `draftChanges` a draft read serves beside the draft, by `TYPE/NAME`. */ + draftChanges: new Map(), })); const mockClient = vi.hoisted(() => { @@ -75,7 +77,8 @@ const mockClient = vi.hoisted(() => { }), getDraft: vi.fn(async (type: string, name: string) => { const draft = server.drafts.get(k(type, name)); - if (draft) return { item: JSON.parse(JSON.stringify(draft)) as Record }; + const draftChanges = server.draftChanges.get(k(type, name)); + if (draft) return { item: JSON.parse(JSON.stringify(draft)) as Record, ...(draftChanges ? { draftChanges } : {}) }; throw Object.assign(new Error(`No pending draft exists for ${type}/${name}.`), { code: 'NO_DRAFT', status: 404 }); }), save: vi.fn(async (type: string, name: string, item: unknown) => { @@ -135,6 +138,7 @@ beforeEach(() => { server.active.clear(); server.drafts.clear(); server.log.length = 0; + server.draftChanges.clear(); for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); vi.mocked(toast.success).mockClear(); vi.mocked(toast.error).mockClear(); @@ -240,7 +244,7 @@ describe('Flows — Save and Cancel in the top bar, live at once (objectstack#36 const dialog = await screen.findByRole('dialog'); fireEvent.click(within(dialog).getByTestId('create-flow-preset-manual')); fireEvent.change(dialog.querySelectorAll('input')[0], { target: { value: 'Escalate' } }); - fireEvent.click(within(dialog).getByRole('button', { name: en('engine.studio.createDraft') })); + fireEvent.click(within(dialog).getByRole('button', { name: en('engine.studio.createLive') })); await waitFor(() => expect(server.log).toEqual(['save flow/escalate', 'publish flow/escalate']), { timeout: 8000 }); expect((mockClient.save.mock.calls[0] as unknown[])[3]).toMatchObject({ mode: 'draft', packageId: PKG, ifNoneMatch: '*' }); @@ -258,3 +262,37 @@ describe('Flows — Save and Cancel in the top bar, live at once (objectstack#36 expect(screen.queryByTestId('studio-save'), 'nothing is left to Save').toBeNull(); }, 40_000); }); + +describe('Flows — the AI assistant’s unpublished draft (objectstack#36511 item 6)', () => { + function serveAiDraft(by: string): void { + server.drafts.set(`flow/${FLOW.name}`, { ...JSON.parse(JSON.stringify(FLOW)), label: 'Notify the owner (AI)' }); + server.draftChanges.set(`flow/${FLOW.name}`, [{ path: ['label'], by, actor: 'usr_1', at: new Date().toISOString() }]); + } + + it('the page says Save makes the AI’s changes live too; 放弃 AI 的改动 drops that flow’s draft, back to the live version', async () => { + serveAiDraft('copilot'); + mockClient.reset.mockImplementationOnce(async (type: string, name: string) => { + server.log.push(`reset ${type}/${name}`); + server.drafts.delete(`${type}/${name}`); + server.draftChanges.delete(`${type}/${name}`); + return {}; + }); + mount(); + expect(await screen.findByTestId('studio-ai-draft-notice', undefined, { timeout: 8000 })).toHaveTextContent( + en('engine.studio.aiDraft.notice'), + ); + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + await waitFor(() => expect(server.log).toEqual([`reset flow/${FLOW.name}`])); + expect(mockClient.reset).toHaveBeenCalledWith('flow', FLOW.name, { state: 'draft', packageId: PKG }); + await waitFor(() => expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull()); + expect(mockClient.save, 'a discard writes nothing').not.toHaveBeenCalled(); + expect(mockClient.publish).not.toHaveBeenCalled(); + }, 40_000); + + it('CONTROL: a draft a person wrote draws no notice', async () => { + serveAiDraft('studio'); + await openFlow(); + await waitFor(() => expect(mockClient.getDraft).toHaveBeenCalled()); + expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull(); + }, 40_000); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.oneLabel-11787.test.ts b/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.oneLabel-11787.test.ts index 94e8c3a4482..a2977a9c878 100644 --- a/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.oneLabel-11787.test.ts +++ b/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.oneLabel-11787.test.ts @@ -1,17 +1,20 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectui#11787 — Studio's create dialogs say one thing: *Save as draft*. + * objectui#11787 — Studio's create dialogs say what the create does, in one + * word per act. * - * Every `CreateItemDialog` in Studio writes a draft (an app, a page, a - * dashboard, a report, an object, a flow, a permission set), so the submit - * button names that one act with one string, `engine.studio.createDraft`. The - * QA pass that filed the card found *New permission set* alone saying - * *Create*. + * objectstack#36511 — the editors whose Save is live (an object, an + * automation, a permission set) create the item live: their dialogs say + * *Create* (`engine.studio.createLive`). Every other `CreateItemDialog` in + * Studio writes a draft (an app, a page, a dashboard, a report, a dataset) and + * says *Save as draft* (`engine.studio.createDraft`). The QA pass that filed + * objectui#11787 found *New permission set* alone saying *Create*, while every + * dialog wrote a draft. * * The call sites are ENUMERATED from this package's source, not listed here * (AGENTS.md #9): a dialog added later is asked the same question, and the - * control below proves the enumeration reaches the site this card changed. + * controls below prove the enumeration reaches the sites of each label. */ import { describe, it, expect } from 'vitest'; @@ -60,20 +63,33 @@ function createDialogSites(): Site[] { return sites; } -const ONE_LABEL = "t('engine.studio.createDraft', locale)"; +const DRAFT_LABEL = "t('engine.studio.createDraft', locale)"; +const LIVE_LABEL = "t('engine.studio.createLive', locale)"; -describe('Studio create dialogs carry one label (objectui#11787)', () => { - it('every CreateItemDialog submits as "Save as draft"', () => { +/** The dialogs of the live editors, by their title key (objectstack#36511). */ +const LIVE_TITLES = ['engine.studio.data.newObject', 'engine.studio.auto.newTitle', 'engine.studio.access.new']; + +const titleKeyOf = (site: Site): string | undefined => site.props.match(/title=\{t\('([^']+)'/)?.[1]; + +describe('Studio create dialogs say what the create does (objectui#11787, objectstack#36511)', () => { + it('a live editor\'s dialog says "Create"; every other one says "Save as draft"', () => { const sites = createDialogSites(); expect(sites.length).toBeGreaterThan(0); for (const site of sites) { - expect({ file: site.file, submitLabel: site.submitLabel }).toEqual({ file: site.file, submitLabel: ONE_LABEL }); + const expected = LIVE_TITLES.includes(titleKeyOf(site) ?? '') ? LIVE_LABEL : DRAFT_LABEL; + expect({ file: site.file, submitLabel: site.submitLabel }).toEqual({ file: site.file, submitLabel: expected }); } }); - it('CONTROL — the enumeration reaches the New permission set dialog, the one that said "Create"', () => { - const access = createDialogSites().filter((site) => /title=\{t\('engine\.studio\.access\.new'/.test(site.props)); - expect(access).toHaveLength(1); - expect(access[0].submitLabel).toBe(ONE_LABEL); + it('CONTROL — the enumeration reaches each live dialog once, the New permission set one included', () => { + const live = createDialogSites().filter((site) => LIVE_TITLES.includes(titleKeyOf(site) ?? '')); + expect(live.map(titleKeyOf).sort()).toEqual([...LIVE_TITLES].sort()); + for (const site of live) expect(site.submitLabel).toBe(LIVE_LABEL); + }); + + it('CONTROL — the enumeration reaches draft dialogs too', () => { + const drafts = createDialogSites().filter((site) => !LIVE_TITLES.includes(titleKeyOf(site) ?? '')); + expect(drafts.length).toBeGreaterThan(0); + for (const site of drafts) expect(site.submitLabel).toBe(DRAFT_LABEL); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.storedName-11792.test.tsx b/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.storedName-11792.test.tsx index dfcbcab3803..d03873f7455 100644 --- a/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.storedName-11792.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/CreateItemDialog.storedName-11792.test.tsx @@ -14,6 +14,9 @@ * REAL Data pillar end to end. */ +// Warmed at module top so the first load of the console's lazily loaded +// authoring code is paid during collection, not inside a test's clock. +import '@objectstack/lint'; import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -139,7 +142,7 @@ describe('Data pillar — New object previews the name it saves (objectui#11792) await waitFor(() => expect(screen.getByTestId('create-item-stored-name')).toHaveTextContent('repairs_repair_ticket'), ); - fireEvent.click(within(dialog).getByRole('button', { name: /save as draft|存为草稿/i })); + fireEvent.click(within(dialog).getByRole('button', { name: /^(create|创建)$/i })); await waitFor(() => expect(mockClient.save).toHaveBeenCalled()); expect(savedName()).toBe('repairs_repair_ticket'); }); @@ -148,7 +151,7 @@ describe('Data pillar — New object previews the name it saves (objectui#11792) packagesFixture = [{ id: 'com.test.repairs', name: 'Repairs', writable: true, namespace: null }]; const dialog = await openAndType('Repair Ticket'); expect(await screen.findByTestId('create-item-stored-name')).toHaveTextContent('repair_ticket'); - fireEvent.click(within(dialog).getByRole('button', { name: /save as draft|存为草稿/i })); + fireEvent.click(within(dialog).getByRole('button', { name: /^(create|创建)$/i })); await waitFor(() => expect(mockClient.save).toHaveBeenCalled()); expect(savedName()).toBe('repair_ticket'); }); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.aiDraftDiscard-36511.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.aiDraftDiscard-36511.test.tsx new file mode 100644 index 00000000000..f28f7599c2f --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.aiDraftDiscard-36511.test.tsx @@ -0,0 +1,200 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36511 item 6 — an object the AI assistant left an unpublished + * draft on. + * + * - The page opens on the draft (the AI's version), and the line over the + * canvas says 「这一项有 AI 未发布的改动,保存会一并生效」. + * - 「放弃 AI 的改动」 discards that one object's draft at its package + * (`DELETE /meta/object/NAME?state=draft&package=`), never the package's + * batch discard; the page goes back to the live version, the line goes, and + * the ledger behind Changes is told to count again (the metadata pulse), so + * its count drops by that item. It never reports a draft save + * (`onDraftSaved`), which would hold the count at one or more. + * - Unsaved edits on the page go with the discard, so the author is asked + * first; declined, nothing is sent. + * - CONTROL: a draft a person wrote in Studio draws neither the notice nor the + * button. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +const PACKAGE = 'com.example.showcase'; +const live = { + name: 'showcase_task', + label: 'Task', + fields: { + priority: { name: 'priority', label: 'Priority', type: 'text' }, + }, +}; +/** The AI's version: one field added. */ +const aiVersion = { + ...live, + fields: { ...live.fields, renewal_count: { name: 'renewal_count', label: 'Renewals', type: 'number' } }, +}; + +const minutesAgo = (n: number) => new Date(Date.now() - n * 60_000 - 5_000).toISOString(); + +/** What the next draft read serves: `null` for no draft. */ +let draftEnvelope: Record | null = null; + +const mockClient = { + save: vi.fn(async () => ({})), + publish: vi.fn(async () => ({})), + reset: vi.fn(async () => { + draftEnvelope = null; + return {}; + }), + list: vi.fn(async (type: string) => (type === 'object' ? [{ name: 'showcase_task', label: 'Task' }] : [])), + listDrafts: vi.fn(async () => []), + layered: vi.fn(async () => ({ effective: live, code: live, draft: draftEnvelope?.item ?? null })), + getDraft: vi.fn(async () => draftEnvelope), + get: vi.fn(async () => null), + withPreviewDrafts() { + return this; + }, +}; + +vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useMetadataClient: () => mockClient, useMetadataTypes: () => ({ entries: [] }) }; +}); + +vi.mock('./packages-io', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, fetchPackages: vi.fn(async () => []) }; +}); + +vi.mock('@object-ui/react', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useAdapter: () => dataSource }; +}); + +import '@objectstack/lint'; +import { DataPillar } from './StudioDesignSurface'; +import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; +import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; +import { t } from '../metadata-admin/i18n'; +import { subscribeMetadataRefresh } from '../../assistant/assistantBus'; + +const discardDrafts = vi.fn(async () => ({ success: true, failedCount: 0, failed: [], discarded: [] })); +const dataSource = Object.assign(createEmptyDataSource(), { + getClient: () => ({ packages: { discardDrafts } }), +}); +failOnAbsorbedFetchError(); + +const L = (key: string) => t(key, 'en-US'); + +const confirmSpy = vi.fn((_message?: string) => true); +beforeEach(() => { + draftEnvelope = null; + confirmSpy.mockReset(); + confirmSpy.mockReturnValue(true); + window.confirm = confirmSpy as unknown as typeof window.confirm; +}); +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +function serveDraft(by: string) { + draftEnvelope = { + type: 'object', + name: 'showcase_task', + item: { ...aiVersion, _draft: true }, + version: 'v1', + draftChanges: [{ path: ['fields', 'renewal_count'], by, actor: 'usr_1', at: minutesAgo(2) }], + }; +} + +function renderPillar(onDraftSaved = vi.fn()): { onDraftSaved: ReturnType } { + render( + + + + + , + ); + return { onDraftSaved }; +} + +/** The Form canvas's card of the field labelled `label`, or `null`. */ +const card = (label: string) => + screen.queryAllByText(label).map((el) => el.closest('.cursor-grab')).find((el) => el !== null) ?? null; + +async function openForm(): Promise { + fireEvent.click(await screen.findByRole('button', { name: L('engine.studio.data.tab.form') })); + await screen.findByTestId('form-toolbar'); +} + +describe('an object with the AI assistant’s unpublished changes (objectstack#36511 item 6)', () => { + it('the page shows the AI’s version and says Save makes it live too', async () => { + serveDraft('copilot'); + renderPillar(); + const line = await screen.findByTestId('studio-copilot-changes'); + expect(within(line).getByTestId('studio-ai-draft-notice')).toHaveTextContent(L('engine.studio.aiDraft.notice')); + expect(within(line).getByTestId('studio-ai-draft-discard')).toHaveTextContent(L('engine.studio.aiDraft.discard')); + await openForm(); + await waitFor(() => expect(card('Renewals')).not.toBeNull()); + }); + + it('放弃 AI 的改动 discards this object’s draft only, goes back to the live version, and the ledger is told', async () => { + serveDraft('copilot'); + const { onDraftSaved } = renderPillar(); + let pulses = 0; + const unsubscribe = subscribeMetadataRefresh(() => { + pulses += 1; + }); + await openForm(); + await waitFor(() => expect(card('Renewals')).not.toBeNull()); + + fireEvent.click(await screen.findByTestId('studio-ai-draft-discard')); + await waitFor(() => expect(mockClient.reset).toHaveBeenCalledTimes(1)); + expect(mockClient.reset).toHaveBeenCalledWith('object', 'showcase_task', { state: 'draft', packageId: PACKAGE }); + expect(discardDrafts, 'never the package’s batch discard').not.toHaveBeenCalled(); + expect(confirmSpy, 'no unsaved edit, nothing to ask').not.toHaveBeenCalled(); + + await waitFor(() => expect(card('Renewals')).toBeNull()); + expect(card('Priority')).not.toBeNull(); + await waitFor(() => expect(screen.queryByTestId('studio-copilot-changes')).toBeNull()); + expect(pulses, 'the ledger is told to count again').toBeGreaterThan(0); + expect(onDraftSaved, 'no draft was saved').not.toHaveBeenCalled(); + expect(mockClient.save, 'a discard writes nothing').not.toHaveBeenCalled(); + expect(mockClient.publish).not.toHaveBeenCalled(); + unsubscribe(); + }); + + it('with an unsaved edit on the page, the author is asked first; declined, nothing is sent', async () => { + serveDraft('mcp'); + renderPillar(); + await openForm(); + await addFieldFromFormToolbar(undefined, { label: 'Due' }); + await screen.findByTestId('studio-save'); + + confirmSpy.mockReturnValueOnce(false); + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + expect(confirmSpy).toHaveBeenCalledWith(L('engine.studio.aiDraft.discardConfirmUnsaved')); + expect(mockClient.reset).not.toHaveBeenCalled(); + expect(card('Due'), 'the edit stays').not.toBeNull(); + + fireEvent.click(screen.getByTestId('studio-ai-draft-discard')); + await waitFor(() => expect(mockClient.reset).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(card('Due')).toBeNull()); + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull()); + }); + + it('CONTROL: a draft a person wrote in Studio draws neither the notice nor the button', async () => { + serveDraft('studio'); + renderPillar(); + await openForm(); + await waitFor(() => expect(mockClient.getDraft).toHaveBeenCalled()); + await waitFor(() => expect(card('Renewals')).not.toBeNull()); + expect(screen.queryByTestId('studio-ai-draft-notice')).toBeNull(); + expect(screen.queryByTestId('studio-ai-draft-discard')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.layoutSaveCancel-36511.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.layoutSaveCancel-36511.test.tsx new file mode 100644 index 00000000000..05e0130f395 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.layoutSaveCancel-36511.test.tsx @@ -0,0 +1,167 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36511 — the field layout (Form · Layout) saves with the top + * bar's Save and Cancel, as the rest of the object page does. + * + * The layout is the object's own `fieldGroups` and `fields[].group` + * (objectstack#36425), so a layout edit lands in the object's buffer: + * - it sends nothing before Save, however long the page waits; + * - Cancel sends nothing and puts the canvas back as the server holds it; + * - Save writes the object's draft with the new layout, then publishes that one + * object at its package. + * + * The edit here is a section moved down; a dragged field commits through the + * same `onChange` (pinned by `ObjectFormDesigner.keyboardDrop-11871`), so it + * reaches the same buffer. + * + * The client is a real `MetadataClient`; only its transport and its reads are + * doubles, so each write's URL is what the server would read. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { MetadataClient } from '@object-ui/data-objectstack'; + +const PACKAGE = 'com.example.showcase'; +const objectDef = { + name: 'showcase_task', + label: 'Task', + fields: [ + { name: 'title', label: 'Title', type: 'text', group: 'main' }, + { name: 'place', label: 'Place', type: 'text', group: 'where' }, + ], + fieldGroups: [ + { key: 'main', label: 'Main' }, + { key: 'where', label: 'Where' }, + ], +}; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +interface Write { + method: string; + url: URL; + body: Record | null; +} +const writes: Write[] = []; + +const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => { + const method = init?.method ?? 'GET'; + if (method === 'GET') return json(404, null); + writes.push({ method, url: new URL(url), body: init?.body ? JSON.parse(String(init.body)) : null }); + return json(200, { success: true, version: 'v1' }); +}); + +const client = new MetadataClient({ baseUrl: 'http://test.local', fetch: fetchImpl as unknown as typeof fetch }); +const layered = vi.fn(async () => ({ effective: objectDef, code: objectDef })); +Object.assign(client, { + list: vi.fn(async () => [{ name: 'showcase_task', label: 'Task' }]), + listDrafts: vi.fn(async () => []), + layered, + getDraft: vi.fn(async () => null), +}); + +vi.mock('sonner', () => ({ + toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn(), message: vi.fn(), dismiss: vi.fn() }, + Toaster: () => null, +})); +vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useMetadataClient: () => client, useMetadataTypes: () => ({ entries: [] }) }; +}); +vi.mock('./packages-io', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, fetchPackages: vi.fn(async () => []) }; +}); +vi.mock('@object-ui/react', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useAdapter: () => dataSource }; +}); + +import { DataPillar } from './StudioDesignSurface'; +import { createEmptyDataSource } from './__tests__/emptyDataSource'; +import { StudioSaveHarness, pressStudioCancel, pressStudioSave } from './__tests__/studioSaveHarness'; +import { t } from '../metadata-admin/i18n'; +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; + +const dataSource = createEmptyDataSource(); + +afterEach(() => { + cleanup(); + writes.length = 0; +}); + +const describeWrite = (w: Write) => `${w.method} ${w.url.pathname}${w.url.search}`; + +/** The section titles on the Form canvas, top to bottom. */ +const sections = () => + screen + .getAllByLabelText(t('engine.studio.designer.group.nameLabel', 'en')) + .map((input) => (input as HTMLInputElement).value); + +async function mountOnLayout(): Promise { + render( + + + + + , + ); + fireEvent.click(await screen.findByRole('button', { name: 'Form' })); + await screen.findByTestId('form-toolbar'); + await waitFor(() => expect(sections()).toEqual(['Main', 'Where'])); +} + +/** Move the first section below the second. */ +function moveMainDown(): void { + fireEvent.click(screen.getAllByRole('button', { name: t('engine.studio.designer.groupDown', 'en') })[0]); +} + +/** Past the retired autosave's 1.5 s debounce and a round trip. */ +async function waitPastTheOldAutosave(): Promise { + await act(async () => { + await new Promise((r) => setTimeout(r, 2300)); + }); +} + +describe('Field layout — Save and Cancel in the top bar (objectstack#36511)', () => { + it('a layout edit sends nothing before Save; Cancel puts the canvas back and sends nothing', async () => { + await mountOnLayout(); + expect(screen.queryByTestId('studio-save')).toBeNull(); + moveMainDown(); + await waitFor(() => expect(sections()).toEqual(['Where', 'Main'])); + expect(await screen.findByTestId('studio-save')).toBeInTheDocument(); + await waitPastTheOldAutosave(); + expect(writes.map(describeWrite), 'no write before Save').toEqual([]); + + const loads = layered.mock.calls.length; + await pressStudioCancel(); + await waitFor(() => expect(sections()).toEqual(['Main', 'Where'])); + expect(layered.mock.calls.length, 'the object was read again from the server').toBeGreaterThan(loads); + expect(screen.queryByTestId('studio-save')).toBeNull(); + expect(writes.map(describeWrite)).toEqual([]); + }); + + it('Save writes the new layout as the object’s draft, then publishes that object at its package', async () => { + await mountOnLayout(); + moveMainDown(); + await waitFor(() => expect(sections()).toEqual(['Where', 'Main'])); + await pressStudioSave(); + await waitFor(() => expect(writes).toHaveLength(2), { timeout: 4000 }); + const [draft, publish] = writes; + expect(draft.method).toBe('PUT'); + expect(draft.url.pathname).toBe('/api/v1/meta/object/showcase_task'); + expect(draft.url.searchParams.get('mode')).toBe('draft'); + expect(draft.url.searchParams.get('package')).toBe(PACKAGE); + expect((draft.body?.fieldGroups as Array<{ key: string }>).map((g) => g.key)).toEqual(['where', 'main']); + expect(publish.method).toBe('POST'); + expect(publish.url.pathname).toBe('/api/v1/meta/object/showcase_task/publish'); + expect(publish.url.searchParams.get('package')).toBe(PACKAGE); + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull()); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.cbpPrerequisiteConfirm-27458.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.cbpPrerequisiteConfirm-27458.test.tsx index 83dfb2c4dc7..5c2d45f1c9e 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.cbpPrerequisiteConfirm-27458.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.cbpPrerequisiteConfirm-27458.test.tsx @@ -14,6 +14,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { t } from '../metadata-admin/i18n'; import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; const CBP_LABEL = t('engine.studio.settings.sharingControlledByParent', 'en-US'); const GUARD_MESSAGE = "Field 'project' is now required but has no default value"; @@ -38,6 +39,8 @@ function renderPanel(refuse: () => Error) { list: async () => [{ name: 'qnine_step', label: 'QN Step' }], listDrafts: async () => [], layered: async () => ({ effective: body, code: null }), + publish: async () => ({}), + reset: async () => ({}), getDraft: async () => null, save: async (_type: string, name: string, saved: Body, opts: { force?: boolean }) => { calls.push({ name, body: saved, force: opts?.force === true }); @@ -45,7 +48,7 @@ function renderPanel(refuse: () => Error) { return saved; }, } as unknown as React.ComponentProps['client']; - render(); + render(); return { calls }; } @@ -53,7 +56,7 @@ async function pickCbpAndSave() { await screen.findByTestId('owd-row-qnine_step'); fireEvent.keyDown(screen.getByTestId('owd-internal-qnine_step'), { key: 'ArrowDown' }); fireEvent.click(within(await screen.findByRole('listbox')).getByRole('option', { name: CBP_LABEL })); - fireEvent.click(screen.getByTestId('owd-save')); + fireEvent.click(await screen.findByTestId('studio-save')); } beforeEach(() => { diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.cbpRequiredMaster-12326.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.cbpRequiredMaster-12326.test.tsx index ca2d3034a48..c264f943ce7 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.cbpRequiredMaster-12326.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.cbpRequiredMaster-12326.test.tsx @@ -22,6 +22,7 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-li import { ObjectSchema } from '@objectstack/spec/data'; import { t, tFormat } from '../metadata-admin/i18n'; import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; const NO_MASTER = t('engine.studio.owd.byParentNoMaster', 'en-US'); const CBP_LABEL = t('engine.studio.settings.sharingControlledByParent', 'en-US'); @@ -34,6 +35,8 @@ function makeClient(objects: Record, saved: Array<{ name: string; type === 'object' ? Object.entries(objects).map(([name, body]) => ({ name, label: body.label ?? name })) : [], listDrafts: async () => [], layered: async (_type: string, name: string) => ({ effective: objects[name] ?? {}, code: null }), + publish: async () => ({}), + reset: async () => ({}), getDraft: async () => null, save: async (_type: string, name: string, body: Body) => { saved.push({ name, body }); @@ -45,7 +48,7 @@ function makeClient(objects: Record, saved: Array<{ name: string; function renderPanel(objects: Record) { const saved: Array<{ name: string; body: Body }> = []; - render(); + render(); return { saved }; } @@ -111,7 +114,7 @@ describe('PackageOwdOverviewPanel — switching a row to controlled_by_parent (o tFormat('engine.studio.owd.byParent', 'en-US', { master: 'crm_account' }), ); - fireEvent.click(screen.getByTestId('owd-save')); + fireEvent.click(await screen.findByTestId('studio-save')); await waitFor(() => expect(saved.length).toBe(1)); expect(saved[0].body.sharingModel).toBe('controlled_by_parent'); expect((saved[0].body.fields as Record).account.required).toBe(true); @@ -135,7 +138,7 @@ describe('PackageOwdOverviewPanel — switching a row to controlled_by_parent (o tFormat('engine.studio.owd.byParent', 'en-US', { master: 'crm_account' }), ); - fireEvent.click(screen.getByTestId('owd-save')); + fireEvent.click(await screen.findByTestId('studio-save')); await waitFor(() => expect(saved.length).toBe(1)); expect(saved[0].body.sharingModel).toBe('controlled_by_parent'); expect((saved[0].body.fields as Record).account.required).toBe(false); diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.layersUnsaved-11799.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.layersUnsaved-11799.test.tsx index 789e2d2d67f..73a1d1f008b 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.layersUnsaved-11799.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.layersUnsaved-11799.test.tsx @@ -34,6 +34,7 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); import { t } from '../metadata-admin/i18n'; import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; const en = (key: string) => t(key, 'en-US'); @@ -98,6 +99,15 @@ async function serve(input: RequestInfo | URL, init?: RequestInit): Promise r.type === seg[0] && (!q.get('package') || r.packageId === q.get('package'))) .map((r) => r.body), }; + } else if (seg.length === 3 && seg[2] === 'publish' && method === 'POST') { + // objectstack#36511 — the Save's second step: that one item's draft goes live. + const key = `${seg[0]}/${seg[1]}`; + const row = server.drafts.get(key); + if (row) { + server.active.set(key, row); + server.drafts.delete(key); + body = { success: true }; + } else [status, body] = [404, { error: { code: 'NO_DRAFT', message: 'absent' } }]; } else if (seg.length === 3 && seg[2] === 'layers') { const row = server.active.get(`${seg[0]}/${seg[1]}`); if (row) body = { code: null, overlay: row.body, overlayScope: 'env', effective: row.body }; @@ -160,7 +170,7 @@ afterEach(() => { }); async function openPanel() { - render(); + render(); await screen.findByTestId(`owd-row-${FRESH.name}`); await screen.findByTestId(`owd-row-${ACCOUNT.name}`); await settle(); @@ -190,13 +200,15 @@ describe('PackageOwdOverviewPanel — an unsaved object is not asked for /layers await pickOwd(`owd-internal-${FRESH.name}`, OWD_LABEL.public_read); await pickOwd(`owd-internal-${ACCOUNT.name}`, OWD_LABEL.private); - fireEvent.click(screen.getByTestId('owd-save')); + fireEvent.click(await screen.findByTestId('studio-save')); await waitFor(() => expect(draftPuts(FRESH.name)).toHaveLength(1)); await waitFor(() => expect(draftPuts(ACCOUNT.name)).toHaveLength(1)); await settle(); - // The save itself asked nothing of the unsaved object's layer; the reload after it neither. - expect(layersAsked(FRESH.name) - before.fresh).toBe(0); + // The save itself asked nothing of the unsaved object's layer. objectstack#36511 + // — the Save made it live, so the reload after it reads its layer once, as + // it reads every published object's. + expect(layersAsked(FRESH.name) - before.fresh).toBe(1); // The edit landed on the draft as-is: every draft key kept, the model replaced. expect(draftPuts(FRESH.name)[0]).toEqual({ ...FRESH, sharingModel: 'public_read' }); // CONTROL: the published object is read as before: once for the save, and diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.partialSave-36511.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.partialSave-36511.test.tsx new file mode 100644 index 00000000000..570c2848588 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.partialSave-36511.test.tsx @@ -0,0 +1,181 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36511 — the OWD overview's rows on the top bar's Save, when not + * every row goes through. + * + * The Save walks the changed rows one after another: each row's draft, then + * that object's own publish. Two rows are changed in each case, Alpha before + * Beta (the table's order), against a server double that keeps a published + * body and a draft per object. + * + * - Beta's publish is refused: Alpha is live and no longer "Unsaved"; Beta + * keeps its edit, the refusal names Beta and the server's reason, and the + * draft this Save wrote for Beta is taken back. + * - Beta asks the controlled-by-parent prerequisite after Alpha went live: the + * page reads Alpha back before it asks, so Alpha is not shown as unsaved, + * and the top bar's Cancel never puts Alpha back to a value the server no + * longer holds. Confirming saves Beta alone. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { t } from '../metadata-admin/i18n'; +import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel'; +import { StudioSaveHarness, pressStudioCancel, pressStudioSave } from './__tests__/studioSaveHarness'; + +const PACKAGE = 'com.qa.owd'; +const L = (key: string) => t(key, 'en-US'); +const PUBLIC_READ = L('engine.studio.settings.sharingPublicRead'); +const PRIVATE = L('engine.studio.settings.sharingPrivate'); +const CBP = L('engine.studio.settings.sharingControlledByParent'); +const PUBLISH_REFUSAL = 'Beta is referenced by a sharing rule that is not saved yet'; + +type Body = Record; + +function destructive() { + const message = "Field 'project' is now required but has no default value"; + return Object.assign(new Error(message), { + status: 409, + code: 'DESTRUCTIVE_CHANGE', + issues: [{ kind: 'required_added', path: 'fields.project', message }], + }); +} + +interface Server { + published: Record; + drafts: Record; + writes: Array<{ op: 'save' | 'publish' | 'reset'; name: string; force?: boolean; state?: string; packageId?: string }>; +} + +/** + * A server double. `refusePublish` names an object whose publish is refused; + * `prereq` names one whose unforced save answers 409 DESTRUCTIVE_CHANGE. + */ +function renderPanel({ refusePublish, prereq }: { refusePublish?: string; prereq?: string } = {}): Server { + const server: Server = { + published: { + a_alpha: { name: 'a_alpha', label: 'Alpha', sharingModel: 'private', fields: { name: { type: 'text' } } }, + b_beta: { + name: 'b_beta', + label: 'Beta', + sharingModel: 'private', + fields: { name: { type: 'text' }, project: { type: 'master_detail', reference: 'a_alpha' } }, + }, + }, + drafts: {}, + writes: [], + }; + const client = { + list: async () => Object.values(server.published).map((b) => ({ name: b.name, label: b.label })), + listDrafts: async () => Object.keys(server.drafts).map((name) => ({ name })), + layered: async (_t: string, name: string) => ({ effective: server.published[name] ?? {}, code: null }), + getDraft: async (_t: string, name: string) => + server.drafts[name] ? { type: 'object', name, item: server.drafts[name] } : null, + save: async (_t: string, name: string, body: Body, opts: { force?: boolean }) => { + server.writes.push({ op: 'save', name, force: opts?.force === true }); + if (name === prereq && !opts?.force) throw destructive(); + server.drafts[name] = JSON.parse(JSON.stringify(body)) as Body; + return body; + }, + publish: async (_t: string, name: string, opts: { packageId?: string }) => { + server.writes.push({ op: 'publish', name, packageId: opts?.packageId }); + if (name === refusePublish) throw Object.assign(new Error(PUBLISH_REFUSAL), { status: 422 }); + server.published[name] = server.drafts[name]; + delete server.drafts[name]; + return {}; + }, + reset: async (_t: string, name: string, opts: { state?: string; packageId?: string }) => { + server.writes.push({ op: 'reset', name, state: opts?.state, packageId: opts?.packageId }); + delete server.drafts[name]; + return {}; + }, + } as unknown as React.ComponentProps['client']; + render( + + + , + ); + return server; +} + +async function pick(name: string, option: string): Promise { + await screen.findByTestId(`owd-row-${name}`); + fireEvent.keyDown(screen.getByTestId(`owd-internal-${name}`), { key: 'ArrowDown' }); + fireEvent.click(within(await screen.findByRole('listbox')).getByRole('option', { name: option })); + await screen.findByTestId(`owd-dirty-${name}`); +} + +beforeEach(() => { + Element.prototype.scrollIntoView = vi.fn(); +}); +afterEach(cleanup); + +describe('the OWD overview when not every row goes through (objectstack#36511)', () => { + it('a refused publish keeps that row unsaved and names it; the other row is live; the draft it wrote is taken back', async () => { + const server = renderPanel({ refusePublish: 'b_beta' }); + await pick('a_alpha', PUBLIC_READ); + await pick('b_beta', PUBLIC_READ); + await pressStudioSave(); + + // Alpha: live, and read back as saved. + await waitFor(() => expect(server.published.a_alpha.sharingModel).toBe('public_read')); + await waitFor(() => expect(screen.queryByTestId('owd-dirty-a_alpha')).toBeNull()); + expect(screen.getByTestId('owd-internal-a_alpha')).toHaveTextContent(PUBLIC_READ); + + // Beta: not live, its edit still on the page, named with the server's reason. + expect(server.published.b_beta.sharingModel).toBe('private'); + expect(screen.getByTestId('owd-dirty-b_beta')).toBeInTheDocument(); + expect(screen.getByTestId('owd-internal-b_beta')).toHaveTextContent(PUBLIC_READ); + expect(await screen.findByText(new RegExp(`Beta: .*${PUBLISH_REFUSAL}`))).toBeInTheDocument(); + + // The draft this Save wrote for Beta is taken back, at the package. + expect(server.writes.filter((w) => w.op === 'reset')).toEqual([ + { op: 'reset', name: 'b_beta', state: 'draft', packageId: PACKAGE }, + ]); + expect(server.drafts.b_beta).toBeUndefined(); + expect(screen.getByTestId('studio-save')).toBeInTheDocument(); + }); + + it('the prerequisite asked after an earlier row went live: that row reads back as saved, and Cancel keeps what the server holds', async () => { + const server = renderPanel({ prereq: 'b_beta' }); + await pick('a_alpha', PUBLIC_READ); + await pick('b_beta', CBP); + await pressStudioSave(); + + await screen.findByTestId('owd-cbp-prereq'); + expect(server.published.a_alpha.sharingModel).toBe('public_read'); + await waitFor(() => expect(screen.queryByTestId('owd-dirty-a_alpha')).toBeNull()); + expect(screen.getByTestId('owd-dirty-b_beta')).toBeInTheDocument(); + + // Closing the confirm, then the top bar's Cancel: Alpha shows the live value. + fireEvent.click(within(screen.getByTestId('owd-cbp-prereq')).getByRole('button', { name: L('engine.cancel') })); + await waitFor(() => expect(screen.queryByTestId('owd-cbp-prereq')).toBeNull()); + const writesBeforeCancel = server.writes.length; + await pressStudioCancel(); + await waitFor(() => expect(screen.queryByTestId('owd-dirty-b_beta')).toBeNull()); + expect(screen.getByTestId('owd-internal-a_alpha')).toHaveTextContent(PUBLIC_READ); + expect(screen.getByTestId('owd-internal-b_beta')).toHaveTextContent(PRIVATE); + expect(server.writes.length, 'Cancel sends nothing').toBe(writesBeforeCancel); + }); + + it('confirming the prerequisite saves the remaining row alone, forced, and publishes it', async () => { + const server = renderPanel({ prereq: 'b_beta' }); + await pick('a_alpha', PUBLIC_READ); + await pick('b_beta', CBP); + await pressStudioSave(); + await screen.findByTestId('owd-cbp-prereq'); + await waitFor(() => expect(screen.queryByTestId('owd-dirty-a_alpha')).toBeNull()); + + const before = server.writes.length; + fireEvent.click(screen.getByTestId('owd-cbp-prereq-confirm')); + await waitFor(() => expect(server.published.b_beta.sharingModel).toBe('controlled_by_parent')); + expect(server.writes.slice(before)).toEqual([ + { op: 'save', name: 'b_beta', force: true }, + { op: 'publish', name: 'b_beta', packageId: PACKAGE }, + ]); + await waitFor(() => expect(screen.queryByTestId('owd-dirty-b_beta')).toBeNull()); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.picklistServedOptions-11692.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.picklistServedOptions-11692.test.tsx index aa8d0f1ccb8..d892520377c 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.picklistServedOptions-11692.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.picklistServedOptions-11692.test.tsx @@ -29,6 +29,7 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); import { toast } from 'sonner'; import { t } from '../metadata-admin/i18n'; import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; /** Pick a dial's option by its label, through the trigger, as a user does; the dials are the shared Select (objectui#11865). */ async function pickOwd(testId: string, label: string): Promise { @@ -106,6 +107,10 @@ const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => { { status, headers: { 'content-type': 'application/json' } }, ); } + // objectstack#36511 — the Save's second step, that one object's publish. + if (init?.method === 'POST' && /\/publish(\?|$)/.test(String(url))) { + return new Response(JSON.stringify({ success: true }), { status: 200, headers: { 'content-type': 'application/json' } }); + } return new Response('null', { status: 404, headers: { 'content-type': 'application/json' } }); }); @@ -129,10 +134,10 @@ afterEach(() => { }); async function changeSharingAndSave(client: MetadataClient): Promise { - render(); + render(); await screen.findByTestId('owd-row-acme_account'); await pickOwd('owd-internal-acme_account', t('engine.studio.settings.sharingPublicRead', 'en-US')); - fireEvent.click(screen.getByTestId('owd-save')); + fireEvent.click(await screen.findByTestId('studio-save')); await waitFor(() => expect(puts).toHaveLength(1)); } diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.readDecorationStrip.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.readDecorationStrip.test.tsx index 32609442bc0..c66262999d0 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.readDecorationStrip.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.readDecorationStrip.test.tsx @@ -41,6 +41,7 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); import { t } from '../metadata-admin/i18n'; import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; /** Pick a dial's option by its label, through the trigger, as a user does; the dials are the shared Select (objectui#11865). */ async function pickOwd(testId: string, label: string): Promise { @@ -82,6 +83,8 @@ function makeClient() { code: null, }), // The decorated envelope, on BOTH the load read and the save-time re-read. + publish: async () => ({}), + reset: async () => ({}), getDraft: async () => ({ type: 'object', name: 'crm_contact', item: SERVED_DRAFT }), save: async (_t: string, name: string, body: Record) => { saved.push({ name, body }); @@ -102,16 +105,16 @@ afterEach(() => { describe('PackageOwdOverviewPanel — read decorations never reach the save (objectui#8181)', () => { it('writes the authored body without `_diagnostics` / `_draft`', async () => { render( - , + />, ); await screen.findByTestId('owd-row-crm_contact'); await pickOwd('owd-internal-crm_contact', t('engine.studio.settings.sharingPublicRead', 'en-US')); - fireEvent.click(screen.getByTestId('owd-save')); + fireEvent.click(await screen.findByTestId('studio-save')); // CONTROL: the save really happened, and really carried the edit. Every // absence assertion below is meaningless without this. diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.refusalClearsOnRevert-26846.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.refusalClearsOnRevert-26846.test.tsx index 8adc007aada..189159a6969 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.refusalClearsOnRevert-26846.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.refusalClearsOnRevert-26846.test.tsx @@ -12,6 +12,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { t } from '../metadata-admin/i18n'; import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); @@ -26,6 +27,8 @@ function makeClient() { list: async (type: string) => (type === 'object' ? [{ name: 'crm_memo', label: 'Memo' }] : []), listDrafts: async () => [], layered: async () => ({ effective: body, code: null }), + publish: async () => ({}), + reset: async () => ({}), getDraft: async () => null, save: vi.fn(async () => { throw Object.assign(new Error(REFUSAL), { status: 422, code: 'VALIDATION_ERROR' }); @@ -39,10 +42,10 @@ async function pick(label: string) { } async function refuseOnce() { - render(); + render(); await screen.findByTestId('owd-row-crm_memo'); await pick(CBP); - fireEvent.click(screen.getByTestId('owd-save')); + fireEvent.click(await screen.findByTestId('studio-save')); await screen.findByText(new RegExp(REFUSAL)); } @@ -55,7 +58,8 @@ describe('PackageOwdOverviewPanel — the refusal banner and the revert (objects it('reverting the refused edit to the loaded value clears the banner', async () => { await refuseOnce(); await pick(PRIVATE); - expect(screen.getByTestId('owd-save')).toHaveTextContent(t('engine.studio.owd.saveNone', 'en-US')); + // objectstack#36511 — nothing is left to save, so the top bar draws no Save. + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull()); await waitFor(() => expect(screen.queryByText(new RegExp(REFUSAL))).toBeNull()); }); diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.servedDraftTakenAsIs-10765.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.servedDraftTakenAsIs-10765.test.tsx index 5ad2718ddbc..0cf5d5ac5d5 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.servedDraftTakenAsIs-10765.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.servedDraftTakenAsIs-10765.test.tsx @@ -27,6 +27,7 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); import { t } from '../metadata-admin/i18n'; import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; /** Pick a dial's option by its label, through the trigger, as a user does; the dials are the shared Select (objectui#11865). */ async function pickOwd(testId: string, label: string): Promise { @@ -60,6 +61,8 @@ function makeClient() { effective: name === PUBLISHED.name ? PUBLISHED : {}, code: null, }), + publish: async () => ({}), + reset: async () => ({}), getDraft: async (_t: string, name: string) => name === PUBLISHED.name ? { type: 'object', name, item: SERVED_DRAFT } : null, save: async (_t: string, name: string, body: Record, opts?: Record) => { @@ -80,7 +83,7 @@ afterEach(() => { describe('PackageOwdOverviewPanel — the pending draft is read and re-saved as-is (objectui#10765)', () => { it('LIST LOAD: a model the draft cleared reads as unset, not as the published value', async () => { - render(); + render(); await screen.findByTestId('owd-row-crm_contact'); const internal = screen.getByTestId('owd-internal-crm_contact'); @@ -91,11 +94,11 @@ describe('PackageOwdOverviewPanel — the pending draft is read and re-saved as- }); it('SAVE: an edit lands on the draft alone — the published model and description the draft deleted do not come back', async () => { - render(); + render(); await screen.findByTestId('owd-row-crm_contact'); await pickOwd('owd-internal-crm_contact', t('engine.studio.settings.sharingPublicRead', 'en-US')); - fireEvent.click(screen.getByTestId('owd-save')); + fireEvent.click(await screen.findByTestId('studio-save')); await waitFor(() => expect(saved).toHaveLength(1)); const { name, body, opts } = saved[0]!; diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.sharedSelect-11865.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.sharedSelect-11865.test.tsx index 6eb8cecfca2..17a029ea3f4 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.sharedSelect-11865.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.sharedSelect-11865.test.tsx @@ -39,6 +39,7 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); import { t } from '../metadata-admin/i18n'; import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; const en = (key: string) => t(key, 'en-US'); @@ -51,6 +52,8 @@ function makeServer(objects: Record) { list: async () => Object.entries(objects).map(([name, body]) => ({ name, label: body.label ?? name })), listDrafts: async () => [], layered: async (_type: string, name: string) => ({ effective: objects[name] ?? {}, code: null }), + publish: async () => ({}), + reset: async () => ({}), getDraft: async () => null, save: async (_type: string, name: string, body: Body, opts?: Body) => { saved.push({ name, body, opts }); @@ -72,7 +75,7 @@ const DIALS = ['owd-internal-p_int', 'owd-internal-p_ext'] as const; async function renderPanel(objects: Record = OBJECTS(), readOnly?: boolean) { const server = makeServer(objects); const utils = render( - , + , ); await screen.findByTestId('owd-row-p_int'); return { ...utils, saved: server.saved }; @@ -92,7 +95,8 @@ async function pick(testId: string, label: string): Promise { fireEvent.click(option); } -const saveButton = () => screen.getByTestId('owd-save') as HTMLButtonElement; +/** The top bar's Save (objectstack#36511), drawn only while a dial holds an unsaved edit. */ +const saveButton = () => screen.queryByTestId('studio-save') as HTMLButtonElement | null; beforeEach(() => { // jsdom has no layout — stub the scroll used by the deep-link highlight. @@ -158,12 +162,12 @@ describe('every option saves what the native dial saved', () => { const { saved } = await renderPanel(); await pick(testId, label); if (json === null) { - expect(saveButton()).toBeDisabled(); + expect(saveButton()).toBeNull(); expect(saved).toEqual([]); return; } expect(saveButton()).toBeEnabled(); - fireEvent.click(saveButton()); + fireEvent.click(saveButton()!); await waitFor(() => expect(saved).toHaveLength(1)); expect(JSON.stringify(saved)).toBe(json); }, @@ -196,7 +200,7 @@ describe('a stored value no option carries is what the trigger shows', () => { expect(listed[0]).toBe('full'); expect(listed.slice(1)).toEqual(WRITES.filter(([d]) => d === 'owd-internal-p_int').map(([, label]) => label)); fireEvent.click(screen.getAllByRole('option')[0]); - expect(saveButton()).toBeDisabled(); + expect(saveButton()).toBeNull(); expect(saved).toEqual([]); }); }); @@ -210,7 +214,7 @@ describe('the keyboard alone picks', () => { within(listbox).getByRole('option', { name: en('engine.studio.settings.sharingPrivate') }), { key: 'Enter' }, ); - fireEvent.click(saveButton()); + fireEvent.click(saveButton()!); await waitFor(() => expect(saved).toHaveLength(1)); expect(JSON.stringify(saved)).toBe(SAVED('p_int', { name: 'p_int', label: 'Int', sharingModel: 'private' })); }); diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.test.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.test.tsx index 2cdf301d05d..a3f37a88c42 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.test.tsx @@ -22,6 +22,7 @@ vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); import { MetadataCtx, type MetadataContextValue } from '@object-ui/react'; import { t, tFormat } from '../metadata-admin/i18n'; import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; const en = (key: string) => t(key, 'en-US'); @@ -56,6 +57,8 @@ function makeClient(server: Server) { }, listDrafts: async () => server.draftOnly.map((name) => ({ name })), layered: async (_type: string, name: string) => ({ effective: server.objects[name] ?? {}, code: null }), + publish: async () => ({}), + reset: async () => ({}), getDraft: async () => null, save: async (_type: string, name: string, body: Record, opts?: Record) => { server.saved.push({ name, body, opts }); @@ -84,12 +87,12 @@ function freshServer(): Server { function renderPanel(server: Server, extra: Partial> = {}) { return render( - , + />, ); } @@ -124,15 +127,15 @@ describe('PackageOwdOverviewPanel — edit → per-object draft', () => { renderPanel(server); await screen.findByTestId('owd-row-crm_contact'); - // No changes → Save disabled. - expect((screen.getByTestId('owd-save') as HTMLButtonElement).disabled).toBe(true); + // No changes → the top bar draws no Save (objectstack#36511). + expect(screen.queryByTestId('studio-save')).toBeNull(); // Widen crm_contact private → public_read. await pickOwd('owd-internal-crm_contact', OWD_LABEL.public_read); expect(screen.getByTestId('owd-dirty-crm_contact')).toBeTruthy(); - expect((screen.getByTestId('owd-save') as HTMLButtonElement).disabled).toBe(false); + expect(screen.getByTestId('studio-save')).toBeEnabled(); - fireEvent.click(screen.getByTestId('owd-save')); + fireEvent.click(await screen.findByTestId('studio-save')); await waitFor(() => expect(server.saved.length).toBe(1)); expect(server.saved[0].name).toBe('crm_contact'); expect(server.saved[0].body.sharingModel).toBe('public_read'); @@ -146,7 +149,7 @@ describe('PackageOwdOverviewPanel — edit → per-object draft', () => { renderPanel(server); await screen.findByTestId('owd-row-crm_account'); await pickOwd('owd-internal-crm_account', OWD_LABEL['']); - fireEvent.click(screen.getByTestId('owd-save')); + fireEvent.click(await screen.findByTestId('studio-save')); await waitFor(() => expect(server.saved.length).toBe(1)); expect('sharingModel' in server.saved[0].body).toBe(false); }); @@ -198,7 +201,7 @@ describe('PackageOwdOverviewPanel — the master is named by its label (objectst it("a master outside this package reads as the served object's label", async () => { render( - + , ); expect(await screen.findByTestId('owd-master-crm_case')).toHaveTextContent(byParent('Customer Account')); @@ -214,7 +217,7 @@ describe('PackageOwdOverviewPanel — read-only', () => { it('renders badges only, with no editing affordances', async () => { renderPanel(freshServer(), { readOnly: true }); await screen.findByTestId('owd-row-crm_account'); - expect(screen.queryByTestId('owd-save')).toBeNull(); + expect(screen.queryByTestId('studio-save')).toBeNull(); expect(screen.queryByTestId('owd-internal-crm_account')).toBeNull(); // The value is still shown as text. const row = within(screen.getByTestId('owd-row-crm_account')); @@ -261,7 +264,7 @@ describe('PackageOwdOverviewPanel — onDirtyChange contract (objectui#2600)', ( await pickOwd('owd-internal-crm_contact', OWD_LABEL.public_read); expect(onDirtyChange).toHaveBeenLastCalledWith(true); - fireEvent.click(screen.getByTestId('owd-save')); + fireEvent.click(await screen.findByTestId('studio-save')); await waitFor(() => expect(server.saved.length).toBe(1)); await waitFor(() => expect(onDirtyChange).toHaveBeenLastCalledWith(false)); }); diff --git a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx index 684612dff9b..b68bef3131d 100644 --- a/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/PackageOwdOverviewPanel.tsx @@ -16,9 +16,11 @@ * the per-principal permission-set matrix (which was considered and rejected). * It has no principal dimension. * - * • Save = per-object metadata DRAFTs under the package scope — byte-for-byte - * what the per-object Settings tab writes, just N objects in one action. - * Publish then flows through the unchanged package security-domain gate. + * • Save = the Studio top bar's one Save (objectstack#36511): each changed + * object's draft under the package scope — byte-for-byte what the + * per-object Settings tab writes — then that object's own publish, so the + * change is live at once. Cancel puts every dial back. A refused object + * keeps its edit on the page, and the reason is shown. * • `controlled_by_parent` rows show the master link (read-only) under the * row's dial. * • There is no external column: `externalSharingModel` is retired by @@ -28,7 +30,7 @@ */ import * as React from 'react'; -import { Save, Loader2, Lock, ArrowUpRight } from 'lucide-react'; +import { Lock, ArrowUpRight } from 'lucide-react'; import type { MetadataClient, MetadataLayered } from '@object-ui/data-objectstack'; // The ONE draft-envelope reader (objectui#8181): unwrap AND strip the // framework's read decorations in one place. This file used to carry its own @@ -61,6 +63,7 @@ import { readFields } from '../metadata-admin/previews/object-fields-io.js'; import { t, tFormat, type SupportedLocale } from '../metadata-admin/i18n.js'; import { cbpMasterDetailDefaultsRequired, deriveMasterObject, requireCbpMasterDetails } from './owd-sharing.js'; import { toast } from 'sonner'; +import { STUDIO_SAVE_TOAST_ID, publishSavedItem, useStudioSaveEntry, type StudioSaveResult } from './studioSaveBar.js'; /** @@ -221,8 +224,6 @@ export interface PackageOwdOverviewPanelProps { packageId: string; /** Bumped on package publish → re-read the freshly published baseline. */ publishNonce?: number; - /** Notify the surface so its pending-changes counter refreshes after a save. */ - onDraftSaved?: () => void; /** * Courtesy gate: read-only packages render badges only (the framework's * ADR-0124 D1 — server enforces, client is courtesy). @@ -242,7 +243,6 @@ export function PackageOwdOverviewPanel({ client, packageId, publishNonce = 0, - onDraftSaved, readOnly = false, locale, highlightObject, @@ -394,17 +394,31 @@ export function PackageOwdOverviewPanel({ if (!isDirty) setSaveError(null); }, [isDirty]); - const doSave = React.useCallback(async (force = false) => { + // objectstack#36511 — the top bar's Save: each changed row's draft, then that + // object's own publish, one row after another. A row refused keeps its edit + // on the page and is named in the refusal; the rows saved are live. + const doSave = React.useCallback(async (force = false): Promise => { const changed = rowState.filter((s) => s.dirty); - if (changed.length === 0) return; + if (changed.length === 0) return { kind: 'declined' }; setSaving(true); setSaveError(null); setPrereq(null); + const refused: Array<{ name: string; label: string; reason: string; edit: OwdEdit }> = []; + let saved = 0; + const savedNames = new Set(); + // Read the rows back from the server, then put back the edits of the rows + // this pass did not save. + const reloadKeeping = async (unsaved: ReadonlyArray<{ row: { name: string }; edit: OwdEdit }>) => { + await load(); + if (unsaved.length > 0) { + setEdits((prev) => ({ ...prev, ...Object.fromEntries(unsaved.map((u) => [u.row.name, u.edit])) })); + } + }; try { // Each changed row lands as that object's package-scoped DRAFT: read the - // fresh body (below), apply just `sharingModel` (unset → drop the key), and - // save. Identical to the per-object Settings write, N times — publish - // then goes through the same package security-domain gate unchanged. + // fresh body (below), apply just `sharingModel` (unset → drop the key), + // save, and publish that one object. Identical to the per-object + // Settings write, N times. for (const s of changed) { // objectui#11799 — the row's saved state from the load decides whether // the baseline is asked before the draft is in hand. @@ -447,9 +461,15 @@ export function PackageOwdOverviewPanel({ // objectstack#27458 — making the relationship required is a change // the server's destructive-change guard asks to confirm (409). Name // the prerequisite and offer it, instead of a dead-end banner. The - // guard stands: nothing is forced until the author confirms. + // guard stands: nothing is forced until the author confirms, and the + // Save stops here with every edit still on the page. if (!force && relations.length > 0 && (e as { status?: number })?.status === 409 && errorCodeIs(e, 'DESTRUCTIVE_CHANGE')) { const issues = (e as { issues?: unknown }).issues; + // Rows this pass already published are live: the page reads them + // back before it asks, so it never shows a live row as unsaved, and + // Cancel never puts back a value the server no longer holds. Every + // row not yet saved keeps its edit for the confirm's second pass. + if (saved > 0) await reloadKeeping(changed.filter((c) => !savedNames.has(c.row.name))); setPrereq({ object: s.row.label, relations, @@ -457,22 +477,66 @@ export function PackageOwdOverviewPanel({ .map((i) => String((i as { message?: unknown })?.message ?? '')) .filter(Boolean), }); - return; + return { kind: 'declined' }; } - throw e; + refused.push({ name: s.row.name, label: s.row.label, reason: formatMetadataError(e), edit: s.edit }); + continue; } + // A draft that was pending before this save (a copilot's) is published + // with it; a refused publish takes back only the draft this save wrote. + const live = await publishSavedItem(client, { type: 'object', name: s.row.name, packageId }, s.row.hasDraft); + if (!live.ok) { + refused.push({ name: s.row.name, label: s.row.label, reason: formatMetadataError(live.error), edit: s.edit }); + continue; + } + saved += 1; + savedNames.add(s.row.name); } - toast.success(tFormat('engine.studio.owd.saved', locale, { count: changed.length })); - onDraftSaved?.(); - await load(); - } catch (e) { - setSaveError(formatMetadataError(e)); + // A Save leaves no draft: the publish told the ledger behind Changes. + // The reload puts every dial back at what the server holds: a refused + // row's edit stays on the page, unsaved. + if (saved > 0) await reloadKeeping(changed.filter((c) => !savedNames.has(c.row.name))); + if (refused.length === 0) return { kind: 'saved' }; + const reason = refused + .map((r) => tFormat('engine.studio.save.refusedLine', locale, { item: r.label, reason: r.reason })) + .join('\n'); + setSaveError(reason); + return { kind: 'refused', reason }; } finally { setSaving(false); } - }, [rowState, client, packageId, onDraftSaved, load, locale]); + }, [rowState, client, packageId, load, locale]); + + // Cancel: every dial back at what the server holds, nothing sent. + const doCancel = React.useCallback(() => { + setEdits(Object.fromEntries(rows.map((r) => [r.name, { internal: r.internal }]))); + setSaveError(null); + setPrereq(null); + }, [rows]); - const canSave = !readOnly && !saving && dirtyCount > 0; + useStudioSaveEntry( + !readOnly && loaded && !loadError + ? { + label: t('engine.studio.owd.title', locale), + order: 0, + dirty: isDirty, + held: null, + save: () => doSave(), + cancel: doCancel, + } + : null, + ); + + // The prerequisite's confirm saves again, forced on the rows that carry one; + // it is the author's answer to the top bar's Save, so it reports as Save does. + const confirmPrereq = React.useCallback(async () => { + const result = await doSave(true); + if (result.kind === 'saved') { + toast.success(tFormat('engine.studio.save.done', locale, { items: t('engine.studio.owd.title', locale) }), { + id: STUDIO_SAVE_TOAST_ID, + }); + } + }, [doSave, locale]); // The dial's options, in the order the native control listed them. const internalOptions = [ @@ -483,29 +547,17 @@ export function PackageOwdOverviewPanel({
{/* objectui#12456 — the overview's title and subtitle are the Access pillar's item header above this panel, so its own header is the - toolbar row: what the dials decide, and Save. */} + toolbar row: what the dials decide. objectstack#36511 — its Save is + the top bar's. */}

{t('engine.studio.owd.description', locale)}

- {readOnly ? ( + {readOnly && ( {t('engine.studio.pkg.readonly', locale)} - ) : ( - )}
@@ -531,7 +583,7 @@ export function PackageOwdOverviewPanel({ )} - diff --git a/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.tsx b/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.tsx new file mode 100644 index 00000000000..3d8d05488ba --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/StudioAiDraftNotice.tsx @@ -0,0 +1,58 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36511 item 6 — the line an item page draws while the AI + * assistant's unpublished draft is on the item: the page shows that version, + * Save makes it live together with the page's own edits, and 「放弃 AI 的改动」 + * drops that one item's draft, back to the live version. + * + * The object page carries the same sentence and button inside its own AI line + * (with its change count and Review); this is the line for the other item + * pages, drawn the same way. + */ + +import * as React from 'react'; +import { Sparkles } from 'lucide-react'; +import { cn } from '@object-ui/components'; +import { t } from '../metadata-admin/i18n.js'; + +export function StudioAiDraftNotice({ + locale, + onDiscard, + busy = false, + className, +}: { + locale: string; + /** Drop the item's draft; `undefined` draws no button (a read-only item). */ + onDiscard?: () => void; + busy?: boolean; + className?: string; +}): React.ReactElement { + return ( +
+ + + {onDiscard && ( + + )} +
+ ); +} diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessCreateTaken-26836.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessCreateTaken-26836.test.tsx index 713d0aede49..0f7d28a3629 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessCreateTaken-26836.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessCreateTaken-26836.test.tsx @@ -95,10 +95,19 @@ function makeClient(seed: { published?: Record; drafts?: Record { + if (drafts[name]) { + published[name] = drafts[name]; + delete drafts[name]; + } + return { success: true }; + }); return { published, drafts, save, + publish, reset, // objectstack#26840 — the Access matrix reads its objects through the draft-overlaid door. withPreviewDrafts() { return this; }, @@ -159,7 +168,7 @@ async function openCreate(label: string, name?: string) { if (name) { fireEvent.change(within(dialog).getByLabelText(en('engine.studio.access.idLabel')), { target: { value: name } }); } - fireEvent.click(within(dialog).getByRole('button', { name: en('engine.studio.createDraft') })); + fireEvent.click(within(dialog).getByRole('button', { name: en('engine.studio.createLive') })); return dialog; } @@ -247,7 +256,7 @@ describe('objectstack#26836 — "+ New" over a taken identifier', () => { ).toBeNull(); }); - it('a fresh identifier: created as a draft, as before, and opened', async () => { + it('a fresh identifier: created as a draft, then published at once (objectstack#36511), and opened', async () => { clientImpl = makeClient({ published: { project_editor: { pkg: PKG, body: EDITOR } } }); renderAccess(); await screen.findByText('1 object granted · 0 field overrides', undefined, { timeout: 8000 }); @@ -256,6 +265,7 @@ describe('objectstack#26836 — "+ New" over a taken identifier', () => { const [type, name, , opts] = clientImpl.save.mock.calls[0]; expect([type, name]).toEqual(['permission', 'project_viewer']); expect(opts).toMatchObject({ mode: 'draft', packageId: PKG, ifNoneMatch: '*', surface: 'studio' }); + await waitFor(() => expect(clientImpl.publish).toHaveBeenCalledWith('permission', 'project_viewer', { packageId: PKG })); expect(toast.success).toHaveBeenCalledWith(tFormat('engine.studio.access.created', 'en', { label: 'Project Viewer' })); await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); expect(await rail().findByTitle('project_viewer')).toBeInTheDocument(); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessGuard.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessGuard.test.tsx index 9de8104f72c..f01ef5d55a9 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessGuard.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessGuard.test.tsx @@ -124,6 +124,9 @@ function makeClient(server: Server) { server.byName[name] = payload; return payload; }, + // objectstack#36511 — a create and a Save publish that one set at once. + publish: async () => ({ success: true }), + reset: async () => ({}), } as any; } @@ -308,8 +311,8 @@ describe('AccessPillar — unsaved OWD overview edits guard (#2600)', () => { fireEvent.change(within(dialog).getByPlaceholderText('Display name (e.g. Sales permissions)'), { target: { value: 'Set C' }, }); - // objectui#11787 — the create dialog's one label: it writes a draft. - fireEvent.click(within(dialog).getByRole('button', { name: t('engine.studio.createDraft', 'en-US') })); + // objectstack#36511 — a permission set is created live: the dialog says Create. + fireEvent.click(within(dialog).getByRole('button', { name: t('engine.studio.createLive', 'en-US') })); await findInSetHeader('set_c'); expect(screen.queryByTestId('owd-overview')).not.toBeInTheDocument(); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessPairCopy-29674.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessPairCopy-29674.test.tsx index 737647913d1..27978d55994 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessPairCopy-29674.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.accessPairCopy-29674.test.tsx @@ -85,6 +85,7 @@ vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); import { StudioDesignSurface } from './StudioDesignSurface'; +import { pressStudioSave } from './__tests__/studioSaveHarness'; import { t, tFormat } from '../metadata-admin/i18n'; window.matchMedia = ((query: string) => ({ @@ -255,6 +256,8 @@ describe('a "New similar" copy in the pair shows the grants it holds on the base renderAccess(COPY); await copyOpen(); fireEvent.click(within(matrix()).getByLabelText(`sc_note ${t('perm.action.edit', 'en')}`)); + // objectstack#36511 — sent by the top bar's Save. + await pressStudioSave(); await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); const [saved] = srv.saves; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.changesCount-11787.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.changesCount-11787.test.tsx index 5d02e25243d..a5077000722 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.changesCount-11787.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.changesCount-11787.test.tsx @@ -10,8 +10,9 @@ * the save lands the header says so, and the read the save asks for is sent * after it rather than joined to one already on the wire. * - * Driven through a save every author reaches: the Access pillar's - * "New permission set", whose dialog also carries Studio's one create label. + * Driven through a create that still writes a draft: Create app in the Studio + * header. objectstack#36511 — a permission set is created live now, so it + * leaves no draft for this count to follow. * * Real: the surface, its pillar, `useMetadataClient` and the client it builds, * and `usePendingDrafts`. Stubbed: `globalThis.fetch` (the server; every @@ -130,14 +131,12 @@ async function drain() { for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0)); } -async function createSetThroughTheDialog() { - // The rail's "+" (the empty block's button shares its name since objectui#12514). - fireEvent.click(await screen.findByTestId('studio-rail-add')); +async function createAppThroughTheDialog() { + const toolbar = await screen.findByTestId('studio-shell-header'); + fireEvent.click(await within(toolbar).findByRole('button', { name: t('engine.studio.app.create', 'en') })); const dialog = await screen.findByRole('dialog'); - fireEvent.change(within(dialog).getByPlaceholderText(t('engine.studio.access.labelPlaceholder', 'en')), { - target: { value: 'Set C' }, - }); - // Studio's one create label (objectui#11787): every create dialog writes a draft. + fireEvent.change(dialog.querySelectorAll('input')[0], { target: { value: 'Field Desk' } }); + // A draft-writing create says so (objectui#11787). fireEvent.click(within(dialog).getByRole('button', { name: t('engine.studio.createDraft', 'en') })); } @@ -156,7 +155,7 @@ describe('the Changes count after a draft save (objectui#11787)', () => { const beforeSave = draftReads.length; await act(async () => { - await createSetThroughTheDialog(); + await createAppThroughTheDialog(); }); await waitFor(() => expect(draftSaves).toHaveLength(1)); await act(drain); @@ -179,7 +178,7 @@ describe('the Changes count after a draft save (objectui#11787)', () => { // The read sent after the save answers with the server's count. await act(async () => { draftReads[beforeSave].respond([ - { type: 'permission', name: 'set_c', packageId: PACKAGE_ID }, + { type: 'app', name: 'a_field_desk', packageId: PACKAGE_ID }, { type: 'object', name: 'a_account', packageId: PACKAGE_ID }, ]); await drain(); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createObjectOwd.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createObjectOwd.test.tsx index a2e9c1e7de7..8942d3a5e3f 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createObjectOwd.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createObjectOwd.test.tsx @@ -14,6 +14,9 @@ * claim is that the SAVED DRAFT carries an authored baseline. */ +// Warmed at module top so the first load of the console's lazily loaded +// authoring code is paid during collection, not inside a test's clock. +import '@objectstack/lint'; import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -97,7 +100,7 @@ function fillAndSubmit(label: string) { // sr-only close button AFTER the footer, so "the last button" is Close and a // positional pick silently dismisses the dialog instead of submitting it. // Matched loosely so the suite survives either of the Studio catalog's two locales. - fireEvent.click(within(dialog).getByRole('button', { name: /save as draft|存为草稿/i })); + fireEvent.click(within(dialog).getByRole('button', { name: /^(create|创建)$/i })); } /** The body `client.save` was called with for the object draft. */ diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createTaken-26917.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createTaken-26917.test.tsx index 7c7b8daaee4..037f7022d4e 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createTaken-26917.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.createTaken-26917.test.tsx @@ -24,6 +24,9 @@ * door does, and refuses the pin over a draft row. */ +// Warmed at module top so the first load of the console's lazily loaded +// authoring code is paid during collection, not inside a test's clock. +import '@objectstack/lint'; import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -192,7 +195,11 @@ afterEach(() => { /** Fill the create dialog's label (the identifier derives from it) and submit. */ function submitCreate(dialog: HTMLElement, label: string) { fireEvent.change(dialog.querySelectorAll('input')[0], { target: { value: label } }); - fireEvent.click(within(dialog).getByRole('button', { name: en('engine.studio.createDraft') })); + // objectstack#36511 — a live editor's dialog says Create; an app's still says Save as draft. + fireEvent.click( + within(dialog).queryByRole('button', { name: en('engine.studio.createLive') }) ?? + within(dialog).getByRole('button', { name: en('engine.studio.createDraft') }), + ); } describe('objectstack#26917 — Automations: New automation over a taken identifier', () => { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftVersionConflict-11773.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftVersionConflict-11773.test.tsx index 4c8f86097a5..b4a81960dac 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftVersionConflict-11773.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.draftVersionConflict-11773.test.tsx @@ -370,13 +370,13 @@ describe('Data pillar — a draft saved elsewhere is not overwritten in silence }); describe('Data pillar — a create sends If-None-Match: * (objectui#11773)', () => { - it('the new object\'s skeleton is sent with the first-write pin; its first edit after the load is pinned to the read', async () => { + it('the new object\'s skeleton is sent with the first-write pin; it is live at once, so each Save after the load asserts no draft', async () => { server.active.clear(); const a = openEditor(); fireEvent.click(await within(a).findByTestId('empty-state-new-object', undefined, { timeout: 8000 })); const dialog = await screen.findByRole('dialog'); fireEvent.change(dialog.querySelectorAll('input')[0]!, { target: { value: 'Ticket' } }); - fireEvent.click(within(dialog).getByRole('button', { name: /save as draft/i })); + fireEvent.click(within(dialog).getByRole('button', { name: /^create$/i })); await waitFor(() => expect(server.saves).toHaveLength(1), { timeout: 8000 }); expect([server.saves[0]!.ifMatch, server.saves[0]!.ifNoneMatch]).toEqual([undefined, '*']); @@ -384,10 +384,12 @@ describe('Data pillar — a create sends If-None-Match: * (objectui#11773)', () fireEvent.click(within(a).getAllByRole('button', { name: 'Form' })[0]!); await addFieldAndSave(a, addFieldFromFormToolbar); await addFieldAndSave(a, addFieldFromFormToolbar, SECOND); - // The skeleton's draft, then the first Save over it, which publishes it. + // The skeleton's draft, which the create publishes at once (objectstack#36511): + // no draft is left, so each Save after the load asserts none. + expect(mockClient.publish).toHaveBeenCalledWith('object', expect.stringMatching(/ticket$/), expect.anything()); expect(server.saves.map((s) => [s.ifMatch, s.ifNoneMatch])).toEqual([ [undefined, '*'], - ['hmac-sha256:v1', undefined], + [undefined, '*'], [undefined, '*'], ]); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowPresets-11861.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowPresets-11861.test.tsx index d0d3dabd47e..e6621a6cd9a 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowPresets-11861.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowPresets-11861.test.tsx @@ -20,6 +20,9 @@ * metadata client is a double that records each save. */ +// Warmed at module top so the first load of the console's lazily loaded +// authoring code is paid during collection, not inside a test's clock. +import '@objectstack/lint'; import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; @@ -133,7 +136,7 @@ async function pickObject(name: string): Promise { } function create(): void { - fireEvent.click(screen.getByRole('button', { name: en('engine.studio.createDraft') })); + fireEvent.click(screen.getByRole('button', { name: en('engine.studio.createLive') })); } /** Wait for save number `n` and return its body, judged by the spec. */ diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowStatusTruth-11779.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowStatusTruth-11779.test.tsx index f7f89104860..cf1fcaa2012 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowStatusTruth-11779.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.flowStatusTruth-11779.test.tsx @@ -27,6 +27,9 @@ * reworded row turns nothing green or red. */ +// Warmed at module top so the first load of the console's lazily loaded +// authoring code is paid during collection, not inside a test's clock. +import '@objectstack/lint'; import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; @@ -347,7 +350,7 @@ describe('a new flow is born switched off, as the bar promises (objectui#11779)' }); // objectui#11861 — the blank flow is the dialog's *Advanced* choice. fireEvent.click(screen.getByRole('radio', { name: en('engine.studio.rules.advanced') })); - fireEvent.click(screen.getByRole('button', { name: en('engine.studio.createDraft') })); + fireEvent.click(screen.getByRole('button', { name: en('engine.studio.createLive') })); await waitFor(() => expect(server.saves).toHaveLength(1), { timeout: 8000 }); const { name, body } = server.saves[0]!; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataCreate-26845.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataCreate-26845.test.tsx index d157a7d8677..b5ff92952a9 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataCreate-26845.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldDataCreate-26845.test.tsx @@ -198,7 +198,7 @@ describe('a held Data field guards create and Pending changes (objectstack#26845 fireEvent.change(within(dialog).getByLabelText(t('engine.studio.data.nameLabel', 'en')), { target: { value: 'Ticket' }, }); - fireEvent.click(within(dialog).getByRole('button', { name: t('engine.studio.createDraft', 'en') })); + fireEvent.click(within(dialog).getByRole('button', { name: t('engine.studio.createLive', 'en') })); await openObjectIs('acme_ticket'); expect(confirmSpy).toHaveBeenCalledTimes(2); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.newFlowTrigger-11788.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.newFlowTrigger-11788.test.tsx index 047bfa1fef5..e7297ea95fd 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.newFlowTrigger-11788.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.newFlowTrigger-11788.test.tsx @@ -19,6 +19,9 @@ * binds a trigger. */ +// Warmed at module top so the first load of the console's lazily loaded +// authoring code is paid during collection, not inside a test's clock. +import '@objectstack/lint'; import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; @@ -138,7 +141,7 @@ async function pickTrigger(trigger: HTMLElement, value: string): Promise { } async function submitAndReadSave(): Promise> { - fireEvent.click(screen.getByRole('button', { name: en('engine.studio.createDraft') })); + fireEvent.click(screen.getByRole('button', { name: en('engine.studio.createLive') })); await waitFor(() => expect(server.saves).toHaveLength(1), { timeout: 8000 }); const { body } = server.saves[0]!; const parsed = FlowSchema.safeParse(body); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.sharedSelect-11865.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.sharedSelect-11865.test.tsx index 316f1b8e8aa..a436eaff1a2 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.sharedSelect-11865.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.sharedSelect-11865.test.tsx @@ -49,6 +49,9 @@ * the writes each option's `change` made. */ +// Warmed at module top so the first load of the console's lazily loaded +// authoring code is paid during collection, not inside a test's clock. +import '@objectstack/lint'; import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -478,7 +481,7 @@ async function openNewObject(): Promise { async function submitObject(): Promise { const dialog = screen.getByRole('dialog'); fireEvent.change(dialog.querySelectorAll('input')[0], { target: { value: 'Visit' } }); - fireEvent.click(within(dialog).getByRole('button', { name: en('engine.studio.createDraft') })); + fireEvent.click(within(dialog).getByRole('button', { name: en('engine.studio.createLive') })); await waitFor_(() => expect(mockClient.save).toHaveBeenCalledTimes(1)); return JSON.stringify((mockClient.save as ReturnType).mock.calls[0]); } @@ -546,7 +549,7 @@ async function openNewFlow(): Promise { /** Submit and return the JSON text of the saved flow. */ async function submitFlow(): Promise { - fireEvent.click(screen.getByRole('button', { name: en('engine.studio.createDraft') })); + fireEvent.click(screen.getByRole('button', { name: en('engine.studio.createLive') })); await waitFor_(() => expect(server.saves).toHaveLength(1)); return JSON.stringify(server.saves[0].body); } diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx index aedc0924c4c..64017f023b9 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx @@ -70,6 +70,7 @@ import { } from './studio-tokens.js'; import { StudioInspector } from './StudioInspector.js'; import { agentDraftMarkOf, DraftChip, DraftSourceLine, isAgentDraftSurface } from './StudioDraftMark.js'; +import { StudioAiDraftNotice } from './StudioAiDraftNotice.js'; import { StudioItemHeader, StudioItemHeaderFoldedItems, @@ -6579,11 +6580,12 @@ export function DataPillar({ setDirty(true); }, []); - // "+ new object": create a fresh object as a DRAFT in this package (runtime - // create — same path the classic Studio editor uses), seeded with one text - // field so the form/grid isn't empty. It stays draft-only (no physical table) - // until the package publish, so we land on Form · Layout — the metadata-level - // surface that never fires data SQL. + // "+ new object": create a fresh object in this package (runtime create — + // same path the classic Studio editor uses), seeded with one text field so + // the form/grid isn't empty, and land on Form · Layout. objectstack#36511 — + // it is written as a draft, then that one object is published, so it is + // live at once like every Save in Studio: no draft is left for a package + // publish, and Changes and Publish stay for the AI assistant's drafts. const doCreateObject = React.useCallback( async (label: string, rawName: string, sharingModel: OwdCreateModel) => { if (packageReadOnly && !newInPair) return; @@ -6626,6 +6628,13 @@ export function DataPillar({ ifNoneMatch: '*', surface: 'studio', }); + // objectstack#36511 — and published at once. A refused publish takes + // back the draft it wrote, so nothing is created, and says why. + const live = await publishSavedItem(client, { type: 'object', name, packageId: target.packageId }, false); + if (!live.ok) { + setError(plainRefusal(live.error)); + return; + } const surface: Surface = target.packageId === railPackageId ? { type: 'object', name, label } : { type: 'object', name, label, addedIn: target.packageId }; setObjects((prev) => [...prev, surface]); @@ -6634,7 +6643,7 @@ export function DataPillar({ setViewMode('form'); setFormMode('layout'); setCreating(false); - onDraftSaved?.(); + toast.success(tFormat('engine.studio.save.done', locale, { items: label }), { id: STUDIO_SAVE_TOAST_ID }); } catch (e) { // Shown in the create dialog, which prints the message only: kept whole. setError(plainRefusal(e)); @@ -6642,7 +6651,7 @@ export function DataPillar({ setCreateBusy(false); } }, - [objects, client, railPackageId, onDraftSaved, packageReadOnly, newInPair, customization, locale, namespace], + [objects, client, railPackageId, packageReadOnly, newInPair, customization, locale, namespace], ); // objectstack#34931 — a save the door refused `409 DESTRUCTIVE_CHANGE`, held @@ -6929,6 +6938,31 @@ export function DataPillar({ } return marks; }, [agentMarkedFields, locale]); + // objectstack#36511 item 6 — 放弃 AI 的改动: this one object's pending draft is + // discarded at the package it was read at (`DELETE /meta/object/NAME?state=draft`), + // so the page goes back to the live version and Changes counts one item + // fewer. Edits on the page not yet saved go with it, asked first. + const [discardingItemDraft, setDiscardingItemDraft] = React.useState(false); + const discardItemDraft = React.useCallback(async () => { + if (!current) return; + if (dirty && !window.confirm(t('engine.studio.aiDraft.discardConfirmUnsaved', locale))) return; + setDiscardingItemDraft(true); + setError(null); + try { + await client.reset('object', current.name, { state: 'draft', ...(packageId ? { packageId } : {}) }); + setHasDraft(false); + setDestructive(null); + // The load installs the live version and pins the next save to it. + reloadObjDraft(); + // The ledger behind Changes re-reads on the pulse, one item fewer. + emitMetadataRefresh(); + } catch (e) { + const refusal = plainRefusal(e); + setError({ ...refusal, message: tFormat('engine.studio.aiDraft.discardFailed', locale, { reason: refusal.message }) }); + } finally { + setDiscardingItemDraft(false); + } + }, [client, current, dirty, locale, packageId, reloadObjDraft]); // 放弃全部未发布改动 — the package's discard door (`packages.discardDrafts`), // which drops every pending draft of the package, the author's own too; the // confirm says so. There is no per-turn undo. @@ -7673,8 +7707,9 @@ export function DataPillar({
)} {/* objectstack#34725 — the AI assistant's drafts are on this - canvas: say how many, where to review them, and the one undo - there is (the package's discard). */} + canvas: say how many, where to review them, and the package's + discard. objectstack#36511 item 6 — and that Save makes them + live too, with the undo of this one object's draft. */} {agentDraftCount > 0 && (
+ {!readOnly && ( + + {t('engine.studio.aiDraft.notice', locale)} + + )} + {!readOnly && ( + + )} {!readOnly && adapter && (
)} - {(error || flowHeld) && ( + {(error || flowHeld || flowAiDraft) && (
+ {flowAiDraft && ( + void discardFlowDraft() : undefined} + busy={discardingFlowDraft || saving !== false} + /> + )} {error && ( { + // objectstack#36511 — the top bar's Save published the set: no + // draft of it is left, and the rail reads its label again. + setDraftNames((names) => { + if (!names.has(current)) return names; + const next = new Set(names); + next.delete(current); + return next; + }); + void load(); + }} readOnly={readOnly} onDirtyChange={setMatrixDirty} embedded @@ -11270,8 +11379,10 @@ export function AccessPillar({ labelPlaceholder={t('engine.studio.access.labelPlaceholder', locale)} idFieldLabel={t('engine.studio.access.idLabel', locale)} idPlaceholder={t('engine.studio.access.idPlaceholder', locale)} - // objectui#11787 — one label on every Studio create dialog: each writes a draft. - submitLabel={t('engine.studio.createDraft', locale)} + // objectstack#36511 — a permission set is created live (written, then + // published at its package), so its dialog says Create; a create that + // still writes a draft says Save as draft (objectui#11787). + submitLabel={t('engine.studio.createLive', locale)} submittingLabel={t('engine.studio.creating', locale)} busy={busy} error={createErr} diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index cc3f5077e31..ddf8561eae8 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -2776,17 +2776,17 @@ const STUDIO_EN: Record = { 'engine.studio.access.title': 'Permission matrix', 'engine.studio.access.subtitle': 'Object permissions · field-level read/write', 'engine.studio.access.bannerTitle': - 'Only this app’s objects are listed here, and saving changes only this app’s grants — grants from other apps stay as they are. Changes are saved as a draft and go live when you Publish the app (top bar), as in Data and Interfaces.', - 'engine.studio.access.banner': 'This app’s objects · live on publish', + 'Only this app’s objects are listed here, and saving changes only this app’s grants — grants from other apps stay as they are. Changes go live when you press Save in the top bar, as in Data and Interfaces.', + 'engine.studio.access.banner': 'This app’s objects · live on save', // objectstack#29674 — the note on an open set the base's pair adds: its matrix lists the base's objects too. - 'engine.studio.access.bannerPair': 'This app’s and {package}’s objects · live on publish', + 'engine.studio.access.bannerPair': 'This app’s and {package}’s objects · live on save', // objectstack#35018 — the open set's origin in the builder's words (the Studio title note). 'engine.studio.access.origin.app': 'Included with the app', // objectstack#35018 — the word before the open item's label on the copilot's "Viewing" line. 'engine.studio.copilot.subject.access': 'Access', 'engine.studio.copilot.subject.flow': 'Flow', 'engine.studio.access.bannerTitlePair': - 'This permission set is part of the customization of {package}, so {package}’s objects are listed as well as this app’s, and saving changes only these grants — grants from other apps stay as they are. Changes are saved as a draft and go live when you Publish (top bar).', + 'This permission set is part of the customization of {package}, so {package}’s objects are listed as well as this app’s, and saving changes only these grants — grants from other apps stay as they are. Changes go live when you press Save in the top bar.', // objectui#11781 — a read-only package saves no draft; objectui#12453 makes this the header link's title. 'engine.studio.access.bannerTitleReadOnly': 'Only this app’s objects are listed here. This app is read-only: you can view its permission sets but not change them.', @@ -3364,6 +3364,19 @@ const STUDIO_EN: Record = { 'engine.studio.save.confirmRemoveField': '• Delete the field “{field}”: its values on every record are removed.', 'engine.studio.save.confirmRetypeField': '• Change “{field}” from {from} to {to}: values already stored may be converted or cleared.', + // objectstack#36511 item 6 — an item the AI assistant left an unpublished + // draft on: the page shows that version, says Save makes it live too, and + // offers to drop that one item's draft. + 'engine.studio.aiDraft.notice': 'This item has unpublished changes from the AI assistant. Saving makes them live too.', + 'engine.studio.aiDraft.discard': 'Discard the AI’s changes', + 'engine.studio.aiDraft.discardTitle': 'Drop this item’s unpublished draft and go back to the live version', + 'engine.studio.aiDraft.discardConfirmUnsaved': + 'Discarding the AI’s changes also drops the changes on this page that you have not saved. Discard anyway?', + 'engine.studio.aiDraft.discardFailed': 'The AI’s changes were not discarded: {reason}', + // objectstack#36511 — the create dialogs of the editors whose Save is live + // (objects, automations, permission sets): the item is created and live at + // once, so the confirm says Create, never Save as draft. + 'engine.studio.createLive': 'Create', 'engine.studio.held.lineExplicit': 'Not ready to save: {clause}. Your changes are kept here; fill it in, then Save.', 'engine.studio.loading': 'Loading…', 'engine.studio.loadFailed': 'Failed to load', @@ -3916,14 +3929,11 @@ const STUDIO_EN: Record = { 'engine.studio.owd.title': 'Who can see which records', 'engine.studio.owd.subtitle': 'Record visibility of each object in this package', 'engine.studio.owd.description': - 'Who can see which records, for every object this package owns — check it at a glance and change it in bulk. Changes save as per-object drafts and go live with the package Publish, exactly like the object’s Settings tab.', + 'Who can see which records, for every object this package owns — check it at a glance and change it in bulk. Save makes the changes live at once, exactly like the object’s Settings tab.', 'engine.studio.owd.colObject': 'Object', 'engine.studio.owd.colInternal': 'Who can see which records', 'engine.studio.owd.none': 'This package declares no objects.', 'engine.studio.owd.loadFailed': 'Failed to load this package’s objects.', - 'engine.studio.owd.save': 'Save {count} change(s)', - 'engine.studio.owd.saveNone': 'No changes', - 'engine.studio.owd.saved': 'Saved {count} object draft(s).', 'engine.studio.owd.unsaved': 'Unsaved', 'engine.studio.owd.byParent': 'Follows its {master}', 'engine.studio.owd.cbpPrereqTitle': 'Make the relationship required?', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 6b967582103..6e6d646af59 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -2480,17 +2480,17 @@ const STUDIO_ZH: Record = { 'engine.studio.access.title': '权限矩阵', 'engine.studio.access.subtitle': '对象权限 · 字段级读写', 'engine.studio.access.bannerTitle': - '这里只列出本应用的对象,保存时只改本应用的授权,其他应用给出的授权保持不变。改动先保存为草稿,点击顶栏「发布」后随应用一起生效(与数据、界面一致)。', - 'engine.studio.access.banner': '本应用对象 · 发布后生效', + '这里只列出本应用的对象,保存时只改本应用的授权,其他应用给出的授权保持不变。改动在点击顶栏「保存」后立即生效(与数据、界面一致)。', + 'engine.studio.access.banner': '本应用对象 · 保存后生效', // objectstack#29674 — the note on an open set the base's pair adds: its matrix lists the base's objects too. - 'engine.studio.access.bannerPair': '本应用及 {package} 对象 · 发布后生效', + 'engine.studio.access.bannerPair': '本应用及 {package} 对象 · 保存后生效', // objectstack#35018 — the open set's origin in the builder's words (the Studio title note). 'engine.studio.access.origin.app': '随应用提供', // objectstack#35018 — the word before the open item's label on the copilot's 「正在看」 line. 'engine.studio.copilot.subject.access': '权限', 'engine.studio.copilot.subject.flow': '流程', 'engine.studio.access.bannerTitlePair': - '这个权限集属于 {package} 的定制,所以除本应用的对象外也列出 {package} 的对象;保存时只改这部分授权,其他应用给出的授权保持不变。改动先保存为草稿,点击顶栏「发布」后生效。', + '这个权限集属于 {package} 的定制,所以除本应用的对象外也列出 {package} 的对象;保存时只改这部分授权,其他应用给出的授权保持不变。改动在点击顶栏「保存」后立即生效。', 'engine.studio.access.bannerTitleReadOnly': '这里只列出本应用的对象。这个应用是只读的:可以查看它的权限集,但不能修改。', // ADR-0090 D5/D9 — 待确认的受众绑定建议(isDefault 权限集,管理员确认后生效,服务端绝不自动绑定) @@ -2988,6 +2988,14 @@ const STUDIO_ZH: Record = { 'engine.studio.save.confirmIrreversible': '保存后以下改动立即生效,之后无法用「取消」撤回:\n{changes}\n\n仍要保存吗?', 'engine.studio.save.confirmRemoveField': '• 删除字段「{field}」:所有记录上这个字段的值都会被删除。', 'engine.studio.save.confirmRetypeField': '• 把字段「{field}」从{from}改成{to}:已存的值可能被转换或清空。', + // objectstack#36511 第 6 项 — 见英文条目。 + 'engine.studio.aiDraft.notice': '这一项有 AI 未发布的改动,保存会一并生效', + 'engine.studio.aiDraft.discard': '放弃 AI 的改动', + 'engine.studio.aiDraft.discardTitle': '丢弃这一项未发布的草稿,回到已生效的版本', + 'engine.studio.aiDraft.discardConfirmUnsaved': '放弃 AI 的改动会一并丢掉本页还没保存的改动。仍要放弃吗?', + 'engine.studio.aiDraft.discardFailed': '没有放弃 AI 的改动:{reason}', + // objectstack#36511 — 见英文条目。 + 'engine.studio.createLive': '创建', 'engine.studio.held.lineExplicit': '还不能保存:{clause}。改动已保留在此处,补全后再点保存。', 'engine.studio.loading': '加载中…', 'engine.studio.loadFailed': '加载失败', @@ -3468,14 +3476,11 @@ const STUDIO_ZH: Record = { 'engine.studio.owd.title': '谁能看到哪些记录', 'engine.studio.owd.subtitle': '本包每个对象的记录可见范围', 'engine.studio.owd.description': - '本包每个对象「谁能看到哪些记录」的设置 —— 在一屏里核对并批量修改。改动按对象保存为草稿,随包发布生效,与对象「设置」页一致。', + '本包每个对象「谁能看到哪些记录」的设置 —— 在一屏里核对并批量修改。点「保存」后改动立即生效,与对象「设置」页一致。', 'engine.studio.owd.colObject': '对象', 'engine.studio.owd.colInternal': '谁能看到哪些记录', 'engine.studio.owd.none': '本包未声明任何对象。', 'engine.studio.owd.loadFailed': '加载本包对象失败。', - 'engine.studio.owd.save': '保存 {count} 处改动', - 'engine.studio.owd.saveNone': '无改动', - 'engine.studio.owd.saved': '已保存 {count} 个对象草稿。', 'engine.studio.owd.unsaved': '未保存', 'engine.studio.owd.byParent': '跟随所属的{master}', 'engine.studio.owd.cbpPrereqTitle': '将该关系设为必填?',