From b4986e855996efe5381d5e2b05f5a6371bb2296c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 22:56:07 +0000 Subject: [PATCH 01/25] wip(studio): top-bar Save and Cancel for the object page Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .../studio-design/StudioDesignSurface.tsx | 491 ++++++++++-------- .../views/studio-design/StudioPillarKit.tsx | 5 +- .../src/views/studio-design/metadataError.ts | 17 + .../views/studio-design/objectSaveConfirm.ts | 58 +++ .../src/views/studio-design/studioSaveBar.tsx | 266 ++++++++++ ui/packages/i18n/src/namespaces/studio/en.ts | 20 + ui/packages/i18n/src/namespaces/studio/zh.ts | 16 + 7 files changed, 646 insertions(+), 227 deletions(-) create mode 100644 ui/packages/app-shell/src/views/studio-design/objectSaveConfirm.ts create mode 100644 ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx 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 a4dd9bcebf3..57edb9957fa 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx @@ -318,6 +318,15 @@ import { SourcePageProperties, type SourcePageNavEntry } from '../metadata-admin import { fetchPendingDrafts, usePendingDrafts } from '../../preview/usePendingDrafts.js'; import { emitMetadataRefresh, subscribeMetadataRefresh } from '../../assistant/assistantBus.js'; import { STUDIO_CHANGES_PARAM, STUDIO_CHANGES_REVIEW } from './studioChangesLink.js'; +import { + publishSavedItem, + StudioSaveControls, + StudioSaveProvider, + useStudioSaveCoordinator, + useStudioSaveEntry, + type StudioSaveResult, +} from './studioSaveBar.js'; +import { irreversibleFieldChanges } from './objectSaveConfirm.js'; import { BATCH_ABORTED_CODE, causalPublishFailures, @@ -331,6 +340,7 @@ import { objectHeldEdit, objectSaveRefusal, plainRefusal, + publishFailureOf, publishRefusal, reportHeldEdit, type PublishFailure, @@ -843,10 +853,14 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re // promotes the drafts the server holds, which do not carry that edit, so it is // refused while one is held rather than going around it silently. const [heldEdit, setHeldEdit] = React.useState(null); + // objectstack#36511 — the open page's buffers that save with the top bar's + // Save and Cancel (`studioSaveBar.tsx`). + const saveBar = useStudioSaveCoordinator(locale); // objectstack#26705 — a held edit lives only in the pillar's buffer, so a // departure drops it exactly as it drops a dirty pillar's edits: both are - // unsaved work, and every guard below reads this one bit. - const unsavedPillarWork = pillarDirty || heldEdit !== null; + // unsaved work, and every guard below reads this one bit. objectstack#36511 + // — so does an edit waiting for the top bar's Save. + const unsavedPillarWork = pillarDirty || heldEdit !== null || saveBar.dirty; const confirmLeavePillar = React.useCallback( () => confirmDropUnsavedWork(unsavedPillarWork, locale), [unsavedPillarWork, locale], @@ -878,11 +892,14 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re // what makes the gate's per-draft findings reach the author (objectui#10039). const shellClient = useMetadataClient(); - // Package-level publish (ADR-0033/0037/0048): edits accumulate as per-item - // drafts STAMPED with this package (each save passes packageId → the draft row's + // Package-level publish (ADR-0033/0037/0048): drafts are per item, STAMPED + // with this package (each save passes packageId → the draft row's // sys_metadata.package_id). Publishing promotes exactly THIS package's drafts in // one atomic pass (POST /packages/:id/publish-drafts), reviewed as a whole in - // DraftChangesPanel. There is no per-item publish. + // DraftChangesPanel. objectstack#36511 — an editor converted to the top bar's + // Save writes its item's draft and publishes that one item at once + // (`publishSavedItem`), so it leaves no draft; Changes and Publish are for the + // drafts other writers (the copilot) and the editors not yet converted leave. const [changesOpen, setChangesOpen] = React.useState(false); // objectui#12517 — which trigger opened the sheet: Publish opens it to // confirm (rows expanded, focus on Publish all), Changes opens it to review. @@ -998,6 +1015,12 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re toast.error(tFormat('engine.studio.held.publish', locale, { clause: heldEdit })); return; } + // objectstack#36511 — a publish re-reads the open page from the server, so + // it would drop edits still waiting for Save: they are saved or cancelled first. + if (saveBar.dirty) { + toast.error(t('engine.studio.save.publishFirst', locale)); + return; + } setPublishing(true); // objectstack#26730 — a refusal is kept on each causal draft's entry, read // by the refused-save reader against the draft the publish judged, and the @@ -1209,7 +1232,7 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re setPublishing(false); } await refreshPending(); - }, [shellClient, packageId, pairId, draftScope, refreshPending, locale, heldEdit]); + }, [shellClient, packageId, pairId, draftScope, refreshPending, locale, heldEdit, saveBar.dirty]); // objectui#11787 — a Studio draft save reports here when it lands, and the // count follows it: the read it asks for is sent after the save, never @@ -1263,17 +1286,13 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re }), [shownPendingCount, packageId, pendingEntries, behindSave], ); - const publishNoneReasonId = React.useId(); const publishReadOnlyReasonId = React.useId(); - // The reason a disabled Publish gives, or `null` when it gives none: the - // button is enabled, or a publish is in flight (a spinner, for a moment, not - // a state the author has to get out of). A read-only package outranks an - // empty ledger; with neither, the button is the primary action. + // The reason a disabled Publish gives, or `null` when it gives none. + // objectstack#36511 — Publish is drawn only while a draft is pending, so the + // one reason left is a read-only package. const publishDisabledReason: { id: string; text: string; testId?: string } | null = publishReadOnly ? { id: publishReadOnlyReasonId, text: t('engine.studio.pkg.readonlyHint', locale) } - : !hasPending && !publishing - ? { id: publishNoneReasonId, text: t('engine.studio.publishNoneTitle', locale), testId: 'publish-none-reason' } - : null; + : null; // Builder → running-app bridge: the builder edits the package (the design // surface), the app is its published front-end. The header's way back to it @@ -1605,11 +1624,11 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re setChangesPosture('confirm'); setChangesOpen(true); }} - disabled={publishing || !hasPending || publishReadOnly} + disabled={publishing || publishReadOnly} aria-describedby={publishDisabledReason?.id} // A disabled Publish's reason is its wrapper's (objectui#12303, // objectstack#31495), never a `title` the disabled button cannot show. - title={hasPending && !publishReadOnly ? t('engine.studio.publishTitle', locale) : undefined} + title={publishReadOnly ? undefined : t('engine.studio.publishTitle', locale)} // objectui#8219 — the primary style is for a publish the author // CAN do. A disabled one (no draft, or a read-only package) // drops to an outline, instead of staying the loudest element @@ -1617,7 +1636,8 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re className={cn( // The border is on both states so the swap never shifts the bar. 'inline-flex h-8 items-center gap-1.5 rounded-md border px-3 text-[13px] font-medium', - publishing || (hasPending && !publishReadOnly) + // objectstack#36511 — beside the top bar's Save, Save is the primary action. + publishing || (!publishReadOnly && !saveBar.dirty) ? 'border-transparent bg-primary text-primary-foreground disabled:opacity-50' : 'text-muted-foreground', // The wrapper takes the hover: the disabled button lets it through. @@ -1631,6 +1651,7 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re return ( +
{/* The ADR-0080 `aiSlot` seam — a cloud edition may still inject its own @@ -1725,64 +1746,71 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re {t('engine.studio.app.create', locale)} )} - {/* objectui#12459 — the pending count is a pill, not "· N" text. */} - - {/* A disabled Publish says why, to the mouse, the keyboard and - assistive tech alike — the record page's Archive pattern - (`DeclaredActionsBar`, objectui#11811), for both reasons it - can be off: a read-only package (objectui#12303) and nothing - pending (objectui#8219, objectstack#31495). A natively - disabled button fires no hover or focus, so the wrapping span - is the tooltip trigger and a tab stop, and the button and the - span both point `aria-describedby` at an `sr-only` copy of - the reason. objectstack#28562 — a read-only base with a - customization package publishes that package's drafts, so it - is not read-only here. */} - {publishDisabledReason ? ( - - - - - {publishButton} + + {/* A disabled Publish says why, to the mouse, the keyboard and + assistive tech alike — the record page's Archive pattern + (`DeclaredActionsBar`, objectui#11811), for the reason it + can be off: a read-only package (objectui#12303). A natively + disabled button fires no hover or focus, so the wrapping span + is the tooltip trigger and a tab stop, and the button and the + span both point `aria-describedby` at an `sr-only` copy of + the reason. objectstack#28562 — a read-only base with a + customization package publishes that package's drafts, so it + is not read-only here. */} + {publishDisabledReason ? ( + + + - {publishDisabledReason.text} + {publishButton} + + {publishDisabledReason.text} + - - - {publishDisabledReason.text} - - - ) : ( - publishButton + + {publishDisabledReason.text} + + + ) : ( + publishButton + )} + )} + {/* objectstack#36511 — the page's Cancel and Save, where Publish + was: drawn only while the open page holds unsaved edits. */} + )} {/* objectui#12725 — the top bar's right-most icon shows or hides the right slot; `⌘.` switches what it shows. @@ -2066,6 +2094,7 @@ function StudioDesignSurfaceBody({ aiSlot, area }: StudioDesignSurfaceProps): Re />
+
); } @@ -5574,10 +5603,6 @@ export function DataPillar({ const client = useMetadataClient(); const adapter = useAdapter(); const locale = useMetadataLocale(); - // The last-saved time reads the DISPLAY locale — not `locale` above, which - // picks the pillar's strings and is `'en-US'` for every non-zh language - // (objectui#10232). - const displayLocale = useDisplayLocale(); // Live server JSONSchemas per metadata type (`/meta/types`) — handed to the // Actions/Hooks config panels so their forms are driven by the real metadata // contract (and stay forward-compatible when the server spec adds fields). @@ -5764,10 +5789,6 @@ export function DataPillar({ const [dirty, setDirty] = React.useState(false); const [hasDraft, setHasDraft] = React.useState(false); const [saving, setSaving] = React.useState(false); - // Timestamp of the last successful draft save — renders a "last saved HH:MM" - // hint next to the Save button (framework#2615 P3: nothing confirmed a draft - // save persisted, unlike the sibling pillars which toast). - const [savedAt, setSavedAt] = React.useState(null); const [gridVer, setGridVer] = React.useState(0); // Records grid ⇄ Form ⇄ Validations ⇄ Settings — four views of the SAME // object. Grid/Form are the runtime renderer (same-renderer principle); @@ -6663,20 +6684,25 @@ export function DataPillar({ ); // objectstack#34931 — a save the door refused `409 DESTRUCTIVE_CHANGE`, held - // for the author's answer: what it would lose, and the save itself. While it - // is held the autosave sends nothing. + // for the author's answer: what it would lose, and the save itself. const [destructive, setDestructive] = React.useState(null); // The object as the server holds it for this buffer (as loaded, or as last // saved): what keeping a field restores it from. const objStoredRef = React.useRef | null>(null); + // The buffer as last committed: a save that lands clears the dirty flag + // only while the buffer is still the body it sent. + const objDraftRef = React.useRef(objDraft); + React.useLayoutEffect(() => { + objDraftRef.current = objDraft; + }); - const doSave = React.useCallback(async (sent: DraftSend, forced?: ObjDraftSend) => { - if (!current) return; - setSaving('draft'); - setError(null); + // objectstack#36511 — the top bar's Save for the object: its draft, then that + // object's own publish, so the save is live at once. A refused publish keeps + // the edits on the page, unsaved, with the reason in the refusal strip. + const doSave = React.useCallback(async (forced?: ObjDraftSend): Promise => { + if (!current) return { kind: 'declined' }; // objectui#10202 — the buffer was seeded from the served object, whose // picklist-bound fields carry the list's resolved `options`; the door // refuses them beside `picklist`, so they stay out of the body. @@ -6685,6 +6711,20 @@ export function DataPillar({ // body, to the address it wrote (`packageId` included), never re-derived. const { name, packageId: to, draft, body } = forced ?? { name: current.name, packageId, draft: objDraft, body: dropServedPicklistOptions(objDraft) }; + // A removed or retyped published field is asked about before anything is sent. + if (!forced) { + const changes = irreversibleFieldChanges(objStoredRef.current, draft, publishedFieldNames, locale); + if ( + changes.length > 0 && + !window.confirm(tFormat('engine.studio.save.confirmIrreversible', locale, { changes: changes.join('\n') })) + ) { + return { kind: 'declined' }; + } + } + setSaving('draft'); + setError(null); + const hadDraft = hasDraft; + const storedBefore = objStoredRef.current; try { const outcome = await saveObjDraft('object', name, body, { mode: 'draft', @@ -6693,38 +6733,42 @@ export function DataPillar({ ...(forced ? { force: true } : {}), }); // objectui#11773 — the author chose the saved version; the load replaces the buffer. - if (outcome === 'reloaded') return; + if (outcome === 'reloaded') return { kind: 'declined' }; objStoredRef.current = draft; setHasDraft(true); - // objectui#11204 — clean only if nothing was edited while it was in flight. - if (sent.unmoved()) setDirty(false); - setSavedAt(new Date()); - // objectstack#27644 — the draft this save stored carries its own publish - // verdict on its next read; the one held described the body before it. - const seq = ++objVerdictSeq.current; - void readDraftForSave(client, 'object', name, to).then((read) => { - if (seq !== objVerdictSeq.current) return; - setObjVerdict(draftEnvelopeDiagnostics(read.answer)); - setObjVerdictBody(extractDraftBody(read.answer) ?? undefined); - }); - // objectstack#28984 — named by the label this save stored; one toast per - // object however many editing pauses save it (`announceDraftSaved`). - announceDraftSaved( - { type: 'object', name }, - typeof body.label === 'string' && body.label ? body.label : current.label, - locale, - ); - onDraftSaved?.({ type: 'object', name }); + setSaving('publish'); + const live = await publishSavedItem(client, { type: 'object', name, packageId: to }, hadDraft); + if (!live.ok) { + if (live.draftDiscarded) { + objStoredRef.current = storedBefore; + setHasDraft(false); + recordObjRead('object', name, to, { ifNoneMatch: '*' }); + } + const refusal = publishRefusal(publishFailureOf('object', name, live.error), 'object', body, locale); + setError(refusal); + return { kind: 'refused', reason: refusal.message }; + } + // Live: no draft is left, so the next save asserts none. The pulse the + // publish sent re-reads the object once this save has settled. + setHasDraft(false); + recordObjRead('object', name, to, { ifNoneMatch: '*' }); + if (JSON.stringify(objDraftRef.current) === JSON.stringify(draft)) setDirty(false); + return { kind: 'saved' }; } catch (e) { // objectstack#34931 — what the save would lose is asked about, once: // a forced save refused again reads as any other refusal. const findings = forced ? null : destructiveFindings(e); - if (findings) setDestructive({ name, packageId: to, draft, body, sent, findings }); - else setError(objectSaveRefusal(e, body, locale)); + if (findings) { + setDestructive({ name, packageId: to, draft, body, findings }); + return { kind: 'declined' }; + } + const refusal = objectSaveRefusal(e, body, locale); + setError(refusal); + return { kind: 'refused', reason: refusal.message }; } finally { setSaving(false); } - }, [saveObjDraft, client, current, objDraft, onDraftSaved, packageId, locale]); + }, [saveObjDraft, recordObjRead, client, current, objDraft, hasDraft, publishedFieldNames, packageId, locale]); // objectstack#34931 — Cancel keeps what the refused save would have lost: // each field a finding names goes back as the server holds it, and nothing @@ -6758,17 +6802,8 @@ export function DataPillar({ [dirty, objDraft, locale], ); - // objectui#5813 — auto-save replaces the Save draft button; the blocked guard - // is the button's old disabled-condition verbatim, plus the hold above. - const { flush: flushObjSave, sending: sendingObjDraft, loaded: objLoaded } = useDraftAutoSave({ - // objectui#11232 — the object `doSave` addresses. - target: `object:${current?.name ?? ''}`, - loadedFor: objDraftFor, - dirty, - blocked: !current || !!saving || readOnly || saveBlocking > 0 || objIncomplete !== null || destructive !== null, - snapshot: objDraft, - save: doSave, - }); + // objectui#11272 — the buffer is the open object's own once its load installed it. + const objLoaded = current !== null && objDraftFor === `object:${current.name}`; // objectstack#28575 — the ensure door's answer for this base's extension // writes: asked by the first add (no prompt), once per base, and again only @@ -6784,46 +6819,58 @@ export function DataPillar({ }); return asked; }, []); - // The extension's draft save, into the pair the door answered. A refusal - // (the suffix, a structural key, the ensure door's walled 403) is shown as - // the server sent it. - const doSaveExt = React.useCallback( - async (sent: DraftSend) => { - if (!extOpen || !customization) return; - const { for: name, body } = extOpen; - setSaving('draft'); - setError(null); - try { - const pair = await extPairFor(customization); - const outcome = await saveExtDraft(OBJECT_EXTENSION_TYPE, name, extensionBodyForSave(body), { - mode: 'draft', - packageId: pair, - surface: 'studio', - }); - if (outcome === 'reloaded') return; - setExtHasDraft(true); - if (sent.unmoved()) setExtDirty(false); - setSavedAt(new Date()); - // objectstack#28984 — the extension customizes the open object, so it - // is named by that object's label. - announceDraftSaved({ type: OBJECT_EXTENSION_TYPE, name }, current?.label ?? '', locale); - onDraftSaved?.({ type: OBJECT_EXTENSION_TYPE, name }); - } catch (e) { - setError(plainRefusal(e)); - } finally { - setSaving(false); - } - }, - [extOpen, customization, extPairFor, saveExtDraft, onDraftSaved, current, locale], - ); - const { flush: flushExtSave } = useDraftAutoSave({ - target: `${OBJECT_EXTENSION_TYPE}:${current?.name ?? ''}`, - loadedFor: extOpen ? `${OBJECT_EXTENSION_TYPE}:${extOpen.for}` : '', - dirty: extDirty, - blocked: !extWritable || !!saving || saveBlocking > 0, - snapshot: extOpen?.body ?? null, - save: doSaveExt, + const extBodyRef = React.useRef(extOpen?.body ?? null); + React.useLayoutEffect(() => { + extBodyRef.current = extOpen?.body ?? null; }); + // The extension's Save, into the pair the door answered, then that + // extension's own publish there (objectstack#36511): an installed app's + // object takes the page's fields live at once, in its `.custom` package. A + // refusal (the suffix, a structural key, the ensure door's walled 403) is + // shown as the server sent it. + const doSaveExt = React.useCallback(async (): Promise => { + if (!extOpen || !customization) return { kind: 'declined' }; + const { for: name, body } = extOpen; + setSaving('draft'); + setError(null); + const hadDraft = extHasDraft; + try { + const pair = await extPairFor(customization); + const outcome = await saveExtDraft(OBJECT_EXTENSION_TYPE, name, extensionBodyForSave(body), { + mode: 'draft', + packageId: pair, + surface: 'studio', + }); + if (outcome === 'reloaded') return { kind: 'declined' }; + setExtHasDraft(true); + setSaving('publish'); + const live = await publishSavedItem(client, { type: OBJECT_EXTENSION_TYPE, name, packageId: pair }, hadDraft); + if (!live.ok) { + if (live.draftDiscarded) { + setExtHasDraft(false); + recordExtRead(OBJECT_EXTENSION_TYPE, name, pair, { ifNoneMatch: '*' }); + } + const refusal = publishRefusal( + publishFailureOf(OBJECT_EXTENSION_TYPE, name, live.error), + OBJECT_EXTENSION_TYPE, + extensionBodyForSave(body), + locale, + ); + setError(refusal); + return { kind: 'refused', reason: refusal.message }; + } + setExtHasDraft(false); + recordExtRead(OBJECT_EXTENSION_TYPE, name, pair, { ifNoneMatch: '*' }); + if (JSON.stringify(extBodyRef.current) === JSON.stringify(body)) setExtDirty(false); + return { kind: 'saved' }; + } catch (e) { + const refusal = plainRefusal(e); + setError(refusal); + return { kind: 'refused', reason: refusal.message }; + } finally { + setSaving(false); + } + }, [extOpen, customization, extPairFor, saveExtDraft, recordExtRead, client, extHasDraft, locale]); // An edit of the folded object's fields, written into the extension: an // extension field whole, a base field's whitelisted change as its patch. const onExtFieldsPatch = React.useCallback( @@ -6951,15 +6998,48 @@ export function DataPillar({ } }, [adapter, locale, objects, packageId, reloadObjDraft]); useHeldEditReport(onHeldEditChange, objHeld?.clause ?? null); - // objectstack#27511 — opening another object replaces the one buffer the - // open object's edits live in, and the autosave's timer sends nothing once - // the open object has changed (objectui#11232). So an edit still inside the - // debounce was dropped by the switch with nothing on screen. The switch now - // sends it first with the autosave's own `flush` and opens the object once - // the buffer is clean, as the Interfaces nav's "Done" closes (objectui#11189); - // a save already in flight is waited out the same way. An edit that cannot - // be sent (held, or its save refused with the refusal on screen) is the - // author's to drop: the switch asks (objectstack#26705). + // objectstack#36511 — the object page's buffers, saved and cancelled by the + // top bar's one Save and Cancel: the object (its fields, rules, actions and + // settings), then a read-only base's extension of it in the pair. A CEL + // verdict no field or rule names yet (Settings reports one count) holds the + // Save as a named edit does. + const objSaveHeld = + objHeld?.clause ?? + (saveBlocking > 0 && current + ? tFormat('engine.studio.held.inspectorInvalid', locale, { item: current.label || current.name }) + : null); + useStudioSaveEntry( + current && objLoaded && !readOnly + ? { + label: current.label || current.name, + order: 0, + dirty, + held: objSaveHeld, + save: () => doSave(), + cancel: () => { + setDestructive(null); + reloadObjDraft(); + }, + } + : null, + ); + useStudioSaveEntry( + current && extOpen !== null && extWritable + ? { + label: current.label || current.name, + order: 1, + dirty: extDirty, + held: saveBlocking > 0 ? tFormat('engine.studio.held.inspectorInvalid', locale, { item: current.label || current.name }) : null, + save: () => doSaveExt(), + cancel: reloadExt, + } + : null, + ); + // objectstack#36511 — opening another object replaces the buffer the open + // object's unsaved edits live in, so the author is asked first, as every + // departure asks (objectstack#26705). The form view's buffer still saves + // itself: its pending edit is sent first and the switch waits for it to + // land (objectstack#27511); one it cannot send is the author's to drop. const [switchTo, setSwitchTo] = React.useState(null); const openObject = React.useCallback( (next: Surface): boolean => { @@ -6968,35 +7048,28 @@ export function DataPillar({ setCurrent(next); return true; } - // objectstack#28575 — and the base object's extension buffer the same way. - // objectstack#30057 — and the form view's buffer. - if ( - saving || - (dirty && objHeld === null && flushObjSave()) || - (extDirty && flushExtSave()) || - (formViewDirty && flushFormView()) - ) { + const dropsEdits = dirty || extDirty; + if (formView.saving || (formViewDirty && flushFormView())) { + if (!confirmDropUnsavedWork(dropsEdits, locale)) return false; setSwitchTo(next); return true; } - if (!confirmDropUnsavedWork(dirty || extDirty || formViewDirty, locale)) return false; + if (!confirmDropUnsavedWork(dropsEdits || formViewDirty, locale)) return false; setSwitchTo(null); setCurrent(next); return true; }, - [current, saving, dirty, extDirty, formViewDirty, objHeld, flushObjSave, flushExtSave, flushFormView, locale], + [current, dirty, extDirty, formViewDirty, formView.saving, flushFormView, locale], ); React.useEffect(() => { if (!switchTo || saving || formView.saving) return; - if (dirty && objHeld === null && flushObjSave()) return; - if (extDirty && flushExtSave()) return; if (formViewDirty && flushFormView()) return; setSwitchTo(null); - // Still dirty: the save was refused (on screen) or an edit taken meanwhile - // is held. The author stays; the next switch asks. - if (dirty || extDirty || formViewDirty) return; + // Still dirty: the form view's save was refused (on screen). The author + // stays; the next switch asks. + if (formViewDirty) return; setCurrent(switchTo); - }, [switchTo, saving, dirty, extDirty, formViewDirty, formView.saving, objHeld, flushObjSave, flushExtSave, flushFormView]); + }, [switchTo, saving, formViewDirty, formView.saving, flushFormView]); // The live request's apply (see `requestedSurface` above). objectstack#26845 // — another object's load replaces the buffer a held edit lives in, so it // goes through the rail's own switch (`openObject`): an unsent edit is sent @@ -7096,14 +7169,12 @@ export function DataPillar({ ); // Drag-reorder columns → reorder the object's `fields` metadata (field display - // order follows metadata order), saved as a DRAFT. Published later via the - // package release — NOT auto-published per reorder as it used to be. - // objectui#11204 — this save is sent here, not by the autosave, so it takes - // its claim on the buffer from the autosave's `sending`: an edit taken while - // it is in flight stays dirty, and the autosave sends it next. + // order follows metadata order). objectstack#36511 — an edit of the buffer + // like any other: it is sent by the top bar's Save, never on the drop. const doReorderFields = React.useCallback( - async (orderedNames: string[]) => { - if (!current) return; + (orderedNames: string[]) => { + // objectui#11272 — never onto another object's buffer. + if (!current || !objLoaded || readOnly) return; const view = readFields(objDraft.fields); // Reorder only the visible fields among their own slots; keep system / // hidden fields (not shown as columns) in their original positions. @@ -7113,32 +7184,11 @@ export function DataPillar({ .filter((e): e is (typeof view.entries)[number] => Boolean(e)); let vi = 0; const entries = view.entries.map((e) => (visible.has(e.name) ? visibleInOrder[vi++] : e)); - const body = { ...objDraft, fields: writeFields({ ...view, entries }) }; - // objectui#11272 — no claim, no save: the buffer is not this object's. - const sent = sendingObjDraft(body); - if (!sent) return; - setObjDraft(body); - setSaving('draft'); - setError(null); - // objectui#10202 — same served `options` as `doSave` above. - const wire = dropServedPicklistOptions(body); - try { - const outcome = await saveObjDraft('object', current.name, wire, { mode: 'draft', packageId, surface: 'studio' }); - if (outcome === 'reloaded') return; - objStoredRef.current = body; - setHasDraft(true); - if (sent.unmoved()) setDirty(false); - onDraftSaved?.({ type: 'object', name: current.name }); - setGridVer((v) => v + 1); // remount so the grid reflects the new (draft) order - } catch (e) { - const findings = destructiveFindings(e); - if (findings) setDestructive({ name: current.name, packageId, draft: body, body: wire, sent, findings }); - else setError(objectSaveRefusal(e, wire, locale)); - } finally { - setSaving(false); - } + setObjDraft({ ...objDraft, fields: writeFields({ ...view, entries }) }); + setDirty(true); + setGridVer((v) => v + 1); // remount so the grid reflects the new order }, - [saveObjDraft, current, objDraft, onDraftSaved, sendingObjDraft, packageId, locale], + [current, objLoaded, readOnly, objDraft], ); // Observed (objectui#11939): an object inspector registered after this pillar @@ -7442,7 +7492,10 @@ export function DataPillar({ onClick={() => { if (!destructive) return; setDestructive(null); - void doSave(destructive.sent, destructive); + const label = current?.label || destructive.name; + void doSave(destructive).then((result) => { + if (result.kind === 'saved') toast.success(tFormat('engine.studio.save.done', locale, { items: label })); + }); }} > {t('engine.edit.forceSave', locale)} @@ -7555,21 +7608,6 @@ export function DataPillar({ status={objDraftStatus} actions={ <> - {/* objectui#5813 — drafts auto-save (see useDraftAutoSave above); the - hint is the whole affordance: saving spinner while in flight, the - last-saved time once landed. The old Save draft button is retired. */} - {saving === 'draft' ? ( - - - {t('engine.studio.autoSaving', locale)} - - ) : savedAt && !dirty && !extDirty ? ( - - {tFormat('engine.studio.data.lastSaved', locale, { - time: savedAt.toLocaleTimeString(displayLocale, { hour: '2-digit', minute: '2-digit' }), - })} - - ) : null} {/* objectstack#28239 — the item tools Setup's item page opens. */} {current && objLoaded && ( ; locale: string; + /** objectstack#36511 — the pillar saves with the top bar's Save, not by itself. */ + explicitSave?: boolean; /** Opens the held input; omitted while that input is the one open. */ onShow?: (target: Target) => void; /** Spacing and type size, which differ by pillar. */ @@ -148,7 +151,7 @@ export function StudioHeldNotice

- {tFormat('engine.studio.held.line', locale, { clause: held.clause })} + {tFormat(explicitSave ? 'engine.studio.held.lineExplicit' : 'engine.studio.held.line', locale, { clause: held.clause })}

{onShow && ( + + + ); +} diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 3989e97f417..31d81f7c7c2 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -3318,6 +3318,26 @@ const STUDIO_EN: Record = { 'engine.studio.pkg.manageRefreshFailed': 'Package {id} could not be refreshed after that change — closing the panel rather than showing the pre-change record as current. {error}', 'engine.studio.publish': 'Publish', + // objectstack#36511 — the top bar's Save and Cancel (`studioSaveBar.tsx`): + // one pair for the open page, where Publish was; a Save is live at once. + 'engine.studio.save.save': 'Save', + 'engine.studio.save.saving': 'Saving…', + 'engine.studio.save.cancel': 'Cancel', + 'engine.studio.save.title': 'Save the changes on this page. They take effect at once.', + 'engine.studio.save.cancelTitle': 'Discard the changes on this page that are not saved', + 'engine.studio.save.done': 'Saved, live now: {items}', + 'engine.studio.save.refused': 'Not saved: {items}', + 'engine.studio.save.refusedLine': '{item}: {reason}', + 'engine.studio.save.savedLine': 'Saved and live: {items}', + 'engine.studio.save.itemSeparator': ', ', + 'engine.studio.save.held': 'Not saved: {clause}. Your changes are kept on the page.', + 'engine.studio.save.publishFirst': 'Save or cancel the changes on this page before you publish.', + 'engine.studio.save.confirmIrreversible': + 'Saving makes these changes live at once, and Cancel cannot undo them afterwards:\n{changes}\n\nSave anyway?', + '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.', + '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', // objectui#11785 — a refused save, in the author's words. The strip shows one diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index cd0c879ceaf..afa4c246acc 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -2951,6 +2951,22 @@ const STUDIO_ZH: Record = { 'engine.studio.pkg.manageRefreshFailed': '软件包 {id} 在该操作后未能刷新 —— 已关闭面板,以免把操作前的记录当作最新呈现。{error}', 'engine.studio.publish': '发布', + 'engine.studio.save.save': '保存', + 'engine.studio.save.saving': '保存中…', + 'engine.studio.save.cancel': '取消', + 'engine.studio.save.title': '保存本页的改动,保存后立即生效。', + 'engine.studio.save.cancelTitle': '丢掉本页还没保存的改动', + 'engine.studio.save.done': '已保存并生效:{items}', + 'engine.studio.save.refused': '未保存:{items}', + 'engine.studio.save.refusedLine': '{item}:{reason}', + 'engine.studio.save.savedLine': '已保存并生效:{items}', + 'engine.studio.save.itemSeparator': '、', + 'engine.studio.save.held': '未保存:{clause}。改动仍保留在页面上。', + 'engine.studio.save.publishFirst': '发布前请先保存或取消本页的改动。', + 'engine.studio.save.confirmIrreversible': '保存后以下改动立即生效,之后无法用「取消」撤回:\n{changes}\n\n仍要保存吗?', + 'engine.studio.save.confirmRemoveField': '• 删除字段「{field}」:所有记录上这个字段的值都会被删除。', + 'engine.studio.save.confirmRetypeField': '• 把字段「{field}」从{from}改成{to}:已存的值可能被转换或清空。', + 'engine.studio.held.lineExplicit': '还不能保存:{clause}。改动已保留在此处,补全后再点保存。', 'engine.studio.loading': '加载中…', 'engine.studio.loadFailed': '加载失败', 'engine.studio.refusal.choiceWithoutOptions': From 2dc4f5eadf70f03094c2763a056d25035a63c163 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 23:06:25 +0000 Subject: [PATCH 02/25] test(studio): pin the object page's top-bar Save and Cancel Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .../DataPillar.saveCancel-36511.test.tsx | 261 ++++++++++++++++++ .../__tests__/studioSaveHarness.tsx | 45 +++ .../studioSaveBar.partialSave-36511.test.tsx | 130 +++++++++ ui/packages/i18n/src/namespaces/studio/en.ts | 2 +- ui/packages/i18n/src/namespaces/studio/zh.ts | 2 +- 5 files changed, 438 insertions(+), 2 deletions(-) create mode 100644 ui/packages/app-shell/src/views/studio-design/DataPillar.saveCancel-36511.test.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/__tests__/studioSaveHarness.tsx create mode 100644 ui/packages/app-shell/src/views/studio-design/studioSaveBar.partialSave-36511.test.tsx diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.saveCancel-36511.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.saveCancel-36511.test.tsx new file mode 100644 index 00000000000..6a00783daf2 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.saveCancel-36511.test.tsx @@ -0,0 +1,261 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36511 — the object page saves with the top bar's Save and + * Cancel, and a Save is live at once. + * + * - An edit sends nothing: no draft write leaves before Save is pressed, however + * long the page waits (the 1.5 s autosave is gone from this buffer). + * - Save writes the object's draft at its package, then publishes that one + * object at the same package (`POST /meta/object/NAME/publish?package=`), and + * says what went live. The batch door (`/packages/:id/publish-drafts`) is + * never called. + * - Cancel sends nothing and puts the page back as the server holds it. + * - A refused publish keeps the page's edits, unsaved (Save is still offered), + * names the reason on the page and in the toast, and takes back the draft the + * save wrote, so the refusal leaves no draft pending. + * - An edit that cannot be sent yet holds the whole Save, naming what it needs. + * - Removing a published field is confirmed at Save with its consequence; + * declined, nothing is sent. + * + * 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 * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { render, screen, fireEvent, cleanup, waitFor, within, act } 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' }, + { name: 'place', label: 'Place', type: 'text' }, + ], +}; + +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 server = { refusePublish: false }; + +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 }); + if (method === 'POST' && server.refusePublish) { + return json(422, { + success: false, + error: { code: 'INVALID_METADATA', message: 'The object refers to a field that is not live yet.' }, + }); + } + 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 () => []) }; +}); +// The field header's ⋯ menu as plain buttons (as in `DataPillar.celGate.test.tsx`). +vi.mock('@object-ui/components', async (importOriginal) => { + const mod = await importOriginal(); + const Pass = (p: { children?: React.ReactNode }) =>
{p.children}
; + const Item = (p: { children?: React.ReactNode; onSelect?: () => void }) => ( + + ); + return { + ...mod, + DropdownMenu: Pass, + DropdownMenuTrigger: Pass, + DropdownMenuContent: Pass, + DropdownMenuItem: Item, + DropdownMenuRadioGroup: Pass, + DropdownMenuRadioItem: Item, + }; +}); +vi.mock('@object-ui/react', async (importOriginal) => { + const mod = await importOriginal(); + return { ...mod, useAdapter: () => dataSource }; +}); + +import { toast } from 'sonner'; +import { DataPillar } from './StudioDesignSurface'; +import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; +import { createEmptyDataSource } from './__tests__/emptyDataSource'; +import { StudioSaveHarness, pressStudioCancel, pressStudioSave } from './__tests__/studioSaveHarness'; +import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; +import { t, tFormat } 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(); +registerBuiltinInspectors(); + +const confirmSpy = vi.fn((_message?: string) => true); +beforeEach(() => { + confirmSpy.mockReset(); + confirmSpy.mockReturnValue(true); + window.confirm = confirmSpy as unknown as typeof window.confirm; +}); +afterEach(() => { + cleanup(); + writes.length = 0; + server.refusePublish = false; + vi.mocked(toast.success).mockClear(); + vi.mocked(toast.error).mockClear(); +}); + +/** 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; +const describeWrite = (w: Write) => `${w.method} ${w.url.pathname}${w.url.search}`; + +async function mountOnForm(): Promise { + render( + + + + + , + ); + fireEvent.click(await screen.findByRole('button', { name: 'Form' })); + await screen.findByTestId('form-toolbar'); +} + +/** 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('Data pillar — 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 object at its package', async () => { + await mountOnForm(); + expect(screen.queryByTestId('studio-save'), 'no edit, no Save').toBeNull(); + await addFieldFromFormToolbar(undefined, { label: 'Due' }); + expect(await screen.findByTestId('studio-save')).toBeInTheDocument(); + expect(screen.getByTestId('studio-cancel')).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/object/showcase_task'); + expect(draft.url.searchParams.get('mode')).toBe('draft'); + expect(draft.url.searchParams.get('package')).toBe(PACKAGE); + expect((draft.body?.fields as Array<{ name: string }>).map((f) => f.name)).toContain('due'); + 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); + expect(writes.some((w) => w.url.pathname.includes('publish-drafts'))).toBe(false); + + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull()); + expect(toast.success).toHaveBeenCalledWith(tFormat('engine.studio.save.done', 'en', { items: 'Task' })); + }); + + it('Cancel sends nothing and puts the page back as the server holds it', async () => { + await mountOnForm(); + await addFieldFromFormToolbar(undefined, { label: 'Due' }); + await waitFor(() => expect(card('Due')).not.toBeNull()); + const loads = layered.mock.calls.length; + + await pressStudioCancel(); + await waitFor(() => expect(card('Due')).toBeNull()); + expect(card('Place')).not.toBeNull(); + expect(layered.mock.calls.length, 'the object was read again from the server').toBeGreaterThan(loads); + expect(screen.queryByTestId('studio-save')).toBeNull(); + await waitPastTheOldAutosave(); + expect(writes.map(describeWrite)).toEqual([]); + }); + + it('a refused publish keeps the edits unsaved, says why, and takes back the draft it wrote', async () => { + server.refusePublish = true; + await mountOnForm(); + await addFieldFromFormToolbar(undefined, { label: 'Due' }); + await pressStudioSave(); + await waitFor(() => expect(writes).toHaveLength(3), { timeout: 4000 }); + expect(writes.map((w) => w.method)).toEqual(['PUT', 'POST', 'DELETE']); + const discard = writes[2]; + expect(discard.url.pathname).toBe('/api/v1/meta/object/showcase_task'); + expect(discard.url.searchParams.get('state')).toBe('draft'); + expect(discard.url.searchParams.get('package')).toBe(PACKAGE); + + const strip = await screen.findByTestId('studio-refusal'); + expect(strip).toHaveTextContent('The object refers to a field that is not live yet.'); + expect(card('Due'), 'the edit is still on the page').not.toBeNull(); + expect(screen.getByTestId('studio-save'), 'and still offered to Save').toBeInTheDocument(); + expect(toast.error).toHaveBeenCalledWith( + tFormat('engine.studio.save.refused', 'en', { items: 'Task' }), + expect.objectContaining({ description: expect.stringContaining('The object refers to a field that is not live yet.') }), + ); + expect(toast.success).not.toHaveBeenCalled(); + }); + + it('an edit that cannot be sent yet holds the whole Save and names what it needs', async () => { + await mountOnForm(); + // A Picklist with no option yet: the write guard would refuse it. + await addFieldFromFormToolbar(undefined, { label: 'Stage', type: /^Picklist$/ }); + await screen.findByTestId('studio-held'); + await pressStudioSave(); + const clause = tFormat('engine.studio.held.needsOptions', 'en', { field: 'Stage' }); + expect(toast.error).toHaveBeenCalledWith(tFormat('engine.studio.save.held', 'en', { clause })); + await waitPastTheOldAutosave(); + expect(writes.map(describeWrite)).toEqual([]); + expect(screen.getByTestId('studio-save')).toBeInTheDocument(); + }); + + it('removing a published field asks at Save, naming the consequence; declined, nothing is sent', async () => { + confirmSpy.mockReturnValue(false); + await mountOnForm(); + fireEvent.click((await screen.findByText('Place')).closest('.cursor-grab') as HTMLElement); + fireEvent.click(await screen.findByRole('button', { name: 'Remove “Place”' })); + fireEvent.click(within(await screen.findByRole('alertdialog')).getByTestId('field-remove-confirm-action')); + await waitFor(() => expect(card('Place')).toBeNull()); + await waitPastTheOldAutosave(); + expect(writes.map(describeWrite), 'removing it from the page sends nothing').toEqual([]); + + await pressStudioSave(); + expect(confirmSpy).toHaveBeenCalledTimes(1); + const asked = String(confirmSpy.mock.calls[0][0]); + expect(asked).toContain(tFormat('engine.studio.save.confirmRemoveField', 'en', { field: 'Place' })); + expect(writes.map(describeWrite), 'declined: nothing sent').toEqual([]); + expect(screen.getByTestId('studio-save')).toBeInTheDocument(); + + confirmSpy.mockReturnValue(true); + await pressStudioSave(); + await waitFor(() => expect(writes.map((w) => w.method)).toEqual(['PUT', 'POST']), { timeout: 4000 }); + expect((writes[0].body?.fields as Array<{ name: string }>).map((f) => f.name)).toEqual(['title']); + expect(t('engine.studio.save.confirmIrreversible', 'en')).not.toBe('engine.studio.save.confirmIrreversible'); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/__tests__/studioSaveHarness.tsx b/ui/packages/app-shell/src/views/studio-design/__tests__/studioSaveHarness.tsx new file mode 100644 index 00000000000..545995f7b79 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/__tests__/studioSaveHarness.tsx @@ -0,0 +1,45 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The top bar's Save and Cancel for a suite that mounts a pillar without the + * surface (objectstack#36511). A pillar's explicit-save buffers register with + * the surface's coordinator, so a pillar mounted alone saves nothing; wrapped + * in {@link StudioSaveHarness} it gets the same coordinator and the same two + * buttons the surface draws, and {@link pressStudioSave} presses Save. + */ + +import * as React from 'react'; +import { act, fireEvent, screen } from '@testing-library/react'; +import { + StudioSaveControls, + StudioSaveProvider, + useStudioSaveCoordinator, +} from '../studioSaveBar'; + +export function StudioSaveHarness({ children, locale = 'en' }: { children: React.ReactNode; locale?: string }): React.ReactElement { + const coordinator = useStudioSaveCoordinator(locale); + return ( + +
+ +
+ {children} +
+ ); +} + +/** Press the top bar's Save once it is drawn (the page holds an unsaved edit). */ +export async function pressStudioSave(): Promise { + const save = await screen.findByTestId('studio-save', undefined, { timeout: 4000 }); + await act(async () => { + fireEvent.click(save); + }); +} + +/** Press the top bar's Cancel once it is drawn. */ +export async function pressStudioCancel(): Promise { + const cancel = await screen.findByTestId('studio-cancel', undefined, { timeout: 4000 }); + await act(async () => { + fireEvent.click(cancel); + }); +} diff --git a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.partialSave-36511.test.tsx b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.partialSave-36511.test.tsx new file mode 100644 index 00000000000..b435c8c03f3 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.partialSave-36511.test.tsx @@ -0,0 +1,130 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36511 — the top bar's one Save over every buffer on the page. + * + * - The pair is drawn only while a registered buffer is dirty. + * - Save sends the dirty buffers in `order`, every one of them: a refused one + * does not stop the rest, and the toast names each refused item with its + * reason and lists the items that were saved. + * - A held buffer refuses the whole Save before anything is sent. + * - Cancel drops every dirty buffer, and only those. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen, waitFor } from '@testing-library/react'; + +vi.mock('sonner', () => ({ + toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn(), message: vi.fn(), dismiss: vi.fn() }, + Toaster: () => null, +})); + +import { toast } from 'sonner'; +import { useStudioSaveEntry, type StudioSaveEntry } from './studioSaveBar'; +import { StudioSaveHarness, pressStudioCancel, pressStudioSave } from './__tests__/studioSaveHarness'; +import { tFormat } from '../metadata-admin/i18n'; + +afterEach(() => { + cleanup(); + vi.mocked(toast.success).mockClear(); + vi.mocked(toast.error).mockClear(); +}); + +function Buffer(props: Partial & { label: string }) { + useStudioSaveEntry({ + order: 0, + dirty: true, + held: null, + save: async () => ({ kind: 'saved' }), + cancel: () => {}, + ...props, + }); + return null; +} + +describe('the top bar Save over every buffer of the page (objectstack#36511)', () => { + it('is drawn only while a buffer is dirty', async () => { + const { rerender } = render( + + + , + ); + expect(screen.queryByTestId('studio-save')).toBeNull(); + expect(screen.queryByTestId('studio-cancel')).toBeNull(); + rerender( + + + , + ); + expect(await screen.findByTestId('studio-save')).toBeInTheDocument(); + expect(screen.getByTestId('studio-cancel')).toBeInTheDocument(); + }); + + it('sends every dirty buffer in order; a refusal names its item and reason and lists what was saved', async () => { + const sent: string[] = []; + const clean = vi.fn(async () => ({ kind: 'saved' as const })); + render( + + { + sent.push('fields'); + return { kind: 'refused', reason: 'Field “Due” is not valid.' }; + }} + /> + { + sent.push('object'); + return { kind: 'saved' }; + }} + /> + (sent.push('hooks'), { kind: 'saved' })} /> + + , + ); + await pressStudioSave(); + await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1)); + expect(sent).toEqual(['object', 'fields', 'hooks']); + expect(clean).not.toHaveBeenCalled(); + const [title, opts] = vi.mocked(toast.error).mock.calls[0]; + expect(title).toBe(tFormat('engine.studio.save.refused', 'en', { items: 'Customer fields' })); + expect((opts as { description: string }).description.split('\n')).toEqual([ + tFormat('engine.studio.save.refusedLine', 'en', { item: 'Customer fields', reason: 'Field “Due” is not valid.' }), + tFormat('engine.studio.save.savedLine', 'en', { items: 'Customer, Hooks' }), + ]); + expect(toast.success).not.toHaveBeenCalled(); + }); + + it('a held buffer refuses the whole Save before anything is sent', async () => { + const save = vi.fn(async () => ({ kind: 'saved' as const })); + render( + + + + , + ); + await pressStudioSave(); + expect(save).not.toHaveBeenCalled(); + expect(toast.error).toHaveBeenCalledWith( + tFormat('engine.studio.save.held', 'en', { clause: 'the field “Stage” needs at least one option' }), + ); + }); + + it('Cancel drops every dirty buffer, and only those', async () => { + const dropped: string[] = []; + render( + + dropped.push('object')} /> + dropped.push('extension')} /> + dropped.push('clean')} /> + , + ); + await pressStudioCancel(); + expect(dropped).toEqual(['object', 'extension']); + }); +}); diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 31d81f7c7c2..98e7835a738 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -375,7 +375,7 @@ const STUDIO_EN: Record = { 'designer.field.section.developer': 'Developer info', 'designer.field.section.developerHint': 'The internal name the API and formulas refer to. Everyday edits do not need it.', 'designer.field.removeConfirmTitle': 'Delete the field “{label}”?', - 'designer.field.removeConfirmBody': 'The field leaves this object\'s draft. The change takes effect when you publish.', + 'designer.field.removeConfirmBody': 'The field leaves this object once the change is saved and live.', 'designer.field.section.advanced': 'Advanced', 'designer.field.section.options': '{type} options', 'designer.field.section.computed': 'Computed value', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index afa4c246acc..0166b55cedf 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -297,7 +297,7 @@ const STUDIO_ZH: Record = { 'designer.field.section.developer': '开发者信息', 'designer.field.section.developerHint': '内部名在接口与公式里引用,日常改字段用不到。', 'designer.field.removeConfirmTitle': '删除字段“{label}”?', - 'designer.field.removeConfirmBody': '字段会从这个对象的草稿中移除,发布后生效。', + 'designer.field.removeConfirmBody': '改动保存并生效后,这个字段会从对象中移除。', 'designer.field.section.advanced': '高级', 'designer.field.section.options': '{type} 选项', 'designer.field.section.computed': '计算值', From 7bec409937e42bd53139a60209822b2d226df678 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 23:30:00 +0000 Subject: [PATCH 03/25] test(studio): the top bar draws Save where Publish was Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- ...StudioDesignSurface.saveBar-36511.test.tsx | 177 ++++++++++++++++++ 1 file changed, 177 insertions(+) create mode 100644 ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.saveBar-36511.test.tsx diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.saveBar-36511.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.saveBar-36511.test.tsx new file mode 100644 index 00000000000..f798f9003c2 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.saveBar-36511.test.tsx @@ -0,0 +1,177 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36511 — the top bar of the Studio surface: Cancel and Save + * where Publish was, Changes and Publish only for drafts. + * + * - With no draft pending, the top bar draws neither Changes nor Publish. + * - An edit on the object page draws Cancel and Save in the top bar's right + * column; Save is its last action. + * - With a draft pending (the copilot's), Changes and Publish are drawn, at the + * left of Cancel and Save, and a publish is refused while the page holds + * edits Save has not sent: the publish re-reads the page and would drop them. + * + * Real: the surface, the Data pillar, the coordinator and `usePendingDrafts`. + * Doubles: the metadata client's reads and transport, the `_drafts` ledger + * read, the package list, and the panels no assertion reads (the changes + * sheet is a button that runs its `onPublish`). + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { MetadataClient } from '@object-ui/data-objectstack'; + +const PACKAGE_ID = 'app.a'; +const objectDef = { name: 'a_task', label: 'Task', fields: [{ name: 'title', label: 'Title', type: 'text' }] }; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +const writes: string[] = []; +const transport = vi.fn(async (url: string, init?: RequestInit) => { + const method = init?.method ?? 'GET'; + if (method === 'GET') return json(404, null); + writes.push(`${method} ${url}`); + return json(200, { success: true }); +}); +const client = new MetadataClient({ baseUrl: 'http://test.local', fetch: transport as unknown as typeof fetch }); +Object.assign(client, { + list: vi.fn(async (type: string) => (type === 'object' ? [{ name: 'a_task', label: 'Task' }] : [])), + listDrafts: vi.fn(async () => []), + layered: vi.fn(async () => ({ effective: objectDef, code: objectDef })), + getDraft: vi.fn(async () => null), +}); + +const ledger: { drafts: Array> } = { drafts: [] }; + +vi.mock('sonner', () => ({ + toast: { warning: vi.fn(), error: vi.fn(), success: 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 actual = await importOriginal>(); + return { + ...actual, + fetchPackages: vi.fn(async () => [{ id: PACKAGE_ID, name: PACKAGE_ID, writable: true, namespace: 'a' }]), + }; +}); +vi.mock('@object-ui/react', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, useAdapter: () => dataSource }; +}); +vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPanel: () => null })); +vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); +vi.mock('../../preview/DraftChangesPanel', () => ({ + DraftChangesPanel: (p: { onPublish?: () => void }) => + p.onPublish ? ( + + ) : null, +})); + +import { toast } from 'sonner'; +import '@objectstack/lint'; +import { StudioDesignSurface } from './StudioDesignSurface'; +import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; +import { createEmptyDataSource } from './__tests__/emptyDataSource'; +import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; +import { t } from '../metadata-admin/i18n'; + +const dataSource = createEmptyDataSource(); +registerBuiltinInspectors(); + +window.matchMedia = ((query: string) => ({ + matches: false, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, +})) as unknown as typeof window.matchMedia; +(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = + (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver ?? + class { + observe() {} + unobserve() {} + disconnect() {} + }; + +beforeEach(() => { + vi.stubGlobal( + 'fetch', + vi.fn(async (input: unknown, init?: { method?: string }) => { + const url = String(input); + if (url.includes('/meta/_drafts')) return json(200, { drafts: ledger.drafts }); + if (init?.method && init.method !== 'GET') writes.push(`${init.method} ${url}`); + return json(200, []); + }) as unknown as typeof fetch, + ); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + writes.length = 0; + ledger.drafts = []; + vi.mocked(toast.error).mockClear(); +}); + +const CHANGES = new RegExp(`^${t('engine.studio.changes', 'en')}`); +const PUBLISH = new RegExp(`^${t('engine.studio.publish', 'en')}$`); + +async function mountAndEdit(): Promise { + render( + + + } /> + + , + ); + fireEvent.click(await screen.findByRole('button', { name: 'Form' }, { timeout: 4000 })); + await addFieldFromFormToolbar(undefined, { label: 'Due' }); + return screen.getByTestId('studio-shell-header'); +} + +describe('the Studio top bar: Save where Publish was, Changes and Publish for drafts (objectstack#36511)', () => { + it('with no draft pending: no Changes, no Publish; an edit draws Cancel and Save at the right', async () => { + const header = await mountAndEdit(); + const save = await within(header).findByTestId('studio-save'); + const cancel = within(header).getByTestId('studio-cancel'); + expect(within(header).queryByRole('button', { name: CHANGES })).toBeNull(); + expect(within(header).queryByRole('button', { name: PUBLISH })).toBeNull(); + // Cancel, then Save, the last of the right column's actions. + expect(cancel.compareDocumentPosition(save) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + const column = save.parentElement as HTMLElement; + const actions = within(column).getAllByRole('button'); + expect(actions[actions.length - 1]).toBe(save); + expect(writes).toEqual([]); + }); + + it('with a draft pending: Changes and Publish at the left of Cancel and Save; Publish waits for Save', async () => { + ledger.drafts = [{ type: 'flow', name: 'a_notify', packageId: PACKAGE_ID }]; + const header = await mountAndEdit(); + const changes = await within(header).findByRole('button', { name: CHANGES }, { timeout: 4000 }); + const publish = within(header).getByRole('button', { name: PUBLISH }); + const cancel = await within(header).findByTestId('studio-cancel'); + const save = within(header).getByTestId('studio-save'); + expect(changes.compareDocumentPosition(publish) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(publish.compareDocumentPosition(cancel) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(cancel.compareDocumentPosition(save) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + + await act(async () => { + fireEvent.click(screen.getByTestId('sheet-publish-all')); + }); + expect(toast.error).toHaveBeenCalledWith(t('engine.studio.save.publishFirst', 'en')); + expect(writes.filter((w) => w.includes('publish'))).toEqual([]); + await waitFor(() => expect(within(header).getByTestId('studio-save')).toBeInTheDocument()); + }); +}); From 3688cdc5eb40cedc28e1611a1a4c753feb0eae4c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 23:36:19 +0000 Subject: [PATCH 04/25] fix(studio): Save waits out the expression check; gate pins press Save Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .../metadata-admin/CelPredicateField.tsx | 3 +- .../DataPillar.actionRefusal-26736.test.tsx | 5 ++- .../DataPillar.addFieldPopover-12516.test.tsx | 6 ++- .../DataPillar.authorRefusal-11785.test.tsx | 9 +++-- .../DataPillar.authoredBuffer-29793.test.tsx | 5 ++- ...aPillar.baseObjectExtension-28575.test.tsx | 14 ++++--- .../studio-design/DataPillar.celGate.test.tsx | 38 +++++++++++-------- ...Pillar.choiceWithoutOptions-11253.test.tsx | 9 +++-- ...ataPillar.copilotDraftMarks-12725.test.tsx | 6 ++- ...ataPillar.destructiveChange-34931.test.tsx | 5 ++- .../DataPillar.draftSavedNamed-28984.test.tsx | 5 ++- .../DataPillar.draftUnreadable-29148.test.tsx | 6 ++- .../DataPillar.formViewLayout-30057.test.tsx | 6 ++- .../DataPillar.heldIncomplete-11786.test.tsx | 13 ++++--- ...taPillar.hiddenSystemFields-11780.test.tsx | 6 ++- .../DataPillar.pairActions-30088.test.tsx | 6 ++- .../DataPillar.panelGate.test.tsx | 28 +++++++------- .../DataPillar.panelHold-27629.test.tsx | 13 +++++-- ...illar.picklistServedOptions-10202.test.tsx | 5 ++- .../DataPillar.railSwitchFlush-27511.test.tsx | 6 ++- .../DataPillar.recordsTab-34794.test.tsx | 6 ++- .../DataPillar.showMeFocus-26730.test.tsx | 5 ++- .../DataPillar.summaryHeld-27461.test.tsx | 5 ++- ...illar.validationVerdictHold-27644.test.tsx | 6 ++- ...StudioDesignSurface.saveBar-36511.test.tsx | 7 +++- .../__tests__/studioSaveHarness.tsx | 16 ++++++-- .../src/views/studio-design/studioSaveBar.tsx | 22 ++++++++--- 27 files changed, 164 insertions(+), 97 deletions(-) diff --git a/ui/packages/app-shell/src/views/metadata-admin/CelPredicateField.tsx b/ui/packages/app-shell/src/views/metadata-admin/CelPredicateField.tsx index ef57a245261..a1bf776b2c9 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/CelPredicateField.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/CelPredicateField.tsx @@ -79,7 +79,8 @@ import { useServerHoldAt, type ServerDiagnosticEntry } from './draftVerdict.js'; // fields as lists (`celAuthoring.ts` stays free of any import at load). import { multiValueFieldsOf, type CelFieldDef } from './clientValidation.js'; -const LINT_DEBOUNCE_MS = 250; +/** The lint pass runs this long after the last keystroke; Studio's Save waits it out (objectstack#36511). */ +export const LINT_DEBOUNCE_MS = 250; const KIND_TAG: Record = { field: 'field', diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx index 9ba52767641..e5d77545c73 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx @@ -129,6 +129,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; import { t, tFormat } from '../metadata-admin/i18n'; @@ -154,9 +155,9 @@ async function outlastDebounce(): Promise { async function mountOnView(def: Record, tabKey: string): Promise { objectDef = def; render( - + - , + , ); // The first match is the flat tab (the passthrough menu draws a second). fireEvent.click((await screen.findAllByRole('button', { name: L(tabKey) }))[0]); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx index ec1faaec8e8..44b130c252a 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx @@ -32,6 +32,7 @@ const mockClient = { listDrafts: vi.fn(async () => []), layered: vi.fn(async () => ({ effective: servedObject, code: servedObject })), getDraft: vi.fn(async () => null), + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn(async () => ({ ok: true })), }; @@ -69,6 +70,7 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { t } from '../metadata-admin/i18n'; import { readFields } from '../metadata-admin/previews/object-fields-io'; import { addFieldFromFormToolbar, addFieldFromGrid } from './__tests__/dataPillarAddField'; @@ -98,9 +100,9 @@ afterEach(() => { async function renderPillar(props: { readOnly?: boolean } = {}) { render( - + - , + , ); await waitFor(() => expect(screen.getByTestId('records-panel')).toBeInTheDocument(), { timeout: 8000 }); } diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx index 9f2af6a1f43..16a72dd71e6 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx @@ -75,6 +75,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; @@ -98,9 +99,9 @@ function controlUnder(label: string): HTMLElement { describe('Studio data page — a held Picklist reads as a sentence (objectui#11785, held since objectui#11786)', () => { it('names the field by its label and shows no developer text', async () => { render( - + - , + , ); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); await addFieldFromFormToolbar(); @@ -134,9 +135,9 @@ describe('Studio data page — a held Picklist reads as a sentence (objectui#117 it('"Show me" opens the named field\'s inspector after it was closed', async () => { render( - + - , + , ); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); await addFieldFromFormToolbar(); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.authoredBuffer-29793.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.authoredBuffer-29793.test.tsx index 8f502c56a54..3336b919f60 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.authoredBuffer-29793.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.authoredBuffer-29793.test.tsx @@ -128,6 +128,7 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { // load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { t, tFormat } from '../metadata-admin/i18n'; import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; import { ObjectFieldInspector } from '../metadata-admin/inspectors/ObjectFieldInspector'; @@ -174,9 +175,9 @@ afterEach(() => { function renderZh() { return render( - + - + , ); } diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.baseObjectExtension-28575.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.baseObjectExtension-28575.test.tsx index 37dcdfa29de..887a612e81b 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.baseObjectExtension-28575.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.baseObjectExtension-28575.test.tsx @@ -82,6 +82,7 @@ const mockClient = { get: vi.fn(async (type: string, name: string, opts?: { packageId?: string }) => type === 'object_extension' && name === OBJECT && opts?.packageId === PAIR ? srv.publishedExt : null, ), + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn(async (type: string, _name: string, _body: unknown, _opts?: { packageId?: string }) => { if (type === 'object_extension' && srv.refuse) throw srv.refuse; return { ok: true, version: 'v2', state: 'draft' }; @@ -125,6 +126,7 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { // warmed here so its first load is paid at import, not inside a test's clock. import '@objectstack/lint'; import { DataPillar, type StudioBaseCustomization } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { t, tFormat } from '../metadata-admin/i18n'; import { emitMetadataRefresh } from '../../assistant/assistantBus'; import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; @@ -186,9 +188,9 @@ afterEach(() => { async function renderBase(over: Partial = {}) { render( - + - , + , ); await waitFor(() => expect(screen.getByTestId('records-panel')).toBeInTheDocument(), { timeout: 8000 }); } @@ -415,9 +417,9 @@ describe('Studio adds a field to a read-only base object as an extension in its describe('CONTROL: a writable package’s add-field is unchanged (objectstack#28575)', () => { it('a plain name into the object’s own body, and a fully editable inspector', async () => { render( - + - , + , ); await waitFor(() => expect(screen.getByTestId('records-panel')).toBeInTheDocument(), { timeout: 8000 }); await openForm(); @@ -495,9 +497,9 @@ describe('the object header says where a base object’s extension is saved (obj it('CONTROL: an object of a writable package says nothing of the kind', async () => { render( - + - , + , ); await waitFor(() => expect(screen.getByTestId('records-panel')).toBeInTheDocument(), { timeout: 8000 }); expect(savedTo()).toBeNull(); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.celGate.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.celGate.test.tsx index 760d1f2d705..e6c6834660e 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.celGate.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.celGate.test.tsx @@ -49,6 +49,7 @@ const objectDef = { const siteDef = { name: 'showcase_site', label: 'Site', fields: [{ name: 'address', label: 'Address', type: 'text' }] }; const mockClient = { + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn(async () => ({})), list: vi.fn(async () => [ { name: 'showcase_task', label: 'Task' }, @@ -107,6 +108,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; // The source under test reaches a dynamic import of `@objectstack/lint`: its first @@ -155,9 +157,9 @@ function stubEngine() { async function openFormulaField() { stubEngine(); render( - + - , + , ); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); const card = (await screen.findByText('Total')).closest('.cursor-grab') as HTMLElement; @@ -166,34 +168,35 @@ async function openFormulaField() { return label.parentElement!.querySelector('[role="combobox"]') as HTMLTextAreaElement; } -// objectui#5813 retired the 保存草稿 button for debounced AUTO-save; the CEL -// gate now guards the TIMER (the objectui#4306 rule verbatim: gating only a -// button would let the timer persist the malformed definition a second later). -// The observable is therefore client.save itself. -describe('DataPillar — auto-save is gated on the field inspector’s CEL verdict (#4306/#5813)', () => { - it("refuses the card's repro: a dangling operator blocks the auto-save", async () => { +// objectstack#36511 — the CEL gate guards the top bar's Save (the objectui#4306 +// rule verbatim: a malformed definition is never sent). The observable is +// therefore client.save itself, after Save is pressed. +describe('DataPillar — Save is gated on the field inspector’s CEL verdict (#4306/#36511)', () => { + it("refuses the card's repro: a dangling operator blocks the Save", async () => { const box = await openFormulaField(); - // A valid formula first: the auto-save fires — pins the must-not-change - // half (a good formula never blocks) and clears the dirty window. + // A valid formula first: Save sends it — pins the must-not-change half (a + // good formula never blocks). fireEvent.change(box, { target: { value: 'record.est_hours * 2' } }); + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 4000 }); mockClient.save.mockClear(); - // Now the card's exact input: well past the debounce, still no save. + // Now the card's exact input: Save sends nothing. fireEvent.change(box, { target: { value: 'record.est_hours *' } }); - await new Promise((r) => setTimeout(r, 2300)); + await pressStudioSave(); expect(mockClient.save).not.toHaveBeenCalled(); }); - it('re-arms the auto-save once the formula parses again', async () => { + it('re-arms the Save once the formula parses again', async () => { const box = await openFormulaField(); fireEvent.change(box, { target: { value: 'record.est_hours *' } }); - await new Promise((r) => setTimeout(r, 2300)); + await pressStudioSave(); expect(mockClient.save).not.toHaveBeenCalled(); fireEvent.change(box, { target: { value: 'record.est_hours * 2' } }); + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 4000 }); }); }); @@ -241,7 +244,7 @@ describe('DataPillar — the CEL hold belongs to the draft, not to the open insp it.each(CLOSERS)('closing the inspector by %s keeps the hold, and the held line names the field', async (_how, close) => { await breakFormula(); close(); - await new Promise((r) => setTimeout(r, 2300)); + await pressStudioSave(); expect(mockClient.save).not.toHaveBeenCalled(); expect(screen.getByTestId('studio-held-message')).toHaveTextContent('Total'); }); @@ -255,8 +258,9 @@ describe('DataPillar — the CEL hold belongs to the draft, not to the open insp const box = label.parentElement!.querySelector('[role="combobox"]') as HTMLTextAreaElement; expect(box.value).toBe('record.est_hours *'); fireEvent.change(box, { target: { value: 'record.est_hours * 2' } }); - await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 4000 }); expect(screen.queryByTestId('studio-held')).toBeNull(); + await pressStudioSave(); + await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 4000 }); }); it('removing the field ends the hold: nothing judged is left in the draft', async () => { @@ -265,6 +269,8 @@ describe('DataPillar — the CEL hold belongs to the draft, not to the open insp // here, see the mock above), and it asks before it removes. fireEvent.click(screen.getByRole('button', { name: 'Remove “Total”' })); fireEvent.click(within(await screen.findByRole('alertdialog')).getByTestId('field-remove-confirm-action')); + confirmSpy.mockReturnValue(true); // Save asks again: the published field leaves. + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 4000 }); const body = (mockClient.save.mock.calls.at(-1) as unknown[] | undefined)?.[2] as { fields: Array<{ name: string }> }; expect(body.fields.map((f) => f.name)).toEqual(['est_hours']); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx index 482ec5c3fdc..2f5b9c7507a 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx @@ -93,6 +93,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; @@ -155,9 +156,9 @@ function heldOptionsLine(label: string): string { /** Add a field on the Form tab and turn it into the given choice type. */ async function addFieldAndType(typeLabel: RegExp): Promise { render( - + - , + , ); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); await addFieldFromFormToolbar(); @@ -207,9 +208,9 @@ describe('Studio data page — an object that already stores an empty select (ob it('an unrelated edit is held and names the stored field; an option on it lets both go', async () => { served = storedEmptySelect; render( - + - , + , ); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotDraftMarks-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotDraftMarks-12725.test.tsx index 914e34f3699..52a43da2b7f 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotDraftMarks-12725.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotDraftMarks-12725.test.tsx @@ -52,6 +52,7 @@ const minutesAgo = (n: number) => new Date(Date.now() - n * 60_000 - 5_000).toIS let draftEnvelope: Record | null = null; const mockClient = { + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn(async () => ({})), list: vi.fn(async (type: string) => type === 'object' @@ -90,6 +91,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { // warmed here so its first load is paid at import, not inside a test's clock. import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; import { ObjectFieldInspector } from '../metadata-admin/inspectors/ObjectFieldInspector'; @@ -125,9 +127,9 @@ function serveDraft(draftChanges?: unknown[]) { /** Render the pillar, open Form, select the field labelled `label`, and return the open rail. */ async function openRail(label: string, name: string): Promise { render( - + - , + , ); fireEvent.click(await screen.findByRole('button', { name: L('engine.studio.data.tab.form') })); const card = (await screen.findByText(label)).closest('[role="button"]') as HTMLElement; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.destructiveChange-34931.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.destructiveChange-34931.test.tsx index d77ba39d51f..2f9f4ed278b 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.destructiveChange-34931.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.destructiveChange-34931.test.tsx @@ -80,6 +80,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; // The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). @@ -101,9 +102,9 @@ const fieldNames = (i: number) => puts[i].body.fields.map((f) => f.name); async function removePlace(first: Response) { answers = [first]; render( - + - , + , ); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); fireEvent.click((await screen.findByText('Place')).closest('.cursor-grab') as HTMLElement); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.draftSavedNamed-28984.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.draftSavedNamed-28984.test.tsx index fbb16792649..aa501197fac 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.draftSavedNamed-28984.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.draftSavedNamed-28984.test.tsx @@ -80,6 +80,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; @@ -106,9 +107,9 @@ function mount(): void { render( <> - + - + , ); } diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.draftUnreadable-29148.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.draftUnreadable-29148.test.tsx index 6f7b160c7a9..cdb957c1989 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.draftUnreadable-29148.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.draftUnreadable-29148.test.tsx @@ -70,6 +70,7 @@ const mockClient = { get: vi.fn(async (type: string, name: string, opts?: { packageId?: string }) => type === 'object_extension' && name === OBJECT && opts?.packageId === PAIR ? srv.publishedExt : null, ), + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn(async (_type: string, _name: string, _body: unknown, _opts?: { packageId?: string }) => ({ ok: true, version: 'v2', @@ -111,6 +112,7 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { }); import { DataPillar, type StudioBaseCustomization } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { t } from '../metadata-admin/i18n'; import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; import { ObjectFieldInspector } from '../metadata-admin/inspectors/ObjectFieldInspector'; @@ -165,9 +167,9 @@ afterEach(() => { async function renderBase(over: Partial = {}) { render( - + - , + , ); await waitFor(() => expect(screen.getByTestId('records-panel')).toBeInTheDocument(), { timeout: 8000 }); } diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx index 79e8be760ff..2c896d86c8c 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx @@ -131,6 +131,7 @@ const mockClient = { return pending ? { item: pending.served, version: 'v7' } : null; }), get: vi.fn(async () => null), + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn(async () => ({ ok: true, version: 'v2', state: 'draft' })), }; @@ -162,6 +163,7 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { // warmed here so its first load is paid at import, not inside a test's clock. import '@objectstack/lint'; import { DataPillar, type StudioBaseCustomization } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { t } from '../metadata-admin/i18n'; import { emitMetadataRefresh } from '../../assistant/assistantBus'; @@ -201,9 +203,9 @@ afterEach(() => { async function openForm(props: { readOnly?: boolean; customization?: StudioBaseCustomization } = {}) { render( - + - , + , ); await waitFor(() => expect(screen.getByTestId('records-panel')).toBeInTheDocument(), { timeout: 8000 }); await userEvent.click(screen.getAllByRole('button', { name: FORM })[0]); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx index 7281e168f9e..be7886b6439 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx @@ -78,6 +78,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; @@ -117,9 +118,9 @@ function lastSentField(name: string): Record | undefined { /** Mount, add a field on the Form tab, and retype it; returns its API name and label. */ async function addFieldAs(typeOption: RegExp): Promise<{ name: string; label: string }> { render( - + - , + , ); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); await addFieldFromFormToolbar(); @@ -202,9 +203,9 @@ describe('Studio data page — Lookup is held until it has a target (objectui#11 describe('Studio data page — complete bodies are sent as before (objectui#11786 controls)', () => { it('a complete edit autosaves, with no held line', async () => { render( - + - , + , ); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); await addFieldFromFormToolbar(); @@ -225,9 +226,9 @@ describe('Studio data page — complete bodies are sent as before (objectui#1178 }, }; render( - + - , + , ); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); await addFieldFromFormToolbar(); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.hiddenSystemFields-11780.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.hiddenSystemFields-11780.test.tsx index dd344bccc7c..e0bc13794b2 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.hiddenSystemFields-11780.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.hiddenSystemFields-11780.test.tsx @@ -122,6 +122,7 @@ const mockClient = { draft: (servedDraft as { item?: unknown } | null)?.item ?? null, })), getDraft: vi.fn(async () => servedDraft), + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn<(type: string, name: string, body: Record, opts?: unknown) => Promise>( async () => ({ ok: true }), ), @@ -201,6 +202,7 @@ vi.mock('@dnd-kit/core', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { SurfaceDeepLinkProvider } from './surfaceDeepLinkChannel'; import { isStudioHiddenSystemField } from './studioHiddenSystemField'; @@ -218,11 +220,11 @@ afterEach(() => { function renderPillar() { return render( - + - , + , ); } 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 8d36801b12b..5526b643a71 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 @@ -121,6 +121,7 @@ const mockClient = { ), get: vi.fn(async () => null), // The pair's action drafts are kept, so a read after a write serves them. + publish: vi.fn(async () => ({})), save: vi.fn(async (type: string, name: string, body: unknown, opts?: { packageId?: string }) => { if (type === 'action' && opts?.packageId === PAIR) srv.pairDrafts[name] = body as Record; return { ok: true, version: 'v2', state: 'draft' }; @@ -176,6 +177,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 { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; import { t, tFormat } from '../metadata-admin/i18n'; @@ -229,9 +231,9 @@ afterEach(() => { async function mountOnActions(props: { readOnly: boolean; customization?: StudioBaseCustomization | null }) { render( - + - , + , ); // The first match is the flat tab (the passthrough menu draws a second). fireEvent.click((await screen.findAllByRole('button', { name: L('engine.studio.data.tab.actions') }, { timeout: 8000 }))[0]); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.panelGate.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.panelGate.test.tsx index aeeebea18f5..29ea92c5076 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.panelGate.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.panelGate.test.tsx @@ -45,6 +45,7 @@ const objectDef = { }; const mockClient = { + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn(async () => ({})), list: vi.fn(async () => [{ name: 'showcase_task', label: 'Task' }]), listDrafts: vi.fn(async () => []), @@ -98,6 +99,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; import { __setCelFormulaLoader } from '../metadata-admin/celAuthoring'; @@ -135,9 +137,9 @@ afterEach(() => { /** Open the pillar's Rules tab and put the selected rule's guard into raw CEL. */ async function openRuleGuard() { render( - + - , + , ); // objectui#12450 — the flat tab; the passthrough menu draws the folded // entry as a second button of the same name. @@ -146,32 +148,32 @@ async function openRuleGuard() { return screen.getAllByRole('combobox').find((el) => el.tagName === 'TEXTAREA') as HTMLTextAreaElement; } -// objectui#5813 retired the 保存草稿 button for debounced AUTO-save; the gate -// now guards the TIMER (objectui#4306's own rule), so the observable is -// client.save itself. -describe('DataPillar — auto-save is gated on the validations panel’s CEL verdict (#4527/#5813)', () => { +// objectstack#36511 — the gate guards the top bar's Save (objectui#4306's own +// rule), so the observable is client.save itself, after Save is pressed. +describe('DataPillar — Save is gated on the validations panel’s CEL verdict (#4527/#36511)', () => { it('refuses a rule guard that does not parse', async () => { const box = await openRuleGuard(); - // A valid guard first — the auto-save fires; pins that a good guard never - // blocks, and clears the dirty window. + // A valid guard first — Save sends it; pins that a good guard never blocks. fireEvent.change(box, { target: { value: "record.status == 'open'" } }); + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 4000 }); mockClient.save.mockClear(); fireEvent.change(box, { target: { value: 'record.status ==' } }); - await new Promise((r) => setTimeout(r, 2300)); + await pressStudioSave(); expect(mockClient.save).not.toHaveBeenCalled(); }); - it('re-arms the auto-save once the guard parses again', async () => { + it('re-arms the Save once the guard parses again', async () => { const box = await openRuleGuard(); fireEvent.change(box, { target: { value: 'record.status ==' } }); - await new Promise((r) => setTimeout(r, 2300)); + await pressStudioSave(); expect(mockClient.save).not.toHaveBeenCalled(); fireEvent.change(box, { target: { value: "record.status == 'open'" } }); + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 4000 }); }); @@ -183,11 +185,11 @@ describe('DataPillar — auto-save is gated on the validations panel’s CEL ver const box = await openRuleGuard(); fireEvent.change(box, { target: { value: 'record.status ==' } }); - await new Promise((r) => setTimeout(r, 2300)); + await pressStudioSave(); expect(mockClient.save).not.toHaveBeenCalled(); fireEvent.click(screen.getByRole('button', { name: 'Form' })); - await new Promise((r) => setTimeout(r, 2300)); + await pressStudioSave(); expect(mockClient.save).not.toHaveBeenCalled(); expect(screen.getByTestId('studio-held-message')).toHaveTextContent('Rule A'); }); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.panelHold-27629.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.panelHold-27629.test.tsx index caf692cc528..e1ea16f5e7a 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.panelHold-27629.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.panelHold-27629.test.tsx @@ -54,6 +54,7 @@ const objectDef = { }; const mockClient: Record & { save: ReturnType } = { + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn(async () => ({})), // The action inspector's field pickers read the object through the preview-draft door. get: vi.fn(async () => objectDef), @@ -104,6 +105,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; import { __setCelFormulaLoader } from '../metadata-admin/celAuthoring'; @@ -137,17 +139,17 @@ afterEach(() => { mockClient.save.mockClear(); }); -/** Past the autosave's 1.5 s debounce. */ -const outlastDebounce = () => new Promise((r) => setTimeout(r, 2300)); +/** The top bar's Save pressed (objectstack#36511): a held edit sends nothing. */ +const outlastDebounce = pressStudioSave; const rawEditorIn = (root: HTMLElement) => within(root).getAllByRole('combobox').find((el) => el.tagName === 'TEXTAREA') as HTMLTextAreaElement; function mount() { render( - + - , + , ); } @@ -198,6 +200,7 @@ describe('DataPillar — a rule guard that does not parse holds with the draft ( }); expect(box.value).toBe('record.status =='); fireEvent.change(box, { target: { value: "record.status == 'open'" } }); + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 4000 }); expect(screen.queryByTestId('studio-held')).toBeNull(); }); @@ -212,6 +215,7 @@ describe('DataPillar — a rule guard that does not parse holds with the draft ( fireEvent.click(screen.getByTestId('data-tab-flat-rules')); const detail = (await screen.findAllByRole('button', { name: 'Delete' })).at(-1)!; fireEvent.click(detail); + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 4000 }); const body = (mockClient.save.mock.calls.at(-1) as unknown[] | undefined)?.[2] as { validations?: unknown[] }; expect(body.validations ?? []).toEqual([]); @@ -248,6 +252,7 @@ describe('DataPillar — an action predicate that does not parse holds with the }); expect(box.value).toBe('record.status =='); fireEvent.change(box, { target: { value: "record.status == 'open'" } }); + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 4000 }); expect(screen.queryByTestId('studio-held')).toBeNull(); }); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx index 8d1b866294f..cc577ba0c7e 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx @@ -143,6 +143,7 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromGrid } from './__tests__/dataPillarAddField'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; @@ -161,9 +162,9 @@ afterEach(() => { function renderData() { render( - + - , + , ); } diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.railSwitchFlush-27511.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.railSwitchFlush-27511.test.tsx index 0166a4715a9..669fd5e8637 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.railSwitchFlush-27511.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.railSwitchFlush-27511.test.tsx @@ -68,6 +68,7 @@ const mockClient = vi.hoisted(() => ({ 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 }); }), + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn(async (_type: string, name: string, item: unknown) => { const body = JSON.parse(JSON.stringify(item)) as Record; server.saves.push({ name, body }); @@ -117,6 +118,7 @@ vi.mock('sonner', () => ({ })); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromGrid } from './__tests__/dataPillarAddField'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { readFields } from '../metadata-admin/previews/object-fields-io'; @@ -173,9 +175,9 @@ const fieldCount = () => screen.getByText(/^\d+ fields?( \(\+\d+ system\))?$/); async function openTask(): Promise { render( - + - , + , ); await waitFor(() => expect(fieldCount()).toHaveTextContent('2 fields'), SLOW); } diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.recordsTab-34794.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.recordsTab-34794.test.tsx index f0621a76c42..5cd48746db2 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.recordsTab-34794.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.recordsTab-34794.test.tsx @@ -53,6 +53,7 @@ const mockClient = { listDrafts: vi.fn(async () => []), layered: vi.fn(async () => ({ effective: SERVED, code: AUTHORED })), getDraft: vi.fn(async () => null), + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn(async () => ({})), }; @@ -92,6 +93,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { // load is paid here, at collection, never inside a case's clock (`check:test-source-alias`). import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { t } from '../metadata-admin/i18n'; import { registerMetadataInspector } from '../metadata-admin/inspector-registry'; import { ObjectFieldInspector } from '../metadata-admin/inspectors/ObjectFieldInspector'; @@ -124,9 +126,9 @@ afterEach(() => { async function renderGrid(props: { readOnly?: boolean } = {}) { render( - + - , + , ); await waitFor(() => expect(document.querySelector('thead th[data-column-key="title"]')).not.toBeNull(), { timeout: 8000, diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx index 2fd902cfe74..3228b3d77ff 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx @@ -111,6 +111,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; @@ -138,9 +139,9 @@ async function outlastDebounce(): Promise { async function mountOnView(def: Record, tabKey: string): Promise { objectDef = def; render( - + - , + , ); // The first match is the flat tab (the passthrough menu draws a second). fireEvent.click((await screen.findAllByRole('button', { name: L(tabKey) }))[0]); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx index c4096ac4c24..713fecc9a04 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx @@ -68,6 +68,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; @@ -109,9 +110,9 @@ function lastSentField(name: string): Record | undefined { */ async function addRollup(): Promise<{ name: string; label: string }> { render( - + - , + , ); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); await addFieldFromFormToolbar(undefined, { label: 'Child Count', type: /^Rollup$/ }); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.validationVerdictHold-27644.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.validationVerdictHold-27644.test.tsx index e0e707294a0..9db8542eb3a 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.validationVerdictHold-27644.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.validationVerdictHold-27644.test.tsx @@ -71,6 +71,7 @@ let server: Server; const PUBLISHED = objectWith(ACCEPTED); const mockClient: Record = { + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn(async (_type: string, _name: string, body: Record) => { const copy = JSON.parse(JSON.stringify(body)) as Record; server.sent.push(copy); @@ -130,6 +131,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { }); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; import { registerBuiltinInspectors } from '../metadata-admin/inspectors'; import { __setCelFormulaLoader } from '../metadata-admin/celAuthoring'; @@ -167,9 +169,9 @@ const pause = (ms = 2500) => new Promise((r) => setTimeout(r, ms)); function mount(draft: Record | null) { server = { draft, sent: [] }; render( - + - , + , ); } diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.saveBar-36511.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.saveBar-36511.test.tsx index f798f9003c2..2601d7284a5 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.saveBar-36511.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.saveBar-36511.test.tsx @@ -148,10 +148,13 @@ describe('the Studio top bar: Save where Publish was, Changes and Publish for dr const cancel = within(header).getByTestId('studio-cancel'); expect(within(header).queryByRole('button', { name: CHANGES })).toBeNull(); expect(within(header).queryByRole('button', { name: PUBLISH })).toBeNull(); - // Cancel, then Save, the last of the right column's actions. + // Cancel, then Save: the last of the right column's actions, where Publish + // was; only the slot's show/hide icon follows it, as it followed Publish. expect(cancel.compareDocumentPosition(save) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); const column = save.parentElement as HTMLElement; - const actions = within(column).getAllByRole('button'); + const actions = within(column) + .getAllByRole('button') + .filter((b) => b.getAttribute('data-testid') !== 'studio-slot-toggle'); expect(actions[actions.length - 1]).toBe(save); expect(writes).toEqual([]); }); diff --git a/ui/packages/app-shell/src/views/studio-design/__tests__/studioSaveHarness.tsx b/ui/packages/app-shell/src/views/studio-design/__tests__/studioSaveHarness.tsx index 545995f7b79..62bb732190b 100644 --- a/ui/packages/app-shell/src/views/studio-design/__tests__/studioSaveHarness.tsx +++ b/ui/packages/app-shell/src/views/studio-design/__tests__/studioSaveHarness.tsx @@ -9,7 +9,8 @@ */ import * as React from 'react'; -import { act, fireEvent, screen } from '@testing-library/react'; +import { expect } from 'vitest'; +import { act, fireEvent, screen, waitFor } from '@testing-library/react'; import { StudioSaveControls, StudioSaveProvider, @@ -28,12 +29,21 @@ export function StudioSaveHarness({ children, locale = 'en' }: { children: React ); } -/** Press the top bar's Save once it is drawn (the page holds an unsaved edit). */ -export async function pressStudioSave(): Promise { +/** + * Press the top bar's Save once it is drawn (the page holds an unsaved edit), + * and, unless `settle` is false, wait for that Save to end: its writes sent, + * or refused before any. `settle: false` for a Save that stops on a question + * the case answers (the draft-version conflict). + */ +export async function pressStudioSave({ settle = true }: { settle?: boolean } = {}): Promise { const save = await screen.findByTestId('studio-save', undefined, { timeout: 4000 }); await act(async () => { fireEvent.click(save); }); + if (!settle) return; + await waitFor(() => expect(screen.queryByTestId('studio-save')?.hasAttribute('disabled') ?? false).toBe(false), { + timeout: 4000, + }); } /** Press the top bar's Cancel once it is drawn. */ diff --git a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx index 849382685c6..a16d4f84b13 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx @@ -18,7 +18,10 @@ * stop the others: the toast names each refused item with its reason and * lists the items that were saved. * - A buffer that holds an edit it cannot send yet (`held`) refuses the whole - * Save before anything is written, naming what it needs. + * Save before anything is written, naming what it needs. The held state is + * read once the expression checks of the last keystroke have run (they run + * {@link LINT_DEBOUNCE_MS} after it): a Save pressed at once never sends a + * formula its check has not judged yet (objectui#4306). * - Cancel drops every dirty buffer's edits: each goes back to what the * server holds. */ @@ -30,6 +33,10 @@ import { cn } from '@object-ui/components'; import type { MetadataClient } from '@object-ui/data-objectstack'; import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; import { t, tFormat } from '../metadata-admin/i18n.js'; +import { LINT_DEBOUNCE_MS } from '../metadata-admin/CelPredicateField.js'; + +/** Past the editors' expression check of the last keystroke, and its report. */ +const VERDICT_SETTLE_MS = LINT_DEBOUNCE_MS + 50; /** What one buffer's Save did. */ export type StudioSaveResult = @@ -137,15 +144,18 @@ export function useStudioSaveCoordinator(locale: string): StudioSaveCoordinator ); const save = React.useCallback(async () => { if (savingRef.current) return; + if (dirtyEntries().length === 0) return; + savingRef.current = true; + setSaving(true); + await new Promise((settled) => setTimeout(settled, VERDICT_SETTLE_MS)); const entries = dirtyEntries(); - if (entries.length === 0) return; const held = entries.find((e) => e.held !== null); - if (held) { - toast.error(tFormat('engine.studio.save.held', locale, { clause: held.held ?? '' })); + if (held || entries.length === 0) { + savingRef.current = false; + setSaving(false); + if (held) toast.error(tFormat('engine.studio.save.held', locale, { clause: held.held ?? '' })); return; } - savingRef.current = true; - setSaving(true); const saved: string[] = []; const refused: Array<{ label: string; reason: string }> = []; try { From 7e799ec7714d5f46f640518454092e161b885458 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 23:39:40 +0000 Subject: [PATCH 05/25] test(studio): Data pillar pins press the top bar's Save Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .../DataPillar.actionRefusal-26736.test.tsx | 19 ++++++-------- .../DataPillar.addFieldPopover-12516.test.tsx | 8 +++--- .../DataPillar.authorRefusal-11785.test.tsx | 14 +++++------ ...Pillar.choiceWithoutOptions-11253.test.tsx | 23 ++++++++--------- ...ataPillar.copilotDraftMarks-12725.test.tsx | 7 +++--- ...ataPillar.destructiveChange-34931.test.tsx | 10 +++++--- .../DataPillar.heldIncomplete-11786.test.tsx | 25 +++++++++---------- ...taPillar.hiddenSystemFields-11780.test.tsx | 2 ++ ...illar.picklistServedOptions-10202.test.tsx | 14 ++++------- .../DataPillar.recordsTab-34794.test.tsx | 1 + .../DataPillar.showMeFocus-26730.test.tsx | 13 +++------- .../DataPillar.summaryHeld-27461.test.tsx | 16 +++++------- 12 files changed, 67 insertions(+), 85 deletions(-) diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx index e5d77545c73..a4419c4f711 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx @@ -63,6 +63,8 @@ function serverIssues(body: Record): Array<{ path: string; mess } const fetchImpl = vi.fn(async (_url: string, init?: RequestInit) => { + // objectstack#36511 — the Save's own publish of the item, and a refused one's discard. + if (init?.method === 'POST' || init?.method === 'DELETE') return new Response('{"success":true}', { status: 200 }); if (init?.method === 'PUT') { const body = JSON.parse(String(init.body)) as Record; puts.push(body); @@ -145,13 +147,6 @@ afterEach(() => { const L = (key: string) => t(key, 'en'); -/** Past the autosave's 1.5 s debounce. */ -async function outlastDebounce(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); -} - async function mountOnView(def: Record, tabKey: string): Promise { objectDef = def; render( @@ -180,7 +175,7 @@ describe('Studio data page — a refused action save is shown at the action, and // Any edit: the label of the first action, which the list selects. const labelInput = (await screen.findByText(L('engine.inspector.action.label'), { selector: 'label' })).parentElement!.querySelector('input')!; fireEvent.change(labelInput, { target: { value: 'Archive now' } }); - await outlastDebounce(); + await pressStudioSave(); expect(puts).toHaveLength(1); // The refusal names the action, not "the server refused this draft". @@ -199,7 +194,7 @@ describe('Studio data page — a refused action save is shown at the action, and // and clear the flat key; the next autosave is accepted, the strip goes. fireEvent.click(expose); fireEvent.click(expose); - await outlastDebounce(); + await pressStudioSave(); expect(puts).toHaveLength(2); expect(lastSentAction('showcase_task_send')).not.toHaveProperty('aiExposed'); expect(serverIssues(puts[1])).toEqual([]); @@ -212,11 +207,11 @@ describe('Studio data page — a Type switch is held until its input is filled ( await mountOnView({ name: 'showcase_task', label: 'Task', fields: [{ name: 'title', label: 'Title', type: 'text' }], actions: [SEND] }, 'engine.studio.data.tab.actions'); await pick(L('engine.inspector.action.type'), L('engine.inspector.action.type.api')); - await outlastDebounce(); + await pressStudioSave(); expect(puts, 'an api action with no endpoint is held, not sent').toEqual([]); expect(screen.queryByTestId('studio-refusal')).toBeNull(); expect(within(await screen.findByTestId('studio-held')).getByTestId('studio-held-message')).toHaveTextContent( - tFormat('engine.studio.held.line', 'en', { + tFormat('engine.studio.held.lineExplicit', 'en', { clause: tFormat('engine.studio.held.actionNeedsInput', 'en', { input: L('engine.inspector.action.target.api.label'), action: 'Send', @@ -226,7 +221,7 @@ describe('Studio data page — a Type switch is held until its input is filled ( const endpoint = screen.getByText(`${L('engine.inspector.action.target.api.label')} *`, { selector: 'label' }).parentElement!.querySelector('input')!; fireEvent.change(endpoint, { target: { value: '/api/v1/send' } }); - await outlastDebounce(); + await pressStudioSave(); expect(puts).toHaveLength(1); // The body the script had is gone with the switch, so the server accepts it. expect(lastSentAction('showcase_task_send')).not.toHaveProperty('body'); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx index 44b130c252a..f347132120d 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx @@ -117,6 +117,7 @@ const toolbarAddField = () => within(screen.getByTestId('form-toolbar')).getByRo /** The fields of the latest object draft the pillar saved. */ async function savedFields(): Promise>> { + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 8000 }); const calls = mockClient.save.mock.calls as unknown as Array<[string, string, Record]>; const body = calls[calls.length - 1][2]; @@ -207,11 +208,8 @@ describe('Data pillar — Add field asks for the label and type first (objectui# expect(within(inspector).getByText('full_name')).toBeInTheDocument(); await addFieldFromFormToolbar(undefined, { label: 'ヘルススコア', apiName: 'health_score' }); await waitFor(() => expect(within(screen.getByTestId('data-field-inspector')).getByText('health_score')).toBeInTheDocument()); - const fields = await waitFor(async () => { - const f = await savedFields(); - expect(Object.keys(f)).toEqual(['name', 'full_name', 'health_score']); - return f; - }, { timeout: 8000 }); + const fields = await savedFields(); + expect(Object.keys(fields)).toEqual(['name', 'full_name', 'health_score']); expect(fields.full_name).toMatchObject({ type: 'text', label: 'Name' }); expect(fields.health_score).toMatchObject({ type: 'text', label: 'ヘルススコア' }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx index 16a72dd71e6..319ab508fda 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx @@ -41,6 +41,8 @@ const objectDef = { const puts: unknown[] = []; const fetchImpl = vi.fn(async (_url: string, init?: RequestInit) => { + // objectstack#36511 — the Save's own publish of the item, and a refused one's discard. + if (init?.method === 'POST' || init?.method === 'DELETE') return new Response('{"success":true}', { status: 200 }); if (init?.method === 'PUT') { puts.push(JSON.parse(String(init.body))); return new Response(JSON.stringify({ success: true }), { @@ -113,17 +115,15 @@ describe('Studio data page — a held Picklist reads as a sentence (objectui#117 await userEvent.click(controlUnder('Type')); await userEvent.click(await screen.findByRole('option', { name: /^Picklist$/ })); - // Past the autosave's 1.5 s debounce: the guard holds the save. - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); + // Save pressed (objectstack#36511): the guard holds it. + await pressStudioSave(); expect(puts, 'the guard must hold this save').toEqual([]); expect(screen.queryByTestId('studio-refusal'), 'held, not refused (objectui#11786)').toBeNull(); const held = await screen.findByTestId('studio-held'); const message = within(held).getByTestId('studio-held-message'); expect(message).toHaveTextContent( - tFormat('engine.studio.held.line', 'en', { + tFormat('engine.studio.held.lineExplicit', 'en', { clause: tFormat('engine.studio.held.needsOptions', 'en', { field: label }), }), ); @@ -145,9 +145,7 @@ describe('Studio data page — a held Picklist reads as a sentence (objectui#117 const apiName = (controlUnder('API name') as HTMLInputElement).value; await userEvent.click(controlUnder('Type')); await userEvent.click(await screen.findByRole('option', { name: /^Picklist$/ })); - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); + await pressStudioSave(); const strip = await screen.findByTestId('studio-held'); // The rail's own header close (the field inspector inside carries another). diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx index 2f5b9c7507a..7ac3f2de38b 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx @@ -18,7 +18,7 @@ * request carries a choice type without options. * * The held save must also say why on screen, naming the field, and adding one - * option must let the next autosave go (the control that proves the pillar is + * option must let the next Save go (the control that proves the pillar is * not simply refusing every select). * * Since objectui#11786 the pillar asks the same guard before sending, so "held" @@ -57,6 +57,8 @@ let served: Record = objectDef; const puts: Array<{ url: string; body: Record }> = []; const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => { + // objectstack#36511 — the Save's own publish of the item, and a refused one's discard. + if (init?.method === 'POST' || init?.method === 'DELETE') return new Response('{"success":true}', { status: 200 }); if (init?.method === 'PUT') { puts.push({ url, body: JSON.parse(String(init.body)) as Record }); return new Response(JSON.stringify({ success: true }), { @@ -133,13 +135,6 @@ function choiceWithoutOptions(): WireField[] { ); } -/** Past the autosave's 1.5 s debounce. */ -async function outlastDebounce(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); -} - /** The inspector control under a visible label. */ function controlUnder(label: string): HTMLElement { const lab = screen.getByText(label, { selector: 'label' }); @@ -148,7 +143,7 @@ function controlUnder(label: string): HTMLElement { /** The held line naming `label`'s missing options (objectui#11786). */ function heldOptionsLine(label: string): string { - return tFormat('engine.studio.held.line', 'en', { + return tFormat('engine.studio.held.lineExplicit', 'en', { clause: tFormat('engine.studio.held.needsOptions', 'en', { field: label }), }); } @@ -175,18 +170,19 @@ describe('Studio data page — a new choice field is not sent without options (o ['select', /^Picklist$/], ['radio', /^Radio$/], ] as const) { - it(`add a field, type it \`${type}\`, wait out the autosave: no request carries it without options`, async () => { + it(`add a field, type it \`${type}\`, press Save: no request carries it without options`, async () => { const fieldName = await addFieldAndType(typeLabel); const fieldLabel = (controlUnder('Label') as HTMLInputElement).value; - await outlastDebounce(); + await pressStudioSave(); expect(choiceWithoutOptions()).toEqual([]); // The held save says why, and names the field. expect(await screen.findByTestId('studio-held-message')).toHaveTextContent(heldOptionsLine(fieldLabel)); - // CONTROL: one option lets the next autosave go, and the banner clears. + // CONTROL: one option lets the next Save go, and the banner clears. const before = puts.length; fireEvent.change(screen.getByPlaceholderText('value'), { target: { value: 'open' } }); + await pressStudioSave(); await waitFor(() => expect(puts.length).toBeGreaterThan(before), { timeout: 4000 }); const sent = wireFields(puts[puts.length - 1].body).find((f) => f.name === fieldName); expect(sent?.type).toBe(type); @@ -219,7 +215,7 @@ describe('Studio data page — an object that already stores an empty select (ob const labelBox = controlUnder('Label') as HTMLInputElement; fireEvent.change(labelBox, { target: { value: 'Headline' } }); fireEvent.blur(labelBox); - await outlastDebounce(); + await pressStudioSave(); // Held: nothing reached the wire, and the banner names the STORED field. expect(puts).toEqual([]); @@ -228,6 +224,7 @@ describe('Studio data page — an object that already stores an empty select (ob // Cleared on screen: the stored field's own inspector carries the editor. await selectCard('Status'); fireEvent.change(screen.getByPlaceholderText('value'), { target: { value: 'open' } }); + await pressStudioSave(); await waitFor(() => expect(puts.length).toBe(1), { timeout: 4000 }); const sent = wireFields(puts[0].body); expect(sent.find((f) => f.name === 'status')?.options).toEqual([expect.objectContaining({ value: 'open' })]); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotDraftMarks-12725.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotDraftMarks-12725.test.tsx index 52a43da2b7f..41b2049d5be 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotDraftMarks-12725.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.copilotDraftMarks-12725.test.tsx @@ -261,6 +261,7 @@ describe('Data pillar field properties — a copilot write while the field is op const label = within(rail).getByTestId('field-label-input'); fireEvent.change(label, { target: { value: 'Renewal total' } }); fireEvent.blur(label); + await pressStudioSave({ settle: false }); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 8000 }); const before = draftReadsOf('showcase_task'); @@ -278,10 +279,10 @@ describe('Data pillar field properties — a copilot write while the field is op await act(async () => { landSave(); }); - // Only the pillar's load installs the drafted field; the save's own - // verdict re-read (the other draft read here) installs no buffer. + // The pillar's load, once, installs the drafted field (objectstack#36511: + // the Save publishes, so no draft verdict is re-read after it). expect(await screen.findByText('Impact scope', undefined, { timeout: 8000 })).toBeInTheDocument(); - expect(draftReadsOf('showcase_task')).toBe(before + 2); + expect(draftReadsOf('showcase_task')).toBe(before + 1); }); it('CONTROL: a pulse re-reads the open object only, never another one in the rail', async () => { diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.destructiveChange-34931.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.destructiveChange-34931.test.tsx index 2f9f4ed278b..c51c9389317 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.destructiveChange-34931.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.destructiveChange-34931.test.tsx @@ -36,6 +36,8 @@ const refused = (status: number, code: string, message: string) => const puts: Array<{ url: string; body: { fields: Array<{ name: string }> } }> = []; let answers: Response[] = []; const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => { + // objectstack#36511 — the Save's own publish of the item, and a refused one's discard. + if (init?.method === 'POST' || init?.method === 'DELETE') return new Response('{"success":true}', { status: 200 }); if (init?.method !== 'PUT') return json(404, null); puts.push({ url, body: JSON.parse(String(init.body)) }); return answers.shift() ?? json(200, { success: true }); @@ -98,7 +100,7 @@ afterEach(() => { const card = (label: string) => screen.queryByText(label)?.closest('.cursor-grab') ?? null; const fieldNames = (i: number) => puts[i].body.fields.map((f) => f.name); -/** Open the Form tab, remove Place, and let the autosave send it. */ +/** Open the Form tab, remove Place, and Save it, agreeing to Save's question (objectstack#36511). */ async function removePlace(first: Response) { answers = [first]; render( @@ -110,6 +112,8 @@ async function removePlace(first: Response) { fireEvent.click((await screen.findByText('Place')).closest('.cursor-grab') as HTMLElement); fireEvent.click(await screen.findByRole('button', { name: 'Remove “Place”' })); fireEvent.click(within(await screen.findByRole('alertdialog')).getByTestId('field-remove-confirm-action')); + window.confirm = vi.fn(() => true); + await pressStudioSave(); await waitFor(() => expect(puts).toHaveLength(1), { timeout: 4000 }); expect(fieldNames(0)).toEqual(['title']); } @@ -138,7 +142,8 @@ describe('Data pillar — a destructive object draft save is confirmed, not dead await removePlace(refused(409, 'DESTRUCTIVE_CHANGE', LOST)); fireEvent.click(within(await screen.findByTestId('object-destructive-confirm')).getByTestId('object-destructive-keep')); await waitFor(() => expect(card('Place')).not.toBeNull()); - await new Promise((r) => setTimeout(r, 2300)); + // Nothing is left to save: the page is the stored object again. + expect(screen.queryByTestId('studio-save')).toBeNull(); expect(puts).toHaveLength(1); expect(screen.queryByTestId('object-destructive-confirm')).toBeNull(); }); @@ -147,7 +152,6 @@ describe('Data pillar — a destructive object draft save is confirmed, not dead await removePlace(refused(422, 'INVALID_METADATA', 'Field place is invalid')); expect(await screen.findByTestId('studio-refusal')).toBeInTheDocument(); expect(screen.queryByTestId('object-destructive-confirm')).toBeNull(); - await new Promise((r) => setTimeout(r, 2300)); expect(puts).toHaveLength(1); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx index be7886b6439..888e41118e3 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx @@ -13,7 +13,7 @@ * Now the pillar asks the same guard BEFORE sending: such an edit stays dirty * and unsent, the inspector hints the input it needs, a neutral line names it * (with "Show me" when that input is not the one open), and completing it lets - * the next autosave go. Errors stay for what the author finished: a server + * the next Save go. Errors stay for what the author finished: a server * refusal of a complete body still shows objectui#11785's red strip. * * The client is a real `MetadataClient`, so the door that runs the guard is the @@ -41,6 +41,8 @@ const puts: Array> = []; let refuseWith: Record | null = null; const fetchImpl = vi.fn(async (_url: string, init?: RequestInit) => { + // objectstack#36511 — the Save's own publish of the item, and a refused one's discard. + if (init?.method === 'POST' || init?.method === 'DELETE') return new Response('{"success":true}', { status: 200 }); if (init?.method === 'PUT') { puts.push(JSON.parse(String(init.body)) as Record); if (refuseWith) { @@ -94,13 +96,6 @@ afterEach(() => { fetchImpl.mockClear(); }); -/** Past the autosave's 1.5 s debounce. */ -async function outlastDebounce(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); -} - /** The inspector control under a visible label. */ function controlUnder(label: string): HTMLElement { const lab = screen.getByText(label, { selector: 'label' }); @@ -133,12 +128,12 @@ async function addFieldAs(typeOption: RegExp): Promise<{ name: string; label: st return { name, label }; } -const heldLine = (clause: string) => tFormat('engine.studio.held.line', 'en', { clause }); +const heldLine = (clause: string) => tFormat('engine.studio.held.lineExplicit', 'en', { clause }); describe('Studio data page — Picklist is held until it has an option (objectui#11786)', () => { it('sends no save and shows no red strip; the options editor carries the hint; one option lets the save go', async () => { const { name, label } = await addFieldAs(/^Picklist$/); - await outlastDebounce(); + await pressStudioSave(); expect(puts, 'an incomplete Picklist is not sent').toEqual([]); expect(screen.queryByTestId('studio-refusal'), 'no red strip on the normal path').toBeNull(); @@ -151,6 +146,7 @@ describe('Studio data page — Picklist is held until it has an option (objectui expect(screen.getByTestId('field-held-hint')).toHaveTextContent(t('designer.field.hint.addOption', 'en')); fireEvent.change(screen.getByPlaceholderText(t('designer.field.optValue', 'en')), { target: { value: 'open' } }); + await pressStudioSave(); await waitFor(() => expect(puts.length).toBe(1), { timeout: 4000 }); expect(lastSentField(name)).toEqual( expect.objectContaining({ type: 'select', options: [expect.objectContaining({ value: 'open' })] }), @@ -162,7 +158,7 @@ describe('Studio data page — Picklist is held until it has an option (objectui it('"Show me" on the line reopens the held field once its inspector is closed', async () => { const { name } = await addFieldAs(/^Picklist$/); - await outlastDebounce(); + await pressStudioSave(); const railHeader = screen.getByText(t('engine.studio.data.fieldProps', 'en')).closest('header') as HTMLElement; fireEvent.click(within(railHeader).getByRole('button', { name: t('engine.studio.close', 'en') })); @@ -179,7 +175,7 @@ describe('Studio data page — Picklist is held until it has an option (objectui describe('Studio data page — Lookup is held until it has a target (objectui#11786)', () => { it('sends no save and shows no red strip; the related-object picker carries the hint; a target lets the save go', async () => { const { name, label } = await addFieldAs(/^Lookup$/); - await outlastDebounce(); + await pressStudioSave(); expect(puts, 'a Lookup with no target is not sent').toEqual([]); expect(screen.queryByTestId('studio-refusal')).toBeNull(); @@ -193,6 +189,7 @@ describe('Studio data page — Lookup is held until it has a target (objectui#11 await userEvent.click(target); await userEvent.type(target, 'showcase_task'); await userEvent.keyboard('{Enter}'); + await pressStudioSave(); await waitFor(() => expect(puts.length).toBe(1), { timeout: 4000 }); expect(lastSentField(name)).toEqual(expect.objectContaining({ type: 'lookup', reference: 'showcase_task' })); await waitFor(() => expect(screen.queryByTestId('studio-held')).toBeNull()); @@ -201,7 +198,7 @@ describe('Studio data page — Lookup is held until it has a target (objectui#11 }); describe('Studio data page — complete bodies are sent as before (objectui#11786 controls)', () => { - it('a complete edit autosaves, with no held line', async () => { + it('a complete edit is sent by Save, with no held line', async () => { render( @@ -209,6 +206,7 @@ describe('Studio data page — complete bodies are sent as before (objectui#1178 ); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); await addFieldFromFormToolbar(); + await pressStudioSave(); await waitFor(() => expect(puts.length).toBe(1), { timeout: 4000 }); expect(screen.queryByTestId('studio-held')).toBeNull(); }); @@ -232,6 +230,7 @@ describe('Studio data page — complete bodies are sent as before (objectui#1178 ); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); await addFieldFromFormToolbar(); + await pressStudioSave(); const strip = await screen.findByTestId('studio-refusal', undefined, { timeout: 4000 }); expect(puts.length).toBe(1); expect(within(strip).getByTestId('studio-refusal-message')).toHaveTextContent( diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.hiddenSystemFields-11780.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.hiddenSystemFields-11780.test.tsx index e0bc13794b2..b60d44bb695 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.hiddenSystemFields-11780.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.hiddenSystemFields-11780.test.tsx @@ -294,6 +294,7 @@ describe.each(CASES)('Data pillar on an object with $title (objectui#11780)', ({ act(() => dnd.onDragEnd!({ active: { id: 'f:industry' }, over: { id: 'f:name' } })); // The auto-save sends the draft the designer committed. + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 5000 }); const body = mockClient.save.mock.calls.at(-1)![2] as { fields: Record> }; @@ -320,6 +321,7 @@ describe.each(CASES)('Data pillar on an object with $title (objectui#11780)', ({ expect(seenColumns[seenColumns.length - 1]).toBe(before); // The edit was real: the draft the pillar saves carries the new label. + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 5000 }); expect(mockClient.save.mock.calls.at(-1)![2].label).toBe('Account (renamed)'); }); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx index cc577ba0c7e..faaceaa0814 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx @@ -71,6 +71,8 @@ function doorRefusal(body: Row): string[] { const puts: Array<{ body: Row; status: number }> = []; const fetchImpl = vi.fn(async (_url: string, init?: RequestInit) => { + // objectstack#36511 — the Save's own publish of the item, and a refused one's discard. + if (init?.method === 'POST' || init?.method === 'DELETE') return new Response('{"success":true}', { status: 200 }); if (init?.method === 'PUT') { const body = JSON.parse(String(init.body)) as Row; const refused = doorRefusal(body); @@ -170,13 +172,6 @@ function renderData() { const fieldCountShown = () => screen.getByText(/^\d+ fields$/).textContent; -/** Past the autosave's 1.5 s debounce. */ -async function outlastDebounce(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); -} - /** What every PUT the page sent carried for `tier` and `status`. */ function sentFields(): Array<{ tier: unknown; status: unknown; status_code: number }> { return puts.map((p) => { @@ -188,11 +183,11 @@ function sentFields(): Array<{ tier: unknown; status: unknown; status_code: numb const SERVED_STATUS = JSON.stringify((SERVED.fields as Record).status); describe('Studio data page — a picklist-bound field is saved without its served options (objectui#10202)', () => { - it('the draft autosave (an added field) sends no bound field with `options`, and the inline select byte-identical', async () => { + it('the Save (an added field) sends no bound field with `options`, and the inline select byte-identical', async () => { renderData(); await waitFor(() => expect(fieldCountShown()).toBe('3 fields'), { timeout: 8000 }); await addFieldFromGrid(); - await outlastDebounce(); + await pressStudioSave(); await waitFor(() => expect(puts.length).toBeGreaterThan(0), { timeout: 4000 }); for (const sent of sentFields()) { @@ -206,6 +201,7 @@ describe('Studio data page — a picklist-bound field is saved without its serve renderData(); await waitFor(() => expect(fieldCountShown()).toBe('3 fields'), { timeout: 8000 }); fireEvent.click(await screen.findByRole('button', { name: 'Reverse columns' }, { timeout: 8000 })); + await pressStudioSave(); await waitFor(() => expect(puts.length).toBeGreaterThan(0), { timeout: 4000 }); const first = puts[0]; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.recordsTab-34794.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.recordsTab-34794.test.tsx index 5cd48746db2..0a4fdf1ccc0 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.recordsTab-34794.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.recordsTab-34794.test.tsx @@ -161,6 +161,7 @@ describe('Data pillar Records tab (objectstack#34794)', () => { expect(screen.getByTestId('grid-add-column')).toBeInTheDocument(); await userEvent.click(toolbarAdd); await completeAddFieldPopover({ label: 'Agenda' }); + await pressStudioSave(); await waitFor(() => expect(mockClient.save).toHaveBeenCalled(), { timeout: 8000 }); const calls = mockClient.save.mock.calls as unknown as Array<[string, string, { fields: Record }]>; expect(Object.keys(calls.at(-1)![2].fields)).toContain('agenda'); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx index 3228b3d77ff..4378af843bd 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx @@ -45,6 +45,8 @@ function serverIssues(body: Record): Array<{ path: string; mess } const fetchImpl = vi.fn(async (_url: string, init?: RequestInit) => { + // objectstack#36511 — the Save's own publish of the item, and a refused one's discard. + if (init?.method === 'POST' || init?.method === 'DELETE') return new Response('{"success":true}', { status: 200 }); if (init?.method === 'PUT') { const body = JSON.parse(String(init.body)) as Record; puts.push(body); @@ -129,13 +131,6 @@ afterEach(() => { const L = (key: string) => t(key, 'en'); -/** Past the autosave's 1.5 s debounce. */ -async function outlastDebounce(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); -} - async function mountOnView(def: Record, tabKey: string): Promise { objectDef = def; render( @@ -170,7 +165,7 @@ describe('Studio data page — "Show me" puts the focus on the input the refusal }; await mountOnView(TASK, 'engine.studio.data.tab.form'); await addFieldFromFormToolbar(undefined, { label: 'Due note' }); - await outlastDebounce(); + await pressStudioSave(); const strip = await screen.findByTestId('studio-refusal', undefined, { timeout: 4000 }); expect(within(strip).getByTestId('studio-refusal-message')).toHaveTextContent( tFormat('engine.studio.refusal.field', 'en', { field: 'Due note' }), @@ -198,7 +193,7 @@ describe('Studio data page — "Show me" puts the focus on the input the refusal // Any edit: the label of the first action, which the list selects. const labelInput = (await screen.findByText(L('engine.inspector.action.label'), { selector: 'label' })).parentElement!.querySelector('input')!; fireEvent.change(labelInput, { target: { value: 'Archive now' } }); - await outlastDebounce(); + await pressStudioSave(); expect(puts).toHaveLength(1); await screen.findByTestId('studio-refusal'); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx index 713fecc9a04..c1be2f21737 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx @@ -34,6 +34,8 @@ const objectDef = { const puts: Array> = []; const fetchImpl = vi.fn(async (_url: string, init?: RequestInit) => { + // objectstack#36511 — the Save's own publish of the item, and a refused one's discard. + if (init?.method === 'POST' || init?.method === 'DELETE') return new Response('{"success":true}', { status: 200 }); if (init?.method === 'PUT') { puts.push(JSON.parse(String(init.body)) as Record); return new Response(JSON.stringify({ success: true }), { @@ -83,13 +85,6 @@ afterEach(() => { fetchImpl.mockClear(); }); -/** Past the autosave's 1.5 s debounce. */ -async function outlastDebounce(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); -} - /** The inspector control under a visible label. */ function controlUnder(label: string): HTMLElement { const lab = screen.getByText(label, { selector: 'label' }); @@ -124,12 +119,12 @@ async function addRollup(): Promise<{ name: string; label: string }> { return { name, label }; } -const heldLine = (clause: string) => tFormat('engine.studio.held.line', 'en', { clause }); +const heldLine = (clause: string) => tFormat('engine.studio.held.lineExplicit', 'en', { clause }); describe('Studio data page — a Rollup is held until it is set up (objectstack#27461)', () => { it('sends no save for the bare roll-up; names each missing input in turn; a count lets the save go', async () => { const { name, label } = await addRollup(); - await outlastDebounce(); + await pressStudioSave(); expect(puts, 'an unconfigured roll-up is not sent').toEqual([]); expect(screen.queryByTestId('studio-refusal')).toBeNull(); @@ -141,7 +136,7 @@ describe('Studio data page — a Rollup is held until it is set up (objectstack# const child = controlUnder(t('designer.field.summary.object', 'en')) as HTMLInputElement; fireEvent.change(child, { target: { value: 'showcase_task' } }); fireEvent.blur(child); - await outlastDebounce(); + await pressStudioSave(); expect(puts, 'a child object alone is not a roll-up yet').toEqual([]); expect(message()).toHaveTextContent(needs('designer.field.summary.function')); @@ -149,6 +144,7 @@ describe('Studio data page — a Rollup is held until it is set up (objectstack# fireEvent.click( within(await screen.findByRole('listbox')).getByRole('option', { name: t('designer.field.summary.fn.count', 'en') }), ); + await pressStudioSave(); await waitFor(() => expect(puts.length).toBe(1), { timeout: 4000 }); expect(lastSentField(name)).toEqual( expect.objectContaining({ type: 'summary', summaryOperations: { object: 'showcase_task', function: 'count' } }), From 17cc57e50ff67a3a6af994320b695e77c13b16e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 23:47:40 +0000 Subject: [PATCH 06/25] test(studio): extension, verdict, switch and toast pins follow Save Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .../DataPillar.authoredBuffer-29793.test.tsx | 2 + ...aPillar.baseObjectExtension-28575.test.tsx | 48 ++++++- .../DataPillar.draftSavedNamed-28984.test.tsx | 45 ++++--- .../DataPillar.draftUnreadable-29148.test.tsx | 1 + .../DataPillar.formViewLayout-30057.test.tsx | 2 + .../DataPillar.pairActions-30088.test.tsx | 1 + .../DataPillar.railSwitchFlush-27511.test.tsx | 68 +++++----- .../DataPillar.saveCancel-36511.test.tsx | 2 +- ...Pillar.savedAtDisplayLocale-10232.test.tsx | 120 ------------------ ...illar.validationVerdictHold-27644.test.tsx | 73 ++++++----- .../src/views/studio-design/studioSaveBar.tsx | 5 +- 11 files changed, 150 insertions(+), 217 deletions(-) delete mode 100644 ui/packages/app-shell/src/views/studio-design/DataPillar.savedAtDisplayLocale-10232.test.tsx diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.authoredBuffer-29793.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.authoredBuffer-29793.test.tsx index 3336b919f60..e0733265ff5 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.authoredBuffer-29793.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.authoredBuffer-29793.test.tsx @@ -219,6 +219,7 @@ describe('DataPillar in a zh-CN console — the object buffer is the authored do renderZh(); await relabel('Severity', 'Level'); + await pressStudioSave(); await waitFor(() => expect(objectSaves().length).toBeGreaterThan(0), { timeout: 8000 }); const { name, body, opts } = objectSaves().at(-1)!; expect(name).toBe(OBJECT); @@ -232,6 +233,7 @@ describe('DataPillar in a zh-CN console — the object buffer is the authored do renderZh(); await relabel('Severity', 'Level'); + await pressStudioSave(); await waitFor(() => expect(objectSaves().length).toBeGreaterThan(0), { timeout: 8000 }); expectAuthoredBody(objectSaves().at(-1)!.body, 'Level'); }); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.baseObjectExtension-28575.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.baseObjectExtension-28575.test.tsx index 887a612e81b..f8eed0d7cfc 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.baseObjectExtension-28575.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.baseObjectExtension-28575.test.tsx @@ -68,6 +68,18 @@ const baseServed = () => ({ }, }); +type Row = Record; +/** The base as served with a published extension merged in: its fields added, its patches applied. */ +function mergedServed(ext: Row): Row { + const fields: Record = { ...(baseServed().fields as Record), ...(ext.fields as Record) }; + for (const [name, patch] of Object.entries((ext.fieldPatches ?? {}) as Record)) { + const { options, ...rest } = patch as { options?: Record }; + const opts = (fields[name].options as Row[] | undefined)?.map((o) => ({ ...o, ...(options?.[String(o.value)] ?? {}) })); + fields[name] = { ...fields[name], ...rest, ...(opts ? { options: opts } : {}) }; + } + return { ...baseServed(), fields }; +} + const mockClient = { list: vi.fn(async (_type: string, opts?: { packageId?: string }) => opts?.packageId === PAIR ? [] : [{ name: OBJECT, label: 'Account' }], @@ -82,9 +94,20 @@ const mockClient = { get: vi.fn(async (type: string, name: string, opts?: { packageId?: string }) => type === 'object_extension' && name === OBJECT && opts?.packageId === PAIR ? srv.publishedExt : null, ), - publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), - save: vi.fn(async (type: string, _name: string, _body: unknown, _opts?: { packageId?: string }) => { + // objectstack#36511 — the Save's own publish: the pair's extension draft + // goes live, and the base serves it merged. + publish: vi.fn(async (type: string) => { + if (type === 'object_extension' && srv.draftExt) { + srv.publishedExt = { ...srv.draftExt, _packageId: PAIR }; + srv.served = mergedServed(srv.draftExt); + srv.draftExt = null; + } + return {}; + }), + reset: vi.fn(async () => ({})), + save: vi.fn(async (type: string, _name: string, body: unknown, _opts?: { packageId?: string }) => { if (type === 'object_extension' && srv.refuse) throw srv.refuse; + if (type === 'object_extension') srv.draftExt = JSON.parse(JSON.stringify(body)) as Record; return { ok: true, version: 'v2', state: 'draft' }; }), }; @@ -227,6 +250,8 @@ describe('Studio adds a field to a read-only base object as an extension in its expect(within(popover).getByTestId('add-field-api-name-preview')).toHaveTextContent('region__c'); await userEvent.click(within(popover).getByTestId('add-field-create')); + await pressStudioSave(); + await waitFor(() => expect(extensionSaves()).toHaveLength(1), { timeout: 8000 }); expect(ensure).toHaveBeenCalledTimes(1); const [[type, name, body, opts]] = extensionSaves(); @@ -246,6 +271,7 @@ describe('Studio adds a field to a read-only base object as an extension in its expect(label).toBeEnabled(); expect(within(inspector).queryByTestId('field-base-patch-only')).toBeNull(); await userEvent.type(label, ' code'); + await pressStudioSave(); await waitFor( () => expect(extensionSaves().at(-1)?.[2]).toStrictEqual({ @@ -261,8 +287,10 @@ describe('Studio adds a field to a read-only base object as an extension in its await renderBase(); await openForm(); await addFromFormToolbar('Region'); + await pressStudioSave(); await waitFor(() => expect(extensionSaves()).toHaveLength(1), { timeout: 8000 }); await addFromFormToolbar('Tier'); + await pressStudioSave(); await waitFor( () => expect(Object.keys((extensionSaves().at(-1)?.[2].fields ?? {}) as object)).toEqual(['region__c', 'tier__c']), { timeout: 8000 }, @@ -277,6 +305,7 @@ describe('Studio adds a field to a read-only base object as an extension in its await userEvent.type(within(popover).getByTestId('add-field-label-input'), 'Region'); expect(within(popover).getByTestId('add-field-api-name-preview')).toHaveTextContent('region__c'); await userEvent.click(within(popover).getByTestId('add-field-create')); + await pressStudioSave(); await waitFor(() => expect(extensionSaves()).toHaveLength(1), { timeout: 8000 }); expect(Object.keys(extensionSaves()[0]![2].fields as object)).toEqual(['region__c']); }); @@ -302,6 +331,8 @@ describe('Studio adds a field to a read-only base object as an extension in its await userEvent.type(within(popover).getByTestId('add-field-label-input'), 'Tier'); await userEvent.click(within(popover).getByTestId('add-field-create')); + await pressStudioSave(); + await waitFor(() => expect(extensionSaves()).toHaveLength(1), { timeout: 8000 }); // The draft starts from the published body: publishing it keeps region__c. expect(extensionSaves()[0]![2]).toStrictEqual({ @@ -321,6 +352,7 @@ describe('Studio adds a field to a read-only base object as an extension in its expect(label).toBeEnabled(); await userEvent.clear(label); await userEvent.type(label, 'Company'); + await pressStudioSave(); await waitFor( () => expect(extensionSaves().at(-1)?.[2]).toStrictEqual({ extend: OBJECT, fieldPatches: { name: { label: 'Company' } } }), { timeout: 8000 }, @@ -340,6 +372,7 @@ describe('Studio adds a field to a read-only base object as an extension in its expect(within(inspector).getByTestId('option-value')).toBeDisabled(); await userEvent.clear(optionLabel); await userEvent.type(optionLabel, 'Tech'); + await pressStudioSave(); await waitFor( () => expect(extensionSaves().at(-1)?.[2]).toStrictEqual({ @@ -381,6 +414,7 @@ describe('Studio adds a field to a read-only base object as an extension in its await renderBase(); await openForm(); await addFromFormToolbar('Region'); + await pressStudioSave(); await waitFor(() => expect(screen.getByText(walled, { exact: false })).toBeInTheDocument(), { timeout: 8000 }); cleanup(); @@ -391,6 +425,7 @@ describe('Studio adds a field to a read-only base object as an extension in its await renderBase(); await openForm(); await addFromFormToolbar('Region'); + await pressStudioSave(); await waitFor(() => expect(screen.getByText(suffix, { exact: false })).toBeInTheDocument(), { timeout: 8000 }); }); @@ -429,14 +464,15 @@ describe('CONTROL: a writable package’s add-field is unchanged (objectstack#28 await userEvent.type(within(popover).getByTestId('add-field-label-input'), 'Region'); expect(within(popover).getByTestId('add-field-api-name-preview')).toHaveTextContent(/^.*region$/); await userEvent.click(within(popover).getByTestId('add-field-create')); + const inspector = await screen.findByTestId('data-field-inspector'); + expect(within(inspector).queryByTestId('field-base-patch-only')).toBeNull(); + expect(within(inspector).getByRole('checkbox', { name: t('designer.field.required', 'en') })).toBeEnabled(); + await pressStudioSave(); await waitFor(() => expect(saves().some(([type]) => type === 'object')).toBe(true), { timeout: 8000 }); const [, , body] = saves().filter(([type]) => type === 'object').at(-1)!; expect(Object.keys(body.fields as object)).toEqual(['name', 'industry', 'region']); expect(extensionSaves()).toEqual([]); expect(ensure).not.toHaveBeenCalled(); - const inspector = await screen.findByTestId('data-field-inspector'); - expect(within(inspector).queryByTestId('field-base-patch-only')).toBeNull(); - expect(within(inspector).getByRole('checkbox', { name: t('designer.field.required', 'en') })).toBeEnabled(); }); }); @@ -449,6 +485,7 @@ describe('A Chinese label names a base object\'s extension field by pinyin, suff await userEvent.type(within(popover).getByTestId('add-field-label-input'), '客户等级'); expect(within(popover).getByTestId('add-field-api-name-preview')).toHaveTextContent('kehu_dengji__c'); await userEvent.click(within(popover).getByTestId('add-field-create')); + await pressStudioSave(); await waitFor(() => expect(extensionSaves()).toHaveLength(1), { timeout: 8000 }); expect(extensionSaves()[0][2]).toStrictEqual({ extend: OBJECT, @@ -471,6 +508,7 @@ describe('the object header says where a base object’s extension is saved (obj await openForm(); expect(savedTo()).toBeNull(); await addFromFormToolbar('Region'); + await pressStudioSave(); await waitFor(() => expect(extensionSaves()).toHaveLength(1), { timeout: 8000 }); await waitFor(() => expect(savedTo()).toHaveTextContent(SAVED_TO), { timeout: 8000 }); expect(environment()).toHaveTextContent(ENVIRONMENT); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.draftSavedNamed-28984.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.draftSavedNamed-28984.test.tsx index aa501197fac..4eb7b6b44e4 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.draftSavedNamed-28984.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.draftSavedNamed-28984.test.tsx @@ -1,14 +1,14 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectstack#28984 — a landed Studio draft autosave names what it saved. + * objectstack#28984 — a landed Studio save names what it saved. * - * The only feedback a landed draft autosave gave was the top bar's - * "Saved HH:MM", which names nothing; only feedback that names the item counts - * as write feedback (ruling 6545938831 ② on #28345). The Data pillar now - * toasts "Draft saved: LABEL" when the draft save lands, and keeps the hint. + * Only feedback that names the item counts as write feedback (ruling + * 6545938831 ② on #28345). objectstack#36511 — the object page saves with the + * top bar's Save, which writes the draft and makes it live, and toasts "Saved, + * live now: LABEL" when it lands. * - * Driven through the pillar's real autosave and a real `MetadataClient` over a + * Driven through the pillar's real Save and a real `MetadataClient` over a * fetch double, with sonner's real `Toaster` mounted, so the assertions read * the toasts a user would see: * @@ -37,11 +37,17 @@ const objectDef = { }; const puts: string[] = []; -const server = { refuse: false }; +const server = { refuse: false, draft: null as unknown, live: null as unknown }; const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => { + // The Save's own publish of the item (objectstack#36511): its draft goes live. + if (init?.method === 'POST') { + server.live = server.draft; + return new Response('{"success":true}', { status: 200 }); + } if (init?.method === 'PUT') { puts.push(String(url)); + server.draft = JSON.parse(String(init.body)); if (server.refuse) { return new Response( JSON.stringify({ success: false, error: { code: 'VALIDATION_ERROR', message: 'The draft was refused by the server.' } }), @@ -60,7 +66,7 @@ const client = new MetadataClient({ baseUrl: 'http://test.local', fetch: fetchIm Object.assign(client, { list: vi.fn(async () => [{ name: 'showcase_task', label: 'Task' }]), listDrafts: vi.fn(async () => []), - layered: vi.fn(async () => ({ effective: objectDef, code: objectDef })), + layered: vi.fn(async () => ({ effective: server.live ?? objectDef, code: objectDef, overlay: server.live })), getDraft: vi.fn(async () => null), }); @@ -89,8 +95,8 @@ import { tFormat } from '../metadata-admin/i18n'; const dataSource = createEmptyDataSource(); registerBuiltinInspectors(); -const SAID = tFormat('engine.studio.draftSaved', 'en', { item: 'Task' }); -const TOAST_ID = 'studio-draft-saved:object:showcase_task'; +const SAID = tFormat('engine.studio.save.done', 'en', { items: 'Task' }); +const TOAST_ID = 'studio-save'; afterEach(() => { act(() => { @@ -99,6 +105,7 @@ afterEach(() => { cleanup(); puts.length = 0; server.refuse = false; + server.draft = server.live = null; fetchImpl.mockClear(); vi.restoreAllMocks(); }); @@ -127,20 +134,16 @@ function controlUnder(label: string): HTMLInputElement { return lab.parentElement!.querySelector('input') as HTMLInputElement; } -/** Waits past the autosave's 1.5 s debounce and the save's round trip. */ -async function pastAutosave(): Promise { - await act(async () => { - await new Promise((r) => setTimeout(r, 2300)); - }); -} +/** The top bar's Save, and its round trip. */ +const pastAutosave = pressStudioSave; -describe('Studio Data pillar — a landed draft autosave names what it saved (objectstack#28984)', () => { - it('a landed save toasts the object by its label, and the top-bar hint stays', async () => { +describe('Studio Data pillar — a landed Save names what it saved (objectstack#28984)', () => { + it('a landed save toasts the object by its label', async () => { const success = vi.spyOn(toast, 'success'); mount(); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); await addFieldFromFormToolbar(); - await screen.findByTestId('data-saved-at', undefined, { timeout: 5000 }); + await pressStudioSave(); expect(puts.some((u) => u.includes('mode=draft')), `PUTs: ${puts.join(' | ')}`).toBe(true); await waitFor(() => expect(savedToasts()).toHaveLength(1)); @@ -154,12 +157,12 @@ describe('Studio Data pillar — a landed draft autosave names what it saved (ob mount(); fireEvent.click(await screen.findByRole('button', { name: 'Form' })); await addFieldFromFormToolbar(); + await pressStudioSave(); await screen.findByTestId('studio-refusal', undefined, { timeout: 5000 }); - expect(puts.length, 'the autosave never sent: the harness is dead').toBeGreaterThan(0); + expect(puts.length, 'the Save never sent: the harness is dead').toBeGreaterThan(0); expect(savedToasts()).toEqual([]); expect(success.mock.calls.filter(([, opts]) => (opts as { id?: string } | undefined)?.id === TOAST_ID)).toEqual([]); - expect(screen.queryByTestId('data-saved-at')).toBeNull(); }); it('saving one object again keeps one toast on screen, under one id', async () => { diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.draftUnreadable-29148.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.draftUnreadable-29148.test.tsx index cdb957c1989..9543b0d19e6 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.draftUnreadable-29148.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.draftUnreadable-29148.test.tsx @@ -224,6 +224,7 @@ describe('DataPillar — a pair extension draft the server refuses to read is no const popover = await screen.findByTestId('add-field-popover'); await userEvent.type(within(popover).getByTestId('add-field-label-input'), 'Region'); await userEvent.click(within(popover).getByTestId('add-field-create')); + await pressStudioSave(); await waitFor(() => expect(extensionSaves()).toHaveLength(1), { timeout: 8000 }); expect(extensionSaves()[0]![3]).toMatchObject({ mode: 'draft', packageId: PAIR }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx index 2c896d86c8c..3b2c4435612 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.formViewLayout-30057.test.tsx @@ -256,6 +256,8 @@ describe('the Form tab lays out the form the app opens (objectstack#30057)', () expect(screen.queryByText(OFF_FORM)).toBeNull(); await userEvent.click(screen.getByTestId('form-designer-add-section-footer')); + // The object's field groups are the object page's: sent by the top bar's Save (objectstack#36511). + await pressStudioSave(); await waitFor(() => expect(saves().length).toBe(1), { timeout: 4000 }); const [type, name, body] = saves()[0]; expect([type, name]).toEqual(['object', OBJECT]); 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 5526b643a71..fa5c8861169 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 @@ -344,6 +344,7 @@ describe('Studio adds an action to an installed app’s object, in its customiza fireEvent.click(screen.getByRole('button', { name: L('engine.studio.new') })); fireEvent.click(await screen.findByTestId('action-preset-change_choice')); await outlastDebounce(); + await pressStudioSave(); await waitFor(() => expect(saves().filter(([type]) => type === 'object').length).toBeGreaterThan(0)); const [, , body] = saves().filter(([type]) => type === 'object').at(-1)!; const names = (body.actions as Array>).map((a) => a.name); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.railSwitchFlush-27511.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.railSwitchFlush-27511.test.tsx index 669fd5e8637..8922a97a727 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.railSwitchFlush-27511.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.railSwitchFlush-27511.test.tsx @@ -2,16 +2,13 @@ /** * objectstack#27511 — an object switch in the Data pillar's rail never drops - * an edit still inside the autosave's debounce. + * an unsaved edit with nothing on screen. * - * The autosave sends 1.5 s after the last edit, and its timer sends nothing - * once the open object has changed (objectui#11232): the rail's switch reloads - * the one buffer the edit lives in. So an edit made less than 1.5 s before a - * click on another object was dropped with nothing on screen, and reverted on - * the next visit. The switch now sends the pending edit first with the - * autosave's own `flush` and opens the next object once its save has landed; a - * save already in flight is waited out the same way; an edit that cannot be - * sent (its save was refused) is the author's to drop, and the switch asks. + * objectstack#36511 — the object page saves with the top bar's Save, so a + * switch sends nothing: the rail's switch reloads the one buffer the edit lives + * in, and an edit Save has not sent (or whose save was refused) is the + * author's to drop, so the switch asks. A saved edit leaves nothing to ask + * about. * * The client is a server double that records every save and can hold or * refuse one; the records grid is a double that draws only its "+" column. @@ -68,7 +65,14 @@ const mockClient = vi.hoisted(() => ({ 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 }); }), - publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), + // The Save's own publish (objectstack#36511): the draft goes live. + publish: vi.fn(async (_type: string, name: string, _opts?: unknown) => { + const draft = server.drafts.get(name); + if (draft) server.active.set(name, draft); + server.drafts.delete(name); + return {}; + }), + reset: vi.fn(async () => ({})), save: vi.fn(async (_type: string, name: string, item: unknown) => { const body = JSON.parse(JSON.stringify(item)) as Record; server.saves.push({ name, body }); @@ -182,58 +186,48 @@ async function openTask(): Promise { await waitFor(() => expect(fieldCount()).toHaveTextContent('2 fields'), SLOW); } -/** Waits past the autosave's debounce: what was sent by then is what will be. */ +/** Lets time pass: what was sent by then is what will be. */ async function pastDebounce(ms = 2500): Promise { await act(async () => { await new Promise((r) => setTimeout(r, ms)); }); } -describe('Data pillar — an object switch inside the autosave debounce (objectstack#27511)', () => { - it('sends the pending edit to its own object first, then opens the next one', async () => { +describe('Data pillar — an object switch over an unsaved edit (objectstack#27511, objectstack#36511)', () => { + it('sends nothing: the switch asks; declined, the edit stays; agreed, Note opens and Task is as stored', async () => { await openTask(); await addFieldFromGrid(); - // Inside the debounce: nothing has been sent yet. - expect(server.saves).toEqual([]); fireEvent.click(screen.getByRole('button', { name: /Note/ })); + expect(confirmSpy).toHaveBeenCalledTimes(1); + expect(fieldCount()).toHaveTextContent('3 fields'); + confirmSpy.mockReturnValue(true); + fireEvent.click(screen.getByRole('button', { name: /Note/ })); await waitFor(() => expect(fieldCount()).toHaveTextContent('1 field'), SLOW); - await pastDebounce(); - // Exactly one save, to Task, carrying the edit; nothing was sent as Note's. - expect(savesRead()).toEqual([['acme_task', ['title', 'status', 'new_field']]]); - expect(confirmSpy).not.toHaveBeenCalled(); - - // The edit is Task's draft: back on Task, it is there. + expect(server.saves).toEqual([]); fireEvent.click(screen.getByRole('button', { name: /Task/ })); - await waitFor(() => expect(fieldCount()).toHaveTextContent('3 fields'), SLOW); + await waitFor(() => expect(fieldCount()).toHaveTextContent('2 fields'), SLOW); }, 30000); - it('waits out a save in flight, and opens the next object once it lands', async () => { + it('a saved edit is the stored object: the switch opens Note at once, and Task keeps the edit', async () => { await openTask(); - let release!: () => void; - server.saveHold = new Promise((r) => (release = r)); await addFieldFromGrid(); - // The timer sends it, and the save is held in flight. - await waitFor(() => expect(server.saves).toHaveLength(1), SLOW); + await pressStudioSave(); + expect(savesRead()).toEqual([['acme_task', ['title', 'status', 'new_field']]]); + expect(mockClient.publish).toHaveBeenCalledWith('object', 'acme_task', { packageId: PKG }); fireEvent.click(screen.getByRole('button', { name: /Note/ })); - await pastDebounce(300); - // Still on Task while its save is in flight. - expect(fieldCount()).toHaveTextContent('3 fields'); - - await act(async () => { - release(); - await new Promise((r) => setTimeout(r, 0)); - }); await waitFor(() => expect(fieldCount()).toHaveTextContent('1 field'), SLOW); - await pastDebounce(); - expect(savesRead()).toEqual([['acme_task', ['title', 'status', 'new_field']]]); + expect(confirmSpy).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: /Task/ })); + await waitFor(() => expect(fieldCount()).toHaveTextContent('3 fields'), SLOW); }, 30000); it('an edit whose save was refused is not dropped silently: the switch asks, and a declined ask keeps it', async () => { await openTask(); server.refuse = true; await addFieldFromGrid(); + await pressStudioSave(); await waitFor(() => expect(server.saves).toHaveLength(1), SLOW); await pastDebounce(300); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.saveCancel-36511.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.saveCancel-36511.test.tsx index 6a00783daf2..3b6931fca79 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.saveCancel-36511.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.saveCancel-36511.test.tsx @@ -181,7 +181,7 @@ describe('Data pillar — Save and Cancel in the top bar, live at once (objectst expect(writes.some((w) => w.url.pathname.includes('publish-drafts'))).toBe(false); await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull()); - expect(toast.success).toHaveBeenCalledWith(tFormat('engine.studio.save.done', 'en', { items: 'Task' })); + expect(toast.success).toHaveBeenCalledWith(tFormat('engine.studio.save.done', 'en', { items: 'Task' }), { id: 'studio-save' }); }); it('Cancel sends nothing and puts the page back as the server holds it', async () => { diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.savedAtDisplayLocale-10232.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.savedAtDisplayLocale-10232.test.tsx deleted file mode 100644 index 54f5ace386b..00000000000 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.savedAtDisplayLocale-10232.test.tsx +++ /dev/null @@ -1,120 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * The Data pillar's last-saved hint reads the DISPLAY locale, not the - * designer's string-table language (objectui#10232). - * - * The pillar's `locale` is `useMetadataLocale()`, which picks one of the - * metadata-admin `t()` tables and is `'en-US'` for every language that is not - * zh. The saved time used to be formatted with it, so a de-DE session read - * "Saved 03:30 PM". The time is now formatted with `useDisplayLocale()`; the - * sentence around it keeps the string-table language. - * - * The UI language is `en` in both sessions, so only the declared display - * locale differs. The saved time is "now", so the faces are told apart by the - * convention, not by a fixed clock: a 24-hour de-DE time carries no day - * period, an en one does. - */ - -import '@testing-library/jest-dom/vitest'; -import * as React from 'react'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { render, screen, fireEvent, cleanup } from '@testing-library/react'; -import { completeAddFieldPopover } from './__tests__/dataPillarAddField'; -import { MemoryRouter } from 'react-router-dom'; -import { I18nProvider, LocalizationProvider } from '@object-ui/i18n'; -import { isMachineLocale, recordLocaleArgumentsAsync } from '@object-ui/test-support'; - -const objectDef = { - name: 'showcase_task', - label: 'Task', - fields: [{ name: 'title', label: 'Title', type: 'text' }], -}; - -const mockClient = { - list: vi.fn(async () => [{ name: 'showcase_task', label: 'Task' }]), - listDrafts: vi.fn(async () => []), - layered: vi.fn(async () => ({ effective: objectDef, code: objectDef })), - getDraft: vi.fn(async () => null), - save: vi.fn(async () => ({})), -}; - -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 () => []) }; -}); - -// objectui#8620: the records grid calls `find()` on this adapter. `{}` had no -// `find()`, so `ListView`'s fetch threw and its `catch` swallowed the error. -// `dataSource` is an empty-backend `DataSource`, created once below the imports -// so every render gets the same object. -vi.mock('@object-ui/react', async (importOriginal) => { - const mod = await importOriginal(); - return { ...mod, useAdapter: () => dataSource }; -}); - -import { DataPillar } from './StudioDesignSurface'; -import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; - -const dataSource = createEmptyDataSource(); -failOnAbsorbedFetchError(); - -afterEach(cleanup); - -/** Mounts the pillar under a declared display `locale`, makes an edit, and returns the saved hint once the auto-save lands. */ -async function readSavedHint(locale: string): Promise { - render( - - - - - - - , - ); - fireEvent.click(await screen.findByRole('button', { name: 'Form' })); - // An edit sets `dirty`; the debounced auto-save lands it and shows the hint. - fireEvent.click((await screen.findAllByRole('button', { name: /Add field/i }))[0]); - // objectui#12516 — Add field asks for the label first. - await completeAddFieldPopover(); - const hint = await screen.findByTestId('data-saved-at', undefined, { timeout: 5000 }); - const text = hint.textContent ?? ''; - cleanup(); - return text; -} - -describe('Data pillar — the last-saved time follows the display locale (objectui#10232)', () => { - it('says the de-DE face under a de-DE session', async () => { - const text = await readSavedHint('de-DE'); - expect(text, `got: ${text}`).toMatch(/\b\d{2}:\d{2}\b/); - expect(text, `got: ${text}`).not.toMatch(/\b(AM|PM)\b/); - }); - - it('keeps the en face under an en session', async () => { - const text = await readSavedHint('en'); - expect(text, `got: ${text}`).toMatch(/\d{2}:\d{2}\s(AM|PM)/); - }); - - it('every locale-taking call receives the declared tag', async () => { - const calls = await recordLocaleArgumentsAsync(async () => { - await readSavedHint('de-DE'); - }); - expect(calls.some((c) => c.locale === 'de-DE'), `saw: ${JSON.stringify(calls).slice(0, 2000)}`).toBe(true); - expect(calls.filter(isMachineLocale), 'these call sites formatted in the machine locale').toEqual([]); - }); -}); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.validationVerdictHold-27644.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.validationVerdictHold-27644.test.tsx index 9db8542eb3a..5af369fa3fd 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.validationVerdictHold-27644.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.validationVerdictHold-27644.test.tsx @@ -11,7 +11,8 @@ * guard the publish refuses read clean and autosaved until Publish refused * it. The verdict judges the stored draft and nothing else: it holds while the * guard still shows the text it judged, and lets the edit that changes that - * text go out, since only that save brings the next verdict. ⛔ The fake door + * text go out. objectstack#36511 — Save is the draft and the item's publish, so + * a guard the publish refuses is refused at Save, at the rule, edits kept. ⛔ The fake door * below is the only place the refusal is decided; the editor restates no rule. */ @@ -71,7 +72,21 @@ let server: Server; const PUBLISHED = objectWith(ACCEPTED); const mockClient: Record = { - publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), + // objectstack#36511 — the Save's own publish: the door refuses the guard, and + // the draft it judged stays pending; an accepted one goes live. + publish: vi.fn(async () => { + const verdict = server.draft ? verdictOf(server.draft) : { valid: true as const }; + if ('errors' in verdict) { + const issues = verdict.errors.map((e) => ({ ...e, path: `objects.showcase_task.${e.path}` })); + throw Object.assign(new Error(REFUSAL), { status: 422, code: 'VALIDATION_FAILED', issues }); + } + server.draft = null; + return {}; + }), + reset: vi.fn(async () => { + server.draft = null; + return {}; + }), save: vi.fn(async (_type: string, _name: string, body: Record) => { const copy = JSON.parse(JSON.stringify(body)) as Record; server.sent.push(copy); @@ -161,10 +176,8 @@ afterEach(() => { vi.mocked(mockClient.save as () => unknown).mockClear(); }); -/** The shared autosave fires 1.5 s after the last edit. */ const AUTOSAVE = { timeout: 5000 }; -/** Longer than the autosave's pause. */ -const pause = (ms = 2500) => new Promise((r) => setTimeout(r, ms)); +const pause = (ms = 600) => new Promise((r) => setTimeout(r, ms)); function mount(draft: Record | null) { server = { draft, sent: [] }; @@ -198,7 +211,7 @@ async function rawGuard(): Promise { const editMessage = (value: string) => fireEvent.change(screen.getByPlaceholderText(t('engine.studio.rules.messagePlaceholder', 'en')), { target: { value } }); -describe('a server error at a validation rule\'s path holds the Data pillar autosave (objectstack#27644)', () => { +describe('a server error at a validation rule\'s path holds the Data pillar Save (objectstack#27644)', () => { it('(a) a stored draft the publish refuses: another edit to the rule is held, no PUT, the message stays', async () => { mount(objectWith(REFUSED)); await openRule(); @@ -207,35 +220,36 @@ describe('a server error at a validation rule\'s path holds the Data pillar auto editMessage('Amount is over the cap'); await waitFor(() => expect(screen.getByTestId('studio-held-message')).toHaveTextContent('Amount cap'), AUTOSAVE); - await pause(); + await pressStudioSave(); expect(server.sent).toHaveLength(0); expect(screen.getByText(REFUSAL)).toBeInTheDocument(); }); - it('(b) the card flow: the refused guard saves once, its re-read holds the next edit', async () => { + it('(b) the card flow: Save sends the guard once; the publish refuses it with its reason, and the edit stays', async () => { mount(objectWith(ACCEPTED)); await openRule(); const box = await rawGuard(); await screen.findByText('Valid CEL', {}, { timeout: 3000 }); - // No client copy of the rule: the lint passes it and the first save goes out. + // No client copy of the rule: the lint passes it and Save sends it. fireEvent.change(box, { target: { value: REFUSED } }); - await waitFor(() => expect(server.sent).toHaveLength(1), AUTOSAVE); - expect(await screen.findByText(REFUSAL, {}, AUTOSAVE)).toBeInTheDocument(); - expect(screen.queryByText('Valid CEL')).toBeNull(); - - editMessage('Amount is over the cap'); - await waitFor(() => expect(screen.getByTestId('studio-held-message')).toHaveTextContent('Amount cap'), AUTOSAVE); - await pause(); + await pressStudioSave(); expect(server.sent).toHaveLength(1); + expect(mockClient.publish).toHaveBeenCalled(); + expect(await screen.findByTestId('studio-refusal', {}, AUTOSAVE)).toHaveTextContent(REFUSAL); + // Refused, the edit is still the page's, unsaved; the draft that was pending carries it. + expect(guardRaw().value).toBe(REFUSED); + expect(screen.getByTestId('studio-save')).toBeInTheDocument(); + expect((server.draft?.validations as Array<{ condition?: string }>)[1]!.condition).toBe(REFUSED); }); - it('(c) editing the guard away releases: the save goes out and its clean re-read clears the verdict', async () => { + it('(c) editing the guard away releases: Save sends it, it goes live, and the re-read clears the verdict', async () => { mount(objectWith(REFUSED)); await openRule(); await screen.findByText(REFUSAL); fireEvent.change(await rawGuard(), { target: { value: ACCEPTED } }); + await pressStudioSave(); await waitFor(() => expect(server.sent).toHaveLength(1), AUTOSAVE); const saved = server.sent[0]!.validations as Array<{ condition?: string }>; @@ -244,7 +258,7 @@ describe('a server error at a validation rule\'s path holds the Data pillar auto expect(screen.queryByTestId('studio-held')).toBeNull(); }); - it('(d) typed back to the judged text before the autosave fires: held again, no PUT', async () => { + it('(d) typed back to the judged text before Save: held again, no PUT', async () => { mount(objectWith(REFUSED)); await openRule(); await screen.findByText(REFUSAL); @@ -254,7 +268,7 @@ describe('a server error at a validation rule\'s path holds the Data pillar auto fireEvent.change(box, { target: { value: REFUSED } }); await waitFor(() => expect(screen.getByTestId('studio-held-message')).toHaveTextContent('Amount cap'), AUTOSAVE); - await pause(); + await pressStudioSave(); expect(server.sent).toHaveLength(0); }); @@ -266,7 +280,7 @@ describe('a server error at a validation rule\'s path holds the Data pillar auto fireEvent.click(screen.getByRole('button', { name: 'Form' })); await waitFor(() => expect(screen.getByTestId('studio-held-message')).toHaveTextContent('Amount cap'), AUTOSAVE); - await pause(); + await pressStudioSave(); expect(server.sent).toHaveLength(0); }); @@ -296,25 +310,19 @@ describe('a rename keeps the served verdict\'s hold on the rule (objectstack#274 fireEvent.click(await screen.findByTestId('rule-preset-reject_when')); } - it('(a) the minted rule: its first save goes out, and the message edit that renames it is held', async () => { + it('(a) the minted rule: Save sends it under the name its message gives, and the refusal names it', async () => { mount(objectWith(ACCEPTED)); await newRejectWhenRule(); // The card's flow: the guard first, then the message, which settles the rule into the draft. fireEvent.change(await rawGuard(), { target: { value: REFUSED } }); editMessage('Over the cap'); + expect(screen.getByDisplayValue('over_the_cap')).toBeInTheDocument(); - // No client copy of the rule: the first save goes out and its re-read brings the verdict. - await waitFor(() => expect(server.sent).toHaveLength(1), AUTOSAVE); + await pressStudioSave(); + expect(server.sent).toHaveLength(1); const first = server.sent[0]!.validations as Array<{ name?: string; condition?: string }>; expect(first[2]).toMatchObject({ name: 'over_the_cap', condition: REFUSED }); - expect(await screen.findByText(REFUSAL, {}, AUTOSAVE)).toBeInTheDocument(); - - // The next message edit renames the rule; the guard still shows the judged text. - editMessage('Over the cap now'); - expect(screen.getByDisplayValue('over_the_cap_now')).toBeInTheDocument(); - await waitFor(() => expect(screen.getByTestId('studio-held-message')).toHaveTextContent('over_the_cap_now'), AUTOSAVE); - await pause(); - expect(server.sent).toHaveLength(1); + expect(await screen.findByTestId('studio-refusal', {}, AUTOSAVE)).toBeInTheDocument(); }); it('(b) a rename through the name input is held the same way', async () => { @@ -325,7 +333,7 @@ describe('a rename keeps the served verdict\'s hold on the rule (objectstack#274 fireEvent.change(screen.getByDisplayValue('amount_cap'), { target: { value: 'amount_limit' } }); await waitFor(() => expect(screen.getByTestId('studio-held-message')).toHaveTextContent('Amount cap'), AUTOSAVE); - await pause(); + await pressStudioSave(); expect(server.sent).toHaveLength(0); }); @@ -336,6 +344,7 @@ describe('a rename keeps the served verdict\'s hold on the rule (objectstack#274 await screen.findByDisplayValue('x'); fireEvent.change(screen.getByDisplayValue('status_set'), { target: { value: 'status_needed' } }); + await pressStudioSave(); // The refused rule beside it was never opened, so nothing holds this edit. await waitFor(() => expect(server.sent).toHaveLength(1), AUTOSAVE); diff --git a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx index a16d4f84b13..e76aad339df 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx @@ -38,6 +38,9 @@ import { LINT_DEBOUNCE_MS } from '../metadata-admin/CelPredicateField.js'; /** Past the editors' expression check of the last keystroke, and its report. */ const VERDICT_SETTLE_MS = LINT_DEBOUNCE_MS + 50; +/** The sonner id of a landed Save's toast: a second Save updates it in place (objectstack#28984). */ +export const STUDIO_SAVE_TOAST_ID = 'studio-save'; + /** What one buffer's Save did. */ export type StudioSaveResult = /** The item was written and is live. */ @@ -183,7 +186,7 @@ export function useStudioSaveCoordinator(locale: string): StudioSaveCoordinator description: lines.join('\n'), }); } else if (saved.length > 0) { - toast.success(tFormat('engine.studio.save.done', locale, { items: names(saved) })); + toast.success(tFormat('engine.studio.save.done', locale, { items: names(saved) }), { id: STUDIO_SAVE_TOAST_ID }); } }, [dirtyEntries, locale, readDirty]); const cancel = React.useCallback(() => { From 4334528df9e0de89933f02afcd77cebb831055de Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 23:53:09 +0000 Subject: [PATCH 07/25] test(studio): top-bar, in-flight, switch and conflict pins follow Save Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- ...ignSurface.autosaveInFlight-11204.test.tsx | 70 ++++---- ...esignSurface.autosaveSwitch-11232.test.tsx | 44 ++--- ...ignSurface.customizePublish-28562.test.tsx | 12 +- ...urface.draftVersionConflict-11773.test.tsx | 151 ++++++++++-------- ...udioDesignSurface.interfacePolish.test.tsx | 28 +--- ...oDesignSurface.narrowHeader-12509.test.tsx | 4 +- ...gnSurface.packageListErrorPosture.test.tsx | 1 - ...esignSurface.publishPosture-12517.test.tsx | 19 ++- ...rface.publishReadOnlyReason-12303.test.tsx | 68 +++----- 9 files changed, 190 insertions(+), 207 deletions(-) diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveInFlight-11204.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveInFlight-11204.test.tsx index 9bb6f1fda3a..c23669d6cc4 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveInFlight-11204.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveInFlight-11204.test.tsx @@ -20,6 +20,9 @@ * stayed dirty for good over content the server already held; the last case * below is that reading. * + * objectstack#36511 — the Data pillar saves with the top bar's Save instead: + * its block pins that an edit taken during a Save is the next Save's. + * * The canvases and inspectors are the REAL registered `FlowPreview` / * `FlowInspector` and `PagePreview` / `PageBlockInspector` / * `PageDefaultInspector`. The Data pillar's records grid is a double that @@ -121,7 +124,13 @@ const mockClient = vi.hoisted(() => { server.drafts.set(k(type, name), body); return { type, name, item }; }), - publish: vi.fn(async () => ({ success: true })), + // The Data pillar's Save publishes the item (objectstack#36511): its draft goes live. + publish: vi.fn(async (type: string, name: string) => { + 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 () => ({})), }; }); @@ -169,6 +178,7 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); import { AutomationsPillar, DataPillar, InterfacesPillar } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromGrid } from './__tests__/dataPillarAddField'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerMetadataPreview } from '../metadata-admin/preview-registry'; @@ -274,32 +284,43 @@ describe('Automations pillar — an edit taken while a flow save is in flight (o }); }); -describe('Data pillar — an edit taken while an object save is in flight (objectui#11204)', () => { +/** + * objectstack#36511 — the object page saves with the top bar's Save: an edit + * taken while a Save is in flight stays on screen, and the page stays dirty + * once that Save lands, so the next Save sends it. Nothing sends it by itself. + */ +describe('Data pillar — an edit taken while an object Save is in flight (objectui#11204)', () => { function renderData() { return render( - - - , + + + + + , ); } const fieldNames = (body: Record) => readFields(body.fields).entries.map((e) => e.name); const fieldCountShown = () => screen.getByText(/^\d+ fields$/).textContent; - const addField = () => addFieldFromGrid(); + /** Save pressed with the save held in flight, then the edit taken meanwhile, then the save landed. */ + async function editDuringSave(edit: () => Promise): Promise { + const release = holdNextSave(); + await pressStudioSave({ settle: false }); + await waitFor(() => expect(server.saves).toHaveLength(1), { timeout: 8000 }); + await edit(); + await release(); + await waitFor(() => expect(screen.getByTestId('studio-save')).toBeEnabled(), { timeout: 8000 }); + } - it('the autosave: an added field stays on screen and lands in the next save', async () => { + it('an added field stays on screen, unsent, and the next Save sends it', async () => { renderData(); await waitFor(() => expect(fieldCountShown()).toBe('2 fields'), { timeout: 8000 }); - - const release = holdNextSave(); - await addField(); - await screen.findByTestId('data-autosaving', undefined, { timeout: 8000 }); - expect(savesOf('object').map(fieldNames)).toEqual([['title', 'status', 'new_field']]); + await addFieldFromGrid(); // A second label: a repeated one would ask for its api name (objectui#13389). - await addFieldFromGrid(undefined, { label: 'Second field' }); + await editDuringSave(() => addFieldFromGrid(undefined, { label: 'Second field' })); expect(fieldCountShown()).toBe('4 fields'); + expect(savesOf('object').map(fieldNames)).toEqual([['title', 'status', 'new_field']]); - await release(); - await settle(); + await pressStudioSave(); expect(fieldCountShown()).toBe('4 fields'); expect(savesOf('object').map(fieldNames)).toEqual([ ['title', 'status', 'new_field'], @@ -307,19 +328,15 @@ describe('Data pillar — an edit taken while an object save is in flight (objec ]); }); - it("the grid's column reorder, a save the pillar sends itself: a field added meanwhile lands in the next save", async () => { + it("the grid's column reorder is an edit Save sends: a field added during that Save is the next Save's", async () => { renderData(); await waitFor(() => expect(fieldCountShown()).toBe('2 fields'), { timeout: 8000 }); - - const release = holdNextSave(); fireEvent.click(await screen.findByRole('button', { name: 'Reverse columns' }, { timeout: 8000 })); - await screen.findByTestId('data-autosaving', undefined, { timeout: 8000 }); + expect(server.saves).toEqual([]); + await editDuringSave(() => addFieldFromGrid()); expect(savesOf('object').map(fieldNames)).toEqual([['status', 'title']]); - await addField(); - expect(fieldCountShown()).toBe('3 fields'); - await release(); - await settle(); + await pressStudioSave(); expect(fieldCountShown()).toBe('3 fields'); expect(savesOf('object').map(fieldNames)).toEqual([ ['status', 'title'], @@ -327,14 +344,13 @@ describe('Data pillar — an edit taken while an object save is in flight (objec ]); }); - it('the control: a reorder with nothing edited meanwhile is the only save', async () => { + it('the control: a reorder with nothing edited meanwhile is the only save, and leaves nothing to save', async () => { renderData(); await waitFor(() => expect(fieldCountShown()).toBe('2 fields'), { timeout: 8000 }); - fireEvent.click(await screen.findByRole('button', { name: 'Reverse columns' }, { timeout: 8000 })); - await waitFor(() => expect(server.saves).toHaveLength(1), { timeout: 8000 }); - await settle(); + await pressStudioSave(); expect(savesOf('object').map(fieldNames)).toEqual([['status', 'title']]); + await waitFor(() => expect(screen.queryByTestId('studio-save')).toBeNull()); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveSwitch-11232.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveSwitch-11232.test.tsx index 45ae7e115ca..dcc66463fab 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveSwitch-11232.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveSwitch-11232.test.tsx @@ -20,9 +20,9 @@ * claim on its buffer reads moved once the item has changed. The previous * item's pending edit is dropped by the hook, which is what every pillar did * whenever the new load landed inside the debounce. The Data pillar is the - * control: its rail sends the pending edit to its own object with the hook's - * `flush` before it switches (objectstack#27511), so nothing of it reaches the - * object opened next either. + * control: it saves with the top bar's Save (objectstack#36511), so its rail + * asks before a switch drops an unsaved edit, and nothing of it reaches either + * object. * * objectui#11203 (folded in): a package switch keeps the Interfaces pillar * mounted, so the nav editor's dirty flag and open editing survived into the @@ -208,6 +208,7 @@ vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); vi.mock('../../preview/DraftChangesPanel', () => ({ DraftChangesPanel: () => null })); import { AutomationsPillar, DataPillar, InterfacesPillar, StudioDesignSurface } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { ADD_FIELD_OFFERED, addFieldFromGrid } from './__tests__/dataPillarAddField'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { registerMetadataPreview } from '../metadata-admin/preview-registry'; @@ -454,37 +455,34 @@ describe('Interfaces page inspector — a save in flight across a page switch (o }, 30000); }); -describe('Data pillar — an object switch inside the debounce, the control (objectui#11232)', () => { - it('sends nothing to the newly opened object; the pending edit goes to its own (objectstack#27511)', async () => { +describe('Data pillar — an object switch over an unsaved edit, the control (objectui#11232)', () => { + it('sends nothing to either object; an edit on the opened object goes to it on Save (objectstack#36511)', async () => { render( - - - , + + + + + , ); await waitFor(() => expect(screen.getByText(/^\d+ fields?( \(\+\d+ system\))?$/)).toHaveTextContent('2 fields'), SLOW); await addFieldFromGrid(); const release = holdLoad('object', 'acme_note'); + // The edit is unsaved: the switch asks, and the author drops it. + confirmSpy.mockReturnValue(true); fireEvent.click(screen.getByRole('button', { name: /Note/ })); - await pastDebounce(); - - expect(savesOf('object', 'acme_note')).toEqual([]); - // objectstack#27511 — the switch sent the edit to Task before it opened Note. - expect(savesOf('object', 'acme_task').map((b) => readFields(b.fields).entries.map((e) => e.name))).toEqual([ - ['title', 'status', 'new_field'], - ]); - server.saves.length = 0; - + expect(confirmSpy).toHaveBeenCalledTimes(1); await release(); await waitFor(() => expect(screen.getByText(/^\d+ fields?( \(\+\d+ system\))?$/)).toHaveTextContent('1 field'), SLOW); await pastDebounce(1800); expect(server.saves).toEqual([]); // The control's own control: an edit on the opened object saves to it. await addFieldFromGrid(); - await waitFor(() => expect(server.saves).toHaveLength(1), SLOW); + await pressStudioSave(); expect(savesOf('object', 'acme_note').map((b) => readFields(b.fields).entries.map((e) => e.name))).toEqual([ ['body', 'new_field'], ]); + expect(savesOf('object', 'acme_task')).toEqual([]); }, 30000); }); @@ -712,9 +710,11 @@ describe("the load window: nothing of the previous item is offered, shown or sav it('Data: a field added during the load saves nothing; one added after the load saves once, to the object opened', async () => { render( - - - , + + + + + , ); await waitFor(() => expect(screen.getByText(/^\d+ fields?( \(\+\d+ system\))?$/)).toHaveTextContent('2 fields'), SLOW); @@ -737,6 +737,7 @@ describe("the load window: nothing of the previous item is offered, shown or sav // The control: a field added after the load saves once, to its own object. await addFieldFromGrid(); + await pressStudioSave(); await waitFor(() => expect(server.saves).toHaveLength(1), SLOW); expect(server.saves.map((s) => [s.type, s.name, s.body.label, fieldNamesOf(s.body)])).toEqual([ ['object', 'acme_note', 'Note', ['body', 'new_field']], @@ -793,6 +794,7 @@ describe('a package switch: Automations and Data open nothing of the previous pa await screen.findByRole('button', { name: /Beta item/ }, SLOW); await waitFor(() => expect(screen.getByText(/^\d+ fields?( \(\+\d+ system\))?$/)).toBeInTheDocument(), SLOW); await addFieldFromGrid(); + await pressStudioSave(); await waitFor(() => expect(server.saves).toHaveLength(1), SLOW); expect(server.saves.map((s) => [s.type, s.name, s.packageId, s.body.label, fieldNamesOf(s.body)])).toEqual([ ['object', 'beta_item', PKG_B, 'Beta item', ['name', 'new_field']], diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.customizePublish-28562.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.customizePublish-28562.test.tsx index 3356149a224..eaafb51c65a 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.customizePublish-28562.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.customizePublish-28562.test.tsx @@ -24,8 +24,8 @@ * - a listed manifest that states no version: Customize disabled, saying so; * - a walled admin (a group posture, not the platform operator) sees * Customize disabled, and the platform operator does not; - * - CONTROL: a base with no pair keeps the read-only Publish and reviews - * the base, as before; + * - CONTROL: a base with no pair reviews the base, as before, and with + * nothing pending draws no Publish (objectstack#36511); * - objectstack#29691: reviewing the pair, the panel is handed the base's * label for its "saved to" sentence, and nothing without a pair; * - objectstack#29691: after Customize, the item header says the same @@ -285,11 +285,11 @@ describe('a read-only base with its pair listed: Pending, the panel and Publish await waitFor(() => expect(srv.publishes).toEqual([PAIR])); }); - it('CONTROL: a base with no pair keeps the read-only Publish, and the panel reviews the base', async () => { + it('CONTROL: a base with no pair and nothing pending draws no Publish, and the panel reviews the base', async () => { renderWorkbench(); - await waitFor(() => expect(publishButton().parentElement).toHaveAttribute('data-disabled-reason'), { timeout: 8000 }); - expect(publishButton()).toBeDisabled(); - expect(panelPackage()).toBe(BASE); + // objectstack#36511 — Publish is drawn only while drafts are pending. + await waitFor(() => expect(panelPackage()).toBe(BASE), { timeout: 8000 }); + expect(screen.queryByRole('button', { name: /^Publish/ })).toBeNull(); expect(panelCustomizationOf()).toBe(''); expect(screen.queryByTestId('publish-all-drafts')).toBeNull(); }); 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 0e78370701d..b43102e4671 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 @@ -19,8 +19,12 @@ * production's. * * The first save after a load is pinned to that load's read: `If-Match` with - * the draft's version, or `If-None-Match: *` when no draft was pending — so the - * card's literal race (two editors who each load and save ONCE) is refused too. + * the draft's version, or `If-None-Match: *` when no draft was pending. + * + * objectstack#36511 — a Save is the draft and then that item's publish, so no + * draft is left after it and the next Save asserts none. The race refused + * here is over a draft pending when both editors opened (a copilot's): the + * second Save is pinned to a draft the first one published. * * The two editors are two mounted `DataPillar`s over one server double: each * pillar holds its own buffer and its own version, exactly as two tabs do. @@ -129,7 +133,13 @@ const mockClient = vi.hoisted(() => { server.drafts.set(k(type, name), { body, version }); return { success: true, version, seq: server.seq, state: 'draft', message: `Saved ${type} '${name}' [seq=${server.seq}]` }; }), - publish: vi.fn(async () => ({ success: true })), + // The Save's own publish (objectstack#36511): the draft goes live, and none is left. + publish: vi.fn(async (type: string, name: string) => { + const draft = server.drafts.get(k(type, name)); + if (draft) server.active.set(k(type, name), draft.body); + server.drafts.delete(k(type, name)); + return { success: true }; + }), reset: vi.fn(async () => ({})), }; }); @@ -177,6 +187,7 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); import { DataPillar } from './StudioDesignSurface'; +import { StudioSaveHarness } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar, addFieldFromGrid, type AddFieldInput } from './__tests__/dataPillarAddField'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; import { readFields } from '../metadata-admin/previews/object-fields-io'; @@ -197,9 +208,11 @@ afterEach(cleanup); /** One editor: a mounted Data pillar, as one browser tab holds it. */ function openEditor(): HTMLElement { const { container } = render( - - - , + + + + + , ); return container; } @@ -209,7 +222,22 @@ const fieldNames = (body: Record) => readFields(body.fields).en // counts its own fields with the same words, so the read is scoped. const fieldCount = (editor: HTMLElement) => within(within(editor).getByTestId('data-object-header')).getByText(/^\d+ fields?( \(\+\d+ system\))?$/).textContent; -const serverDraftFields = () => fieldNames(server.drafts.get(`object/${OBJECT.name}`)!.body); +const liveFields = () => fieldNames(server.active.get(`object/${OBJECT.name}`)!); + +/** Press this editor's own top-bar Save (objectstack#36511) and wait for its draft save to be sent. */ +async function saveIn(editor: HTMLElement): Promise { + const before = server.saves.length; + const save = await within(editor).findByTestId('studio-save', undefined, { timeout: 4000 }); + await act(async () => { + fireEvent.click(save); + }); + await waitFor(() => expect(server.saves.length).toBe(before + 1), { timeout: 8000 }); +} + +/** A draft pending when the editors open (a copilot's): the version both pin their first Save to. */ +const PENDING = 'hmac-sha256:pending'; +const servePendingDraft = () => + server.drafts.set(`object/${OBJECT.name}`, { body: JSON.parse(JSON.stringify(OBJECT)), version: PENDING }); async function loaded(editor: HTMLElement, count: string): Promise { await waitFor(() => expect(fieldCount(editor)).toBe(count), { timeout: 8000 }); @@ -219,7 +247,7 @@ async function loaded(editor: HTMLElement, count: string): Promise { const SECOND: AddFieldInput = { label: 'Second field' }; /** - * Add a field and wait until the autosave carrying it has landed. From the + * Add a field, press Save and wait until it has landed. From the * Records grid's "+" column by default; a draft-only object has no grid, so * its case adds from the Form toolbar (objectui#12511). A second field on the * same object takes another label (`input`): a repeated label derives a taken @@ -230,113 +258,99 @@ async function addFieldAndSave( add = addFieldFromGrid, input?: AddFieldInput, ): Promise { - const before = server.saves.length; await add(editor, input); - await waitFor(() => expect(server.saves.length).toBe(before + 1), { timeout: 8000 }); - await waitFor(() => expect(within(editor).queryByTestId('data-autosaving')).toBeNull(), { timeout: 8000 }); + await saveIn(editor); + await waitFor(() => expect(within(editor).queryByTestId('studio-save')).toBeNull(), { timeout: 8000 }); } -/** Reverse the grid's columns (a save the pillar sends itself) and wait for it. */ +/** Reverse the grid's columns and press Save. */ async function reorderAndSave(editor: HTMLElement): Promise { - const before = server.saves.length; fireEvent.click(await within(editor).findByRole('button', { name: 'Reverse columns' }, { timeout: 8000 })); - await waitFor(() => expect(server.saves.length).toBe(before + 1), { timeout: 8000 }); - await waitFor(() => expect(within(editor).queryByTestId('data-autosaving')).toBeNull(), { timeout: 8000 }); + await saveIn(editor); } /** - * The race, with both editors past their first save: A saves, B opens on A's - * draft and saves its own change, then A — still holding the copy it saved — - * edits again. + * The race over a draft pending when both editors opened: A saves (its draft, + * then its publish), then B — still holding the copy it opened — saves its own + * change, pinned to the draft that is no longer there. */ async function raceTwoEditors(): Promise<{ a: HTMLElement; b: HTMLElement }> { + servePendingDraft(); const a = openEditor(); await loaded(a, '2 fields'); - await addFieldAndSave(a); // A: + new_field const b = openEditor(); - await loaded(b, '3 fields'); - await reorderAndSave(b); // B: status before title - expect(serverDraftFields()).toEqual(['status', 'title', 'new_field']); - await addFieldFromGrid(a, SECOND); // A's stale copy + second_field + await loaded(b, '2 fields'); + // B edits first: its unsaved edit holds the page's re-read when A's publish + // pulses (one tab here; two tabs never share it). + fireEvent.click(await within(b).findByRole('button', { name: 'Reverse columns' }, { timeout: 8000 })); + await addFieldAndSave(a); // A: + new_field, live + expect(liveFields()).toEqual(['title', 'status', 'new_field']); + await saveIn(b); // B's stale copy, reordered await screen.findByTestId('draft-conflict-dialog', undefined, { timeout: 8000 }); return { a, b }; } describe('Data pillar — a draft saved elsewhere is not overwritten in silence (objectui#11773)', () => { - it('one editor: the first autosave is pinned to the load ("no draft"), and each later one to the receipt before it', async () => { + it('one editor: every Save asserts no draft is pending, since the Save before it published (objectstack#36511)', async () => { const a = openEditor(); await loaded(a, '2 fields'); await addFieldAndSave(a); await addFieldAndSave(a, addFieldFromGrid, SECOND); - await reorderAndSave(a); expect(server.saves.map((s) => [s.ifMatch, s.ifNoneMatch])).toEqual([ [undefined, '*'], - ['hmac-sha256:v1', undefined], - ['hmac-sha256:v2', undefined], + [undefined, '*'], ]); // The draft was read at the package the saves write. expect(mockClient.getDraft).toHaveBeenCalledWith('object', OBJECT.name, { packageId: PKG }); expect(server.saves.every((s) => s.packageId === PKG)).toBe(true); + expect(mockClient.publish).toHaveBeenCalledWith('object', OBJECT.name, { packageId: PKG }); + expect(liveFields()).toEqual(['title', 'status', 'new_field', 'second_field']); expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(); }); - it('the card\'s race: two editors who each load and save ONCE — the later first save is refused, and the earlier one\'s field survives', async () => { - const a = openEditor(); - await loaded(a, '2 fields'); - const b = openEditor(); - await loaded(b, '2 fields'); - await addFieldAndSave(a); // A: + new_field, the first draft - expect(serverDraftFields()).toEqual(['title', 'status', 'new_field']); - await addFieldFromGrid(b); // B's first save, built on the published object - await screen.findByTestId('draft-conflict-dialog', undefined, { timeout: 8000 }); - const refused = server.saves[server.saves.length - 1]!; - expect([refused.ifMatch, refused.ifNoneMatch]).toEqual([undefined, '*']); - // A's field is still in the draft: B's stale copy was not written over it. - expect(serverDraftFields()).toEqual(['title', 'status', 'new_field']); - }); - it('an editor that opens on a pending draft pins its first save to the version that read served', async () => { - server.drafts.set(`object/${OBJECT.name}`, { body: JSON.parse(JSON.stringify(OBJECT)), version: 'hmac-sha256:pending' }); + servePendingDraft(); const a = openEditor(); await loaded(a, '2 fields'); await addFieldAndSave(a); - expect(server.saves.map((s) => [s.ifMatch, s.ifNoneMatch])).toEqual([['hmac-sha256:pending', undefined]]); + expect(server.saves.map((s) => [s.ifMatch, s.ifNoneMatch])).toEqual([[PENDING, undefined]]); }); it('two editors: the stale save is refused with the conflict dialog, and the other editor\'s change survives', async () => { - const { a } = await raceTwoEditors(); + const { b } = await raceTwoEditors(); const refused = server.saves[server.saves.length - 1]!; - expect(refused.ifMatch).toBe('hmac-sha256:v1'); - expect(fieldNames(refused.body)).toEqual(['title', 'status', 'new_field', 'second_field']); - // Nothing was written over B's draft. - expect(serverDraftFields()).toEqual(['status', 'title', 'new_field']); + expect(refused.ifMatch).toBe(PENDING); + expect(fieldNames(refused.body)).toEqual(['status', 'title']); + // Nothing was written over A's change. + expect(liveFields()).toEqual(['title', 'status', 'new_field']); + expect(server.drafts.size).toBe(0); expect(screen.getByTestId('draft-conflict-dialog')).toHaveTextContent('acme_task'); fireEvent.click(screen.getByTestId('draft-conflict-cancel')); await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), { timeout: 8000 }); - // Keep editing: A's edit stays on screen, unsaved, and the refusal says so. - expect(fieldCount(a)).toBe('4 fields'); - expect(within(a).getByText(/^Not saved:/)).toBeInTheDocument(); - expect(serverDraftFields()).toEqual(['status', 'title', 'new_field']); + // Keep editing: B's edit stays on screen, unsaved, and the refusal says so. + expect(within(b).getByTestId('studio-save')).toBeInTheDocument(); + expect(within(b).getByText(/^Not saved:/)).toBeInTheDocument(); + expect(liveFields()).toEqual(['title', 'status', 'new_field']); }); - it('"reload" replaces the stale buffer with the saved draft, and the next save is pinned to that draft\'s version', async () => { - const { a } = await raceTwoEditors(); + it('"reload" replaces the stale buffer with what A saved, and the next save is built on it', async () => { + const { b } = await raceTwoEditors(); const savesBefore = server.saves.length; fireEvent.click(screen.getByTestId('draft-conflict-reload')); await waitFor(() => expect(screen.queryByTestId('draft-conflict-dialog')).toBeNull(), { timeout: 8000 }); - await loaded(a, '3 fields'); + await loaded(b, '3 fields'); expect(server.saves.length).toBe(savesBefore); - await addFieldAndSave(a, addFieldFromGrid, SECOND); + await addFieldAndSave(b, addFieldFromGrid, SECOND); const next = server.saves[server.saves.length - 1]!; - expect(next.ifMatch).toBe('hmac-sha256:v2'); - // Built on B's draft: B's column order is kept. - expect(fieldNames(next.body)).toEqual(['status', 'title', 'new_field', 'second_field']); + expect([next.ifMatch, next.ifNoneMatch]).toEqual([undefined, '*']); + // Built on A's change: its field is kept. + expect(fieldNames(next.body)).toEqual(['title', 'status', 'new_field', 'second_field']); }); - it('"overwrite" asks again, then re-sends pinned to the refusal\'s currentVersion and wins; the next save is pinned to it', async () => { - const { a } = await raceTwoEditors(); + it('"overwrite" asks again, then re-sends pinned to the refusal\'s currentVersion and wins', async () => { + await raceTwoEditors(); fireEvent.click(screen.getByTestId('draft-conflict-overwrite')); // The second, explicit confirmation — nothing is sent until it is given. const savesBefore = server.saves.length; @@ -347,13 +361,9 @@ describe('Data pillar — a draft saved elsewhere is not overwritten in silence }); await waitFor(() => expect(server.saves.length).toBe(savesBefore + 1), { timeout: 8000 }); const overwrite = server.saves[server.saves.length - 1]!; - // B's draft is the version the refusal named. - expect([overwrite.ifMatch, overwrite.ifNoneMatch]).toEqual(['hmac-sha256:v2', undefined]); - expect(serverDraftFields()).toEqual(['title', 'status', 'new_field', 'second_field']); - await waitFor(() => expect(within(a).queryByTestId('data-autosaving')).toBeNull(), { timeout: 8000 }); - - await addFieldAndSave(a, addFieldFromGrid, { label: 'Third field' }); - expect(server.saves[server.saves.length - 1]!.ifMatch).toBe(`hmac-sha256:v${server.seq - 1}`); + // No draft is the version the refusal named. + expect([overwrite.ifMatch, overwrite.ifNoneMatch]).toEqual([undefined, '*']); + await waitFor(() => expect(liveFields()).toEqual(['status', 'title']), { timeout: 8000 }); }); }); @@ -372,10 +382,11 @@ 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. expect(server.saves.map((s) => [s.ifMatch, s.ifNoneMatch])).toEqual([ [undefined, '*'], ['hmac-sha256:v1', undefined], - ['hmac-sha256:v2', undefined], + [undefined, '*'], ]); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacePolish.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacePolish.test.tsx index f0c2bae4318..5695d5f3b48 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacePolish.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacePolish.test.tsx @@ -134,30 +134,14 @@ function renderWorkbench() { ); } -/** The header Publish button, once the pending-draft count has resolved. */ -async function publishButton(): Promise { - // The rail's labelled leaf appears once the app has loaded, by which time the - // header's draft count has resolved too. - await screen.findByRole('button', { name: '客户仪表盘 仪表盘' }); - return screen.getByRole('button', { name: /^发布/ }); -} - describe('Studio top bar — the Publish button with nothing to publish (objectui#8219)', () => { - it('no draft: disabled, NOT the primary style, and the reason is visible text', async () => { + it('no draft: no Publish at all (objectstack#36511), and no "nothing to publish" text', async () => { renderWorkbench(); - const btn = await publishButton(); - expect(btn).toBeDisabled(); - expect(btn.className).not.toMatch(/\bbg-primary\b/); - expect(btn.className).not.toMatch(/\btext-primary-foreground\b/); - // An outline: a border that is actually drawn (the primary state carries a - // transparent one only to keep the bar from shifting). - expect(btn.className).toMatch(/\bborder\b/); - expect(btn.className).not.toMatch(/\bborder-transparent\b/); - // The reason is on screen, not only in the hover tooltip. - const reason = screen.getByTestId('publish-none-reason'); - expect(reason).toHaveTextContent('没有待发布的草稿'); - expect(reason).toBeVisible(); - expect(btn).toHaveAccessibleDescription('没有待发布的草稿'); + // The rail's labelled leaf appears once the app has loaded, by which time the + // header's draft count has resolved too. + await screen.findByRole('button', { name: '客户仪表盘 仪表盘' }); + expect(screen.queryByRole('button', { name: /^发布/ })).toBeNull(); + expect(screen.queryByTestId('publish-none-reason')).toBeNull(); }); it('a pending draft: enabled, the primary button, and no "nothing to publish" text', async () => { diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowHeader-12509.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowHeader-12509.test.tsx index 05c00d8aba0..114271998f8 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowHeader-12509.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.narrowHeader-12509.test.tsx @@ -154,7 +154,9 @@ describe('Studio shell header below and above 640 px (objectui#12509)', () => { const groups = Array.from(header.children); expect(groups).toHaveLength(3); expect(groups[1]).toBe(nav); - expect(within(groups[2] as HTMLElement).getByText(t('engine.studio.publish', 'en'))).toBeInTheDocument(); + // The actions column: with nothing pending and nothing edited, no Publish (objectstack#36511). + expect(groups[2]).toHaveClass('justify-end'); + expect(within(groups[2] as HTMLElement).queryByText(t('engine.studio.publish', 'en'))).toBeNull(); for (const key of ['data', 'automations', 'interfaces', 'access']) { const link = within(nav).getByRole('link', { name: t(`engine.studio.pillar.${key}`, 'en') }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageListErrorPosture.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageListErrorPosture.test.tsx index 9e41f2c6b50..cb787d0a2df 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageListErrorPosture.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.packageListErrorPosture.test.tsx @@ -131,7 +131,6 @@ describe('Studio top bar — package-list fetch failure is reported, not swallow await waitFor(() => expect(toastError).toHaveBeenCalled()); // The rest of the header survived the failure. expect(screen.getByRole('link', { name: 'Interfaces' })).toBeInTheDocument(); - expect(screen.getByRole('button', { name: /Publish/ })).toBeInTheDocument(); // …and its way out still works (objectstack#36501): no app is known, so // it goes to the console's landing. fireEvent.click(screen.getByTestId('studio-back-to-app')); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.publishPosture-12517.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.publishPosture-12517.test.tsx index 321ec437138..6b9f89304ed 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.publishPosture-12517.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.publishPosture-12517.test.tsx @@ -7,8 +7,7 @@ * * Publish stays review-then-confirm (objectui#2261): the header click opens the * sheet and publishes nothing; only the sheet's footer button does. With - * nothing pending, Publish stays disabled and described by - * `publish-none-reason` (objectui#12303). + * nothing pending, neither door is drawn (objectstack#36511). * * Real: the surface, `useMetadataClient` and `usePendingDrafts`. Stubbed: * `globalThis.fetch`, `packages-io`'s package list, `sonner`, the dock and @@ -171,19 +170,19 @@ describe('objectui#12517 — Publish opens the sheet to confirm, Changes opens i }); }); -describe('objectui#12517 keeps objectui#12303 — nothing pending', () => { +describe('objectui#12517 — nothing pending', () => { beforeEach(() => { pending = []; }); - it('Publish stays disabled and described by publish-none-reason; no count pill', async () => { + it('neither Changes nor Publish is drawn, and no count pill (objectstack#36511)', async () => { renderSurface(); - const reason = await screen.findByTestId('publish-none-reason'); - expect(publishButton()).toBeDisabled(); - expect(publishButton()).toHaveAttribute('aria-describedby', reason.id); + // The ledger was read and answered nothing. + await waitFor(() => expect(vi.mocked(fetch).mock.calls.some(([u]) => String(u) === DRAFTS)).toBe(true)); + await new Promise((r) => setTimeout(r, 50)); + expect(screen.queryByRole('button', { name: new RegExp(`^${t('engine.studio.changes', 'en')}`) })).toBeNull(); + expect(screen.queryByRole('button', { name: t('engine.studio.publish', 'en') })).toBeNull(); expect(screen.queryByTestId('studio-changes-count')).toBeNull(); - // Changes still opens the sheet, to review. - fireEvent.click(changesButton()); - expect(await screen.findByTestId('probe-changes-panel')).toHaveAttribute('data-posture', 'review'); + expect(screen.queryByTestId('publish-none-reason')).toBeNull(); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.publishReadOnlyReason-12303.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.publishReadOnlyReason-12303.test.tsx index ba07f6c26ab..2a5e14e7181 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.publishReadOnlyReason-12303.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.publishReadOnlyReason-12303.test.tsx @@ -16,12 +16,10 @@ * other half of the row, is pinned in * `StudioDesignSurface.automationsReadOnly-11124.test.tsx`. * - * objectstack#31495 — the other disabled state, a writable package with - * nothing pending ("No drafts pending publish"), kept the `title` on the - * disabled button: no wrapper, no tooltip on hover, and Tab skipped Publish. - * It now takes the same wrapper, described by the same `sr-only` reason - * (`publish-none-reason`); with a draft pending Publish is a plain enabled - * button again. Pinned in the last block below. + * objectstack#36511 — Publish is drawn only while drafts are pending, so the + * read-only cases below hold one, and with nothing pending there is no Publish + * and no "No drafts pending publish" reason (which objectstack#31495 had + * wrapped the same way). Pinned in the last block below. * * The REAL `StudioDesignSurface` over a fetch stub (the harness of * `StudioDesignSurface.interfacePolish.test.tsx`); only the package list's @@ -93,7 +91,7 @@ function json(body: unknown, status = 200) { beforeEach(() => { pkg.writable = false; - drafts = []; + drafts = [{ type: 'dashboard', name: 'acme_dashboard', packageId: PACKAGE_ID }]; vi.stubGlobal( 'fetch', vi.fn(async (input: unknown) => { @@ -134,11 +132,7 @@ const describedBy = (el: HTMLElement) => { return id ? document.getElementById(id) : null; }; -/** - * Publish once its wrapper gives `reason`. The wrapper alone is not enough to - * wait on: before the package list answers, an empty ledger already wraps - * Publish in the "nothing pending" reason (objectstack#31495). - */ +/** Publish once its wrapper gives `reason`. */ async function wrappedPublish(reason: string): Promise { renderWorkbench(); return waitFor( @@ -191,52 +185,28 @@ describe('Studio header Publish on a read-only package — the reason reaches th for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0)); }); const btn = publish(); + expect(btn).toBeEnabled(); expect(btn).not.toHaveAttribute('title', REASON); - // An empty ledger still wraps it, in its own reason (objectstack#31495). - expect(describedBy(btn.parentElement as HTMLElement)).toHaveTextContent(NONE_PENDING); - expect(describedBy(btn)).not.toHaveTextContent(REASON); + expect(btn.parentElement).not.toHaveAttribute('data-disabled-reason'); expect(screen.queryByText(REASON)).toBeNull(); }); }); -describe('Studio header Publish with nothing pending — the reason reaches the author (objectstack#31495)', () => { +describe('Studio header with nothing pending: no Publish, so no reason (objectstack#31495, objectstack#36511)', () => { beforeEach(() => { pkg.writable = true; }); - /** Publish on a writable package once the empty ledger has wrapped it. */ - const nonePendingPublish = () => wrappedPublish(NONE_PENDING); - - it('the wrapper is a tab stop, and it and the button are described by "No drafts pending publish"', async () => { - const btn = await nonePendingPublish(); - expect(btn).toBeDisabled(); - // The disabled button cannot show a `title`; the reason is the wrapper's. - expect(btn).not.toHaveAttribute('title'); - expect(btn).toHaveAccessibleDescription(NONE_PENDING); - const wrapper = btn.parentElement as HTMLElement; - expect(wrapper).toHaveAttribute('tabindex', '0'); - expect(wrapper).toHaveAccessibleDescription(NONE_PENDING); - // One reason element, the `sr-only` one both point at. - expect(describedBy(wrapper)).toBe(screen.getByTestId('publish-none-reason')); - expect(describedBy(btn)).toBe(describedBy(wrapper)); - // The wrapper takes the hover: the disabled button lets it through. - expect(btn.className).toMatch(/(^|\s)disabled:pointer-events-none(\s|$)/); - }); - - it('hovering Publish opens a tooltip with the reason', async () => { - const user = userEvent.setup(); - const btn = await nonePendingPublish(); - await user.hover(btn.parentElement as HTMLElement); - expect(await screen.findByRole('tooltip')).toHaveTextContent(NONE_PENDING); - }); - - it('a keyboard user reaches the reason: Tab from "Changes" lands on Publish’s wrapper, which opens the tooltip', async () => { - const user = userEvent.setup(); - const btn = await nonePendingPublish(); - screen.getByRole('button', { name: /^Changes/ }).focus(); - await user.tab(); - expect(btn.parentElement).toHaveFocus(); - expect(await screen.findByRole('tooltip')).toHaveTextContent(NONE_PENDING); + it('a writable package with an empty ledger draws no Publish and no "No drafts pending publish"', async () => { + drafts = []; + renderWorkbench(); + await waitFor(() => expect(fetchPackages).toHaveBeenCalled(), { timeout: 8000 }); + await act(async () => { + for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0)); + }); + expect(screen.queryByRole('button', { name: /^Publish/ })).toBeNull(); + expect(screen.queryByTestId('publish-none-reason')).toBeNull(); + expect(screen.queryByText(NONE_PENDING)).toBeNull(); }); it('CONTROL — a draft pending: a plain enabled Publish, no wrapper and no reason', async () => { From 9dac29fb375ec3b9021295d828ae41fda2e50d7a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 00:13:06 +0000 Subject: [PATCH 08/25] chore(changeset): Studio object page saves with Cancel and Save Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .changeset/36511-studio-save-cancel.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .changeset/36511-studio-save-cancel.md diff --git a/.changeset/36511-studio-save-cancel.md b/.changeset/36511-studio-save-cancel.md new file mode 100644 index 00000000000..cffcd3e6a4b --- /dev/null +++ b/.changeset/36511-studio-save-cancel.md @@ -0,0 +1,15 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(studio): the object page saves with Cancel and Save in the top bar, and a Save is live at once + +Clause-②: no +Metadata-protocol: none + +Studio's object page (fields, validation rules, actions, settings and field groups) no longer autosaves a draft 1.5 s after each edit. Edits stay on the page until the author presses Save, which sits at the right of the Studio top bar where Publish was; Cancel beside it puts the page back as the server holds it. Save writes the object's draft and then publishes that one object at the package it was written to, so the change is live at once. An installed app's object takes its edits into the paired `.custom` package and publishes them there. + +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. From b6f217c9a7d9dbbc3d783ad32088af8768c02f18 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 00:26:17 +0000 Subject: [PATCH 09/25] test(studio): narrow the verdict double's refused errors Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .../DataPillar.validationVerdictHold-27644.test.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.validationVerdictHold-27644.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.validationVerdictHold-27644.test.tsx index 5af369fa3fd..88e0276670a 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.validationVerdictHold-27644.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.validationVerdictHold-27644.test.tsx @@ -75,9 +75,9 @@ const mockClient: Record = { // objectstack#36511 — the Save's own publish: the door refuses the guard, and // the draft it judged stays pending; an accepted one goes live. publish: vi.fn(async () => { - const verdict = server.draft ? verdictOf(server.draft) : { valid: true as const }; - if ('errors' in verdict) { - const issues = verdict.errors.map((e) => ({ ...e, path: `objects.showcase_task.${e.path}` })); + const errors = server.draft ? verdictOf(server.draft).errors : undefined; + if (errors) { + const issues = errors.map((e) => ({ ...e, path: `objects.showcase_task.${e.path}` })); throw Object.assign(new Error(REFUSAL), { status: 422, code: 'VALIDATION_FAILED', issues }); } server.draft = null; From 40ddad601f61bdd484b45ee0dea5c920f372a1af Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 00:54:12 +0000 Subject: [PATCH 10/25] test(studio): the field-groups pins press Save Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .../DataPillar.internalFormRetired-36425.test.tsx | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.internalFormRetired-36425.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.internalFormRetired-36425.test.tsx index 3baf5241d44..9efa6fe9004 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.internalFormRetired-36425.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.internalFormRetired-36425.test.tsx @@ -15,8 +15,8 @@ * * Pinned: * - an object with a default internal form view: the field groups are the - * canvas, the chip says so, Add group saves the object's `fieldGroups` and - * writes no view; Preview shows the field groups, not the view's sections; + * canvas, the chip says so, Add group then the top bar's Save + * (objectstack#36511) saves the object's `fieldGroups` and writes no view; Preview shows the field groups, not the view's sections; * - CONTROL: no form view: the same canvas and the same save. */ @@ -109,6 +109,7 @@ const mockClient = { return pending ? { item: pending.served, version: 'v7' } : null; }), get: vi.fn(async () => null), + publish: vi.fn(async () => ({})), reset: vi.fn(async () => ({})), save: vi.fn(async () => ({ ok: true, version: 'v2', state: 'draft' })), }; @@ -140,6 +141,7 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { // warmed here so its first load is paid at import, not inside a test's clock. import '@objectstack/lint'; import { DataPillar, type StudioBaseCustomization } from './StudioDesignSurface'; +import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { t } from '../metadata-admin/i18n'; const FORM = t('engine.studio.data.tab.form', 'en'); @@ -160,9 +162,9 @@ afterEach(() => { async function openForm(props: { readOnly?: boolean; customization?: StudioBaseCustomization } = {}) { render( - + - , + , ); await waitFor(() => expect(screen.getByTestId('records-panel')).toBeInTheDocument(), { timeout: 8000 }); await userEvent.click(screen.getAllByRole('button', { name: FORM })[0]); @@ -186,6 +188,7 @@ describe('the Form tab lays out by field groups, internal form or not (objectsta expect(screen.queryByTestId('form-layout-flow')).toBeNull(); await userEvent.click(screen.getByTestId('form-designer-add-section-footer')); + await pressStudioSave(); await waitFor(() => expect(saves().length).toBe(1), { timeout: 4000 }); const [type, name, body] = saves()[0]; expect([type, name]).toEqual(['object', OBJECT]); @@ -219,6 +222,7 @@ describe('the Form tab lays out by field groups, internal form or not (objectsta expect(screen.getByText(UNGROUPED)).toBeInTheDocument(); await userEvent.click(screen.getByTestId('form-designer-add-section-footer')); + await pressStudioSave(); await waitFor(() => expect(saves().length).toBe(1), { timeout: 4000 }); const [type, name, body] = saves()[0]; expect([type, name]).toEqual(['object', OBJECT]); From 38d53121e53c82e9d2bb5caf097c573d1c96d401 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 00:55:57 +0000 Subject: [PATCH 11/25] test(studio): pay the linter's first load at collection; the lint debounce in its own module Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .../app-shell/src/views/metadata-admin/CelPredicateField.tsx | 3 +-- .../app-shell/src/views/metadata-admin/celLintDebounce.ts | 4 ++++ .../studio-design/DataPillar.actionRefusal-26736.test.tsx | 2 ++ .../studio-design/DataPillar.addFieldPopover-12516.test.tsx | 2 ++ .../studio-design/DataPillar.authorRefusal-11785.test.tsx | 2 ++ .../DataPillar.choiceWithoutOptions-11253.test.tsx | 2 ++ .../studio-design/DataPillar.draftSavedNamed-28984.test.tsx | 2 ++ .../studio-design/DataPillar.draftUnreadable-29148.test.tsx | 2 ++ .../studio-design/DataPillar.heldIncomplete-11786.test.tsx | 2 ++ .../DataPillar.hiddenSystemFields-11780.test.tsx | 2 ++ .../src/views/studio-design/DataPillar.panelGate.test.tsx | 2 ++ .../views/studio-design/DataPillar.panelHold-27629.test.tsx | 2 ++ .../DataPillar.picklistServedOptions-10202.test.tsx | 2 ++ .../studio-design/DataPillar.railSwitchFlush-27511.test.tsx | 2 ++ .../views/studio-design/DataPillar.showMeFocus-26730.test.tsx | 2 ++ .../views/studio-design/DataPillar.summaryHeld-27461.test.tsx | 2 ++ .../StudioDesignSurface.autosaveInFlight-11204.test.tsx | 2 ++ .../StudioDesignSurface.draftVersionConflict-11773.test.tsx | 2 ++ .../StudioDesignSurface.interfacePolish.test.tsx | 2 ++ .../app-shell/src/views/studio-design/studioSaveBar.tsx | 2 +- 20 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 ui/packages/app-shell/src/views/metadata-admin/celLintDebounce.ts diff --git a/ui/packages/app-shell/src/views/metadata-admin/CelPredicateField.tsx b/ui/packages/app-shell/src/views/metadata-admin/CelPredicateField.tsx index a1bf776b2c9..159f1b9c1f7 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/CelPredicateField.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/CelPredicateField.tsx @@ -79,8 +79,7 @@ import { useServerHoldAt, type ServerDiagnosticEntry } from './draftVerdict.js'; // fields as lists (`celAuthoring.ts` stays free of any import at load). import { multiValueFieldsOf, type CelFieldDef } from './clientValidation.js'; -/** The lint pass runs this long after the last keystroke; Studio's Save waits it out (objectstack#36511). */ -export const LINT_DEBOUNCE_MS = 250; +import { LINT_DEBOUNCE_MS } from './celLintDebounce.js'; const KIND_TAG: Record = { field: 'field', diff --git a/ui/packages/app-shell/src/views/metadata-admin/celLintDebounce.ts b/ui/packages/app-shell/src/views/metadata-admin/celLintDebounce.ts new file mode 100644 index 00000000000..3670aaed51d --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/celLintDebounce.ts @@ -0,0 +1,4 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** The CEL editors lint this long after the last keystroke; Studio's Save waits it out (objectstack#36511). */ +export const LINT_DEBOUNCE_MS = 250; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx index a4419c4f711..770e0983c5d 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx @@ -130,6 +130,8 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource } from './__tests__/emptyDataSource'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx index f347132120d..374bf0d88e4 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.addFieldPopover-12516.test.tsx @@ -69,6 +69,8 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { return { ...mod, ObjectView: GridDouble }; }); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { t } from '../metadata-admin/i18n'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx index 319ab508fda..42a8d2aec7f 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx @@ -76,6 +76,8 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx index 7ac3f2de38b..c7cfef20a72 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx @@ -94,6 +94,8 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.draftSavedNamed-28984.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.draftSavedNamed-28984.test.tsx index 4eb7b6b44e4..614508351a6 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.draftSavedNamed-28984.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.draftSavedNamed-28984.test.tsx @@ -85,6 +85,8 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.draftUnreadable-29148.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.draftUnreadable-29148.test.tsx index 9543b0d19e6..cd67d5702b8 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.draftUnreadable-29148.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.draftUnreadable-29148.test.tsx @@ -111,6 +111,8 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { return { ...mod, ObjectView: GridDouble }; }); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar, type StudioBaseCustomization } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { t } from '../metadata-admin/i18n'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx index 888e41118e3..947df0a5b66 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx @@ -79,6 +79,8 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.hiddenSystemFields-11780.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.hiddenSystemFields-11780.test.tsx index b60d44bb695..57210ff2fc4 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.hiddenSystemFields-11780.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.hiddenSystemFields-11780.test.tsx @@ -201,6 +201,8 @@ vi.mock('@dnd-kit/core', async (importOriginal) => { return { ...actual, DndContext: CapturingDndContext }; }); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { SurfaceDeepLinkProvider } from './surfaceDeepLinkChannel'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.panelGate.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.panelGate.test.tsx index 29ea92c5076..95665cdf99c 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.panelGate.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.panelGate.test.tsx @@ -98,6 +98,8 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.panelHold-27629.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.panelHold-27629.test.tsx index e1ea16f5e7a..9598b24c32a 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.panelHold-27629.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.panelHold-27629.test.tsx @@ -104,6 +104,8 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { createEmptyDataSource, failOnAbsorbedFetchError } from './__tests__/emptyDataSource'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx index faaceaa0814..8e31b093edd 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx @@ -144,6 +144,8 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromGrid } from './__tests__/dataPillarAddField'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.railSwitchFlush-27511.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.railSwitchFlush-27511.test.tsx index 8922a97a727..ffdff986de0 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.railSwitchFlush-27511.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.railSwitchFlush-27511.test.tsx @@ -121,6 +121,8 @@ vi.mock('sonner', () => ({ Toaster: () => null, })); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromGrid } from './__tests__/dataPillarAddField'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx index 4378af843bd..7ad6fdc5e5e 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx @@ -112,6 +112,8 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx index c1be2f21737..f2dfe3f9aeb 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx @@ -69,6 +69,8 @@ vi.mock('@object-ui/react', async (importOriginal) => { return { ...mod, useAdapter: () => dataSource }; }); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar } from './__tests__/dataPillarAddField'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveInFlight-11204.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveInFlight-11204.test.tsx index c23669d6cc4..0ed86e7336d 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveInFlight-11204.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.autosaveInFlight-11204.test.tsx @@ -177,6 +177,8 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { AutomationsPillar, DataPillar, InterfacesPillar } from './StudioDesignSurface'; import { StudioSaveHarness, pressStudioSave } from './__tests__/studioSaveHarness'; import { addFieldFromGrid } from './__tests__/dataPillarAddField'; 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 b43102e4671..4c8f86097a5 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 @@ -186,6 +186,8 @@ vi.mock('@object-ui/plugin-view', async (importOriginal) => { vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), dismiss: vi.fn() } })); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { DataPillar } from './StudioDesignSurface'; import { StudioSaveHarness } from './__tests__/studioSaveHarness'; import { addFieldFromFormToolbar, addFieldFromGrid, type AddFieldInput } from './__tests__/dataPillarAddField'; diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacePolish.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacePolish.test.tsx index 5695d5f3b48..cc7174d5447 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacePolish.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.interfacePolish.test.tsx @@ -53,6 +53,8 @@ vi.mock('../../components/SuggestedBindingsPanel', () => ({ SuggestedBindingsPan vi.mock('../metadata-admin/AccessExplainPanel', () => ({ AccessExplainPanel: () => null })); vi.mock('./StudioAiCopilot', () => ({ StudioChatDock: () => null })); +// The source reaches a dynamic import of it: its first load is paid at collection (`check:test-source-alias`). +import '@objectstack/lint'; import { StudioDesignSurface } from './StudioDesignSurface'; // The designer rows this suite reads in zh live in `@object-ui/i18n`'s `studio` diff --git a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx index e76aad339df..d02c2092eb6 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx @@ -33,7 +33,7 @@ import { cn } from '@object-ui/components'; import type { MetadataClient } from '@object-ui/data-objectstack'; import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; import { t, tFormat } from '../metadata-admin/i18n.js'; -import { LINT_DEBOUNCE_MS } from '../metadata-admin/CelPredicateField.js'; +import { LINT_DEBOUNCE_MS } from '../metadata-admin/celLintDebounce.js'; /** Past the editors' expression check of the last keystroke, and its report. */ const VERDICT_SETTLE_MS = LINT_DEBOUNCE_MS + 50; From 1d6c0845f5c23cddf062cd66f26c8f799462c688 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 01:31:02 +0000 Subject: [PATCH 12/25] fix(studio): the save bar's registry adds a buffer with enlist, not register Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .../app-shell/src/views/studio-design/studioSaveBar.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx index d02c2092eb6..8628df7a46b 100644 --- a/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx +++ b/ui/packages/app-shell/src/views/studio-design/studioSaveBar.tsx @@ -67,7 +67,8 @@ export interface StudioSaveEntry { } interface StudioSaveRegistry { - register: (id: number, entry: React.MutableRefObject) => () => void; + /** Add a buffer; the answer removes it. (Not `register`: that name is the component registry's.) */ + enlist: (id: number, entry: React.MutableRefObject) => () => void; /** An entry's `dirty` or `held` changed: the top bar re-reads them. */ changed: () => void; } @@ -94,7 +95,7 @@ export function useStudioSaveEntry(entry: StudioSaveEntry | null): void { const [id] = React.useState(() => ++nextEntryId); React.useEffect(() => { if (!registry) return; - return registry.register(id, ref); + return registry.enlist(id, ref); }, [registry, id]); const dirty = entry?.dirty ?? false; const held = entry?.held ?? null; @@ -127,7 +128,7 @@ export function useStudioSaveCoordinator(locale: string): StudioSaveCoordinator }, []); // A state initializer, so its identity is the surface's for life (AGENTS.md #10). const [registry] = React.useState(() => ({ - register: (id, ref) => { + enlist: (id, ref) => { entriesRef.current.set(id, ref); setDirty(readDirty()); return () => { From a184f37f99f13f75621ae8204243b4531d5fd3f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 02:06:07 +0000 Subject: [PATCH 13/25] wip(studio): the hooks buffer lifted to the Data pillar, saved by the top bar Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .../views/studio-design/ObjectHooksPanel.tsx | 419 ++-------------- .../studio-design/StudioDesignSurface.tsx | 26 +- .../views/studio-design/objectHooksBuffer.ts | 452 ++++++++++++++++++ ui/packages/i18n/src/namespaces/studio/en.ts | 17 +- ui/packages/i18n/src/namespaces/studio/zh.ts | 15 +- 5 files changed, 530 insertions(+), 399 deletions(-) create mode 100644 ui/packages/app-shell/src/views/studio-design/objectHooksBuffer.ts diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx index 8413d38545c..f3dfd93964f 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx @@ -9,390 +9,70 @@ /** * Data pillar — Hooks view. * - * Unlike validations/actions (inline arrays on the object draft), hooks are a - * SEPARATE `hook` metadata type whose `object` field targets one object, a - * list, or `*`. So this panel fetches them (client.list) and persists each one - * on its own (client.save('hook', …, { mode: 'draft' })) — the object's Save - * draft doesn't cover them. + * Hooks are a SEPARATE `hook` metadata type whose `object` field targets one + * object, a list, or `*`, so each is saved on its own, not with the object. + * The list, the open hook's buffer and its Save live in the pillar's + * {@link ObjectHooksBuffer} (`objectHooksBuffer.ts`, objectstack#36511): this + * view draws them and survives being unmounted by a tab switch. An edit stays + * on the page until the top bar's Save, which makes the hook live at once. * * Master-detail, editable: a left list of the hooks that fire on this object, * and on the right the hook's inspector (the platform's generic metadata form, - * SchemaForm, until the curated one registers). An edit autosaves to the - * hook's draft the way the other Studio editors do (objectui#11787): the shared - * autosave, 1.5s after the last edit, held while a CEL syntax error stands or - * while the hook's name differs from the one it was created with, and the - * panel's status line in place of the old Save hook button. - * - * A new hook targets the object it is created from (`addHook`). Its target - * picker is told which objects belong to this package (objectui#11820), so it - * lists them first and puts every other object — other packages' and the - * platform's own — under a heading that warns about the reach. + * SchemaForm, until the curated one registers). A new hook targets the object + * it is created from. Its target picker is told which objects belong to this + * package (objectui#11820), so it lists them first and puts every other object + * under a heading that warns about the reach. */ import React from 'react'; import { Webhook, Plus, Loader2 } from 'lucide-react'; -import { useDisplayLocale } from '@object-ui/i18n'; import { SchemaForm } from '../metadata-admin/SchemaForm.js'; import { useRegisteredMetadataDefaultInspector } from '../metadata-admin/default-inspector-registry.js'; -import { HookTargetScopeContext, type HookTargetScope } from '../metadata-admin/inspectors/HookDefaultInspector.js'; -import { loadPackageSurfaces } from './packageSurfaces.js'; -import { useMetadataClient } from '../metadata-admin/useMetadata.js'; -// objectui#11773 — the hook's draft save sends the version it was built on. -import { readDraftForSave, useDraftSaveGuard, type DraftPin } from '../metadata-admin/DraftConflictDialog.js'; -// objectui#11787 — a hook autosaves through the pillars' own autosave. -import { useDraftAutoSave, type DraftSend } from './useDraftAutoSave.js'; +import { HookTargetScopeContext } from '../metadata-admin/inspectors/HookDefaultInspector.js'; import { StudioEmptyState, StudioEmptyStateAction } from './StudioEmptyState.js'; import { t, tFormat, useMetadataLocale } from '../metadata-admin/i18n.js'; -// `formatMetadataError` is the one metadata-save error reader (objectui#11302). -import { extractDraftBody, formatMetadataError } from '@object-ui/data-objectstack'; - -interface HookItem { - name?: string; - label?: string; - object?: string | string[]; - async?: boolean; - [key: string]: unknown; -} - -/** - * The body out of a `getDraft()` envelope, decoration-free (objectui#8181). - * - * This was a hand-rolled fourth copy of `extractDraftBody` that skipped the - * read-decoration strip, so a served `_diagnostics` / `_draft` rode the hook - * body into `save('hook', ...)` below. The unwrap is the shared one now; only - * the `HookItem` narrowing is local. - */ -const draftBody = (resp: unknown): HookItem | null => - extractDraftBody(resp) as HookItem | null; - -/** Does this hook's `object` target match the object we're viewing? */ -function targetsObject(hook: HookItem, objectName: string): boolean { - const target = hook.object; - if (target === '*') return true; - if (typeof target === 'string') return target === objectName; - if (Array.isArray(target)) return target.includes(objectName) || target.includes('*'); - return false; -} - -/** A fresh, unique, snake_case hook name scoped to the object. */ -function nextHookName(objectName: string, existing: string[]): string { - const base = (objectName || 'hook').replace(/[^a-z0-9_]/gi, '_').toLowerCase(); - const taken = new Set(existing); - let i = existing.length + 1; - let name = `${base}_hook_${i}`; - while (taken.has(name)) name = `${base}_hook_${++i}`; - return name; -} +import { formatMetadataError } from '@object-ui/data-objectstack'; +import type { HookItem, ObjectHooksBuffer } from './objectHooksBuffer.js'; export function ObjectHooksPanel({ - objectName, - packageId, + buffer, disabled, hookSchema, - publishNonce = 0, - onDraftSaved, }: { - objectName: string; - packageId: string; + /** The pillar's hooks buffer for the open object. */ + buffer: ObjectHooksBuffer; disabled?: boolean; - /** - * objectui#11773 — bumped by a package publish, which drops every draft and - * with them the version this panel's last save received. - */ - publishNonce?: number; /** * The live server JSONSchema for the `hook` type (`/meta/types`). Drives the * SchemaForm so the fields, enums and grouping come from the real hook * metadata contract rather than being synthesised from the value shape. */ hookSchema?: Record; - /** - * objectui#11787 — a hook draft landed (an edit, or "+ New"), so the - * surface's pending-changes count refreshes, as every other draft save does. - */ - onDraftSaved?: () => void; }) { const locale = useMetadataLocale(); - const client = useMetadataClient(); - // Curated hook authoring surface (object picker + events + dedicated body - // editor); falls back to the generic SchemaForm if unregistered, and swaps - // the curated surface in if it is registered later (objectui#11939). + // Curated hook authoring surface; falls back to the generic SchemaForm if + // unregistered, and swaps the curated surface in if it is registered later + // (objectui#11939). const HookInspector = useRegisteredMetadataDefaultInspector('hook'); - const [hooks, setHooks] = React.useState([]); - // objectstack#29148 — the listed hooks whose pending draft the server refused - // to read (`403`), with the refusal as thrown. Such a hook opens no buffer: - // one seeded from its published row would be saved over the draft it never - // read. The other hooks of the list load as before. - const [refusedHooks, setRefusedHooks] = React.useState>(() => new Map()); - const [loading, setLoading] = React.useState(true); - const [error, setError] = React.useState(null); - const [selected, setSelected] = React.useState(null); - const [draft, setDraft] = React.useState(null); - // objectui#11787 — the hook whose body the buffer holds (`selected` when its - // install has run), and when its last draft save landed. - const [draftFor, setDraftFor] = React.useState(null); - const [savedAt, setSavedAt] = React.useState<{ hook: string; at: Date } | null>(null); - const displayLocale = useDisplayLocale(); - const [dirty, setDirty] = React.useState(false); - const [saving, setSaving] = React.useState(false); - const [nonce, setNonce] = React.useState(0); - // objectui#11773 — each hook's pin: what the list load read for it (its - // draft's version, or "no draft row"), then each save's receipt. A save - // writes the list in place (objectui#11787) and the re-read that follows - // "+ New" reads back what was written, so the pin survives both; a - // conflict's "reload" re-reads the list, and a publish forgets every pin. - const reloadHooks = React.useCallback(() => setNonce((n) => n + 1), []); const { - save: saveHookDraft, - recordRead: recordHookRead, - forget: forgetHookVersion, - dialog: hookConflictDialog, - } = useDraftSaveGuard(client, reloadHooks); - React.useEffect(() => { - forgetHookVersion(); - }, [publishNonce, forgetHookVersion]); - // The publish a list load started under: a load still in flight when a - // publish lands read the drafts that publish drained, so it records no pins. - const publishNonceRef = React.useRef(publishNonce); - React.useLayoutEffect(() => { - publishNonceRef.current = publishNonce; - }); - - /* ─── objectui#11820 — the objects of this package, for the target picker ── - * - * The package's own list — published and draft, the merge the pillars' rails - * use (`loadPackageSurfaces`) — plus the object this panel is open on, which - * the Data pillar only offers from this package. Held in state, stamped with - * the package it was read for, so the context value keeps its identity - * between reads and a scope read for another package is never applied. - * Until it answers, and if it fails, the picker shows its flat list. */ - const [packageScope, setPackageScope] = React.useState< - (HookTargetScope & { packageId: string; objectName: string }) | null - >(null); - React.useEffect(() => { - let cancelled = false; - loadPackageSurfaces(client, 'object', packageId) - .then((items) => { - if (cancelled) return; - const names = new Set(items.map((i) => i.name)); - names.add(objectName); - setPackageScope({ packageId, objectName, packageObjects: names }); - }) - .catch(() => { - if (!cancelled) setPackageScope(null); - }); - return () => { - cancelled = true; - }; - }, [client, packageId, objectName]); - const hookTargetScope = - packageScope && packageScope.packageId === packageId && packageScope.objectName === objectName - ? packageScope - : null; - - /* ─── Blocking CEL verdicts → this panel's OWN save (objectui#4527) ──────── - * - * Unlike the object's other panels, this one writes the hook itself - * (`client.save('hook', …, { mode: 'draft' })`), so it owns the save that - * has to refuse: the autosave below is held while one stands (objectui#11787). The count is STAMPED with the hook it describes and - * mismatch is read as 0, so a verdict that lands after the author switched - * hooks cannot gate the one now on screen — derivation, not a reset effect, - * and the selected hook always has its editor available to fix in. */ - const [celErrors, setCelErrors] = React.useState<{ hook: string; count: number }>({ - hook: '', - count: 0, - }); - const selectedHookName = String(draft?.name ?? ''); - const reportCel = React.useCallback( - (count: number) => { - setCelErrors((prev) => { - if (prev.hook !== selectedHookName) return { hook: selectedHookName, count }; - if (prev.count === count) return prev; - return { hook: selectedHookName, count }; - }); - }, - [selectedHookName], - ); - const blockingIssues = celErrors.hook === selectedHookName ? celErrors.count : 0; - - // The hook the buffer holds and whether it holds an unsent edit, read by the - // list load (objectui#11773) and the install below (objectui#11787). - const bufferRef = React.useRef({ hook: draftFor, dirty }); - React.useLayoutEffect(() => { - bufferRef.current = { hook: draftFor, dirty }; - }); - - React.useEffect(() => { - let cancelled = false; - const publishAtStart = publishNonceRef.current; - setLoading(true); - setError(null); - (async () => { - try { - // `list()` only sees PUBLISHED hooks; a freshly-created (or edited) - // hook is a draft, so also pull draft headers and hydrate each body - // (headers carry no `object`, so we must load them to filter + edit). - // Drafts win over the published row of the same name. - const [pub, draftHeaders] = await Promise.all([ - client.list('hook', { packageId }) as Promise, - client.listDrafts({ packageId, type: 'hook' }).catch(() => null), - ]); - const draftNames = (draftHeaders || []).map((d) => String(d.name ?? '')).filter(Boolean); - // objectui#11773 — each draft is read at the address its save writes - // (`?package=` this package), so the version it serves pins that save. - const reads = await Promise.all(draftNames.map((n) => readDraftForSave(client, 'hook', n, packageId))); - if (cancelled) return; - const byName = new Map(); - // What the next save of each listed hook is pinned to. A hook this - // package's drafts ledger does not list has no draft at the save's - // address — when the ledger was read at all: an unreadable ledger says - // nothing, and pins nothing. - const pins = new Map(); - const refused = new Map(); - for (const h of pub || []) { - if (h?.name && targetsObject(h, objectName)) { - byName.set(String(h.name), h); - pins.set(String(h.name), draftHeaders ? { ifNoneMatch: '*' } : null); - } - } - draftNames.forEach((n, i) => { - const read = reads[i]!; - // A refused draft is not this hook's absence. Its published row stays - // listed and pins nothing; a hook known only by its refused draft is - // not listed, since nothing says it fires on this object. - if ('refused' in read) { - if (byName.has(n)) { - refused.set(n, read.refused); - pins.set(n, null); - } - return; - } - const body = draftBody(read.answer); - if (body && targetsObject(body, objectName)) byName.set(n, body); - if (byName.has(n)) pins.set(n, reads[i]!.pin); - }); - setHooks([...byName.values()]); - setRefusedHooks(refused); - // A hook whose buffer holds an unsent edit keeps the pin that edit was - // built on: the install below does not replace that buffer either. - const open = bufferRef.current; - for (const [n, pin] of pins) { - if (publishNonceRef.current !== publishAtStart) break; - if (!(open.dirty && open.hook === n)) recordHookRead('hook', n, packageId, pin); - } - } catch (e) { - if (!cancelled) setError(formatMetadataError(e)); - } finally { - if (!cancelled) setLoading(false); - } - })(); - return () => { - cancelled = true; - }; - }, [client, packageId, objectName, nonce, recordHookRead]); - - // Load the selected hook into an editable draft: on a selection change, and - // when the list changes. objectui#11787 — except over an unsent edit of that - // same hook: the list an autosave writes holds what that save sent, and an - // edit the author took meanwhile is newer than it (`bufferRef`, above). - React.useEffect(() => { - if (selected !== null && bufferRef.current.hook === selected && bufferRef.current.dirty) return; - // objectstack#29148 — no buffer over a draft the server refused to read. - const hook = selected !== null && refusedHooks.has(selected) ? null : (hooks.find((h) => h.name === selected) ?? null); - setDraft(hook ? { ...hook } : null); - setDraftFor(hook ? selected : null); - setDirty(false); - }, [selected, hooks, refusedHooks]); - - const save = React.useCallback(async (sent: DraftSend) => { - if (!draft?.name) return; - setSaving(true); - setError(null); - try { - if ((await saveHookDraft('hook', String(draft.name), draft, { mode: 'draft', packageId, surface: 'studio' })) === 'reloaded') { - // objectui#11773 — the author chose the saved version: the list re-read - // installs it over this buffer, which holds nothing of theirs to keep. - setDirty(false); - return; - } - // No success toast: with autosave it would fire after every editing - // pause; the status line is the affordance (objectui#11787). - // objectui#11204 — clean only if nothing was edited while it was in flight. - if (sent.unmoved()) setDirty(false); - setSavedAt({ hook: String(selected ?? ''), at: new Date() }); - onDraftSaved?.(); - // The list now holds what the draft holds. Written in place rather than - // read again: a re-read blanks the list to "Loading…" at every editing - // pause, and it would answer with this very body (a draft wins over the - // published row of its name, and a hook no longer aimed at this object - // leaves its list). - const sentBody = draft; - setHooks((list) => { - const kept = list.filter((h) => h.name !== sentBody.name); - if (!targetsObject(sentBody, objectName)) return kept; - const at = list.findIndex((h) => h.name === sentBody.name); - return at < 0 ? [...kept, sentBody] : list.map((h, i) => (i === at ? sentBody : h)); - }); - } catch (e) { - setError(formatMetadataError(e)); - } finally { - setSaving(false); - } - }, [saveHookDraft, draft, packageId, selected, onDraftSaved, objectName]); - - // objectui#11787 — a hook autosaves to its draft like the pillars' editors: - // the shared autosave, blocked where the Save hook button was disabled (a - // blocking CEL verdict holds the edit, objectui#4527) and while the package - // is read-only. The hook is the open item; the buffer is its own once the - // install above has run for it. - const hookTarget = `hook:${selected ?? ''}`; - // objectui#11787 — a hook keeps the name it was created with ("+ New" sets - // it). The draft is stored under its name, and the inspector commits the name - // on every keystroke, so a rename the autosave sent would stage one more hook - // per pause while typing (measured: two drafts, each under a partial name, - // beside the original). The same rule the package door's permission matrix - // keeps for its api name: a renamed buffer is held, and the line below says - // how to get the edit saved. - const renamedFrom = - draft !== null && draftFor !== null && String(draft.name ?? '') !== draftFor ? draftFor : null; - useDraftAutoSave({ - target: hookTarget, - loadedFor: `hook:${draftFor ?? ''}`, + hooks, + refusedHooks, + loading, + error, + selected, + draft, dirty, - blocked: !draft?.name || saving || !!disabled || blockingIssues > 0 || renamedFrom !== null, - snapshot: draft, - save, - }); - - const addHook = React.useCallback(async () => { - const name = nextHookName(objectName, hooks.map((h) => String(h.name ?? ''))); - // A complete, *valid* skeleton so the immediate save passes: hooks require - // an object, at least one event, and a valid body discriminator. - const fresh: HookItem = { - name, - label: t('engine.studio.hooks.newLabel', locale), - object: objectName, - events: ['beforeInsert'], - body: { language: 'js', source: 'return;' }, - priority: 100, - async: false, - }; - setSaving(true); - setError(null); - try { - // objectui#11773 — a create is the first-write pin: refused where the - // name already holds a draft, instead of written over it. - await client.save('hook', name, fresh, { mode: 'draft', packageId, ifNoneMatch: '*', surface: 'studio' }); - // objectui#11787 — a new hook is a new draft: the count says so. - onDraftSaved?.(); - setNonce((n) => n + 1); - setSelected(name); - } catch (e) { - setError(formatMetadataError(e)); - } finally { - setSaving(false); - } - }, [client, objectName, hooks, packageId, locale, onDraftSaved]); + saving, + renamedFrom, + blockingIssues, + hookTargetScope, + select: setSelected, + patch, + replace, + addHook, + reportCel, + dialog: hookConflictDialog, + } = buffer; // objectui#12514 — an object no hook targets is one centered block whose // button runs the list header's own "New". @@ -503,25 +183,18 @@ export function ObjectHooksPanel({ <>
{String(draft.label || draft.name)} - {/* objectui#11787 — the status line every Studio editor shows in - place of a Save button: saving while in flight, the - last-saved time once landed, and why an edit is held when a - CEL syntax error holds it. */} + {/* objectstack#36511 — the top bar's Save sends the hook; the + line says only that it is on its way, and why an edit is + held when an expression error holds it. */} {disabled ? null : saving ? ( - + {t('engine.studio.autoSaving', locale)} ) : renamedFrom !== null ? null : blockingIssues > 0 && dirty ? ( - + {t('perm.cel.saveBlocked', locale)} - ) : savedAt && savedAt.hook === selected && !dirty ? ( - - {tFormat('engine.studio.data.lastSaved', locale, { - time: savedAt.at.toLocaleTimeString(displayLocale, { hour: '2-digit', minute: '2-digit' }), - })} - ) : null}
{renamedFrom !== null && !disabled && ( @@ -541,10 +214,7 @@ export function ObjectHooksPanel({ type="hook" name={String(draft.name ?? '')} draft={draft as Record} - onPatch={(patch) => { - setDraft((d) => ({ ...(d as HookItem), ...patch })); - setDirty(true); - }} + onPatch={(change) => patch(change as Partial)} readOnly={!!disabled} locale={locale} serverSchema={hookSchema} @@ -556,10 +226,7 @@ export function ObjectHooksPanel({ } - onChange={(next) => { - setDraft(next as HookItem); - setDirty(true); - }} + onChange={(next) => replace(next as HookItem)} readOnly={!!disabled} /> 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 23d31e33403..10f08fd9501 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx @@ -455,6 +455,7 @@ import { ObjectSettingsPanel } from './ObjectSettingsPanel.js'; import { PackageOwdOverviewPanel } from './PackageOwdOverviewPanel.js'; import { ObjectApiPanel } from './ObjectApiPanel.js'; import { ObjectHooksPanel } from './ObjectHooksPanel.js'; +import { useObjectHooksBuffer } from './objectHooksBuffer.js'; import { ObjectActionsPanel } from './ObjectActionsPanel.js'; import { getIcon } from '../../utils/getIcon.js'; import { @@ -6979,16 +6980,26 @@ export function DataPillar({ } : null, ); - // objectstack#36511 — opening another object replaces the buffer the open + // objectstack#36511 — the Hooks tab's buffer lives here, not in its panel, + // so an edit outlives a tab switch and the top bar's Save still sends it. + const hooksBuffer = useObjectHooksBuffer({ + objectName: current?.name ?? '', + packageId, + active: viewMode === 'hooks', + disabled: readOnly, + publishNonce, + }); + // objectstack#36511 — opening another object replaces the buffers the open // object's unsaved edits live in, so the author is asked first, as every // departure asks (objectstack#26705); nothing is sent by the switch. + const pageDirty = dirty || extDirty || hooksBuffer.dirty; const openObject = React.useCallback( (next: Surface): boolean => { - if (next.name !== current?.name && !confirmDropUnsavedWork(dirty || extDirty, locale)) return false; + if (next.name !== current?.name && !confirmDropUnsavedWork(pageDirty, locale)) return false; setCurrent(next); return true; }, - [current, dirty, extDirty, locale], + [current, pageDirty, locale], ); // The live request's apply (see `requestedSurface` above). objectstack#26845 // — another object's load replaces the buffer a held edit lives in, so it @@ -7702,14 +7713,7 @@ export function DataPillar({ onBlockingIssuesChange={reportPanelBlocking} /> ) : viewMode === 'hooks' ? ( - + ) : viewMode === 'actions' ? (
extractDraftBody(resp) as HookItem | null; + +/** Does this hook's `object` target match the object we're viewing? */ +export function targetsObject(hook: HookItem, objectName: string): boolean { + const target = hook.object; + if (target === '*') return true; + if (typeof target === 'string') return target === objectName; + if (Array.isArray(target)) return target.includes(objectName) || target.includes('*'); + return false; +} + +/** A fresh, unique, snake_case hook name scoped to the object. */ +function nextHookName(objectName: string, existing: string[]): string { + const base = (objectName || 'hook').replace(/[^a-z0-9_]/gi, '_').toLowerCase(); + const taken = new Set(existing); + let i = existing.length + 1; + let name = `${base}_hook_${i}`; + while (taken.has(name)) name = `${base}_hook_${++i}`; + return name; +} + +/** The order the hooks buffer saves in, after the object and its extension: a hook reads the object's fields. */ +const HOOKS_SAVE_ORDER = 3; + +export interface ObjectHooksBuffer { + /** The hooks that fire on the object, a new unsaved one last. */ + hooks: readonly HookItem[]; + /** Listed hooks whose pending draft the server refused to read (objectstack#29148). */ + refusedHooks: ReadonlyMap; + loading: boolean; + error: string | null; + selected: string | null; + /** The open hook as edited, or `null`. */ + draft: HookItem | null; + /** The open hook holds edits the server does not have (a new hook always does). */ + dirty: boolean; + /** A Save of the open hook is in flight. */ + saving: boolean; + /** The stored name, while the buffer's `name` differs from it. */ + renamedFrom: string | null; + /** The open hook's expression errors, as its inspector last reported them. */ + blockingIssues: number; + /** The package's objects, for the target picker (objectui#11820); `null` until read. */ + hookTargetScope: HookTargetScope | null; + /** Open a hook; asks first over an unsaved edit of another. */ + select: (name: string | null) => void; + /** Patch the open hook. */ + patch: (change: Partial) => void; + /** Replace the open hook's body (the generic form's whole-value change). */ + replace: (next: HookItem) => void; + /** Start a new hook on the object: listed and opened, sent by Save. */ + addHook: () => void; + /** The open hook's inspector reports its expression errors. */ + reportCel: (count: number) => void; + /** The draft conflict dialog; render it once. */ + dialog: React.ReactElement; +} + +export function useObjectHooksBuffer({ + objectName, + packageId, + active, + disabled, + publishNonce = 0, +}: { + objectName: string; + packageId: string; + /** The Hooks tab is open: the first time for this object, the list is read. */ + active: boolean; + disabled?: boolean; + /** Bumped by a package publish, which drops every draft and the versions its saves received. */ + publishNonce?: number; +}): ObjectHooksBuffer { + const locale = useMetadataLocale(); + const client = useMetadataClient(); + const key = `${packageId}/${objectName}`; + // Latched: once opened for this object, the buffer stays read while other tabs show. + const [openedFor, setOpenedFor] = React.useState(null); + if (active && objectName && openedFor !== key) setOpenedFor(key); + const live = openedFor === key; + + const [listed, setListed] = React.useState([]); + // The new hook "+ New" started, until a Save writes it. + const [created, setCreated] = React.useState(null); + // The listed hooks with a pending draft at this package: a refused Save keeps such a draft. + const [drafted, setDrafted] = React.useState>(() => new Set()); + const [refusedHooks, setRefusedHooks] = React.useState>(() => new Map()); + const [loading, setLoading] = React.useState(true); + const [error, setError] = React.useState(null); + const [selected, setSelected] = React.useState(null); + const [draft, setDraft] = React.useState(null); + // The hook whose body the buffer holds (`selected` once its install has run). + const [draftFor, setDraftFor] = React.useState(null); + const [edited, setEdited] = React.useState(false); + const [saving, setSaving] = React.useState(false); + const [nonce, setNonce] = React.useState(0); + const reloadHooks = React.useCallback(() => setNonce((n) => n + 1), []); + const { save: saveHookDraft, recordRead: recordHookRead, forget: forgetHookVersion, dialog } = useDraftSaveGuard( + client, + reloadHooks, + ); + React.useEffect(() => { + forgetHookVersion(); + }, [publishNonce, forgetHookVersion]); + const publishNonceRef = React.useRef(publishNonce); + React.useLayoutEffect(() => { + publishNonceRef.current = publishNonce; + }); + + const hooks = React.useMemo( + () => (created && !listed.some((h) => h.name === created.name) ? [...listed, created] : listed), + [listed, created], + ); + const isCreated = created !== null && draftFor === created.name; + const dirty = edited || isCreated; + + // objectui#11820 — the objects of this package for the target picker, stamped + // with the package and object it was read for. + const [packageScope, setPackageScope] = React.useState< + (HookTargetScope & { packageId: string; objectName: string }) | null + >(null); + React.useEffect(() => { + if (!live) return; + let cancelled = false; + loadPackageSurfaces(client, 'object', packageId) + .then((items) => { + if (cancelled) return; + const names = new Set(items.map((i) => i.name)); + names.add(objectName); + setPackageScope({ packageId, objectName, packageObjects: names }); + }) + .catch(() => { + if (!cancelled) setPackageScope(null); + }); + return () => { + cancelled = true; + }; + }, [client, packageId, objectName, live]); + const hookTargetScope = + packageScope && packageScope.packageId === packageId && packageScope.objectName === objectName + ? packageScope + : null; + + // objectui#4527 — the open hook's blocking expression errors, stamped with + // the hook they describe, so a late report never holds another hook. + const [celErrors, setCelErrors] = React.useState<{ hook: string; count: number }>({ hook: '', count: 0 }); + const selectedHookName = String(draft?.name ?? ''); + const reportCel = React.useCallback( + (count: number) => { + setCelErrors((prev) => + prev.hook === selectedHookName && prev.count === count ? prev : { hook: selectedHookName, count }, + ); + }, + [selectedHookName], + ); + const blockingIssues = celErrors.hook === selectedHookName ? celErrors.count : 0; + + // Read by the list load and the install below: the hook the buffer holds and + // whether it holds an unsent edit. + const bufferRef = React.useRef({ hook: draftFor, dirty, body: draft }); + React.useLayoutEffect(() => { + bufferRef.current = { hook: draftFor, dirty, body: draft }; + }); + + // Another object: nothing of the last one's hooks is kept. + React.useEffect(() => { + setListed([]); + setCreated(null); + setSelected(null); + setDrafted(new Set()); + setRefusedHooks(new Map()); + setError(null); + setLoading(true); + }, [key]); + + React.useEffect(() => { + if (!live) return; + let cancelled = false; + const publishAtStart = publishNonceRef.current; + setLoading(true); + setError(null); + (async () => { + try { + // `list()` serves published hooks only; a pending draft is read too, + // each at the address its save writes, and wins over its published row. + const [pub, draftHeaders] = await Promise.all([ + client.list('hook', { packageId }) as Promise, + client.listDrafts({ packageId, type: 'hook' }).catch(() => null), + ]); + const draftNames = (draftHeaders || []).map((d) => String(d.name ?? '')).filter(Boolean); + const reads = await Promise.all(draftNames.map((n) => readDraftForSave(client, 'hook', n, packageId))); + if (cancelled) return; + const byName = new Map(); + // What the next save of each listed hook is pinned to: no pin where the + // drafts ledger could not be read, since it says nothing. + const pins = new Map(); + const refused = new Map(); + const pending = new Set(); + for (const h of pub || []) { + if (h?.name && targetsObject(h, objectName)) { + byName.set(String(h.name), h); + pins.set(String(h.name), draftHeaders ? { ifNoneMatch: '*' } : null); + } + } + draftNames.forEach((n, i) => { + const read = reads[i]!; + // objectstack#29148 — a refused draft is not this hook's absence. + if ('refused' in read) { + if (byName.has(n)) { + refused.set(n, read.refused); + pins.set(n, null); + } + return; + } + const body = draftBody(read.answer); + if (body && targetsObject(body, objectName)) byName.set(n, body); + if (byName.has(n)) { + pins.set(n, read.pin); + if (read.answer !== null) pending.add(n); + } + }); + setListed([...byName.values()]); + setRefusedHooks(refused); + setDrafted(pending); + // A hook whose buffer holds an unsent edit keeps the pin that edit was built on. + const open = bufferRef.current; + for (const [n, pin] of pins) { + if (publishNonceRef.current !== publishAtStart) break; + if (!(open.dirty && open.hook === n)) recordHookRead('hook', n, packageId, pin); + } + } catch (e) { + if (!cancelled) setError(formatMetadataError(e)); + } finally { + if (!cancelled) setLoading(false); + } + })(); + return () => { + cancelled = true; + }; + }, [client, packageId, objectName, nonce, recordHookRead, live]); + + // Load the selected hook into the buffer: on a selection change and when the + // list changes, except over an unsent edit of that same hook. + React.useEffect(() => { + if (selected !== null && bufferRef.current.hook === selected && bufferRef.current.dirty) return; + // objectstack#29148 — no buffer over a draft the server refused to read. + const hook = selected !== null && refusedHooks.has(selected) ? null : (hooks.find((h) => h.name === selected) ?? null); + setDraft(hook ? { ...hook } : null); + setDraftFor(hook ? selected : null); + setEdited(false); + }, [selected, hooks, refusedHooks]); + + const select = React.useCallback( + (name: string | null) => { + if (name === bufferRef.current.hook) { + setSelected(name); + return; + } + if (!confirmDropUnsavedWork(bufferRef.current.dirty, locale)) return; + setCreated(null); + setEdited(false); + setSelected(name); + }, + [locale], + ); + + const patch = React.useCallback((change: Partial) => { + setDraft((d) => (d ? { ...d, ...change } : d)); + setEdited(true); + }, []); + const replace = React.useCallback((next: HookItem) => { + setDraft(next); + setEdited(true); + }, []); + + const addHook = React.useCallback(() => { + if (!confirmDropUnsavedWork(bufferRef.current.dirty, locale)) return; + const name = nextHookName(objectName, listed.map((h) => String(h.name ?? ''))); + // A complete, valid skeleton: a hook needs an object, an event and a body. + const fresh: HookItem = { + name, + label: t('engine.studio.hooks.newLabel', locale), + object: objectName, + events: ['beforeInsert'], + body: { language: 'js', source: 'return;' }, + priority: 100, + async: false, + }; + setError(null); + setEdited(false); + setCreated(fresh); + setSelected(name); + }, [objectName, listed, locale]); + + const renamedFrom = + draft !== null && draftFor !== null && String(draft.name ?? '') !== draftFor ? draftFor : null; + + // The top bar's Save for the open hook: its draft, then that hook's publish. + const save = React.useCallback(async (): Promise => { + const name = draftFor; + const body = draft; + if (name === null || !body) return { kind: 'declined' }; + const isNew = created !== null && created.name === name; + const hadDraft = drafted.has(name); + setSaving(true); + setError(null); + try { + if (isNew) { + // objectui#11773 — a create is the first-write pin: refused where the + // name already holds a draft, instead of written over it. + await client.save('hook', name, body, { mode: 'draft', packageId, ifNoneMatch: '*', surface: 'studio' }); + } else if ( + (await saveHookDraft('hook', name, body, { mode: 'draft', packageId, surface: 'studio' })) === 'reloaded' + ) { + // The author chose the saved version: the list re-read installs it. + setEdited(false); + return { kind: 'declined' }; + } + const outcome = await publishSavedItem(client, { type: 'hook', name, packageId }, hadDraft); + if (!outcome.ok) { + if (outcome.draftDiscarded) { + recordHookRead('hook', name, packageId, { ifNoneMatch: '*' }); + } else { + // The draft stays pending (a copilot's, or one its discard could not take back). + setDrafted((prev) => new Set(prev).add(name)); + if (isNew) { + setCreated(null); + setListed((list) => [...list.filter((h) => h.name !== name), body]); + } + } + const reason = formatMetadataError(outcome.error); + setError(reason); + return { kind: 'refused', reason }; + } + // Live: no draft is left, so the next save asserts none. + recordHookRead('hook', name, packageId, { ifNoneMatch: '*' }); + setDrafted((prev) => { + if (!prev.has(name)) return prev; + const next = new Set(prev); + next.delete(name); + return next; + }); + // The list now holds what was saved; a hook no longer aimed at this object leaves it. + setListed((list) => { + const kept = list.filter((h) => h.name !== name); + if (!targetsObject(body, objectName)) return kept; + const at = list.findIndex((h) => h.name === name); + return at < 0 ? [...kept, body] : list.map((h, i) => (i === at ? body : h)); + }); + if (isNew) setCreated(null); + if (JSON.stringify(bufferRef.current.body) === JSON.stringify(body)) setEdited(false); + return { kind: 'saved' }; + } catch (e) { + const reason = formatMetadataError(e); + setError(reason); + return { kind: 'refused', reason }; + } finally { + setSaving(false); + } + }, [client, draft, draftFor, created, drafted, packageId, objectName, saveHookDraft, recordHookRead]); + + const cancel = React.useCallback(() => { + setError(null); + setEdited(false); + if (isCreated) { + setCreated(null); + setSelected(null); + return; + } + const hook = listed.find((h) => h.name === draftFor) ?? null; + setDraft(hook ? { ...hook } : null); + }, [isCreated, listed, draftFor]); + + const label = String(draft?.label || draft?.name || draftFor || ''); + const held = + renamedFrom !== null + ? tFormat('engine.studio.held.hookRename', locale, { name: renamedFrom }) + : blockingIssues > 0 + ? tFormat('engine.studio.held.celInvalidHook', locale, { hook: label }) + : null; + useStudioSaveEntry( + live && draftFor !== null && !disabled + ? { label, order: HOOKS_SAVE_ORDER, dirty, held, save, cancel } + : null, + ); + + return { + hooks: live ? hooks : [], + refusedHooks, + loading: !live || loading, + error, + selected, + draft, + dirty, + saving, + renamedFrom, + blockingIssues, + hookTargetScope, + select, + patch, + replace, + addHook, + reportCel, + dialog, + }; +} diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index a26cc2b8343..f42d653ff02 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -2705,10 +2705,11 @@ const STUDIO_EN: Record = { 'engine.studio.auto.unregisteredTitle': 'The automation engine on this deployment holds no registration for this flow', 'engine.studio.auto.enabled': 'Switched on', 'engine.studio.auto.disabled': 'Switched off', - 'engine.studio.auto.enableTitle': 'Enable this automation (publish to apply)', - 'engine.studio.auto.disableTitle': 'Disable this automation (publish to apply)', - 'engine.studio.auto.enabledToast': 'Switched on — publish to apply', - 'engine.studio.auto.disabledToast': 'Switched off — publish to apply', + // objectstack#36511 — the switch is live at once, as an installed app's is. + 'engine.studio.auto.enableTitle': 'Enable this automation. It takes effect at once.', + 'engine.studio.auto.disableTitle': 'Disable this automation. It takes effect at once.', + 'engine.studio.auto.enabledToast': 'Switched on, live now', + 'engine.studio.auto.disabledToast': 'Switched off, live now', 'engine.studio.auto.newTitle': 'New automation', 'engine.studio.auto.none': 'No automations yet — click “+” above to create one', 'engine.studio.auto.emptyMain': 'No automations in this package yet.', @@ -3389,6 +3390,10 @@ const STUDIO_EN: Record = { 'engine.studio.held.celInvalidRule': 'an expression on the rule “{rule}” has an error to fix', 'engine.studio.held.celInvalidAction': 'an expression on the action “{action}” has an error to fix', 'engine.studio.held.inspectorInvalid': '“{item}” has an error to fix in its inspector', + // objectstack#36511 — a hook's Save held: an expression error, or a name changed from the one it is stored under. + 'engine.studio.held.celInvalidHook': 'an expression on the hook “{hook}” has an error to fix', + 'engine.studio.held.hookRename': 'the hook {name} keeps the name it was created with', + 'engine.studio.held.pairActionRename': 'the action {name} keeps the name it was created with', 'engine.studio.held.line': 'Not saved yet: {clause}. Your changes are kept here and saved once it is filled in.', 'engine.studio.held.publish': 'Not published: {clause}, so that change is not saved yet. Finish it, then publish.', 'engine.studio.held.inputHint': 'Required. Changes are saved once this has a value.', @@ -3829,7 +3834,7 @@ const STUDIO_EN: Record = { 'engine.studio.actions.presets': 'Common actions', 'engine.studio.actions.notSaved': 'Not saved — needs “{input}”', 'engine.studio.actions.heldNeeds': 'the action “{action}” needs “{input}”', - 'engine.studio.actions.renameHeld': 'Not saved yet: an action added to an installed app keeps the name it was created with. Change the name back to {name} to save your changes.', + 'engine.studio.actions.renameHeld': 'Not ready to save: an action added to an installed app keeps the name it was created with. Change the name back to {name}, then Save.', 'engine.studio.actions.preset.change': 'Change a picklist field', 'engine.studio.actions.preset.changeHint': 'Asks for a new “{field}”, then saves it.', 'engine.studio.actions.preset.changeNeeds': 'Needs a picklist field on this object.', @@ -3850,7 +3855,7 @@ const STUDIO_EN: Record = { 'engine.studio.api.body': 'Example body', 'engine.studio.api.bodyOmitted': 'Required fields come first. Optional fields not shown: {fields}', // Hooks view - 'engine.studio.hooks.renameHeld': 'Not saved yet: a hook keeps the name it was created with. Change the name back to {name} to save your changes.', + 'engine.studio.hooks.renameHeld': 'Not ready to save: a hook keeps the name it was created with. Change the name back to {name}, then Save.', 'engine.studio.hooks.none': 'No hooks target this object.', 'engine.studio.hooks.newButton': 'New hook', 'engine.studio.hooks.async': 'async', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 8406bf09fed..2c6b6b2efb8 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -2420,10 +2420,10 @@ const STUDIO_ZH: Record = { 'engine.studio.auto.unregisteredTitle': '此部署的自动化引擎未注册该流程', 'engine.studio.auto.enabled': '已启用', 'engine.studio.auto.disabled': '已停用', - 'engine.studio.auto.enableTitle': '启用此自动化(发布后生效)', - 'engine.studio.auto.disableTitle': '停用此自动化(发布后生效)', - 'engine.studio.auto.enabledToast': '已设为启用 — 发布后生效', - 'engine.studio.auto.disabledToast': '已设为停用 — 发布后生效', + 'engine.studio.auto.enableTitle': '启用此自动化,立即生效', + 'engine.studio.auto.disableTitle': '停用此自动化,立即生效', + 'engine.studio.auto.enabledToast': '已启用,立即生效', + 'engine.studio.auto.disabledToast': '已停用,立即生效', 'engine.studio.auto.newTitle': '新建自动化', 'engine.studio.auto.none': '还没有自动化 — 点上方的「+」新建', 'engine.studio.auto.emptyMain': '这个软件包还没有自动化。', @@ -3002,6 +3002,9 @@ const STUDIO_ZH: Record = { 'engine.studio.held.celInvalidRule': '规则「{rule}」的表达式有错误需要修正', 'engine.studio.held.celInvalidAction': '动作「{action}」的表达式有错误需要修正', 'engine.studio.held.inspectorInvalid': '「{item}」在检查器中有错误需要修正', + 'engine.studio.held.celInvalidHook': '钩子「{hook}」的表达式有错误需要修正', + 'engine.studio.held.hookRename': '钩子 {name} 需保留创建时的名称', + 'engine.studio.held.pairActionRename': '操作 {name} 需保留创建时的名称', 'engine.studio.held.line': '尚未保存:{clause}。更改已保留在此处,补全后会自动保存。', 'engine.studio.held.publish': '未发布:{clause},该更改尚未保存。请先补全,再发布。', 'engine.studio.held.inputHint': '必填。填写后才会保存更改。', @@ -3389,7 +3392,7 @@ const STUDIO_ZH: Record = { 'engine.studio.actions.presets': '常用操作', 'engine.studio.actions.notSaved': '未保存 —— 需要「{input}」', 'engine.studio.actions.heldNeeds': '操作「{action}」需要「{input}」', - 'engine.studio.actions.renameHeld': '尚未保存:给已安装应用新增的操作会保留创建时的名称。把名称改回 {name} 即可保存更改。', + 'engine.studio.actions.renameHeld': '还不能保存:给已安装应用新增的操作会保留创建时的名称。把名称改回 {name},再点保存。', 'engine.studio.actions.preset.change': '修改下拉选择字段', 'engine.studio.actions.preset.changeHint': '询问新的「{field}」,然后保存。', 'engine.studio.actions.preset.changeNeeds': '需要该对象有一个下拉选择字段。', @@ -3410,7 +3413,7 @@ const STUDIO_ZH: Record = { 'engine.studio.api.body': '示例请求体', 'engine.studio.api.bodyOmitted': '必填字段排在最前。未列出的可选字段:{fields}', // Hooks view - 'engine.studio.hooks.renameHeld': '尚未保存:钩子会保留创建时的名称。把名称改回 {name} 即可保存更改。', + 'engine.studio.hooks.renameHeld': '还不能保存:钩子会保留创建时的名称。把名称改回 {name},再点保存。', 'engine.studio.hooks.none': '没有钩子作用于该对象。', 'engine.studio.hooks.newButton': '新建钩子', 'engine.studio.hooks.async': '异步', From bb0875685654cd47b2c7a99e560f2f330d5b51fe Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 02:06:18 +0000 Subject: [PATCH 14/25] wip(studio): the hooks conflict dialog drawn by the pillar Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .../app-shell/src/views/studio-design/ObjectHooksPanel.tsx | 3 --- .../app-shell/src/views/studio-design/StudioDesignSurface.tsx | 2 ++ 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx index f3dfd93964f..de8b837fff9 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectHooksPanel.tsx @@ -71,7 +71,6 @@ export function ObjectHooksPanel({ replace, addHook, reportCel, - dialog: hookConflictDialog, } = buffer; // objectui#12514 — an object no hook targets is one centered block whose @@ -79,7 +78,6 @@ export function ObjectHooksPanel({ if (!loading && hooks.length === 0) { return (
- {hookConflictDialog} {error && (
{error} @@ -106,7 +104,6 @@ export function ObjectHooksPanel({ return (
- {hookConflictDialog} {/* hook list */}
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 10f08fd9501..082aba72bcb 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.tsx @@ -7366,6 +7366,8 @@ export function DataPillar({ return (
{objConflictDialog} + {/* objectstack#36511 — the hooks buffer's, here: a Save may ask while the Hooks tab is closed. */} + {hooksBuffer.dialog} {/* objectstack#34931 — the door's other 409: confirmed, it is sent again forced; else what it would lose is kept. */} !open && keepDestructive()}> From 0a019af0d730ef0552c3afe87da5c23a197378c4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 02:07:30 +0000 Subject: [PATCH 15/25] fix(studio): drop the unused act imports; the live journey presses Save for the extension The customize journey's extension step now asserts the new save: nothing is written before the top bar's Save, which writes the extension's draft into the pair and publishes that one item there, leaving no draft. Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- ui/e2e/live/studio-customize-journey.spec.ts | 41 +++++++++++++++---- .../DataPillar.actionRefusal-26736.test.tsx | 2 +- .../DataPillar.authorRefusal-11785.test.tsx | 2 +- ...Pillar.choiceWithoutOptions-11253.test.tsx | 2 +- .../DataPillar.heldIncomplete-11786.test.tsx | 2 +- ...illar.picklistServedOptions-10202.test.tsx | 2 +- .../DataPillar.showMeFocus-26730.test.tsx | 2 +- .../DataPillar.summaryHeld-27461.test.tsx | 2 +- 8 files changed, 41 insertions(+), 14 deletions(-) diff --git a/ui/e2e/live/studio-customize-journey.spec.ts b/ui/e2e/live/studio-customize-journey.spec.ts index fcc12a1d329..063023dac65 100644 --- a/ui/e2e/live/studio-customize-journey.spec.ts +++ b/ui/e2e/live/studio-customize-journey.spec.ts @@ -1,4 +1,4 @@ -import { test as base, expect, type APIRequestContext, type Page, type Response } from '@playwright/test'; +import { test as base, expect, type APIRequestContext, type Page, type Request, type Response } from '@playwright/test'; /** * Live e2e for the ADR-0146 customization journey, walked through the Studio @@ -12,9 +12,10 @@ import { test as base, expect, type APIRequestContext, type Page, type Response * type's list) — not what the canvas draws. * 2. Restore package original: the pair's draft and row are deleted at the * pair, and the three reads serve the shipped column set again. - * 3. Add `region__c`: Add field on the base object's Form writes an - * `object_extension` into the pair; once published, the base object is - * served with the field and the pair's own read and export carry it. + * 3. Add `region__c`: Add field on the base object's Form, then the top + * bar's Save (objectstack#36511), writes an `object_extension` into the + * pair and publishes that one item there, so the base object is served + * with the field at once and the pair's own read and export carry it. * 4. Uninstall the base: the uninstall door refuses the read-only showcase * with 422 `WRITABLE_PACKAGE_REQUIRED` and removes nothing. This is the * refusal `main` answers here, and the one asserted: `DELETE @@ -230,19 +231,45 @@ test('a read-only base is customized, restored and extended through Studio, and await page.getByTestId('add-field-label-input').fill(FIELD.label); await expect(page.getByTestId('add-field-api-name-preview')).toContainText(FIELD.name); + // objectstack#36511 — the add stays on the page until the top bar's + // Save: no write of the extension leaves before it is pressed. + const extensionWrites: string[] = []; + const onRequest = (r: Request) => { + if (r.method() !== 'GET' && r.url().includes(`/api/v1/meta/object_extension/${OBJECT}`)) { + extensionWrites.push(`${r.method()} ${r.url()}`); + } + }; + page.on('request', onRequest); + await page.getByTestId('add-field-create').click(); + await expect(page.getByTestId('studio-save')).toBeVisible(); + expect(extensionWrites).toEqual([]); + + // Save writes the extension's draft into the pair, then publishes that + // one item there: live at once, with no package publish. const drafted = page.waitForResponse( (r) => r.request().method() === 'PUT' && r.url().includes(`/api/v1/meta/object_extension/${OBJECT}?`), ); - await page.getByTestId('add-field-create').click(); + const published = page.waitForResponse( + (r) => r.request().method() === 'POST' && r.url().includes(`/api/v1/meta/object_extension/${OBJECT}/publish`), + ); + await page.getByTestId('studio-save').click(); const draft = await drafted; expect(draft.ok(), await draft.text()).toBeTruthy(); expect(new URL(draft.url()).searchParams.get('package')).toBe(PAIR); + expect(new URL(draft.url()).searchParams.get('mode')).toBe('draft'); expect(draft.request().postDataJSON()).toEqual({ extend: OBJECT, fields: { [FIELD.name]: { type: 'text', label: FIELD.label } }, }); - - await publishPair(page); + const publish = await published; + expect(publish.ok(), await publish.text()).toBeTruthy(); + expect(new URL(publish.url()).searchParams.get('package')).toBe(PAIR); + // The Save left nothing to save, and no draft for the package publish. + await expect(page.getByTestId('studio-save')).toHaveCount(0); + page.off('request', onRequest); + expect(extensionWrites.map((w) => w.split(' ')[0])).toEqual(['PUT', 'POST']); + const pending = await request.get(`${API}/api/v1/meta/object_extension/${OBJECT}?state=draft&package=${PAIR}`); + expect(pending.status(), await pending.text()).toBe(404); const object = await request.get(`${API}/api/v1/meta/object/${OBJECT}`); expect(object.ok(), await object.text()).toBeTruthy(); const objectBody = await object.json(); diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx index 770e0983c5d..4e291a6b3ff 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.actionRefusal-26736.test.tsx @@ -27,7 +27,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { render, screen, fireEvent, cleanup, act, waitFor, within } from '@testing-library/react'; +import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; import { ActionSchema } from '@objectstack/spec/ui'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx index 42a8d2aec7f..ccc172a6c43 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.authorRefusal-11785.test.tsx @@ -27,7 +27,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { render, screen, fireEvent, cleanup, act, within } from '@testing-library/react'; +import { render, screen, fireEvent, cleanup, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx index c7cfef20a72..0afeb6449c8 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.choiceWithoutOptions-11253.test.tsx @@ -29,7 +29,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { render, screen, fireEvent, cleanup, waitFor, act } from '@testing-library/react'; +import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx index 947df0a5b66..60c988a3407 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.heldIncomplete-11786.test.tsx @@ -24,7 +24,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { render, screen, fireEvent, cleanup, act, waitFor, within } from '@testing-library/react'; +import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx index 8e31b093edd..24fdba5b025 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.picklistServedOptions-10202.test.tsx @@ -23,7 +23,7 @@ import { afterEach, describe, expect, it, vi } 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 { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx index 7ad6fdc5e5e..eda46e9aada 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.showMeFocus-26730.test.tsx @@ -17,7 +17,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { render, screen, fireEvent, cleanup, act, waitFor, within } from '@testing-library/react'; +import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; diff --git a/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx b/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx index f2dfe3f9aeb..5cbf0647a3c 100644 --- a/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/DataPillar.summaryHeld-27461.test.tsx @@ -20,7 +20,7 @@ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { render, screen, fireEvent, cleanup, act, waitFor, within } from '@testing-library/react'; +import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { MetadataClient } from '@object-ui/data-objectstack'; From e31fc762790b522bb29d10662a900544b5ea8f6a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 02:23:13 +0000 Subject: [PATCH 16/25] wip(studio): an installed app's pair actions are buffered by the Data pillar and saved by the top bar Claude-Session: https://claude.ai/code/session_01ADHkmPsv99YG2tCHoSe8Nb Co-authored-by: Claude --- .../studio-design/ObjectActionsPanel.tsx | 42 +- .../studio-design/StudioDesignSurface.tsx | 34 +- .../views/studio-design/pairObjectActions.ts | 388 +++++++++++------- 3 files changed, 283 insertions(+), 181 deletions(-) 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}