diff --git a/.changeset/36511-studio-save-cancel-2.md b/.changeset/36511-studio-save-cancel-2.md new file mode 100644 index 00000000000..0835bf1bd49 --- /dev/null +++ b/.changeset/36511-studio-save-cancel-2.md @@ -0,0 +1,13 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(studio): hooks, an installed app's added actions and flows save with the top bar, and a Save is live at once + +Clause-②: no +Metadata-protocol: none + +The Studio's hooks, the actions an installed app's object gains in its `.custom` package and flows no longer autosave a draft 1.5 s after each edit. Edits stay on the page until the author presses Save in the top bar; Cancel puts them back as the server holds them. Save writes each edited item's draft and then publishes that one item at the package it was written to, so the change is live at once. A new hook or an added action is written only by Save, and a removed added action is deleted by Save. + +A flow's on/off switch needs no Save: a flip writes the stored flow with the new status and publishes it at once, leaving any unsaved canvas edit on the page for Save. A new flow is published as it is created, switched off, so switching it on makes it live straight away. The inspector footers and the Studio landing say that Save makes a change live; permission sets follow in a separate change. diff --git a/ui/packages/app-shell/src/views/metadata-admin/DirectoryPage.stateVocabulary-29705.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/DirectoryPage.stateVocabulary-29705.test.tsx index 4c8e7512138..d52e5d3dd79 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/DirectoryPage.stateVocabulary-29705.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/DirectoryPage.stateVocabulary-29705.test.tsx @@ -362,6 +362,7 @@ describe('one word per state, the second pass (objectstack#29729)', () => { 'engine.studio.customize.walled', 'engine.studio.customize.noVersion', 'engine.studio.customize.draftFooter', + 'engine.studio.customize.saveFooter', 'engine.studio.customize.restoreBody', 'engine.studio.customize.restoreFlowBody', 'engine.edit.resetConfirmBody', diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.customizeFlow-28570.test.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.customizeFlow-28570.test.tsx index aaabd1bc939..13f7d47d68d 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.customizeFlow-28570.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.customizeFlow-28570.test.tsx @@ -92,6 +92,7 @@ const srv = vi.hoisted(() => ({ saveRefusal: null as null | { status: number; message: string }, saves: [] as Array<{ name: string; body: Record; opts: Record }>, resets: [] as Array<{ name: string; opts: Record }>, + publishes: [] as Array<{ name: string; opts: Record }>, version: 0, /** Whether the engine's `_status` answer holds a row for the flow. */ statusRow: true, @@ -137,6 +138,16 @@ const mockClient = vi.hoisted(() => ({ srv.version += 1; return { success: true, version: `v${srv.version}`, state: 'draft' }; }), + // objectstack#36511 — a Save publishes the one flow it wrote: the pair's draft + // becomes its published row. + publish: vi.fn(async (_type: string, name: string, opts: Record = {}) => { + srv.publishes.push({ name, opts: clone(opts) }); + if (opts.packageId === PAIR && srv.pairDraft) { + srv.pairActive = srv.pairDraft; + srv.pairDraft = null; + } + return { success: true }; + }), reset: vi.fn(async (_type: string, name: string, opts: Record = {}) => { srv.resets.push({ name, opts: clone(opts) }); if (opts.packageId === PAIR) { @@ -159,12 +170,15 @@ vi.mock('@object-ui/react', async (importOriginal) => { vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() } })); +// The source reaches a dynamic `import('@objectstack/lint')`: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { AutomationsPillar, type StudioBaseCustomization } from './StudioDesignSurface'; import { ensureCustomizationPackage } from './packages-io'; import { registerMetadataPreview } from '../metadata-admin/preview-registry'; import { publishRefusal } from './metadataError'; import { t, tFormat } from '../metadata-admin/i18n'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; const dataSource = createEmptyDataSource(); @@ -221,6 +235,7 @@ beforeEach(() => { srv.saveRefusal = null; srv.saves.length = 0; srv.resets.length = 0; + srv.publishes.length = 0; srv.version = 0; srv.statusRow = true; for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); @@ -262,9 +277,11 @@ function Host({ function mount(props: React.ComponentProps = {}) { return render( - - - , + + + + + , ); } @@ -331,7 +348,12 @@ describe('Customize a read-only base’s flow into its pair (objectstack#28570)' await customize(); patchFlow(); + await sleep(1500); + expect(srv.saves, 'nothing is written before Save (objectstack#36511)').toEqual([]); + await pressStudioSave(); await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); + // Then that one flow is published at the pair: the override is live. + await waitFor(() => expect(srv.publishes).toEqual([{ name: FLOW_NAME, opts: { packageId: PAIR } }])); expect(srv.ensure).toEqual([201]); const [saved] = srv.saves; expect(saved!.name).toBe(FLOW_NAME); @@ -353,11 +375,13 @@ describe('Customize a read-only base’s flow into its pair (objectstack#28570)' await waitFor(() => expect(screen.queryByTestId('studio-override-popover')).toBeNull()); await expectLedgerSwitchAlone(); - // A later edit asks the door no more, and is pinned to the version it was answered. + // A later edit asks the door no more; its draft was published, so the next + // save asserts no draft again. patchFlow(); + await pressStudioSave(); await waitFor(() => expect(srv.saves).toHaveLength(2), { timeout: 8000 }); expect(srv.ensure).toEqual([201]); - expect(srv.saves[1]!.opts).toMatchObject({ packageId: PAIR, ifMatch: 'v1' }); + expect(srv.saves[1]!.opts).toMatchObject({ packageId: PAIR, ifNoneMatch: '*' }); expect(srv.saves[1]!.body.overrides).toEqual(DECLARATION); expect(calls('/toggle')).toHaveLength(0); }); @@ -385,6 +409,7 @@ describe('Customize a read-only base’s flow into its pair (objectstack#28570)' // Its editors are open: an edit is saved into the pair, keeping the declaration. fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }); patchFlow(); + await pressStudioSave(); await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); expect(srv.saves[0]!.opts.packageId).toBe(PAIR); expect(srv.saves[0]!.body.overrides).toEqual(DECLARATION); @@ -436,6 +461,7 @@ describe('Customize a read-only base’s flow into its pair (objectstack#28570)' await customize(); expect(within(header()).queryByRole('switch')).toBeNull(); patchFlow(); + await pressStudioSave(); await waitFor(() => expect(srv.saves).toHaveLength(1), { timeout: 8000 }); await within(header()).findByTestId('studio-override-chip', undefined, { timeout: 8000 }); expect(within(header()).queryByRole('switch')).toBeNull(); @@ -470,6 +496,7 @@ describe('Customize a read-only base’s flow into its pair (objectstack#28570)' await openFlow(); await customize(); patchFlow(); + await pressStudioSave(); expect(await screen.findByTestId('studio-refusal-message', undefined, { timeout: 8000 })).toHaveTextContent(sentence); expect(within(header()).queryByTestId('studio-override-chip')).toBeNull(); }); diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.heldIncomplete-11786.test.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.heldIncomplete-11786.test.tsx index 4da1bd8bd5d..ddbed0a4c2b 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.heldIncomplete-11786.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.heldIncomplete-11786.test.tsx @@ -87,7 +87,10 @@ vi.mock('@object-ui/react', async (importOriginal) => { vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); +// The source reaches a dynamic `import('@objectstack/lint')`: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { AutomationsPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerMetadataPreview } from '../metadata-admin/preview-registry'; import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; @@ -131,9 +134,11 @@ async function outlastDebounce(): Promise { /** Open the flow and add a Notify step on its one edge, as an author does. */ async function addNotify(): Promise { render( - - - , + + + + + , ); fireEvent.click(await screen.findByRole('button', { name: 'Insert node here' }, { timeout: 8000 })); const option = screen.getAllByRole('option').find((o) => o.textContent?.startsWith('Notify')); @@ -168,6 +173,9 @@ describe('Automations page — a new Notify step is held until it is filled in ( fireEvent.change(within(rail).getByPlaceholderText('Your request was approved'), { target: { value: 'Request approved' }, }); + // objectstack#36511 — filled in, the step is no longer held, and Save sends it. + await waitFor(() => expect(screen.queryByTestId('studio-held')).toBeNull()); + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalledTimes(1), { timeout: 4000 }); const sent = mockClient.saves[0].nodes as Array>; expect(sent.find((n) => n.id === id)).toEqual( diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.problemsAgree-27799.test.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.problemsAgree-27799.test.tsx index 920a185c466..1990310075c 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.problemsAgree-27799.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.problemsAgree-27799.test.tsx @@ -126,6 +126,7 @@ vi.mock('../metadata-admin/previews/useObjectFields', () => ({ import { AutomationsPillar } from './StudioDesignSurface'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { getMetadataPreview, registerMetadataPreview } from '../metadata-admin/preview-registry'; import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; import { FlowInspector } from '../metadata-admin/inspectors/FlowInspector'; @@ -173,9 +174,11 @@ afterEach(() => { /** Open the flow, select Update Records, add the value `id` and switch it to a blank expression. */ async function writeBlankExpression() { render( - - - , + + + + + , ); fireEvent.click(await screen.findByRole('button', { name: 'select write' }, { timeout: 8000 })); // The node has two maps (Filter, Field values); the value goes in Field values. @@ -209,7 +212,9 @@ describe('Automations page — Problems and the node agree on a blank expression // The node: business words, not the envelope's wire shape. expect(within(map).getByRole('alert').textContent).toBe(NEEDED()); - // The draft is stored, and its verdict read again … + // Saved (objectstack#36511: by the top bar's Save), and its verdict read + // again. The double keeps serving the stored draft with its verdict. + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 6000 }); await waitFor(() => expect(server.draftReads).toBeGreaterThan(readsBefore), { timeout: 6000 }); @@ -227,6 +232,7 @@ describe('Automations page — Problems and the node agree on a blank expression it('control: once the expression is written, the cell and the Problems list clear together', async () => { const { map } = await writeBlankExpression(); + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 6000 }); fireEvent.click(screen.getByTestId('auto-tab-problems')); await screen.findByTestId('flow-problem-target', {}, { timeout: 6000 }); @@ -237,6 +243,7 @@ describe('Automations page — Problems and the node agree on a blank expression fireEvent.blur(source); expect(within(map).queryByRole('alert')).toBeNull(); + await pressStudioSave(); await waitFor(() => expect(mockClient.save.mock.calls.length).toBeGreaterThan(saves), { timeout: 6000 }); expect(await screen.findByText(EMPTY(), {}, { timeout: 6000 })).toBeInTheDocument(); expect(screen.queryByTestId('flow-problem-target')).toBeNull(); 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 new file mode 100644 index 00000000000..1dbbd003d82 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.saveCancel-36511.test.tsx @@ -0,0 +1,260 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36511 — a flow saves with the top bar's Save and Cancel, and a + * Save is live at once; its switch and its creation are live at once too. + * + * - A canvas or properties edit sends nothing until Save, however long the page + * waits (the flow's 1.5 s autosave is gone). + * - Save writes the flow's draft at its package, then publishes that one flow + * at the same package (`publish('flow', NAME, { packageId })`). + * - Cancel sends nothing and puts the flow back as the server holds it. + * - The switch needs no Save: a flip writes the stored flow with the new + * `status` and publishes it at once. An unsaved canvas edit is not sent with + * it, and stays on the page for Save. + * - A new flow is published as it is created (born off), and switching it on + * publishes it on, at once. + * + * The REAL `AutomationsPillar` with the REAL registered `FlowPreview` and + * `FlowInspector`, over a metadata client double whose publish moves the + * draft to the live row, as the server's single-item publish does. + */ + +import '@testing-library/jest-dom/vitest'; +// Paid at collection, not inside a clocked case (check:test-source-alias): +// the source under test loads `@objectstack/lint` lazily. +import '@objectstack/lint'; +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// Module scope as well as in the `vi.mock` factory below: the cold transform is paid +// during collection, which no test or hook timeout clocks (AGENTS.md, flaky-test discipline). +import '@object-ui/components'; +import { render, screen, fireEvent, cleanup, waitFor, within, act } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +const PKG = 'com.acme.app'; + +const FLOW = { + name: 'notify_owner', + label: 'Notify owner', + type: 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], +}; + +const server = vi.hoisted(() => ({ + active: new Map>(), + drafts: new Map>(), + /** Every write, in order: `save TYPE/NAME`, `publish TYPE/NAME`, `reset TYPE/NAME`. */ + log: [] as string[], +})); + +const mockClient = vi.hoisted(() => { + const k = (type: string, name: string) => `${type}/${name}`; + return { + list: vi.fn(async (type: string) => + [...server.active.entries()] + .filter(([key]) => key.startsWith(`${type}/`)) + .map(([, row]) => ({ name: row.name, label: row.label ?? row.name })), + ), + listResponse: vi.fn(async (type: string) => ({ + items: [...server.active.keys()].filter((key) => key.startsWith(`${type}/`)).map((key) => ({ name: key.split('/')[1] })), + })), + listDrafts: vi.fn(async () => []), + listTypes: vi.fn(async () => ({ entries: [] })), + get: vi.fn(async () => null), + references: vi.fn(async () => []), + layered: vi.fn(async (type: string, name: string) => { + const eff = server.active.get(k(type, name)) ?? null; + const draft = server.drafts.get(k(type, name)) ?? null; + return { code: null, overlay: eff, overlayScope: eff ? 'env' : null, effective: eff, draft, editable: true, deletable: true, resettable: false, lock: 'none' }; + }), + 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 }; + 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) => { + server.log.push(`save ${k(type, name)}`); + server.drafts.set(k(type, name), JSON.parse(JSON.stringify(item)) as Record); + return { type, name, item }; + }), + // The single-item publish: the pending draft becomes the live row. + publish: vi.fn(async (type: string, name: string) => { + server.log.push(`publish ${k(type, name)}`); + const draft = server.drafts.get(k(type, name)); + if (draft) { + server.active.set(k(type, name), draft); + server.drafts.delete(k(type, name)); + } + return { success: true }; + }), + reset: vi.fn(async (type: string, name: string) => { + server.log.push(`reset ${k(type, name)}`); + return {}; + }), + }; +}); + +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 }; +}); +vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); + +import { toast } from 'sonner'; +import { AutomationsPillar } from './StudioDesignSurface'; +import { createEmptyDataSource } from './__tests__/emptyDataSource'; +import { StudioSaveHarness, pressStudioCancel, pressStudioSave } from './__tests__/studioSaveHarness'; +import { registerMetadataPreview } from '../metadata-admin/preview-registry'; +import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; +import { FlowPreview } from '../metadata-admin/previews/FlowPreview'; +import { FlowInspector } from '../metadata-admin/inspectors/FlowInspector'; +import { t, tFormat } from '../metadata-admin/i18n'; + +const dataSource = createEmptyDataSource(); +registerMetadataPreview('flow', FlowPreview); +registerMetadataInspector('flow', FlowInspector); + +const en = (key: string) => t(key, 'en'); +const fetchSpy = vi.fn(async (_input: RequestInfo | URL) => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })); + +beforeEach(() => { + server.active.clear(); + server.drafts.clear(); + server.log.length = 0; + for (const fn of Object.values(mockClient)) (fn as unknown as { mockClear: () => void }).mockClear(); + vi.mocked(toast.success).mockClear(); + vi.mocked(toast.error).mockClear(); + window.confirm = vi.fn(() => true) as unknown as typeof window.confirm; + // The `/automation/_status` probe, the action catalog and the run history + // read all go through the global `fetch`; one double answers "absent". + vi.stubGlobal('fetch', fetchSpy); + server.active.set(`flow/${FLOW.name}`, JSON.parse(JSON.stringify(FLOW))); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +function mount(): void { + render( + + + + + , + ); +} + +const statusText = () => screen.getByText('Status:').nextElementSibling; + +async function openFlow(): Promise { + mount(); + await screen.findByTestId('auto-tab-canvas', undefined, { timeout: 8000 }); + await waitFor(() => expect(statusText()).toHaveTextContent(en('engine.studio.auto.enabled')), { timeout: 8000 }); +} + +async function editStartLabel(value: string): Promise { + fireEvent.click(document.querySelector('[data-node-id="start"] [role="button"]') as HTMLElement); + const box = await within(screen.getByTestId('auto-config-aside')).findByLabelText('Label', undefined, { timeout: 8000 }); + fireEvent.change(box, { target: { value } }); + fireEvent.blur(box); +} + +/** 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)); + }); +} + +const nodeLabel = (id: string) => + ((server.active.get(`flow/${FLOW.name}`)?.nodes as Array<{ id: string; label?: string }>) ?? []).find((n) => n.id === id)?.label; + +describe('Flows — Save and Cancel in the top bar, live at once (objectstack#36511)', () => { + it('an edit sends nothing until Save; Save writes the draft, then publishes that flow at its package', async () => { + await openFlow(); + expect(screen.queryByTestId('studio-save')).toBeNull(); + await editStartLabel('Kick-off'); + expect(await screen.findByTestId('studio-save')).toBeInTheDocument(); + await waitPastTheOldAutosave(); + expect(server.log, 'no write before Save').toEqual([]); + + await pressStudioSave(); + await waitFor(() => expect(server.log).toEqual([`save flow/${FLOW.name}`, `publish flow/${FLOW.name}`]), { timeout: 4000 }); + const [, , body, opts] = mockClient.save.mock.calls[0] as unknown as [string, string, Record, Record]; + expect(opts).toMatchObject({ mode: 'draft', packageId: PKG }); + expect(JSON.stringify(body.nodes)).toContain('Kick-off'); + expect(mockClient.publish).toHaveBeenCalledWith('flow', FLOW.name, { packageId: PKG }); + expect(nodeLabel('start'), 'the live row holds the edit').toBe('Kick-off'); + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull()); + expect(toast.success).toHaveBeenCalledWith(tFormat('engine.studio.save.done', 'en', { items: FLOW.label }), { id: 'studio-save' }); + }, 30_000); + + it('Cancel sends nothing and puts the flow back as the server holds it', async () => { + await openFlow(); + await editStartLabel('Kick-off'); + await waitFor(() => expect(document.querySelector('[data-node-id="start"]')).toHaveTextContent('Kick-off')); + + await pressStudioCancel(); + await waitFor(() => expect(document.querySelector('[data-node-id="start"]')).toHaveTextContent('Start')); + expect(document.querySelector('[data-node-id="start"]')).not.toHaveTextContent('Kick-off'); + expect(screen.queryByTestId('studio-save')).toBeNull(); + await waitPastTheOldAutosave(); + expect(server.log).toEqual([]); + }, 30_000); + + it('the switch is live at once: the stored flow is written with the new status and published, without the unsaved edit', async () => { + await openFlow(); + await editStartLabel('Kick-off'); + await screen.findByTestId('studio-save'); + + fireEvent.click(screen.getByRole('switch')); + await waitFor(() => expect(server.log).toEqual([`save flow/${FLOW.name}`, `publish flow/${FLOW.name}`]), { timeout: 4000 }); + const live = server.active.get(`flow/${FLOW.name}`)!; + expect(live.status).toBe('obsolete'); + expect(nodeLabel('start'), 'the unsaved edit was not sent with the switch').toBe('Start'); + expect(toast.success).toHaveBeenCalledWith(en('engine.studio.auto.disabledToast')); + // The edit stays on the page, for Save. + expect(screen.getByTestId('studio-save')).toBeInTheDocument(); + expect(document.querySelector('[data-node-id="start"]')).toHaveTextContent('Kick-off'); + }, 30_000); + + it('a new flow is published as it is created, off; switched on, it is published on at once', async () => { + mount(); + await screen.findByTestId(`auto-rail-row-${FLOW.name}`, undefined, { timeout: 8000 }); + fireEvent.click(screen.getByTitle(en('engine.studio.auto.newTitle'))); + 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') })); + + 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: '*' }); + expect(mockClient.publish).toHaveBeenCalledWith('flow', 'escalate', { packageId: PKG }); + expect(server.active.get('flow/escalate')?.status, 'born off').toBe('obsolete'); + expect(server.drafts.has('flow/escalate'), 'no draft is left').toBe(false); + + const toggle = await screen.findByRole('switch', undefined, { timeout: 8000 }); + await waitFor(() => expect(toggle).toHaveAttribute('aria-checked', 'false'), { timeout: 8000 }); + await waitFor(() => expect(toggle).not.toHaveAttribute('aria-disabled')); + fireEvent.click(toggle); + await waitFor(() => expect(server.log.slice(2)).toEqual(['save flow/escalate', 'publish flow/escalate']), { timeout: 8000 }); + expect(server.active.get('flow/escalate')?.status, 'switched on, live').toBe('active'); + expect(toast.success).toHaveBeenCalledWith(en('engine.studio.auto.enabledToast')); + expect(screen.queryByTestId('studio-save'), 'nothing is left to Save').toBeNull(); + }, 40_000); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.serverVerdict-26858.test.tsx b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.serverVerdict-26858.test.tsx index 331e12204c6..210c8531a13 100644 --- a/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.serverVerdict-26858.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/AutomationsPillar.serverVerdict-26858.test.tsx @@ -91,7 +91,10 @@ vi.mock('@object-ui/react', async (importOriginal) => { vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); +// The source reaches a dynamic `import('@objectstack/lint')`: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { AutomationsPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { getMetadataPreview, registerMetadataPreview } from '../metadata-admin/preview-registry'; import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; @@ -149,9 +152,11 @@ afterEach(() => { function renderPillar() { render( - - - , + + + + + , ); } @@ -165,13 +170,14 @@ describe('Automations page — the edge condition shows the draft\'s served verd await waitFor(() => expect(screen.queryByTestId('flow-edge-server-error')).toBeNull()); }); - it('the verdict follows the draft: after the autosave of a fixed condition the refusal goes', async () => { + it('the verdict follows the save: after the Save of a fixed condition the refusal goes (objectstack#36511)', async () => { renderPillar(); fireEvent.click(await screen.findByRole('button', { name: 'select e2' }, { timeout: 8000 })); await screen.findByTestId('flow-edge-server-error', {}, { timeout: 8000 }); const readsBefore = server.draftReads; fireEvent.click(screen.getByRole('button', { name: 'fix e2' })); + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 6000 }); await waitFor(() => expect(server.draftReads).toBeGreaterThan(readsBefore), { timeout: 6000 }); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActions-30088.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActions-30088.test.tsx index fa5c8861169..1da2bc468ed 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActions-30088.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.pairActions-30088.test.tsx @@ -11,13 +11,15 @@ * * Pinned: * - the Actions view of a read-only base's object offers New, with the same - * presets, once the base has or can get its pair; a preset writes a new - * `action` item into the pair as a draft (`objectName` = the object, - * `ifNoneMatch: '*'`), asking the ensure door, and the object is not - * written; + * presets, once the base has or can get its pair; a preset writes nothing + * until the top bar's Save, which writes a new `action` item into the pair + * as a draft (`objectName` = the object, `ifNoneMatch: '*'`), asking the + * ensure door, then publishes that one action at the pair + * (objectstack#36511), and the object is not written; * - the vendor's actions stay read-only (no Delete, the editor disabled); - * the added one carries the "added" mark, edits autosave into the pair's - * draft, and Delete removes its draft and its published row at the pair; + * the added one carries the "added" mark, an edit is sent by Save into the + * pair's draft and published, and Delete takes the row off the page, its + * draft and its published row at the pair going with the next Save; * - "only customizations" counts the added action and narrows the list to it; * - walled: no New, and the pair's action opens read-only; * - CONTROL: on a writable package an action is still written into the @@ -177,7 +179,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { // collection, never inside a case's clocked window (`check:test-source-alias`). import '@objectstack/lint'; import { DataPillar, type StudioBaseCustomization } from './StudioDesignSurface'; -import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; +import { StudioSaveHarness, pressStudioCancel, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; import { t, tFormat } from '../metadata-admin/i18n'; @@ -240,7 +242,7 @@ async function mountOnActions(props: { readOnly: boolean; customization?: Studio await within(await screen.findByTestId('actions-list', undefined, { timeout: 8000 })).findByText('Convert'); } -/** Past the autosave's 1.5 s debounce. */ +/** Past the retired autosave's 1.5 s debounce: nothing may leave before Save. */ async function outlastDebounce(): Promise { await act(async () => { await new Promise((r) => setTimeout(r, 2300)); @@ -266,13 +268,22 @@ describe('Studio adds an action to an installed app’s object, in its customiza expect(await screen.findByTestId(`action-preset-${id}`)).toBeInTheDocument(); } fireEvent.click(screen.getByTestId('action-preset-change_choice')); + // objectstack#36511 — nothing is written, and no pair asked for, before Save. + await outlastDebounce(); + expect(actionSaves()).toHaveLength(0); + expect(ensure).not.toHaveBeenCalled(); - await waitFor(() => expect(actionSaves()).toHaveLength(1)); + await pressStudioSave(); + await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(1)); + expect(actionSaves()).toHaveLength(1); const [, name, body, opts] = actionSaves()[0]!; expect(name).toMatch(/^crm_lead_action_\d+$/); expect(name).not.toBe(VENDOR.name); expect(body).toMatchObject({ name, objectName: OBJECT, operation: 'update', locations: ['record_header'] }); expect(opts).toMatchObject({ mode: 'draft', packageId: PAIR, ifNoneMatch: '*' }); + // Then that one action is published at the pair: live at once. + expect(mockClient.publish).toHaveBeenCalledWith('action', name, { packageId: PAIR }); + expect(mockClient.save.mock.invocationCallOrder[0]).toBeLessThan(mockClient.publish.mock.invocationCallOrder[0]); expect(ensure).toHaveBeenCalledTimes(1); expect(saves().filter(([type]) => type === 'object')).toHaveLength(0); @@ -300,16 +311,23 @@ describe('Studio adds an action to an installed app’s object, in its customiza expect(label).toBeEnabled(); fireEvent.change(label, { target: { value: 'Mark qualified' } }); await outlastDebounce(); - await waitFor(() => expect(actionSaves()).toHaveLength(1)); + expect(actionSaves(), 'no write before Save').toHaveLength(0); + await pressStudioSave(); + await waitFor(() => expect(mockClient.publish).toHaveBeenCalledTimes(1)); + expect(actionSaves()).toHaveLength(1); const [, name, body, opts] = actionSaves()[0]!; expect(name).toBe(KEPT.name); expect(body).toMatchObject({ name: KEPT.name, label: 'Mark qualified', objectName: OBJECT }); // The read's decorations are not written back. expect(body).not.toHaveProperty('_packageId'); expect(opts).toMatchObject({ mode: 'draft', packageId: PAIR }); + expect(mockClient.publish).toHaveBeenCalledWith('action', KEPT.name, { packageId: PAIR }); expect(saves().filter(([type]) => type === 'object')).toHaveLength(0); fireEvent.click(screen.getByRole('button', { name: L('engine.studio.actions.delete') })); + await outlastDebounce(); + expect(mockClient.reset, 'Delete sends nothing before Save').not.toHaveBeenCalled(); + await pressStudioSave(); await waitFor(() => expect(mockClient.reset).toHaveBeenCalledTimes(2)); expect(mockClient.reset.mock.calls).toEqual([ ['action', KEPT.name, { state: 'draft', packageId: PAIR }], @@ -329,6 +347,29 @@ describe('Studio adds an action to an installed app’s object, in its customiza expect(within(list()).getByText('Qualify')).toBeInTheDocument(); }, 30_000); + it('Cancel takes back an added action and an edit: nothing is sent, the list is as the pair holds it (objectstack#36511)', async () => { + srv.pairPublished = [KEPT]; + await mountOnActions({ readOnly: true, customization: customizationOf() }); + fireEvent.click(await within(list()).findByText('Qualify', undefined, { timeout: 8000 })); + fireEvent.change(screen.getByRole('textbox', { name: L('engine.inspector.action.label') }), { + target: { value: 'Mark qualified' }, + }); + fireEvent.click(screen.getByRole('button', { name: L('engine.studio.new') })); + fireEvent.click(await screen.findByTestId('action-preset-change_choice')); + await waitFor(() => expect(within(list()).getAllByTestId('customization-mark')).toHaveLength(2)); + + await pressStudioCancel(); + await waitFor(() => expect(within(list()).getAllByTestId('customization-mark')).toHaveLength(1)); + expect(within(list()).getByText('Qualify')).toBeInTheDocument(); + expect(within(list()).queryByText('Mark qualified')).not.toBeInTheDocument(); + expect(screen.queryByTestId('studio-save')).toBeNull(); + await outlastDebounce(); + expect(actionSaves()).toHaveLength(0); + expect(mockClient.publish).not.toHaveBeenCalled(); + expect(mockClient.reset).not.toHaveBeenCalled(); + expect(ensure).not.toHaveBeenCalled(); + }, 30_000); + it('walled: no New, and the pair’s action opens read-only', async () => { srv.pairPublished = [KEPT]; await mountOnActions({ readOnly: true, customization: customizationOf({ walled: true }) }); @@ -361,7 +402,7 @@ describe('Studio adds an action to an installed app’s object, in its customiza * * `action` is a translatable type: in a zh-CN session the pair's list and its * served drafts carry the translated label and confirmation text, and the - * autosave sends the buffer whole. Here the served reads carry the translated + * Save sends the buffer whole. Here the served reads carry the translated * copies and the pair's layered read the stored source. * * Direction, written before the run: with the buffer seeded from the served @@ -373,7 +414,7 @@ describe('a pair action edits the action as stored (objectstack#35054)', () => { const SOURCE = { ...KEPT, confirmText: 'Qualify this lead?' }; const SERVED = { ...SOURCE, label: '资格认定', confirmText: '认定此线索?' }; - it('a zh-CN edit autosaves the stored confirmation text; the edited label changes', async () => { + it('a zh-CN edit saves the stored confirmation text; the edited label changes', async () => { srv.pairPublished = [SERVED]; srv.pairDrafts = { [KEPT.name]: SERVED }; srv.stored = { [KEPT.name]: { published: SOURCE, draft: SOURCE } }; @@ -383,7 +424,7 @@ describe('a pair action edits the action as stored (objectstack#35054)', () => { const label = screen.getByRole('textbox', { name: L('engine.inspector.action.label') }); expect(label).toHaveValue('Qualify'); fireEvent.change(label, { target: { value: 'Mark qualified' } }); - await outlastDebounce(); + await pressStudioSave(); await waitFor(() => expect(actionSaves()).toHaveLength(1)); const [, name, body, opts] = actionSaves()[0]!; expect(name).toBe(KEPT.name); @@ -408,5 +449,7 @@ describe('a pair action edits the action as stored (objectstack#35054)', () => { await outlastDebounce(); expect(actionSaves()).toHaveLength(0); expect(await screen.findByText(L('engine.studio.refusal.draftUnreadable'))).toBeInTheDocument(); + // objectstack#36511 — and the top bar offers no Save for it. + expect(screen.queryByTestId('studio-save')).toBeNull(); }, 30_000); }); diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.tsx index bba87522e3e..e25bb6ff4cd 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectActionsPanel.tsx @@ -77,7 +77,6 @@ import React from 'react'; import { useParams } from 'react-router-dom'; import { toast } from 'sonner'; import { Ban, Zap, Plus, Trash2, ChevronDown, ChevronRight, Loader2, Power } from 'lucide-react'; -import { useDisplayLocale } from '@object-ui/i18n'; import { Popover, PopoverTrigger, PopoverContent } from '@object-ui/components'; import { getIcon } from '../../utils/getIcon.js'; import { useRegisteredMetadataDefaultInspector } from '../metadata-admin/default-inspector-registry.js'; @@ -93,7 +92,7 @@ import { type ActionPresetFieldOpt, } from './actionPresets.js'; import { StudioEmptyState, StudioEmptyStateAction } from './StudioEmptyState.js'; -import { usePairObjectActions, type PairActionsDoor } from './pairObjectActions.js'; +import type { PairActionsDoor, PairObjectActions } from './pairObjectActions.js'; import { RailCustomizationFilter, RailCustomizationMark, useRailCustomizationsOnly } from './StudioRailCustomizations.js'; import { FlowLedgerSwitch } from './FlowLedgerSwitch.js'; import { isStudioOrgScope } from './studioScope.js'; @@ -148,6 +147,21 @@ function labelText(label: I18nLabel | undefined, fallback: string, locale: strin return label == null ? fallback : navItemLabelText(label, locale); } +/** The pair's actions where there is no pair: nothing listed, nothing offered. */ +const NO_PAIR_ACTIONS: PairObjectActions = { + rows: [], + pairId: null, + error: null, + saving: false, + dirty: false, + renamedFrom: () => null, + create: async () => false, + patch: () => undefined, + remove: async () => undefined, + reportBlocking: () => undefined, + dialog: <>, +}; + export function ObjectActionsPanel({ draft, onPatch, @@ -157,6 +171,7 @@ export function ObjectActionsPanel({ onCelVerdictsChange, focus, pair = null, + pairActions = null, }: { draft: Record; onPatch: (patch: Record) => void; @@ -193,18 +208,24 @@ export function ObjectActionsPanel({ * the object draft's. */ pair?: PairActionsDoor | null; + /** objectstack#36511 — the pair's actions on this object, the Data pillar's buffer (`usePairObjectActions`). */ + pairActions?: PairObjectActions | null; }) { const locale = useMetadataLocale(); // The last-saved time reads the DISPLAY locale (objectui#10232). - const displayLocale = useDisplayLocale(); const objectName = typeof draft.name === 'string' ? draft.name : ''; // objectui#4527 — each action's blocking CEL verdict, by name (see below). const [celErrors, setCelErrors] = React.useState>({}); - const blockingOf = React.useCallback((name: string) => celErrors[name] ?? 0, [celErrors]); // objectstack#30088 — the pair's actions on this object, and the vendor's: // the object's served actions less any the pair holds (a published one is // served folded into the object too). - const added = usePairObjectActions(pair, objectName, blockingOf); + // objectstack#36511 — read and buffered by the Data pillar, so an unsaved + // edit outlives this view. + const added = pairActions ?? NO_PAIR_ACTIONS; + const reportPairBlockingRef = React.useRef(added.reportBlocking); + React.useLayoutEffect(() => { + reportPairBlockingRef.current = added.reportBlocking; + }); const addedNames = React.useMemo(() => new Set(added.rows.map((r) => r.name)), [added.rows]); const actions = React.useMemo( () => @@ -361,6 +382,7 @@ export function ObjectActionsPanel({ * DERIVED against the live action-name set rather than repaired by an effect. */ const reportCel = React.useCallback((actionName: string, count: number) => { + reportPairBlockingRef.current(actionName, count); setCelErrors((prev) => (prev[actionName] === count ? prev : { ...prev, [actionName]: count })); }, []); const liveActionNames = React.useMemo( @@ -610,7 +632,6 @@ export function ObjectActionsPanel({ if (allListed.length === 0) { return (
- {added.dialog} {pairError} - {added.dialog} {/* action list */}
@@ -766,18 +786,12 @@ export function ObjectActionsPanel({ <> {editable(sel.name) && (
- {/* objectstack#30088 — a pair action autosaves on its own: its status line. */} + {/* objectstack#36511 — a pair action is sent by the top bar's Save. */} {selAdded && added.saving ? ( {t('engine.studio.autoSaving', locale)} - ) : selAdded && added.savedAt !== null && added.savedAt.name === sel.name && added.dirty !== sel.name ? ( - - {tFormat('engine.studio.data.lastSaved', locale, { - time: added.savedAt.at.toLocaleTimeString(displayLocale, { hour: '2-digit', minute: '2-digit' }), - })} - ) : null}